answer
stringlengths 17
10.2M
|
|---|
package edu.hm.hafner.analysis.parser;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import edu.hm.hafner.analysis.Issue;
import edu.hm.hafner.analysis.IssueBuilder;
import edu.hm.hafner.analysis.LookaheadParser;
import edu.hm.hafner.analysis.Severity;
import edu.hm.hafner.util.LookaheadStream;
import edu.hm.hafner.util.StringContainsUtils;
/**
* A parser for gcc 4.x compiler warnings.
*
* @author Frederic Chateau
*/
public class Gcc4CompilerParser extends LookaheadParser {
private static final long serialVersionUID = 5490211629355204910L;
private static final String GCC_WARNING_PATTERN =
ANT_TASK + "(.+?):(\\d+):(?:(\\d+):)? ?([wW]arning|.*[Ee]rror): (.*)$";
private static final Pattern CLASS_PATTERN = Pattern.compile("\\[-W(.+)]$");
/**
* Creates a new instance of {@link Gcc4CompilerParser}.
*/
public Gcc4CompilerParser() {
super(GCC_WARNING_PATTERN);
}
/**
* Creates a new instance of {@link Gcc4CompilerParser} with specified pattern.
* @param pattern a regex pattern to be used instead of the default one
*/
public Gcc4CompilerParser(final String pattern) {
super(pattern == null || pattern.isEmpty() ? GCC_WARNING_PATTERN : ANT_TASK + pattern);
}
@Override
protected boolean isLineInteresting(final String line) {
return line.contains("arning") || line.contains("rror");
}
@Override
protected Optional<Issue> createIssue(final Matcher matcher, final LookaheadStream lookahead,
final IssueBuilder builder) {
StringBuilder message = new StringBuilder(matcher.group(5));
Matcher classMatcher = CLASS_PATTERN.matcher(message.toString());
if (classMatcher.find() && classMatcher.group(1) != null) {
builder.setCategory(classMatcher.group(1));
}
while (lookahead.hasNext() && isMessageContinuation(lookahead)) {
message.append('\n');
message.append(lookahead.next());
}
return builder.setFileName(matcher.group(1))
.setLineStart(matcher.group(2))
.setColumnStart(matcher.group(3))
.setMessage(message.toString())
.setSeverity(Severity.guessFromString(matcher.group(4)))
.buildOptional();
}
@SuppressWarnings("PMD.AvoidLiteralsInIfCondition")
private boolean isMessageContinuation(final LookaheadStream lookahead) {
String peek = lookahead.peekNext();
if (peek.length() < 3) {
return false;
}
if (peek.charAt(0) == '/' || peek.charAt(0) == '[' || peek.charAt(0) == '<' || peek.charAt(0) == '=') {
return false;
}
if (peek.charAt(1) == ':') {
return false;
}
if (peek.charAt(2) == '/' || peek.charAt(0) == '\\') {
return false;
}
return !StringContainsUtils.containsAnyIgnoreCase(peek, "arning", "rror", "make");
}
}
|
package parking.business;
/* Import */
import parking.business.facture.Facture;
import parking.business.vehicule.Vehicule;
import parking.exception.business.*;
import parking.gui.Vue;
import parking.gui.gerer.VueParking;
import parking.gui.gerer.VueTimer;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Class Parking permettant de creer le parking qui comprend comme
* criteres le nombre de places maximum, le nom du parking, etc..
*
* @author Chergui, Coadalen, Corfa, Corral
*/
public class Parking implements Serializable {
/* Debut Donnees Membres */
/**
* Le numero de la prochaine place qui sera creee.
*/
private int numeroPlace;
/**
* Le nombre de place maximum du parking.
*/
private int nbPlacesMax;
/**
* Le nombre de place occupees.
*/
private int nbPlaceOccupees;
/**
* Le nom du parking.
*/
private String nom;
/**
* La liste des vehicule du parking.
*/
private ArrayList<Place> listePlaces;
/**
* La liste de tous les clients.
*/
private ArrayList<Client> listeClients;
/**
* La liste de toutes les factures.
*/
private ArrayList<Facture> listeFacture;
/**
* La liste de toute les vues.
*/
private ArrayList<Vue> listeVueNotifiable;
/**
* Le tarif d'une place de type particulier.
*/
private double tarifParticulier;
/**
* Le tarif d'une place de type transporteur.
*/
private double tarifTransporteur;
/**
* Le numero de la facture associee a un client.
*/
private int numeroFacture;
/**
* Un booleen permettant de savoir si une fonction a ete appelee en interne ou non.
*/
private boolean appelInterne;
/**
* Le singleton represente l'unique parking de l'application.
*/
private static Parking singleton = null;
/**
* Initialisation des informations generales du parking.
* Statiquement car le parking est unique.
*/
public static Parking getInstance() {
if (singleton != null) {
return singleton;
}
singleton = new Parking();
return singleton;
} // getInstance ()
/* Constructeur */
private Parking() {
/* Initialisation des donnees membres */
nom = "Mon Parking";
numeroPlace = 0;
numeroFacture = 0;
listeVueNotifiable = new ArrayList<Vue>();
listePlaces = new ArrayList<Place>();
listeFacture = new ArrayList<Facture>();
listeClients = new ArrayList<Client>();
nbPlacesMax = 24;
tarifParticulier = 1;
tarifTransporteur = 1.5;
appelInterne = false;
/* Ajout de la vue Parking */
VueParking vueParking = new VueParking();
listeVueNotifiable.add(vueParking);
/* Ajout de la vue du timer */
VueTimer vueTimer = new VueTimer(Timer.getInstance());
Timer.getInstance().setVue(vueTimer);
/* Demarrage Timer */
Timer.getInstance().start();
} // Constructeur
/* Getter */
/**
* Methode renvoyant le nombre de place occupees.
*
* @return le nombre de places occupees.
*/
public int getNbPlaceOccupees() {
return nbPlaceOccupees;
} // getNbPlaceOccupees()
/**
* Methode renvoyant le numero de la prochaine place a creer.
*
* @return le numero de la prochaine place a creer.
*/
public int getNumeroPlace() {
return numeroPlace;
} // getNumeroPlace()
/**
* Methode renvoyant le nombre de place maximal du parking.
*
* @return Nombre de place max du parking.
*/
public int getNbPlacesMax() {
return nbPlacesMax;
} // getNbPlacesMax()
/**
* Methode renvoyant le nom du parking.
*
* @return Nom du parking.
*/
public String getNom() {
return nom;
} // getNom()
/**
* Methode renvoyant la liste des clients.
*
* @return La liste des clients.
*/
public ArrayList<Client> getListeClients() {
return listeClients;
} // getListeClients()
/**
* Methode renvoyant la liste des vues.
*
* @return La liste des vues.
*/
public ArrayList<Vue> getListeVueNotifiable() {
return listeVueNotifiable;
} // getListeVueNotifiable
/**
* Methode getTarifTransporteur() renvoie le tarif d'une place de type transporteur.
*
* @return Le tarif d'une place de type transporteur.
*/
public double getTarifTransporteur() { return tarifTransporteur; } // getTarifTransporteur()
/**
* Methode getTarifParticulier() renvoie le tarif d'une place de type particulier.
*
* @return Le tarif d'une place de type particulier.
*/
public double getTarifParticulier() { return tarifParticulier; } // getTarifParticulier()
/**
* Methode getNumeroFacture() renvoie le numero de la prochaine facture.
*
* @return Le numero de la prochaine facture.
*/
public int getNumeroFacture() { return numeroFacture; } // getNumeroFacture()
/**
* Methode getLocation() permet de connaitre la place ou se situe un vehicule a partir de son numero d'immatriculation.
*
* @param numeroImmatriculation
* numero d'immatriculation du vehicule a recherche.
* @return le numero ou le vehicule se trouve sur le parking.
*/
public int getLocation(String numeroImmatriculation) {
for (Place p : this.listePlaces) {
if (p.getVehicule() != null && p.getVehicule().getImmatriculation().equals(numeroImmatriculation)) {
return p.getNumeroPlace();
}
}
return -1;
} // getLocation()
/**
* Methode getListeClients() renvoie la liste des clients.
*
* @return La liste des clients.
*/
public ArrayList<Client> getListeClient() { return listeClients; } // getListeClients()
/**
* Methode getListePlaces() renvoie la liste des places.
*
* @return La liste des places.
*/
public ArrayList<Place> getListePlaces() { return listePlaces; } // getListePlaces()
/**
* Methode getListeFacture() renvoie la liste des factures.
*
* @return La liste des factures.
*/
public ArrayList<Facture> getListeFacture() { return listeFacture; } // getListeFacture()
/* Setter */
/**
* Methode setNumeroPlace modifie le numero de la prochaine place a ajouter au parking.
*
* @param numeroPlace
* Numero de la prochaine place a ajouter au parking.
*/
public void setNumeroPlace(int numeroPlace) {
this.numeroPlace = numeroPlace;
}// setNumeroPlace()
/**
* Methode setNbPlacesMax modifie le nombre de places maximum du parking.
*
* @param nbPlacesMax
* Nombre de places maximum du parking.
*/
public void setNbPlacesMax(int nbPlacesMax) {
this.nbPlacesMax = nbPlacesMax;
} // setNbPlacesMax()
/**
* Methode setNom qui modifie le nom du parking.
*
* @param nom
* Le nom du parking.
*/
public void setNom(String nom) {
this.nom = nom;
} // setNom()
/**
* Methode setListePlaces qui modifie la liste des places.
*
* @param listePlaces
* Liste des places.
*/
public void setListePlaces(ArrayList<Place> listePlaces) {
this.listePlaces = listePlaces;
} // setListesPlaces()
/**
* Methode setListeClients qui modifie la liste des clients.
*
* @param listeClients
* Liste des clients.
*/
public void setListeClients(ArrayList<Client> listeClients) {
this.listeClients = listeClients;
} // setListeClients()
/**
* Methode setListeFacture qui modifie la liste des factures.
*
* @param listeFacture
* Liste des factures.
*/
public void setListeFacture(ArrayList<Facture> listeFacture) {
this.listeFacture = listeFacture;
} // setListeFactures()
/**
* Methode setListeVueNotifiable qui modifie la liste des vues.
*
* @param listeVueNotifiable
* Liste des vues.
*/
public void setListeVueNotifiable(ArrayList<Vue> listeVueNotifiable) {
this.listeVueNotifiable = listeVueNotifiable;
} // setListeVueNotifiable()
/**
* Methode setTarifTransporteur() modifie le tarif d'une place de type transporteur.
*
* @param tarifTransporteur
* Le tarif pour une place de type transporteur.
*/
public void setTarifTransporteur(double tarifTransporteur) {
this.tarifTransporteur = tarifTransporteur;
} //setTarifTransporteur()
/**
* Methode setTarifParticulier() modifie le tarif d'une place de type particulier.
*
* @param tarifParticulier
* Le tarif pour une place de type particulier.
*/
public void setTarifParticulier(double tarifParticulier) {
this.tarifParticulier = tarifParticulier;
} //setTarifParticulier()
/**
* Methode setNumeroFacture() modifie le numero de la prochaine facture.
*
* @param numeroFacture
* Le numero de la prochaine facture.
*/
public void setNumeroFacture(int numeroFacture) {
this.numeroFacture = numeroFacture;
} //setNumeroFacture()
/**
* Methode setNbPlaceOccupees() modifie le nombre de places occupees.
*
* @param nbPlaceOccupees
* Le nombre de places occupees.
*/
public void setNbPlaceOccupees(int nbPlaceOccupees) {
this.nbPlaceOccupees = nbPlaceOccupees;
} //setNbPlaceOccupees()
/* Methodes */
/**
* Methode addClient() ajoute un client a la liste des clients.
*
* @param c
* Le client a ajouter.
*/
public void addClient(Client c){
listeClients.add(c);
} //addClient()
/**
* Methode addFacture() ajoute une facture a la liste des factures.
*
* @param facture
* La facture a ajouter.
*/
public void addFacture(Facture facture) {
listeFacture.add(facture);
} //addFacture()
/**
* Methode addVue() ajoute une vue a la liste des vues.
*
* @param v
* La vue a ajouter.
*/
public void addVue(Vue v) {
listeVueNotifiable.add(v);
} // addVue()
/**
* Methode notifier() met a jour toutes les vues.
*/
public void notifier() {
for (Vue v : listeVueNotifiable) {
v.mettreAJour();
}
} // notifier()
/**
* Methode toString() permettant de connaitre toutes les informations detaillees sur le parking.
*
* @return renvoie une chaine de caracteres contenant les informatiosn sur le parking.
*/
@Override
public String toString() {
return "Parking [nom=" + nom + ", listePlaces=" + listePlaces + "]";
}// toString()
/**
* Methode permettant d'ajouter une place dans le parking.
*
* @param p
* la place a ajouter.
*/
public void ajouterPlace(Place p){
try {
if(this.getNbPlacesMax() == this.getNumeroPlace())
throw new NombrePlacesMaxException();
p.setNumero(this.getNumeroPlace());
this.setNumeroPlace(this.getNumeroPlace() + 1);
this.listePlaces.add(p);
//Met a jour les vues
notifier();
}
catch (NombrePlacesMaxException e) {
System.out.println("Le parking a atteint le nombre maximal de places");
}
}// ajouterPlace()
/**
* Methode testant l'existence d'un vehicule dans le parking.
*
* @param v
* Vehicule a rechercher dans le parking.
* @return Renvoie un booleen indiquant si le vehicule est present ou non.
*/
public boolean vehiculeGare(Vehicule v){
for(Place p : this.listePlaces ){
if(p.getVehicule() == v)
return true;
}
return false;
} // vehiculeGare()
/**
* Methode unpark() permet de retirer un vehicule de sa place sur le parking.
*
* @param numeroPlace
* Numero de la place ou retirer le vehicule.
* @return renvoie le vehicule retire.
*/
public Vehicule unpark(int numeroPlace) {
for(Place p : this.listePlaces){
if (numeroPlace == p.getNumeroPlace())
try {
if (!appelInterne) {
--nbPlaceOccupees;
this.addFacture(new Facture(p));
}
return p.retirerVehicule();
}
catch (PlaceLibreException e) {
System.out.println("La place est déja vide !");
return null;
}
finally {
notifier();
}
}
return null;
} // unpark()
/**
* Methode park() permet de garer un vehicule sur une place de parking. La fonction va
* chercher la premiere place du meme type que le vehicule a garer. Sinon si c'est une
* une voiture elle la placera sur une place du type transporteur si il y en a une de disponible.
*
* @param vehicule
* Le vehicule a garer sur le parking.
*/
public void park(Vehicule vehicule) {
try {
String typePlace = "Transporteur";
if (vehicule.getType().equals("Voiture")) {
typePlace = "Particulier";
}
for (Place p : this.listePlaces) {
if (p.getVehicule() == null && !(p.getReservation())) {
if (p.getType().equals(typePlace)) {
p.setVehicule(vehicule);
if (!appelInterne) {
++nbPlaceOccupees;
p.getVehicule().setDateArrivee();
}
return;
}
}
}
//Si plus aucune place particulier n'est disponible
//recherche d'une place transporteur
for (Place p : this.listePlaces) {
if (p.getVehicule() == null && !(p.getReservation())) {
++nbPlaceOccupees;
p.setVehicule(vehicule);
p.getVehicule().setDateArrivee();
return;
}
}
throw new PlusAucunePlaceException();
}
catch(PlaceOccupeeException e){
System.out.println("La place est déja occupée et/ou n'est pas adaptée à ce véhicule");
}
catch (PlaceReserverException e) {
System.out.println("La place " + numeroPlace + " est réservée !");
}
catch (PlusAucunePlaceException e) {
System.out.println("Le parking est complet !");
}
finally {
notifier();
}
} // park()
/**
* Methode etatParking() affiche l'etat du parking.
* Pour cela elle affiche, pour chaque vehicule, la
* place qu'il occupe, le type de cette place, etc..
*/
public void etatParking() {
System.out.println("Debut de l'affichage du parking !");
for(Place p : this.listePlaces) {
System.out.println("La place numero : " + p.getNumeroPlace() + " du type : " + p.getType());
if (p.getVehicule() != null)
System.out.println("La place a pour vehicule : " + p.getVehicule() + "\n");
else
System.out.println("La place n'a pas de vehicule ! Elle " + p.getReserver() + "\n");
}
System.out.println("Fin de l'affichage du parking !\n");
} // etatParking()
/**
* Methode bookPlace() permet de reserver une place disponible sur le parking.
*
* @return La place reservee.
*/
public Place bookPlace() {
try {
for (Place p : this.listePlaces) {
if (p.getVehicule() == null) {
p.setReservation(true);
return p;
}
}
throw new PlusAucunePlaceException();
}
catch (PlusAucunePlaceException e) {
System.out.println("Aucune place disponble");
return null;
}
finally {
notifier();
}
} // bookPlace()
/**
* Methode freePlace() permet de liberer une place reserver sur le parking.
*
* @param numeroPlace
* Numero de la place a dereserver.
* @return La place de nouveau libre.
*/
public Place freePlace(int numeroPlace) {
try {
for (Place p : this.listePlaces) {
if (p.getNumeroPlace() == numeroPlace ) {
if (p.getReservation()) {
p.setReservation(false);
return p;
}
else
throw new PlaceDisponibleException();
}
}
return null;
}
catch (PlaceDisponibleException e) {
System.out.println("Place déja disponible ! (Non réservée)");
return null;
}
finally {
notifier();
}
} // freePlace()
/**
* Methode retirerVehicule() permet de retirer un vehicule d'une place a partir de son numero d'immatriculation.
*
* @param numeroImmatriculation
* Numero d'immatriculation du vehicule a retirer.
* @return Le vehicule retire de sa place de parking.
*/
public Vehicule retirerVehicule(String numeroImmatriculation) {
int numPlace = getLocation(numeroImmatriculation);
if (numPlace == -1)
return null;
else
return unpark(numPlace);
} // retirerVehicule()
/**
* Methode reorganiserPlaces() reorganise les places de parking apres le depart d'un vehicule.
* par exemple si une place du type particulier s'est liberee et qu'une voiture est sur une
* place du type camion , on va alors la deplacer sur la place libre.
*/
public void reorganiserPlaces() {
appelInterne = true;
for (Place p : this.listePlaces) {
if (p.getType().equals("Transporteur") && p.getVehicule() != null) {
if (p.getVehicule().getType().equals("Voiture")) {
Vehicule vretire = unpark(p.getNumeroPlace());
this.park(vretire);
}
}
}
notifier();
appelInterne = false;
} // reorganiserPlaces()
} // Parking class
|
package flaxbeard.cyberware.common.item;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.MobEffects;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.CombatRules;
import net.minecraft.util.DamageSource;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent;
import net.minecraftforge.event.entity.living.LivingHurtEvent;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry.TargetPoint;
import flaxbeard.cyberware.api.CyberwareAPI;
import flaxbeard.cyberware.api.ICyberwareUserData;
import flaxbeard.cyberware.common.CyberwareContent;
import flaxbeard.cyberware.common.lib.LibConstants;
import flaxbeard.cyberware.common.network.CyberwarePacketHandler;
import flaxbeard.cyberware.common.network.ParticlePacket;
public class ItemHeartUpgrade extends ItemCyberware
{
public ItemHeartUpgrade(String name, EnumSlot slot, String[] subnames)
{
super(name, slot, subnames);
MinecraftForge.EVENT_BUS.register(this);
}
@Override
public boolean isIncompatible(ItemStack stack, ItemStack other)
{
return other.getItem() == CyberwareContent.cyberheart && (stack.getItemDamage() == 0 || stack.getItemDamage() == 3);
}
@SubscribeEvent
public void handleDeath(LivingDeathEvent event)
{
EntityLivingBase e = event.getEntityLiving();
ItemStack test = new ItemStack(this, 1, 0);
if (CyberwareAPI.isCyberwareInstalled(e, test) && !event.isCanceled())
{
ICyberwareUserData cyberware = CyberwareAPI.getCapability(e);
ItemStack stack = CyberwareAPI.getCyberware(e, test);
if ((!stack.hasTagCompound() || !stack.getTagCompound().hasKey("used")) && cyberware.usePower(test, this.getPowerConsumption(test), false))
{
ItemStack[] items = cyberware.getInstalledCyberware(EnumSlot.HEART);
ItemStack[] itemsNew = items.clone();
for (int i = 0; i < items.length; i++)
{
ItemStack item = items[i];
if (item != null && item.getItem() == this && item.getItemDamage() == 0)
{
itemsNew[i] = null;
break;
}
}
if (e instanceof EntityPlayer)
{
cyberware.setInstalledCyberware(e, EnumSlot.HEART, itemsNew);
cyberware.updateCapacity();
if (!e.worldObj.isRemote)
{
CyberwareAPI.updateData(e);
}
}
else
{
if (!stack.hasTagCompound())
{
stack.setTagCompound(new NBTTagCompound());
}
stack.getTagCompound().setBoolean("used", true);
}
e.setHealth(e.getMaxHealth() / 3F);
event.setCanceled(true);
}
}
}
private static Map<EntityLivingBase, Integer> timesPlatelets = new HashMap<EntityLivingBase, Integer>();
@SubscribeEvent
public void handleLivingUpdate(LivingUpdateEvent event)
{
EntityLivingBase e = event.getEntityLiving();
ItemStack test = new ItemStack(this, 1, 2);
if (e.ticksExisted % 20 == 0 && CyberwareAPI.isCyberwareInstalled(e, test))
{
isStemWorking.put(e, CyberwareAPI.getCapability(e).usePower(test, getPowerConsumption(test)));
}
test = new ItemStack(this, 1, 1);
if (e.ticksExisted % 20 == 0 && CyberwareAPI.isCyberwareInstalled(e, test))
{
isPlateletWorking.put(e, CyberwareAPI.getCapability(e).usePower(test, getPowerConsumption(test)));
}
if (isPlateletWorking(e) && CyberwareAPI.isCyberwareInstalled(e, test))
{
if (e.getHealth() >= e.getMaxHealth() * .8F && e.getHealth() != e.getMaxHealth())
{
int t = getPlateletTime(e);
if (t >= 40)
{
timesPlatelets.put(e, e.ticksExisted);
e.heal(1);
}
}
else
{
timesPlatelets.put(e, e.ticksExisted);
}
}
else
{
if (timesPlatelets.containsKey(e))
{
timesPlatelets.remove(e);
}
}
if (CyberwareAPI.isCyberwareInstalled(e, new ItemStack(this, 1, 2)))
{
if (isStemWorking(e))
{
int t = getMedkitTime(e);
if (t >= 100 && damageMedkit.get(e) > 0F)
{
CyberwarePacketHandler.INSTANCE.sendToAllAround(new ParticlePacket(0, (float) e.posX, (float) e.posY + e.height / 2F, (float) e.posZ),
new TargetPoint(e.worldObj.provider.getDimension(), e.posX, e.posY, e.posZ, 20));
e.heal(damageMedkit.get(e));
timesMedkit.put(e, 0);
damageMedkit.put(e, 0F);
}
}
}
else
{
if (timesMedkit.containsKey(e))
{
//timesMedkit.remove(e);
//damageMedkit.remove(e);
}
}
}
private static Map<EntityLivingBase, Boolean> isPlateletWorking = new HashMap<EntityLivingBase, Boolean>();
private boolean isPlateletWorking(EntityLivingBase e)
{
if (!isPlateletWorking.containsKey(e))
{
isPlateletWorking.put(e, false);
}
return isPlateletWorking.get(e);
}
private static Map<EntityLivingBase, Boolean> isStemWorking = new HashMap<EntityLivingBase, Boolean>();
private boolean isStemWorking(EntityLivingBase e)
{
if (!isStemWorking.containsKey(e))
{
isStemWorking.put(e, false);
}
return isStemWorking.get(e);
}
private static Map<EntityLivingBase, Integer> timesMedkit = new HashMap<EntityLivingBase, Integer>();
private static Map<EntityLivingBase, Float> damageMedkit = new HashMap<EntityLivingBase, Float>();
@SubscribeEvent(priority = EventPriority.LOWEST)
public void handleHurt(LivingHurtEvent event)
{
EntityLivingBase e = event.getEntityLiving();
if (!event.isCanceled() && CyberwareAPI.isCyberwareInstalled(e, new ItemStack(this, 1, 2)))
{
float damageAmount = event.getAmount();
DamageSource damageSrc = event.getSource();
damageAmount = applyArmorCalculations(e, damageSrc, damageAmount);
damageAmount = applyPotionDamageCalculations(e, damageSrc, damageAmount);
damageAmount = Math.max(damageAmount - e.getAbsorptionAmount(), 0.0F);
damageMedkit.put(e, damageAmount);
timesMedkit.put(e, e.ticksExisted);
}
}
// Stolen from EntityLivingBase
protected float applyArmorCalculations(EntityLivingBase e, DamageSource source, float damage)
{
if (!source.isUnblockable())
{
damage = CombatRules.getDamageAfterAbsorb(damage, (float)e.getTotalArmorValue(), (float)e.getEntityAttribute(SharedMonsterAttributes.ARMOR_TOUGHNESS).getAttributeValue());
}
return damage;
}
// Stolen from EntityLivingBase
protected float applyPotionDamageCalculations(EntityLivingBase e, DamageSource source, float damage)
{
if (source.isDamageAbsolute())
{
return damage;
}
else
{
if (e.isPotionActive(MobEffects.RESISTANCE) && source != DamageSource.outOfWorld)
{
int i = (e.getActivePotionEffect(MobEffects.RESISTANCE).getAmplifier() + 1) * 5;
int j = 25 - i;
float f = damage * (float)j;
damage = f / 25.0F;
}
if (damage <= 0.0F)
{
return 0.0F;
}
else
{
int k = EnchantmentHelper.getEnchantmentModifierDamage(e.getArmorInventoryList(), source);
if (k > 0)
{
damage = CombatRules.getDamageAfterMagicAbsorb(damage, (float)k);
}
return damage;
}
}
}
private int getPlateletTime(EntityLivingBase e)
{
if (e != null)
{
if (!timesPlatelets.containsKey(e))
{
timesPlatelets.put(e, e.ticksExisted);
return 0;
}
return e.ticksExisted - timesPlatelets.get(e);
}
return 0;
}
private int getMedkitTime(EntityLivingBase e)
{
if (e != null)
{
if (!timesMedkit.containsKey(e))
{
timesMedkit.put(e, e.ticksExisted);
damageMedkit.put(e, 0F);
return 0;
}
return e.ticksExisted - timesMedkit.get(e);
}
return 0;
}
@SubscribeEvent
public void power(LivingUpdateEvent event)
{
EntityLivingBase e = event.getEntityLiving();
ItemStack test = new ItemStack(this, 1, 3);
if (e.ticksExisted % 20 == 0 && CyberwareAPI.isCyberwareInstalled(e, test))
{
CyberwareAPI.getCapability(e).addPower(getPowerProduction(test), test);
}
}
@Override
public int getPowerConsumption(ItemStack stack)
{
return stack.getItemDamage() == 0 ? LibConstants.DEFIBRILLATOR_CONSUMPTION :
stack.getItemDamage() == 1 ? LibConstants.PLATELET_CONSUMPTION :
stack.getItemDamage() == 2 ? LibConstants.STEMCELL_CONSUMPTION : 0;
}
@Override
public int getCapacity(ItemStack stack)
{
return stack.getItemDamage() == 0 ? LibConstants.DEFIBRILLATOR_CONSUMPTION: 0;
}
@Override
public boolean hasCustomPowerMessage(ItemStack stack)
{
return stack.getItemDamage() == 0 ? true : false;
}
@Override
public int getPowerProduction(ItemStack stack)
{
return stack.getItemDamage() == 3 ? LibConstants.COUPLER_PRODUCTION + 1 : 0;
}
}
|
package gr.charos.mailer.service.impl;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import gr.charos.mailer.model.CommandResult;
import gr.charos.mailer.model.Email;
import gr.charos.mailer.service.AddressReader;
import gr.charos.mailer.service.ApplicationManager;
import gr.charos.mailer.service.MailSender;
public class CommandManagerImpl extends ApplicationManager {
public CommandManagerImpl(MailSender mailSender, AddressReader addressReader) {
this.mailSender = mailSender;
this.addressReader = addressReader;
mail = new Email();
}
public CommandResult manageCommand(String command) {
CommandResult cr = CommandResult.success;
if (command != "prev") {
getPreviousCommands().push(command);
}
String[] input = command.split(" ");
try {
switch (input[0]) {
case "quit":
quit();
break;
case "help":
help();
break;
case "prev":
prev();
break;
case "load":
for (int i = 1; i < input.length; i++) {
addMails(addressReader.readAddresses(input[i]));
}
break;
case "status":
status();
if (input.length > 1 && input[1] == "detail") {
detail();
}
break;
case "mail":
switch (input[1]) {
case "sender":
setSenderEmail(input[2]);
break;
case "subject":
setSubject(input[2]);
break;
case "body":
setBody(input[2]);
break;
default:
break;
}
break;
case "send":
send();
break;
case "log":
log();
break;
default:
help();
break;
}
} catch (Exception ex) {
ex.printStackTrace();
cr = CommandResult.failure;
}
return cr;
}
public void log() {
System.out.println("Displaying Previous commands");
for (String command : getPreviousCommands()) {
System.out.println(command);
}
}
public void send(){
int size = getEmails().size();
System.out.println(size + " Total Addresses: ");
int counter = 1;
for (String email : getEmails()) {
System.out.println("Sending " + counter++ + " of " + size + " (" + email + ")");
mail.setRecipientEmail(email);
boolean sent = mailSender.sendMail(mail);
if (sent) {
System.out.println("Sent!");
} else {
System.out.println("Not Sent... Waiting for 5 seconds and trying again");
try {
Thread.sleep(5 * 1000);
sent = mailSender.sendMail(mail);
System.out.println("Not Sent... Giving up at :" + email);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void status() {
System.out.println(getEmails().size() + " email addresses");
System.out.println("From : " + mail.getSenderEmail() );
System.out.println("Subject : " + mail.getSubject());
System.out.println("Body : " + mail.getBody());
}
public void help() {
System.out.println("Type 'load [filename]' to load addresses from paths (space-separated)");
System.out.println("Type 'preload' to load pre-fetched addresses");
System.out.println("Type 'status' to get overview of loaded messages");
System.out.println("Type 'status detail' to get overview of loaded messages");
System.out.println("Type 'mail sender [sender]' to set mail subject");
System.out.println("Type 'mail subject [subject]' to set mail subject");
System.out.println("Type 'mail body [body]' to set mail subject (HTML supported)");
System.out.println("Type 'send' to send mail");
System.out.println("Type 'prev' to execute previous command");
System.out.println("Type 'log' to view command history");
System.out.println("Type 'quit' to exit, ");
System.out.println("Type 'help' for this message :) ");
}
}
|
package io.gatekeeper.node.service.backend.consul;
import com.mashape.unirest.http.HttpClientHelper;
import com.mashape.unirest.http.HttpMethod;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.request.HttpRequest;
import com.mashape.unirest.request.HttpRequestWithBody;
import io.gatekeeper.configuration.data.backend.ConsulBackendConfiguration;
import io.gatekeeper.node.service.backend.common.crypto.EncryptionProvider;
import java.util.ArrayList;
import java.util.List;
public class Client {
private String host;
private Integer port;
private String prefix;
private String token;
private EncryptionProvider encryption;
public static Client build(ConsulBackendConfiguration configuration) throws Exception {
try {
return build(
configuration.host,
configuration.port,
configuration.prefix,
configuration.token,
new EncryptionProvider(configuration.key)
);
} catch (Exception exception) {
throw new Exception("Could not create encryption provider");
}
}
public static Client build(String host, Integer port, String prefix, String token, EncryptionProvider encryption) {
return new Client(host, port, prefix, token, encryption);
}
Client(String host, Integer port, String prefix, String token, EncryptionProvider encryption) {
assert null != host;
assert null != port;
assert null != prefix;
assert null != encryption;
this.host = host;
this.port = port;
this.prefix = prefix;
this.token = token;
this.encryption = encryption;
}
public void put(String key, String value) throws Exception {
String encrypted;
try {
encrypted = encryption.encrypt(value);
} catch (Exception e) {
throw new Exception("Could not encrypt value");
}
HttpRequest request = new HttpRequestWithBody(
HttpMethod.PUT,
makeConsulUrl(key)
).body(encrypted).getHttpRequest();
authorizeHttpRequest(request);
HttpResponse<String> response;
try {
response = HttpClientHelper.request(request, String.class);
} catch (Exception exception) {
throw new ConsulException("Consul request failed", exception);
}
if (!response.getBody().equals("true")) {
throw new ConsulException(
String.format("Consul PUT %s failed", key)
);
}
}
public String get(String key) throws Exception {
HttpRequest request = new HttpRequestWithBody(
HttpMethod.GET,
makeConsulUrl(key) + "?raw"
).getHttpRequest();
authorizeHttpRequest(request);
HttpResponse<String> response;
try {
response = HttpClientHelper.request(request, String.class);
} catch (Exception exception) {
throw new ConsulException("Consul request failed", exception);
}
if (response.getStatus() == 404) {
return null;
}
String encrypted = response.getBody();
return encryption.decrypt(encrypted);
}
public List<String> list(String key) throws Exception {
HttpRequest request = new HttpRequestWithBody(
HttpMethod.GET,
makeConsulUrl(key) + "?keys&separator=/"
).getHttpRequest();
authorizeHttpRequest(request);
HttpResponse<JsonNode> response;
try {
response = HttpClientHelper.request(request, JsonNode.class);
} catch (Exception exception) {
throw new ConsulException("Consul request failed", exception);
}
if (response.getStatus() == 404) {
return null;
}
JsonNode data = response.getBody();
if (!data.isArray()) {
throw new ConsulException("Malformed response - expected an array");
}
List<String> keys = new ArrayList<>(data.getArray().length());
data.getArray().forEach((object) -> {
keys.add(object.toString());
});
return keys;
}
/**
* Adds the appropriate authorization data to the given pre-built request.
*
* @param request The request to modify
*/
private void authorizeHttpRequest(HttpRequest request) {
if (token != null) {
request.header("X-Consul-Token", token);
}
}
private String makeConsulUrl(String path) {
assert null != path;
if (prefix != null) {
return String.format("http://%s:%s/v1/kv/%s/%s", host, port, prefix, path);
} else {
return String.format("http://%s:%s/v1/kv/%s", host, port, path);
}
}
}
|
package io.mattw.youtube.commentsuite.fxml;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.SearchListResponse;
import com.google.api.services.youtube.model.SearchResult;
import io.mattw.youtube.commentsuite.FXMLSuite;
import io.mattw.youtube.commentsuite.ImageLoader;
import io.mattw.youtube.commentsuite.util.*;
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.ListChangeListener;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;
import static javafx.application.Platform.runLater;
/**
* @author mattwright324
*/
public class SearchYouTube implements Initializable {
private static final Logger logger = LogManager.getLogger();
private Location<IpApiProvider, IpApiProvider.Location> location;
private YouTube youtubeApi;
private ClipboardUtil clipboardUtil = new ClipboardUtil();
private BrowserUtil browserUtil = new BrowserUtil();
@FXML private Pane form;
@FXML private ImageView searchIcon;
@FXML private ImageView geoIcon;
@FXML private ComboBox<String> searchType;
@FXML private TextField searchText;
@FXML private Button submit;
@FXML private HBox locationBox;
@FXML private TextField searchLocation;
@FXML private Button geolocate;
@FXML private ComboBox<String> searchRadius;
@FXML private ComboBox<String> searchOrder;
@FXML private ComboBox<String> resultType;
@FXML private ListView<SearchYouTubeListItem> resultsList;
@FXML private HBox bottom;
@FXML private Button btnAddToGroup;
@FXML private Button btnClear;
@FXML private Button btnNextPage;
@FXML private Label searchInfo;
@FXML private MenuItem menuCopyId;
@FXML private MenuItem menuOpenBrowser;
@FXML private MenuItem menuAddToGroup;
@FXML private MenuItem menuDeselectAll;
@FXML private OverlayModal<SYAddToGroupModal> addToGroupModal;
private int total = 0;
private int number = 0;
private String emptyToken = "emptyToken";
private String pageToken = emptyToken;
private YouTube.Search.List searchList;
private SimpleBooleanProperty searching = new SimpleBooleanProperty(false);
private String[] types = {"all", "video", "playlist", "channel"};
private String previousType;
@Override
public void initialize(URL location, ResourceBundle resources) {
logger.debug("Initialize SearchYouTube");
youtubeApi = FXMLSuite.getYouTube();
this.location = FXMLSuite.getLocation();
MultipleSelectionModel selectionModel = resultsList.getSelectionModel();
searchIcon.setImage(ImageLoader.SEARCH.getImage());
geoIcon.setImage(ImageLoader.LOCATION.getImage());
BooleanBinding isLocation = searchType.valueProperty().isEqualTo("Location");
locationBox.managedProperty().bind(isLocation);
locationBox.visibleProperty().bind(isLocation);
searchRadius.managedProperty().bind(isLocation);
searchRadius.visibleProperty().bind(isLocation);
isLocation.addListener((o, ov, nv) -> {
runLater(() -> {
if (nv) {
previousType = resultType.getValue();
resultType.setValue("Video");
resultType.setDisable(true);
} else {
resultType.setValue(previousType);
resultType.setDisable(false);
}
});
});
resultsList.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
menuCopyId.setOnAction(ae -> {
List<SearchYouTubeListItem> list = selectionModel.getSelectedItems();
List<String> ids = list.stream().map(SearchYouTubeListItem::getObjectId).collect(Collectors.toList());
clipboardUtil.setClipboard(ids);
});
menuOpenBrowser.setOnAction(ae -> {
List<SearchYouTubeListItem> list = selectionModel.getSelectedItems();
for (SearchYouTubeListItem view : list) {
browserUtil.open(view.getYoutubeURL());
}
});
menuAddToGroup.setOnAction(ae -> btnAddToGroup.fire());
menuDeselectAll.setOnAction(ae -> selectionModel.clearSelection());
btnAddToGroup.disableProperty().bind(selectionModel.selectedIndexProperty().isEqualTo(-1));
selectionModel.getSelectedItems().addListener((ListChangeListener) (c -> {
int items = selectionModel.getSelectedItems().size();
runLater(() -> btnAddToGroup.setText(String.format("Add to Group (%s)", items)));
}));
resultsList.itemsProperty().addListener((o, ov, nv) -> runLater(() -> {
int selectedCount = selectionModel.getSelectedItems().size();
btnAddToGroup.setText(String.format("Add to Group (%s)", selectedCount));
}));
btnClear.setOnAction(ae -> runLater(() -> resultsList.getItems().clear()));
geolocate.setOnAction(ae -> new Thread(() -> {
geolocate.setDisable(true);
try {
IpApiProvider.Location myLocation = this.location.getMyLocation();
String coordinates = myLocation.lat + "," + myLocation.lon;
runLater(() -> searchLocation.setText(coordinates));
} catch (IOException e) {
logger.error(e);
}
geolocate.setDisable(false);
}).start());
bottom.disableProperty().bind(searching);
form.disableProperty().bind(searching);
form.setOnKeyPressed(ke -> {
if (ke.getCode() == KeyCode.ENTER) {
runLater(() ->
submit.fire()
);
}
});
submit.setOnAction(ae -> {
total = 0;
number = 0;
pageToken = emptyToken;
resultsList.getItems().clear();
runLater(() -> searchInfo.setText(String.format("Showing %s out of %s", resultsList.getItems().size(), total)));
logger.debug("Submit New Search [pageToken={},type={},text={},locText={},locRadius={},order={},result={}]",
pageToken, searchType.getValue(), searchText.getText(), searchLocation.getText(),
searchRadius.getValue(), searchOrder.getValue(), resultType.getValue());
new Thread(() ->
search(pageToken, searchType.getValue(), searchText.getText(), searchLocation.getText(),
searchRadius.getValue(), searchOrder.getValue(),
resultType.getSelectionModel().getSelectedIndex())
).start();
});
btnNextPage.setOnAction(ae ->
new Thread(() ->
search(pageToken, searchType.getValue(), searchText.getText(), searchLocation.getText(),
searchRadius.getValue(), searchOrder.getValue(),
resultType.getSelectionModel().getSelectedIndex())
).start()
);
SYAddToGroupModal syAddToGroupModal = new SYAddToGroupModal(resultsList);
addToGroupModal.setContent(syAddToGroupModal);
syAddToGroupModal.getBtnClose().setOnAction(ae -> {
addToGroupModal.setVisible(false);
addToGroupModal.setManaged(false);
});
addToGroupModal.visibleProperty().addListener((cl) -> {
syAddToGroupModal.getBtnClose().setCancelButton(addToGroupModal.isVisible());
syAddToGroupModal.getBtnSubmit().setDefaultButton(addToGroupModal.isVisible());
});
btnAddToGroup.setOnAction(ae -> {
syAddToGroupModal.cleanUp();
addToGroupModal.setVisible(true);
addToGroupModal.setManaged(true);
});
}
public void search(String pageToken, String type, String text, String locText, String locRadius, String order, int resultType) {
runLater(() -> searching.setValue(true));
try {
String encodedText = URLEncoder.encode(text, "UTF-8");
String searchType = types[resultType];
if (pageToken.equals(emptyToken)) {
pageToken = "";
}
if (order.equals("Video Count")) {
order = "videoCount";
} else if (order.equals("View Count")) {
order = "viewCount";
}
searchList = youtubeApi.search().list("snippet")
.setKey(FXMLSuite.getYouTubeApiKey())
.setMaxResults(50L)
.setPageToken(pageToken)
.setQ(encodedText)
.setType(searchType)
.setOrder(order.toLowerCase());
SearchListResponse sl;
if (type.equals("Normal")) {
logger.debug("Normal Search [key={},part=snippet,text={},type={},order={},token={}]",
FXMLSuite.getYouTubeApiKey(), encodedText, searchType, order.toLowerCase(), pageToken);
sl = searchList.execute();
} else {
logger.debug("Location Search [key={},part=snippet,text={},loc={},radius={},type={},order={},token={}]",
FXMLSuite.getYouTubeApiKey(), encodedText, locText, locRadius, searchType, order.toLowerCase(), pageToken);
sl = searchList
.setType("video")
.setLocation(locText)
.setLocationRadius(locRadius)
.execute();
}
this.pageToken = sl.getNextPageToken() == null ? emptyToken : sl.getNextPageToken();
this.total = sl.getPageInfo().getTotalResults();
logger.debug("Search [videos={}]", sl.getItems().size());
for (SearchResult item : sl.getItems()) {
logger.debug("Video [id={},author={},title={}]",
item.getId(),
item.getSnippet().getChannelTitle(),
item.getSnippet().getTitle());
SearchYouTubeListItem view = new SearchYouTubeListItem(item, number++);
runLater(() -> {
resultsList.getItems().add(view);
searchInfo.setText(String.format("Showing %s out of %s", resultsList.getItems().size(), total));
});
}
} catch (IOException e) {
logger.error(e);
e.printStackTrace();
}
runLater(() -> {
if (this.pageToken != null && !this.pageToken.equals(emptyToken)) {
btnNextPage.setDisable(false);
}
searching.setValue(false);
});
}
}
|
package mcjty.rftools.blocks.screens;
import net.minecraftforge.common.config.Configuration;
public class ScreenConfiguration {
public static final String CATEGORY_SCREEN = "screen";
public static int CONTROLLER_MAXENERGY = 60000;
public static int CONTROLLER_RECEIVEPERTICK = 1000;
public static int BUTTON_RFPERTICK = 0;
public static int DUMP_RFPERTICK = 0;
public static int ELEVATOR_BUTTON_RFPERTICK = 0;
public static int CLOCK_RFPERTICK = 1;
public static int COMPUTER_RFPERTICK = 4;
public static int COUNTERPLUS_RFPERTICK = 30;
public static int COUNTER_RFPERTICK = 4;
public static int DIMENSION_RFPERTICK = 6;
public static int ENERGY_RFPERTICK = 4;
public static int ENERGYPLUS_RFPERTICK = 30;
public static int FLUID_RFPERTICK = 4;
public static int FLUIDPLUS_RFPERTICK = 30;
public static int ITEMSTACKPLUS_RFPERTICK = 30;
public static int ITEMSTACK_RFPERTICK = 4;
public static int MACHINEINFO_RFPERTICK = 4;
public static int REDSTONE_RFPERTICK = 4;
public static int TEXT_RFPERTICK = 0;
public static int STORAGE_CONTROL_RFPERTICK = 6;
public static boolean useTruetype = true;
public static String font = "rftools:fonts/ubuntu.ttf";
public static float fontSize = 40;
public static String additionalCharacters = "";
public static void init(Configuration cfg) {
CONTROLLER_MAXENERGY = cfg.get(CATEGORY_SCREEN, "screenControllerMaxRF", CONTROLLER_MAXENERGY,
"Maximum RF storage that the screen controller can hold").getInt();
CONTROLLER_RECEIVEPERTICK = cfg.get(CATEGORY_SCREEN, "screenControllerRFPerTick", CONTROLLER_RECEIVEPERTICK,
"RF per tick that the the screen controller can receive").getInt();
BUTTON_RFPERTICK = cfg.get(CATEGORY_SCREEN, "buttonRFPerTick", BUTTON_RFPERTICK,
"RF per tick/per block for the button module").getInt();
DUMP_RFPERTICK = cfg.get(CATEGORY_SCREEN, "dumpRFPerTick", DUMP_RFPERTICK,
"RF per tick/per block for the dump module").getInt();
ELEVATOR_BUTTON_RFPERTICK = cfg.get(CATEGORY_SCREEN, "elevatorButtonRFPerTick", ELEVATOR_BUTTON_RFPERTICK,
"RF per tick/per block for the elevator button module").getInt();
CLOCK_RFPERTICK = cfg.get(CATEGORY_SCREEN, "clockRFPerTick", CLOCK_RFPERTICK,
"RF per tick/per block for the clock module").getInt();
COMPUTER_RFPERTICK = cfg.get(CATEGORY_SCREEN, "computerRFPerTick", COMPUTER_RFPERTICK,
"RF per tick/per block for the computer module").getInt();
COUNTERPLUS_RFPERTICK = cfg.get(CATEGORY_SCREEN, "counterPlusRFPerTick", COUNTERPLUS_RFPERTICK,
"RF per tick/per block for the counter plus module").getInt();
COUNTER_RFPERTICK = cfg.get(CATEGORY_SCREEN, "counterRFPerTick", COUNTER_RFPERTICK,
"RF per tick/per block for the counter module").getInt();
DIMENSION_RFPERTICK = cfg.get(CATEGORY_SCREEN, "dimensionRFPerTick", DIMENSION_RFPERTICK,
"RF per tick/per block for the dimension module").getInt();
ENERGY_RFPERTICK = cfg.get(CATEGORY_SCREEN, "energyRFPerTick", ENERGY_RFPERTICK,
"RF per tick/per block for the energy module").getInt();
ENERGYPLUS_RFPERTICK = cfg.get(CATEGORY_SCREEN, "energyPlusRFPerTick", ENERGYPLUS_RFPERTICK,
"RF per tick/per block for the energy plus module").getInt();
FLUID_RFPERTICK = cfg.get(CATEGORY_SCREEN, "fluidRFPerTick", FLUID_RFPERTICK,
"RF per tick/per block for the fluid module").getInt();
FLUIDPLUS_RFPERTICK = cfg.get(CATEGORY_SCREEN, "fluidPlusRFPerTick", FLUIDPLUS_RFPERTICK,
"RF per tick/per block for the fluid plus module").getInt();
ITEMSTACKPLUS_RFPERTICK = cfg.get(CATEGORY_SCREEN, "itemstackPlusRFPerTick", ITEMSTACKPLUS_RFPERTICK,
"RF per tick/per block for the itemstack plus module").getInt();
ITEMSTACK_RFPERTICK = cfg.get(CATEGORY_SCREEN, "itemstackRFPerTick", ITEMSTACK_RFPERTICK,
"RF per tick/per block for the itemstack module").getInt();
MACHINEINFO_RFPERTICK = cfg.get(CATEGORY_SCREEN, "machineInfoRFPerTick", MACHINEINFO_RFPERTICK,
"RF per tick/per block for the machine information module").getInt();
REDSTONE_RFPERTICK = cfg.get(CATEGORY_SCREEN, "redstoneRFPerTick", REDSTONE_RFPERTICK,
"RF per tick/per block for the redstone module").getInt();
TEXT_RFPERTICK = cfg.get(CATEGORY_SCREEN, "textRFPerTick", TEXT_RFPERTICK,
"RF per tick/per block for the text module").getInt();
useTruetype = cfg.get(CATEGORY_SCREEN, "useTruetype", useTruetype,
"Set to true for TrueType font, set to false for vanilla font").getBoolean();
font = cfg.get(CATEGORY_SCREEN, "fontName", font,
"The default truetype font to use").getString();
fontSize = (float) cfg.get(CATEGORY_SCREEN, "fontSize", fontSize,
"The size of the font").getDouble();
additionalCharacters = cfg.get(CATEGORY_SCREEN, "additionalCharacters", additionalCharacters,
"Additional characters that should be supported by the truetype system").getString();
}
}
|
package net.avatar.realms.spigot.commandsign;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionAttachment;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import net.avatar.realms.spigot.commandsign.data.IBlockSaver;
import net.avatar.realms.spigot.commandsign.data.JsonBlockSaver;
import net.avatar.realms.spigot.commandsign.model.CommandBlock;
import net.avatar.realms.spigot.commandsign.model.EditingConfiguration;
import net.avatar.realms.spigot.commandsign.tasks.ExecuteTask;
import net.avatar.realms.spigot.commandsign.tasks.SaverTask;
import net.milkbowl.vault.economy.Economy;
public class CommandSign extends JavaPlugin{
private static CommandSign plugin;
private Map<Player, PermissionAttachment> playerPerms;
private Map<Location, CommandBlock> commandBlocks;
private Map<Player, EditingConfiguration> creatingConfigurations;
private Map<Player, EditingConfiguration> editingConfigurations;
private Map<Player, CommandBlock> copyingConfigurations;
private Map<Player, Location> deletingBlocks;
private Map<UUID, ExecuteTask> executingTasks;
public List<Player> infoPlayers;
private IBlockSaver blockSaver;
private SaverTask saver;
private Economy economy;
@Override
public void onEnable() {
plugin = this;
initializeDataStructures();
this.getCommand("commandsign").setExecutor(new CommandSignCommands(this));
this.getServer().getPluginManager().registerEvents(new CommandSignListener(this), this);
initializeEconomy();
try {
initializeSaver();
getLogger().info("CommandSigns properly enabled !");
}
catch (Exception e) {
getLogger().severe("Was not able to create the save file for command sign plugin");
e.printStackTrace();
}
}
private void initializeEconomy() {
if (this.getServer().getPluginManager().getPlugin("Vault") != null) {
RegisteredServiceProvider<Economy> rsp = getServer().getServicesManager().getRegistration(Economy.class);
if (rsp != null) {
this.economy = rsp.getProvider();
if (this.economy != null) {
getLogger().info("Vault economy detected for command signs ! ");
}
}
}
}
@Override
public void onDisable() {
plugin = null;
if (this.blockSaver != null) {
saveData();
}
}
private void initializeDataStructures() {
this.playerPerms = new HashMap<Player, PermissionAttachment>();
this.commandBlocks = new HashMap<Location , CommandBlock>();
this.creatingConfigurations = new HashMap<Player, EditingConfiguration>();
this.editingConfigurations = new HashMap<Player, EditingConfiguration>();
this.copyingConfigurations = new HashMap<Player, CommandBlock>();
this.deletingBlocks = new HashMap<Player, Location>();
this.executingTasks = new HashMap<UUID, ExecuteTask>();
this.infoPlayers = new LinkedList<Player>();
}
private void initializeSaver() throws Exception {
this.blockSaver = new JsonBlockSaver(this.getDataFolder());
loadData();
this.saver = new SaverTask(this);
long delay = 20 * 60 * 10; //Server ticks
long period = 20 * 60 * 5; // Server ticks
Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, this.saver, delay, period);
}
public static CommandSign getPlugin() {
return plugin;
}
public PermissionAttachment getPlayerPermissions(Player player) {
if (this.playerPerms.containsKey(player)) {
return this.playerPerms.get(player);
}
PermissionAttachment perms = player.addAttachment(this);
this.playerPerms.put(player, perms);
return perms;
}
public Map<Location, CommandBlock> getCommandBlocks() {
return this.commandBlocks;
}
public Map<Player, EditingConfiguration> getCreatingConfigurations() {
return this.creatingConfigurations;
}
public Map<Player, EditingConfiguration> getEditingConfigurations() {
return this.editingConfigurations;
}
public Map<Player, CommandBlock> getCopyingConfigurations() {
return this.copyingConfigurations;
}
public Map<UUID, ExecuteTask> getExecutingTasks() {
return this.executingTasks;
}
public Map<Player, Location> getDeletingBlocks() {
return this.deletingBlocks;
}
public List<Player> getInfoPlayers() {
return this.infoPlayers;
}
private void loadData() {
Collection<CommandBlock> data = this.blockSaver.load();
if (data == null) {
return;
}
for (CommandBlock block : data) {
this.commandBlocks.put(block.getLocation(), block);
}
}
public void saveData() {
this.blockSaver.save(this.commandBlocks.values());
}
}
|
package net.floodlightcontroller.connmonitor;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Array;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.openflow.protocol.OFFlowMod;
import org.openflow.protocol.OFFlowRemoved;
import org.openflow.protocol.OFMatch;
import org.openflow.protocol.OFMessage;
import org.openflow.protocol.OFPacketIn;
import org.openflow.protocol.OFPacketOut;
import org.openflow.protocol.OFPort;
import org.openflow.protocol.OFSetConfig;
import org.openflow.protocol.OFStatisticsRequest;
import org.openflow.protocol.OFSwitchConfig.OFConfigFlags;
import org.openflow.protocol.OFType;
import org.openflow.protocol.Wildcards;
import org.openflow.protocol.action.OFAction;
import org.openflow.protocol.action.OFActionDataLayerDestination;
import org.openflow.protocol.action.OFActionNetworkLayerDestination;
import org.openflow.protocol.action.OFActionNetworkLayerSource;
import org.openflow.protocol.action.OFActionOutput;
import org.openflow.protocol.action.OFActionTransportLayerDestination;
import org.openflow.protocol.action.OFActionTransportLayerSource;
import org.openflow.protocol.statistics.OFFlowStatisticsReply;
import org.openflow.protocol.statistics.OFFlowStatisticsRequest;
import org.openflow.protocol.statistics.OFStatistics;
import org.openflow.protocol.statistics.OFStatisticsType;
import org.openflow.util.HexString;
import net.floodlightcontroller.connmonitor.ForwardFlowItem.ForwardFLowItemState;
import net.floodlightcontroller.core.FloodlightContext;
import net.floodlightcontroller.core.IFloodlightProviderService;
import net.floodlightcontroller.core.IOFMessageListener;
import net.floodlightcontroller.core.IOFSwitch;
import net.floodlightcontroller.core.IListener.Command;
import net.floodlightcontroller.core.IOFSwitch.PortChangeType;
import net.floodlightcontroller.core.IOFSwitchListener;
import net.floodlightcontroller.core.ImmutablePort;
import net.floodlightcontroller.core.module.FloodlightModuleContext;
import net.floodlightcontroller.core.module.FloodlightModuleException;
import net.floodlightcontroller.core.module.IFloodlightModule;
import net.floodlightcontroller.core.module.IFloodlightService;
import net.floodlightcontroller.packet.Ethernet;
import net.floodlightcontroller.packet.IPacket;
import net.floodlightcontroller.packet.IPv4;
import net.floodlightcontroller.packet.TCP;
import net.floodlightcontroller.packet.UDP;
import net.floodlightcontroller.restserver.IRestApiService;
import net.floodlightcontroller.routing.ForwardingBase;
import net.floodlightcontroller.routing.IRoutingDecision;
import net.floodlightcontroller.routing.IRoutingDecision.RoutingAction;
public class ConnMonitor extends ForwardingBase implements IFloodlightModule,IOFMessageListener, IOFSwitchListener, IConnMonitorService {
//FIXME: move these to configure file
static short HARD_TIMEOUT = 0;
static short IDLE_TIMEOUT = 30;
static short HIH_HARD_TIMEOUT = 300;
static short HIH_IDLE_TIMEOUT = 60;
static short DELTA = 50;
static long CONN_TIMEOUT = 300000;
static short HIGH_PRIORITY = 20;
static short DEFAULT_PRIORITY = 5;
static short DROP_PRIORITY = 0;
static short HIGH_DROP_PRIORITY = 100;
static short HIGH_DROP_TIMEOUT = 300;
static long LASSEN_SW = 203050741063572L;
static long MISSOURI_SW = 161340422318L;
static int CONN_MAX_SIZE = 100000;
static String hih_manager_url = "http://localhost:55551/inform";
static String honeypotConfigFileName = "honeypots.config";
static String PortsConfigFileName = "ports.config";
static byte[] lassen_mac_address = {(byte)0xb8,(byte) 0xac,(byte)0x6f,(byte)0x4a,(byte) 0xdf,(byte) 0x94};
static short lassen_default_out_port = 9; //port number for eth0
static byte[] missouri_mac_address = {(byte)0x00, (byte)0x25, (byte)0x90, (byte)0xA3, (byte)0x78, (byte)0xAE};
static short missouri_default_out_port = 1;
static byte[] nc_mac_address = {(byte)0x00, (byte)0x30, (byte)0x48, (byte)0x30, (byte)0x03, (byte)0xAF};
static byte[] honeypot_net = {(byte)192,(byte)168,(byte)1, (byte)0};
static int honeypot_net_mask = 8;
static byte[] public_honeypot_net = {(byte)130, (byte)107, (byte)0, (byte)0};
static int public_honeypot_net_mask = 16;
//FIXME: move these to configure file
//static byte[] nw_ip_address = {(byte)129,(byte)105,(byte)44, (byte)107};
static byte[] test_ip_address_in = {(byte)130,(byte)107,(byte)240, (byte)188};
static byte[] test_ip_address_out = {(byte)112,(byte)221,(byte)111, (byte)111};
/*
* only for test...
*/
//static byte[] heather_download_address = {(byte)130, (byte)107, (byte)128, (byte)143}; //FIXME
static byte[] migration_ip_address = {(byte)10,(byte)1,(byte)1, (byte)10};
static byte[] migration_mac_address = {(byte)0x62, (byte)0x04, (byte)0xc6, (byte)0x49, (byte)0xb0, (byte)0x2e};
static short migration_out_port = 6;
static byte migration_type = HoneyPot.HIGH_INTERACTION;
static byte[] garuda_src_ip = {(byte)129,(byte)105,(byte)44,(byte)99 };
static byte[] dod_src_ip = {(byte)129,(byte)105,(byte)44,(byte)60 };
static byte[] a_src_ip = {(byte)24,(byte)13,(byte)81,(byte)140 };
static byte[] neighbor_ip_address = {(byte)10,(byte)1,(byte)1, (byte)2};
static byte[] neighbor_mac_address = {(byte)0x08, (byte)0x00, (byte)0x27, (byte)0xeb, (byte)0x66, (byte)0xbb};
static short neighbor_out_port = 5;
static byte[] snooper_ip_address = {(byte)10,(byte)1,(byte)1, (byte)21};
static short snooper_out_port = 19;
String migrationEngineIP = "130.107.10.50";
short migrationEngineListenPort = 22222;
/*
* These five tables' sizes are fixed.
* no worry about memory leak...
*/
protected Hashtable<String,HoneyPot> honeypots;
private Hashtable<String,Long> switches;
protected Hashtable<Short, Vector<HoneyPot>> ports;
protected Hashtable<Short, Vector<HoneyPot>> portsForHIH;
protected Hashtable<String,Boolean> HIHAvailabilityMap;
protected Hashtable<Long, String > HIHNameMap;
protected Hashtable<String, Integer> HIHFlowCount;
/*
* These tables's sizes will get increased
* Make sure they will NOT increase infinitely...
*/
protected Hashtable<Long,Connection> connMap;
protected Hashtable<String, Connection> connToPot;
protected Hashtable<String, HashSet<Integer> > HIHClientMap;
protected ForwardFlowTable forwardFlowTable;
protected ConcurrentLinkedQueue<ForwardFlowItem> flowRemovedTasks;
protected ConcurrentLinkedQueue<ForwardFlowItem> flowRemovedDoneTasks;
protected IFloodlightProviderService floodlightProvider;
protected IRestApiService restApi;
private ExecutorService executor;
private FlowRemoveMsgSender nwMsgSender;
protected MyLogger logger;
static Date currentTime = new Date();
private long lastClearConnMapTime;
private long lastClearConnToPotTime;
private long lastTime;
private long packetCounter;
private long droppedCounter;
private long droppedHIHCounter;
@Override
public String getName() {
return ConnMonitor.class.getSimpleName();
}
@Override
public boolean isCallbackOrderingPrereq(OFType type, String name) {
return false;
}
@Override
public boolean isCallbackOrderingPostreq(OFType type, String name) {
return false;
}
/*
* DownloadIP: 130.107.1XXXXXXX.1XXXXXX1
* OpenIP: 130.107.1XXXXXXX.1XXXXXX0 => 13 valid bits
* srcIP/13 => one OpenIP
*/
static public int getOpenAddress(int srcIP){
/* get first 13 bits 0x00 00 1F FF */
int net = (srcIP>>19)&(0x00001FFF);
int first7 = (net>>6)&(0x0000007F);
int last6 = (net)&(0x0000003F);
int c = first7 | 128; //1 first7
int d = (last6<<1) | 128; //1 last6 0
int dstIP = ((130<<24) | (107<<16) | (c<<8) | d);
return dstIP;
}
private String buildMessageForHIHManager(String name, String type, String time){
String url = hih_manager_url+"?name="+name+"&type="+type;
if(time != null)
url += "&time="+time;
return url;
}
private net.floodlightcontroller.core.IListener.Command PacketInMsgHandler(
IOFSwitch sw, OFMessage msg, FloodlightContext cntx){
packetCounter++;
if(sw.getId() == MISSOURI_SW){
Ethernet eth =
IFloodlightProviderService.bcStore.get(cntx,
IFloodlightProviderService.CONTEXT_PI_PAYLOAD);
Connection conn = new Connection(eth);
/*OFPacketIn packet_in_msg = (OFPacketIn)msg;
boolean no_buffer_id = false;
if (packet_in_msg.getBufferId() == 0xffffffff){
no_buffer_id = true;
}*/
/* For statistics */
if((conn.getType()==Connection.INTERNAL_TO_EXTERNAL) &&
(conn.getProtocol()==0x06)){
long now = System.currentTimeMillis();
long five_min = 60000*10;
if(now - lastTime > five_min){
Date date = new Date(now);
float rs = (float)(packetCounter-droppedCounter)/(float)(packetCounter);
logger.LogDebug("In five mins: pkt counter: "+packetCounter+" dropped counter:"+droppedCounter+" rs:"+rs+" time:"+date.toString());
OFMatch match = new OFMatch();
match.setWildcards(OFMatch.OFPFW_ALL);
int mb = 1024*1024;
Runtime runtime = Runtime.getRuntime();
long free_memory = runtime.freeMemory()/mb;
long total_memory = runtime.totalMemory()/mb;
logger.LogDebug("free memory: "+free_memory+" Total memory:"+total_memory);
logger.LogDebug("connection size: "+connMap.size()+" connToPot size:"+connToPot.size());
if (free_memory < 100){
forceClearMaps();
logger.LogDebug("Force clear maps!!!");
}
logger.LogDebug("");
packetCounter = 1;
droppedCounter = 1;
lastTime = now;
}
}
if(conn.srcIP==0 || conn.type==Connection.INVALID){
droppedCounter++;
return Command.CONTINUE;
}
int x = 2;
int y = 1;
y += 1;
if(processedByOtherHoneynets(conn, ((OFPacketIn)msg).getInPort(), sw,msg, eth) ){
return Command.CONTINUE;
}
HoneyPot pot = getHoneypotFromConnection(conn);
if(pot == null){
droppedCounter++;
return Command.CONTINUE;
}
conn.setHoneyPot(pot);
Long key = conn.getConnectionSimplifiedKey();
Connection e2IFlow = null;
byte[] srcIP = null;
if(connMap.containsKey(key)){
e2IFlow = connMap.get(key);
if(conn.type==Connection.EXTERNAL_TO_INTERNAL){
String connKey =
Connection.createConnKeyString(conn.getDstIP(), conn.getDstPort(), e2IFlow.dstIP, conn.getSrcPort());
if(connToPot.containsKey(connKey) && (connToPot.get(connKey).pot.getName().equals(conn.pot.getName())) ){
connToPot.get(connKey).updateTime();
}
else if((e2IFlow.dstIP != conn.dstIP)){
if(e2IFlow.isConnExpire(CONN_TIMEOUT)){
connMap.put(key, conn);
}
else{
int openIP = getOpenAddress(conn.srcIP);
if(openIP == conn.dstIP){
logger.LogDebug("hit open IP: "+ IPv4.fromIPv4Address(conn.srcIP)+" "+IPv4.fromIPv4Address(conn.dstIP));
}
else{
return Command.CONTINUE;
}
}
}
else
{
e2IFlow.updateTime();
}
}
else if(conn.type==Connection.INTERNAL_TO_EXTERNAL){
srcIP = IPv4.toIPv4AddressBytes(e2IFlow.dstIP);
if(e2IFlow.getHoneyPot()==null){
e2IFlow.setHoneyPot(getHoneypotFromConnection(e2IFlow));
}
String connKey =
Connection.createConnKeyString(conn.getDstIP(), conn.getDstPort(), e2IFlow.dstIP, conn.getSrcPort());
if(connToPot.containsKey(connKey)){
if(connToPot.get(connKey).getHoneyPot().getName().equals( conn.getHoneyPot().getName())){
connToPot.get(connKey).updateTime();
}
else{
connToPot.put(connKey, conn);
}
}
else{
connToPot.put(connKey, conn);
}
if(conn.getHoneyPot().getType()==HoneyPot.HIGH_INTERACTION){
if(!( HIHClientMap.containsKey( conn.getHoneyPot().getName() )) ){
HIHClientMap.put(conn.getHoneyPot().getName(), new HashSet<Integer>() );
}
HIHClientMap.get(conn.getHoneyPot().getName()).add(conn.getDstIP());
}
clearMaps();
}
else{
logger.LogError("shouldn't come here "+conn);
return Command.CONTINUE;
}
}
else{ //no such connection
if(conn.type==Connection.EXTERNAL_TO_INTERNAL){
connMap.put(key, conn);
if(conn.pot.getType()==HoneyPot.HIGH_INTERACTION){
logger.LogDebug("allocate HIGH_INTERACTION honeypot for connection "+conn);
//inform hih manager
String url = buildMessageForHIHManager(conn.pot.getName(),"newvm",null);
try {
executor.submit(new Request(new URL(url)));
} catch (MalformedURLException e) {
logger.LogError("error sending request");
e.printStackTrace();
}
if(HIHAvailabilityMap.get(conn.pot.getName())==false){
logger.LogError("error inconsistency "+conn.pot.getName()+" ");
droppedHIHCounter++;
return Command.CONTINUE;
}
if(conn.getHoneyPot().getType()==HoneyPot.HIGH_INTERACTION){
if(!( HIHClientMap.containsKey( conn.getHoneyPot().getName() )) ){
HIHClientMap.put(conn.getHoneyPot().getName(), new HashSet<Integer>() );
}
HIHClientMap.get(conn.getHoneyPot().getName()).add(conn.getSrcIP());
}
HIHAvailabilityMap.put(conn.pot.getName(), false);
}
clearMaps();
//logger.info("2 new e2i connection, assigned to "+key+" "+conn);
}
else if(conn.type==Connection.INTERNAL_TO_EXTERNAL){
conn.setSrcIP(conn.getHoneyPot().getDownloadAddrInt());
e2IFlow = new Connection(conn);
e2IFlow.setHoneyPot(conn.getHoneyPot());
srcIP = pot.getDownloadAddress();
String connKey =
Connection.createConnKeyString(conn.getDstIP(), conn.getDstPort(),
conn.getHoneyPot().getDownloadAddrInt(), conn.getSrcPort());
if(connToPot.containsKey(connKey)){
if(connToPot.get(connKey).getHoneyPot().getName().equals( conn.getHoneyPot().getName())){
connToPot.get(connKey).updateTime();
}
else{
connToPot.put(connKey, conn);
}
}
else{
connToPot.put(connKey, conn);
}
if(conn.getHoneyPot().getType()==HoneyPot.HIGH_INTERACTION){
if(!( HIHClientMap.containsKey( conn.getHoneyPot().getName() )) ){
HIHClientMap.put(conn.getHoneyPot().getName(), new HashSet<Integer>() );
}
HIHClientMap.get(conn.getHoneyPot().getName()).add(conn.getDstIP());
}
}
else{
logger.LogError("shouldn't come here 2 "+conn);
return Command.CONTINUE;
}
}
OFPacketIn pktInMsg = (OFPacketIn)msg;
OFMatch match = null;
byte[] newDstMAC = null;
byte[] newDstIP = null;
short outPort = 0;
boolean result1 = true;
if( conn.pot.getType() == HoneyPot.HIGH_INTERACTION ){
/* High Interaction Honeypot (HIH)'s flow is different:
* 1. we guarantee e2i flow expire before i2e flow
* 2. we handle flow removal message only for e2i flow
* 3. e2i flow will be set idle timeout, i2e will not
*/
//i2e
match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkDestination(conn.srcIP);
match.setNetworkSource(conn.getHoneyPot().getIpAddrInt());
match.setInputPort(conn.pot.getOutPort());
match.setTransportSource(conn.dstPort);
match.setTransportDestination(conn.srcPort);
match.setNetworkProtocol(conn.getProtocol());
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP );
newDstMAC = nc_mac_address;
outPort = missouri_default_out_port;
byte[] newSrcIP = IPv4.toIPv4AddressBytes(conn.dstIP);
result1 =
installPathForFlow(sw.getId(),conn.pot.getOutPort(),match,(short)0,conn.pot.getId(),
newDstMAC,newDstIP,newSrcIP,
(short)0, (short)0,
outPort,(short)0,(short)(HIH_HARD_TIMEOUT+DELTA),HIGH_PRIORITY);
//e2i
match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkDestination(conn.dstIP);
match.setNetworkSource(conn.srcIP);
match.setTransportSource(conn.srcPort);
match.setTransportDestination(conn.dstPort);
match.setInputPort(pktInMsg.getInPort());
match.setNetworkProtocol(conn.getProtocol());
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP);
newDstMAC = conn.pot.getMacAddress();
newDstIP = conn.getHoneyPot().getIpAddress();
outPort = conn.pot.getOutPort();
boolean result2 =
installPathForFlow(sw.getId(),pktInMsg.getInPort(),match,OFFlowMod.OFPFF_SEND_FLOW_REM,conn.pot.getId(),
newDstMAC,newDstIP,srcIP,(short)0, (short)0,outPort,HIH_IDLE_TIMEOUT,HIH_HARD_TIMEOUT,HIGH_PRIORITY);
result1 &= result2;
int count = HIHFlowCount.get(conn.getHoneyPot().getName());
count++;
HIHFlowCount.put(conn.getHoneyPot().getName(), count);
}
else if(conn.type == Connection.EXTERNAL_TO_INTERNAL){
match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkDestination(conn.srcIP);
match.setNetworkSource(conn.getHoneyPot().getIpAddrInt());
match.setInputPort(pktInMsg.getInPort());
match.setTransportSource(conn.dstPort);
match.setTransportDestination(conn.srcPort);
match.setNetworkProtocol(conn.getProtocol());
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP );
newDstMAC = nc_mac_address;
outPort = pktInMsg.getInPort();
byte[] newSrcIP = IPv4.toIPv4AddressBytes(conn.dstIP);
result1 = installPathForFlow(sw.getId(),pktInMsg.getInPort(),match,(short)0,(long)0,
newDstMAC,newDstIP,newSrcIP,(short)0, (short)0,outPort,IDLE_TIMEOUT,HARD_TIMEOUT,HIGH_PRIORITY);
match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkDestination(conn.dstIP);
match.setNetworkSource(conn.srcIP);
match.setTransportSource(conn.srcPort);
match.setTransportDestination(conn.dstPort);
match.setInputPort(pktInMsg.getInPort());
match.setNetworkProtocol(conn.getProtocol());
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP);
newDstMAC = lassen_mac_address;
newDstIP = conn.getHoneyPot().getIpAddress();
outPort = pktInMsg.getInPort();
boolean result2 = installPathForFlow(sw.getId(),pktInMsg.getInPort(),match,(short)0,(long)0,
newDstMAC,newDstIP,srcIP,(short)0, (short)0,outPort,IDLE_TIMEOUT,HARD_TIMEOUT,HIGH_PRIORITY);
result1 &= result2;
}
else if(conn.type == Connection.INTERNAL_TO_EXTERNAL){
match = new OFMatch();
//FIXME: no need to set strict match here
match.setDataLayerType((short)0x0800);
match.setNetworkDestination(conn.dstIP);
match.setNetworkSource(e2IFlow.getHoneyPot().getIpAddrInt());
match.setInputPort(pktInMsg.getInPort());
match.setTransportSource(conn.srcPort);
match.setTransportDestination(conn.dstPort);
match.setNetworkProtocol(conn.getProtocol());
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP );
newDstMAC = nc_mac_address;
outPort = pktInMsg.getInPort();
result1 = installPathForFlow(sw.getId(), pktInMsg.getInPort(),match,(short)0,(long)0,
newDstMAC,newDstIP,srcIP,(short)0, (short)0,outPort,IDLE_TIMEOUT,HARD_TIMEOUT,HIGH_PRIORITY);
}
else{
logger.LogError("shouldn't come here 3 "+conn);
return Command.CONTINUE;
}
//forwardPacket(sw,pktInMsg, dstMAC,dstIP,srcIP,outPort);
boolean result2 = forwardPacket(sw,pktInMsg, newDstMAC,newDstIP,srcIP,outPort);
if(!result1 || !result2){
logger.LogError("fail to install rule for "+conn);
}
}
else if(sw.getId() == LASSEN_SW){
logger.LogError("Ignore packets sent from LASSEN_SW");
initLassenSwitch(sw.getId());
}
else{
logger.LogDebug("Unknown switch: "+sw.getStringId());
}
return Command.CONTINUE;
}
private net.floodlightcontroller.core.IListener.Command FlowRemovedMsgHandler(
IOFSwitch sw, OFMessage msg, FloodlightContext cntx){
if(msg instanceof OFFlowRemoved){
OFFlowRemoved removedMsg = (OFFlowRemoved)msg;
if(removedMsg.getReason()==OFFlowRemoved.OFFlowRemovedReason.OFPRR_DELETE){
return Command.CONTINUE;
}
/*
* Add codes here to detect ForwardFlow gets removed
* remember to update cookie_key_map, table and send request to NW
*/
int dstIP = removedMsg.getMatch().getNetworkDestination();
int srcIP = removedMsg.getMatch().getNetworkSource();
for(Honeynet net : Honeynet.getAllHoneynets()){
String name = net.getName();
Honeynet.SubnetMask mask = net.getMask();
System.err.println("remove flows: test for honeynet "+name+" mask:"+mask+" src_ip:"+IPv4.fromIPv4Address(srcIP)+" dst_ip:"+IPv4.fromIPv4Address(dstIP));
if(Honeynet.inSubnet(mask, dstIP) || Honeynet.inSubnet(mask, srcIP) ){
long cookie = removedMsg.getCookie();
System.err.println(" remove flows: flow belonging to "+name+" with cookie:"+cookie);
String key = forwardFlowTable.fromCookieToKey(cookie);
if(key == null){
System.err.println(" the item has already been removed from forwardFlowTable");
return Command.CONTINUE;
}
forwardFlowTable.removeCookieStringMap(cookie);
ForwardFlowItem item = forwardFlowTable.get(key);
if(item == null){
System.err.println(" can't find this item from forwardFlowTable");
return Command.CONTINUE;
}
item.setState(ForwardFLowItemState.WAIT_FOR_DEL_ACK);
deleteForwardRule(sw,item);
informRemoteToDestroyFlowInfo(item);
System.err.println(" done handling forward rules removed msg "+cookie);
return Command.CONTINUE;
}
}
processDoneItems();
if(removedMsg.getReason()==OFFlowRemoved.OFFlowRemovedReason.OFPRR_HARD_TIMEOUT){
logger.LogDebug("TODO: FlowRemovedMsgHandler handle OFPRR_HARD_TIMEOUT");
return Command.CONTINUE;
}
else{
/* send destroy msg to manager */
long cookie = removedMsg.getCookie();
String honeypotName = null;
if(HIHNameMap.containsKey(cookie)){
honeypotName = HIHNameMap.get(cookie);
}
if(honeypotName != null){
int count = HIHFlowCount.get(honeypotName) - 1;
if(count > 0){
logger.LogDebug("flow for vm: "+honeypotName+" gets removed. "+count+" has left");
HIHFlowCount.put(honeypotName, count);
}
else if(count <= 0){
logger.LogDebug("flow for vm: "+honeypotName+" gets removed. leave vm");
HIHFlowCount.put(honeypotName, 0);
String url = buildMessageForHIHManager(honeypotName, "leavevm", null);
try {
executor.submit(new Request(new URL(url)));
} catch (MalformedURLException e) {
logger.LogError("fail to send leavevm request");
e.printStackTrace();
}
}
}
else{
logger.LogError("invalid cookie! "+cookie);
}
return Command.CONTINUE;
}
}
else{
}
return Command.CONTINUE;
}
@Override
public net.floodlightcontroller.core.IListener.Command receive(
IOFSwitch sw, OFMessage msg, FloodlightContext cntx) {
if (msg.getType() == OFType.PACKET_IN)
{
return PacketInMsgHandler(sw,msg,cntx);
}
else if(msg.getType() == OFType.FLOW_REMOVED){
return FlowRemovedMsgHandler(sw,msg,cntx);
}
else{
}
return Command.CONTINUE;
}
private HoneyPot getHoneypotFromConnection(Connection conn){
if(conn.type==Connection.EXTERNAL_TO_INTERNAL){
short dport = conn.getDstPort();
int dstIP = conn.getDstIP();
int flag = (dstIP>>8)&0x000000e0;
/* Test codes, can be deleted */
int g_ip = IPv4.toIPv4Address(garuda_src_ip);
int d_ip = IPv4.toIPv4Address(dod_src_ip);
int a_ip = IPv4.toIPv4Address(a_src_ip);
if(((conn.srcIP==g_ip) || (conn.srcIP==d_ip)) && (dport==(short)23) ){
logger.LogDebug("return kippo for 23");
return honeypots.get("kippo");
}
if((conn.srcIP == g_ip) && ((dport==(short)445) || (dport==(short)139) || (dport==(short)139))){
return honeypots.get("lily_winxp3");
}
/* End of Test Codes */
/* if we have records for this connection, use existing honeypot */
String key =
Connection.createConnKeyString(conn.getSrcIP(), conn.getSrcPort(), conn.getDstIP(), conn.getDstPort());
if(connToPot.containsKey(key)){
if(!(connToPot.get(key).isConnExpire(CONN_TIMEOUT))){
connToPot.get(key).updateTime();
return connToPot.get(key).getHoneyPot();
}
}
/* otherwise, we allocate honeypot based on default policy */
/* first check if this port can be addressed by HIH */
if(portsForHIH.containsKey(dport)){
/* check if this src already has one HIH */
Iterator<Map.Entry<String, HashSet<Integer>>> it1 = HIHClientMap.entrySet().iterator();
while (it1.hasNext()) {
Map.Entry<String, HashSet<Integer>> entry = it1.next();
HashSet<Integer> ips = HIHClientMap.get(entry.getKey());
for(Integer ip : ips){
if(ip == conn.getSrcIP()){
logger.LogDebug("choose HIH honeypot [old src] "+entry.getKey()+" "+entry.getValue() +conn);
return honeypots.get(entry.getKey());
}
}
}
/* check if we have available HIH */
Iterator<Map.Entry<String, Boolean>> it2 = HIHAvailabilityMap.entrySet().iterator();
while (it2.hasNext()) {
Map.Entry<String, Boolean> entry = it2.next();
if(entry.getValue() == true){
HoneyPot pot = honeypots.get(entry.getKey());
if(pot.getMask().containsKey(dport) && pot.getMask().get(dport).inSubnet(dstIP)){
logger.LogError("choose HIH honeypot [new src] "+entry.getKey()+" "+entry.getValue() +conn);
return honeypots.get(entry.getKey());
}
}
}
}
/* if not, find a LIH to address the port */
if(ports.containsKey(dport)){
Vector<HoneyPot> pots = ports.get(dport);
for(HoneyPot pot : pots){
if(pot.getMask().containsKey(dport) && pot.getMask().get(dport).inSubnet(dstIP)){
return pot;
}
}
logger.LogError("can't address dstIP "+IPv4.fromIPv4Address(dstIP)+ dport+" ");
for(HoneyPot pot : pots){
logger.LogError(pot.getName()+" containsKey:"+pot.getMask().containsKey(dport));
if(pot.getMask().containsKey(dport))
logger.LogError(pot.getName()+" :"+pot.getMask().get(dport)+" "+pot.getMask().get(dport).inSubnet(dstIP));
}
return null;
}
else{
logger.LogDebug("can't address port "+dport);
//for(short p : ports.keySet()){
// System.err.println("debug: port:"+p);
return null;
}
}
else if(conn.type == Connection.INTERNAL_TO_EXTERNAL){
for (HoneyPot pot: honeypots.values()) {
if(pot.getIpAddrInt() == conn.getSrcIP()){
return pot;
}
}
}
return null;
}
private boolean initMissouriSwitch(long switchId){
IOFSwitch sw = floodlightProvider.getSwitch(switchId);
OFMatch match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkDestination(IPv4.toIPv4Address(public_honeypot_net));
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP|
OFMatch.OFPFW_NW_SRC_ALL| public_honeypot_net_mask<<OFMatch.OFPFW_NW_DST_SHIFT|
OFMatch.OFPFW_NW_PROTO | OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_TP_SRC | OFMatch.OFPFW_TP_DST |
OFMatch.OFPFW_IN_PORT);
byte[] newDstMAC = null;
byte[] newDstIP = null;
byte[] newSrcIP = null;
short outPort = OFPort.OFPP_CONTROLLER.getValue();
boolean result =
installPathForFlow(sw.getId(),(short)0,match,(short)0,(long)0, newDstMAC,newDstIP,newSrcIP,
(short)0, (short)0,outPort,(short)0, (short)0,DEFAULT_PRIORITY);
if(!result){
logger.LogError("fail to create default rule1 for MISSOURI 1");
System.exit(1);
return false;
}
match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkSource(IPv4.toIPv4Address(honeypot_net));
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP|
OFMatch.OFPFW_NW_DST_ALL| honeypot_net_mask<<OFMatch.OFPFW_NW_SRC_SHIFT|
OFMatch.OFPFW_NW_PROTO | OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_TP_SRC | OFMatch.OFPFW_TP_DST |
OFMatch.OFPFW_IN_PORT);
result = installPathForFlow(sw.getId(),(short)0,match,(short)0,(long)0, newDstMAC,newDstIP,newSrcIP,
(short)0, (short)0,outPort,(short)0, (short)0,DEFAULT_PRIORITY);
if(!result){
logger.LogError("fail to create default rule1 for MISSOURI 2");
System.exit(1);
return false;
}
match = new OFMatch();
match.setWildcards(OFMatch.OFPFW_ALL);
result = installDropRule(sw.getId(),match,(short)0,(short)0,DROP_PRIORITY);
/***Configure Switch to send whole package to Controller***/
OFSetConfig config = new OFSetConfig();
config.setMissSendLength((short)0xffff);
try{
sw.write(config, null);
sw.flush();
System.out.println("Done writing config to sw");
}
catch(Exception e){
System.err.println("Write config to sw: "+e);
}
return result;
}
private void deleteForwardRule(IOFSwitch sw, ForwardFlowItem item){
System.err.println(" deleteForwardRule");
OFFlowMod ruleIncoming = new OFFlowMod();
ruleIncoming.setOutPort(OFPort.OFPP_NONE);
ruleIncoming.setCommand(OFFlowMod.OFPFC_DELETE);
ruleIncoming.setBufferId(OFPacketOut.BUFFER_ID_NONE);
OFMatch match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkSource(item.getSrc_ip());
match.setNetworkDestination(item.getDst_ip());
match.setTransportSource(item.getSrc_port());
match.setTransportDestination(item.getDst_port());
match.setNetworkProtocol(item.getProtocol());
match.setWildcards( OFMatch.OFPFW_IN_PORT |
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP);
ruleIncoming.setMatch(match.clone());
OFFlowMod ruleOutgoing = new OFFlowMod();
ruleOutgoing.setOutPort(OFPort.OFPP_NONE);
ruleOutgoing.setCommand(OFFlowMod.OFPFC_DELETE);
ruleOutgoing.setBufferId(OFPacketOut.BUFFER_ID_NONE);
match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkSource(item.getRemote_ip());
match.setNetworkDestination(item.getSrc_ip());
match.setTransportSource(item.getDst_port());
short port = item.getSrc_port();
if(item.getSrc_port() != item.getNew_src_port())
port = item.getNew_src_port();
match.setTransportDestination(port);
match.setNetworkProtocol(item.getProtocol());
match.setWildcards( OFMatch.OFPFW_IN_PORT |
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP);
ruleOutgoing.setMatch(match.clone());
try{
sw.write(ruleIncoming, null);
sw.write(ruleOutgoing, null);
sw.flush();
}
catch (IOException e){
logger.LogError("fail delete flows for: "+item+" "+ruleIncoming+" "+ruleOutgoing);
}
}
private void informRemoteToDestroyFlowInfo(ForwardFlowItem item){
System.err.println(" Inform "+item.getName()+" to Destroy Flow Info");
flowRemovedTasks.add(item);
if(flowRemovedTasks.size() > CONN_MAX_SIZE/2){
System.err.println(" Alert!!! clear flowRemovedTasks");
flowRemovedTasks.clear();
}
}
private int positivePort(short port){
int rs = port & 0x0000ffff;
return rs;
}
/*untested method*/
private void processDoneItems(){
ForwardFlowItem item = null;
int count = 0;
while((item=flowRemovedDoneTasks.poll()) != null){
int srcIP = item.getSrc_ip();
int dstIP = item.getDst_ip();
short srcPort = item.getNew_src_port()==0?item.getSrc_port():item.getNew_src_port();
short dstPort = item.getDst_port();
String key = ForwardFlowItem.generateForwardFlowTableKey(srcIP, srcPort, dstIP, dstPort);
ForwardFlowItem storedItem = forwardFlowTable.get(key);
storedItem.setState(ForwardFLowItemState.FREE);
count++;
}
if(count != 0){
System.err.println("Done free "+count+" items");
}
}
private boolean processedByOtherHoneynets(Connection conn, short inport,IOFSwitch sw, OFMessage msg,Ethernet eth ){
long switch_id = sw.getId();
for(Honeynet thirdPartyHoneynet : Honeynet.getAllHoneynets()){
//Honeynet thirdPartyHoneynet = Honeynet.getHoneynet("nw");
if(thirdPartyHoneynet ==null){
System.err.println("No honeynet!");
return false;
}
Honeynet.SubnetMask mask = thirdPartyHoneynet.getMask();
String name = thirdPartyHoneynet.getName();
byte[] remoteIPAddress = IPv4.toIPv4AddressBytes(thirdPartyHoneynet.getIp());
byte[] newDstMAC = null;
byte[] newDstIP = null;
byte[] newSrcIP = null;
short outPort = 0;
/*from thirdPartyHoneynet to SRI */
if((conn.srcIP==thirdPartyHoneynet.getIp()) && (Honeynet.inSubnet(mask,conn.dstIP))){
//130.107.244.244:3357-129.105.44.107:80
String key = ForwardFlowItem.generateForwardFlowTableKey(conn.dstIP, conn.dstPort, conn.srcIP, conn.srcPort);
//System.err.println("SENT FROM "+name+" src:"+IPv4.fromIPv4Address(conn.srcIP)+" dst:"+IPv4.fromIPv4Address(conn.dstIP) +
// " flow srcport:"+positivePort(conn.srcPort) +
// " flow dstport:"+positivePort(conn.dstPort)+"\n key:"+key);
ForwardFlowItem item = forwardFlowTable.get(key);
if(item==null){
System.err.println(" can't find this flow. give up!!!");
return true;
}
IPacket packet = eth.getPayload();
short front_src_ip = (short)( (item.getSrc_ip()>>>16) & 0x0000ffff);
short end_src_ip = (short)(item.getSrc_ip() & 0x0000ffff);
if(packet instanceof IPv4){
IPv4 ip_pkt = (IPv4)packet;
// FIXME: information is stored in ecn because dscn will be striped!!!
byte ecn = ip_pkt.getDiffServ();
if(ecn == 0x01){
//System.err.println("missing 0x04 setup packet "+((OFPacketIn)msg).getInPort());
boolean rs = forwardPacket2OtherNet(sw,(OFPacketIn)msg, nc_mac_address,remoteIPAddress,
IPv4.toIPv4AddressBytes(conn.getDstIP()),((OFPacketIn)msg).getInPort(),
eth, (byte)0x01, front_src_ip,
conn.dstPort, conn.srcPort);
//System.err.println("done resending 0x04 setup packet "+rs);
return true;
}
else if(ecn == 0x02){
//System.err.println("missing 0x08 setup packet "+((OFPacketIn)msg).getInPort());
boolean rs = forwardPacket2OtherNet(sw,(OFPacketIn)msg, nc_mac_address,remoteIPAddress,
IPv4.toIPv4AddressBytes(conn.getDstIP()),((OFPacketIn)msg).getInPort(),
eth, (byte)0x02, end_src_ip,
conn.dstPort, conn.srcPort);
//System.err.println("done resending 0x08 setup packet "+rs);
return true;
}
else if(ecn == 0x03){
//System.err.println("missing 0x0c setup packet "+((OFPacketIn)msg).getInPort());
boolean rs1 = forwardPacket2OtherNet(sw,(OFPacketIn)msg, nc_mac_address,remoteIPAddress,
IPv4.toIPv4AddressBytes(conn.getDstIP()),((OFPacketIn)msg).getInPort(),
eth, (byte)0x01, front_src_ip,
conn.dstPort, conn.srcPort);
boolean rs2 = forwardPacket2OtherNet(sw,(OFPacketIn)msg, nc_mac_address,remoteIPAddress,
IPv4.toIPv4AddressBytes(conn.getDstIP()),((OFPacketIn)msg).getInPort(),
eth, (byte)0x02, end_src_ip,
conn.dstPort, conn.srcPort);
//System.err.println("done resending 0x04 setup packet "+rs1);
//System.err.println("done resending 0x08 setup packet "+rs2);
return true;
}
else{
System.err.println(" dscn: "+ecn);
}
}
//System.err.println(" original src:"+IPv4.fromIPv4Address(item.getSrc_ip()));
/* thirdPartyHoneynet->attacker rule */
OFMatch match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkDestination(conn.dstIP);
match.setNetworkSource(IPv4.toIPv4Address(remoteIPAddress));
match.setTransportDestination(conn.dstPort);
match.setTransportSource(conn.srcPort);
match.setInputPort(inport);
match.setNetworkProtocol(conn.getProtocol());
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP);
newDstMAC = nc_mac_address;
newDstIP = IPv4.toIPv4AddressBytes(item.getSrc_ip());
newSrcIP = IPv4.toIPv4AddressBytes(conn.dstIP);
outPort = inport;
short new_dst_port = 0;
if(item.getSrc_port() !=item.getNew_src_port() )
new_dst_port = item.getSrc_port();
//System.err.println(" new_dst_port:"+positivePort(new_dst_port));
boolean rs = installPathForFlow(switch_id,inport,match,OFFlowMod.OFPFF_SEND_FLOW_REM,
item.getFlow_cookie(), newDstMAC,newDstIP,newSrcIP,
(short)0, new_dst_port,outPort,IDLE_TIMEOUT,HARD_TIMEOUT,HIGH_PRIORITY);
forwardPacket(sw,(OFPacketIn)msg, nc_mac_address,newDstIP,newSrcIP,outPort);
if (rs == false){
System.err.println(" Fail setting ruls for sending traffic to NW");
}
return true;
}//thirdPartyHoneynet->attacker
else if(Honeynet.inSubnet(mask,conn.dstIP)){ /*Attacker -> thirdPartyHoneynet*/
/*For test
int special_ip = IPv4.toIPv4Address("130.107.244.244");
if((conn.dstPort != (short)80)|| (conn.dstIP != special_ip) )
return true;
*/
//130.107.244.244:3357-129.105.44.107:80
String key = ForwardFlowItem.generateForwardFlowTableKey(conn.dstIP, conn.srcPort, thirdPartyHoneynet.getIp(), conn.dstPort);
//System.err.println("SENT TO "+name+" src:"+IPv4.fromIPv4Address(conn.srcIP)+" dst:"+IPv4.fromIPv4Address(conn.dstIP) +
// " flow srcport:"+positivePort(conn.srcPort) +
// " flow dstport:"+positivePort(conn.dstPort)+"\n key:"+key);
short new_src_port = conn.srcPort;
long cookie = 0;
if(forwardFlowTable.containsKey(key)) /* table item exists*/
{
//System.err.println(" entry exists for this flow:"+key);
int count = 0;
while(true){
if(count > 5){
System.err.println(" can't find available port: give up!!!");
return true;
}
count++;
key = ForwardFlowItem.generateForwardFlowTableKey(conn.dstIP, new_src_port, thirdPartyHoneynet.getIp(), conn.dstPort);
processDoneItems();
ForwardFlowItem item = forwardFlowTable.get(key);
if((item==null) || (item.getState()==ForwardFlowItem.ForwardFLowItemState.FREE)){
//System.err.println(" flow entry is ready for replacement");
item = new ForwardFlowItem(conn.srcIP,conn.srcPort,conn.dstIP,conn.dstPort,new_src_port,(long)HARD_TIMEOUT,
conn.getProtocol(),thirdPartyHoneynet.getIp(),name);
cookie = forwardFlowTable.put(key, item);
break;
}
else if(item.getState()==ForwardFlowItem.ForwardFLowItemState.WAIT_FOR_DEL_ACK){
//the other thread can only delete this item
//System.err.println(" flow entry is not ready for replacement: WAIT_FOR_DEL_ACK");
new_src_port = ForwardFlowItem.generateRandomPortNumber();
continue;
}
else if(item.getState()==ForwardFlowItem.ForwardFLowItemState.USE){
//System.err.println(" flow entry is in USE");
if((conn.srcIP == item.getSrc_ip()) && (conn.srcPort==item.getSrc_port())){
//System.err.println(" same flow, update StartingTime.");
if(forwardFlowTable.updateStartingtime(key,System.currentTimeMillis())==false){
System.err.println(" error updateStartingTime. This one is deleted by other thread");
}
cookie = item.getFlow_cookie();
break;
}
else if(item.expire()){
forwardFlowTable.updateItemState(key, ForwardFlowItem.ForwardFLowItemState.WAIT_FOR_DEL_ACK);
//System.err.println(" not same flow, but expired, del it asynchronously");
deleteForwardRule(sw,item);
informRemoteToDestroyFlowInfo(item);
new_src_port = ForwardFlowItem.generateRandomPortNumber();
continue;
}
else{
//System.err.println(" not same flow, switch port");
new_src_port = ForwardFlowItem.generateRandomPortNumber();
continue;
}
}
}
}
else /*new item*/
{ /*src_ip, short src_port, int dst_ip, short dst_port, short new_src_port, timeout*/
//System.err.println(" no entry exists");
/* For test */
//new_src_port = (short)(conn.srcPort+(short)100);
//key = ForwardFlowItem.generateForwardFlowTableKey(conn.dstIP, new_src_port, nw.getIp(), conn.dstPort);
ForwardFlowItem item = new ForwardFlowItem(conn.srcIP,conn.srcPort,conn.dstIP,conn.dstPort,new_src_port,(long)HARD_TIMEOUT,
conn.getProtocol(),thirdPartyHoneynet.getIp(),name);
cookie = forwardFlowTable.put(key, item);
}
//System.err.println(" send setup packets out "+conn+
// "\n flow srcPort:"+positivePort(conn.srcPort)+" new srcPort:"+positivePort(new_src_port));
int src_ip = conn.srcIP;
short front_src_ip = (short)( (src_ip>>>16) & 0x0000ffff);
short end_src_ip = (short)(src_ip & 0x0000ffff);
forwardPacket2OtherNet(sw,(OFPacketIn)msg, nc_mac_address,remoteIPAddress,
IPv4.toIPv4AddressBytes(conn.getDstIP()),((OFPacketIn)msg).getInPort(),
eth,(byte)0x01,front_src_ip,(new_src_port==conn.srcPort)?(short)0:new_src_port,(short)0);
forwardPacket2OtherNet(sw,(OFPacketIn)msg, nc_mac_address,remoteIPAddress,
IPv4.toIPv4AddressBytes(conn.getDstIP()),((OFPacketIn)msg).getInPort(),
eth,(byte)0x02, end_src_ip,(new_src_port==conn.srcPort)?(short)0:new_src_port,(short)0);
//test
/* Attacker->nw rule */
OFMatch match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkDestination(conn.dstIP);
match.setNetworkSource(conn.srcIP);
match.setInputPort(inport);
match.setTransportSource(conn.srcPort);
match.setTransportDestination(conn.dstPort);
match.setNetworkProtocol(conn.getProtocol());
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP );
newDstMAC = nc_mac_address;
newDstIP = remoteIPAddress;
newSrcIP = IPv4.toIPv4AddressBytes(conn.dstIP);
outPort = inport;
if((new_src_port==conn.srcPort) || (new_src_port==0))
new_src_port = 0;
//System.err.println(" install rule for forwording packets to NW. Match:"+match);
boolean rs = installPathForFlow(switch_id,inport,match,OFFlowMod.OFPFF_SEND_FLOW_REM,
cookie, newDstMAC,newDstIP,newSrcIP,new_src_port, (short)0,outPort,IDLE_TIMEOUT,HARD_TIMEOUT,HIGH_PRIORITY);
if(rs==false){
System.err.println(" error installing rule: Match"+match);
}
return true;
}// Outside -> NW field
}
return false;
}
/*private boolean processedByOtherHoneynets_(Connection conn, short inport,IOFSwitch sw, OFMessage msg,Ethernet eth ){
long switch_id = sw.getId();
byte[] src_tmp = IPv4.toIPv4AddressBytes(conn.srcIP);
byte[] dst_tmp = IPv4.toIPv4AddressBytes(conn.dstIP);
if( (src_tmp[0]==(byte)129) && (src_tmp[1]==(byte)105) && (src_tmp[2]==(byte)44) && (src_tmp[3]==(byte)107) ){
System.err.println("Packages sent from NW: "+conn );
return true;
}
else if((dst_tmp[0]==(byte)130) && (dst_tmp[1]==(byte)107) && (dst_tmp[2]>=(byte)240)){
byte[] newDstMAC = null;
byte[] newDstIP = null;
byte[] newSrcIP = null;
short outPort = 0;
int src_ip = conn.srcIP;
short front_src_ip = (short)( (src_ip>>>16) & 0x0000ffff);
short end_src_ip = (short)(src_ip & 0x0000ffff);
System.err.println(conn);
forwardPacket2OtherNet(sw,(OFPacketIn)msg, nc_mac_address,nw_ip_address,IPv4.toIPv4AddressBytes(conn.getDstIP()),((OFPacketIn)msg).getInPort(), eth,(byte)0x01,front_src_ip);
forwardPacket2OtherNet(sw,(OFPacketIn)msg, nc_mac_address,nw_ip_address,IPv4.toIPv4AddressBytes(conn.getDstIP()),((OFPacketIn)msg).getInPort(), eth,(byte)0x02, end_src_ip);
OFMatch match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkDestination(conn.dstIP);
match.setNetworkSource(conn.srcIP);
match.setInputPort(inport);
match.setTransportSource(conn.srcPort);
match.setTransportDestination(conn.dstPort);
match.setNetworkProtocol(conn.getProtocol());
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP );
newDstMAC = nc_mac_address;
newDstIP = nw_ip_address;
newSrcIP = IPv4.toIPv4AddressBytes(conn.dstIP);
outPort = inport;
boolean rs1 = installPathForFlow(switch_id,inport,match,(short)0,(long)0, newDstMAC,newDstIP,newSrcIP,outPort,IDLE_TIMEOUT,HARD_TIMEOUT,HIGH_PRIORITY);
match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkDestination(conn.dstIP);
match.setNetworkSource(IPv4.toIPv4Address(nw_ip_address));
match.setTransportSource(conn.dstPort);
match.setTransportDestination(conn.srcPort);
match.setInputPort(inport);
match.setNetworkProtocol(conn.getProtocol());
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP);
newDstMAC = nc_mac_address;
newDstIP = IPv4.toIPv4AddressBytes(conn.srcIP);
newSrcIP = IPv4.toIPv4AddressBytes(conn.dstIP);
outPort = inport;
boolean rs2 = installPathForFlow(switch_id,inport,match,(short)0,(long)0, newDstMAC,newDstIP,newSrcIP,outPort,IDLE_TIMEOUT,HARD_TIMEOUT,HIGH_PRIORITY);
boolean rs = rs1 & rs2;
if (rs == false){
System.err.println("Fail setting ruls for sending traffic to NW");
}
return true;
}
return false;
}*/
private boolean initLassenSwitch(long switchId){
IOFSwitch sw = floodlightProvider.getSwitch(switchId);
OFMatch match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkSource(IPv4.toIPv4Address(honeypot_net));
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP|
OFMatch.OFPFW_NW_DST_ALL| honeypot_net_mask<<OFMatch.OFPFW_NW_SRC_SHIFT|
OFMatch.OFPFW_NW_PROTO | OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_TP_SRC | OFMatch.OFPFW_TP_DST |
OFMatch.OFPFW_IN_PORT);
byte[] newDstMAC = missouri_mac_address;
byte[] newDstIP = null;
byte[] newSrcIP = null;
short outPort = lassen_default_out_port;
boolean result = installPathForFlow(sw.getId(),(short)0,match,(short)0,(long)0,newDstMAC,newDstIP,newSrcIP,
(short)0, (short)0,outPort,(short)0, (short)0,DEFAULT_PRIORITY);
if(!result){
logger.LogError("failed to create default rule for LASSEN 1");
System.exit(1);
return false;
}
for(HoneyPot pot : honeypots.values()){
setForwardRulesFromLassenToHoneyPot(sw,pot.getIpAddress(),pot.getMacAddress(),pot.getOutPort());
}
match = new OFMatch();
match.setWildcards(OFMatch.OFPFW_ALL);
result = installDropRule(sw.getId(),match,(short)0,(short)0,DROP_PRIORITY);
/*
* The following rules are used only for migration demo (telnet)
*/
/* ip,nw_src=10.1.1.10,nw_dst=10.1.1.2,actions=mod_dl_dst:08:00:27:eb:66:bb, output:5 */
match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkSource(IPv4.toIPv4Address(migration_ip_address));
match.setNetworkDestination(IPv4.toIPv4Address(neighbor_ip_address));
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP|
OFMatch.OFPFW_NW_PROTO | OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_TP_SRC | OFMatch.OFPFW_TP_DST |
OFMatch.OFPFW_IN_PORT);
newDstMAC = neighbor_mac_address;
newDstIP = null;
newSrcIP = null;
outPort = neighbor_out_port;
result = installPathForFlow(sw.getId(),(short)0,match,(short)0,(long)0,newDstMAC,newDstIP,newSrcIP,(short)0, (short)0,outPort,(short)0, (short)0,(short)(DEFAULT_PRIORITY+5));
if(!result){
logger.LogError("failed to create default rule for LASSEN 2");
System.exit(1);
return false;
}
/* ip,nw_dst=10.1.1.21,actions=output:19 */
match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkDestination(IPv4.toIPv4Address(snooper_ip_address));
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP|
OFMatch.OFPFW_NW_SRC_ALL |
OFMatch.OFPFW_NW_PROTO | OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_TP_SRC | OFMatch.OFPFW_TP_DST |
OFMatch.OFPFW_IN_PORT);
newDstMAC = null;
newDstIP = null;
newSrcIP = null;
outPort = snooper_out_port;
result = installPathForFlow(sw.getId(),(short)0,match,(short)0,(long)0,newDstMAC,newDstIP,newSrcIP,(short)0, (short)0,outPort,(short)0, (short)0,DEFAULT_PRIORITY);
if(!result){
logger.LogDebug("failed to create default rule for LASSEN 3");
System.exit(1);
return false;
}
/* ip,nw_src=10.1.1.21,nw_dst=10.1.1.10,actions=output:6 */
match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkDestination(IPv4.toIPv4Address(migration_ip_address));
match.setNetworkSource(IPv4.toIPv4Address(snooper_ip_address));
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP|
OFMatch.OFPFW_NW_PROTO | OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_TP_SRC | OFMatch.OFPFW_TP_DST |
OFMatch.OFPFW_IN_PORT);
newDstMAC = null;
newDstIP = null;
newSrcIP = null;
outPort = migration_out_port;
result = installPathForFlow(sw.getId(),(short)0,match,(short)0,(long)0,newDstMAC,newDstIP,newSrcIP,(short)0, (short)0,outPort,(short)0, (short)0,DEFAULT_PRIORITY);
if(!result){
logger.LogError("failed to create default rule for LASSEN 4");
System.exit(1);
return false;
}
//tcp,nw_src=10.1.1.10,actions=output:9"
match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkSource(IPv4.toIPv4Address(migration_ip_address));
match.setNetworkProtocol((byte)0x06);
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP|
OFMatch.OFPFW_NW_DST_ALL| OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_TP_SRC | OFMatch.OFPFW_TP_DST |
OFMatch.OFPFW_IN_PORT);
newDstMAC = null;
newDstIP = null;
newSrcIP = null;
outPort = lassen_default_out_port;
result = installPathForFlow(sw.getId(),(short)0,match,(short)0,(long)0,newDstMAC,newDstIP,newSrcIP,(short)0, (short)0,outPort,(short)0, (short)0,DEFAULT_PRIORITY);
if(!result){
logger.LogError("failed to create default rule for LASSEN 5");
System.exit(1);
return false;
}
return result;
}
private boolean setForwardRulesFromLassenToHoneyPot(IOFSwitch sw, byte[] ip, byte[] mac, short outport){
OFMatch match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkDestination(IPv4.toIPv4Address(ip));
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP|
OFMatch.OFPFW_NW_SRC_ALL|
OFMatch.OFPFW_NW_PROTO | OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_TP_SRC | OFMatch.OFPFW_TP_DST |
OFMatch.OFPFW_IN_PORT);
byte[] newDstMAC = mac;
byte[] newDstIP = null;
byte[] newSrcIP = null;
short outPort = outport;
boolean result = installPathForFlow(sw.getId(),(short)0,match,(short)0,(long)0, newDstMAC, newDstIP,newSrcIP, (short)0, (short)0,outPort, (short)0, (short)0,DEFAULT_PRIORITY);
if(!result){
logger.LogError("Failed creating default rule from LASSEN to "+ip);
System.exit(1);
}
return true;
}
static public String bytesToHexString(byte[] contents){
StringBuilder hexcontents = new StringBuilder();
for (byte b:contents) {
hexcontents.append(String.format("%02X ", b));
}
return hexcontents.toString();
}
static public String shortToHexString(short content){
String str = Integer.toHexString(content & 0xffff);
return str;
}
static public String byteToHexString(byte content){
String str = Integer.toHexString(content & 0xff);
return str;
}
public boolean forwardPacket(IOFSwitch sw, OFPacketIn pktInMsg,
byte[] dstMAC, byte[] destIP, byte[] srcIP, short outSwPort)
{
OFPacketOut pktOut = new OFPacketOut();
pktOut.setInPort(pktInMsg.getInPort());
pktOut.setBufferId(pktInMsg.getBufferId());
List<OFAction> actions = new ArrayList<OFAction>();
int actionLen = 0;
if(dstMAC != null){
OFActionDataLayerDestination action_mod_dst_mac =
new OFActionDataLayerDestination(dstMAC);
actions.add(action_mod_dst_mac);
actionLen += OFActionDataLayerDestination.MINIMUM_LENGTH;
}
if(destIP != null){
OFActionNetworkLayerDestination action_mod_dst_ip =
new OFActionNetworkLayerDestination(IPv4.toIPv4Address(destIP));
actions.add(action_mod_dst_ip);
actionLen += OFActionNetworkLayerDestination.MINIMUM_LENGTH;
}
if(srcIP != null){
OFActionNetworkLayerSource action_mod_src_ip =
new OFActionNetworkLayerSource(IPv4.toIPv4Address(srcIP));
actions.add(action_mod_src_ip);
actionLen += OFActionNetworkLayerSource.MINIMUM_LENGTH;
}
OFActionOutput action_out_port;
actionLen += OFActionOutput.MINIMUM_LENGTH;
if(pktInMsg.getInPort() == outSwPort){
action_out_port = new OFActionOutput(OFPort.OFPP_IN_PORT.getValue());
}
else{
action_out_port = new OFActionOutput(outSwPort);
}
actions.add(action_out_port);
pktOut.setActions(actions);
pktOut.setActionsLength((short)actionLen);
// Set data if it is included in the packet in but buffer id is NONE
if (pktOut.getBufferId() == OFPacketOut.BUFFER_ID_NONE)
{
//System.err.println("debug BUFFER_ID_NONE");
byte[] packetData = pktInMsg.getPacketData();
pktOut.setLength((short)(OFPacketOut.MINIMUM_LENGTH
+ pktOut.getActionsLength() + packetData.length));
pktOut.setPacketData(packetData);
}//no buffer ID
else
{
//System.err.println("debug NOT BUFFER_ID_NONE");
pktOut.setLength((short)(OFPacketOut.MINIMUM_LENGTH
+ pktOut.getActionsLength()));
}
try
{
sw.write(pktOut, null);
sw.flush();
//logger.info("forwarded packet ");
}
catch (IOException e)
{
logger.LogError("failed forward packet");
return false;
}
return true;
}
public boolean forwardPacket2OtherNet(IOFSwitch sw, OFPacketIn pktInMsg,
byte[] dstMAC, byte[] dstIP, byte[] srcIP, short outSwPort, Ethernet eth, byte dscp, short id,
short newSrcPort, short newDstPort)
{
OFPacketOut pktOut = new OFPacketOut();
pktOut.setInPort(pktInMsg.getInPort());
pktOut.setBufferId(pktInMsg.getBufferId());
//System.err.println("forward new src: "+IPv4.fromIPv4Address(IPv4.toIPv4Address(srcIP)));
//System.err.println("forward new dst: "+IPv4.fromIPv4Address(IPv4.toIPv4Address(dstIP)));
List<OFAction> actions = new ArrayList<OFAction>();
int actionLen = 0;
if(dstMAC != null){
OFActionDataLayerDestination action_mod_dst_mac =
new OFActionDataLayerDestination(dstMAC);
actions.add(action_mod_dst_mac);
actionLen += OFActionDataLayerDestination.MINIMUM_LENGTH;
}
if(srcIP != null){
OFActionNetworkLayerSource action_mod_src_ip =
new OFActionNetworkLayerSource(IPv4.toIPv4Address(srcIP));
actions.add(action_mod_src_ip);
actionLen += OFActionNetworkLayerSource.MINIMUM_LENGTH;
}
if(dstIP != null){
OFActionNetworkLayerDestination action_mod_dst_ip =
new OFActionNetworkLayerDestination(IPv4.toIPv4Address(dstIP));
actions.add(action_mod_dst_ip);
actionLen += OFActionNetworkLayerDestination.MINIMUM_LENGTH;
}
if(newSrcPort != 0){
OFActionTransportLayerSource action_mod_src_tp =
new OFActionTransportLayerSource(newSrcPort);
actions.add(action_mod_src_tp);
actionLen += OFActionTransportLayerSource.MINIMUM_LENGTH;
}
if(newDstPort != 0){
OFActionTransportLayerDestination action_mod_dst_tp =
new OFActionTransportLayerDestination(newDstPort);
actions.add(action_mod_dst_tp);
actionLen += OFActionTransportLayerDestination.MINIMUM_LENGTH;
}
OFActionOutput action_out_port;
actionLen += OFActionOutput.MINIMUM_LENGTH;
if(pktInMsg.getInPort() == outSwPort){
action_out_port = new OFActionOutput(OFPort.OFPP_IN_PORT.getValue());
}
else{
action_out_port = new OFActionOutput(outSwPort);
}
actions.add(action_out_port);
pktOut.setActions(actions);
pktOut.setActionsLength((short)actionLen);
/*if (pktOut.getBufferId() == OFPacketOut.BUFFER_ID_NONE)
{
byte[] packetData = pktInMsg.getPacketData();
pktOut.setLength((short)(OFPacketOut.MINIMUM_LENGTH
+ pktOut.getActionsLength() + packetData.length));
pktOut.setPacketData(packetData);
}*/
// Set data if it is included in the packet in but buffer id is NONE
if (pktOut.getBufferId() == OFPacketOut.BUFFER_ID_NONE)
{
//System.err.println("debug BUFFER_ID_NONE");
byte[] packetData = pktInMsg.getPacketData();
pktOut.setLength((short)(OFPacketOut.MINIMUM_LENGTH
+ pktOut.getActionsLength() + packetData.length));
int packet_len = packetData.length;
int msg_len = pktInMsg.getLength();
IPacket pkt = eth.getPayload();
if(pkt instanceof IPv4){
IPv4 ip_pkt = (IPv4)pkt;
int ip_len = ip_pkt.getTotalLength();
int ip_header_len = (ip_pkt.getHeaderLength() & 0x000000ff) * 4;
//System.err.println("msglen:"+msg_len+" packetlen:"+packet_len+" iplen:"+ip_len+" ip headerlen:"+ip_header_len);
byte[] ip_pkt_data = Arrays.copyOfRange(packetData,
ChecksumCalc.ETHERNET_HEADER_LEN,ChecksumCalc.ETHERNET_HEADER_LEN + ip_len);
//byte ecn = (byte)((int)(ip_pkt_data[1])&0x03);
dscp = (byte)(dscp << 2);
ip_pkt_data[1] = (byte)((dscp)&0xff);
dscp = (byte)((int)(ip_pkt_data[1])>>>2);
//ecn = (byte)((int)(ip_pkt_data[1])&0x03);
ip_pkt_data[4] = (byte)((id>>>8) & 0xff);
ip_pkt_data[5] = (byte)(id & 0xff);
/*if(srcIP != null){
ip_pkt_data[12] = srcIP[0];
ip_pkt_data[13] = srcIP[1];
ip_pkt_data[14] = srcIP[2];
ip_pkt_data[15] = srcIP[3];
}
if(dstIP != null){
ip_pkt_data[16] = dstIP[0];
ip_pkt_data[17] = dstIP[1];
ip_pkt_data[18] = dstIP[2];
ip_pkt_data[19] = dstIP[3];
}*/
//System.err.println("NEW DSCP:"+byteToHexString(dscp)+" ID:"+shortToHexString(ecn));
if(ChecksumCalc.reCalcAndUpdateIPPacketChecksum(ip_pkt_data, ip_header_len)==false){
System.err.println("error calculating ip pkt checksum");
}
byte[] new_ether_data = new byte[packet_len];
for(int i=0; i<ChecksumCalc.ETHERNET_HEADER_LEN; i++)
new_ether_data[i] = packetData[i];
for(int i=ChecksumCalc.ETHERNET_HEADER_LEN,j=0;
i<packet_len;
i++,j++){
if(j < ip_len)
new_ether_data[i] = ip_pkt_data[j];
else
new_ether_data[i] = 0x00;
}
pktOut.setPacketData(new_ether_data);
}
else{
short eth_type = eth.getEtherType();
String eth_type_str = Integer.toHexString(eth_type & 0xffff);
//System.err.println("msglen:"+msg_len+" packetlen:"+packet_len+" iplen: no ipv4 pkt :"+eth_type_str);
pktOut.setPacketData(packetData);
}
}//no buffer ID
else
{
System.err.println("ERROR BUFFER ID IS NOT NONE");
pktOut.setLength((short)(OFPacketOut.MINIMUM_LENGTH
+ pktOut.getActionsLength()));
}
try
{
//System.err.println("wrote pktOut");
sw.write(pktOut, null);
sw.flush();
//logger.info("forwarded packet ");
}
catch (IOException e)
{
System.err.println("failed writing packet out:"+e);
logger.LogError("failed forward packet");
return false;
}
return true;
}
public boolean forwardPacket2OtherNet_(IOFSwitch sw, OFPacketIn pktInMsg,
byte[] dstMAC, byte[] destIP, byte[] srcIP, short outSwPort, Ethernet eth, byte dscp, short id,
short new_src_port, short new_dst_port)
{
OFPacketOut pktOut = new OFPacketOut();
pktOut.setInPort(pktInMsg.getInPort());
pktOut.setBufferId(pktInMsg.getBufferId());
List<OFAction> actions = new ArrayList<OFAction>();
int actionLen = 0;
if(dstMAC != null){
OFActionDataLayerDestination action_mod_dst_mac =
new OFActionDataLayerDestination(dstMAC);
actions.add(action_mod_dst_mac);
actionLen += OFActionDataLayerDestination.MINIMUM_LENGTH;
}
if(destIP != null){
OFActionNetworkLayerDestination action_mod_dst_ip =
new OFActionNetworkLayerDestination(IPv4.toIPv4Address(destIP));
actions.add(action_mod_dst_ip);
actionLen += OFActionNetworkLayerDestination.MINIMUM_LENGTH;
}
if(srcIP != null){
OFActionNetworkLayerSource action_mod_src_ip =
new OFActionNetworkLayerSource(IPv4.toIPv4Address(srcIP));
actions.add(action_mod_src_ip);
actionLen += OFActionNetworkLayerSource.MINIMUM_LENGTH;
}
OFActionOutput action_out_port;
actionLen += OFActionOutput.MINIMUM_LENGTH;
if(pktInMsg.getInPort() == outSwPort){
action_out_port = new OFActionOutput(OFPort.OFPP_IN_PORT.getValue());
}
else{
action_out_port = new OFActionOutput(outSwPort);
}
actions.add(action_out_port);
pktOut.setActions(actions);
pktOut.setActionsLength((short)actionLen);
// Set data if it is included in the packet in but buffer id is NONE
if (pktOut.getBufferId() == OFPacketOut.BUFFER_ID_NONE)
{
//System.err.println("debug BUFFER_ID_NONE");
byte[] packetData = pktInMsg.getPacketData();
pktOut.setLength((short)(OFPacketOut.MINIMUM_LENGTH
+ pktOut.getActionsLength() + packetData.length));
int packet_len = packetData.length;
int msg_len = pktInMsg.getLength();
IPacket pkt = eth.getPayload();
if(pkt instanceof IPv4){
IPv4 ip_pkt = (IPv4)pkt;
int ip_len = ip_pkt.getTotalLength();
int ip_header_len = (ip_pkt.getHeaderLength() & 0x000000ff) * 4;
short payload_len = (short)(ip_len - ip_header_len);
int src_ip = ip_pkt.getSourceAddress();
int dst_ip = ip_pkt.getDestinationAddress();
//System.err.println("msglen:"+msg_len+" packetlen:"+packet_len+" iplen:"+ip_len+" ip headerlen:"+ip_header_len);
byte[] ip_pkt_data = Arrays.copyOfRange(packetData,
ChecksumCalc.ETHERNET_HEADER_LEN,ChecksumCalc.ETHERNET_HEADER_LEN + ip_len);
byte[] new_tp_data = null;
if((new_src_port!=0) || (new_dst_port!=0)){
IPacket tp_pkt = ip_pkt.getPayload();
if(tp_pkt instanceof TCP){
//System.err.println(" Modify TCP");
TCP tcp = (TCP)tp_pkt;
if(new_src_port != 0)
tcp.setSourcePort(new_src_port);
if(new_dst_port != 0)
tcp.setDestinationPort(new_dst_port);
tcp.resetChecksum();
new_tp_data = tcp.serialize();
}
else if(tp_pkt instanceof UDP){
//System.err.println(" UDP original checksum:");
UDP udp = (UDP)tp_pkt;
if(new_src_port != 0)
udp.setSourcePort(new_src_port);
if(new_dst_port != 0)
udp.setDestinationPort(new_dst_port);
udp.resetChecksum();
new_tp_data = udp.serialize();
}
else{
System.err.println(" unknown IP packet. Ignore...");
return false;
}
}
/* Modify DSCP */
byte ecn = (byte)((int)(ip_pkt_data[1])&0x03);
dscp = (byte)(dscp << 2);
ip_pkt_data[1] = (byte)((dscp|ecn)&0xff);
dscp = (byte)((int)(ip_pkt_data[1])>>>2);
ecn = (byte)((int)(ip_pkt_data[1])&0x03);
/* Modify ID */
ip_pkt_data[4] = (byte)((id>>>8) & 0xff);
ip_pkt_data[5] = (byte)(id & 0xff);
//System.err.println("NEW DSCP:"+byteToHexString(dscp)+" ID:"+shortToHexString(ecn));
if(ChecksumCalc.reCalcAndUpdateIPPacketChecksum(ip_pkt_data, ip_header_len)==false){
System.err.println("error calculating ip pkt checksum");
}
/* install Ethernet header */
byte[] new_ether_data = new byte[packet_len];
for(int i=0; i<ChecksumCalc.ETHERNET_HEADER_LEN; i++)
new_ether_data[i] = packetData[i];
if(new_tp_data != null){
for(int i=ChecksumCalc.ETHERNET_HEADER_LEN,j=0;
i<ChecksumCalc.ETHERNET_HEADER_LEN+ip_header_len;
i++,j++){
new_ether_data[i] = ip_pkt_data[j];
}
for(int i=ChecksumCalc.ETHERNET_HEADER_LEN+ip_header_len,j=0;i<packet_len; i++,j++){
if(j < new_tp_data.length)
new_ether_data[i] = new_tp_data[j];
else
new_ether_data[i] = 0x00;
}
}
else{
for(int i=ChecksumCalc.ETHERNET_HEADER_LEN,j=0;
i<packet_len;
i++,j++){
if(j < ip_len)
new_ether_data[i] = ip_pkt_data[j];
else
new_ether_data[i] = 0x00;
}
}
pktOut.setPacketData(new_ether_data);
}
else{
short eth_type = eth.getEtherType();
String eth_type_str = Integer.toHexString(eth_type & 0xffff);
//System.err.println("msglen:"+msg_len+" packetlen:"+packet_len+" iplen: no ipv4 pkt :"+eth_type_str);
pktOut.setPacketData(packetData);
}
}//no buffer ID
else
{
System.err.println("ERROR BUFFER ID IS NOT NONE");
pktOut.setLength((short)(OFPacketOut.MINIMUM_LENGTH
+ pktOut.getActionsLength()));
}
try
{
sw.write(pktOut, null);
sw.flush();
//logger.info("forwarded packet ");
}
catch (IOException e)
{
logger.LogError("failed forward packet");
return false;
}
return true;
}
private boolean installPathForFlow(long swID,short inPort,OFMatch match,
short flowFlag, long flowCookie,
byte[] newDstMAC, byte[] newDstIP, byte[] newSrcIP,
short srcPort, short dstPort,
short outPort,
short idleTimeout, short hardTimeout,short priority) {
IOFSwitch sw = floodlightProvider.getSwitch(swID);
if(sw == null){
logger.LogError("deleteFlows fail getting switch [installPathForFlow]");
return false;
}
OFFlowMod rule = new OFFlowMod();
if (flowFlag != (short) 0) {
rule.setFlags(flowFlag);
}
if (flowCookie != (long) 0)
rule.setCookie(flowCookie);
rule.setHardTimeout(hardTimeout);
rule.setIdleTimeout(idleTimeout);
rule.setPriority(priority);
rule.setCommand(OFFlowMod.OFPFC_MODIFY_STRICT);
rule.setBufferId(OFPacketOut.BUFFER_ID_NONE);
rule.setMatch(match.clone());
//OFActionTransportLayerSource action_mod_tp_src = new OFActionTransportLayerSource();
List<OFAction> actions = new ArrayList<OFAction>();
int actionLen = 0;
if (newDstMAC != null) {
OFActionDataLayerDestination action_mod_dst_mac = new OFActionDataLayerDestination(
newDstMAC);
actions.add(action_mod_dst_mac);
actionLen += OFActionDataLayerDestination.MINIMUM_LENGTH;
}
if (newDstIP != null) {
OFActionNetworkLayerDestination action_mod_dst_ip = new OFActionNetworkLayerDestination(
IPv4.toIPv4Address(newDstIP));
actions.add(action_mod_dst_ip);
actionLen += OFActionNetworkLayerDestination.MINIMUM_LENGTH;
}
if (newSrcIP != null) {
OFActionNetworkLayerSource action_mod_src_ip = new OFActionNetworkLayerSource(
IPv4.toIPv4Address(newSrcIP));
actions.add(action_mod_src_ip);
actionLen += OFActionNetworkLayerSource.MINIMUM_LENGTH;
}
if(srcPort != 0){
OFActionTransportLayerSource action_mod_tp_src = new OFActionTransportLayerSource(srcPort);
actions.add(action_mod_tp_src);
actionLen += OFActionTransportLayerSource.MINIMUM_LENGTH;
}
if(dstPort != 0){
OFActionTransportLayerDestination action_mod_tp_dst = new OFActionTransportLayerDestination(dstPort);
actions.add(action_mod_tp_dst);
actionLen += OFActionTransportLayerDestination.MINIMUM_LENGTH;
}
OFActionOutput action_out_port;
actionLen += OFActionOutput.MINIMUM_LENGTH;
if (outPort == inPort) {
action_out_port = new OFActionOutput(OFPort.OFPP_IN_PORT.getValue());
} else {
action_out_port = new OFActionOutput(outPort);
}
actions.add(action_out_port);
rule.setActions(actions);
rule.setLength((short) (OFFlowMod.MINIMUM_LENGTH + actionLen));
//System.err.println("done installing rule:"+rule);
try {
sw.write(rule, null);
sw.flush();
} catch (IOException e) {
logger.LogError("fail to install rule: " + rule);
return false;
}
return true;
}
private void clearMaps(){
if(connToPot.size()>= CONN_MAX_SIZE){
connToPot = new Hashtable<String,Connection>();
long currTime = System.currentTimeMillis();
currTime -= lastClearConnToPotTime;
logger.LogError("Clear connToPot after "+currTime/1000+" seconds");
lastClearConnToPotTime = System.currentTimeMillis();
}
if(connMap.size() >= CONN_MAX_SIZE){
connMap = new Hashtable<Long, Connection>();
long currTime = System.currentTimeMillis();
currTime -= lastClearConnMapTime;
logger.LogError("Clear connMap after "+currTime/1000+" seconds");
lastClearConnMapTime = System.currentTimeMillis();
}
}
private void forceClearMaps(){
connToPot = new Hashtable<String,Connection>();
long currTime = System.currentTimeMillis();
currTime -= lastClearConnToPotTime;
logger.LogError("Clear connToPot after "+currTime/1000+" seconds");
lastClearConnToPotTime = System.currentTimeMillis();
connMap = new Hashtable<Long, Connection>();
currTime = System.currentTimeMillis();
currTime -= lastClearConnMapTime;
logger.LogError("Clear connMap after "+currTime/1000+" seconds");
lastClearConnMapTime = System.currentTimeMillis();
System.gc();
}
private boolean installDropRule(long swID, OFMatch match,short idleTimeout, short hardTimeout, short priority){
IOFSwitch sw = floodlightProvider.getSwitch(swID);
if(sw == null){
logger.LogError("deleteFlows fail getting switch [installDropRule]");
return false;
}
OFFlowMod rule = new OFFlowMod();
rule.setHardTimeout(hardTimeout);
rule.setIdleTimeout(idleTimeout);
rule.setPriority(priority);
rule.setCommand(OFFlowMod.OFPFC_ADD);
rule.setBufferId(OFPacketOut.BUFFER_ID_NONE);
rule.setMatch(match.clone());
/* Empty action list means drop! */
List<OFAction> actions = new ArrayList<OFAction>();
rule.setActions(actions);
rule.setLength((short)(OFFlowMod.MINIMUM_LENGTH));
try
{
sw.write(rule, null);
sw.flush();
logger.LogDebug("succ installed drop rule: "+rule);
}
catch (IOException e)
{
logger.LogError("fail installing rule: "+rule);
return false;
}
return true;
}
private boolean deleteFlowsForHoneypot(String honeypotName){
if(!(honeypots.containsKey(honeypotName)) ){
logger.LogError("fail finding honeypot "+honeypotName);
return false;
}
short outPort = honeypots.get(honeypotName).getOutPort();
long swID = 0;
try{
swID = switches.get(honeypots.get(honeypotName).getSwName());
}
catch(Exception e){
logger.LogError("switches"+e);
return false;
}
IOFSwitch sw = floodlightProvider.getSwitch(swID);
if(sw == null){
logger.LogError("fail getting switch deleteFlowsForHoneypot");
return false;
}
OFFlowMod ruleIncoming = new OFFlowMod();
ruleIncoming.setOutPort(outPort);
ruleIncoming.setCommand(OFFlowMod.OFPFC_DELETE);
ruleIncoming.setBufferId(OFPacketOut.BUFFER_ID_NONE);
OFMatch match = new OFMatch();
match.setWildcards(~0);
ruleIncoming.setMatch(match.clone());
OFFlowMod ruleOutgoing = new OFFlowMod();
ruleOutgoing.setOutPort(OFPort.OFPP_NONE);
ruleOutgoing.setCommand(OFFlowMod.OFPFC_DELETE);
ruleOutgoing.setBufferId(OFPacketOut.BUFFER_ID_NONE);
match = new OFMatch();
match.setInputPort(outPort);
match.setWildcards(~(OFMatch.OFPFW_IN_PORT));
ruleOutgoing.setMatch(match.clone());
try{
sw.write(ruleIncoming, null);
sw.write(ruleOutgoing, null);
sw.flush();
}
catch (IOException e){
logger.LogError("fail delete flows for: "+honeypotName+" "+ruleIncoming+" "+ruleOutgoing);
return false;
}
return true;
}
private boolean deleteFlows(OFMatch match, long swID){
IOFSwitch sw = floodlightProvider.getSwitch(swID);
if(sw == null){
logger.LogError("deleteFlows fail getting switch ");
return false;
}
OFFlowMod rule = new OFFlowMod();
rule.setOutPort(OFPort.OFPP_NONE);
rule.setCommand(OFFlowMod.OFPFC_DELETE);
rule.setBufferId(OFPacketOut.BUFFER_ID_NONE);
rule.setMatch(match.clone());
try{
sw.write(rule, null);
sw.flush();
logger.LogDebug("succ delete flow "+rule);
}
catch (IOException e)
{
logger.LogError("fail delete flows for: "+rule);
return false;
}
return true;
}
@Override
public Collection<Class<? extends IFloodlightService>> getModuleServices() {
Collection<Class<? extends IFloodlightService>> l = new ArrayList<Class<? extends IFloodlightService>>();
l.add(IConnMonitorService.class);
return l;
}
@Override
public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() {
Map<Class<? extends IFloodlightService>, IFloodlightService> m = new HashMap<Class<? extends IFloodlightService>, IFloodlightService>();
m.put(IConnMonitorService.class, this);
return m;
}
@Override
public Collection<Class<? extends IFloodlightService>> getModuleDependencies() {
Collection<Class<? extends IFloodlightService>> l = new ArrayList<Class<? extends IFloodlightService>>();
l.add(IFloodlightProviderService.class);
l.add(IRestApiService.class);
return l;
}
@Override
public void init(FloodlightModuleContext context)
throws FloodlightModuleException {
floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class);
restApi = context.getServiceImpl(IRestApiService.class);
connMap = new Hashtable<Long,Connection>();
honeypots = new Hashtable<String, HoneyPot>();
ports = new Hashtable<Short, Vector<HoneyPot>>();
portsForHIH = new Hashtable<Short, Vector<HoneyPot>>();
connToPot = new Hashtable<String,Connection>();
HIHAvailabilityMap = new Hashtable<String,Boolean>();
HIHClientMap = new Hashtable<String, HashSet<Integer> >();
HIHNameMap = new Hashtable<Long, String>();
HIHFlowCount = new Hashtable<String, Integer>();
forwardFlowTable = new ForwardFlowTable();
flowRemovedTasks = new ConcurrentLinkedQueue<ForwardFlowItem>();
flowRemovedDoneTasks = new ConcurrentLinkedQueue<ForwardFlowItem>();
executor = Executors.newFixedThreadPool(1);
nwMsgSender = new FlowRemoveMsgSender(flowRemovedTasks,flowRemovedDoneTasks,"http://129.105.44.107:8899/wm/connmonitor/inform/json");
logger = new MyLogger();
/* Init Switches */
switches = new Hashtable<String,Long>();
switches.put("lassen", LASSEN_SW);
switches.put("missouri",MISSOURI_SW);
/* Init Honeypots */
initHoneypots();
//initPorts();
/* Init other honeynet */
Honeynet.putHoneynet("nw", IPv4.toIPv4Address("129.105.44.107"), IPv4.toIPv4Address("130.107.240.0"), 20, nwMsgSender);
Honeynet.putHoneynet("ec2", IPv4.toIPv4Address("54.213.197.234"), IPv4.toIPv4Address("130.107.224.0"), 20, null);
/* Start nwMsgSender */
nwMsgSender.start();
lastClearConnMapTime = System.currentTimeMillis();
lastClearConnToPotTime = System.currentTimeMillis();
lastTime = System.currentTimeMillis();
droppedCounter = 0;
packetCounter = 1;
//honeypot_config_path
// IPv4Netmask mask1 = new IPv4Netmask("130.107.128.0/17");
// System.err.println(mask1);
// System.err.println("130.107.146.172 : 130.107.128.0/17 "+mask1.inSubnet(IPv4.toIPv4Address("130.107.146.172")));
//System.err.println("192.1.3.4: 128.0.0.0/5 "+mask1.inSubnet("192.1.3.4"));
// IPv4Netmask mask2 = new IPv4Netmask("0.0.0.0/0");
// System.err.println("130.107.248.128: 0.0.0.0/0 "+mask2.inSubnet(IPv4.toIPv4Address("130.107.248.128")));
/* IPv4Netmask mask2 = new IPv4Netmask("128.0.0.0/10");
System.err.println("128.32.3.4: 128.0.0.0/10 "+mask2.inSubnet("128.32.3.4"));
System.err.println("192.1.3.4: 128.0.0.0/10 "+mask2.inSubnet("192.1.3.4"));
System.err.println("128.64.3.4: 128.0.0.0/10 "+mask2.inSubnet("128.64.3.4"));
IPv4Netmask mask3 = new IPv4Netmask("128.122.160.0/20");
System.err.println("128.122.168.227: 128.122.32.0/10 "+mask3.inSubnet("128.122.168.227"));
System.err.println("128.122.158.227: 128.122.32.0/10 "+mask3.inSubnet("128.122.158.227"));
System.err.println("128.120.160.227: 128.122.32.0/10 "+mask3.inSubnet("128.120.160.227"));
IPv4Netmask mask4 = new IPv4Netmask("128.122.160.192/28");
System.err.println("128.122.160.200: 128.122.32.0/10 "+mask4.inSubnet("128.122.160.200"));
System.err.println("128.122.161.200: 128.122.32.0/10 "+mask4.inSubnet("128.122.161.200"));
System.err.println("128.122.160.224: 128.122.32.0/10 "+mask4.inSubnet("128.122.160.224"));
*/
}
@Override
public void startUp(FloodlightModuleContext context)
throws FloodlightModuleException {
floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this);
floodlightProvider.addOFMessageListener(OFType.FLOW_REMOVED, this);
floodlightProvider.addOFSwitchListener(this);
restApi.addRestletRoutable(new ConnMonitorWebRoutable());
}
@Override
public net.floodlightcontroller.core.IListener.Command processPacketInMessage(
IOFSwitch sw, OFPacketIn pi, IRoutingDecision decision,
FloodlightContext cntx) {
return null;
}
@Override
public void switchAdded(long switchId) {
logger.LogDebug("switch added");
if(switchId == LASSEN_SW){
logger.LogError("LASSEN switch gets added");
}
else if(switchId == MISSOURI_SW){
logger.LogDebug("MISSOURI switch gets added");
}
else{
logger.LogDebug("Unknown switch gets added "+switchId);
}
}
@Override
public void switchRemoved(long switchId) {
if(switchId == LASSEN_SW || switchId==MISSOURI_SW){
logger.LogDebug("Importatnt switch gets removed "+switchId);
}
}
@Override
public void switchActivated(long switchId) {
if(switchId == LASSEN_SW){
logger.LogDebug("LASSEN switch gets activated");
initLassenSwitch(switchId);
}
else if(switchId == MISSOURI_SW){
logger.LogDebug("MISSOURI switch gets activated");
initMissouriSwitch(switchId);
}
else{
logger.LogError("Unknown switch gets activated "+switchId);
}
}
@Override
public void switchPortChanged(long switchId, ImmutablePort port,
PortChangeType type) {
if(switchId == LASSEN_SW || switchId==MISSOURI_SW){
}
}
@Override
public void switchChanged(long switchId) {
if(switchId == LASSEN_SW || switchId==MISSOURI_SW){
}
}
private void initHoneypots(){
BufferedReader br = null;
try {
InputStream ins = this.getClass().getClassLoader().getResourceAsStream(honeypotConfigFileName);
br = new BufferedReader(new InputStreamReader(ins));
String line = null;
byte[] mac = new byte[6];
/* id name ip mac out_port down_ip type switch */
while ((line = br.readLine()) != null) {
logger.LogInfo(line);
if(line.startsWith("
continue;
String[] elems = line.split("\t");
int len = elems.length;
int id = Integer.parseInt(elems[0]);
String name = elems[1].trim();
byte[] ip = IPv4.toIPv4AddressBytes(elems[2]);
String[] rawMAC = elems[3].split(":");
for(int i=0; i<6; i++)
mac[i] = (byte)Integer.parseInt(rawMAC[i],16);
short outPort = (short)Integer.parseInt(elems[4]);
byte[] downIP = IPv4.toIPv4AddressBytes(elems[5]);
byte type = HoneyPot.LOW_INTERACTION;
if(elems[6].trim().equals("H") ){
type = HoneyPot.HIGH_INTERACTION;
}
String swName = elems[7].trim().toLowerCase();
honeypots.put(name, new HoneyPot(name,id,ip,mac,downIP,outPort,type,swName));
if(type == HoneyPot.HIGH_INTERACTION){
HIHAvailabilityMap.put(name, false);
HIHNameMap.put((long)id, name);
HIHFlowCount.put(name,0);
}
}
ins.close();
ins = this.getClass().getClassLoader().getResourceAsStream(PortsConfigFileName);
br = new BufferedReader(new InputStreamReader(ins));
/* Port Name Netmask */
while ((line = br.readLine()) != null) {
if(line.startsWith("#") || line.trim().length()==0)
continue;
String[] elems = line.split("\t");
short port = (short)Integer.parseInt(elems[0]);
String name = elems[1].trim();
IPv4Netmask mask = new IPv4Netmask(elems[2]);
HoneyPot pot = honeypots.get(name);
if(pot == null){
logger.LogError("can't find pot:"+name);
continue;
}
pot.getMask().put(port, mask);
if(ports.containsKey(port)){
Vector<HoneyPot> pots = ports.get(port);
pots.add(pot);
ports.put(port, pots);
}
else{
System.err.println("debug:"+port+" "+pot.getName());
Vector<HoneyPot> pots = new Vector<HoneyPot>();
pots.add(pot);
ports.put(port, pots);
}
if(pot.getType()==HoneyPot.HIGH_INTERACTION){
if(portsForHIH.containsKey(port)){
Vector<HoneyPot> pots = portsForHIH.get(port);
pots.add(pot);
portsForHIH.put((short)port, pots);
}
else{
Vector<HoneyPot> pots = new Vector<HoneyPot>();
pots.add(pot);
portsForHIH.put((short)port, pots);
}
logger.LogInfo("HIH "+name+" for port:"+port+" mask:"+elems[2]);
}
else{
logger.LogInfo("LIH "+name+" for port:"+port+" mask:"+elems[2]);
}
}
Iterator<Map.Entry<Short, Vector<HoneyPot>>> it = ports.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Short, Vector<HoneyPot>> entry = it.next();
Vector<HoneyPot> pots = ports.get(entry.getKey());
for(HoneyPot pot : pots){
System.err.println("test:"+entry.getKey()+" : "+pot.getName());
}
}
}catch(Exception e){
logger.LogError("failed to read honeypot_config_path");
e.printStackTrace();
}
}
/*private void initPorts(){
ports.put((short)443, "dionaea");
//ports.put((short)445, "dionaea");
ports.put((short)5060, "dionaea");
ports.put((short)5061, "dionaea");
ports.put((short)20, "dionaea");
ports.put((short)21, "dionaea");
ports.put((short)42, "dionaea");
ports.put((short)1433, "dionaea");
ports.put((short)3306, "dionaea");
ports.put((short)22, "kippo");
ports.put((short)3389, "kippo");
ports.put((short)5900, "kippo");
ports.put((short)4689, "kippo");
ports.put((short)135, "dionaea_honeyd");
ports.put((short)139, "dionaea_honeyd");
ports.put((short)445, "dionaea_honeyd");
ports.put((short)446, "dionaea_honeyd");
ports.put((short)80, "honeyd");
ports.put((short)8080, "kippo_honeyd");
ports.put((short)8081, "kippo_honeyd");
ports.put((short)4444, "honeyd");
ports.put((short)5554, "honeyd");
ports.put((short)9996, "honeyd");
ports.put((short)8967, "honeyd");
ports.put((short)9898, "honeyd");
ports.put((short)20168, "honeyd");
ports.put((short)1080, "honeyd");
ports.put((short)3127, "honeyd");
ports.put((short)3128, "honeyd");
ports.put((short)10080, "honeyd");
ports.put((short)110, "honeyd");
ports.put((short)25, "honeyd");
ports.put((short)23, "honeyd");
ports.put((short)6129, "honeyd");
ports.put((short)1433, "honeyd");
ports.put((short)3306, "honeyd");
ports.put((short)4899, "kippo_high");
}
*/
@Override
public boolean ReceiveInterestingSrcMsg(String content) {
logger.LogInfo("TODO: received information: "+content);
return false;
}
@Override
public boolean ReceiveHIHStatus(String pot_name, String status){
if(status.equals("live")){
if(HIHAvailabilityMap.containsKey(pot_name)){
logger.LogDebug("debug: "+pot_name+" is "+status);
HIHAvailabilityMap.put(pot_name, true);
return true;
}
else{
logger.LogDebug("debug: "+pot_name+" is not valid pot");
return false;
}
}
else if(status.equals("dead")){
if(HIHAvailabilityMap.containsKey(pot_name)){
logger.LogDebug("debug: "+pot_name+" is "+status);
HIHAvailabilityMap.put(pot_name, false);
HIHClientMap.put(pot_name, new HashSet<Integer>());
HIHFlowCount.put(pot_name, 0);
logger.LogDebug("delete all flows toward "+pot_name);
deleteFlowsForHoneypot(pot_name);
return true;
}
else{
logger.LogDebug("debug: "+pot_name+" is not valid pot");
return false;
}
}
else if(status.equals("none")){
logger.LogError(pot_name+ "does not exist");
if(HIHAvailabilityMap.containsKey(pot_name)){
HIHAvailabilityMap.remove(pot_name);
deleteFlowsForHoneypot(pot_name);
}
return false;
}
else{
logger.LogError("error: invalid status: "+status);
return false;
}
}
@Override
public List<Connection> getConnections() {
return null;
}
private boolean SendUDPData(String data,String dstIP, short dstPort){
try{
DatagramSocket socket = new DatagramSocket();
byte[] buf = new byte[256];
buf = data.getBytes();
InetAddress dst = InetAddress.getByName(dstIP);
DatagramPacket packet = new DatagramPacket(buf, buf.length, dst, dstPort);
socket.send(packet);
socket.close();
}
catch(Exception e){
logger.LogError("error sending udp: "+e+" "+data);
return false;
}
logger.LogDebug("Sent out data "+data);
return true;
}
/* This function is only for demonstration */
@Override
public boolean WhetherMigrate(String src_ip, String src_port,
String lih_ip,String dst_port) {
String hih_ip = "10.1.1.2";
String migration_engine_ip = "10.1.1.10";
logger.LogInfo("Received migration permission request message from LIH:"+lih_ip+": "+src_ip+":"+src_port+" => "+lih_ip+":"+dst_port);
if(src_ip.equals("129.105.44.99")){
}
else{
logger.LogInfo("Migration denied for client 129.105.44.60 (POLICY)");
logger.LogInfo("Replying to LIH’s migration permission inquiry: Don't Migrate");
return false;
}
logger.LogInfo("Looking up HIH table for available HIH with service on port "+dst_port);
IOFSwitch sw = floodlightProvider.getSwitch(MISSOURI_SW);
Long key = Connection.getConnectionSimplifiedKey(src_ip,lih_ip);
Connection conn = null;
if(!(connMap.containsKey(key))){
logger.LogInfo("Refuse migration: no such connections");
return false;
}
else{
conn = connMap.get(key);
}
String public_dst_ip = IPv4.fromIPv4Address(conn.dstIP);
String flow1 = src_ip+":"+src_port +"=>"+public_dst_ip+":"+dst_port;
String flow2 = lih_ip+":"+dst_port +"=>"+src_ip+":"+src_port;
String flow3 = migration_engine_ip+" (MigrationEngine):"+dst_port +"=>"+src_ip+":"+src_port;
logger.LogInfo("Looking up connection table for the session’s original destination IP: "+IPv4.fromIPv4Address(conn.dstIP));
logger.LogInfo("Starting flow migration: "+flow1);
logger.LogInfo("Deleting existing flow rules for flows:");
logger.LogInfo("\t"+flow1);
logger.LogInfo("\t"+flow2);
logger.LogInfo("Adding new flow rules for flows:");
logger.LogInfo("\t"+flow1);
logger.LogInfo("\t"+flow3);
logger.LogInfo("Sending message to MigrationEngine to migrate:");
logger.LogInfo("\tFlow:"+flow1);
logger.LogInfo("\tOriginal LIH:"+lih_ip);
logger.LogInfo("\tNew HIH:"+hih_ip);
int dst_ip = conn.dstIP;
//delete e2i
OFMatch match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkSource(IPv4.toIPv4Address(src_ip));
match.setNetworkDestination(dst_ip);
match.setTransportSource((short)(Integer.parseInt(src_port)));
match.setTransportDestination((short)(Integer.parseInt(dst_port)));
match.setInputPort(missouri_default_out_port);
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP|
OFMatch.OFPFW_NW_PROTO | OFMatch.OFPFW_NW_TOS );
deleteFlows(match,MISSOURI_SW);
//delete i2e
match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkDestination(IPv4.toIPv4Address(src_ip));
match.setTransportSource((short)(Integer.parseInt(dst_port)));
match.setTransportDestination((short)(Integer.parseInt(src_port)));
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP|
OFMatch.OFPFW_NW_SRC_ALL |
OFMatch.OFPFW_NW_PROTO | OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_IN_PORT);
deleteFlows(match,MISSOURI_SW);
//drop i2e
match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkDestination(IPv4.toIPv4Address(src_ip));
match.setNetworkSource(IPv4.toIPv4Address("192.168.1.6"));
match.setTransportSource((short)(Integer.parseInt(dst_port)));
match.setTransportDestination((short)(Integer.parseInt(src_port)));
match.setNetworkProtocol((byte)0x06);
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP|
OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_IN_PORT);
installDropRule(sw.getId(),match,IDLE_TIMEOUT,HARD_TIMEOUT,DROP_PRIORITY);
//new e2i
short outPort = missouri_default_out_port;
short inPort = missouri_default_out_port;
match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkSource(IPv4.toIPv4Address(src_ip));
match.setNetworkDestination(dst_ip);
match.setTransportSource((short)(Integer.parseInt(src_port)));
match.setTransportDestination((short)(Integer.parseInt(dst_port)));
match.setNetworkProtocol((byte)0x06);
//match.setInputPort(migration_mac_address);
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP|
OFMatch.OFPFW_IN_PORT);
byte[] newDstMac = migration_mac_address;
byte[] newDstIP = migration_ip_address;
boolean result1 = installPathForFlow(sw.getId(), inPort,
match,(short)0,(long)0,
newDstMac,newDstIP,null,(short)0, (short)0,outPort,IDLE_TIMEOUT,HARD_TIMEOUT,HIGH_PRIORITY);
//new i2e
match = new OFMatch();
match.setDataLayerType((short)0x0800);
match.setNetworkDestination(IPv4.toIPv4Address(src_ip));
match.setNetworkSource(IPv4.toIPv4Address(migration_ip_address));
match.setTransportSource((short)(Integer.parseInt(dst_port)));
match.setTransportDestination((short)(Integer.parseInt(src_port)));
match.setNetworkProtocol((byte)0x06);
match.setWildcards(
OFMatch.OFPFW_DL_DST | OFMatch.OFPFW_DL_SRC |
OFMatch.OFPFW_NW_TOS |
OFMatch.OFPFW_DL_VLAN |OFMatch.OFPFW_DL_VLAN_PCP|
OFMatch.OFPFW_IN_PORT);
newDstMac = nc_mac_address;
newDstIP= null;
byte[] newSrcIP = IPv4.toIPv4AddressBytes(dst_ip);
boolean result2 = installPathForFlow(sw.getId(), inPort,
match,(short)0,(long)0,
newDstMac,null,newSrcIP,(short)0, (short)0,outPort,IDLE_TIMEOUT,HARD_TIMEOUT,HIGH_PRIORITY);
boolean result = result1 & result2;
boolean rs = false;
if(result){
rs = SendUDPData(src_ip+":"+src_port+":"+public_dst_ip+":"+dst_port+":"+lih_ip+":"+hih_ip+":",migrationEngineIP, migrationEngineListenPort);
}
else{
logger.LogError("Fail setting rules WhetherMigrate");
}
logger.LogInfo("Replying to LIH’s migration permission inquiry: Do Migrate");
return rs;
}
}
|
package net.openhft.chronicle.map;
import net.openhft.chronicle.algo.bitset.*;
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.core.Maths;
import net.openhft.chronicle.hash.VanillaGlobalMutableState;
import net.openhft.chronicle.hash.impl.TierCountersArea;
import net.openhft.chronicle.hash.impl.VanillaChronicleHash;
import net.openhft.chronicle.hash.impl.stage.hash.ChainingInterface;
import net.openhft.chronicle.hash.replication.AbstractReplication;
import net.openhft.chronicle.hash.replication.ReplicableEntry;
import net.openhft.chronicle.hash.replication.TimeProvider;
import net.openhft.chronicle.map.impl.CompiledReplicatedMapIterationContext;
import net.openhft.chronicle.map.impl.CompiledReplicatedMapQueryContext;
import net.openhft.chronicle.map.replication.MapRemoteOperations;
import net.openhft.chronicle.values.Values;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReferenceArray;
import static net.openhft.chronicle.algo.MemoryUnit.*;
import static net.openhft.chronicle.algo.bitset.BitSetFrame.NOT_FOUND;
import static net.openhft.chronicle.algo.bytes.Access.checkedBytesStoreAccess;
import static net.openhft.chronicle.algo.bytes.Access.nativeAccess;
public class ReplicatedChronicleMap<K, V, R> extends VanillaChronicleMap<K, V, R>
implements Replica, Replica.EntryExternalizable {
// for file, jdbc and UDP replication
public static final int RESERVED_MOD_ITER = 8;
public static final int ADDITIONAL_ENTRY_BYTES = 10;
private static final long serialVersionUID = 0L;
private static final Logger LOG = LoggerFactory.getLogger(ReplicatedChronicleMap.class);
private static final long LAST_UPDATED_HEADER_SIZE = 128L * 8L;
private static final int SIZE_OF_BOOTSTRAP_TIME_STAMP = 8;
public transient TimeProvider timeProvider;
/**
* Default value is 0, that corresponds to "unset" identifier value (valid ids are positive)
*/
private transient byte localIdentifier;
transient Set<Closeable> closeables;
private transient long identifierUpdatedBytesOffset;
private transient BitSet modIterSet;
private transient AtomicReferenceArray<ModificationIterator> modificationIterators;
private transient long startOfModificationIterators;
private transient boolean bootstrapOnlyLocalEntries;
public transient long cleanupTimeout;
public transient TimeUnit cleanupTimeoutUnit;
public transient MapRemoteOperations<K, V, R> remoteOperations;
transient CompiledReplicatedMapQueryContext<K, V, R> remoteOpContext;
transient CompiledReplicatedMapIterationContext<K, V, R> remoteItContext;
transient BitSetFrame mainSegmentsModIterFrameForUpdates;
transient BitSetFrame mainSegmentsModIterFrameForIteration;
transient BitSetFrame tierBulkModIterFrameForUpdates;
transient BitSetFrame tierBulkModIterFrameForIteration;
public ReplicatedChronicleMap(@NotNull ChronicleMapBuilder<K, V> builder,
AbstractReplication replication)
throws IOException {
super(builder);
initTransientsFromReplication(replication);
}
@Override
protected VanillaGlobalMutableState createGlobalMutableState() {
return Values.newNativeReference(ReplicatedGlobalMutableState.class);
}
@Override
protected ReplicatedGlobalMutableState globalMutableState() {
return (ReplicatedGlobalMutableState) super.globalMutableState();
}
private int assignedModIterBitSetSizeInBytes() {
return (int) CACHE_LINES.align(BYTES.alignAndConvert(127 + RESERVED_MOD_ITER, BITS), BYTES);
}
@Override
public void initTransients() {
super.initTransients();
initOwnTransients();
}
private void initOwnTransients() {
modificationIterators =
new AtomicReferenceArray<>(127 + RESERVED_MOD_ITER);
closeables = new CopyOnWriteArraySet<>();
long mainSegmentsBitSetSize = BYTES.toBits(modIterBitSetSizeInBytes());
mainSegmentsModIterFrameForUpdates =
new SingleThreadedFlatBitSetFrame(mainSegmentsBitSetSize);
mainSegmentsModIterFrameForIteration =
new ConcurrentFlatBitSetFrame(mainSegmentsBitSetSize);
long tierBulkBitSetSize =
BYTES.toBits(tierBulkModIterBitSetSizeInBytes(tiersInBulk));
tierBulkModIterFrameForUpdates = new SingleThreadedFlatBitSetFrame(tierBulkBitSetSize);
tierBulkModIterFrameForIteration = new ConcurrentFlatBitSetFrame(tierBulkBitSetSize);
}
@Override
void initTransientsFromBuilder(ChronicleMapBuilder<K, V> builder) {
super.initTransientsFromBuilder(builder);
this.remoteOperations = (MapRemoteOperations<K, V, R>) builder.remoteOperations;
this.timeProvider = builder.timeProvider();
cleanupTimeout = builder.cleanupTimeout;
cleanupTimeoutUnit = builder.cleanupTimeoutUnit;
}
void initTransientsFromReplication(AbstractReplication replication) {
this.localIdentifier = replication.identifier();
this.bootstrapOnlyLocalEntries = replication.bootstrapOnlyLocalEntries();
if (localIdentifier == -1)
throw new IllegalStateException("localIdentifier should not be -1");
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
initOwnTransients();
}
long modIterBitSetSizeInBytes() {
long bytes = BITS.toBytes(bitsPerSegmentInModIterBitSet() * actualSegments);
return CACHE_LINES.align(bytes, BYTES);
}
@Override
protected long computeTierBulkInnerOffsetToTiers(long tiersInBulk) {
return super.computeTierBulkInnerOffsetToTiers(tiersInBulk) +
tierBulkModIterBitSetSizeInBytes(tiersInBulk) * (128 + RESERVED_MOD_ITER);
}
private long tierBulkModIterBitSetSizeInBytes(long numberOfTiersInBulk) {
long bytes = BITS.toBytes(bitsPerSegmentInModIterBitSet() * numberOfTiersInBulk);
return CACHE_LINES.align(bytes, BYTES);
}
private long bitsPerSegmentInModIterBitSet() {
// min 128 * 8 to prevent false sharing on updating bits from different segments
// TODO this doesn't prevent false sharing. There should be GAPS between per-segment bits
return Maths.nextPower2(actualChunksPerSegment, 128L * 8L);
}
@Override
public long mapHeaderInnerSize() {
return super.mapHeaderInnerSize() + LAST_UPDATED_HEADER_SIZE +
assignedModIterBitSetSizeInBytes() +
(modIterBitSetSizeInBytes() * (128 + RESERVED_MOD_ITER));
}
public void setLastModificationTime(byte identifier, long timestamp) {
final long offset = identifierUpdatedBytesOffset + identifier * 8L;
// purposely not volatile as this will impact performance,
// and the worst that will happen is we'll end up loading more data on a bootstrap
if (bs.readLong(offset) < timestamp)
bs.writeLong(offset, timestamp);
}
@Override
public long lastModificationTime(byte remoteIdentifier) {
assert remoteIdentifier != this.identifier();
// purposely not volatile as this will impact performance,
// and the worst that will happen is we'll end up loading more data on a bootstrap
return bs.readLong(identifierUpdatedBytesOffset + remoteIdentifier * 8L);
}
@Override
public void onHeaderCreated() {
long offset = super.mapHeaderInnerSize();
identifierUpdatedBytesOffset = offset;
offset += LAST_UPDATED_HEADER_SIZE;
ConcurrentFlatBitSetFrame modIterBitSetFrame =
new ConcurrentFlatBitSetFrame(BYTES.toBits(assignedModIterBitSetSizeInBytes()));
modIterSet = new ReusableBitSet(modIterBitSetFrame, checkedBytesStoreAccess(), bs, offset);
offset += assignedModIterBitSetSizeInBytes();
startOfModificationIterators = offset;
}
@Override
protected void zeroOutNewlyMappedChronicleMapBytes() {
super.zeroOutNewlyMappedChronicleMapBytes();
bs.zeroOut(super.mapHeaderInnerSize(), this.mapHeaderInnerSize());
}
void addCloseable(Closeable closeable) {
closeables.add(closeable);
}
@Override
public synchronized void close() {
if (closed)
return;
for (Closeable closeable : closeables) {
try {
closeable.close();
} catch (IOException e) {
LOG.error("", e);
}
}
super.close();
}
@Override
public byte identifier() {
byte id = localIdentifier;
if (id == 0) {
throw new IllegalStateException("Replication identifier is not set for this\n" +
"replicated Chronicle Map. This should only be possible if persisted\n" +
"replicated Chronicle Map access from another process/JVM run/after\n" +
"a transfer from another machine, and replication identifier is not\n" +
"specified when access is configured, e. g. ChronicleMap.of(...)" +
".createPersistedTo(existingFile).\n" +
"In this case, replicated Chronicle Map \"doesn't know\" it's identifier,\n" +
"and is able to perform simple _read_ operations like map.get(), which\n" +
"doesn't access the identifier. To perform updates, insertions, replication\n" +
"tasks, you should configure the current node identifier,\n" +
"by `replication(identifier)` method call in ChronicleMapBuilder\n" +
"configuration chain.");
}
assert id > 0;
return id;
}
@Override
public ModificationIterator acquireModificationIterator(byte remoteIdentifier) {
ModificationIterator modificationIterator = modificationIterators.get(remoteIdentifier);
if (modificationIterator != null)
return modificationIterator;
synchronized (modificationIterators) {
modificationIterator = modificationIterators.get(remoteIdentifier);
if (modificationIterator != null)
return modificationIterator;
final ModificationIterator modIter = new ModificationIterator(remoteIdentifier);
modificationIterators.set(remoteIdentifier, modIter);
modIterSet.set(remoteIdentifier);
return modIter;
}
}
public void raiseChange(long tierIndex, long pos, long timestamp) {
for (long next = modIterSet.nextSetBit(0L); next > 0L;
next = modIterSet.nextSetBit(next + 1L)) {
try {
acquireModificationIterator((byte) next).raiseChange(tierIndex, pos, timestamp);
} catch (Exception e) {
LOG.error("", e);
}
}
}
public void dropChange(long tierIndex, long pos) {
for (long next = modIterSet.nextSetBit(0L); next > 0L;
next = modIterSet.nextSetBit(next + 1L)) {
try {
acquireModificationIterator((byte) next).dropChange(tierIndex, pos);
} catch (Exception e) {
LOG.error("", e);
}
}
}
public void moveChange(long oldTierIndex, long oldPos, long newTierIndex, long newPos,
long timestamp) {
for (long next = modIterSet.nextSetBit(0L); next > 0L;
next = modIterSet.nextSetBit(next + 1L)) {
try {
ModificationIterator modificationIterator =
acquireModificationIterator((byte) next);
if (modificationIterator.dropChange(oldTierIndex, oldPos))
modificationIterator.raiseChange(newTierIndex, newPos, timestamp);
} catch (Exception e) {
LOG.error("", e);
}
}
}
public boolean isChanged(long tierIndex, long pos) {
for (long next = modIterSet.nextSetBit(0L); next > 0L;
next = modIterSet.nextSetBit(next + 1L)) {
ModificationIterator modificationIterator =
acquireModificationIterator((byte) next);
if (modificationIterator.isChanged(tierIndex, pos))
return true;
}
return false;
}
@Override
public boolean identifierCheck(@NotNull ReplicableEntry entry, int chronicleId) {
return entry.originIdentifier() == identifier();
}
@Override
public int sizeOfEntry(@NotNull Bytes entry, int chronicleId) {
long start = entry.readPosition();
try {
final long keySize = keySizeMarshaller.readSize(entry);
entry.readSkip(keySize + 8); // we skip 8 for the timestamp
final byte identifier = entry.readByte();
if (identifier != identifier()) {
// although unlikely, this may occur if the entry has been updated
return 0;
}
entry.readSkip(1); // is Deleted
long valueSize = valueSizeMarshaller.readSize(entry);
long currentPosition = entry.readPosition();
long currentAddr = entry.address(currentPosition);
long skip = alignAddr(currentAddr, alignment) - currentAddr;
long result = currentPosition + skip + valueSize - start;
// entries can be larger than Integer.MAX_VALUE as we are restricted to the size we can
// make a byte buffer
assert result < Integer.MAX_VALUE;
return (int) result + SIZE_OF_BOOTSTRAP_TIME_STAMP;
} finally {
entry.readPosition(start);
}
}
/**
* This method does not set a segment lock, A segment lock should be obtained before calling
* this method, especially when being used in a multi threaded context.
*/
@Override
public void writeExternalEntry(
@NotNull Bytes entry, @NotNull Bytes destination, int chronicleId, long bootstrapTime) {
final long keySize = keySizeMarshaller.readSize(entry);
final long keyPosition = entry.readPosition();
entry.readSkip(keySize);
final long timeStamp = entry.readLong();
final byte identifier = entry.readByte();
if (identifier != identifier()) {
// although unlikely, this may occur if the entry has been updated
return;
}
final boolean isDeleted = entry.readBoolean();
long valueSize;
if (!isDeleted) {
valueSize = valueSizeMarshaller.readSize(entry);
} else {
valueSize = Math.max(0, valueSizeMarshaller.minStorableSize());
}
final long valuePosition = entry.readPosition();
destination.writeLong(bootstrapTime);
keySizeMarshaller.writeSize(destination, keySize);
valueSizeMarshaller.writeSize(destination, valueSize);
destination.writeStopBit(timeStamp);
if (identifier == 0)
throw new IllegalStateException("Identifier can't be 0");
destination.writeByte(identifier);
destination.writeBoolean(isDeleted);
// write the key
destination.write(entry, keyPosition, keySize);
boolean debugEnabled = LOG.isDebugEnabled();
String message = null;
if (debugEnabled) {
if (isDeleted) {
LOG.debug("WRITING ENTRY TO DEST - into local-id={}, remove(key={})",
identifier(), entry.toString().trim());
} else {
message = String.format(
"WRITING ENTRY TO DEST - into local-id=%d, put(key=%s,",
identifier(), entry.toString().trim());
}
}
if (isDeleted)
return;
// skipping the alignment, as alignment wont work when we send the data over the wire.
long valueAddr = entry.address(valuePosition);
long skip = alignAddr(valueAddr, alignment) - valueAddr;
// writes the value
destination.write(entry, valuePosition + skip, valueSize);
if (debugEnabled) {
LOG.debug(message + "value=" + entry.toString().trim() + ")");
}
}
private ChainingInterface q() {
ChainingInterface queryContext;
queryContext = cxt.get();
if (queryContext == null) {
queryContext = new CompiledReplicatedMapQueryContext<>(ReplicatedChronicleMap.this);
cxt.set(queryContext);
}
return queryContext;
}
@Override
public CompiledReplicatedMapQueryContext<K, V, R> mapContext() {
return q().getContext(CompiledReplicatedMapQueryContext.class,
ci -> new CompiledReplicatedMapQueryContext<>(ci, this));
}
/**
* Assumed to be called from a single thread - the replication thread. Not to waste time
* for going into replication thread's threadLocal map, cache the context in Map's field
*/
private CompiledReplicatedMapQueryContext<K, V, R> remoteOpContext() {
if (remoteOpContext == null) {
remoteOpContext = (CompiledReplicatedMapQueryContext<K, V, R>) q();
}
assert !remoteOpContext.usedInit();
remoteOpContext.initUsed(true);
return remoteOpContext;
}
private CompiledReplicatedMapIterationContext<K, V, R> remoteItContext() {
if (remoteItContext == null) {
remoteItContext = (CompiledReplicatedMapIterationContext<K, V, R>) i();
}
assert !remoteItContext.usedInit();
remoteItContext.initUsed(true);
return remoteItContext;
}
/**
* This method does not set a segment lock, A segment lock should be obtained before calling
* this method, especially when being used in a multi threaded context.
*/
@Override
public void readExternalEntry(@NotNull Bytes source) {
try (CompiledReplicatedMapQueryContext<K, V, R> remoteOpContext = mapContext()) {
remoteOpContext.initReplicationInput(source);
remoteOpContext.processReplicatedEvent();
}
}
private ChainingInterface i() {
ChainingInterface iterContext;
iterContext = cxt.get();
if (iterContext == null) {
iterContext = new CompiledReplicatedMapIterationContext<>(ReplicatedChronicleMap.this);
cxt.set(iterContext);
}
return iterContext;
}
public CompiledReplicatedMapIterationContext<K, V, R> iterationContext() {
return i().getContext(CompiledReplicatedMapIterationContext.class,
ci -> new CompiledReplicatedMapIterationContext<>(ci, this));
}
/**
* <p>Once a change occurs to a map, map replication requires that these changes are picked up
* by another thread, this class provides an iterator like interface to poll for such changes.
* </p> <p>In most cases the thread that adds data to the node is unlikely to be the same thread
* that replicates the data over to the other nodes, so data will have to be marshaled between
* the main thread storing data to the map, and the thread running the replication. </p> <p>One
* way to perform this marshalling, would be to pipe the data into a queue. However, This class
* takes another approach. It uses a bit set, and marks bits which correspond to the indexes of
* the entries that have changed. It then provides an iterator like interface to poll for such
* changes. </p>
*
* @author Rob Austin.
*/
class ModificationIterator implements Replica.ModificationIterator {
private ModificationNotifier modificationNotifier;
private final long mainSegmentsChangesBitSetAddr;
private final int segmentIndexShift;
private final long posMask;
private final long offsetToBitSetWithinATierBulk;
// when a bootstrap is send this is the time stamp that the client will bootstrap up to
// if it is set as ZERO then the onPut() will set it to the current time, once the
// consumer has cycled through the bit set the timestamp will be set back to zero.
private AtomicLong bootStrapTimeStamp = new AtomicLong();
private long lastBootStrapTimeStamp = timeProvider.currentTime();
// records the current position of the cursor in the bitset
// TODO volatile?
private volatile long position = NOT_FOUND;
// -1 for main segments area, 0-N is tier bulk id
private int iterationMainSegmentsAreaOrTierBulk = -1;
private long tierBulkBitSetAddr = 0L;
public ModificationIterator(int remoteIdentifier) {
long bitsPerSegment = bitsPerSegmentInModIterBitSet();
segmentIndexShift = Long.numberOfTrailingZeros(bitsPerSegment);
posMask = bitsPerSegment - 1L;
mainSegmentsChangesBitSetAddr = bsAddress() + startOfModificationIterators +
remoteIdentifier * modIterBitSetSizeInBytes();
nativeAccess().zeroOut(null, mainSegmentsChangesBitSetAddr, modIterBitSetSizeInBytes());
offsetToBitSetWithinATierBulk =
remoteIdentifier * tierBulkModIterBitSetSizeInBytes(tiersInBulk);
}
public ModificationIterator(int remoteIdentifier, ModificationNotifier notifier) {
this(remoteIdentifier);
setModificationNotifier(notifier);
}
public void setModificationNotifier(@NotNull ModificationNotifier modificationNotifier) {
this.modificationNotifier = modificationNotifier;
}
/**
* used to merge multiple segments and positions into a single index used by the bit map
*
* @param tierIndex the index of the maps segment
* @param pos the position within this {@code tierIndex}
* @return and index the has combined the {@code tierIndex} and {@code pos} into a
* single value
*/
private long combine(long tierIndex, long pos) {
long tierIndexMinusOne = tierIndex - 1;
if (tierIndexMinusOne < actualSegments)
return (tierIndexMinusOne << segmentIndexShift) | pos;
return combineExtraTier(tierIndexMinusOne, pos);
}
private long combineExtraTier(long tierIndexMinusOne, long pos) {
long extraTierIndex = tierIndexMinusOne - actualSegments;
long tierIndexOffsetWithinBulk = extraTierIndex & (tiersInBulk - 1);
return (tierIndexOffsetWithinBulk << segmentIndexShift) | pos;
}
void raiseChange(long tierIndex, long pos, long timestamp) {
LOG.debug("raise change: id {}, tierIndex {}, pos {}",
localIdentifier, tierIndex, pos);
long bitIndex = combine(tierIndex, pos);
if (tierIndex <= actualSegments) {
mainSegmentsModIterFrameForUpdates.set(nativeAccess(), null,
mainSegmentsChangesBitSetAddr, bitIndex);
} else {
raiseExtraTierChange(tierIndex, bitIndex);
}
// assert timestamp > timeProvider.currentTime() - TimeUnit.SECONDS.toMillis(1) &&
// timestamp <= timeProvider.currentTime() : "timeStamp=" + timestamp + ", " +
// "currentTime=" + timeProvider.currentTime();
// todo improve this - use the timestamp from the entry its self
bootStrapTimeStamp.compareAndSet(0, timestamp);
if (modificationNotifier != null)
modificationNotifier.onChange();
}
private void raiseExtraTierChange(long tierIndex, long bitIndex) {
tierIndex = tierIndex - actualSegments - 1;
long bulkIndex = tierIndex >> log2TiersInBulk;
TierBulkData tierBulkData = tierBulkOffsets.get((int) bulkIndex);
long bitSetAddr = bitSetAddr(tierBulkData);
tierBulkModIterFrameForUpdates.set(nativeAccess(), null, bitSetAddr, bitIndex);
}
boolean dropChange(long tierIndex, long pos) {
LOG.debug("drop change: id {}, tierIndex {}, pos {}", localIdentifier, tierIndex, pos);
long bitIndex = combine(tierIndex, pos);
if (tierIndex <= actualSegments) {
return mainSegmentsModIterFrameForUpdates.clearIfSet(nativeAccess(), null,
mainSegmentsChangesBitSetAddr, bitIndex);
} else {
return dropExtraTierChange(tierIndex, bitIndex);
}
}
private boolean dropExtraTierChange(long tierIndex, long bitIndex) {
tierIndex = tierIndex - actualSegments - 1;
long bulkIndex = tierIndex >> log2TiersInBulk;
TierBulkData tierBulkData = tierBulkOffsets.get((int) bulkIndex);
long bitSetAddr = bitSetAddr(tierBulkData);
return tierBulkModIterFrameForUpdates.clearIfSet(nativeAccess(), null,
bitSetAddr, bitIndex);
}
private long bitSetAddr(TierBulkData tierBulkData) {
return tierBulkData.bytesStore.address(tierBulkData.offset) +
offsetToBitSetWithinATierBulk;
}
boolean isChanged(long tierIndex, long pos) {
long bitIndex = combine(tierIndex, pos);
if (tierIndex <= actualSegments) {
return mainSegmentsModIterFrameForUpdates.isSet(nativeAccess(), null,
mainSegmentsChangesBitSetAddr, bitIndex);
} else {
return isChangedExtraTier(tierIndex, bitIndex);
}
}
private boolean isChangedExtraTier(long tierIndex, long bitIndex) {
long extraTierIndex = tierIndex - actualSegments - 1;
long bulkIndex = extraTierIndex >> log2TiersInBulk;
TierBulkData tierBulkData = tierBulkOffsets.get((int) bulkIndex);
long bitSetAddr = bitSetAddr(tierBulkData);
return tierBulkModIterFrameForUpdates.isSet(nativeAccess(), null, bitSetAddr, bitIndex);
}
/**
* you can continue to poll hasNext() until data becomes available. If are are in the middle
* of processing an entry via {@code nextEntry}, hasNext will return true until the bit is
* cleared
*
* @return true if there is an entry
*/
@Override
public boolean hasNext() {
return nextPosition() >= 0;
}
private long nextPosition() {
long nextPos;
long position = this.position;
boolean allBitSetsScannedFromTheStart = false;
// at most 2 iterations
while (!allBitSetsScannedFromTheStart) {
if (iterationMainSegmentsAreaOrTierBulk == -1) {
allBitSetsScannedFromTheStart = position < 0;
if ((nextPos = mainSegmentsModIterFrameForIteration.nextSetBit(nativeAccess(),
null, mainSegmentsChangesBitSetAddr, position + 1)) != NOT_FOUND) {
return nextPos;
} else {
this.position = position = NOT_FOUND;
// go to the first bulk
iterationMainSegmentsAreaOrTierBulk = 0;
}
}
// for each allocated tier bulk
while (iterationMainSegmentsAreaOrTierBulk <
globalMutableState().getAllocatedExtraTierBulks()) {
VanillaChronicleHash.TierBulkData tierBulkData =
tierBulkOffsets.get(iterationMainSegmentsAreaOrTierBulk);
tierBulkBitSetAddr = bitSetAddr(tierBulkData);
if ((nextPos = tierBulkModIterFrameForIteration.nextSetBit(nativeAccess(), null,
tierBulkBitSetAddr, position + 1)) != NOT_FOUND) {
return nextPos;
}
// go to the next bulk
iterationMainSegmentsAreaOrTierBulk++;
this.position = position = NOT_FOUND;
}
this.iterationMainSegmentsAreaOrTierBulk = -1;
this.position = position = NOT_FOUND;
bootStrapTimeStamp.set(0);
}
return NOT_FOUND;
}
/**
* @param entryCallback call this to get an entry, this class will take care of the locking
* @return true if an entry was processed
*/
@Override
public boolean nextEntry(@NotNull EntryCallback entryCallback, int chronicleId) {
while (true) {
long position = nextPosition();
if (position == NOT_FOUND) {
this.position = NOT_FOUND;
return false;
}
this.position = position;
int segmentIndexOrTierIndexOffsetWithinBulk =
(int) (position >>> segmentIndexShift);
try (CompiledReplicatedMapIterationContext<K, V, R> context =
iterationContext()) {
if (iterationMainSegmentsAreaOrTierBulk < 0) {
// if main area
// segmentIndexOrTierIndexOffsetWithinBulk is segment index
context.initSegmentIndex(segmentIndexOrTierIndexOffsetWithinBulk);
} else {
// extra tiers
// segmentIndexOrTierIndexOffsetWithinBulk is tier index offset within bulk
TierBulkData tierBulkData =
tierBulkOffsets.get(iterationMainSegmentsAreaOrTierBulk);
long tierBaseAddr = tierAddr(tierBulkData,
segmentIndexOrTierIndexOffsetWithinBulk);
long tierCountersAreaAddr = tierBaseAddr + tierHashLookupOuterSize;
context.initSegmentIndex(
TierCountersArea.segmentIndex(tierCountersAreaAddr));
int tier = TierCountersArea.tier(tierCountersAreaAddr);
long tierIndex = actualSegments +
(iterationMainSegmentsAreaOrTierBulk << log2TiersInBulk) +
segmentIndexOrTierIndexOffsetWithinBulk + 1;
context.initSegmentTier(tier, tierIndex, tierBaseAddr);
}
context.updateLock().lock();
if (changesForUpdatesGet(position)) {
entryCallback.onBeforeEntry();
final long segmentPos = position & posMask;
context.readExistingEntry(segmentPos);
// it may not be successful if the buffer can not be re-sized so we will
// process it later, by NOT clearing the changes.clear(position)
context.segmentBytes()
.readLimit(context.valueOffset() + context.valueSize());
context.segmentBytes().readPosition(context.keySizeOffset());
boolean success = entryCallback.onEntry(
context.segmentBytes(), chronicleId, bootStrapTimeStamp());
entryCallback.onAfterEntry();
if (success)
changesForUpdatesClear(position);
return success;
}
// if the position was already cleared by another thread
// while we were trying to obtain segment lock (for example, in relocation()),
// go to pick up next (next iteration in while (true) loop)
}
}
}
private boolean changesForUpdatesGet(long position) {
if (iterationMainSegmentsAreaOrTierBulk < 0) {
return mainSegmentsModIterFrameForUpdates.get(nativeAccess(), null,
mainSegmentsChangesBitSetAddr, position);
} else {
return tierBulkModIterFrameForUpdates.get(nativeAccess(), null,
tierBulkBitSetAddr, position);
}
}
private void changesForUpdatesClear(long position) {
if (iterationMainSegmentsAreaOrTierBulk < 0) {
mainSegmentsModIterFrameForUpdates.clear(nativeAccess(), null,
mainSegmentsChangesBitSetAddr, position);
} else {
tierBulkModIterFrameForUpdates.clear(nativeAccess(), null,
tierBulkBitSetAddr, position);
}
}
/**
* @return the timestamp that the remote client should bootstrap from when there has been a
* disconnection, this time maybe later than the message time as event are not send in
* chronological order from the bit set.
*/
private long bootStrapTimeStamp() {
final long timeStamp = bootStrapTimeStamp.get();
long result = (timeStamp == 0) ? this.lastBootStrapTimeStamp : timeStamp;
this.lastBootStrapTimeStamp = result;
return result;
}
@Override
public void dirtyEntries(long fromTimeStamp) {
try (CompiledReplicatedMapIterationContext<K, V, R> c = iterationContext()) {
// iterate over all the segments and mark bit in the modification iterator
// that correspond to entries with an older timestamp
boolean debugEnabled = LOG.isDebugEnabled();
for (int segmentIndex = 0; segmentIndex < actualSegments; segmentIndex++) {
c.initSegmentIndex(segmentIndex);
c.forEachSegmentReplicableEntry(e -> {
if (debugEnabled) {
LOG.debug("Bootstrap entry: id {}, key {}, value {}", localIdentifier,
c.key(), c.value());
}
// Bizarrely the next line line cause NPE in JDT compiler
//assert re.originTimestamp() > 0L;
if (debugEnabled) {
LOG.debug("Bootstrap decision: bs ts: {}, entry ts: {}, " +
"entry id: {}, local id: {}",
fromTimeStamp, e.originTimestamp(),
e.originIdentifier(), localIdentifier);
}
if (e.originTimestamp() >= fromTimeStamp &&
(!bootstrapOnlyLocalEntries ||
e.originIdentifier() == localIdentifier)) {
raiseChange(c.tierIndex(), c.pos(), c.timestamp());
}
});
}
}
}
}
}
|
package net.technic.technicblocks.blocks;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.IIcon;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import net.technic.technicblocks.blocks.behavior.BlockBehavior;
import net.technic.technicblocks.blocks.behavior.functions.*;
import net.technic.technicblocks.client.BlockModel;
import net.technic.technicblocks.items.DataDrivenItemBlock;
import java.util.*;
public class DataDrivenBlock extends Block {
private BlockModel blockModel;
private Collection<String> blockTags;
private List<Integer> subBlockMetadatas = new ArrayList<Integer>();
private Map<Integer, DataDrivenSubBlock> subBlocks = new HashMap<Integer, DataDrivenSubBlock>();
private byte subblockMask;
private List<BlockBehavior> behaviors;
private List<IBlockPlacementBehavior> blockPlacementBehaviors = new ArrayList<IBlockPlacementBehavior>();
private List<IItemBlockTargetBehavior> itemBlockTargetBehaviors = new ArrayList<IItemBlockTargetBehavior>();
private List<IBlockDropBehavior> blockDropBehaviors = new ArrayList<IBlockDropBehavior>();
private List<ICreativePickerBehavior> creativePickerBehaviors = new ArrayList<ICreativePickerBehavior>();
private List<INeighborUpdateBehavior> neighborUpdateBehaviors = new ArrayList<INeighborUpdateBehavior>();
private List<IBlockTickBehavior> blockTickBehaviors = new ArrayList<IBlockTickBehavior>();
public DataDrivenBlock(Material material, BlockModel blockModel, Collection<String> blockTags, List<BlockBehavior> behaviors, List<DataDrivenSubBlock> dataDrivenSubBlocks) {
super(material);
this.blockModel = blockModel;
this.blockTags = blockTags;
this.behaviors = behaviors;
interfaceifyBehaviors();
for (DataDrivenSubBlock subBlock : dataDrivenSubBlocks) {
subBlockMetadatas.add(subBlock.getMetadata());
subBlocks.put(subBlock.getMetadata(), subBlock);
}
subblockMask = 0x0F;
byte nonSubblockMask = 0;
for(BlockBehavior convention : behaviors) {
if (convention.isMetadataReserved())
nonSubblockMask |= convention.getMetadataMask();
}
subblockMask = (byte)(subblockMask & ~nonSubblockMask);
this.opaque = this.isOpaqueCube();
this.lightOpacity = this.isOpaqueCube() ? 255 : 0;
}
private void interfaceifyBehaviors() {
for(BlockBehavior behavior : behaviors) {
if (behavior instanceof IBlockPlacementBehavior)
blockPlacementBehaviors.add((IBlockPlacementBehavior)behavior);
if (behavior instanceof IItemBlockTargetBehavior)
itemBlockTargetBehaviors.add((IItemBlockTargetBehavior)behavior);
if (behavior instanceof IBlockDropBehavior)
blockDropBehaviors.add((IBlockDropBehavior)behavior);
if (behavior instanceof ICreativePickerBehavior)
creativePickerBehaviors.add((ICreativePickerBehavior)behavior);
if (behavior instanceof INeighborUpdateBehavior)
neighborUpdateBehaviors.add((INeighborUpdateBehavior)behavior);
if (behavior instanceof IBlockTickBehavior) {
if (((IBlockTickBehavior)behavior).shouldTickRandomly())
this.setTickRandomly(true);
blockTickBehaviors.add((IBlockTickBehavior)behavior);
}
}
}
@Override
@SideOnly(Side.CLIENT)
public void getSubBlocks(Item item, CreativeTabs tab, List list) {
for(DataDrivenSubBlock subBlock : subBlocks.values()) {
if (subBlock.isInCreativeMenu()) {
list.add(new ItemStack(this, 1, subBlock.getMetadata()));
}
}
}
@Override
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister registry)
{
for (DataDrivenSubBlock subBlock : subBlocks.values()) {
subBlock.getTextureScheme().registerIcons(registry);
}
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIcon(int side, int meta)
{
ForgeDirection dir = transformBlockFacing(meta, ForgeDirection.VALID_DIRECTIONS[side]);
return getSubBlock(meta).getTextureScheme().getTextureForSide(dir);
}
@Override
@SideOnly(Side.CLIENT)
public IIcon getIcon(IBlockAccess world, int x, int y, int z, int side)
{
int meta = world.getBlockMetadata(x,y,z);
ForgeDirection physicalSide = ForgeDirection.VALID_DIRECTIONS[side];
ForgeDirection virtualSide = transformBlockFacing(meta, physicalSide);
return getSubBlock(meta).getTextureScheme().getTextureForSide(this, world, x, y, z, physicalSide, virtualSide);
}
public BlockModel getBlockModel() {
return blockModel;
}
public boolean hasBlockTag(String tag) {
return blockTags.contains(tag);
}
public ForgeDirection reverseTransformBlockFacing(int metadata, ForgeDirection direction) {
for (BlockBehavior convention : behaviors) {
direction = convention.reverseTransformBlockFacing(metadata, direction);
}
return direction;
}
public ForgeDirection transformBlockFacing(int metadata, ForgeDirection direction) {
for (BlockBehavior convention : behaviors) {
direction = convention.transformBlockFacing(metadata, direction);
}
return direction;
}
public boolean isOnFloor(int metadata) {
boolean isOnFloor = true;
for (BlockBehavior convention : behaviors) {
isOnFloor = convention.transformIsOnFloor(metadata, isOnFloor);
}
return isOnFloor;
}
public DataDrivenSubBlock getSubBlock(int metadata) {
metadata &= subblockMask;
if (subBlocks.containsKey(metadata))
return subBlocks.get(metadata);
return null;
}
public DataDrivenSubBlock getSubBlock(IBlockAccess world, int x, int y, int z) {
int metadata = world.getBlockMetadata(x,y,z);
return getSubBlock(metadata);
}
public int getSubBlockMask() {
return subblockMask;
}
public int getSubBlockCount() {
return subBlocks.size();
}
public int getSubBlockMetadataByIndex(int index) {
return subBlockMetadatas.get(index);
}
@Override
public int getRenderType() { return getBlockModel().getRendererId(); }
@Override
public boolean isOpaqueCube() {
if (getBlockModel() == null)
return true;
return getBlockModel().isOpaqueCube();
}
@Override
public boolean isSideSolid(IBlockAccess world, int x, int y, int z, ForgeDirection side) {
return getBlockModel().isSideSolid(this, world, x, y, z, side);
}
/**
* Updates the blocks bounds based on its current state. Args: world, x, y, z
*/
@Override
public void setBlockBoundsBasedOnState(IBlockAccess world, int x, int y, int z)
{
getBlockModel().setBlockBounds(this, world, x, y, z);
}
@Override
public AxisAlignedBB getCollisionBoundingBoxFromPool(World world, int x, int y, int z)
{
return getBlockModel().getCentralCollisionBox(this, world, x, y, z);
}
/**
* Ray traces through the blocks collision from start vector to end vector returning a ray trace hit. Args: world,
* x, y, z, startVec, endVec
*/
@Override
public MovingObjectPosition collisionRayTrace(World world, int x, int y, int z, Vec3 start, Vec3 end)
{
return getBlockModel().traceCollision(this, world, x, y, z, start, end);
}
/**
* Checks if a vector is within the Y and Z bounds of the block.
*/
public boolean isVecYZContained(Vec3 p_149654_1_)
{
return p_149654_1_ == null ? false : p_149654_1_.yCoord >= this.minY && p_149654_1_.yCoord <= this.maxY && p_149654_1_.zCoord >= this.minZ && p_149654_1_.zCoord <= this.maxZ;
}
/**
* Checks if a vector is within the X and Z bounds of the block.
*/
public boolean isVecXZContained(Vec3 p_149687_1_)
{
return p_149687_1_ == null ? false : p_149687_1_.xCoord >= this.minX && p_149687_1_.xCoord <= this.maxX && p_149687_1_.zCoord >= this.minZ && p_149687_1_.zCoord <= this.maxZ;
}
/**
* Checks if a vector is within the X and Y bounds of the block.
*/
public boolean isVecXYContained(Vec3 p_149661_1_)
{
return p_149661_1_ == null ? false : p_149661_1_.xCoord >= this.minX && p_149661_1_.xCoord <= this.maxX && p_149661_1_.yCoord >= this.minY && p_149661_1_.yCoord <= this.maxY;
}
/**
* Adds all intersecting collision boxes to a list. (Be sure to only add boxes to the list if they intersect the
* mask.) Parameters: World, X, Y, Z, mask, list, colliding entity
*/
@Override
public void addCollisionBoxesToList(World world, int x, int y, int z, AxisAlignedBB mask, List list, Entity entity)
{
getBlockModel().collectCollisionBoxes(this, world, x, y, z, mask, list, entity);
}
@Override
public int onBlockPlaced(World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int metadata)
{
ForgeDirection face = ForgeDirection.VALID_DIRECTIONS[side];
for (IBlockPlacementBehavior behavior : blockPlacementBehaviors)
metadata = behavior.transformPlacementMetadata(this, world, x, y, z, face, hitX, hitY, hitZ, metadata);
return metadata;
}
@Override
public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase player, ItemStack item)
{
for (IBlockPlacementBehavior behavior : blockPlacementBehaviors)
behavior.triggerBlockPlacement(this, world, x, y, z, player, item);
}
@Override
public ArrayList<ItemStack> getDrops(World world, int x, int y, int z, int metadata, int fortune) {
boolean dropDefaults = true;
for(IBlockDropBehavior behavior : blockDropBehaviors) {
dropDefaults = behavior.doesDropDefault(world, x, y, z, metadata, fortune);
if (!dropDefaults)
break;
}
ArrayList<ItemStack> returnValue;
if (dropDefaults)
returnValue = super.getDrops(world, x, y, z, metadata, fortune);
else
returnValue = new ArrayList<ItemStack>();
for (IBlockDropBehavior behavior : blockDropBehaviors) {
behavior.addExtraDrops(returnValue, world, x, y, z, metadata, fortune);
}
return returnValue;
}
@Override
public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z)
{
ItemStack result = new ItemStack(this, 1, this.getSubBlock(world,x,y,z).getMetadata());
for(ICreativePickerBehavior pickerBehavior : creativePickerBehaviors) {
result = pickerBehavior.transformPickResult(target, world, x, y, z, result);
}
return result;
}
public boolean shouldPlaceBlock(EntityPlayer player, DataDrivenItemBlock item, ItemStack itemStack, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) {
boolean shouldPlaceBlock = true;
ForgeDirection face = ForgeDirection.VALID_DIRECTIONS[side];
for (IItemBlockTargetBehavior behavior : itemBlockTargetBehaviors) {
shouldPlaceBlock = behavior.transformShouldPlaceBlock(player, this, item, itemStack, world, x, y, z, face, hitX, hitY, hitZ, shouldPlaceBlock);
}
return shouldPlaceBlock;
}
public boolean itemUsedOnBlock(EntityPlayer player, DataDrivenItemBlock item, ItemStack itemStack, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) {
boolean shouldConsumeItem = false;
ForgeDirection face = ForgeDirection.VALID_DIRECTIONS[side];
for (IItemBlockTargetBehavior behavior : itemBlockTargetBehaviors) {
shouldConsumeItem = behavior.itemUsedOnBlock(player, this, item, itemStack, world, x, y, z, face, hitX, hitY, hitZ) || shouldConsumeItem;
}
return shouldConsumeItem;
}
/**
* Ticks the block if it's been scheduled
*/
@Override
public void updateTick(World world, int x, int y, int z, Random random)
{
super.updateTick(world, x, y, z, random);
for(IBlockTickBehavior behavior : blockTickBehaviors) {
behavior.blockUpdateTick(this, world, x, y, z, random);
}
}
/**
* Lets the block know when one of its neighbor changes. Doesn't know which neighbor changed (coordinates passed are
* their own) Args: x, y, z, neighbor Block
*/
@Override
public void onNeighborBlockChange(World world, int x, int y, int z, Block neighbor)
{
super.onNeighborBlockChange(world, x, y, z, neighbor);
for(INeighborUpdateBehavior behavior : neighborUpdateBehaviors) {
behavior.neighborUpdated(this, world, x, y, z, neighbor);
}
}
}
|
package nl.hsac.fitnesse.fixture.util.selenium.by;
import org.openqa.selenium.By;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebElement;
/**
* Custom By to deal with finding elements in a table representing a grid of values.
*/
public class GridBy {
public static SingleElementOrNullBy coordinates(int columnIndex, int rowIndex) {
return new Value.AtCoordinates(columnIndex, rowIndex);
}
public static SingleElementOrNullBy columnInRow(String requestedColumnName, int rowIndex) {
return new Value.OfInRowNumber(requestedColumnName, rowIndex);
}
public static SingleElementOrNullBy columnInRowWhereIs(String requestedColumnName, String selectOnColumn, String selectOnValue) {
return new Value.OfInRowWhereIs(requestedColumnName, selectOnValue, selectOnColumn);
}
public static XPathBy rowNumber(int rowIndex) {
return new Row.InNumber(rowIndex);
}
public static XPathBy rowWhereIs(String selectOnColumn, String selectOnValue) {
return new Row.WhereIs(selectOnValue, selectOnColumn);
}
public static abstract class Value extends SingleElementOrNullBy {
public static class AtCoordinates extends Value {
private final int columnIndex;
private final int rowIndex;
public AtCoordinates(int columnIndex, int rowIndex) {
this.columnIndex = columnIndex;
this.rowIndex = rowIndex;
}
@Override
public WebElement findElement(SearchContext context) {
String row = Integer.toString(rowIndex);
String column = Integer.toString(columnIndex);
return getValueByXPath(context, "(.//tr[boolean(td)])[%s]/td[%s]", row, column);
}
}
public static class OfInRowNumber extends Value {
private final String requestedColumnName;
private final int rowIndex;
public OfInRowNumber(String requestedColumnName, int rowIndex) {
this.requestedColumnName = requestedColumnName;
this.rowIndex = rowIndex;
}
@Override
public WebElement findElement(SearchContext context) {
String columnXPath = String.format("((.//table[.//tr/th/descendant-or-self::text()[normalized(.)='%s']])[last()]//tr[boolean(td)])[%s]/td", requestedColumnName, rowIndex);
return valueInRow(context, columnXPath, requestedColumnName);
}
}
public static class OfInRowWhereIs extends Value {
private final String requestedColumnName;
private final String selectOnColumn;
private final String selectOnValue;
public OfInRowWhereIs(String requestedColumnName, String selectOnValue, String selectOnColumn) {
this.requestedColumnName = requestedColumnName;
this.selectOnColumn = selectOnColumn;
this.selectOnValue = selectOnValue;
}
@Override
public WebElement findElement(SearchContext context) {
String columnXPath = getXPathForColumnInRowByValueInOtherColumn(requestedColumnName, selectOnColumn, selectOnValue);
return valueInRow(context, columnXPath, requestedColumnName);
}
}
protected WebElement valueInRow(SearchContext context, String columnXPath, String requestedColumnName) {
String requestedIndex = getXPathForColumnIndex(requestedColumnName);
return getValueByXPath(context, "%s[%s]", columnXPath, requestedIndex);
}
protected WebElement getValueByXPath(SearchContext context, String xpathPattern, String... params) {
By xPathBy = new XPathBy(xpathPattern, params);
return new ValueOfBy(xPathBy).findElement(context);
}
}
public static class Row {
public static class InNumber extends XPathBy {
public InNumber(int rowIndex) {
super("(.//tr[boolean(td)])[%s]", Integer.toString(rowIndex));
}
}
public static class WhereIs extends XPathBy {
public WhereIs(String selectOnValue, String selectOnColumn) {
super(getXPathForColumnInRowByValueInOtherColumn(selectOnColumn, selectOnValue) + "/..");
}
}
}
/**
* Creates an XPath expression that will find a cell in a row, selecting the row based on the
* text in a specific column (identified by its header text).
* @param columnName header text of the column to find value in.
* @param value text to find in column with the supplied header.
* @return XPath expression selecting a td in the row
*/
public static String getXPathForColumnInRowByValueInOtherColumn(String columnName, String value) {
String selectIndex = getXPathForColumnIndex(columnName);
return String.format("(.//table[.//tr/th/descendant-or-self::text()[normalized(.)='%3$s']])[last()]//tr[td[%1$s]/descendant-or-self::text()[normalized(.)='%2$s']]/td",
selectIndex, value, columnName);
}
/**
* Creates an XPath expression that will find a cell in a row, selecting the row based on the
* text in a specific column (identified by its header text).
* @param extraColumnName name of other header text that must be present in table's header row
* @param columnName header text of the column to find value in.
* @param value text to find in column with the supplied header.
* @return XPath expression selecting a td in the row
*/
public static String getXPathForColumnInRowByValueInOtherColumn(String extraColumnName, String columnName, String value) {
String selectIndex = getXPathForColumnIndex(columnName);
return String.format("(.//table[.//tr[th/descendant-or-self::text()[normalized(.)='%3$s'] and th/descendant-or-self::text()[normalized(.)='%4$s']]])[last()]//tr[td[%1$s]/descendant-or-self::text()[normalized(.)='%2$s']]/td",
selectIndex, value, columnName, extraColumnName);
}
/**
* Creates an XPath expression that will determine, for a row, which index to use to select the cell in the column
* with the supplied header text value.
* @param columnName name of column in header (th)
* @return XPath expression which can be used to select a td in a row
*/
public static String getXPathForColumnIndex(String columnName) {
// determine how many columns are before the column with the requested name
// the column with the requested name will have an index of the value +1 (since XPath indexes are 1 based)
return String.format("count(ancestor::table[1]//tr/th/descendant-or-self::text()[normalized(.)='%s']/ancestor-or-self::th[1]/preceding-sibling::th)+1", columnName);
}
}
|
package nl.tudelft.dnainator.graph;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.function.Predicate;
import nl.tudelft.dnainator.core.SequenceNode;
/**
* A description of a query and its parameters.
*/
public class GraphQueryDescription {
private Collection<String> idStrings;
private Collection<String> sourceStrings;
private Predicate<SequenceNode> filter;
private boolean queryFrom = false;
private int from = 0;
private boolean queryTo = false;
private int to = Integer.MAX_VALUE;
/**
* Query for the given id.
* @param id the String id to search for
* @return this
*/
public GraphQueryDescription hasId(String id) {
return haveIds(Collections.singletonList(id));
}
/**
* Query for the given ids.
* @param ids the ids to search for.
* @return this
*/
public GraphQueryDescription haveIds(Collection<String> ids) {
if (idStrings == null) {
idStrings = new ArrayList<>(ids);
return this;
}
idStrings.addAll(ids);
return this;
}
/**
* @return Whether the query should query for ids.
*/
public boolean shouldQueryIds() {
return idStrings != null;
}
/**
* @return The ids to query for.
*/
public Collection<String> getIds() {
return idStrings;
}
/**
* The result should have the given source as one of its sources.
* @param source The source to search for.
* @return this
*/
public GraphQueryDescription containsSource(String source) {
return containsSources(Collections.singletonList(source));
}
/**
* The result should have one of the given sources.
* @param sources The sources to search for.
* @return this
*/
public GraphQueryDescription containsSources(Collection<String> sources) {
if (sourceStrings == null) {
sourceStrings = new ArrayList<>(sources);
return this;
}
sourceStrings.addAll(sources);
return this;
}
/**
* @return Whether the query should query for sources.
*/
public boolean shouldQuerySources() {
return sourceStrings != null;
}
/**
* @return The source parameters.
*/
public Collection<String> getSources() {
return sourceStrings;
}
/**
* Filter the result with the given {@link Predicate}.
* @param p the predicate to test against.
* @return this
*/
public GraphQueryDescription filter(Predicate<SequenceNode> p) {
filter = p;
return this;
}
/**
* @return Whether the result should be filtered.
*/
public boolean shouldFilter() {
return filter != null;
}
/**
* @return The filter predicate.
*/
public Predicate<SequenceNode> getFilter() {
return filter;
}
/**
* Search from the given rank (inclusive).
* @param start The rank to search from.
* @return this
*/
public GraphQueryDescription fromRank(int start) {
from = start;
queryFrom = true;
return this;
}
/**
* @return Whether the query should search from a rank.
*/
public boolean shouldQueryFrom() {
return queryFrom;
}
/**
* @return The rank to search from (inclusive).
*/
public int getFrom() {
return from;
}
/**
* Search towards the given rank (exclusive).
* @param end The rank to search towards.
* @return this
*/
public GraphQueryDescription toRank(int end) {
to = end;
queryTo = true;
return this;
}
/**
* @return Whether the query should search towards a rank.
*/
public boolean shouldQueryTo() {
return queryTo;
}
/**
* @return The rank to search towards (exclusive).
*/
public int getTo() {
return to;
}
}
|
package org.cyclops.cyclopscore.persist.nbt;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import org.apache.logging.log4j.Level;
import org.cyclops.cyclopscore.CyclopsCore;
import org.cyclops.cyclopscore.helper.MinecraftHelpers;
import java.lang.reflect.Field;
import java.util.*;
/**
* Types of NBT field classes used for persistence of fields in {@link org.cyclops.cyclopscore.tileentity.CyclopsTileEntity}.
* @author rubensworks
*
* @param <T> The field class type.
* @see NBTPersist
*/
public abstract class NBTClassType<T> {
/**
* A map of all the types to their persist actions.
*/
public static Map<Class<?>, NBTClassType<?>> NBTYPES = new HashMap<Class<?>, NBTClassType<?>>();
static {
NBTYPES.put(Integer.class, new NBTClassType<Integer>() {
@Override
protected void writePersistedField(String name, Integer object, NBTTagCompound tag) {
tag.setInteger(name, object);
}
@Override
protected Integer readPersistedField(String name, NBTTagCompound tag) {
return tag.getInteger(name);
}
});
NBTYPES.put(int.class, NBTYPES.get(Integer.class));
NBTYPES.put(Float.class, new NBTClassType<Float>() {
@Override
protected void writePersistedField(String name, Float object, NBTTagCompound tag) {
tag.setFloat(name, object);
}
@Override
protected Float readPersistedField(String name, NBTTagCompound tag) {
return tag.getFloat(name);
}
});
NBTYPES.put(float.class, NBTYPES.get(Float.class));
NBTYPES.put(Boolean.class, new NBTClassType<Boolean>() {
@Override
protected void writePersistedField(String name, Boolean object, NBTTagCompound tag) {
tag.setBoolean(name, object);
}
@Override
protected Boolean readPersistedField(String name, NBTTagCompound tag) {
return tag.getBoolean(name);
}
});
NBTYPES.put(boolean.class, NBTYPES.get(Boolean.class));
NBTYPES.put(String.class, new NBTClassType<String>() {
@Override
protected void writePersistedField(String name, String object, NBTTagCompound tag) {
if(object != null && !object.isEmpty()) {
tag.setString(name, object);
}
}
@Override
protected String readPersistedField(String name, NBTTagCompound tag) {
return tag.getString(name);
}
});
NBTYPES.put(NBTTagCompound.class, new NBTClassType<NBTTagCompound>() {
@Override
protected void writePersistedField(String name, NBTTagCompound object, NBTTagCompound tag) {
tag.setTag(name, object);
}
@Override
protected NBTTagCompound readPersistedField(String name, NBTTagCompound tag) {
return tag.getCompoundTag(name);
}
});
NBTYPES.put(Set.class, new CollectionNBTClassType<Set>() {
@Override
protected Set createNewCollection() {
return Sets.newHashSet();
}
});
NBTYPES.put(List.class, new CollectionNBTClassType<List>() {
@Override
protected List createNewCollection() {
return Lists.newLinkedList();
}
});
NBTYPES.put(Map.class, new NBTClassType<Map>() {
@Override
protected void writePersistedField(String name, Map object, NBTTagCompound tag) {
NBTTagCompound mapTag = new NBTTagCompound();
NBTTagList list = new NBTTagList();
boolean setKeyType = false;
boolean setValueType = false;
for(Map.Entry entry : (Set<Map.Entry>) object.entrySet()) {
NBTTagCompound entryTag = new NBTTagCompound();
getType(entry.getKey().getClass(), object).writePersistedField("key", entry.getKey(), entryTag);
if(entry.getValue() != null) {
getType(entry.getValue().getClass(), object).writePersistedField("value", entry.getValue(), entryTag);
}
list.appendTag(entryTag);
if(!setKeyType) {
setKeyType = true;
mapTag.setString("keyType", entry.getKey().getClass().getName());
}
if(!setValueType && entry.getValue() != null) {
setValueType = true;
mapTag.setString("valueType", entry.getValue().getClass().getName());
}
}
mapTag.setTag("map", list);
tag.setTag(name, mapTag);
}
@SuppressWarnings("unchecked")
@Override
protected Map readPersistedField(String name, NBTTagCompound tag) {
NBTTagCompound mapTag = tag.getCompoundTag(name);
Map map = Maps.newHashMap();
NBTTagList list = mapTag.getTagList("map", MinecraftHelpers.NBTTag_Types.NBTTagCompound.ordinal());
if(list.tagCount() > 0) {
NBTClassType keyNBTClassType;
NBTClassType valueNBTClassType = null; // Remains null when all map values are null.
try {
Class keyType = Class.forName(mapTag.getString("keyType"));
keyNBTClassType = getType(keyType, map);
} catch (ClassNotFoundException e) {
CyclopsCore.clog(Level.WARN, "No class found for NBT type map key '" + mapTag.getString("keyType")
+ "', this could be a mod error.");
return map;
}
if(mapTag.hasKey("valueType")) {
try {
Class valueType = Class.forName(mapTag.getString("valueType"));
valueNBTClassType = getType(valueType, map);
} catch (ClassNotFoundException e) {
CyclopsCore.clog(Level.WARN, "No class found for NBT type map value '" + mapTag.getString("valueType")
+ "', this could be a mod error.");
return map;
}
}
for (int i = 0; i < list.tagCount(); i++) {
NBTTagCompound entryTag = list.getCompoundTagAt(i);
Object key = keyNBTClassType.readPersistedField("key", entryTag);
Object value = null;
// If the class type is null, this means all map values are null, so
// we won't have any problems with just inserting nulls for all values here.
// Also check if it has a 'value' tag, since later elements can still be null.
if(valueNBTClassType != null && entryTag.hasKey("value")) {
value = valueNBTClassType.readPersistedField("value", entryTag);
}
map.put(key, value);
}
}
return map;
}
});
}
private static boolean isImplementsInterface(Class<?> clazz, Class<?> interfaceClazz) {
try {
clazz.asSubclass(interfaceClazz);
} catch (ClassCastException e) {
return false;
}
return true;
}
protected static NBTClassType getType(Class<?> type, Object target) {
// Add special logic for INBTSerializable's
if(isImplementsInterface(type, INBTSerializable.class)) {
return new INBTSerializable.SelfNBTClassType(type);
} else {
NBTClassType<?> action = NBTClassType.NBTYPES.get(type);
if (action == null) {
throw new RuntimeException("No NBT persist action found for type " + type.getName()
+ " in class " + target.getClass() + " for target object " + target + ".");
}
return action;
}
}
/**
* Perform a field persist action.
* @param provider The provider that has the field.
* @param field The field to persist or read.
* @param tag The tag compound to read or write to.
* @param write If there should be written, otherwise there will be read.
*/
public static void performActionForField(INBTProvider provider, Field field, NBTTagCompound tag, boolean write) {
Class<?> type = field.getType();
String fieldName = field.getName();
// Make editable, will set back to the original at the end of this call.
boolean wasAccessible = field.isAccessible();
field.setAccessible(true);
// Get a non-null action
NBTClassType<?> action = getType(type, provider);
try {
action.persistedFieldAction(provider, field, tag, write);
} catch (IllegalAccessException e) {
throw new RuntimeException("Could not access field " + fieldName + " in " + provider.getClass());
}
field.setAccessible(wasAccessible);
}
@SuppressWarnings("unchecked")
public void persistedFieldAction(INBTProvider provider, Field field, NBTTagCompound tag, boolean write) throws IllegalAccessException {
String name = field.getName();
Object castTile = field.getDeclaringClass().cast(provider);
if(write) {
try {
T object = (T) field.get(castTile);
try {
writePersistedField(name, object, tag);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Something went from with the field " + field.getName() + " in " + castTile + ": " + e.getMessage());
}
} catch (IllegalArgumentException e) {
throw new RuntimeException("Can not write the field " + field.getName() + " in " + castTile + " since it does not exist.");
}
} else {
T object = null;
try {
object = readPersistedField(name, tag);
field.set(castTile, object);
} catch (IllegalArgumentException e) {
throw new RuntimeException("Can not read the field " + field.getName() + " as " + object + " in " + castTile + " since it does not exist OR there is a class mismatch.");
}
}
}
protected abstract void writePersistedField(String name, T object, NBTTagCompound tag);
protected abstract T readPersistedField(String name, NBTTagCompound tag);
private abstract static class CollectionNBTClassType<C extends Collection> extends NBTClassType<C> {
protected abstract C createNewCollection();
@Override
protected void writePersistedField(String name, C object, NBTTagCompound tag) {
NBTTagCompound collectionTag = new NBTTagCompound();
NBTTagList list = new NBTTagList();
boolean setTypes = false;
for(Object element : object) {
NBTTagCompound elementTag = new NBTTagCompound();
getType(element.getClass(), object).writePersistedField("element", element, elementTag);
list.appendTag(elementTag);
if (!setTypes) {
setTypes = true;
collectionTag.setString("elementType", element.getClass().getName());
}
}
collectionTag.setTag("collection", list);
tag.setTag(name, collectionTag);
}
@Override
protected C readPersistedField(String name, NBTTagCompound tag) {
NBTTagCompound collectionTag = tag.getCompoundTag(name);
C collection = createNewCollection();
NBTTagList list = collectionTag.getTagList("collection", MinecraftHelpers.NBTTag_Types.NBTTagCompound.ordinal());
if(list.tagCount() > 0) {
NBTClassType elementNBTClassType;
try {
Class elementType = Class.forName(collectionTag.getString("elementType"));
elementNBTClassType = getType(elementType, collection);
} catch (ClassNotFoundException e) {
CyclopsCore.clog(Level.WARN, "No class found for NBT type collection element '" + collectionTag.getString("elementType")
+ "', this could be a mod error.");
return collection;
}
for (int i = 0; i < list.tagCount(); i++) {
NBTTagCompound entryTag = list.getCompoundTagAt(i);
Object element = elementNBTClassType.readPersistedField("element", entryTag);
collection.add(element);
}
}
return collection;
}
}
}
|
package org.cytoscape.commandDialog.internal;
import static org.cytoscape.work.ServiceProperties.COMMAND;
import static org.cytoscape.work.ServiceProperties.COMMAND_NAMESPACE;
import static org.cytoscape.work.ServiceProperties.ENABLE_FOR;
import static org.cytoscape.work.ServiceProperties.INSERT_SEPARATOR_BEFORE;
import static org.cytoscape.work.ServiceProperties.IN_MENU_BAR;
import static org.cytoscape.work.ServiceProperties.MENU_GRAVITY;
import static org.cytoscape.work.ServiceProperties.PREFERRED_MENU;
import static org.cytoscape.work.ServiceProperties.TITLE;
import java.io.File;
import java.util.Properties;
import java.util.concurrent.BlockingQueue;
import org.cytoscape.commandDialog.internal.handlers.CommandHandler;
import org.cytoscape.commandDialog.internal.tasks.CommandDialogTaskFactory;
import org.cytoscape.commandDialog.internal.tasks.PauseCommandTaskFactory;
import org.cytoscape.commandDialog.internal.tasks.RunCommandsTaskFactory;
import org.cytoscape.commandDialog.internal.tasks.RunCommandsTask;
import org.cytoscape.commandDialog.internal.tasks.QuitTaskFactory;
import org.cytoscape.commandDialog.internal.tasks.SleepCommandTaskFactory;
import org.cytoscape.commandDialog.internal.ui.CommandToolDialog;
import org.cytoscape.app.event.AppsFinishedStartingEvent;
import org.cytoscape.app.event.AppsFinishedStartingListener;
import org.cytoscape.application.swing.CySwingApplication;
import org.cytoscape.application.CyShutdown;
import org.cytoscape.command.AvailableCommands;
import org.cytoscape.command.CommandExecutorTaskFactory;
import org.cytoscape.property.CyProperty;
import org.cytoscape.service.util.AbstractCyActivator;
import org.cytoscape.work.SynchronousTaskManager;
import org.cytoscape.work.TaskFactory;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.ops4j.pax.logging.spi.PaxAppender;
public class CyActivator extends AbstractCyActivator {
private static Logger logger = LoggerFactory
.getLogger(org.cytoscape.commandDialog.internal.CyActivator.class);
public CyActivator() {
super();
}
static Properties ezProps(String... args) {
final Properties props = new Properties();
for (int i = 0; i < args.length; i += 2)
props.setProperty(args[i], args[i + 1]);
return props;
}
public void start(BundleContext bc) {
// See if we have a graphics console or not
boolean haveGUI = true;
ServiceReference ref = bc.getServiceReference(CySwingApplication.class.getName());
if (ref == null) {
haveGUI = false;
}
// Get a handle on the CyServiceRegistrar
AvailableCommands availableCommands = getService(bc, AvailableCommands.class);
CommandExecutorTaskFactory commandExecutor = getService(bc, CommandExecutorTaskFactory.class);
SynchronousTaskManager taskManager = getService(bc, SynchronousTaskManager.class);
CommandHandler commandHandler = new CommandHandler(availableCommands, commandExecutor, taskManager);
final CommandToolDialog dialog;
// Register ourselves as a listener for CyUserMessage logs
registerService(bc, commandHandler, PaxAppender.class,
ezProps("org.ops4j.pax.logging.appender.name",
"TaskMonitorShowMessagesAppender"));
// Get any command line arguments. The "-S" and "-R" are ours
CyProperty<Properties> commandLineProps = getService(bc, CyProperty.class, "(cyPropertyName=commandline.props)");
Properties p = commandLineProps.getProperties();
final String scriptFile;
if (p.getProperty("scriptFile") != null)
scriptFile = p.getProperty("scriptFile");
else
scriptFile = null;
if (haveGUI) {
CySwingApplication swingApp = (CySwingApplication) getService(bc, CySwingApplication.class);
// Create our dialog -- we only want one of these instantiated
dialog = new CommandToolDialog(swingApp.getJFrame(), commandHandler);
// Menu task factories
TaskFactory commandDialog = new CommandDialogTaskFactory(dialog);
Properties commandDialogProps = new Properties();
commandDialogProps.setProperty(PREFERRED_MENU, "Tools");
commandDialogProps.setProperty(TITLE, "Command Line Dialog");
commandDialogProps.setProperty(COMMAND, "open dialog");
commandDialogProps.setProperty(COMMAND_NAMESPACE, "command");
commandDialogProps.setProperty(IN_MENU_BAR, "true");
registerService(bc, commandDialog, TaskFactory.class, commandDialogProps);
TaskFactory pauseCommand = new PauseCommandTaskFactory(swingApp.getJFrame());
Properties pauseProperties = new Properties();
pauseProperties.setProperty(COMMAND_NAMESPACE, "command");
pauseProperties.setProperty(COMMAND, "pause");
registerService(bc, pauseCommand, TaskFactory.class, pauseProperties);
} else {
dialog = null;
}
TaskFactory runCommand = new RunCommandsTaskFactory(dialog, commandHandler);
Properties runCommandProps = new Properties();
runCommandProps.setProperty(PREFERRED_MENU, "Tools");
runCommandProps.setProperty(TITLE, "Execute Command File");
runCommandProps.setProperty(COMMAND, "run");
runCommandProps.setProperty(COMMAND_NAMESPACE, "command");
runCommandProps.setProperty(IN_MENU_BAR, "true");
registerService(bc, runCommand, TaskFactory.class, runCommandProps);
CyShutdown shutdown = getService(bc, CyShutdown.class);
TaskFactory quitCommand = new QuitTaskFactory(shutdown);
Properties quitCommandProps = new Properties();
quitCommandProps.setProperty(COMMAND, "quit");
quitCommandProps.setProperty(COMMAND_NAMESPACE, "command");
registerService(bc, quitCommand, TaskFactory.class, quitCommandProps);
TaskFactory sleepCommand = new SleepCommandTaskFactory();
Properties sleepProperties = new Properties();
sleepProperties.setProperty(COMMAND_NAMESPACE, "command");
sleepProperties.setProperty(COMMAND, "sleep");
registerService(bc, sleepCommand, TaskFactory.class, sleepProperties);
if (scriptFile != null) {
registerService(bc, new StartScript(scriptFile, commandHandler, dialog),
AppsFinishedStartingListener.class, new Properties());
}
}
class StartScript implements AppsFinishedStartingListener {
String scriptFile;
CommandToolDialog dialog;
RunCommandsTask runTask;
CommandHandler commandHandler;
protected StartScript(String scriptFile, CommandHandler commandHandler, CommandToolDialog dialog) {
this.scriptFile = scriptFile;
this.dialog = dialog;
this.commandHandler = commandHandler;
runTask = new RunCommandsTask(dialog, commandHandler);
}
public void handleEvent(AppsFinishedStartingEvent event) {
if (dialog != null && scriptFile != null) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
// TODO: need a non-gui approach to this!
dialog.executeCommand("command run file="+scriptFile);
}
});
} else if (dialog == null) {
runTask.executeCommandScript(scriptFile, null);
}
}
}
}
|
package org.dataone.annotator.store;
import java.io.IOException;
import java.io.InputStream;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dataone.client.auth.CertificateManager;
import org.dataone.client.v2.itk.D1Client;
import org.dataone.portal.PortalCertificateManager;
import org.dataone.portal.TokenGenerator;
import org.dataone.service.exceptions.BaseException;
import org.dataone.service.exceptions.InvalidToken;
import org.dataone.service.types.v1.Session;
import org.dataone.service.types.v1.Subject;
import org.dataone.service.types.v1.SubjectInfo;
public class AnnotatorRestServlet extends HttpServlet {
public static Log log = LogFactory.getLog(AnnotatorRestServlet.class);
public static Session getSession(HttpServletRequest request) throws BaseException {
log.debug("Inspecting request for session information");
Session session = null;
// look for certificate-based session (d1 default)
try {
session = CertificateManager.getInstance().getSession(request);
log.debug("Session from original request: " + session);
} catch (InvalidToken e) {
log.warn(e.getMessage(), e);
}
// try getting it from the token (annotator library)
if (session == null) {
debugHeaders(request);
String token = request.getHeader("x-annotator-auth-token");
try {
session = TokenGenerator.getInstance().getSession(token);
} catch (IOException e) {
log.warn(e.getMessage(), e);
}
log.debug("Session from x-annotator-auth-token: " + session);
// set it for the client to use
D1Client.setAuthToken(token);
}
// see if we can proxy as the user
if (session != null) {
try {
log.warn("looking up certificate from portal");
// register the portal certificate with the certificate manager for the calling subject
X509Certificate certificate = PortalCertificateManager.getInstance().getCertificate(request);
PrivateKey key = PortalCertificateManager.getInstance().getPrivateKey(request);
String certSubject = CertificateManager.getInstance().getSubjectDN(certificate);
String sessionSubject = session.getSubject().getValue();
// TODO: verify that the users are the same
log.warn("Certifcate subject: " + certSubject);
log.warn("Session subject: " + sessionSubject);
// now the methods will "know" who is calling them - used in conjunction with Certificate Manager
CertificateManager.getInstance().registerCertificate(certSubject , certificate, key);
log.warn("Registered portal certificate for: " + certSubject);
session = new Session();
Subject subject = new Subject();
subject.setValue(certSubject);
session.setSubject(subject);
} catch (Exception e) {
log.error("cound not register user session from portal: " + e.getMessage(), e);
}
}
// FIXME: for now, just use the CN certificate for everything
// try {
// String nodeProperties = "/etc/dataone/node.properties";
// Settings.augmentConfiguration(nodeProperties);
// String certificateDirectory = Settings.getConfiguration().getString("D1Client.certificate.directory");
// String certificateFilename = Settings.getConfiguration().getString("D1Client.certificate.filename");
// String certificateLocation = certificateDirectory + File.separator + certificateFilename;
// CertificateManager.getInstance().setCertificateLocation(certificateLocation);
// Subject subject = ClientIdentityManager.getCurrentIdentity();
// session = new Session();
// session.setSubject(subject);
// } catch (Exception e) {
// ServiceFailure sf = new ServiceFailure("000", e.getMessage());
// sf.initCause(e);
// throw sf;
// NOTE: if session is null at this point, we are default to whatever CertificateManager has
// which may not be the original user from the web
return session;
}
private static void debugHeaders(HttpServletRequest request) {
Enumeration<String> headers = request.getHeaderNames();
while (headers.hasMoreElements()) {
String name = (String) headers.nextElement();
String value = request.getHeader(name);
log.debug("Header: " + name + "=" + value);
//System.out.println("Header: " + name + "=" + value);
}
}
private String getResource(HttpServletRequest request) {
// get the resource
String resource = request.getPathInfo();
resource = resource.substring(resource.indexOf("/") + 1);
return resource;
}
/**
* Initalize servlet by setting logger
*/
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
/** Handle "GET" method requests from HTTP clients */
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
log.debug("HTTP Verb: GET");
String resource = this.getResource(request);
AnnotatorStore as = null;
try {
as = new JsonAnnotatorStore(getSession(request));
} catch (BaseException e) {
throw new ServletException(e);
}
if (resource.startsWith("annotations/")) {
String id = request.getPathInfo().substring(request.getPathInfo().lastIndexOf("/") + 1);
try {
String result = as.read(id);
IOUtils.write(result, response.getOutputStream());
return;
} catch (Exception e) {
throw new ServletException(e);
}
}
// handle listing them
if (resource.startsWith("annotations")) {
try {
String result = as.index();
IOUtils.write(result, response.getOutputStream());
return;
} catch (Exception e) {
throw new ServletException(e);
}
}
// handle searching them
if (resource.startsWith("search")) {
String query = request.getQueryString();
try {
String result = as.search(query);
IOUtils.write(result, response.getOutputStream());
return;
} catch (Exception e) {
e.printStackTrace();
throw new ServletException(e);
}
}
// handle token request
if (resource.startsWith("token")) {
String token = "";
// generate a token for this user based on information in the request
try {
X509Certificate certificate = PortalCertificateManager.getInstance().getCertificate(request);
if (certificate != null) {
String userId = CertificateManager.getInstance().getSubjectDN(certificate);
String fullName = null;
SubjectInfo subjectInfo = CertificateManager.getInstance().getSubjectInfo(certificate);
if (subjectInfo != null) {
fullName = subjectInfo.getPerson(0).getFamilyName();
if (subjectInfo.getPerson(0).getGivenNameList() != null && subjectInfo.getPerson(0).getGivenNameList().size() > 0) {
fullName = subjectInfo.getPerson(0).getGivenName(0) + fullName;
}
}
token = TokenGenerator.getInstance().getJWT(userId, fullName);
// make sure we keep the cookie on the reponse
Cookie cookie = PortalCertificateManager.getInstance().getCookie(request);
String identifier = cookie.getValue();
PortalCertificateManager.getInstance().setCookie(identifier, response);
}
response.getWriter().print(token);
return;
} catch (Exception e) {
e.printStackTrace();
throw new ServletException(e);
}
}
}
/** Handle "POST" method requests from HTTP clients */
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
log.debug("HTTP Verb: POST");
AnnotatorStore as = null;
try {
as = new JsonAnnotatorStore(getSession(request));
} catch (BaseException e) {
throw new ServletException(e);
}
String resource = this.getResource(request);
if (resource.equals("annotations")) {
try {
// get the annotation from the request
InputStream is = request.getInputStream();
String annotationContent = IOUtils.toString(is, "UTF-8");
// create it on the node
String id = as.create(annotationContent);
// TODO: determine which is the correct approach for responding to CREATE
// redirect to read?
boolean redirect = false;
if (redirect) {
response.setStatus(303);
response.sendRedirect(request.getRequestURI() + "/" + id);
} else {
response.setStatus(200);
// write it back in the response
annotationContent = as.read(id);
IOUtils.write(annotationContent, response.getOutputStream());
}
} catch (Exception e) {
throw new ServletException(e);
}
}
}
/** Handle "DELETE" method requests from HTTP clients */
@Override
protected void doDelete(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
log.debug("HTTP Verb: DELETE");
AnnotatorStore as = null;
try {
as = new JsonAnnotatorStore(getSession(request));
} catch (BaseException e) {
throw new ServletException(e);
}
String resource = this.getResource(request);
if (resource.startsWith("annotations/")) {
String id = request.getPathInfo().substring(request.getPathInfo().lastIndexOf("/") + 1);
try {
// delete the annotation
as.delete(id);
// say no content
response.setContentLength(0);
response.setStatus(204);
} catch (Exception e) {
throw new ServletException(e);
}
}
}
/** Handle "PUT" method requests from HTTP clients */
@Override
protected void doPut(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
log.debug("HTTP Verb: PUT");
AnnotatorStore as = null;
try {
as = new JsonAnnotatorStore(getSession(request));
} catch (BaseException e) {
throw new ServletException(e);
}
String resource = this.getResource(request);
if (resource.startsWith("annotations/")) {
try {
String id = request.getPathInfo().substring(request.getPathInfo().lastIndexOf("/") + 1);
// get the annotation from the request
InputStream is = request.getInputStream();
// update it on the node
String result = as.update(id, IOUtils.toString(is, "UTF-8"));
// redirect to read?
boolean redirect = false;
if (redirect) {
response.setStatus(303);
response.sendRedirect(request.getRequestURI() + "/" + id);
} else {
response.setStatus(200);
// write it back in the response
IOUtils.write(result, response.getOutputStream());
}
} catch (Exception e) {
throw new ServletException(e);
}
}
}
/** Handle "HEAD" method requests from HTTP clients */
@Override
protected void doHead(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
log.debug("HTTP Verb: HEAD");
}
}
|
package de.longri.cachebox3.utils;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import de.longri.cachebox3.callbacks.GenericCallBack;
import de.longri.cachebox3.interfaces.ProgressCancelRunnable;
import de.longri.cachebox3.utils.exceptions.CancelException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.channels.FileChannel;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnZip {
private final Logger log = LoggerFactory.getLogger(UnZip.class);
/**
* Extract the given ZIP-File
*
* @param zipFile file to extract
* @return Extracted Folder Path as String
* @throws IOException with IO error
*/
public FileHandle extractFolder(FileHandle zipFile) throws IOException {
String path = zipFile.file().getAbsolutePath();
String resultPath = extractFolder(path);
return Gdx.files.absolute(resultPath);
}
/**
* Extract the given ZIP-File
*
* @param zipFile file to extract
* @return Extracted Folder Path as String
* @throws IOException with IO error
*/
public FileHandle extractFolder(FileHandle zipFile, GenericCallBack<Double> progressCallBack) throws IOException {
String path = zipFile.file().getAbsolutePath();
String resultPath = extractFolder(path, progressCallBack, null);
return Gdx.files.absolute(resultPath);
}
/**
* @param zipFile file to extract
* attention in ACB2 the default is here == true
* @return Extracted Folder Path as String
* @throws IOException with IO error
*/
public String extractFolder(String zipFile) throws IOException {
return extractFolder(zipFile, null, null);
}
// /**
// * Extract the given ZIP-File
// *
// * @param zipFile file to extract
// * @param here true: extract into the path where the zipfile is <br>
// * false: extract into new path with the name of the zipfile (without extension)
// * @return Extracted Folder Path as String
// * @throws IOException with IO error
// */
// public String extractFolder(String zipFile, boolean here) throws IOException {
// log.debug("extract => " + zipFile);
// int BUFFER = 2048;
// File file = new File(zipFile);
// ZipFile zip = new ZipFile(file.getAbsolutePath());
// String newPath = zipFile.substring(0, zipFile.length() - 4);
// if (here) {
// newPath = file.getParent();
// } else {
// new File(newPath).mkdir();
// Enumeration<?> zipFileEntries = zip.entries();
// // Process each entry
// while (zipFileEntries.hasMoreElements()) {
// // grab a zip file entry
// ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
// String currentEntry = entry.getName();
// File destFile = new File(newPath, currentEntry);
// // destFile = FileFactory.createFile(newPath, destFile.getName());
// File destinationParent = destFile.getParentFile();
// // create the parent directory structure if needed
// destinationParent.mkdirs();
// destinationParent.setLastModified(entry.getTime()); // set original Datetime to be able to import ordered oldest first
// if (!entry.isDirectory()) {
// BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry));
// int currentByte;
// // establish buffer for writing file
// byte data[] = new byte[BUFFER];
// // write the current file to disk
// FileOutputStream fos = new FileOutputStream(destFile);
// BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER);
// // read and write until last byte is encountered
// while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
// dest.write(data, 0, currentByte);
// dest.flush();
// dest.close();
// is.close();
// destFile.setLastModified(entry.getTime()); // set original Datetime to be able to import ordered oldest first
// if (currentEntry.endsWith(".zip")) {
// // found a zip file, try to open
// extractFolder(destFile.getAbsolutePath());
// zip.close();
// return newPath;
public FileHandle extractFolder(FileHandle zipFile, final ProgressCancelRunnable progressCancelRunnable) throws IOException {
progressCancelRunnable.getIsCanceledAtomic();
final CharSequence msg = progressCancelRunnable.getProgressMsg();
return extractFolder(zipFile, new GenericCallBack<Double>() {
@Override
public void callBack(Double value) {
progressCancelRunnable.setProgress(value.floatValue(), msg);
}
});
}
public String extractFolder(FileHandle fileHandle, GenericCallBack<Double> progressCallBack, AtomicBoolean atomicCancel) throws IOException, CancelException {
return extractFolder(fileHandle.file().getAbsolutePath(), progressCallBack, atomicCancel);
}
public String extractFolder(String file, GenericCallBack<Double> progressCallBack, AtomicBoolean atomicCancel) throws IOException, CancelException {
String newPath = file.substring(0, file.length() - 4);
File folder = new File(newPath);
File zipfile = new File(file);
FileInputStream is = new FileInputStream(zipfile.getCanonicalFile());
FileChannel channel = is.getChannel();
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze = null;
try {
while ((ze = zis.getNextEntry()) != null && ((atomicCancel != null && !atomicCancel.get())) || atomicCancel == null) {
File f = new File(folder.getCanonicalPath(), ze.getName());
if (ze.isDirectory()) {
f.mkdirs();
continue;
}
f.getParentFile().mkdirs();
OutputStream fos = new BufferedOutputStream(new FileOutputStream(f));
try {
try {
final byte[] buf = new byte[1024 * 1024];
int bytesRead;
long nread = 0L;
long length = zipfile.length();
while (-1 != (bytesRead = zis.read(buf)) && ((atomicCancel != null && !atomicCancel.get())) || atomicCancel == null) {
fos.write(buf, 0, bytesRead);
nread += bytesRead;
if (progressCallBack != null) {
progressCallBack.callBack(((double) length / (double) channel.position()) * 100.0);
}
}
} finally {
fos.close();
}
} catch (final IOException ioe) {
f.delete();
throw ioe;
}
}
} finally {
zis.close();
}
return newPath;
}
}
|
package bisq.core.api;
import bisq.core.api.model.AddressBalanceInfo;
import bisq.core.monetary.Price;
import bisq.core.offer.Offer;
import bisq.core.offer.OfferPayload;
import bisq.core.payment.PaymentAccount;
import bisq.core.trade.handlers.TransactionResultHandler;
import bisq.core.trade.statistics.TradeStatistics2;
import bisq.core.trade.statistics.TradeStatisticsManager;
import bisq.common.app.Version;
import org.bitcoinj.core.Coin;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
/**
* Provides high level interface to functionality of core Bisq features.
* E.g. useful for different APIs to access data of different domains of Bisq.
*/
@Singleton
@Slf4j
public class CoreApi {
private final CoreDisputeAgentsService coreDisputeAgentsService;
private final CoreOffersService coreOffersService;
private final CorePaymentAccountsService paymentAccountsService;
private final CorePriceService corePriceService;
private final CoreWalletsService walletsService;
private final TradeStatisticsManager tradeStatisticsManager;
@Inject
public CoreApi(CoreDisputeAgentsService coreDisputeAgentsService,
CoreOffersService coreOffersService,
CorePaymentAccountsService paymentAccountsService,
CorePriceService corePriceService,
CoreWalletsService walletsService,
TradeStatisticsManager tradeStatisticsManager) {
this.coreDisputeAgentsService = coreDisputeAgentsService;
this.coreOffersService = coreOffersService;
this.corePriceService = corePriceService;
this.paymentAccountsService = paymentAccountsService;
this.walletsService = walletsService;
this.tradeStatisticsManager = tradeStatisticsManager;
}
@SuppressWarnings("SameReturnValue")
public String getVersion() {
return Version.VERSION;
}
// Dispute Agents
public void registerDisputeAgent(String disputeAgentType, String registrationKey) {
coreDisputeAgentsService.registerDisputeAgent(disputeAgentType, registrationKey);
}
// Offers
public List<Offer> getOffers(String direction, String currencyCode) {
return coreOffersService.getOffers(direction, currencyCode);
}
public Offer createOffer(String currencyCode,
String directionAsString,
String priceAsString,
boolean useMarketBasedPrice,
double marketPriceMargin,
long amountAsLong,
long minAmountAsLong,
double buyerSecurityDeposit,
String paymentAccountId,
TransactionResultHandler resultHandler) {
return coreOffersService.createOffer(currencyCode,
directionAsString,
priceAsString,
useMarketBasedPrice,
marketPriceMargin,
amountAsLong,
minAmountAsLong,
buyerSecurityDeposit,
paymentAccountId,
resultHandler);
}
public Offer createOffer(String offerId,
String currencyCode,
OfferPayload.Direction direction,
Price price,
boolean useMarketBasedPrice,
double marketPriceMargin,
Coin amount,
Coin minAmount,
double buyerSecurityDeposit,
PaymentAccount paymentAccount,
boolean useSavingsWallet,
TransactionResultHandler resultHandler) {
return coreOffersService.createOffer(offerId,
currencyCode,
direction,
price,
useMarketBasedPrice,
marketPriceMargin,
amount,
minAmount,
buyerSecurityDeposit,
paymentAccount,
useSavingsWallet,
resultHandler);
}
// PaymentAccounts
public void createPaymentAccount(String paymentMethodId,
String accountName,
String accountNumber,
String currencyCode) {
paymentAccountsService.createPaymentAccount(paymentMethodId,
accountName,
accountNumber,
currencyCode);
}
public Set<PaymentAccount> getPaymentAccounts() {
return paymentAccountsService.getPaymentAccounts();
}
// Prices
public double getMarketPrice(String currencyCode) {
return corePriceService.getMarketPrice(currencyCode);
}
// Wallets
public long getAvailableBalance() {
return walletsService.getAvailableBalance();
}
public long getAddressBalance(String addressString) {
return walletsService.getAddressBalance(addressString);
}
public AddressBalanceInfo getAddressBalanceInfo(String addressString) {
return walletsService.getAddressBalanceInfo(addressString);
}
public List<AddressBalanceInfo> getFundingAddresses() {
return walletsService.getFundingAddresses();
}
public void setWalletPassword(String password, String newPassword) {
walletsService.setWalletPassword(password, newPassword);
}
public void lockWallet() {
walletsService.lockWallet();
}
public void unlockWallet(String password, long timeout) {
walletsService.unlockWallet(password, timeout);
}
public void removeWalletPassword(String password) {
walletsService.removeWalletPassword(password);
}
public List<TradeStatistics2> getTradeStatistics() {
return new ArrayList<>(tradeStatisticsManager.getObservableTradeStatisticsSet());
}
public int getNumConfirmationsForMostRecentTransaction(String addressString) {
return walletsService.getNumConfirmationsForMostRecentTransaction(addressString);
}
}
|
package org.mitre.synthea.world.concepts;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.mitre.synthea.export.Exporter;
import org.mitre.synthea.helpers.Config;
import org.mitre.synthea.helpers.SimpleCSV;
import org.mitre.synthea.helpers.Utilities;
import org.mitre.synthea.world.agents.Person;
/**
* BirthStatistics determines when a mother will give birth, the sex of
* the baby, and the newborn height and weight.
*/
public class BirthStatistics {
public static final String BIRTH_WEEK = "pregnancy_birth_week";
public static final String BIRTH_DATE = "pregnancy_birth_date";
public static final String BIRTH_WEIGHT = "pregnancy_birth_weight";
public static final String BIRTH_HEIGHT = "pregnancy_birth_height";
public static final String BIRTH_SEX = "pregnancy_birth_sex";
/** Default birth weight. */
public static final double DEFAULT_WEIGHT = 3.5; // kilograms (kg)
/** Default birth height. */
public static final double DEFAULT_HEIGHT = 51.0; // centimeters (cm)
private static final boolean LOG_OUTPUT = Boolean.parseBoolean(
Config.get("generate.birthweights.logging", "false"));
private static FileWriter OUTPUT = openFile();
private static FileWriter openFile() {
FileWriter fw = null;
if (LOG_OUTPUT) {
try {
File output = Exporter.getOutputFolder("", null);
output.mkdirs();
Path outputDirectory = output.toPath();
File file = outputDirectory.resolve("birth_statistics.csv").toFile();
fw = new FileWriter(file);
} catch (IOException e) {
System.err.println("Failed to open birth statistics report file!");
e.printStackTrace();
}
}
return fw;
}
private static List<? extends Map<String,String>> WEIGHT_DATA = loadData();
private static List<? extends Map<String,String>> loadData() {
String filename = Config.get("generate.birthweights.default_file");
List<? extends Map<String,String>> csv = null;
try {
String resource = Utilities.readResource(filename);
csv = SimpleCSV.parse(resource);
} catch (Exception e) {
System.err.println("Failed to load default birth weight file!");
e.printStackTrace();
}
return csv;
}
/**
* Clear birth statistics of mothers newborn. Call this method
* after the mother gives birth.
* @param mother The baby's mother.
*/
public static void clearBirthStatistics(Person mother) {
mother.attributes.remove(BIRTH_DATE);
mother.attributes.remove(BIRTH_HEIGHT);
mother.attributes.remove(BIRTH_SEX);
mother.attributes.remove(BIRTH_WEEK);
mother.attributes.remove(BIRTH_WEIGHT);
}
/**
* Sets attributes on the mother on when her baby will be born,
* the baby sex, and the birth height and weight.
* <p/>
* These attributes will be overridden on subsequent pregnancies.
* @param mother The baby's mother.
* @param time The time.
*/
public static void setBirthStatistics(Person mother, long time) {
// Ignore men, they cannot become pregnant.
if (mother.attributes.get(Person.GENDER) == "M") {
return;
}
// Ignore women who are not pregnant.
if (!mother.attributes.containsKey("pregnant")
|| ((Boolean) mother.attributes.get("pregnant")) == false) {
return;
}
// Boy or Girl?
String babySex = null;
if (mother.attributes.containsKey(BIRTH_SEX)) {
babySex = (String) mother.attributes.get(BIRTH_SEX);
} else {
if (mother.random.nextBoolean()) {
babySex = "M";
} else {
babySex = "F";
}
}
mother.attributes.put(BIRTH_SEX, babySex);
// If there was no weight data, set some default values.
if (WEIGHT_DATA == null) {
mother.attributes.put(BIRTH_WEEK, 40);
mother.attributes.put(BIRTH_HEIGHT, DEFAULT_HEIGHT);
mother.attributes.put(BIRTH_WEIGHT, DEFAULT_WEIGHT);
return;
}
// Is the mother hispanic?
boolean hispanic = isHispanic(mother);
// Set up some temporary variables...
double max = 0;
boolean rhispanic;
String rsex;
double x;
// Get the max weight of the rows...
for (Map<String, String> row : WEIGHT_DATA) {
rhispanic = Boolean.parseBoolean(row.get("hispanic_mother"));
rsex = row.get("baby_sex");
x = Double.parseDouble(row.get("sum"));
if (rhispanic == hispanic
&& rsex.equals(babySex)
&& x > max) {
max = x;
}
}
// When will the baby be born?
Map<String, String> data = null;
double roll = mother.rand(0, max);
for (Map<String, String> row : WEIGHT_DATA) {
rhispanic = Boolean.parseBoolean(row.get("hispanic_mother"));
rsex = row.get("baby_sex");
x = Double.parseDouble(row.get("sum"));
if (rhispanic == hispanic
&& rsex.equals(babySex)
&& ((x < roll) || (data == null))) {
data = row;
}
}
long week = Long.parseLong(data.get("lmp_gestational_age"));
mother.attributes.put(BIRTH_WEEK, week);
mother.attributes.put(BIRTH_DATE, (time + Utilities.convertTime("weeks", week)));
// How much will the baby weigh?
max = Double.parseDouble(data.get("weight"));
roll = mother.rand(0, max);
List<String> weights = new ArrayList<String>(data.keySet());
weights.remove("hispanic_mother");
weights.remove("baby_sex");
weights.remove("lmp_gestational_age");
weights.remove("weight");
weights.remove("sum");
weights.sort(null);
for (String weight : weights) {
x = Double.parseDouble(data.get(weight));
roll = roll - x;
x = Double.parseDouble(weight) / 1000; // convert from grams to kilograms
mother.attributes.put(BIRTH_WEIGHT, x);
if (roll < 0) {
break;
}
}
// How long will the baby be?
mother.attributes.put(BIRTH_HEIGHT, DEFAULT_HEIGHT);
// Record the statistics
if (LOG_OUTPUT) {
synchronized (OUTPUT) {
try {
OUTPUT.write("" + hispanic);
OUTPUT.write(',');
OUTPUT.write(babySex);
OUTPUT.write(',');
OUTPUT.write("" + (long) mother.attributes.get(BIRTH_WEEK));
OUTPUT.write(',');
OUTPUT.write("" + (double) mother.attributes.get(BIRTH_WEIGHT));
OUTPUT.write(System.lineSeparator());
OUTPUT.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Check whether or not the mother is hispanic.
* @param mother The baby's mother.
* @return True if the mother is hispanic, otherwise false.
*/
private static boolean isHispanic(Person mother) {
String race = (String) mother.attributes.get(Person.RACE);
String ethnicity = (String) mother.attributes.get(Person.ETHNICITY);
return (race.equalsIgnoreCase("hispanic") || ethnicity.equalsIgnoreCase("hispanic"));
}
}
|
package hudson.model;
import hudson.EnvVars;
import hudson.remoting.Callable;
import hudson.remoting.VirtualChannel;
import hudson.util.DaemonThreadFactory;
import hudson.util.RunList;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Collections;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Represents a set of {@link Executor}s on the same computer.
*
* <p>
* {@link Executor}s on one {@link Computer} are transparently interchangeable
* (that is the definition of {@link Computer}.)
*
* <p>
* This object is related to {@link Node} but they have some significant difference.
* {@link Computer} primarily works as a holder of {@link Executor}s, so
* if a {@link Node} is configured (probably temporarily) with 0 executors,
* you won't have a {@link Computer} object for it.
*
* Also, even if you remove a {@link Node}, it takes time for the corresponding
* {@link Computer} to be removed, if some builds are already in progress on that
* node.
*
* <p>
* This object also serves UI (since {@link Node} is an interface and can't have
* related side pages.)
*
* @author Kohsuke Kawaguchi
*/
public abstract class Computer implements ModelObject {
private final List<Executor> executors = new ArrayList<Executor>();
private int numExecutors;
/**
* True if Hudson shouldn't start new builds on this node.
*/
private boolean temporarilyOffline;
/**
* {@link Node} object may be created and deleted independently
* from this object.
*/
protected String nodeName;
public Computer(Node node) {
assert node.getNumExecutors()!=0 : "Computer created with 0 executors";
setNode(node);
}
/**
* Gets the channel that can be used to run a program on this computer.
*
* @return
* never null when {@link #isOffline()}==false.
*/
public abstract VirtualChannel getChannel();
/**
* If {@link #getChannel()}==null, attempts to relaunch the slave agent.
*/
public abstract void doLaunchSlaveAgent( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException;
/**
* Number of {@link Executor}s that are configured for this computer.
*
* <p>
* When this value is decreased, it is temporarily possible
* for {@link #executors} to have a larger number than this.
*/
// ugly name to let EL access this
public int getNumExecutors() {
return numExecutors;
}
/**
* Returns the {@link Node} that this computer represents.
*/
public Node getNode() {
if(nodeName==null)
return Hudson.getInstance();
return Hudson.getInstance().getSlave(nodeName);
}
public boolean isOffline() {
return temporarilyOffline || getChannel()==null;
}
/**
* Returns true if this node is marked temporarily offline by the user.
*
* <p>
* In contrast, {@link #isOffline()} represents the actual online/offline
* state. For example, this method may return false while {@link #isOffline()}
* returns true if the slave agent failed to launch.
*
* @deprecated
* You should almost always want {@link #isOffline()}.
* This method is marked as deprecated to warn people when they
* accidentally call this method.
*/
public boolean isTemporarilyOffline() {
return temporarilyOffline;
}
public void setTemporarilyOffline(boolean temporarilyOffline) {
this.temporarilyOffline = temporarilyOffline;
Hudson.getInstance().getQueue().scheduleMaintenance();
}
public String getIcon() {
if(isOffline())
return "computer-x.gif";
else
return "computer.gif";
}
public String getDisplayName() {
return nodeName;
}
public String getUrl() {
return "computer/"+getDisplayName()+"/";
}
/**
* Returns projects that are tied on this node.
*/
public List<Project> getTiedJobs() {
List<Project> r = new ArrayList<Project>();
for( Project p : Hudson.getInstance().getProjects() ) {
if(p.getAssignedNode()==getNode())
r.add(p);
}
return r;
}
/**
* Called to notify {@link Computer} that its corresponding {@link Node}
* configuration is updated.
*/
protected void setNode(Node node) {
assert node!=null;
if(node instanceof Slave)
this.nodeName = node.getNodeName();
else
this.nodeName = null;
setNumExecutors(node.getNumExecutors());
}
/**
* Called to notify {@link Computer} that it will be discarded.
*/
protected void kill() {
setNumExecutors(0);
}
private synchronized void setNumExecutors(int n) {
this.numExecutors = n;
// send signal to all idle executors to potentially kill them off
for( Executor e : executors )
if(e.getCurrentBuild()==null)
e.interrupt();
// if the number is increased, add new ones
while(executors.size()<numExecutors)
executors.add(new Executor(this));
}
/**
* Returns the number of idle {@link Executor}s that can start working immediately.
*/
public synchronized int countIdle() {
int n = 0;
for (Executor e : executors) {
if(e.isIdle())
n++;
}
return n;
}
/**
* Gets the read-only view of all {@link Executor}s.
*/
public synchronized List<Executor> getExecutors() {
return new ArrayList<Executor>(executors);
}
/**
* Called by {@link Executor} to kill excessive executors from this computer.
*/
/*package*/ synchronized void removeExecutor(Executor e) {
executors.remove(e);
if(executors.isEmpty())
Hudson.getInstance().removeComputer(this);
}
/**
* Interrupt all {@link Executor}s.
*/
public synchronized void interrupt() {
for (Executor e : executors) {
e.interrupt();
}
}
/**
* Gets the system properties of the JVM on this computer.
* If this is the master, it returns the system property of the master computer.
*/
public Map<Object,Object> getSystemProperties() throws IOException, InterruptedException {
return getChannel().call(new GetSystemProperties());
}
private static final class GetSystemProperties implements Callable<Map<Object,Object>,RuntimeException> {
public Map<Object,Object> call() {
return new TreeMap<Object,Object>(System.getProperties());
}
private static final long serialVersionUID = 1L;
}
/**
* Gets the environment variables of the JVM on this computer.
* If this is the master, it returns the system property of the master computer.
*/
public Map<String,String> getEnvVars() throws IOException, InterruptedException {
VirtualChannel channel = getChannel();
if(channel==null)
return Collections.singletonMap("N/A","N/A");
return channel.call(new GetEnvVars());
}
private static final class GetEnvVars implements Callable<Map<String,String>,RuntimeException> {
public Map<String,String> call() {
return new TreeMap<String,String>(EnvVars.masterEnvVars);
}
private static final long serialVersionUID = 1L;
}
protected static final ExecutorService threadPoolForRemoting = Executors.newCachedThreadPool(new DaemonThreadFactory());
public void doRssAll( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rss(req, rsp, " all builds", new RunList(getTiedJobs()));
}
public void doRssFailed( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
rss(req, rsp, " failed builds", new RunList(getTiedJobs()).failureOnly());
}
private void rss(StaplerRequest req, StaplerResponse rsp, String suffix, RunList runs) throws IOException, ServletException {
RSS.forwardToRss(getDisplayName()+ suffix, getUrl(),
runs.newBuilds(), Run.FEED_ADAPTER, req, rsp );
}
public void doToggleOffline( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
if(!Hudson.adminCheck(req,rsp))
return;
setTemporarilyOffline(!temporarilyOffline);
rsp.forwardToPreviousPage(req);
}
}
|
package org.neo4j.gis.spatial;
import java.util.List;
import org.neo4j.gis.spatial.query.SearchIntersect;
import org.neo4j.graphdb.Node;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.MultiLineString;
/**
* Creates a Network of LineStrings.
* If a LineString start point or end point is equal to some other LineString start point or end point,
* the two LineStrings are connected together with a Relationship.
*
* @author Davide Savazzi
*/
public class LineStringNetworkGenerator {
// Constructor
public LineStringNetworkGenerator(EditableLayer pointsLayer, EditableLayer edgesLayer) {
this(pointsLayer, edgesLayer, null);
}
public LineStringNetworkGenerator(EditableLayer pointsLayer, EditableLayer edgesLayer, Double buffer) {
this.pointsLayer = pointsLayer;
this.edgesLayer = edgesLayer;
this.buffer = buffer;
}
// Public methods
public void add(SpatialDatabaseRecord record) {
Geometry geometry = record.getGeometry();
if (geometry instanceof MultiLineString) {
add((MultiLineString) geometry, record);
} else if (geometry instanceof LineString) {
add((LineString) geometry, record);
} else {
// TODO better handling?
throw new IllegalArgumentException("geometry type not supported: " + geometry.getGeometryType());
}
}
public void add(MultiLineString lines) {
add(lines, null);
}
public void add(LineString line) {
add(line, null);
}
// Private methods
protected void add(MultiLineString line, SpatialDatabaseRecord record) {
for (int i = 0; i < line.getNumGeometries(); i++) {
add((LineString) line.getGeometryN(i), record);
}
}
protected void add(LineString line, SpatialDatabaseRecord edge) {
if (edge == null) {
edge = edgesLayer.add(line);
}
// TODO reserved property?
edge.setProperty("_network_length", edge.getGeometry().getLength());
addEdgePoint(edge.getGeomNode(), line.getStartPoint());
addEdgePoint(edge.getGeomNode(), line.getEndPoint());
}
protected void addEdgePoint(Node edge, Geometry edgePoint) {
if (buffer != null) edgePoint = edgePoint.buffer(buffer.doubleValue());
Search search = new SearchIntersect(edgePoint);
pointsLayer.getIndex().executeSearch(search);
List<SpatialDatabaseRecord> results = search.getResults();
if (results.size() == 0) {
SpatialDatabaseRecord point = pointsLayer.add(edgePoint);
edge.createRelationshipTo(point.getGeomNode(), SpatialRelationshipTypes.NETWORK);
} else {
for (SpatialDatabaseRecord point : results) {
edge.createRelationshipTo(point.getGeomNode(), SpatialRelationshipTypes.NETWORK);
}
}
}
// Attributes
private EditableLayer pointsLayer;
private EditableLayer edgesLayer;
private Double buffer;
}
|
package hudson.util;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.ListIterator;
import java.util.AbstractList;
import java.util.Arrays;
/**
* Varios {@link Iterator} implementations.
*
* @author Kohsuke Kawaguchi
* @see AdaptedIterator
*/
public class Iterators {
/**
* Returns the empty iterator.
*/
public static <T> Iterator<T> empty() {
return Collections.<T>emptyList().iterator();
}
/**
* Produces {A,B,C,D,E,F} from {{A,B},{C},{},{D,E,F}}.
*/
public static abstract class FlattenIterator<U,T> implements Iterator<U> {
private final Iterator<? extends T> core;
private Iterator<U> cur;
protected FlattenIterator(Iterator<? extends T> core) {
this.core = core;
cur = Collections.<U>emptyList().iterator();
}
protected FlattenIterator(Iterable<? extends T> core) {
this(core.iterator());
}
protected abstract Iterator<U> expand(T t);
public boolean hasNext() {
while(!cur.hasNext()) {
if(!core.hasNext())
return false;
cur = expand(core.next());
}
return true;
}
public U next() {
if(!hasNext()) throw new NoSuchElementException();
return cur.next();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
/**
* Creates a filtered view of another iterator.
*
* @since 1.150
*/
public static abstract class FilterIterator<T> implements Iterator<T> {
private final Iterator<? extends T> core;
private T next;
private boolean fetched;
protected FilterIterator(Iterator<? extends T> core) {
this.core = core;
}
protected FilterIterator(Iterable<? extends T> core) {
this(core.iterator());
}
private void fetch() {
while(!fetched && core.hasNext()) {
T n = core.next();
if(filter(n)) {
next = n;
fetched = true;
}
}
}
/**
* Filter out items in the original collection.
*
* @return
* true to leave this item and return this item from this iterator.
* false to hide this item.
*/
protected abstract boolean filter(T t);
public boolean hasNext() {
fetch();
return fetched;
}
public T next() {
fetch();
if(!fetched) throw new NoSuchElementException();
fetched = false;
return next;
}
public void remove() {
core.remove();
}
}
/**
* Returns the {@link Iterable} that lists items in the reverse order.
*
* @since 1.150
*/
public static <T> Iterable<T> reverse(final List<T> lst) {
return new Iterable<T>() {
public Iterator<T> iterator() {
final ListIterator<T> itr = lst.listIterator(lst.size());
return new Iterator<T>() {
public boolean hasNext() {
return itr.hasPrevious();
}
public T next() {
return itr.previous();
}
public void remove() {
itr.remove();
}
};
}
};
}
/**
* Returns a list that represents [start,end).
*
* For example sequence(1,5,1)={1,2,3,4}, and sequence(7,1,-2)={7.5,3}
*
* @since 1.150
*/
public static List<Integer> sequence(final int start, int end, final int step) {
final int size = (end-start)/step;
if(size<0) throw new IllegalArgumentException("List size is negative");
return new AbstractList<Integer>() {
public Integer get(int index) {
if(index<0 || index>=size)
throw new IndexOutOfBoundsException();
return start+index*step;
}
public int size() {
return size;
}
};
}
public static List<Integer> sequence(int start, int end) {
return sequence(start,end,1);
}
/**
* The short cut for {@code reverse(sequence(start,end,step))}.
*
* @since 1.150
*/
public static List<Integer> reverseSequence(int start, int end, int step) {
return sequence(end-1,start-1,-step);
}
public static List<Integer> reverseSequence(int start, int end) {
return reverseSequence(start,end,1);
}
/**
* Casts {@link Iterator} by taking advantage of its covariant-ness.
*/
@SuppressWarnings({"unchecked"})
public static <T> Iterator<T> cast(Iterator<? extends T> itr) {
return (Iterator)itr;
}
/**
* Casts {@link Iterable} by taking advantage of its covariant-ness.
*/
@SuppressWarnings({"unchecked"})
public static <T> Iterable<T> cast(Iterable<? extends T> itr) {
return (Iterable)itr;
}
/**
* Returns an {@link Iterator} that only returns items of the given subtype.
*/
@SuppressWarnings({"unchecked"})
public static <T extends U,U> Iterator<T> subType(Iterator<U> itr, final Class<T> type) {
return (Iterator)new FilterIterator<U>(itr) {
protected boolean filter(U u) {
return type.isInstance(u);
}
};
}
/**
* Creates a read-only mutator that disallows {@link Iterator#remove()}.
*/
public static <T> Iterator<T> readOnly(final Iterator<T> itr) {
return new Iterator<T>() {
public boolean hasNext() {
return itr.hasNext();
}
public T next() {
return itr.next();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
/**
* Returns an {@link Iterable} that iterates over all the given {@link Iterable}s.
*
* <p>
* That is, this creates {A,B,C,D} from {A,B},{C,D}.
*/
public static <T> Iterable<T> sequence( final Iterable<? extends T>... iterables ) {
return new Iterable<T>() {
public Iterator<T> iterator() {
return new FlattenIterator<T,Iterable<? extends T>>(Arrays.asList(iterables)) {
protected Iterator<T> expand(Iterable<? extends T> iterable) {
return cast(iterable).iterator();
}
};
}
};
}
}
|
package Subsystem.Swerve;
import MathObject.O_Point;
import Robot.CommandBase;
import Robot.OI;
import MathObject.O_Vector;
import com.sun.squawk.util.MathUtils;
/**
*
* @author 1218
*/
public class C_Swerve extends CommandBase {
public C_Swerve() {
requires(swerve);
}
protected void initialize() {
}
protected void execute() {
if (!OI.leftThumbClick.get())
{
boolean shouldRunTwist = true;
if (OI.joystick1.getRawAxis(3) > 0.4) //back left button, front left wheel
{
System.out.println("turning of front left wheel");
swerve.swerve(new O_Vector(0, 0), new O_Point(1,-1), (float)OI.joystick1.getRawAxis(4));
shouldRunTwist = false;
}
if (OI.joystick1.getRawAxis(3) < -0.4) //back right button, front right wheel
{
System.out.println("turning of front right wheel");
swerve.swerve(new O_Vector(0, 0), new O_Point(1,1), (float)OI.joystick1.getRawAxis(4));
shouldRunTwist = false;
}
if (OI.R1.get())//back right wheel
{
System.out.println("turning of back right wheel");
swerve.swerve(new O_Vector(0, 0), new O_Point(-1,1), -1*(float)OI.joystick1.getRawAxis(4));
shouldRunTwist = false;
}
if (OI.L1.get()) //back left wheel
{
System.out.println("turning of back left wheel");
swerve.swerve(new O_Vector(0, 0), new O_Point(-1,-1), -1*(float)OI.joystick1.getRawAxis(4));
shouldRunTwist = false;
}
if (shouldRunTwist)
{
System.out.println("swerve twisting");
swerve.swerve(new O_Vector(-(float)OI.joystick1.getY(), (float)OI.joystick1.getX()), new O_Point(0,0), -1*(float)OI.joystick1.getRawAxis(4));
}
}
else
{
//snake mode
System.out.println("snake mode");
swerve.swerve(new O_Vector(0, 0), new O_Point(0, 1/((float)OI.joystick1.getRawAxis(4) + 0.02f )), (float)OI.joystick1.getY() * getSin(OI.joystick1.getRawAxis(4)));
}
}
float getSin(double value)
{
if (value >= 0)
{
return 1;
}
else
{
return -1;
}
}
protected boolean isFinished() {
return false;
}
protected void end() {
}
protected void interrupted() {
}
}
|
package org.opentosca.csarrepo.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.opentosca.csarrepo.exception.AuthenticationException;
import org.opentosca.csarrepo.service.CreateUserService;
/**
* Implementation of the creation of an user
*
* @author Thomas Kosch, (mail@thomaskosch.com)
*
*/
@SuppressWarnings("serial")
@WebServlet(CreateUserServlet.PATH)
public class CreateUserServlet extends AbstractServlet {
private static final Logger LOGGER = LogManager.getLogger(CreateUserServlet.class);
private static final String NAME = "name";
private static final String PASSWORD = "password";
private static final String MAIL = "mail";
public static final String PATH = "/createuser";
public CreateUserServlet() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendError(405, "Method Not Allowed");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
try {
this.checkUserAuthentication(request, response);
String name = request.getParameter(NAME);
String password = request.getParameter(PASSWORD);
String mail = request.getParameter(MAIL);
CreateUserService createUserService = new CreateUserService(name, mail, password);
LOGGER.debug("Creating new User " + name + "...");
if (createUserService.hasErrors()) {
this.addErrors(request, createUserService.getErrors());
}
this.redirect(request, response, ListUserServlet.PATH);
} catch (AuthenticationException e) {
response.getWriter().print(e.getMessage());
return;
}
}
}
|
package org.wildfly.swarm.plugin.process;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.jboss.shrinkwrap.descriptor.api.Descriptors;
import org.jboss.shrinkwrap.descriptor.api.jbossmodule15.ArtifactType;
import org.jboss.shrinkwrap.descriptor.api.jbossmodule15.DependenciesType;
import org.jboss.shrinkwrap.descriptor.api.jbossmodule15.FilterType;
import org.jboss.shrinkwrap.descriptor.api.jbossmodule15.ModuleDependencyType;
import org.jboss.shrinkwrap.descriptor.api.jbossmodule15.ModuleDescriptor;
import org.jboss.shrinkwrap.descriptor.api.jbossmodule15.PathSetType;
import org.jboss.shrinkwrap.descriptor.api.jbossmodule15.ResourcesType;
import org.jboss.shrinkwrap.descriptor.api.jbossmodule15.SystemDependencyType;
import org.wildfly.swarm.plugin.FractionMetadata;
/**
* @author Bob McWhirter
*/
public class ModuleGenerator implements Function<FractionMetadata, FractionMetadata> {
private static final String RUNTIME = "runtime";
private static final String MAIN = "main";
private static final String DEPLOYMENT = "deployment";
private static final String DETECT = "detect";
private static final String MODULE_XML = "module.xml";
private final Log log;
private final MavenProject project;
public ModuleGenerator(Log log,
MavenProject project) {
this.log = log;
this.project = project;
}
@Override
public FractionMetadata apply(FractionMetadata meta) {
if (meta.hasModuleConf()) {
Path moduleConf = meta.getModuleConf();
List<String> dependencies;
try (BufferedReader reader = new BufferedReader(new FileReader(moduleConf.toFile()))) {
dependencies = reader.lines()
.map(String::trim)
.filter(line -> !line.startsWith("
.collect(Collectors.toList());
generate(meta.getBaseModulePath(), dependencies);
} catch (IOException e) {
this.log.error(e.getMessage(), e);
}
}
return meta;
}
private void generate(Path root, List<String> dependencies) throws IOException {
String moduleName = root.toString().replace(File.separatorChar, '.');
Path outputDir = Paths.get(this.project.getBuild().getOutputDirectory(), "modules");
Path runtimeModuleXml = outputDir.resolve(root).resolve(Paths.get(RUNTIME, MODULE_XML));
Path apiModuleXml = outputDir.resolve(root).resolve(Paths.get("api", MODULE_XML));
Path mainModuleXml = outputDir.resolve(root).resolve(Paths.get(MAIN, MODULE_XML));
Path deploymentModuleXml = outputDir.resolve(root).resolve(Paths.get(DEPLOYMENT, MODULE_XML));
Set<String> apiPaths = determineApiPaths();
Set<String> runtimePaths = determineRuntimePaths();
Set<String> deploymentPaths = determineDeploymentPaths();
// -- runtime
ModuleDescriptor runtimeModule = Descriptors.create(ModuleDescriptor.class);
runtimeModule
.name(moduleName)
.slot(RUNTIME);
ArtifactType<ResourcesType<ModuleDescriptor>> runtimeArtifact = runtimeModule.getOrCreateResources().createArtifact();
runtimeArtifact.name(this.project.getGroupId() + ":" + this.project.getArtifactId() + ":" + this.project.getVersion());
PathSetType<FilterType<ArtifactType<ResourcesType<ModuleDescriptor>>>> runtimeExcludeSet = runtimeArtifact.getOrCreateFilter()
.createExcludeSet();
for (String path : apiPaths) {
runtimeExcludeSet.createPath().name(path);
}
for (String path : deploymentPaths) {
runtimeExcludeSet.createPath().name(path);
}
runtimeModule.getOrCreateDependencies()
.createModule().name(moduleName).slot(MAIN).export(true);
runtimeModule.getOrCreateDependencies()
.createModule().name("org.wildfly.swarm.bootstrap").optional(true).up()
.createModule().name("org.wildfly.swarm.container").slot(RUNTIME).up()
.createModule().name("org.wildfly.swarm.spi").slot(RUNTIME).up();
runtimeModule.getOrCreateDependencies()
.createModule()
.name("javax.enterprise.api");
runtimeModule.getOrCreateDependencies()
.createModule()
.name("org.jboss.weld.se");
addDependencies(runtimeModule, dependencies);
// -- api
ModuleDescriptor apiModule = Descriptors.create(ModuleDescriptor.class);
apiModule.name(moduleName).slot("api");
ArtifactType<ResourcesType<ModuleDescriptor>> apiArtifact = apiModule.getOrCreateResources().createArtifact();
apiArtifact.name(this.project.getGroupId() + ":" + this.project.getArtifactId() + ":" + this.project.getVersion());
PathSetType<FilterType<ArtifactType<ResourcesType<ModuleDescriptor>>>> apiIncludeSet = apiArtifact.getOrCreateFilter()
.createIncludeSet();
for (String path : apiPaths) {
apiIncludeSet.createPath().name(path);
}
apiIncludeSet.createPath().name("META-INF");
PathSetType<FilterType<ArtifactType<ResourcesType<ModuleDescriptor>>>> apiExcludeSet = apiArtifact.getOrCreateFilter()
.createExcludeSet();
for (String path : runtimePaths) {
apiExcludeSet.createPath().name(path);
}
for (String path : deploymentPaths) {
apiExcludeSet.createPath().name(path);
}
apiModule.getOrCreateDependencies()
.createModule()
.name("org.wildfly.swarm.container");
apiModule.getOrCreateDependencies()
.createModule()
.name("javax.enterprise.api");
apiModule.getOrCreateDependencies()
.createModule()
.name("org.jboss.weld.se");
addDependencies(apiModule, dependencies);
// -- main
ModuleDescriptor mainModule = Descriptors.create(ModuleDescriptor.class);
mainModule.name(moduleName).slot(MAIN);
SystemDependencyType<DependenciesType<ModuleDescriptor>> system = mainModule.getOrCreateDependencies().createSystem();
system.export(true);
PathSetType<SystemDependencyType<DependenciesType<ModuleDescriptor>>> systemPaths = system.getOrCreatePaths();
for (String path : apiPaths) {
systemPaths.createPath().name(path);
}
ModuleDependencyType<DependenciesType<ModuleDescriptor>> depModule = mainModule.getOrCreateDependencies()
.createModule();
depModule.name(moduleName)
.slot(apiModule.getSlot())
.export(true)
.services("export");
FilterType<ModuleDependencyType<DependenciesType<ModuleDescriptor>>> imports = depModule.getOrCreateImports();
for (String path : apiPaths) {
imports.createInclude().path(path);
}
imports.getOrCreateInclude().path("**");
FilterType<ModuleDependencyType<DependenciesType<ModuleDescriptor>>> exports = depModule.getOrCreateExports();
exports.createInclude().path("**");
// -- deployment
ModuleDescriptor deploymentModule = null;
if (!deploymentPaths.isEmpty()) {
deploymentModule = Descriptors.create(ModuleDescriptor.class);
deploymentModule
.name(moduleName)
.slot(DEPLOYMENT);
ArtifactType<ResourcesType<ModuleDescriptor>> deploymentArtifact = deploymentModule.getOrCreateResources().createArtifact();
deploymentArtifact.name(this.project.getGroupId() + ":" + this.project.getArtifactId() + ":" + this.project.getVersion());
PathSetType<FilterType<ArtifactType<ResourcesType<ModuleDescriptor>>>> deploymentExcludeSet = deploymentArtifact.getOrCreateFilter()
.createExcludeSet();
for (String path : apiPaths) {
deploymentExcludeSet.createPath().name(path);
}
for (String path : runtimePaths) {
deploymentExcludeSet.createPath().name(path);
}
ModuleDependencyType<DependenciesType<ModuleDescriptor>> deploymentMainDep = deploymentModule.getOrCreateDependencies()
.createModule();
deploymentMainDep.name(moduleName)
.slot(mainModule.getSlot());
addDependencies(deploymentModule, dependencies);
}
export(mainModule, mainModuleXml);
export(apiModule, apiModuleXml);
export(runtimeModule, runtimeModuleXml);
export(deploymentModule, deploymentModuleXml);
}
private void addDependencies(ModuleDescriptor module, List<String> dependencies) {
for (String dependency : dependencies) {
dependency = dependency.trim();
if (!dependency.isEmpty()) {
boolean optional = false;
if (dependency.startsWith("*")) {
optional = true;
dependency = dependency.substring(1);
}
String services = null;
if (dependency.contains("services=export")) {
services = "export";
dependency = dependency.replace("services=export", "");
} else if (dependency.contains("services=import")) {
services = "import";
dependency = dependency.replace("services=import", "");
}
boolean isexport = false;
if (dependency.contains("export=true")) {
isexport = true;
dependency = dependency.replace("export=true", "");
}
dependency = dependency.trim();
int colonLoc = dependency.indexOf(':');
String depName;
String depSlot;
if (colonLoc < 0) {
depName = dependency;
depSlot = MAIN;
} else {
depName = dependency.substring(0, colonLoc);
depSlot = dependency.substring(colonLoc + 1);
}
ModuleDependencyType<DependenciesType<ModuleDescriptor>> moduleDep = module.getOrCreateDependencies()
.createModule()
.name(depName)
.slot(depSlot);
if (services != null) {
moduleDep.services(services);
}
if (isexport) {
moduleDep.export(isexport);
}
if (optional) {
moduleDep.optional(true);
}
}
}
}
private void export(ModuleDescriptor module, Path path) throws IOException {
if (module == null) {
log.info("Not exporting empty module: " + path);
return;
}
Files.createDirectories(path.getParent());
try (FileOutputStream out = new FileOutputStream(path.toFile())) {
module.exportTo(out);
}
}
private Set<String> determineApiPaths() throws IOException {
return determinePaths((file) -> (!(file.contains(RUNTIME) || file.contains(DEPLOYMENT) || file.contains(DETECT))));
}
private Set<String> determineRuntimePaths() throws IOException {
return determinePaths((file) -> file.contains(RUNTIME));
}
private Set<String> determineDeploymentPaths() throws IOException {
return determinePaths((file) -> file.contains(DEPLOYMENT));
}
private Set<String> determinePaths(Predicate<String> pred) throws IOException {
Path dir = Paths.get(this.project.getBuild().getOutputDirectory());
Set<String> paths = new HashSet<>();
if (Files.exists(dir)) {
FileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.getFileName().toString().endsWith(".class")) {
if (pred.test(file.toString())) {
paths.add(javaSlashize(dir.relativize(file.getParent())));
}
}
return super.visitFile(file, attrs);
}
};
Files.walkFileTree(dir, visitor);
}
return paths;
}
private String javaSlashize(Path path) {
List<String> parts = new ArrayList<>();
int numParts = path.getNameCount();
for (int i = 0; i < numParts; ++i) {
parts.add(path.getName(i).toString());
}
return String.join("/", parts);
}
}
|
package pete.metrics.adaptability.elements;
class EventElements extends ElementsCollection {
public EventElements() {
buildTopLevelStartEvents();
buildEventSubProcessStartEvents();
buildEndEvents();
buildIntermediateEvents();
}
public String buildEventXPathExpression(String event, String eventType) {
|
package pitt.search.semanticvectors.vectors;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.FixedBitSet;
/**
* Binary implementation of Vector.
*
* Uses an "elemental" representation which is a single bit string (Lucene FixedBitSet).
*
* Superposes on this a "semantic" representation which contains the weights with which different
* vectors have been added (superposed) onto this one. Calling {@link #superpose} causes the
* voting record to be updated, but for performance the votes are not tallied back into the
* elemental bit set representation until {@link #normalize} or one of the writing functions
* is called.
*
* @author Trevor Cohen
*/
public class BinaryVector implements Vector {
/**
* Enumeration of normalization options.
*/
public enum BinaryNormalizationMethod {
/**
* Set to one if more ones than zeros recorded in the voting record for
* this dimension (zeros are recorded implicitly, by counting total votes),
* and split at random (50% chance of 1) if the same number of ones and zeros.
* Otherwise zero.
*/
SPATTERCODE,
/**
* The probability of a one is equal to the probability of the proportion of 1 to 0
* votes for this dimension, assuming a Gaussian distribution
*/
PROBABILISTIC
}
public static BinaryNormalizationMethod NORMALIZE_METHOD = BinaryNormalizationMethod.SPATTERCODE;
public static void setNormalizationMethod(BinaryNormalizationMethod normalizationMethod) {
logger.info("Globally setting binary vector NORMALIZATION_METHOD to: '" + normalizationMethod + "'");
NORMALIZE_METHOD = normalizationMethod;
}
public static final Logger logger = Logger.getLogger(BinaryVector.class.getCanonicalName());
/** Returns {@link VectorType#BINARY} */
public VectorType getVectorType() { return VectorType.BINARY; }
// TODO: Determing proper interface for default constants.
/**
* Number of decimal places to consider in weighted superpositions of binary vectors.
* Higher precision requires additional memory during training.
*/
public static final int BINARY_VECTOR_DECIMAL_PLACES = 2;
public static final boolean BINARY_BINDING_WITH_PERMUTE = false;
private static int DEBUG_PRINT_LENGTH = 64;
private Random random;
private final int dimension;
/**
* Elemental representation for binary vectors.
*/
protected FixedBitSet bitSet;
private boolean isSparse;
private AtomicBoolean unTallied = new AtomicBoolean(true);
/**
* Representation of voting record for superposition. Each FixedBitSet object contains one bit
* of the count for the vote in each dimension. The count for any given dimension is derived from
* all of the bits in that dimension across the FixedBitSets in the voting record.
*
* The precision of the voting record (in number of decimal places) is defined upon initialization.
* By default, if the first weight added is an integer, rounding occurs to the nearest integer.
* Otherwise, rounding occurs to the second binary place.
*/
private ArrayList<FixedBitSet> votingRecord;
/** BINARY_VECTOR_DECIMAL_PLACESum of the weights with which vectors have been added into the voting record */
AtomicInteger totalNumberOfVotes = new AtomicInteger(0);
// TODO(widdows) Understand and comment this.
int minimum = 0;
// Used only for temporary internal storage.
private FixedBitSet tempSet;
public BinaryVector(int dimension) {
// Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks
if (dimension % 64 != 0) {
throw new IllegalArgumentException("Dimension should be a multiple of 64: "
+ dimension + " will lead to trouble!");
}
this.dimension = dimension;
this.bitSet = new FixedBitSet(dimension);
this.isSparse = true;
this.random = new Random();
}
/**
* Returns a new copy of this vector, in dense format.
*/
@SuppressWarnings("unchecked")
public BinaryVector copy() {
BinaryVector copy = new BinaryVector(dimension);
copy.bitSet = (FixedBitSet) bitSet.clone();
if (!isSparse)
copy.votingRecord = (ArrayList<FixedBitSet>) votingRecord.clone();
return copy;
}
public String toString() {
StringBuilder debugString = new StringBuilder("");
if (isSparse) {
debugString.append(" Sparse. First " + DEBUG_PRINT_LENGTH + " values are:\n");
for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(bitSet.get(x) ? "1 " : "0 ");
debugString.append("\nCardinality " + bitSet.cardinality()+"\n");
}
else {
debugString.append(" Dense. First " + DEBUG_PRINT_LENGTH + " values are:\n");
for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(bitSet.get(x) ? "1" : "0");
// output voting record for first DEBUG_PRINT_LENGTH dimension
debugString.append("\nVOTING RECORD: \n");
for (int y =0; y < votingRecord.size(); y++)
{
for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(votingRecord.get(y).get(x) ? "1 " : "0 ");
debugString.append("\n");
}
// Calculate actual values for first 20 dimension
double[] actualvals = new double[DEBUG_PRINT_LENGTH];
debugString.append("COUNTS : ");
for (int x =0; x < votingRecord.size(); x++) {
for (int y = 0; y < DEBUG_PRINT_LENGTH; y++) {
if (votingRecord.get(x).get(y)) actualvals[y] += Math.pow(2, x);
}
}
for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) {
debugString.append((int) ((minimum + actualvals[x]) / Math.pow(10, BINARY_VECTOR_DECIMAL_PLACES)) + " ");
}
// TODO - output count from first DEBUG_PRINT_LENGTH dimension
debugString.append("\nNORMALIZED: ");
this.normalize();
for (int x = 0; x < DEBUG_PRINT_LENGTH; x++) debugString.append(bitSet.get(x) + " ");
debugString.append("\n");
debugString.append("\nCardinality " + bitSet.cardinality()+"\n");
debugString.append("Votes " + totalNumberOfVotes+"\n");
debugString.append("Minimum " + minimum + "\n");
debugString.append("\n");
}
return debugString.toString();
}
@Override
public int getDimension() {
return dimension;
}
public BinaryVector createZeroVector(int dimension) {
// Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks
if (dimension % 64 != 0) {
logger.severe("Dimension should be a multiple of 64: "
+ dimension + " will lead to trouble!");
}
return new BinaryVector(dimension);
}
@Override
public boolean isZeroVector() {
if (isSparse)
{
return bitSet.cardinality() == 0;
} else {
return (votingRecord == null) || (votingRecord.size() == 0) || (votingRecord.size()==1 && votingRecord.get(0).cardinality() == 0);
}
}
@Override
/**
* Generates a basic elemental vector with a given number of 1's and otherwise 0's.
* For binary vectors, the numnber of 1's and 0's must be the same, half the dimension.
*
* @return representation of basic binary vector.
*/
public BinaryVector generateRandomVector(int dimension, int numEntries, Random random) {
// Check "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks
if (dimension % 64 != 0) {
throw new IllegalArgumentException("Dimension should be a multiple of 64: "
+ dimension + " will lead to trouble!");
}
// Check for balance between 1's and 0's
if (numEntries != dimension / 2) {
logger.severe("Attempting to create binary vector with unequal number of zeros and ones."
+ " Unlikely to produce meaningful results. Therefore, seedlength has been set to "
+ " dimension/2, as recommended for binary vectors");
numEntries = dimension / 2;
}
BinaryVector randomVector = new BinaryVector(dimension);
randomVector.bitSet = new FixedBitSet(dimension);
int testPlace = dimension - 1, entryCount = 0;
// Iterate across dimension of bitSet, changing 0 to 1 if random(1) > 0.5
// until dimension/2 1's added.
while (entryCount < numEntries) {
testPlace = random.nextInt(dimension);
if (!randomVector.bitSet.get(testPlace)) {
randomVector.bitSet.set(testPlace);
entryCount++;
}
}
return randomVector;
}
@Override
/**
* Measures overlap of two vectors using 1 - normalized Hamming distance
*
* Causes this and other vector to be converted to dense representation.
*/
public double measureOverlap(Vector other) {
IncompatibleVectorsException.checkVectorsCompatible(this, other);
if (isZeroVector()) return 0;
BinaryVector binaryOther = (BinaryVector) other;
if (binaryOther.isZeroVector()) return 0;
// Calculate hamming distance in place. Have not checked if this is fastest performance.
double hammingDistance = BinaryVectorUtils.xorCount(this.bitSet, binaryOther.bitSet);
return 2*(0.5 - (hammingDistance / (double) dimension));
}
@Override
/**
* Adds the other vector to this one. If this vector was an elemental vector, the
* "semantic vector" components (i.e. the voting record and temporary bitset) will be
* initialized.
*
* Note that the precision of the voting record (in decimal places) is decided at this point:
* if the initialization weight is an integer, rounding will occur to the nearest integer.
* If not, rounding will occur to the second decimal place.
*
* This is an attempt to save space, as voting records can be prohibitively expansive
* if not contained.
*/
public synchronized void superpose(Vector other, double weight, int[] permutation) {
IncompatibleVectorsException.checkVectorsCompatible(this, other);
if (weight == 0d) return;
if (other.isZeroVector()) return;
BinaryVector binaryOther = (BinaryVector) other;
boolean flippedBitSet = false; //for subtraction
if (weight < 0) //subtraction
{
weight = Math.abs(weight);
binaryOther.bitSet.flip(0, binaryOther.getDimension());
flippedBitSet = true;
}
if (isSparse) {
elementalToSemantic();
}
if (permutation != null) {
// Rather than permuting individual dimensions, we permute 64 bit groups at a time.
// This should be considerably quicker, and dimension/64 should allow for sufficient
// permutations
if (permutation.length != dimension / 64) {
throw new IllegalArgumentException("Binary vector of dimension " + dimension
+ " must have permutation of length " + dimension / 64
+ " not " + permutation.length);
}
//TODO permute in place and reverse, to avoid creating a new BinaryVector here
BinaryVector temp = binaryOther.copy();
temp.permute(permutation);
superposeBitSet(temp.bitSet, weight);
}
else {
superposeBitSet(binaryOther.bitSet, weight);
}
if (flippedBitSet) binaryOther.bitSet.flip(0, binaryOther.getDimension()); //return to original configuration
unTallied.set(true); //there are votes that haven't been tallied yet
}
/**
* This method is the first of two required to facilitate superposition. The underlying representation
* (i.e. the voting record) is an ArrayList of FixedBitSet, each with dimension "dimension", which can
* be thought of as an expanding 2D array of bits. Each column keeps count (in binary) for the respective
* dimension, and columns are incremented in parallel by sweeping a bitset across the rows. In any dimension
* in which the BitSet to be added contains a "1", the effect will be that 1's are changed to 0's until a
* new 1 is added (e.g. the column '110' would become '001' and so forth).
*
* The first method deals with floating point issues, and accelerates superposition by decomposing
* the task into segments.
*
* @param incomingBitSet
* @param weight
*/
protected synchronized void superposeBitSet(FixedBitSet incomingBitSet, double weight) {
// If fractional weights are used, encode all weights as integers (1000 x double value).
weight = (int) Math.round(weight * Math.pow(10, BINARY_VECTOR_DECIMAL_PLACES));
if (weight == 0) return;
// Keep track of number (or cumulative weight) of votes.
totalNumberOfVotes.set(totalNumberOfVotes.get() + (int) weight);
// Decompose superposition task such that addition of some power of 2 (e.g. 64) is accomplished
// by beginning the process at the relevant row (e.g. 7) instead of starting multiple (e.g. 64)
// superposition processes at the first row.
int logFloorOfWeight = (int) (Math.floor(Math.log(weight)/Math.log(2)));
if (logFloorOfWeight < votingRecord.size() - 1) {
while (logFloorOfWeight > 0) {
superposeBitSetFromRowFloor(incomingBitSet, logFloorOfWeight);
weight = weight - (int) Math.pow(2,logFloorOfWeight);
logFloorOfWeight = (int) (Math.floor(Math.log(weight)/Math.log(2)));
}
}
// Add remaining component of weight incrementally.
for (int x = 0; x < weight; x++)
superposeBitSetFromRowFloor(incomingBitSet, 0);
}
/**
* Performs superposition from a particular row by sweeping a bitset across the voting record
* such that for any column in which the incoming bitset contains a '1', 1's are changed
* to 0's until a new 1 can be added, facilitating incrementation of the
* binary number represented in this column.
*
* @param incomingBitSet the bitset to be added
* @param rowfloor the index of the place in the voting record to start the sweep at
*/
protected synchronized void superposeBitSetFromRowFloor(FixedBitSet incomingBitSet, int rowfloor) {
// Attempt to save space when minimum value across all columns > 0
// by decrementing across the board and raising the minimum where possible.
int max = getMaximumSharedWeight();
if (max > 0) {
decrement(max);
}
// Handle overflow: if any column that will be incremented
// contains all 1's, add a new row to the voting record.
tempSet.xor(tempSet);
tempSet.xor(incomingBitSet);
for (int x = rowfloor; x < votingRecord.size() && tempSet.cardinality() > 0; x++) {
tempSet.and(votingRecord.get(x));
}
if (tempSet.cardinality() > 0) {
votingRecord.add(new FixedBitSet(dimension));
}
// Sweep copy of bitset to be added across rows of voting record.
// If a new '1' is added, this position in the copy is changed to zero
// and will not affect future rows.
// The xor step will transform 1's to 0's or vice versa for
// dimension in which the temporary bitset contains a '1'.
votingRecord.get(rowfloor).xor(incomingBitSet);
tempSet.xor(tempSet);
tempSet.xor(incomingBitSet);
for (int x = rowfloor + 1; x < votingRecord.size(); x++) {
tempSet.andNot(votingRecord.get(x-1)); //if 1 already added, eliminate dimension from tempSet
votingRecord.get(x).xor(tempSet);
// votingRecord.get(x).trimTrailingZeros(); //attempt to save in sparsely populated rows
}
}
/**
* Reverses a string - simplifies the decoding of the binary vector for the 'exact' method
* although it wouldn't be difficult to reverse the counter instead
*/
public static String reverse(String str) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
return new StringBuffer(str).reverse().toString();
}
/**
* Sets {@link #tempSet} to be a bitset with a "1" in the position of every dimension
* in the {@link #votingRecord} that exactly matches the target number.
*/
private synchronized void setTempSetToExactMatches(int target) {
if (target == 0) {
tempSet.set(0, dimension);
tempSet.xor(votingRecord.get(0));
for (int x = 1; x < votingRecord.size(); x++)
tempSet.andNot(votingRecord.get(x));
} else
{
String inbinary = reverse(Integer.toBinaryString(target));
tempSet.xor(tempSet);
try {
tempSet.xor(votingRecord.get(inbinary.indexOf("1"))); //this requires error checking, it is throwing an index out of bounds exception
}
catch (Exception e)
{
e.printStackTrace();
}
for (int q =0; q < votingRecord.size(); q++) {
if (q < inbinary.length() && inbinary.charAt(q) == '1')
tempSet.and(votingRecord.get(q));
else
tempSet.andNot(votingRecord.get(q));
}
}
}
/**
* This method is used determine which dimension will receive 1 and which 0 when the voting
* process is concluded. It produces an FixedBitSet in which
* "1" is assigned to all dimension with a count > 50% of the total number of votes (i.e. more 1's than 0's added)
* "0" is assigned to all dimension with a count < 50% of the total number of votes (i.e. more 0's than 1's added)
* "0" or "1" are assigned to all dimension with a count = 50% of the total number of votes (i.e. equal 1's and 0's added)
*
* @return an FixedBitSet representing the superposition of all vectors added up to this point
*/
protected synchronized FixedBitSet concludeVote() {
if (votingRecord.size() == 0 || votingRecord.size() == 1 && votingRecord.get(0).cardinality() ==0) return new FixedBitSet(dimension);
else return concludeVote(totalNumberOfVotes.get());
}
protected synchronized FixedBitSet concludeVote(int target) {
int target2 = (int) Math.ceil((double) target / (double) 2);
target2 = target2 - minimum;
// Unlikely other than in testing: minimum more than half the votes
if (target2 < 0) {
FixedBitSet ans = new FixedBitSet(dimension);
ans.set(0, dimension);
return ans;
}
boolean even = (target % 2 == 0);
FixedBitSet result = concludeVote(target2, votingRecord.size() - 1);
if (even) {
setTempSetToExactMatches(target2);
boolean switcher = true;
// 50% chance of being true with split vote.
int q = tempSet.nextSetBit(0);
while (q != DocIdSetIterator.NO_MORE_DOCS)
{
switcher = !switcher;
if (switcher) tempSet.clear(q);
q = tempSet.nextSetBit(q);
}
result.andNot(tempSet);
}
return result;
}
protected synchronized FixedBitSet concludeVote(int target, int row_ceiling) {
/**
logger.info("Entering conclude vote, target " + target + " row_ceiling " + row_ceiling +
"voting record " + votingRecord.size() +
" minimum "+ minimum + " index "+ Math.log(target)/Math.log(2) +
" vector\n" + toString());
**/
if (target == 0) {
FixedBitSet atLeastZero = new FixedBitSet(dimension);
atLeastZero.set(0, dimension);
return atLeastZero;
}
double rowfloor = Math.log(target)/Math.log(2);
int row_floor = (int) Math.floor(rowfloor); //for 0 index
int remainder = target - (int) Math.pow(2,row_floor);
//System.out.println(target+"\t"+rowfloor+"\t"+row_floor+"\t"+remainder);
if (row_floor >= votingRecord.size()) //In this instance, the number we are checking for is higher than the capacity of the voting record
{
return new FixedBitSet(dimension);
}
if (row_ceiling == 0 && target == 1) {
return votingRecord.get(0);
}
if (remainder == 0) {
// Simple case - the number we're looking for is 2^n, so anything with a "1" in row n or above is true.
FixedBitSet definitePositives = new FixedBitSet(dimension);
for (int q = row_floor; q <= row_ceiling; q++)
definitePositives.or(votingRecord.get(q));
return definitePositives;
}
else {
// Simple part of complex case: first get anything with a "1" in a row above n (all true).
FixedBitSet definitePositives = new FixedBitSet(dimension);
for (int q = row_floor+1; q <= row_ceiling; q++)
definitePositives.or(votingRecord.get(q));
// Complex part of complex case: get those that have a "1" in the row of n.
FixedBitSet possiblePositives = (FixedBitSet) votingRecord.get(row_floor).clone();
FixedBitSet definitePositives2 = concludeVote(remainder, row_floor-1);
possiblePositives.and(definitePositives2);
definitePositives.or(possiblePositives);
return definitePositives;
}
}
/**
* Decrement every dimension. Assumes at least one count in each dimension
* i.e: no underflow check currently - will wreak havoc with zero counts
*/
public synchronized void decrement() {
tempSet.set(0, dimension);
for (int q = 0; q < votingRecord.size(); q++) {
votingRecord.get(q).xor(tempSet);
tempSet.and(votingRecord.get(q));
}
}
/**
* Decrement every dimension by the number passed as a parameter. Again at least one count in each dimension
* i.e: no underflow check currently - will wreak havoc with zero counts
*/
public synchronized void decrement(int weight) {
if (weight == 0) return;
minimum+= weight;
int logfloor = (int) (Math.floor(Math.log(weight)/Math.log(2)));
if (logfloor < votingRecord.size() - 1) {
while (logfloor > 0) {
selectedDecrement(logfloor);
weight = weight - (int) Math.pow(2,logfloor);
logfloor = (int) (Math.floor(Math.log(weight)/Math.log(2)));
}
}
for (int x = 0; x < weight; x++) {
decrement();
}
}
public synchronized void selectedDecrement(int floor) {
tempSet.set(0, dimension);
for (int q = floor; q < votingRecord.size(); q++) {
votingRecord.get(q).xor(tempSet);
tempSet.and(votingRecord.get(q));
}
}
/**
* Returns the highest value shared by all dimensions.
*/
protected synchronized int getMaximumSharedWeight() {
int thismaximum = 0;
tempSet.xor(tempSet); // Reset tempset to zeros.
for (int x = votingRecord.size() - 1; x >= 0; x
tempSet.or(votingRecord.get(x));
if (tempSet.cardinality() == dimension) {
thismaximum += (int) Math.pow(2, x);
tempSet.xor(tempSet);
}
}
return thismaximum;
}
/**
* Implements binding using permutations and XOR.
*/
public void bind(Vector other, int direction) {
IncompatibleVectorsException.checkVectorsCompatible(this, other);
BinaryVector binaryOther = (BinaryVector) other.copy();
if (direction > 0) {
//as per Kanerva 2009: bind(A,B) = perm+(A) XOR B = C
//this also functions as the left inverse: left inverse (A,C) = perm+(A) XOR C = B
this.permute(PermutationUtils.getShiftPermutation(VectorType.BINARY, dimension, 1)); //perm+(A)
this.bitSet.xor(binaryOther.bitSet); //perm+(A) XOR B
} else {
//as per Kanerva 2009: right inverse(C,B) = perm-(C XOR B) = perm-(perm+(A)) = A
this.bitSet.xor(binaryOther.bitSet); //C XOR B
this.permute(PermutationUtils.getShiftPermutation(VectorType.BINARY, dimension, -1)); //perm-(C XOR B) = A
}
}
/**
* Implements inverse of binding using permutations and XOR.
*/
public void release(Vector other, int direction) {
if (!BINARY_BINDING_WITH_PERMUTE)
bind(other);
else
bind (other, direction);
}
@Override
/**
* Implements binding using exclusive OR.
*/
public void bind(Vector other) {
IncompatibleVectorsException.checkVectorsCompatible(this, other);
if (!BINARY_BINDING_WITH_PERMUTE) {
BinaryVector binaryOther = (BinaryVector) other;
this.bitSet.xor(binaryOther.bitSet);
} else {
bind(other, 1);
}
}
@Override
/**
* Implements inverse binding using exclusive OR.
*/
public void release(Vector other) {
if (!BINARY_BINDING_WITH_PERMUTE)
bind(other);
else
bind(other, -1);
}
@Override
/**
* Normalizes the vector, converting sparse to dense representations in the process. This approach deviates from the "majority rule"
* approach that is standard in the Binary Spatter Code(). Rather, the probability of assigning a one in a particular dimension
* is a function of the probability of encountering the number of votes in the voting record in this dimension.
*
* This will be slower than normalizeBSC() below, but discards less information with positive effects on accuracy in preliminary experiments
*
* As a simple example to illustrate why this would be the case, consider the superposition of vectors for the terms "jazz","jazz" and "rock"
* With the BSC normalization, the vector produced is identical to "jazz" (as jazz wins the vote in each case). With probabilistic normalization,
* the vector produced is somewhat similar to both "jazz" and "rock", with a similarity that is proportional to the weights assigned to the
* superposition, e.g. 0.624000:jazz; 0.246000:rock
*/
public synchronized void normalize() {
if (votingRecord == null) return;
if (votingRecord.size() == 1) {
this.bitSet = votingRecord.get(0);
return;
}
if (NORMALIZE_METHOD.equals(BinaryNormalizationMethod.SPATTERCODE))
{
//faster majority rule normalization
this.bitSet = concludeVote();
}
else
{ //slower probabilistic normalization
//clear bitset;
this.bitSet.xor(this.bitSet);
//Ensure that the same set of superposed vectors will always produce the same result
long theSuperpositionSeed = 0;
for (int q =0; q < votingRecord.size(); q++)
theSuperpositionSeed += votingRecord.get(q).getBits()[0];
random.setSeed(theSuperpositionSeed);
//Determine value above the universal minimum for each dimension of the voting record
int max = totalNumberOfVotes.get();
//Determine the maximum possible votes on the voting record
int maxpossiblevotesonrecord = 0;
for (int q=0; q < votingRecord.size(); q++)
maxpossiblevotesonrecord += Math.pow(2, q);
//For each possible value on the record, get a BitSet with a "1" in the
//position of the dimensions that match this value
for (int x = 1; x <= maxpossiblevotesonrecord; x++) {
this.setTempSetToExactMatches(x);
//no exact matches
if (this.tempSet.cardinality() == 0) continue;
//For each y==1 on said BitSet (indicating votes in dimension[y] == x)
int y = tempSet.nextSetBit(0);
//determine total number of votes
double votes = minimum+x;
//calculate standard deviations above/below the mean of max/2
double z = (votes - (max/2)) / (Math.sqrt(max)/2);
//find proportion of data points anticipated within z standard deviations of the mean (assuming approximately normal distribution)
double proportion = erf(z/Math.sqrt(2));
//convert into a value between 0 and 1 (i.e. centered on 0.5 rather than centered on 0)
proportion = (1+proportion) /2;
while (y != DocIdSetIterator.NO_MORE_DOCS) {
//probabilistic normalization
if ((random.nextDouble()) <= proportion) this.bitSet.set(y);
y++;
if (y == this.dimension) break;
y = tempSet.nextSetBit(y);
}
}
}
//housekeeping
votingRecord = new ArrayList<FixedBitSet>();
votingRecord.add((FixedBitSet) bitSet.clone());
totalNumberOfVotes.set(1);
tempSet = new FixedBitSet(dimension);
minimum = 0;
}
/**
* approximation of error function, equation 7.1.27 from
* Abramowitz, M. and Stegun, I. A. (Eds.). "Repeated Integrals of the Error Function." S 7.2
* in Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables,
* 9th printing. New York: Dover, pp. 299-300, 1972.
* error of approximation <= 5*10^-4
*/
public double erf(double z) {
//erf(-x) == -erf(x)
double sign = Math.signum(z);
z = Math.abs(z);
double a1 = 0.278393, a2 = 0.230389, a3 = 0.000972, a4 = 0.078108;
double sumterm = 1 + a1*z + a2*Math.pow(z,2) + a3*Math.pow(z,3) + a4*Math.pow(z,4);
return sign * ( 1-1/(Math.pow(sumterm, 4)));
}
/**
* Faster normalization according to the Binary Spatter Code's "majority" rule
*/
public synchronized void normalizeBSC() {
if (!isSparse)
this.bitSet = concludeVote();
votingRecord = new ArrayList<FixedBitSet>();
votingRecord.add((FixedBitSet) bitSet.clone());
totalNumberOfVotes.set(1);
tempSet = new FixedBitSet(dimension);
minimum = 0;
}
/**
* Counts votes without normalizing vector (i.e. voting record is not altered). Used in SemanticVectorCollider.
*/
public synchronized void tallyVotes() {
if (!isSparse && unTallied.get()) //only count if there are votes since the last tally
try { this.bitSet = concludeVote();
unTallied.set(false); } catch (Exception e) {e.printStackTrace();}
}
@Override
/**
* Writes vector out to object output stream. Converts to dense format if necessary.
*/
public void writeToLuceneStream(IndexOutput outputStream) {
if (isSparse) {
elementalToSemantic();
}
long[] bitArray = bitSet.getBits();
for (int i = 0; i < bitArray.length; i++) {
try {
outputStream.writeLong(bitArray[i]);
} catch (IOException e) {
logger.severe("Couldn't write binary vector to lucene output stream.");
e.printStackTrace();
}
}
}
/**
* Writes vector out to object output stream. Converts to dense format if necessary. Truncates to length k.
*/
public void writeToLuceneStream(IndexOutput outputStream, int k) {
if (isSparse) {
elementalToSemantic();
}
long[] bitArray = bitSet.getBits();
for (int i = 0; i < k/64; i++) {
try {
outputStream.writeLong(bitArray[i]);
} catch (IOException e) {
logger.severe("Couldn't write binary vector to lucene output stream.");
e.printStackTrace();
}
}
}
@Override
/**
* Reads a (dense) version of a vector from a Lucene input stream.
*/
public void readFromLuceneStream(IndexInput inputStream) {
long bitArray[] = new long[(dimension / 64)];
for (int i = 0; i < dimension / 64; ++i) {
try {
bitArray[i] = inputStream.readLong();
} catch (IOException e) {
logger.severe("Couldn't read binary vector from lucene output stream.");
e.printStackTrace();
}
}
this.bitSet = new FixedBitSet(bitArray, dimension);
this.isSparse = true;
}
@Override
/**
* Writes vector to a string of the form 010 etc. (no delimiters).
*
* No terminating newline or delimiter.
*/
public String writeToString() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < dimension; ++i) {
builder.append(this.bitSet.get(i) ? "1" : "0");
}
return builder.toString();
}
/**
* Writes vector to a string of the form 010 etc. (no delimiters).
*
* No terminating newline or delimiter.
*/
public String writeLongToString() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < (bitSet.getBits().length); ++i) {
builder.append(Long.toString(bitSet.getBits()[i])+"|");
}
return builder.toString();
}
@Override
/**
* Writes vector from a string of the form 01001 etc.
*/
public void readFromString(String input) {
if (input.length() != dimension) {
throw new IllegalArgumentException("Found " + (input.length()) + " possible coordinates: "
+ "expected " + dimension);
}
for (int i = 0; i < dimension; ++i) {
if (input.charAt(i) == '1')
bitSet.set(i);
}
}
/**
* Automatically translate elemental vector (no storage capacity) into
* semantic vector (storage capacity initialized, this will occupy RAM)
*/
protected void elementalToSemantic() {
if (!isSparse) {
logger.warning("Tried to transform an elemental vector which is not in fact elemental."
+ "This may be a programming error.");
return;
}
votingRecord = new ArrayList<FixedBitSet>();
votingRecord.add((FixedBitSet) bitSet.clone());
tempSet = new FixedBitSet(dimension);
isSparse = false;
}
/**
* Permute the long[] array underlying the FixedBitSet binary representation
*/
public void permute(int[] permutation) {
if (permutation.length != getDimension() / 64) {
throw new IllegalArgumentException("Binary vector of dimension " + getDimension()
+ " must have permutation of length " + getDimension() / 64
+ " not " + permutation.length);
}
//TODO permute in place without creating additional long[] (if proves problematic at scale)
long[] coordinates = bitSet.getBits();
long[] newCoordinates = new long[coordinates.length];
for (int i = 0; i < coordinates.length; ++i) {
int positionToAdd = i;
positionToAdd = permutation[positionToAdd];
newCoordinates[i] = coordinates[positionToAdd];
}
bitSet = new FixedBitSet(newCoordinates, getDimension());
}
// Available for testing and copying.
protected BinaryVector(FixedBitSet inSet) {
this.dimension = (int) inSet.length();
this.bitSet = inSet;
}
// Available for testing
protected int bitLength() {
return bitSet.getBits().length;
}
// Monitor growth of voting record.
protected int numRows() {
if (isSparse) return 0;
return votingRecord.size();
}
//access bitset directly
protected FixedBitSet getCoordinates() {
// TODO Auto-generated method stub
return this.bitSet;
}
//access bitset directly
protected void setCoordinates(FixedBitSet incomingBitSet) {
// TODO Auto-generated method stub
this.bitSet = incomingBitSet;
}
//set DEBUG_PRINT_LENGTTH
public static void setDebugPrintLength(int length){
DEBUG_PRINT_LENGTH = length;
}
}
|
package com.plugin.core;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Hashtable;
import java.util.Iterator;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Build;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import com.plugin.util.ApkReader;
import dalvik.system.DexClassLoader;
public class PluginLoader {
private static final String LOG_TAG = PluginLoader.class.getSimpleName();
private static Application sApplication;
private static final Hashtable<String, PluginDescriptor> sInstalledPlugins = new Hashtable<String, PluginDescriptor>();
private static boolean isInited = false;
public static final String ACTION_PLUGIN_CHANGED = "com.plugin.core.action_plugin_changed";
public static final String EXTRA_TYPE = "com.plugin.core.EXTRA_TYPE";
private PluginLoader() {
}
/**
* loader,
*
* @param app
*/
public static synchronized void initLoader(Application app) {
if (!isInited) {
sApplication = app;
readInstalledPlugins();
isInited = true;
}
}
public boolean isInstalled(String pluginId, String pluginVersion) {
PluginDescriptor pluginDescriptor = getPluginDescriptorByPluginId(pluginId);
if (pluginDescriptor != null) {
return pluginDescriptor.getVersion().equals(pluginVersion);
}
return false;
}
/**
*
*
* @param srcPluginFile
* @return
*/
public static synchronized boolean installPlugin(String srcPluginFile) {
Log.e(LOG_TAG, "Install plugin " + srcPluginFile);
boolean isInstallSuccess = false;
PluginDescriptor pluginDescriptor = ApkReader.readPluginDescriptor(srcPluginFile);
if (pluginDescriptor == null || TextUtils.isEmpty(pluginDescriptor.getId())) {
return isInstallSuccess;
}
PluginDescriptor oldPluginDescriptor = getPluginDescriptorByPluginId(pluginDescriptor.getId());
if (oldPluginDescriptor != null) {
remove(pluginDescriptor.getId());
}
if (pluginDescriptor != null) {
String destPluginFile = genInstallPath(pluginDescriptor.getId(), pluginDescriptor.getVersion());
boolean isCopySuccess = ApkReader.copyFile(srcPluginFile, destPluginFile);
if (isCopySuccess) {
pluginDescriptor.setInstalledPath(destPluginFile);
PluginDescriptor previous = sInstalledPlugins.put(pluginDescriptor.getId(), pluginDescriptor);
isInstallSuccess = saveInstalledPlugins(sInstalledPlugins);
if (isInstallSuccess) {
Intent intent = new Intent(ACTION_PLUGIN_CHANGED);
if (previous == null) {
intent.putExtra(EXTRA_TYPE, "add");
} else {
intent.putExtra(EXTRA_TYPE, "replace");
}
intent.putExtra("id", pluginDescriptor.getId());
intent.putExtra("version", pluginDescriptor.getVersion());
sApplication.sendBroadcast(intent);
}
}
}
return isInstallSuccess;
}
private static String getPluginClassNameById(PluginDescriptor pluginDescriptor, String clazzId) {
String clazzName = pluginDescriptor.getFragments().get(clazzId);
if (clazzName == null) {
clazzName = pluginDescriptor.getActivities().get(clazzId);
}
return clazzName;
}
/**
* classIdclass
*
* @param clazzId
* @return
*/
@SuppressWarnings("rawtypes")
public static Class loadPluginClassById(String clazzId) {
Log.v(LOG_TAG, "loadPluginClass for clazzId " + clazzId);
PluginDescriptor pluginDescriptor = getPluginDescriptorByClassId(clazzId);
if (pluginDescriptor != null) {
DexClassLoader pluginClassLoader = pluginDescriptor.getPluginClassLoader();
if (pluginClassLoader == null) {
initPlugin(pluginDescriptor);
pluginClassLoader = pluginDescriptor.getPluginClassLoader();
}
if (pluginClassLoader != null) {
String clazzName = getPluginClassNameById(pluginDescriptor, clazzId);
if (clazzName != null) {
try {
Class pluginClazz = ((ClassLoader) pluginClassLoader).loadClass(clazzName);
Log.v(LOG_TAG, "loadPluginClass Success for classId " + clazzId);
return pluginClazz;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
Log.e(LOG_TAG, "loadPluginClass Fail for classId " + clazzId);
return null;
}
/**
* classContext
*
* @param clazz
* @return
*/
public static Context getPluginContext(@SuppressWarnings("rawtypes") Class clazz) {
// clazz.getClassLoader(); classloader
// classloaderloader
Context pluginContext = null;
PluginDescriptor pluginDescriptor = getPluginDescriptorByClassName(clazz.getName());
if (pluginDescriptor != null) {
pluginContext = pluginDescriptor.getPluginContext();
} else {
Log.e(LOG_TAG, "PluginDescriptor Not Found for " + clazz.getName());
}
if (pluginContext == null) {
Log.e(LOG_TAG, "Context Not Found for " + clazz.getName());
}
return pluginContext;
}
/**
*
*
* @param pluginClassBean
*/
private static void initPlugin(PluginDescriptor pluginDescriptor) {
Log.d(LOG_TAG, "initPlugin, Resources, DexClassLoader, Context");
Resources pluginRes = PluginCreator.createPluginResource(sApplication, pluginDescriptor.getInstalledPath());
DexClassLoader pluginClassLoader = PluginCreator.createPluginClassLoader(pluginDescriptor.getInstalledPath());
Context pluginContext = PluginCreator
.createPluginApplicationContext(sApplication, pluginRes, pluginClassLoader);
pluginDescriptor.setPluginContext(pluginContext);
pluginDescriptor.setPluginClassLoader(pluginClassLoader);
}
private static synchronized boolean saveInstalledPlugins(Hashtable<String, PluginDescriptor> installedPlugins) {
ObjectOutputStream objectOutputStream = null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(installedPlugins);
objectOutputStream.flush();
byte[] data = byteArrayOutputStream.toByteArray();
String list = Base64.encodeToString(data, Base64.DEFAULT);
getSharedPreference().edit().putString("plugins.list", list).commit();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (objectOutputStream != null) {
try {
objectOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
/**
* class,class
*/
public static synchronized void removeAll() {
sInstalledPlugins.entrySet().iterator();
sInstalledPlugins.clear();
boolean isSuccess = saveInstalledPlugins(sInstalledPlugins);
if (isSuccess) {
Intent intent = new Intent(ACTION_PLUGIN_CHANGED);
intent.putExtra(EXTRA_TYPE, "remove");
sApplication.sendBroadcast(intent);
}
}
public static synchronized void remove(String pluginId) {
PluginDescriptor old = sInstalledPlugins.remove(pluginId);
if (old != null) {
boolean isSuccess = saveInstalledPlugins(sInstalledPlugins);
new File(old.getInstalledPath()).delete();
if (isSuccess) {
Intent intent = new Intent(ACTION_PLUGIN_CHANGED);
intent.putExtra(EXTRA_TYPE, "remove");
sApplication.sendBroadcast(intent);
}
}
}
@SuppressWarnings("unchecked")
public static Hashtable<String, PluginDescriptor> listAll() {
return (Hashtable<String, PluginDescriptor>) sInstalledPlugins.clone();
}
private static PluginDescriptor getPluginDescriptorByClassId(String clazzID) {
Iterator<PluginDescriptor> itr = sInstalledPlugins.values().iterator();
while (itr.hasNext()) {
PluginDescriptor descriptor = itr.next();
if (descriptor.getFragments().containsKey(clazzID) && descriptor.isEnabled()) {
return descriptor;
} else if (descriptor.getActivities().containsKey(clazzID) && descriptor.isEnabled()) {
return descriptor;
}
}
return null;
}
public static PluginDescriptor getPluginDescriptorByPluginId(String pluginId) {
PluginDescriptor pluginDescriptor = sInstalledPlugins.get(pluginId);
if (pluginDescriptor != null && pluginDescriptor.isEnabled()) {
return pluginDescriptor;
}
return null;
}
private static PluginDescriptor getPluginDescriptorByClassName(String clazzName) {
Iterator<PluginDescriptor> itr = sInstalledPlugins.values().iterator();
while (itr.hasNext()) {
PluginDescriptor descriptor = itr.next();
if (descriptor.getFragments().containsValue(clazzName) && descriptor.isEnabled()) {
return descriptor;
} else if (descriptor.getActivities().containsValue(clazzName) && descriptor.isEnabled()) {
return descriptor;
}
}
return null;
}
public static synchronized void enablePlugin(String pluginId, boolean enable) {
PluginDescriptor pluginDescriptor = sInstalledPlugins.get(pluginId);
if (pluginDescriptor != null && !pluginDescriptor.isEnabled()) {
pluginDescriptor.setEnabled(enable);
saveInstalledPlugins(sInstalledPlugins);
}
}
@SuppressWarnings("unchecked")
private static synchronized Hashtable<String, PluginDescriptor> readInstalledPlugins() {
if (sInstalledPlugins.size() == 0) {
String list = getSharedPreference().getString("plugins.list", "");
Serializable object = null;
if (!TextUtils.isEmpty(list)) {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
Base64.decode(list, Base64.DEFAULT));
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(byteArrayInputStream);
object = (Serializable) objectInputStream.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (objectInputStream != null) {
try {
objectInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (byteArrayInputStream != null) {
try {
byteArrayInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
if (object != null) {
Hashtable<String, PluginDescriptor> installedPlugin = (Hashtable<String, PluginDescriptor>) object;
sInstalledPlugins.putAll(installedPlugin);
}
}
return sInstalledPlugins;
}
/**
* , apk
*/
private static String genInstallPath(String pluginId, String pluginVersoin) {
return sApplication.getDir("plugin_dir", Context.MODE_PRIVATE).getAbsolutePath() + "/" + pluginId + "/"
+ pluginVersoin + ".apk";
}
private static SharedPreferences getSharedPreference() {
SharedPreferences sp = sApplication.getSharedPreferences("plugins.installed",
Build.VERSION.SDK_INT < 11 ? Context.MODE_PRIVATE : Context.MODE_PRIVATE | 0x0004);
return sp;
}
}
|
// Triple Play - utilities for use in PlayN-based games
package tripleplay.ui;
import playn.core.Pointer;
import playn.core.Pointer.Event;
import playn.core.Sound;
import pythagoras.f.IDimension;
import pythagoras.f.Point;
import react.Signal;
import react.Slot;
import react.Value;
/**
* Controls the behavior of a widget (how it responds to pointer events).
*/
public abstract class Behavior<T extends Element<T>> implements Pointer.Listener {
/** Implements button-like behavior: selects the element when the pointer is in bounds, and
* deselects on release. This is a pretty common case and inherited by {@link Click}. */
public static class Select<T extends Element<T>> extends Behavior<T> {
public Select (T owner) {
super(owner);
}
@Override protected void onPress (Pointer.Event event) {
updateSelected(true);
}
@Override protected void onHover (Pointer.Event event, boolean inBounds) {
updateSelected(inBounds);
}
@Override protected boolean onRelease (Pointer.Event event) {
// it's a click if we ended in bounds
return updateSelected(false);
}
@Override protected void onCancel (Pointer.Event event) {
updateSelected(false);
}
@Override protected void onClick (Pointer.Event event) {
// nothing by default, subclasses wire this up as needed
}
}
/** A behavior that ignores everything. This allows subclasses to easily implement a single
* {@code onX} method. */
public static class Ignore<T extends Element<T>> extends Behavior<T> {
public Ignore (T owner) { super(owner); }
@Override protected void onPress (Pointer.Event event) {}
@Override protected void onHover (Pointer.Event event, boolean inBounds) {}
@Override protected boolean onRelease (Pointer.Event event) { return false; }
@Override protected void onCancel (Pointer.Event event) {}
@Override protected void onClick (Pointer.Event event) {}
}
/** Implements clicking behavior. */
public static class Click<T extends Element<T>> extends Select<T> {
/** A delay (in milliseconds) during which the owner will remain unclickable after it has
* been clicked. This ensures that users don't hammer away at a widget, triggering
* multiple responses (which code rarely protects against). Inherited. */
public static Style<Integer> DEBOUNCE_DELAY = Style.newStyle(true, 500);
/** A signal emitted with our owner when clicked. */
public Signal<T> clicked = Signal.create();
public Click (T owner) {
super(owner);
}
/** Triggers a click. */
public void click () {
soundAction();
clicked.emit(_owner); // emit a click event
}
@Override public void layout () {
super.layout();
_debounceDelay = resolveStyle(DEBOUNCE_DELAY);
}
@Override protected void onPress (Pointer.Event event) {
// ignore press events if we're still in our debounce interval
if (event.time() - _lastClickStamp > _debounceDelay) super.onPress(event);
}
@Override protected void onClick (Pointer.Event event) {
_lastClickStamp = event.time();
click();
}
protected int _debounceDelay;
protected double _lastClickStamp;
}
/** Implements toggling behavior. */
public static class Toggle<T extends Element<T>> extends Behavior<T> {
/** A signal emitted with our owner when clicked. */
public final Signal<T> clicked = Signal.create();
/** Indicates whether our owner is selected. It may be listened to, and updated. */
public final Value<Boolean> selected = Value.create(false);
public Toggle (T owner) {
super(owner);
selected.connect(selectedDidChange());
}
/** Triggers a click. */
public void click () {
soundAction();
clicked.emit(_owner); // emit a click event
}
@Override protected void onPress (Pointer.Event event) {
_anchorState = _owner.isSelected();
selected.update(!_anchorState);
}
@Override protected void onHover (Pointer.Event event, boolean inBounds) {
selected.update(inBounds ? !_anchorState : _anchorState);
}
@Override protected boolean onRelease (Pointer.Event event) {
return _anchorState != _owner.isSelected();
}
@Override protected void onCancel (Pointer.Event event) {
selected.update(_anchorState);
}
@Override protected void onClick (Pointer.Event event) {
click();
}
protected boolean _anchorState;
}
/**
* Tracks the pressed position as an anchor and delegates to subclasses to update state based
* on anchor and drag position.
*/
public static abstract class Track<T extends Element<T>> extends Ignore<T>
{
/** A distance, in event coordinates, used to decide if tracking should be temporarily
* cancelled. If the pointer is hovered more than this distance outside of the owner's
* bounds, the tracking will revert to the anchor position, just like when the pointer is
* cancelled. A null value indicates that the tracking will be unconfined in this way.
* TODO: default to 35 if no Slider uses are relying on lack of hover limit. */
public static Style<Float> HOVER_LIMIT = Style.newStyle(true, (Float)null);
/** Holds the necessary data for the currently active press. {@code Track} subclasses can
* derive if more transient information is needed. */
public class State {
/** Time the press started. */
public final double pressTime;
/** The press and drag positions. */
public final Point press, drag;
/** Creates a new tracking state with the given starting press event. */
public State (Pointer.Event event) {
pressTime = event.time();
toPoint(event, press = new Point());
drag = new Point(press);
}
/** Updates the state to the current event value and called {@link Track#onTrack()}. */
public void update (Pointer.Event event) {
boolean cancel = false;
if (_hoverLimit != null) {
float lim = _hoverLimit, lx = event.localX(), ly = event.localY();
IDimension size = _owner.size();
cancel = lx + lim < 0 || ly + lim < 0 ||
lx - lim >= size.width() || ly - lim >= size.height();
}
toPoint(event, drag);
onTrack(press, cancel ? press : drag);
}
}
protected Track (T owner) {
super(owner);
}
/**
* Called when the pointer is dragged. After cancel or if the pointer goes outside the
* hover limit, drag will be equal to anchor.
* @param anchor the pointer position when initially pressed
* @param drag the current pointer position
*/
abstract protected void onTrack (Point anchor, Point drag);
/**
* Creates the state instance for the given press. Subclasses may return an instance
* of a derived {@code State} if more information is needed during tracking.
*/
protected State createState (Pointer.Event press) {
return new State(press);
}
/**
* Converts an event to coordinates consumed by {@link #onTrack(Point, Point)}. By
* default, simply uses the local x, y.
*/
protected void toPoint (Pointer.Event event, Point dest) {
dest.set(event.localX(), event.localY());
}
@Override protected void onPress (Event event) {
_state = createState(event);
}
@Override protected void onHover (Event event, boolean inBounds) {
_state.update(event);
}
@Override protected boolean onRelease (Event event) {
_state = null;
return false;
}
@Override protected void onCancel (Event event) {
// track to the press position to cancel
onTrack(_state.press, _state.press);
_state = null;
}
@Override public void layout () {
super.layout();
_hoverLimit = resolveStyle(HOVER_LIMIT);
}
protected State _state;
protected Float _hoverLimit;
}
/** A click behavior that captures the pointer and optionally issues clicks based on some time
* based function. */
public static abstract class Capturing<T extends Element<T>> extends Click<T>
implements Interface.Task
{
protected Capturing (T owner) {
super(owner);
}
@Override protected void onPress (Event event) {
super.onPress(event);
event.capture();
_task = _owner.root().iface().addTask(this);
}
@Override protected void onCancel (Event event) {
super.onCancel(event);
cancelTask();
}
@Override protected boolean onRelease (Event event) {
super.onRelease(event);
cancelTask();
return false;
}
/** Cancels the time-based task. This is called automatically by the pointer release
* and cancel events. */
protected void cancelTask () {
if (_task == null) return;
_task.remove();
_task = null;
}
protected Interface.TaskHandle _task;
}
/** Captures the pointer and dispatches one click on press, a second after an initial delay
* and at regular intervals after that. */
public static class RapidFire<T extends Element<T>> extends Capturing<T>
{
/** Milliseconds after the first click that the second click is dispatched. */
public static final Style<Integer> INITIAL_DELAY = Style.newStyle(true, 200);
/** Milliseconds between repeated click dispatches. */
public static final Style<Integer> REPEAT_DELAY = Style.newStyle(true, 75);
/** Creates a new rapid fire behavior for the given owner. */
public RapidFire (T owner) {
super(owner);
}
@Override protected void onPress (Event event) {
super.onPress(event);
_timeInBounds = 0;
click();
}
@Override protected void onHover (Event event, boolean inBounds) {
super.onHover(event, inBounds);
if (!inBounds) _timeInBounds = -1;
}
@Override public void update (int delta) {
if (_timeInBounds < 0) return;
int was = _timeInBounds;
_timeInBounds += delta;
int limit = was < _initDelay ? _initDelay :
_initDelay + _repDelay * ((was - _initDelay) / _repDelay + 1);
if (was < limit && _timeInBounds >= limit) click();
}
@Override public void layout () {
super.layout();
_initDelay = _owner.resolveStyle(INITIAL_DELAY);
_repDelay = _owner.resolveStyle(REPEAT_DELAY);
}
protected int _initDelay, _repDelay, _timeInBounds;
}
public Behavior (T owner) {
_owner = owner;
}
@Override public void onPointerStart (Pointer.Event event) {
if (_owner.isEnabled()) onPress(event);
}
@Override public void onPointerDrag (Pointer.Event event) {
if (_owner.isEnabled()) onHover(event, _owner.contains(event.localX(), event.localY()));
}
@Override public void onPointerEnd (Pointer.Event event) {
if (onRelease(event)) onClick(event);
}
@Override public void onPointerCancel (Pointer.Event event) {
onCancel(event);
}
/** Called when our owner is laid out. If the behavior needs to resolve configuration via
* styles, this is where it should do it. */
public void layout () {
_actionSound = resolveStyle(Style.ACTION_SOUND);
}
/** Emits the action sound for our owner, if one is configured. */
public void soundAction () {
if (_actionSound != null) _actionSound.play();
}
/** Resolves the value for the supplied style via our owner. */
protected <V> V resolveStyle (Style<V> style) {
return Styles.resolveStyle(_owner, style);
}
/** Returns the {@link Root} to which our owning element is added, or null. */
protected Root root () {
return _owner.root();
}
/** Called when the pointer is pressed down on our element. */
protected abstract void onPress (Pointer.Event event);
/** Called as the user drags the pointer around after pressing. Derived classes map this onto
* the widget state, such as updating selectedness. */
protected abstract void onHover (Pointer.Event event, boolean inBounds);
/** Called when the pointer is released after having been pressed on this widget. This should
* return true if the gesture is considered a click, in which case {@link #onClick} will
* be called automatically. */
protected abstract boolean onRelease (Pointer.Event event);
/** Called when the interaction is canceled after having been pressed on this widget. This
* should not result in a call to {@link #onClick}. */
protected abstract void onCancel (Pointer.Event event);
/** Called when the pointer is released and the subclass decides that it is a click, i.e.
* returns true from {@link #onRelease(Pointer.Event)}. */
protected abstract void onClick (Pointer.Event event);
/** Updates the selected state of our owner, invalidating if selectedness changes.
* @return true if the owner was selected on entry. */
protected boolean updateSelected (boolean selected) {
boolean wasSelected = _owner.isSelected();
if (selected != wasSelected) {
_owner.set(Element.Flag.SELECTED, selected);
_owner.invalidate();
}
return wasSelected;
}
/** Slot for calling {@link #updateSelected(boolean)}. */
protected Slot<Boolean> selectedDidChange () {
return new Slot<Boolean>() {
@Override public void onEmit (Boolean selected) {
updateSelected(selected);
}
};
}
protected final T _owner;
protected Sound _actionSound;
}
|
package thwack.and.bash.game.level;
import java.util.ArrayList;
import thwack.and.bash.game.Game;
import thwack.and.bash.game.entity.Entity;
import thwack.and.bash.game.entity.mob.Player;
import thwack.and.bash.game.util.Util.Pixels;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.maps.MapLayer;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.Manifold;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
/*
* THIS IS NOT THE FINAL VERSION,
*/
public class Level {
private Level(){}
private static World world;
private static OrthogonalTiledMapRenderer mapRenderer;
private static TiledMap tiledMap;
private static Player player;
public static void update(float delta){
world.step(1 / 60f, 6, 2);
}
public static void render(){
Rectangle r = Game.getMapViewport();
OrthographicCamera c = Game.getGameCamera();
mapRenderer.setView(c);
mapRenderer.render();
Game.getBatch().setProjectionMatrix(Game.getScreenCamera().combined);
}
public static void load(String tmxLevel, World world){
Level.world = world;
tiledMap = new TmxMapLoader().load("levels/" + tmxLevel);
mapRenderer = new OrthogonalTiledMapRenderer(tiledMap, Game.getBatch());
addBox2D();
setContactListener();
player = (Player) Entity.getEntity("player");
}
public static World getWorld(){
return world;
}
//Shall fix this
private static void addBox2D(){
float tileSize = 0;
ArrayList<Box2DCell> cells = new ArrayList<Box2DCell>();
MapLayer mapLayer = tiledMap.getLayers().get("collision");
TiledMapTileLayer layer = (TiledMapTileLayer) mapLayer;
tileSize = layer.getTileWidth();
for(int y = 0; y < layer.getHeight(); y++){
for(int x = 0; x < layer.getWidth(); x++){
Cell cell = layer.getCell(x, y);
if(cell == null){
continue;
}
if(cell.getTile() == null){
continue;
}
cells.add(new Box2DCell(cell, x, y));
}
}
// l J
int i = cells.size() - 1;
ArrayList<Box2DCell> yCells = new ArrayList<Box2DCell>();
while(true){
Box2DCell c = cells.get(0);
float x = c.x;
while(true){
Box2DCell c2 = findCellToRight(cells, c, x);
if(c2 != null){
cells.remove(c2);
x++;
i
} else {
break;
}
}
float x2 = x - c.x + 1;
if(x2 - 1 >= 1){
BodyDef bodyDef = new BodyDef();
bodyDef.position.x = Pixels.toMeters(c.x * tileSize + x2 * tileSize / 2);
bodyDef.position.y = Pixels.toMeters(c.y * tileSize + tileSize / 2);
bodyDef.type = BodyType.StaticBody;
Body body = world.createBody(bodyDef);
body.setUserData("tile");
PolygonShape shape = new PolygonShape();
shape.setAsBox(Pixels.toMeters(x2 * tileSize / 2), Pixels.toMeters(tileSize / 2));
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.friction = 0;
Fixture f = body.createFixture(fixtureDef);
f.setUserData("tile");
}
if(x2 - 1 == 0){
yCells.add(c);
}
cells.remove(c);
if(cells.size() <= 0){
break;
}
}
//l l
//l l
//L _J
if(yCells.size() != 0) {
while(true){
Box2DCell c = yCells.get(0);
float y = c.y;
while(true){
Box2DCell c2 = findCellToDown(yCells, c, y);
if(c2 != null){
yCells.remove(c2);
y++;
} else {
break;
}
}
float y2 = y - c.y + 1;
if(y2 == 0){
y2 = 1;
}
BodyDef bodyDef = new BodyDef();
bodyDef.position.x = Pixels.toMeters(c.x * tileSize + tileSize / 2);
bodyDef.position.y = Pixels.toMeters(c.y * tileSize + y2 * tileSize / 2);
bodyDef.type = BodyType.StaticBody;
Body body = world.createBody(bodyDef);
body.setUserData("tile");
PolygonShape shape = new PolygonShape();
shape.setAsBox(Pixels.toMeters(tileSize / 2), Pixels.toMeters(y2 * tileSize / 2));
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.friction = 0;
Fixture f = body.createFixture(fixtureDef);
f.setUserData("tile");
yCells.remove(c);
if(yCells.size() <= 0){
break;
}
}
}
}
private static Box2DCell findCellToRight(ArrayList<Box2DCell> cells, Box2DCell c, float x){
for(int i = 0; i < cells.size(); i++){
if(cells.get(i) == c){
continue;
}
if(cells.get(i).y == c.y && cells.get(i).x == x + 1){
Box2DCell c2 = cells.get(i);
cells.remove(i);
return c2;
}
}
return null;
}
private static Box2DCell findCellToDown(ArrayList<Box2DCell> cells, Box2DCell c, float y){
for(int i = 0; i < cells.size(); i++){
if(cells.get(i) == c){
continue;
}
if(cells.get(i).y == y + 1 && cells.get(i).x == c.x){
Box2DCell c2 = cells.get(i);
cells.remove(i);
return c2;
}
}
return null;
}
private static void setContactListener(){
world.setContactListener(new ContactListener(){
@Override
public void beginContact(Contact contact) {
}
@Override
public void endContact(Contact contact) {
}
@Override
public void preSolve(Contact contact, Manifold oldManifold) {
}
@Override
public void postSolve(Contact contact, ContactImpulse impulse) {
}
});
}
private static boolean check(Entity e, Contact c){
Fixture a = c.getFixtureA();
Fixture b = c.getFixtureB();
if(a.getUserData() == null){
//System.out.println("A fixture you just collied with or you's user data == null, fix this");
return false;
}
if(b.getUserData() == null){
//System.out.println("B fixture you just collied with or you's user data == null, fix this");
return false;
}
if(a.getUserData().equals(e.getFixture().getUserData())){
return true;
}
else if(b.getUserData().equals(e.getFixture().getUserData())){
return true;
}
return false;
}
}
|
package info.guardianproject.otr;
public interface OtrConstants {
/*
* If Alice wishes to communicate to Bob that she is willing to use OTR, she can attach a special whitespace tag to any plaintext message she sends him. This tag may occur anywhere in the message, and may be hidden from the user (as in the Query Messages, above).
The tag consists of the following 16 bytes, followed by one or more sets of 8 bytes indicating the version of OTR Alice is willing to use:
Always send "\x20\x09\x20\x20\x09\x09\x09\x09" "\x20\x09\x20\x09\x20\x09\x20\x20", followed by one or more of:
"\x20\x09\x20\x09\x20\x20\x09\x20" to indicate a willingness to use OTR version 1 with Bob (note: this string must come before all other whitespace version tags, if it is present, for backwards compatibility)
"\x20\x20\x09\x09\x20\x20\x09\x20" to indicate a willingness to use OTR version 2 with
*/
public static final String QueryMessage_Bizzare = "?OTRv?";
public static final String QueryMessage_V1_CASE1 = "?OTR?";
public static final String QueryMessage_V1_CASE2 = "?OTR?v?";
public static final String QueryMessage_V2 = "?OTRv2?";
public static final String QueryMessage_V12 = "?OTR?v2?";
public static final String QueryMessage_V14x = "?OTRv24x?";
public static final String QueryMessage_V124x = "?OTR?v24x?";
public static final String CommonRequest = " Your contact is requesting to start an encrypted chat. Please install ChatSecure (Android, iPhone and iPad) from https://get.chatsecure.org/ or other encryption-capable messaging app.";
public static final String QueryMessage_CommonRequest = "?OTR?v2? " + CommonRequest;
public static final String PlainText_V12 = "This is a plain text that has hidden support for V1 and V2! ";
public static final String PlainText_V1 = "This is a plain text that has hidden support for V1! ";
}
|
package io.github.benjimarshall.chem;
import java.math.MathContext;
import java.math.RoundingMode;
public class Solution extends Substance {
public Solution(Substance substance, Volume volume) {
super(substance);
this.volume = volume;
this.concentration = calculateConcentration(getMoles(), volume);
}
public Solution(Substance substance, Concentration concentration) {
super(substance);
this.concentration = concentration;
this.volume = calculateVolume(substance.getMoles(), concentration);
}
protected Concentration calculateConcentration(Mole moles, Volume volume) {
return new Concentration(moles.getQuantity().divide(volume.getVolumeInLitres(),
new MathContext(5, RoundingMode.HALF_UP)));
}
protected Volume calculateVolume(Mole moles, Concentration concentration) {
return new Volume(moles.getQuantity().divide(concentration.getConcentration(),
new MathContext(5, RoundingMode.HALF_UP)));
}
protected Mole calculateMoles(Volume volume, Concentration concentration) {
return new Mole(volume.getVolumeInLitres().multiply(concentration.getConcentration(),
new MathContext(5, RoundingMode.HALF_UP)));
}
public Solution(String formula, Mole moles, Volume volume) throws NotationInterpretationException {
super(formula, moles);
this.volume = volume;
this.concentration = calculateConcentration(moles, volume);
}
public Solution(String formula, Mass mass, Volume volume) throws NotationInterpretationException {
super(formula, mass);
this.volume = volume;
this.concentration = calculateConcentration(getMoles(), volume);
}
public Solution(Molecule molecule, Mole moles, Volume volume) {
super(molecule, moles);
this.volume = volume;
this.concentration = calculateConcentration(moles, volume);
}
public Solution(Molecule molecule, Mass mass, Volume volume) {
super(molecule, mass);
this.volume = volume;
this.concentration = calculateConcentration(getMoles(), volume);
}
public Solution(String formula, Mole moles, Concentration concentration) throws NotationInterpretationException {
super(formula, moles);
this.concentration = concentration;
this.volume = calculateVolume(moles, concentration);
}
public Solution(String formula, Mass mass, Concentration concentration) throws NotationInterpretationException {
super(formula, mass);
this.concentration = concentration;
this.volume = calculateVolume(getMoles(), concentration);
}
public Solution(Molecule molecule, Mole moles, Concentration concentration) {
super(molecule, moles);
this.concentration = concentration;
this.volume = calculateVolume(moles, concentration);
}
public Solution(Molecule molecule, Mass mass, Concentration concentration) {
super(molecule, mass);
this.concentration = concentration;
this.volume = calculateVolume(getMoles(), concentration);
}
@Override
public String toString() {
return super.toString() + " in " + volume.toString() + " at " + concentration.toString();
}
public Volume getVolume() {
return volume;
}
public Concentration getConcentration() {
return concentration;
}
protected Volume volume;
// In dm3
protected Concentration concentration;
}
|
package net.sf.picard.sam;
import net.sf.picard.cmdline.CommandLineProgram;
import net.sf.picard.cmdline.Option;
import net.sf.picard.cmdline.StandardOptionDefinitions;
import net.sf.picard.cmdline.Usage;
import net.sf.picard.metrics.MetricsFile;
import net.sf.picard.util.Log;
import net.sf.picard.PicardException;
import net.sf.picard.io.IoUtil;
import net.sf.samtools.*;
import net.sf.samtools.util.SortingCollection;
import net.sf.samtools.util.SortingLongCollection;
import java.io.*;
import java.util.*;
/**
* A better duplication marking algorithm that handles all cases including clipped
* and gapped alignments.
*
* @author Tim Fennell
*/
public class MarkDuplicates extends CommandLineProgram {
private final Log log = Log.getInstance(MarkDuplicates.class);;
/**
* If more than this many sequences in SAM file, don't spill to disk because there will not
* be enough file handles.
*/
private static final int MAX_SEQUENCES_FOR_DISK_READ_ENDS_MAP = 500;
@Usage public final String USAGE =
"Examines aligned records in the supplied SAM or BAM file to locate duplicate molecules. " +
"All records are then written to the output file with the duplicate records flagged.";
@Option(shortName= StandardOptionDefinitions.INPUT_SHORT_NAME, doc="The input SAM or BAM file to analyze. Must be coordinate sorted.") public File INPUT;
@Option(shortName=StandardOptionDefinitions.OUTPUT_SHORT_NAME, doc="The output file to right marked records to") public File OUTPUT;
@Option(shortName="M", doc="File to write duplication metrics to") public File METRICS_FILE;
@Option(doc="If true do not write duplicates to the output file instead of writing them with appropriate flags set.") public boolean REMOVE_DUPLICATES = false;
@Option(doc="If true, assume that the input file is coordinate sorted, even if the header says otherwise.",
shortName = StandardOptionDefinitions.ASSUME_SORTED_SHORT_NAME)
public boolean ASSUME_SORTED = false;
private SortingCollection<ReadEnds> pairSort;
private SortingCollection<ReadEnds> fragSort;
private SortingLongCollection duplicateIndexes;
private int numDuplicateIndices = 0;
private Map<String,Short> libraryIds = new HashMap<String,Short>();
private short nextLibraryId = 1;
/** Stock main method. */
public static void main(final String[] args) {
System.exit(new MarkDuplicates().instanceMain(args));
}
/**
* Main work method. Reads the BAM file once and collects sorted information about
* the 5' ends of both ends of each read (or just one end in the case of pairs).
* Then makes a pass through those determining duplicates before re-reading the
* input file and writing it out with duplication flags set correctly.
*/
protected int doWork() {
IoUtil.assertFileIsReadable(INPUT);
IoUtil.assertFileIsWritable(OUTPUT);
IoUtil.assertFileIsWritable(METRICS_FILE);
reportMemoryStats("Start of doWork");
log.info("Reading input file and constructing read end information.");
buildSortedReadEndLists();
reportMemoryStats("After buildSortedReadEndLists");
generateDuplicateIndexes();
reportMemoryStats("After generateDuplicateIndexes");
log.info("Marking " + this.numDuplicateIndices + " records as duplicates.");
Map<String,DuplicationMetrics> metricsByLibrary = new HashMap<String,DuplicationMetrics>();
final SAMFileReader in = new SAMFileReader(INPUT);
final SAMFileHeader header = in.getFileHeader();
final SAMFileWriter out = new SAMFileWriterFactory().makeSAMOrBAMWriter(in.getFileHeader(),
true,
OUTPUT);
// Now copy over the file while marking all the necessary indexes as duplicates
long recordInFileIndex = 0;
long nextDuplicateIndex = (this.duplicateIndexes.hasNext() ? this.duplicateIndexes.next(): -1);
for (final SAMRecord rec : in) {
String library = getLibraryName(header, rec);
DuplicationMetrics metrics = metricsByLibrary.get(library);
if (metrics == null) {
metrics = new DuplicationMetrics();
metrics.LIBRARY = library;
metricsByLibrary.put(library, metrics);
}
// First bring the simple metrics up to date
if (rec.getReadUnmappedFlag()) {
++metrics.UNMAPPED_READS;
}
else if (!rec.getReadPairedFlag() || rec.getMateUnmappedFlag()) {
++metrics.UNPAIRED_READS_EXAMINED;
}
else {
++metrics.READ_PAIRS_EXAMINED; // will need to be divided by 2 at the end
}
if (recordInFileIndex++ == nextDuplicateIndex) {
rec.setDuplicateReadFlag(true);
// Update the duplication metrics
if (!rec.getReadPairedFlag() || rec.getMateUnmappedFlag()) {
++metrics.UNPAIRED_READ_DUPLICATES;
}
else {
++metrics.READ_PAIR_DUPLICATES;// will need to be divided by 2 at the end
}
// Now try and figure out the next duplicate index
if (this.duplicateIndexes.hasNext()) {
nextDuplicateIndex = this.duplicateIndexes.next();
} else {
// Only happens once we've marked all the duplicates
nextDuplicateIndex = -1;
}
}
else {
rec.setDuplicateReadFlag(false);
}
if (this.REMOVE_DUPLICATES && rec.getDuplicateReadFlag()) {
// do nothing
}
else {
out.addAlignment(rec);
}
}
reportMemoryStats("Before output close");
out.close();
reportMemoryStats("After output close");
// Write out the metrics
final MetricsFile<DuplicationMetrics,Double> file = getMetricsFile();
for (DuplicationMetrics metrics : metricsByLibrary.values()) {
metrics.READ_PAIRS_EXAMINED = metrics.READ_PAIRS_EXAMINED / 2;
metrics.READ_PAIR_DUPLICATES = metrics.READ_PAIR_DUPLICATES / 2;
metrics.calculateDerivedMetrics();
file.addMetric(metrics);
}
if (metricsByLibrary.size() == 1) {
file.setHistogram(metricsByLibrary.values().iterator().next().calculateRoiHistogram());
}
file.write(METRICS_FILE);
return 0;
}
private void reportMemoryStats(final String stage) {
System.gc();
final Runtime runtime = Runtime.getRuntime();
log.info(stage + " freeMemory: " + runtime.freeMemory() + "; totalMemory: " + runtime.totalMemory() +
"; maxMemory: " + runtime.maxMemory());
}
/**
* Goes through all the records in a file and generates a set of ReadEnds objects that
* hold the necessary information (reference sequence, 5' read coordinate) to do
* duplication, caching to disk as necssary to sort them.
*/
private void buildSortedReadEndLists() {
final int maxInMemory = (int) ((Runtime.getRuntime().maxMemory() * 0.25) / ReadEnds.SIZE_OF);
log.info("Will retain up to " + maxInMemory + " data points before spilling to disk.");
this.pairSort = SortingCollection.newInstance(ReadEnds.class,
new ReadEndsCodec(),
new ReadEndsComparator(),
maxInMemory);
this.fragSort = SortingCollection.newInstance(ReadEnds.class,
new ReadEndsCodec(),
new ReadEndsComparator(),
maxInMemory);
final SAMFileReader sam = new SAMFileReader(INPUT);
final SAMFileHeader header = sam.getFileHeader();
if (header.getSortOrder() != SAMFileHeader.SortOrder.coordinate) {
if (ASSUME_SORTED) {
log.info("Assuming input is coordinate sorted.");
} else {
throw new PicardException(INPUT + " is not coordinate sorted.");
}
}
final ReadEndsMap tmp;
if (header.getSequenceDictionary().getSequences().size() > MAX_SEQUENCES_FOR_DISK_READ_ENDS_MAP) {
tmp = new RAMReadEndsMap();
} else {
tmp = new DiskReadEndsMap();
}
long index = 0;
for (final SAMRecord rec : sam) {
if (rec.getReadUnmappedFlag()) {
if (rec.getReferenceIndex() == -1) {
// When we hit the unmapped reads with no coordinate, no reason to continue.
break;
}
// If this read is unmapped but sorted with the mapped reads, just skip it.
}
else {
final ReadEnds fragmentEnd = buildReadEnds(header, index, rec);
this.fragSort.add(fragmentEnd);
if (rec.getReadPairedFlag() && !rec.getMateUnmappedFlag()) {
final String key = rec.getAttribute(ReservedTagConstants.READ_GROUP_ID) + ":" + rec.getReadName();
ReadEnds pairedEnds = tmp.remove(rec.getReferenceIndex(), key);
// See if we've already seen the first end or not
if (pairedEnds == null) {
pairedEnds = buildReadEnds(header, index, rec);
tmp.put(pairedEnds.read2Sequence, key, pairedEnds);
}
else {
final int sequence = fragmentEnd.read1Sequence;
final int coordinate = fragmentEnd.read1Coordinate;
// If the second read is actually later, just add the second read data, else flip the reads
if (sequence > pairedEnds.read1Sequence ||
(sequence == pairedEnds.read1Sequence && coordinate >= pairedEnds.read1Coordinate)) {
pairedEnds.read2Sequence = sequence;
pairedEnds.read2Coordinate = coordinate;
pairedEnds.read2IndexInFile = index;
pairedEnds.orientation = getOrientationByte(pairedEnds.orientation == ReadEnds.R,
rec.getReadNegativeStrandFlag());
}
else {
pairedEnds.read2Sequence = pairedEnds.read1Sequence;
pairedEnds.read2Coordinate = pairedEnds.read1Coordinate;
pairedEnds.read2IndexInFile = pairedEnds.read1IndexInFile;
pairedEnds.read1Sequence = sequence;
pairedEnds.read1Coordinate = coordinate;
pairedEnds.read1IndexInFile = index;
pairedEnds.orientation = getOrientationByte(rec.getReadNegativeStrandFlag(),
pairedEnds.orientation == ReadEnds.R);
}
pairedEnds.score += getScore(rec);
this.pairSort.add(pairedEnds);
}
}
}
// Print out some stats every 1m reads
if (++index % 1000000 == 0) {
log.info("Read " + index + " records. Tracking " + tmp.size() + " as yet unmatched pairs. " +
tmp.sizeInRam() + " records in RAM. Last sequence index: " + rec.getReferenceIndex());
}
}
log.info("Read " + index + " records. " + tmp.size() + " pairs never matched.");
sam.close();
// Tell these collections to free up memory if possible.
this.pairSort.doneAdding();
this.fragSort.doneAdding();
}
/** Builds a read ends object that represents a single read. */
private ReadEnds buildReadEnds(final SAMFileHeader header, final long index, final SAMRecord rec) {
final ReadEnds ends = new ReadEnds();
ends.read1Sequence = rec.getReferenceIndex();
ends.read1Coordinate = rec.getReadNegativeStrandFlag() ? rec.getUnclippedEnd() : rec.getUnclippedStart();
ends.orientation = rec.getReadNegativeStrandFlag() ? ReadEnds.R : ReadEnds.F;
ends.read1IndexInFile = index;
ends.score = getScore(rec);
// Doing this lets the ends object know that it's part of a pair
if (rec.getReadPairedFlag() && !rec.getMateUnmappedFlag()) {
ends.read2Sequence = rec.getMateReferenceIndex();
}
// Fill in the library ID
ends.libraryId = getLibraryId(header, rec);
return ends;
}
/** Get the library ID for the given SAM record. */
private short getLibraryId(SAMFileHeader header, SAMRecord rec) {
final String library = getLibraryName(header, rec);
Short libraryId = this.libraryIds.get(library);
if (libraryId == null) {
libraryId = this.nextLibraryId++;
this.libraryIds.put(library, libraryId);
}
return libraryId;
}
/**
* Gets the library name from the header for the record. If the RG tag is not present on
* the record, or the library isn't denoted on the read group, a constant string is
* returned.
*/
private String getLibraryName(SAMFileHeader header, SAMRecord rec) {
final String readGroupId = (String) rec.getAttribute("RG");
if (readGroupId != null) {
SAMReadGroupRecord rg = header.getReadGroup(readGroupId);
if (rg != null) {
return rg.getLibrary();
}
}
return "Unknown Library";
}
/**
* Returns a single byte that encodes the orientation of the two reads in a pair.
*/
private byte getOrientationByte(final boolean read1NegativeStrand, final boolean read2NegativeStrand) {
if (read1NegativeStrand) {
if (read2NegativeStrand) return ReadEnds.RR;
else return ReadEnds.RF;
}
else {
if (read2NegativeStrand) return ReadEnds.FR;
else return ReadEnds.FF;
}
}
/** Calculates a score for the read which is the sum of scores over Q20. */
private short getScore(final SAMRecord rec) {
short score = 0;
for (final byte b : rec.getBaseQualities()) {
if (b >= 15) score += b;
}
return score;
}
/**
* Goes through the accumulated ReadEnds objects and determines which of them are
* to be marked as duplicates.
*
* @return an array with an ordered list of indexes into the source file
*/
private void generateDuplicateIndexes() {
final int maxInMemory = (int) ((Runtime.getRuntime().maxMemory() * 0.25) / SortingLongCollection.SIZEOF);
log.info("Will retain up to " + maxInMemory + " duplicate indices before spilling to disk.");
this.duplicateIndexes = new SortingLongCollection(maxInMemory, TMP_DIR);
ReadEnds firstOfNextChunk = null;
final List<ReadEnds> nextChunk = new ArrayList<ReadEnds>(200);
// First just do the pairs
log.info("Traversing read pair information and detecting duplicates.");
for (final ReadEnds next : this.pairSort) {
if (firstOfNextChunk == null) {
firstOfNextChunk = next;
nextChunk.add(firstOfNextChunk);
}
else if (areComparableForDuplicates(firstOfNextChunk, next, true)) {
nextChunk.add(next);
}
else {
if (nextChunk.size() > 1) {
markDuplicatePairs(nextChunk);
}
nextChunk.clear();
nextChunk.add(next);
firstOfNextChunk = next;
}
}
markDuplicatePairs(nextChunk);
this.pairSort = null;
// Now deal with the fragments
log.info("Traversing fragment information and detecting duplicates.");
boolean containsPairs = false;
boolean containsFrags = false;
for (final ReadEnds next : this.fragSort) {
if (firstOfNextChunk != null && areComparableForDuplicates(firstOfNextChunk, next, false)) {
nextChunk.add(next);
containsPairs = containsPairs || next.isPaired();
containsFrags = containsFrags || !next.isPaired();
}
else {
if (nextChunk.size() > 1 && containsFrags) {
markDuplicateFragments(nextChunk, containsPairs);
}
nextChunk.clear();
nextChunk.add(next);
firstOfNextChunk = next;
containsPairs = next.isPaired();
containsFrags = !next.isPaired();
}
}
markDuplicateFragments(nextChunk, containsPairs);
this.fragSort = null;
log.info("Sorting list of duplicate records.");
this.duplicateIndexes.doneAddingStartIteration();
}
private boolean areComparableForDuplicates(final ReadEnds lhs, final ReadEnds rhs, final boolean compareRead2) {
boolean retval = lhs.libraryId == rhs.libraryId &&
lhs.read1Sequence == rhs.read1Sequence &&
lhs.read1Coordinate == rhs.read1Coordinate &&
lhs.orientation == rhs.orientation;
if (retval && compareRead2) {
retval = lhs.read2Sequence == rhs.read2Sequence &&
lhs.read2Coordinate == rhs.read2Coordinate;
}
return retval;
}
private void addIndexAsDuplicate(final long bamIndex) {
this.duplicateIndexes.add(bamIndex);
++this.numDuplicateIndices;
}
/**
* Takes a list of ReadEnds objects and removes from it all objects that should
* not be marked as duplicates.
*
* @param list
*/
private void markDuplicatePairs(final List<ReadEnds> list) {
short maxScore = 0;
ReadEnds best = null;
for (final ReadEnds end : list) {
if (end.score > maxScore || best == null) {
maxScore = end.score;
best = end;
}
}
for (final ReadEnds end : list) {
if (end != best) {
addIndexAsDuplicate(end.read1IndexInFile);
addIndexAsDuplicate(end.read2IndexInFile);
}
}
}
/**
* Takes a list of ReadEnds objects and removes from it all objects that should
* not be marked as duplicates.
*
* @param list
*/
private void markDuplicateFragments(final List<ReadEnds> list, final boolean containsPairs) {
if (containsPairs) {
for (final ReadEnds end : list) {
if (!end.isPaired()) addIndexAsDuplicate(end.read1IndexInFile);
}
}
else {
short maxScore = 0;
ReadEnds best = null;
for (final ReadEnds end : list) {
if (end.score > maxScore || best == null) {
maxScore = end.score;
best = end;
}
}
for (final ReadEnds end : list) {
if (end != best) {
addIndexAsDuplicate(end.read1IndexInFile);
}
}
}
}
/** Comparator for ReadEnds that orders by read1 position then pair orientation then read2 position. */
static class ReadEndsComparator implements Comparator<ReadEnds> {
public int compare(final ReadEnds lhs, final ReadEnds rhs) {
int retval = lhs.libraryId - rhs.libraryId;
if (retval == 0) retval = lhs.read1Sequence - rhs.read1Sequence;
if (retval == 0) retval = lhs.read1Coordinate - rhs.read1Coordinate;
if (retval == 0) retval = lhs.orientation - rhs.orientation;
if (retval == 0) retval = lhs.read2Sequence - rhs.read2Sequence;
if (retval == 0) retval = lhs.read2Coordinate - rhs.read2Coordinate;
if (retval == 0) retval = (int) (lhs.read1IndexInFile - rhs.read1IndexInFile);
if (retval == 0) retval = (int) (lhs.read2IndexInFile - rhs.read2IndexInFile);
return retval;
}
}
}
|
package org.apache.commons.codec;
/**
* <p>Provides the highest level of abstraction for Encoders.
* This is the sister interface of {@link Decoder}. Every implementation of
* Encoder provides this common generic interface whic allows a user to pass a
* generic Object to any Encoder implementation in the codec package.</p>
*
* @author Tim O'Brien
* @author Gary Gregory
* @version $Id: Encoder.java,v 1.5 2003/10/04 16:24:14 tobrien Exp $
*/
public interface Encoder {
/**
* Encodes an "Object" and returns the encoded content
* as an Object. The Objects here may just be <code>byte[]</code>
* or <code>String</code>s depending on the implementation used.
*
* @param pObject An object ot encode
*
* @return An "encoded" Object
*
* @throws EncoderException an encoder exception is
* thrown if the encoder experiences a failure
* condition during the encoding process.
*/
Object encode(Object pObject) throws EncoderException;
}
|
package org.jdesktop.swingx;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractButton;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
/**
* @author Amy Fowler
* @version 1.0
*/
public class JXRadioGroup extends JPanel {
private static final long serialVersionUID = 3257285842266567986L;
private ButtonGroup buttonGroup;
private List<Object> values = new ArrayList<Object>();
private ActionSelectionListener actionHandler;
private List<ActionListener> actionListeners;
public JXRadioGroup() {
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
buttonGroup = new ButtonGroup();
}
public JXRadioGroup(Object radioValues[]) {
this();
for(int i = 0; i < radioValues.length; i++) {
add(radioValues[i]);
}
}
public void setValues(Object[] radioValues) {
clearAll();
for(int i = 0; i < radioValues.length; i++) {
add(radioValues[i]);
}
}
private void clearAll() {
values.clear();
removeAll();
buttonGroup = new ButtonGroup();
}
public void add(Object radioValue) {
values.add(radioValue);
addButton(new JRadioButton(radioValue.toString()));
}
public void add(AbstractButton button) {
values.add(button.getText());
// PENDING: mapping needs cleanup...
addButton(button);
}
private void addButton(AbstractButton button) {
buttonGroup.add(button);
super.add(button);
if (actionHandler == null) {
actionHandler = new ActionSelectionListener();
}
button.addActionListener(actionHandler);
button.addItemListener(actionHandler);
}
private class ActionSelectionListener implements ActionListener,
ItemListener {
public void actionPerformed(ActionEvent e) {
fireActionEvent(e);
}
public void itemStateChanged(ItemEvent e) {
fireActionEvent(null);
}
}
public AbstractButton getSelectedButton() {
ButtonModel selectedModel = buttonGroup.getSelection();
AbstractButton children[] = getButtonComponents();
for(int i = 0; i < children.length; i++) {
AbstractButton button = (AbstractButton)children[i];
if (button.getModel() == selectedModel) {
return button;
}
}
return null;
}
private AbstractButton[] getButtonComponents() {
Component[] children = getComponents();
List<AbstractButton> buttons = new ArrayList<AbstractButton>();
for (int i = 0; i < children.length; i++) {
if (children[i] instanceof AbstractButton) {
buttons.add((AbstractButton) children[i]);
}
}
return (AbstractButton[]) buttons.toArray(new AbstractButton[buttons.size()]);
}
private int getSelectedIndex() {
ButtonModel selectedModel = buttonGroup.getSelection();
Component children[] = getButtonComponents();
for (int i = 0; i < children.length; i++) {
AbstractButton button = (AbstractButton) children[i];
if (button.getModel() == selectedModel) {
return i;
}
}
return -1;
}
public Object getSelectedValue() {
int index = getSelectedIndex();
return (index < 0 || index >= values.size()) ? null : values.get(index);
}
public void setSelectedValue(Object value) {
int index = values.indexOf(value);
AbstractButton button = getButtonComponents()[index];
button.setSelected(true);
}
public void addActionListener(ActionListener l) {
if (actionListeners == null) {
actionListeners = new ArrayList<ActionListener>();
}
actionListeners.add(l);
}
public void removeActionListener(ActionListener l) {
if (actionListeners != null) {
actionListeners.remove(l);
}
}
public ActionListener[] getActionListeners() {
if (actionListeners != null) {
return (ActionListener[])actionListeners.toArray(new ActionListener[0]);
}
return new ActionListener[0];
}
protected void fireActionEvent(ActionEvent e) {
if (actionListeners != null) {
for (int i = 0; i < actionListeners.size(); i++) {
ActionListener l = (ActionListener) actionListeners.get(i);
l.actionPerformed(e);
}
}
}
}
|
package com.restfb.types;
import static java.util.Collections.unmodifiableList;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.restfb.Facebook;
import com.restfb.util.DateUtils;
import com.restfb.util.ReflectionUtils;
import com.restfb.util.StringUtils;
public class User extends NamedFacebookType {
@Facebook("first_name")
private String firstName;
@Facebook("middle_name")
private String middleName;
@Facebook("last_name")
private String lastName;
@Facebook
private String link;
@Facebook
private String bio;
@Facebook
private String about;
@Facebook("relationship_status")
private String relationshipStatus;
@Facebook
private String religion;
@Facebook
private String website;
@Facebook
private String birthday;
@Facebook
private String email;
@Facebook
private Double timezone;
@Facebook
private Boolean verified;
@Facebook
private String gender;
@Facebook
private String political;
@Facebook
private String locale;
@Facebook
private NamedFacebookType hometown;
@Facebook
private NamedFacebookType location;
@Facebook("significant_other")
private NamedFacebookType significantOther;
@Facebook("updated_time")
private String updatedTime;
@Facebook(value = "interested_in", contains = String.class)
private List<String> interestedIn = new ArrayList<String>();
@Facebook(value = "meeting_for", contains = String.class)
private List<String> meetingFor = new ArrayList<String>();
@Facebook(contains = Work.class)
private List<Work> work = new ArrayList<Work>();
@Facebook(contains = Education.class)
private List<Education> education = new ArrayList<Education>();
public static class Work {
@Facebook
private NamedFacebookType employer;
@Facebook
private NamedFacebookType location;
@Facebook
private NamedFacebookType position;
@Facebook("start_date")
private String startDate;
@Facebook("end_date")
private String endDate;
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return ReflectionUtils.hashCode(this);
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object that) {
return ReflectionUtils.equals(this, that);
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return ReflectionUtils.toString(this);
}
/**
* The employer for this job.
*
* @return The employer for this job.
*/
public NamedFacebookType getEmployer() {
return employer;
}
/**
* The location of this job.
*
* @return The location of this job.
*/
public NamedFacebookType getLocation() {
return location;
}
/**
* Position held at this job.
*
* @return Position held at this job.
*/
public NamedFacebookType getPosition() {
return position;
}
/**
* Date this job was started.
*
* @return Date this job was started.
*/
public Date getStartDate() {
return DateUtils.toDateFromMonthYearFormat(startDate);
}
/**
* Date this job ended.
*
* @return Date this job ended.
*/
public Date getEndDate() {
return DateUtils.toDateFromMonthYearFormat(endDate);
}
}
public static class Education {
@Facebook
private NamedFacebookType school;
@Facebook
private NamedFacebookType year;
@Facebook
private NamedFacebookType degree;
@Facebook(value = "concentration", contains = NamedFacebookType.class)
private List<NamedFacebookType> concentration = new ArrayList<NamedFacebookType>();
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return ReflectionUtils.hashCode(this);
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object that) {
return ReflectionUtils.equals(this, that);
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return ReflectionUtils.toString(this);
}
/**
* The school name and ID.
*
* @return The school name and ID.
*/
public NamedFacebookType getSchool() {
return school;
}
/**
* Graduation year.
*
* @return Graduation year.
*/
public NamedFacebookType getYear() {
return year;
}
/**
* Degree acquired.
*
* @return Degree acquired.
*/
public NamedFacebookType getDegree() {
return degree;
}
/**
* Concentrations/minors.
*
* @return Concentrations/minors.
*/
public List<NamedFacebookType> getConcentration() {
return unmodifiableList(concentration);
}
}
/**
* The user's first name.
*
* @return The user's first name.
*/
public String getFirstName() {
return firstName;
}
/**
* The user's middle name.
*
* @return The user's middle name.
*/
public String getMiddleName() {
return middleName;
}
/**
* The user's last name.
*
* @return The user's last name.
*/
public String getLastName() {
return lastName;
}
/**
* A link to the user's profile.
*
* @return A link to the user's profile.
*/
public String getLink() {
return link;
}
/**
* The user's blurb that appears under their profile picture.
*
* @return The user's blurb that appears under their profile picture.
*/
public String getAbout() {
return about;
}
/**
* The user's relationship status.
*
* @return The user's relationship status.
*/
public String getRelationshipStatus() {
return relationshipStatus;
}
/**
* The user's birthday as a {@code String}.
* <p>
* Will always succeed, even if the user has specified month/year format only.
* If you'd like to use a typed version of this accessor, call
* {@link #getBirthdayAsDate()} instead.
*
* @return The user's birthday as a {@code String}.
*/
public String getBirthday() {
return birthday;
}
/**
* The user's birthday, typed to {@code java.util.Date} if possible.
*
* @return The user's birthday, or {@code null} if unavailable or only
* available in month/year format.
*/
public Date getBirthdayAsDate() {
if (StringUtils.isBlank(getBirthday()) || getBirthday().split("/").length < 2)
return null;
return DateUtils.toDateFromShortFormat(birthday);
}
/**
* The user's religion.
*
* @return The user's religion.
*/
public String getReligion() {
return religion;
}
/**
* A link to the user's personal website.
*
* @return A link to the user's personal website.
*/
public String getWebsite() {
return website;
}
/**
* The proxied or contact email address granted by the user.
*
* @return The proxied or contact email address granted by the user.
*/
public String getEmail() {
return email;
}
/**
* The user's timezone offset.
*
* @return The user's timezone offset.
*/
public Double getTimezone() {
return timezone;
}
/**
* Is the user verified?
*
* @return User verification status.
*/
public Boolean getVerified() {
return verified;
}
/**
* Date the user's profile was updated.
*
* @return Date the user's profile was updated.
*/
public Date getUpdatedTime() {
return DateUtils.toDateFromLongFormat(updatedTime);
}
/**
* The user's gender.
*
* @return The user's gender.
*/
public String getGender() {
return gender;
}
/**
* The user's biographical snippet.
*
* @return The user's biographical snippet.
*/
public String getBio() {
return bio;
}
/**
* The user's political affiliation.
*
* @return The user's political affiliation.
*/
public String getPolitical() {
return political;
}
/**
* The user's locale.
*
* @return The user's locale.
*/
public String getLocale() {
return locale;
}
/**
* The user's hometown.
*
* @return The user's hometown.
*/
public NamedFacebookType getHometown() {
return hometown;
}
/**
* The user's current location.
*
* @return The user's current location.
*/
public NamedFacebookType getLocation() {
return location;
}
/**
* The user's significant other.
*
* @return The user's significant other.
*/
public NamedFacebookType getSignificantOther() {
return significantOther;
}
/**
* The user's interests.
*
* @return The user's interests.
*/
public List<String> getInterestedIn() {
return unmodifiableList(interestedIn);
}
/**
* What genders the user is interested in meeting.
*
* @return What genders the user is interested in meeting.
*/
public List<String> getMeetingFor() {
return unmodifiableList(meetingFor);
}
/**
* A list of the work history from the user's profile
*
* @return A list of the work history from the user's profile
*/
public List<Work> getWork() {
return unmodifiableList(work);
}
/**
* A list of the education history from the user's profile
*
* @return A list of the education history from the user's profile
*/
public List<Education> getEducation() {
return unmodifiableList(education);
}
}
|
package com.pdsuk.cordova.bluetoothle;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.UUID;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.io.UnsupportedEncodingException;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.util.Base64;
import android.util.Log;
public class BluetoothLePlugin extends CordovaPlugin {
private CallbackContext connectCallback;
private CallbackContext disconnectCallback;
private CallbackContext onDeviceAddedCallback;
private CallbackContext onDeviceDroppedCallback;
private CallbackContext onAdapterStateChangedCallback;
private CallbackContext onCharacteristicValueChangedCallback;
private CallbackContext rssiCallback;
private CallbackContext deviceInfoCallback;
private Map<CallbackKey, CallbackContext> readWriteCallbacks;
private Map<String, BluetoothGatt> connectedGattServers;
private Context mContext;
private boolean mRegisteredReceiver = false;
private boolean mRegisteredPairingReceiver = false;
//Client Configuration UUID for notifying/indicating
private final UUID clientConfigurationDescriptorUuid = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
this.connectedGattServers = new HashMap<String, BluetoothGatt>();
this.readWriteCallbacks = new HashMap<CallbackKey, CallbackContext>();
cordova.getActivity().registerReceiver(mReceiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
}
private String getLongUUID(String uuid) {
if (uuid.length() == 4) {
return "0000" + uuid + "-0000-1000-8000-00805f9b34fb";
}
return uuid;
}
@Override
public boolean execute(final String action, final JSONArray args, final CallbackContext callback) throws JSONException {
try {
if ("getAdapterState".equals(action)) {
getAdapterState(callback);
} else if ("startDiscovery".equals(action)) {
startDiscovery(callback);
} else if ("stopDiscovery".equals(action)) {
stopDiscovery(callback);
} else if ("connect".equals(action)) {
connect(args.getString(0), callback);
} else if ("disconnect".equals(action)) {
disconnect(args.getString(0), callback);
} else if ("isSupported".equals(action)) {
JSONObject result = new JSONObject();
result.put("isSupported", isSupported());
callback.success(result);
} else if ("isConnected".equals(action)) {
JSONObject result = new JSONObject();
result.put("isConnected", isConnected(args.getString(0)));
callback.success(result);
} else if ("_close".equals(action)) {
close(args.getString(0), callback);
} else if ("getService".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
getService(address, serviceId, callback);
} else if ("getServices".equals(action)) {
String address = args.getString(0);
getServices(address, callback);
} else if ("getDevice".equals(action)) {
String address = args.getString(0);
getDeviceInfo(address, callback);
} else if ("getCharacteristic".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
String characteristicId = getLongUUID(args.getString(2));
getCharacteristic(address, serviceId, characteristicId, callback);
} else if ("getCharacteristics".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
getCharacteristics(address, serviceId, callback);
} else if ("getIncludedServices".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
getIncludedServices(address, serviceId, callback);
} else if ("getDescriptor".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
String characteristicId = getLongUUID(args.getString(2));
String descriptorId = getLongUUID(args.getString(3));
getDescriptor(address, serviceId, characteristicId, descriptorId, callback);
} else if ("getDescriptors".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
String characteristicId = getLongUUID(args.getString(2));
getDescriptors(address, serviceId, characteristicId, callback);
} else if ("readCharacteristicValue".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
String characteristicId = getLongUUID(args.getString(2));
readCharacteristicValue(address, serviceId, characteristicId, callback);
} else if ("writeCharacteristicValue".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
String characteristicId = getLongUUID(args.getString(2));
byte[] value = Base64.decode(args.getString(3), Base64.NO_WRAP);
writeCharacteristicValue(address, serviceId, characteristicId, value, callback);
} else if ("startCharacteristicNotifications".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
String characteristicId = getLongUUID(args.getString(2));
startCharacteristicNotifications(address, serviceId, characteristicId, callback);
} else if ("stopCharacteristicNotifications".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
String characteristicId = getLongUUID(args.getString(2));
stopCharacteristicNotifications(address, serviceId, characteristicId, callback);
} else if ("readDescriptorValue".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
String characteristicId = getLongUUID(args.getString(2));
String descriptorId = getLongUUID(args.getString(3));
readDescriptorValue(address, serviceId, characteristicId, descriptorId, callback);
} else if ("writeDescriptorValue".equals(action)) {
String address = args.getString(0);
String serviceId = getLongUUID(args.getString(1));
String characteristicId = getLongUUID(args.getString(2));
String descriptorId = getLongUUID(args.getString(3));
byte[] value = Base64.decode(args.getString(3), Base64.NO_WRAP);
writeDescriptorValue(address, serviceId, characteristicId, descriptorId, value, callback);
} else if ("onDeviceAdded".equals(action)) {
onDeviceAddedCallback = callback;
} else if ("onDeviceDropped".equals(action)) {
onDeviceDroppedCallback = callback;
} else if ("onAdapterStateChanged".equals(action)) {
onAdapterStateChangedCallback = callback;
} else if ("onCharacteristicValueChanged".equals(action)) {
onCharacteristicValueChangedCallback = callback;
} else {
return false;
}
} catch (Exception e) {
callback.error(JSONObjects.asError(e));
}
return true;
}
private BluetoothManager getBluetoothManager() {
return (BluetoothManager) cordova.getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
}
private BluetoothDevice getDevice(String address) throws Exception {
BluetoothManager bluetoothManager = (BluetoothManager) cordova.getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
BluetoothDevice device = bluetoothManager.getAdapter().getRemoteDevice(address);
if (device == null) {
throw new Exception("Unable to find device with address " + address);
}
return device;
}
private void getDeviceInfo(String address, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
deviceInfoCallback = callback;
boolean result = gatt.readRemoteRssi();
if (!result) {
throw new Exception("Could not initiate BluetoothGatt#readRemoteRssi. Android didn't tell us why either.");
}
}
private void getAdapterState(CallbackContext callback) {
BluetoothManager bluetoothManager = (BluetoothManager) cordova.getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
callback.success(JSONObjects.asAdapter(bluetoothManager.getAdapter()));
}
private BluetoothAdapter.LeScanCallback scanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] ad) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
JSONObject obj = JSONObjects.asDevice(device, rssi, ad);
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, obj);
pluginResult.setKeepCallback(true);
onDeviceAddedCallback.sendPluginResult(pluginResult);
}
});
}
};
private void startDiscovery(CallbackContext callback) throws Exception {
BluetoothManager bluetoothManager = getBluetoothManager();
boolean result = bluetoothManager.getAdapter().startLeScan(scanCallback);
if (!result) {
throw new Exception("Could not start scan (BluetoothAdapter#startLeScan). Android didn't tell us why either.");
}
callback.success();
}
private void stopDiscovery(CallbackContext callback) {
BluetoothManager bluetoothManager = getBluetoothManager();
bluetoothManager.getAdapter().stopLeScan(scanCallback);
callback.success();
}
private boolean isSupported() {
if (android.os.Build.VERSION.SDK_INT >= 18) {
return cordova.getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE);
}
return false;
}
private boolean isConnected(String address) {
BluetoothManager bluetoothManager = getBluetoothManager();
List<BluetoothDevice> devices = bluetoothManager.getConnectedDevices(BluetoothProfile.GATT_SERVER);
for (BluetoothDevice device : devices) {
if (device.getAddress().equals(address)) {
return true;
}
}
return false;
}
private BluetoothDevice getPairedDevice(final BluetoothAdapter adapter, String address) {
Set<BluetoothDevice> devices = adapter.getBondedDevices();
Iterator<BluetoothDevice> it = devices.iterator();
while (it.hasNext()) {
BluetoothDevice device = (BluetoothDevice) it.next();
if (address.equals(device.getAddress()))
return device;
}
return null;
}
private void unpairDevice(BluetoothDevice device) {
try {
Method method = BluetoothDevice.class.getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
Log.i("bluetoothle", "BondedDevice : removeBond()");
} catch (Exception e) {
Log.e("bluetoothle", e.getMessage());
e.printStackTrace();
}
}
void pairDevice(BluetoothDevice device) {
try {
device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
//device.getClass().getMethod("cancelPairingUserInput", boolean.class).invoke(device, true);
byte[] passkey = ByteBuffer.allocate(6).putInt(000000).array();
Log.i("bluetoothle", "Passkey : " + passkey.toString());
Method m = device.getClass().getMethod("setPin", byte[].class);
m.invoke(device, passkey);
Method bond = device.getClass().getMethod("createBond", (Class[]) null);
bond.invoke(device, (Object[]) null);
Log.i("bluetoothle", "Bonded Device : remove()");
} catch (Exception e) {
e.printStackTrace();
}
}
private void connect(String address, CallbackContext callback) throws Exception {
if (isConnected(address)) {
callback.success();
return;
}
connectCallback = callback;
BluetoothDevice device = getDevice(address);
if (device.getBondState() == 12) {
}
BluetoothGatt gatt = device.connectGatt(cordova.getActivity().getApplicationContext(), false, gattCallback);
connectedGattServers.put(gatt.getDevice().getAddress(), gatt);
}
private void disconnect(String address, CallbackContext callback) throws Exception {
if (!isConnected(address)) {
callback.success();
return;
}
disconnectCallback = callback;
BluetoothGatt gatt = connectedGattServers.get(address);
gatt.disconnect();
}
private void close(String address, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
connectedGattServers.remove(gatt.getDevice().getAddress());
gatt.close();
if (gatt.getDevice().getBondState() == BluetoothDevice.BOND_BONDED) {
connectedGattServers.remove(address);
}
callback.success();
}
private void getService(String address, String uuid, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(uuid));
if (service == null) {
throw new Exception(String.format("No service found with the given UUID %s", uuid));
}
callback.success(JSONObjects.asService(service, gatt.getDevice()));
}
private void getServices(String address, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
JSONArray result = new JSONArray();
for (BluetoothGattService s : gatt.getServices()) {
result.put(JSONObjects.asService(s, gatt.getDevice()));
}
callback.success(result);
}
private void getCharacteristic(String address, String serviceId, String characteristicId, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristicId));
if (characteristic == null) {
throw new Exception(String.format("No characteristic found with the given UUID %s", characteristicId));
}
callback.success(JSONObjects.asCharacteristic(characteristic));
}
private void getCharacteristics(String address, String serviceId, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
JSONArray result = new JSONArray();
for (BluetoothGattCharacteristic c : service.getCharacteristics()) {
result.put(JSONObjects.asCharacteristic(c));
}
callback.success(result);
}
private void getIncludedServices(String address, String serviceId, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
JSONArray result = new JSONArray();
for (BluetoothGattService s : service.getIncludedServices()) {
result.put(JSONObjects.asService(s, gatt.getDevice()));
}
callback.success(result);
}
private void getDescriptor(String address, String serviceId, String characteristicId, String descriptorId, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristicId));
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(descriptorId));
if (descriptor == null) {
throw new Exception(String.format("No descriptor found with the given UUID %s", descriptorId));
}
callback.success(JSONObjects.asDescriptor(descriptor));
}
private void getDescriptors(String address, String serviceId, String characteristicId, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristicId));
JSONArray result = new JSONArray();
for (BluetoothGattDescriptor d : characteristic.getDescriptors()) {
result.put(JSONObjects.asDescriptor(d));
}
callback.success(result);
}
private void readCharacteristicValue(String address, String serviceId, String characteristicId, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristicId));
CallbackKey key = new CallbackKey(gatt, characteristic, "readCharacteristicValue");
readWriteCallbacks.put(key, callback);
boolean result = gatt.readCharacteristic(characteristic);
if (!result) {
readWriteCallbacks.remove(key);
throw new Exception(String.format("Could not initiate characteristic read operation for %s", characteristicId));
}
}
private void writeCharacteristicValue(String address, String serviceId, String characteristicId, byte[] value, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristicId));
boolean result = characteristic.setValue(value);
if (!result) {
throw new Exception("Could not store characteristic value");
}
CallbackKey key = new CallbackKey(gatt, characteristic, "writeCharacteristicValue");
readWriteCallbacks.put(key, callback);
if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0) {
characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);
} else if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) != 0) {
characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);
}
result = gatt.writeCharacteristic(characteristic);
if (!result) {
readWriteCallbacks.remove(key);
throw new Exception("Could not initiate characteristic write operation");
}
}
private void startCharacteristicNotifications(String address, String serviceId, String characteristicId, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristicId));
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(clientConfigurationDescriptorUuid);
boolean result = false;
result = gatt.setCharacteristicNotification(characteristic, true);
if (!result) {
throw new Exception("Could not set enable notifications/indications");
}
if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
result = descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
} else if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) {
result = descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
} else {
throw new Exception("The device does not support notifications/indications on the given characteristic.");
}
if (!result) {
gatt.setCharacteristicNotification(characteristic, false);
throw new Exception("Could not store notification/indication value on the characteristic's configuration descriptor");
}
CallbackKey key = new CallbackKey(gatt, descriptor, "writeDescriptorValue");
readWriteCallbacks.put(key, callback);
result = gatt.writeDescriptor(descriptor);
if (!result) {
gatt.setCharacteristicNotification(characteristic, false);
readWriteCallbacks.remove(key);
throw new Exception("Could not initiate writing the notification/indication value on the characteristic's configuration descriptor");
}
}
private void stopCharacteristicNotifications(String address, String serviceId, String characteristicId, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristicId));
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(clientConfigurationDescriptorUuid);
boolean result = false;
result = gatt.setCharacteristicNotification(characteristic, false);
if (!result) {
throw new Exception("Could not disable notifications/indications");
}
if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
result = descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
} else if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE) != 0) {
// yes, supposedly disabling "indications" is done the same as disabling "notifications"
result = descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
} else {
throw new Exception("The device does not support notifications/indications on the given characteristic.");
}
if (!result) {
throw new Exception("Could not store notification/indication value on the characteristic's configuration descriptor");
}
CallbackKey key = new CallbackKey(gatt, descriptor, "writeDescriptorValue");
readWriteCallbacks.put(key, callback);
result = gatt.writeDescriptor(descriptor);
if (!result) {
readWriteCallbacks.remove(key);
throw new Exception("Could not initiate writing the notification/indication value on the characteristic's configuration descriptor");
}
}
private void readDescriptorValue(String address, String serviceId, String characteristicId, String descriptorId, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristicId));
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(descriptorId));
CallbackKey key = new CallbackKey(gatt, descriptor, "readDescriptorValue");
readWriteCallbacks.put(key, callback);
boolean result = gatt.readDescriptor(descriptor);
if (!result) {
readWriteCallbacks.remove(key);
throw new Exception("Could not initiate reading descriptor");
}
}
private void writeDescriptorValue(String address, String serviceId, String characteristicId, String descriptorId, byte[] value, CallbackContext callback) throws Exception {
BluetoothGatt gatt = connectedGattServers.get(address);
BluetoothGattService service = gatt.getService(UUID.fromString(serviceId));
BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(characteristicId));
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString(descriptorId));
boolean result = descriptor.setValue(value);
if (!result) {
throw new Exception("Could not store descriptor value");
}
CallbackKey key = new CallbackKey(gatt, descriptor, "writeDescriptorValue");
readWriteCallbacks.put(key, callback);
result = gatt.writeDescriptor(descriptor);
if (!result) {
readWriteCallbacks.remove(key);
throw new Exception(String.format("Failed on BluetoothGatt#writeDescriptor for descriptor %s. Android didn't tell us why either.", descriptorId));
}
}
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(final BluetoothGatt gatt, final int status, final int newState) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
if (newState == BluetoothProfile.STATE_CONNECTED) {
gatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
JSONObject obj = JSONObjects.asDevice(gatt, getBluetoothManager());
if (disconnectCallback == null) {
// the user didn't ask for a disconnect, meaning we were dropped
Log.v("bluetoothle", onDeviceDroppedCallback.getCallbackId());
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, obj);
pluginResult.setKeepCallback(true);
onDeviceDroppedCallback.sendPluginResult(pluginResult);
return;
}
disconnectCallback.success(obj);
disconnectCallback = null;
}
}
});
}
@Override
public void onServicesDiscovered(final BluetoothGatt gatt, final int status) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
if (status == BluetoothGatt.GATT_SUCCESS) {
for (BluetoothGattService service : gatt.getServices()) {
for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()) {
characteristic.getDescriptors();
}
}
connectCallback.success(JSONObjects.asDevice(gatt, getBluetoothManager()));
connectCallback = null;
} else {
connectCallback.error(JSONObjects.asError(new Exception("Device discovery failed")));
}
connectCallback = null;
}
});
}
@Override
public void onCharacteristicRead(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int status) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
CallbackKey key = new CallbackKey(gatt, characteristic, "readCharacteristicValue");
CallbackContext callback = readWriteCallbacks.get(key);
if (callback == null) {
Log.e("bluetoothle", "Characteristic " + characteristic.getUuid().toString() + " was read, but apparently nobody asked for it (no callback set)");
return;
}
if (status == BluetoothGatt.GATT_SUCCESS) {
callback.success(Base64.encodeToString(characteristic.getValue(), Base64.NO_WRAP));
} else {
callback.error(JSONObjects.asError(new Exception("Failed to read characteristic")));
}
readWriteCallbacks.remove(key);
}
});
}
@Override
public void onCharacteristicChanged(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) {
if (onCharacteristicValueChangedCallback == null) {
return;
}
PluginResult result = new PluginResult(PluginResult.Status.OK, JSONObjects.asCharacteristic(characteristic));
result.setKeepCallback(true);
onCharacteristicValueChangedCallback.sendPluginResult(result);
}
@Override
public void onCharacteristicWrite(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final int status) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
CallbackKey key = new CallbackKey(gatt, characteristic, "writeCharacteristicValue");
CallbackContext callback = readWriteCallbacks.get(key);
if (callback == null) {
Log.e("bluetoothle", "Characteristic " + characteristic.getUuid().toString() + " was written, but apparently nobody asked for it (no callback set)");
return;
}
if (status == BluetoothGatt.GATT_SUCCESS) {
callback.success(JSONObjects.asCharacteristic(characteristic));
} else {
callback.error(JSONObjects.asError(new Exception("Failed to write characteristic")));
}
readWriteCallbacks.remove(key);
}
});
}
@Override
public void onDescriptorRead(final BluetoothGatt gatt, final BluetoothGattDescriptor descriptor, final int status) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
CallbackKey key = new CallbackKey(gatt, descriptor, "readDescriptorValue");
CallbackContext callback = readWriteCallbacks.get(key);
if (callback == null) {
Log.e("bluetoothle", "Descriptor " + descriptor.getUuid().toString() + " was read, but apparently nobody asked for it (no callback set)");
return;
}
if (status == BluetoothGatt.GATT_SUCCESS) {
callback.success(JSONObjects.asDescriptor(descriptor));
} else {
callback.error(JSONObjects.asError(new Exception("Failed to read descriptor " + descriptor.getUuid().toString())));
}
readWriteCallbacks.remove(key);
}
});
}
@Override
public void onDescriptorWrite(final BluetoothGatt gatt, final BluetoothGattDescriptor descriptor, final int status) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
CallbackKey key = new CallbackKey(gatt, descriptor, "writeDescriptorValue");
CallbackContext callback = readWriteCallbacks.get(key);
if (callback == null) {
Log.e("bluetoothle", "Descriptor " + descriptor.getUuid().toString() + " was written, but apparently nobody asked for it (no callback set)");
return;
}
if (status == BluetoothGatt.GATT_SUCCESS) {
callback.success(JSONObjects.asDescriptor(descriptor));
} else {
callback.error(JSONObjects.asError(new Exception("Failed to write descriptor " + descriptor.getUuid().toString())));
}
readWriteCallbacks.remove(key);
}
});
}
@Override
public void onReadRemoteRssi(final BluetoothGatt gatt, final int rssi, final int status) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
BluetoothManager bluetoothManager = (BluetoothManager) cordova.getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
if (rssiCallback != null) {
if (status == BluetoothGatt.GATT_SUCCESS) {
rssiCallback.success(rssi);
} else {
rssiCallback.error(JSONObjects.asError(new Exception("Received an error after attempting to read RSSI for device " + gatt.getDevice().getAddress())));
}
rssiCallback = null;
} else if (deviceInfoCallback != null) {
if (status == BluetoothGatt.GATT_SUCCESS) {
deviceInfoCallback.success(JSONObjects.asDevice(gatt, bluetoothManager, rssi));
} else {
deviceInfoCallback.error(JSONObjects.asError(new Exception("Received an error after attempting to read RSSI for device " + gatt.getDevice().getAddress())));
}
deviceInfoCallback = null;
} else {
return;
}
}
});
}
};
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
if (onAdapterStateChangedCallback == null) {
return;
}
if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_ON) {
connectedGattServers = new HashMap<String, BluetoothGatt>();
}
if (state == BluetoothAdapter.STATE_OFF || state == BluetoothAdapter.STATE_ON) {
JSONObject obj = JSONObjects.asAdapter(getBluetoothManager().getAdapter());
PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, obj);
pluginResult.setKeepCallback(true);
onAdapterStateChangedCallback.sendPluginResult(pluginResult);
}
}
}
});
}
};
private BroadcastReceiver mPairingBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
BluetoothDevice remoteDevice = (BluetoothDevice) intent.getExtras().get(BluetoothDevice.EXTRA_DEVICE);
// TODO - Hardcoded for now
String mPasskey = "123456";
try {
if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST")) {
byte[] pin = (byte[]) BluetoothDevice.class.getMethod("convertPinToBytes", String.class)
.invoke(BluetoothDevice.class, mPasskey);
BluetoothDevice.class.getMethod("setPin", byte[].class)
.invoke(remoteDevice, pin);
BluetoothDevice.class.getMethod("setPairingConfirmation", boolean.class)
.invoke(remoteDevice, true);
Log.d("bluetoothle", "Success to set passkey.");
final IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
cordova.getActivity().registerReceiver(mBondingBroadcastReceiver, filter);
}
} catch (Exception e) {
Log.e("bluetoothle", e.getMessage());
e.printStackTrace();
}
cordova.getActivity().unregisterReceiver(this);
mRegisteredPairingReceiver = false;
}
};
private BroadcastReceiver mBondingBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent intent) {
final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
final int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
final int previousBondState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1);
Log.d("bluetoothle", "Bond state changed for: " + device.getAddress() +
" new state: " + bondState +
" previous: " + previousBondState);
if (bondState == BluetoothDevice.BOND_BONDED) {
try {
BluetoothDevice.class.getMethod("cancelPairingUserInput").invoke(mGatt.getDevice());
Log.d("bluetoothle", "Cancel user input");
} catch (Exception e) {
Log.e("bluetoothle", e.getMessage());
e.printStackTrace();
}
cordova.getActivity().unregisterReceiver(this);
}
}
};
/**
*
* @param callbackContext
* @param message
*/
private void keepCallback(final CallbackContext callbackContext, JSONObject message) {
PluginResult r = new PluginResult(PluginResult.Status.OK, message);
r.setKeepCallback(true);
callbackContext.sendPluginResult(r);
}
/**
*
* @param callbackContext
* @param message
*/
private void keepCallback(final CallbackContext callbackContext, String message) {
PluginResult r = new PluginResult(PluginResult.Status.OK, message);
r.setKeepCallback(true);
callbackContext.sendPluginResult(r);
}
/**
*
* @param callbackContext
* @param message
*/
private void keepCallback(final CallbackContext callbackContext, byte[] message) {
PluginResult r = new PluginResult(PluginResult.Status.OK, message);
r.setKeepCallback(true);
callbackContext.sendPluginResult(r);
}
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (status == BluetoothGatt.GATT_SUCCESS) {
if (!this.mPasskey.isEmpty()) {
if (!mRegisteredPairingReceiver) {
final IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST);
cordova.getActivity().registerReceiver(mPairingBroadcastReceiver, filter);
mRegisteredPairingReceiver = true;
}
try {
Method createBond = BluetoothDevice.class.getMethod("createBond", (Class[]) null);
createBond.invoke(gatt.getDevice(), (Object[]) null);
} catch (Exception e) {
Log.e("bluetoothle", e.getMessage());
e.printStackTrace();
}
}
try {
JSONObject o = new JSONObject();
o.put("deviceHandle", mHandle);
o.put("state", newState);
keepCallback(connectCallback, o);
} catch (JSONException e) {
e.printStackTrace();
assert (false);
}
} else {
connectCallback.error(status);
}
//refresh(gatt);
}
// Used as keys for the `readWriteOperations` Map
private class CallbackKey {
private BluetoothGatt gatt;
private Object scd; // service, characteristic, or descriptor
private String operation;
public CallbackKey(BluetoothGatt gatt, Object scd, String operation) {
this.gatt = gatt;
this.scd = scd;
this.operation = operation;
}
@Override
public int hashCode() {
int hash = 1;
hash = 31 * hash + gatt.hashCode();
hash = 31 * hash + scd.hashCode();
hash = 31 * hash + operation.hashCode();
return hash;
}
public boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof CallbackKey)) {
return false;
}
return
equals(((CallbackKey) obj).gatt, gatt) &&
equals(((CallbackKey) obj).scd, scd) &&
equals(((CallbackKey) obj).operation, operation);
}
}
}
|
package net.fortuna.ical4j.data;
import java.io.IOException;
import java.io.StringWriter;
import net.fortuna.ical4j.util.Strings;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import junit.framework.TestCase;
/**
* Unit tests for FoldingWriter.
* @author Ben Fortuna
*/
public class FoldingWriterTest extends TestCase {
private static final Log LOG = LogFactory.getLog(FoldingWriterTest.class);
/**
* Test writing a line equal to fold length.
*/
public void testLineLength73() throws IOException {
StringWriter sw = new StringWriter();
FoldingWriter writer = new FoldingWriter(sw);
writer.write("BEGIN:VCALENDAR");
writer.write(Strings.LINE_SEPARATOR);
writer.write("PRODID:-//Open Source Applications Foundation//NONSGML Scooby Server//EN");
writer.write(Strings.LINE_SEPARATOR);
writer.write("VERSION:2.0");
LOG.info(sw.getBuffer());
}
}
|
package hudson.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import hudson.WebAppMain;
import hudson.model.Hudson;
import hudson.model.listeners.ItemListener;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import jenkins.model.Jenkins;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.NoListenerConfiguration;
import org.jvnet.hudson.test.TestEnvironment;
import org.jvnet.hudson.test.TestExtension;
import org.kohsuke.stapler.WebApp;
/**
*
*
* @author Kohsuke Kawaguchi
*/
public class BootFailureTest {
@Rule
public TemporaryFolder tmpDir = new TemporaryFolder();
static boolean makeBootFail = true;
static WebAppMain wa;
static class CustomRule extends JenkinsRule {
@Override
public void before() {
env = new TestEnvironment(testDescription);
env.pin();
// don't let Jenkins start automatically
}
@Override
public Hudson newHudson() throws Exception {
localPort = 0;
wa = new WebAppMain() {
@Override
public WebAppMain.FileAndDescription getHomeDir(ServletContextEvent event) {
try {
return new WebAppMain.FileAndDescription(homeLoader.allocate(), "test");
} catch (Exception x) {
throw new AssertionError(x);
}
}
};
// Without this gymnastic, the jenkins-test-harness adds a NoListenerConfiguration
// that prevents us to inject our own custom WebAppMain
// With this approach we can make the server calls the regular contextInitialized
ServletContext ws = createWebServer((context, server) -> {
NoListenerConfiguration noListenerConfiguration = context.getBean(NoListenerConfiguration.class);
// future-proof
assertNotNull(noListenerConfiguration);
if (noListenerConfiguration != null) {
context.removeBean(noListenerConfiguration);
context.addBean(new NoListenerConfiguration(context) {
@Override
protected void doStart() {
// default behavior of noListenerConfiguration
super.doStart();
// ensuring our custom context will received the contextInitialized event
context.addEventListener(wa);
}
});
}
});
wa.joinInit();
Object a = WebApp.get(ws).getApp();
if (a instanceof Hudson) {
return (Hudson) a;
}
return null; // didn't boot
}
}
@Rule
public CustomRule j = new CustomRule();
@After
public void tearDown() {
Jenkins j = Jenkins.getInstanceOrNull();
if (j != null) {
j.cleanUp();
}
}
public static class SeriousError extends Error {}
@TestExtension("runBootFailureScript")
public static class InduceBootFailure extends ItemListener {
@Override
public void onLoaded() {
if (makeBootFail)
throw new SeriousError();
}
}
@Test
public void runBootFailureScript() throws Exception {
final File home = tmpDir.newFolder();
j.with(() -> home);
// creates a script
Files.writeString(home.toPath().resolve("boot-failure.groovy"), "hudson.util.BootFailureTest.problem = exception", StandardCharsets.UTF_8);
Path d = home.toPath().resolve("boot-failure.groovy.d");
Files.createDirectory(d);
Files.writeString(d.resolve("1.groovy"), "hudson.util.BootFailureTest.runRecord << '1'", StandardCharsets.UTF_8);
Files.writeString(d.resolve("2.groovy"), "hudson.util.BootFailureTest.runRecord << '2'", StandardCharsets.UTF_8);
// first failed boot
makeBootFail = true;
assertNull(j.newHudson());
assertEquals(1, bootFailures(home));
// second failed boot
problem = null;
runRecord = new ArrayList<>();
assertNull(j.newHudson());
assertEquals(2, bootFailures(home));
assertEquals(Arrays.asList("1", "2"), runRecord);
// make sure the script has actually run
assertEquals(SeriousError.class, problem.getCause().getClass());
// if it boots well, the failure record should be gone
makeBootFail = false;
assertNotNull(j.newHudson());
assertFalse(BootFailure.getBootFailureFile(home).exists());
}
private static int bootFailures(File home) throws IOException {
return new BootFailure() { }.loadAttempts(home).size();
}
@Issue("JENKINS-24696")
@Test
public void interruptedStartup() throws Exception {
final File home = tmpDir.newFolder();
j.with(() -> home);
Path d = home.toPath().resolve("boot-failure.groovy.d");
Files.createDirectory(d);
Files.writeString(d.resolve("1.groovy"), "hudson.util.BootFailureTest.runRecord << '1'", StandardCharsets.UTF_8);
j.newHudson();
assertEquals(List.of("1"), runRecord);
}
@TestExtension("interruptedStartup")
public static class PauseBoot extends ItemListener {
@Override
public void onLoaded() {
wa.contextDestroyed(null);
}
}
// to be set by the script
public static Exception problem;
public static List<String> runRecord = new ArrayList<>();
}
|
import com.maxeler.maxcompiler.v2.managers.custom.CustomManager;
import com.maxeler.maxcompiler.v2.managers.custom.DFELink;
import com.maxeler.maxcompiler.v2.managers.custom.blocks.*;
import com.maxeler.maxcompiler.v2.managers.custom.stdlib.MemoryControlGroup;
import com.maxeler.maxcompiler.v2.managers.engine_interfaces.*;
import com.maxeler.maxcompiler.v2.managers.BuildConfig;
import com.maxeler.maxcompiler.v2.statemachine.manager.ManagerStateMachine;
import com.custom_computing_ic.dfe_snippets.manager.*;
public class SpmvManager extends CustomManager{
private final int cacheSize;
private final int inputWidth;
private final int maxRows;
private final int numPipes;
// parameters of CSR format used: float64 values, int32 index.
private static final int mantissaWidth = 53;
private static final int indexWidth = 32;
private static final int FLOATING_POINT_LATENCY = 16;
private static final boolean DBG_PAR_CSR_CTL = false;
private static final boolean DBG_SPMV_KERNEL = false;
private static final boolean DBG_REDUCTION_KERNEL = false;
private static final boolean dramReductionEnabled = true; //false;
SpmvManager(SpmvEngineParams ep) {
super(ep);
inputWidth = ep.getInputWidth();
cacheSize = ep.getVectorCacheSize();
maxRows = ep.getMaxRows();
numPipes = ep.getNumPipes();
if (384 % inputWidth != 0) {
throw new RuntimeException("Error! 384 is not a multiple of INPUT WIDTH: " +
"This may lead to stalls due to padding / unpadding ");
}
addMaxFileConstant("inputWidth", inputWidth);
addMaxFileConstant("cacheSize", cacheSize);
addMaxFileConstant("maxRows", maxRows);
addMaxFileConstant("numPipes", numPipes);
ManagerUtils.setDRAMMaxDeviceFrequency(this, ep);
//config.setAllowNonMultipleTransitions(true);
for (int i = 0; i < numPipes; i++)
addComputePipe(i, inputWidth);
}
void addComputePipe(int id, int inputWidth) {
StateMachineBlock readControlBlock = addStateMachine(
getReadControl(id),
new ParallelCsrReadControl(this, inputWidth, DBG_PAR_CSR_CTL));
readControlBlock.getInput("length") <== addUnpaddingKernel("colptr" + id, 32, id * 10 + 1);
KernelBlock k = addKernel(new SpmvKernel(
makeKernelParameters(getComputeKernel(id)),
inputWidth,
cacheSize,
indexWidth,
mantissaWidth,
DBG_SPMV_KERNEL
));
k.getInput("indptr_values") <== addUnpaddingKernel("indptr_values" + id, inputWidth * 96, id * 10 + 2);
k.getInput("vromLoad") <== addUnpaddingKernel("vromLoad" + id, 64, id * 10 + 3);
k.getInput("control") <== readControlBlock.getOutput("control");
KernelBlock r = null;
if (dramReductionEnabled) {
r = addKernel(new DramSpmvReductionKernel(makeKernelParameters(getReductionKernel(id))));
r.getInput("prevb") <== addUnpaddingKernel("prevb" + id, 64, id * 10 + 5);
}
else {
r = addKernel(new BramSpmvReductionKernel(
makeKernelParameters(getReductionKernel(id)),
FLOATING_POINT_LATENCY,
maxRows,
DBG_REDUCTION_KERNEL));
}
addPaddingKernel("reductionOut" + id) <== r.getOutput("reductionOut");
r.getInput("reductionIn") <== k.getOutput("output");
r.getInput("skipCount") <== k.getOutput("skipCount");
}
DFELink addPaddingKernel(String stream)
{
System.out.println("Creating kernel " + getPaddingKernel(stream));
KernelBlock p = addKernel(new PaddingKernel(
makeKernelParameters(getPaddingKernel(stream))));
addStreamToOnCardMemory(stream,
MemoryControlGroup.MemoryAccessPattern.LINEAR_1D) <== p.getOutput("paddingOut");
return p.getInput("paddingIn");
}
DFELink addUnpaddingKernel(
String stream,
int bitwidth,
int id)
{
KernelBlock k = addKernel(new
UnpaddingKernel(makeKernelParameters(getUnpaddingKernel(stream)), bitwidth, id));
k.getInput("paddingIn") <== addStreamFromOnCardMemory(stream,
MemoryControlGroup.MemoryAccessPattern.LINEAR_1D);
return k.getOutput("pout");
}
String getComputeKernel(int id) {
return "computeKernel" + id;
}
String getReductionKernel(int id) {
return "reductionKernel" + id;
}
String getPaddingKernel(String id) {
return "padding_" + id;
}
String getReadControl(int id) {
return "readControl" + id;
}
String getFanoutName(int id) {
return "flush" + id;
}
String getUnpaddingKernel(String stream) {
return "unpadding_" + stream;
}
void setUpComputePipe(
EngineInterface ei, int id,
InterfaceParam vectorLoadCycles,
InterfaceParam nPartitions,
InterfaceParam n,
InterfaceParam outResultStartAddress,
InterfaceParam outResultSize,
InterfaceParam vStartAddress,
InterfaceParam colPtrStartAddress,
InterfaceParam colptrSize,
InterfaceParam indptrValuesStartAddress,
InterfaceParam indptrValuesSize,
InterfaceParam totalCycles,
InterfaceParam reductionCycles,
InterfaceParam nIterations) {
String computeKernel = getComputeKernel(id);
String reductionKernel = getReductionKernel(id);
String paddingKernel = getPaddingKernel("" + id);
String readControl = getReadControl(id);
ei.setTicks(computeKernel, totalCycles * nIterations);
ei.setScalar(computeKernel, "vectorLoadCycles", vectorLoadCycles);
ei.setTicks(reductionKernel, reductionCycles * nIterations);
ei.setScalar(reductionKernel, "nRows", n);
ei.setScalar(reductionKernel, "totalCycles", reductionCycles);
String stream = "vromLoad" + id;
setupUnpaddingKernel(
ei,
getUnpaddingKernel(stream),
stream,
vectorLoadCycles * nPartitions,
ei.addConstant(8), // XXX magic constant...
nIterations,
vStartAddress
);
InterfaceParam colptrEntries = colptrSize / CPUTypes.INT32.sizeInBytes();
stream = "colptr" + id;
setupUnpaddingKernel(
ei,
getUnpaddingKernel(stream),
stream,
colptrEntries,
ei.addConstant(4),
nIterations,
colPtrStartAddress);
InterfaceParam valueEntries = indptrValuesSize / (8 + 4) / inputWidth; // 12 bytes per entry
stream = "indptr_values" + id;
setupUnpaddingKernel(
ei,
getUnpaddingKernel(stream),
stream,
valueEntries,
inputWidth * ei.addConstant(8 + 4),
nIterations,
indptrValuesStartAddress);
InterfaceParam zero = ei.addConstant(0l);
ei.setScalar(readControl, "nrows", n);
ei.setScalar(readControl, "vectorLoadCycles", vectorLoadCycles);
ei.setScalar(readControl, "nPartitions", nPartitions);
ei.setScalar(readControl, "nIterations", nIterations);
InterfaceParam spmvOutputWidthBytes = ei.addConstant(CPUTypes.DOUBLE.sizeInBytes());
InterfaceParam spmvOutputSizeBytes = n * spmvOutputWidthBytes;
if (dramReductionEnabled) {
setupUnpaddingKernel(ei,
getUnpaddingKernel("prevb" + id),
"prevb" + id,
n,
ei.addConstant(8),
nIterations * nPartitions,
outResultStartAddress
);
stream = "reductionOut" + id;
setupUnpaddingKernel(ei,
getPaddingKernel(stream),
stream,
n,
ei.addConstant(8),
nIterations * nPartitions,
outResultStartAddress);
} else {
InterfaceParam spmvPaddingCycles = getPaddingCycles(spmvOutputSizeBytes, spmvOutputWidthBytes);
InterfaceParam spmvTotalCyclesPerIteration = n + spmvPaddingCycles;
ei.setTicks(paddingKernel, spmvTotalCyclesPerIteration * nIterations);
ei.setScalar(paddingKernel, "nInputs", n);
ei.setScalar(paddingKernel, "totalCycles", spmvTotalCyclesPerIteration);
ei.setLMemLinearWrapped(
"paddingOut" + id,
outResultStartAddress,
outResultSize,
outResultSize * nIterations,
zero
);
}
}
/**
* An unpadding kernel reads a stream from memory and discards the bytes
* which were added to pad the data to a multiple of BURST_SIZE_BYTES.
*
* @param size size in number of elements of the stream
* @param memoryStream the stream from memory to unpad
* @param inputWidthBytes the number of bytes the kernel should read (and
* write) every cycle
*/
private void setupUnpaddingKernel(
EngineInterface ei,
String kernelId,
String memoryStream,
InterfaceParam size,
InterfaceParam inputWidthBytes,
InterfaceParam iterations,
InterfaceParam startAddress
) {
InterfaceParam unpaddingCycles = getPaddingCycles(size * inputWidthBytes, inputWidthBytes);
InterfaceParam totalSize = unpaddingCycles + size;
System.out.println("Setting ticks for kernel " + kernelId);
ei.setTicks(kernelId, totalSize * iterations);
ei.setScalar(kernelId, "nInputs", size);
ei.setScalar(kernelId, "totalCycles", totalSize);
ei.setLMemLinearWrapped(memoryStream,
startAddress,
totalSize * inputWidthBytes,
totalSize * inputWidthBytes * iterations,
ei.addConstant(0));
}
private InterfaceParam smallestMultipleLargerThan(InterfaceParam x, long y) {
return
y * (x / y +
InterfaceMath.max(
0l, InterfaceMath.min(x % y, 1l)));
}
private InterfaceParam getPaddingCycles(
InterfaceParam outSizeBytes,
InterfaceParam outWidthBytes)
{
final int burstSizeBytes = 384;
InterfaceParam writeSize = smallestMultipleLargerThan(outSizeBytes, burstSizeBytes);
return (writeSize - outSizeBytes) / outWidthBytes;
}
private EngineInterface interfaceDefault() {
EngineInterface ei = new EngineInterface();
InterfaceParam vectorLoadCycles = ei.addParam("vectorLoadCycles", CPUTypes.INT);
InterfaceParam nPartitions = ei.addParam("nPartitions", CPUTypes.INT);
InterfaceParam nIterations = ei.addParam("nIterations", CPUTypes.INT);
InterfaceParamArray nrows = ei.addParamArray("nrows", CPUTypes.INT32);
InterfaceParamArray outStartAddresses = ei.addParamArray("outStartAddresses", CPUTypes.INT64);
InterfaceParamArray outResultSizes = ei.addParamArray("outResultSizes", CPUTypes.INT32);
InterfaceParamArray totalCycles = ei.addParamArray("totalCycles", CPUTypes.INT32);
InterfaceParamArray vStartAddresses = ei.addParamArray("vStartAddresses", CPUTypes.INT64);
InterfaceParamArray indptrValuesAddresses = ei.addParamArray("indptrValuesAddresses", CPUTypes.INT64);
InterfaceParamArray indptrValuesSizes = ei.addParamArray("indptrValuesSizes", CPUTypes.INT32);
InterfaceParamArray colptrStartAddresses = ei.addParamArray("colPtrStartAddresses", CPUTypes.INT64);
InterfaceParamArray colptrSizes = ei.addParamArray("colptrSizes", CPUTypes.INT32);
InterfaceParamArray reductionCycles = ei.addParamArray("reductionCycles", CPUTypes.INT32);
for (int i = 0; i < numPipes; i++)
setUpComputePipe(ei, i,
vectorLoadCycles,
nPartitions,
nrows.get(i),
outStartAddresses.get(i),
outResultSizes.get(i),
vStartAddresses.get(i),
colptrStartAddresses.get(i),
colptrSizes.get(i),
indptrValuesAddresses.get(i),
indptrValuesSizes.get(i),
totalCycles.get(i),
reductionCycles.get(i),
nIterations);
ei.ignoreLMem("cpu2lmem");
ei.ignoreStream("fromcpu");
ei.ignoreStream("tocpu");
ei.ignoreLMem("lmem2cpu");
return ei;
}
public static void main(String[] args) {
SpmvManager manager = new SpmvManager(new SpmvEngineParams(args));
//ManagerUtils.debug(manager);
manager.createSLiCinterface(ManagerUtils.dramWrite(manager));
manager.createSLiCinterface(ManagerUtils.dramRead(manager));
manager.createSLiCinterface(manager.interfaceDefault());
ManagerUtils.setFullBuild(manager, BuildConfig.Effort.HIGH, 2, 2);
manager.build();
}
}
|
package com.tns;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.zip.ZipEntry;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.util.SparseArray;
import com.tns.internal.ExtractPolicy;
public class Platform
{
private static native void initNativeScript(String filesPath, int appJavaObjectId, boolean verboseLoggingEnabled, String packageName, int debuggerPort);
private static native void runNativeScript(String appModuleName, String appContent);
private static native Object callJSMethodNative(int javaObjectID, String methodName, Object... packagedArgs) throws NativeScriptException;
private static native String[] createJSInstanceNative(Object javaObject, int javaObjectID, String canonicalName, boolean createActivity, Object[] packagedCreationArgs);
private static native int generateNewObjectId();
private static native void enableVerboseLoggingNative();
private static native void disableVerboseLoggingNative();
private static native void adjustAmountOfExternalAllocatedMemoryNative(long changeInBytes);
private static native void passUncaughtExceptionToJsNative(Throwable ex, String stackTrace);
private static Context NativeScriptContext;
private static SparseArray<Object> strongInstances = new SparseArray<Object>();
private static SparseArray<WeakReference<Object>> weakInstances = new SparseArray<WeakReference<Object>>();
private static NativeScriptHashMap<Object, Integer> strongJavaObjectToID = new NativeScriptHashMap<Object, Integer>();
private static NativeScriptWeakHashMap<Object, Integer> weakJavaObjectToID = new NativeScriptWeakHashMap<Object, Integer>();
private static Runtime runtime = Runtime.getRuntime();
private final static Object keyNotFoundObject = new Object();
public final static String ApplicationAssetsPath = "app/";
private static Object[] empty = new Object[0];
private static String[] methodOverrides;
private static int currentObjectId = -1;
private static ExtractPolicy extractPolicy;
private static Thread mainThread;
private static long lastUsedMemory = 0;
private static ArrayList<Constructor<?>> ctorCache = new ArrayList<Constructor<?>>();
public final static String DefaultApplicationModuleName = "./bootstrap";
private static JsDebugger jsDebugger;
public static boolean IsLogEnabled = BuildConfig.DEBUG;
public final static String DEFAULT_LOG_TAG = "TNS.Java";
public static int init(Context context) throws Exception
{
jsDebugger = new JsDebugger(context);
mainThread = Thread.currentThread();
if (NativeScriptContext != null)
{
throw new Exception("NativeScriptApplication already initialized");
}
Require.init(context);
NativeScriptContext = context;
if (IsLogEnabled) Log.d(DEFAULT_LOG_TAG, "Initializing NativeScript JAVA");
int appJavaObjectId = generateNewObjectId();
makeInstanceStrong(context, appJavaObjectId);
if (IsLogEnabled) Log.d(DEFAULT_LOG_TAG, "Initialized app instance id:" + appJavaObjectId);
int appBuilderWritableAssetsId = context.getResources().getIdentifier("appBuilderWritableAssets", "bool", context.getPackageName());
AssetExtractor.extractAssets(context, extractPolicy, appBuilderWritableAssetsId == 0 ? false : context.getResources().getBoolean(appBuilderWritableAssetsId));
int debuggerPort = jsDebugger.getDebuggerPortFromEnvironment();
Platform.initNativeScript(Require.getApplicationFilesPath(), appJavaObjectId, IsLogEnabled, context.getPackageName(), debuggerPort);
Date d = new Date();
int pid = android.os.Process.myPid();
File f = new File("/proc/" + pid);
Date lastModDate = new Date(f.lastModified());
if (IsLogEnabled) Log.d(DEFAULT_LOG_TAG, "init time=" + (d.getTime() - lastModDate.getTime()));
return appJavaObjectId;
}
static void installSecondaryDexes(Context context)
{
com.tns.multidex.MultiDex.install(context);
}
public static void enableVerboseLogging()
{
IsLogEnabled = true;
enableVerboseLoggingNative();
}
public static void disableVerboseLogging()
{
IsLogEnabled = false;
disableVerboseLoggingNative();
}
static void setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler handler)
{
if (handler == null)
{
final UncaughtExceptionHandler h = Thread.getDefaultUncaughtExceptionHandler();
handler = new UncaughtExceptionHandler()
{
@Override
public void uncaughtException(Thread thread, Throwable ex)
{
if (IsLogEnabled) Log.e(DEFAULT_LOG_TAG, "Uncaught Exception Message=" + ex.getMessage());
String content;
PrintStream ps = null;
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ps = new PrintStream(baos);
ex.printStackTrace(ps);
try
{
content = baos.toString("US-ASCII");
}
catch (UnsupportedEncodingException e)
{
content = e.getMessage();
}
passUncaughtExceptionToJsNative(ex, content);
}
finally
{
if (ps != null)
ps.close();
}
if (IsLogEnabled) Log.e(DEFAULT_LOG_TAG, "Uncaught Exception Stack=" + content);
final String errMsg = content;
new Thread() {
@Override
public void run()
{
Intent intent = ErrorReport.getIntent(NativeScriptContext, ErrorReportActivity.class, errMsg);
NativeScriptContext.startActivity(intent);
}
}.start();
if (h != null)
{
h.uncaughtException(thread, ex);
}
}
};
}
Thread.setDefaultUncaughtExceptionHandler(handler);
}
static void setExtractPolicy(ExtractPolicy policy)
{
if (policy == null)
{
policy = new ExtractPolicy()
{
@Override
public boolean extract(String appRoot) {
return true;
}
@Override
public boolean shouldSkip(File outputFile, File zipFile, ZipEntry zipEnty)
{
boolean shouldSkip = outputFile.exists() && (zipFile.lastModified() <= outputFile.lastModified()); //TODO: check lastModified when application is installed on sdcard with FAT32 format
return shouldSkip;
}
};
}
extractPolicy = policy;
}
public static void run(String appFileName) throws Exception
{
String appContent = Require.getAppContent(appFileName);
runNativeScript(appFileName, appContent);
}
private static int cacheConstructor(String className, Object[] args) throws ClassNotFoundException
{
Constructor<?> ctor = MethodResolver.resolveConstructor(className, args);
int ctorId = ctorCache.size();
ctorCache.add(ctor);
return ctorId;
}
public static Object createInstance(Object[] args, String[] methodOverrides, int objectId, int constructorId) throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException
{
if (IsLogEnabled) Log.d(DEFAULT_LOG_TAG, "Creating instance for ctorId=" + constructorId);
Constructor<?> ctor = ctorCache.get(constructorId);
boolean success = MethodResolver.convertConstructorArgs(ctor, args);
if (!success)
{
StringBuilder builder = new StringBuilder();
builder.append(constructorId + "(");
for (Object arg : args)
{
if (arg != null)
{
builder.append(arg.toString() + ", ");
}
else
{
builder.append("null, ");
}
}
builder.append(")");
throw new InstantiationException("MethodResolver didn't resolve any constructor with the specified arguments " + builder.toString());
}
Object instance;
try
{
Platform.currentObjectId = objectId;
Platform.methodOverrides = methodOverrides;
instance = ctor.newInstance(args);
makeInstanceStrong(instance, objectId);
}
finally
{
Platform.methodOverrides = null;
Platform.currentObjectId = -1;
}
adjustAmountOfExternalAllocatedMemory();
return instance;
}
private static long getChangeInBytesOfUsedMemory()
{
long usedMemory = runtime.totalMemory() - runtime.freeMemory();
long changeInBytes = usedMemory - lastUsedMemory;
lastUsedMemory = usedMemory;
return changeInBytes;
}
private static void adjustAmountOfExternalAllocatedMemory()
{
long changeInBytes = getChangeInBytesOfUsedMemory();
adjustAmountOfExternalAllocatedMemoryNative(changeInBytes);
}
// TODO: recomplie the bindings to support the args method and remove this
// one since it is not needed after bindings recompile.
public static void initInstance(Object instance)
{
initInstance(instance, empty);
}
public static void initInstance(Object instance, Object... args)
{
String[] methodOverrides = Platform.methodOverrides;
if (methodOverrides == null)
{
methodOverrides = createJSInstance(instance, args);
}
if (instance instanceof NativeScriptHashCodeProvider)
{
NativeScriptHashCodeProvider obj = (NativeScriptHashCodeProvider) instance;
obj.setNativeScriptOverrides(methodOverrides);
}
int objectId = Platform.currentObjectId;
if (objectId != -1)
{
makeInstanceStrong(instance, objectId);
Platform.currentObjectId = -1;
}
}
private static String[] createJSInstance(Object instance, Object... args)
{
int javaObjectID = generateNewObjectId();
makeInstanceStrong(instance, javaObjectID);
Object[] packagedArgs = packageArgs(args);
String[] methodOverrides = createJSInstanceNative(instance, javaObjectID, instance.getClass().getCanonicalName(), instance instanceof Activity, packagedArgs);
if (IsLogEnabled)
{
Log.d(DEFAULT_LOG_TAG, "JSInstance for " + instance.getClass().toString() + " created with overrides");
for (Object methodOverride : methodOverrides)
{
Log.d(DEFAULT_LOG_TAG, methodOverride.toString());
}
}
return methodOverrides;
}
private static String[] getTypeMetadata(String className, int index) throws ClassNotFoundException
{
Class<?> clazz = Class.forName(className);
String[] result = getTypeMetadata(clazz, index);
return result;
}
private static String[] getTypeMetadata(Class<?> clazz, int index)
{
Class<?> mostOuterClass = clazz.getEnclosingClass();
ArrayList<Class<?>> outerClasses = new ArrayList<Class<?>>();
while (mostOuterClass != null)
{
outerClasses.add(0, mostOuterClass);
Class<?> nextOuterClass = mostOuterClass.getEnclosingClass();
if (nextOuterClass == null)
break;
mostOuterClass = nextOuterClass;
}
Package p = (mostOuterClass != null)
? mostOuterClass.getPackage()
: clazz.getPackage();
int packageCount = 1;
String pname = p.getName();
for (int i=0; i<pname.length(); i++)
{
if (pname.charAt(i) == '.')
++packageCount;
}
String name = clazz.getName();
String[] parts = name.split("[\\.\\$]");
int endIdx = parts.length;
int len = endIdx - index;
String[] result = new String[len];
int endOuterTypeIdx = packageCount + outerClasses.size();
for (int i=index; i<endIdx; i++)
{
if (i < packageCount)
{
result[i - index] = "P";
}
else
{
if (i < endOuterTypeIdx)
{
result[i - index] = getTypeMetadata(outerClasses.get(i - packageCount));
}
else
{
result[i - index] = getTypeMetadata(clazz);
}
}
}
return result;
}
private static String getTypeMetadata(Class<?> clazz)
{
StringBuilder sb = new StringBuilder();
if (clazz.isInterface())
{
sb.append("I ");
}
else
{
sb.append("C ");
}
if (Modifier.isStatic(clazz.getModifiers()))
{
sb.append("S\n");
}
else
{
sb.append("I\n");
}
for (Method m: clazz.getMethods())
{
sb.append("M ");
sb.append(m.getName());
Class<?>[] params = m.getParameterTypes();
String sig = MethodResolver.getMethodSignature(m.getReturnType(), params);
sb.append(" ");
sb.append(sig);
int paramCount = params.length;
sb.append(" ");
sb.append(paramCount);
sb.append("\n");
}
for (Field f: clazz.getFields())
{
sb.append("F ");
sb.append(f.getName());
sb.append(" ");
String sig = MethodResolver.getTypeSignature(f.getType());
sb.append(sig);
sb.append(" 0\n");
}
String ret = sb.toString();
return ret;
}
public static int makeClassInstanceOfTypeStrong(String classPath) throws InstantiationException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException
{
if (IsLogEnabled) Log.d(DEFAULT_LOG_TAG, "Making Class<?> instance of " + classPath + " strong");
Class<?> clazz = Class.forName(classPath.replace('/', '.'));
int key = generateNewObjectId();
makeInstanceStrong(clazz, key);
if (IsLogEnabled) Log.d(DEFAULT_LOG_TAG, "Class<?> of " + classPath + " made strong id:" + key);
return key;
}
private static void makeInstanceStrong(Object instance, int objectId)
{
if (instance == null)
{
throw new IllegalArgumentException("instance cannot be null");
}
int key = objectId;
strongInstances.put(key, instance);
strongJavaObjectToID.put(instance, key);
if (IsLogEnabled) Log.d(DEFAULT_LOG_TAG, "MakeInstanceStrong (" + key + ", " + instance.getClass().toString() + ")");
// return key;
}
private static void makeInstanceWeak(int javaObjectID, boolean keepAsWeak)
{
if (IsLogEnabled) Log.d(DEFAULT_LOG_TAG, "makeInstanceWeak instance " + javaObjectID + " keepAsWeak=" + keepAsWeak);
Object instance = strongInstances.get(javaObjectID);
if (keepAsWeak) {
weakJavaObjectToID.put(instance, Integer.valueOf(javaObjectID));
weakInstances.put(javaObjectID, new WeakReference<Object>(instance));
}
strongInstances.delete(javaObjectID);
strongJavaObjectToID.remove(instance);
}
private static void makeInstanceWeak(ByteBuffer buff, int length, boolean keepAsWeak)
{
buff.position(0);
for (int i=0; i<length; i++)
{
int javaObjectId = buff.getInt();
makeInstanceWeak(javaObjectId, keepAsWeak);
}
}
private static void checkWeakObjectAreAlive(ByteBuffer input, ByteBuffer output, int length)
{
input.position(0);
output.position(0);
for (int i=0; i<length; i++)
{
int javaObjectId = input.getInt();
WeakReference<Object> weakRef = weakInstances.get(javaObjectId);
int isReleased;
if (weakRef != null)
{
Object instance = weakRef.get();
if (instance == null)
{
isReleased = 1;
weakInstances.delete(javaObjectId);
}
else
{
isReleased = 0;
}
}
else
{
isReleased = 1;
}
output.putInt(isReleased);
}
}
public static Object getJavaObjectByID(int javaObjectID) throws Exception
{
if (IsLogEnabled) Log.d(DEFAULT_LOG_TAG, "Platform.getJavaObjectByID:" + javaObjectID);
Object instance = strongInstances.get(javaObjectID, keyNotFoundObject);
if (instance == keyNotFoundObject)
{
WeakReference<Object> wr = weakInstances.get(javaObjectID);
if (wr == null)
{
throw new NativeScriptException("No weak reference found. Attempt to use cleared object reference id=" + javaObjectID);
}
instance = wr.get();
if (instance == null)
{
throw new NativeScriptException("Attempt to use cleared object reference id=" + javaObjectID);
}
}
// Log.d(DEFAULT_LOG_TAG,
// "Platform.getJavaObjectByID found strong object with id:" +
// javaObjectID);
return instance;
}
private static Integer getJavaObjectID(Object obj)
{
Integer id = strongJavaObjectToID.get(obj);
if (id == null)
{
id = weakJavaObjectToID.get(obj);
}
return id;
}
public static int getorCreateJavaObjectID(Object obj)
{
Integer result = getJavaObjectID(obj);
if (result == null)
{
int objectId = generateNewObjectId();
makeInstanceStrong(obj, objectId);
result = objectId;
}
return result;
}
// sends args in pairs (typeID, value, null) except for objects where its
// (typeid, javaObjectID, javaJNIClassPath)
public static Object callJSMethod(Object javaObject, String methodName, Object... args) throws NativeScriptException
{
return callJSMethod(javaObject, methodName, false /* isConstructor */, args);
}
public static Object callJSMethodWithDelay(Object javaObject, String methodName, long delay, Object... args) throws NativeScriptException
{
return callJSMethod(javaObject, methodName, false /* isConstructor */, delay, args);
}
public static Object callJSMethod(Object javaObject, String methodName, boolean isConstructor, Object... args) throws NativeScriptException
{
Object ret = callJSMethod(javaObject, methodName, isConstructor, 0, args);
return ret;
}
public static Object callJSMethod(Object javaObject, String methodName, boolean isConstructor, long delay, Object... args) throws NativeScriptException
{
Integer javaObjectID = getJavaObjectID(javaObject);
if (javaObjectID == null)
{
if (IsLogEnabled) Log.e(DEFAULT_LOG_TAG, "Platform.CallJSMethod: calling js method " + methodName + " with javaObjectID " + javaObjectID + " type=" + ((javaObject != null) ? javaObject.getClass().getCanonicalName() : "null"));
APP_FAIL("Application failed");
}
if (IsLogEnabled) Log.d(DEFAULT_LOG_TAG, "Platform.CallJSMethod: calling js method " + methodName + " with javaObjectID " + javaObjectID + " type=" + ((javaObject != null) ? javaObject.getClass().getCanonicalName() : "null"));
Object result = dispatchCallJSMethodNative(javaObjectID, methodName, isConstructor, delay, args);
return result;
}
// Packages args in format (typeID, value, null) except for objects where it
// (typeid, javaObjectID, canonicalName)
// if javaObject has no javaObjecID meaning javascript object does not
// exists for this object we assign one.
private static Object[] packageArgs(Object... args)
{
int len = (args != null) ? (args.length * 3) : 0;
Object[] packagedArgs = new Object[len];
if (len > 0)
{
int jsArgsIndex = 0;
for (int i = 0; i < args.length; i++)
{
Object value = args[i];
int typeId = TypeIDs.GetObjectTypeId(value);
String javaClassPath = null;
if (typeId == TypeIDs.JsObject)
{
javaClassPath = value.getClass().getName();
value = getorCreateJavaObjectID(value);
}
packagedArgs[jsArgsIndex++] = typeId;
packagedArgs[jsArgsIndex++] = value;
packagedArgs[jsArgsIndex++] = javaClassPath;
}
}
return packagedArgs;
}
public static void APP_FAIL(String message)
{
// TODO: allow app to handle fail message report here. For example
// integrate google app reports
// Log.d(DEFAULT_LOG_TAG, message);
// System.exit(-1);
// throw an exception to enter the Thread.setDefaultUncaughtExceptionHandler
throw new NativeScriptException(message);
}
public static String resolveMethodOverload(String className, String methodName, Object[] args) throws Exception
{
if (IsLogEnabled) Log.d(DEFAULT_LOG_TAG, "resolveMethodOverload: Resolving method " + methodName + " on class " + className);
String res = MethodResolver.resolveMethodOverload(className, methodName, args);
if (IsLogEnabled) Log.d(DEFAULT_LOG_TAG, "resolveMethodOverload: method found :" + res);
if (res == null)
{
throw new Exception("Failed resolving method " + methodName + " on class " + className);
}
return res;
}
private static HashMap<String, String> map = null;
private static String readMetadata(String name) throws Exception
{
if (map == null)
{
InputStream inputStream = NativeScriptContext.getAssets().open("metadata/metadata.txt", AssetManager.ACCESS_STREAMING);
String mappings = FileSystem.readAll(inputStream);
inputStream.close();
String[] lines = mappings.split(System.getProperty("line.separator"));
HashMap<String, String> tmpMap = new HashMap<String, String>();
for (String s: lines)
{
String[] parts = s.split(" ");
tmpMap.put(parts[0], parts[1]);
}
map = tmpMap;
}
String assetName = map.get(name);
InputStream inputStream = NativeScriptContext.getAssets().open("metadata/" + assetName, AssetManager.ACCESS_STREAMING);
String metadata = FileSystem.readAll(inputStream);
inputStream.close();
return metadata;
}
public static boolean isJavaThrowable(Object obj)
{
boolean isJavaThrowable = false;
if (obj != null)
{
Class<?> c = obj.getClass();
isJavaThrowable = Throwable.class.isAssignableFrom(c);
}
return isJavaThrowable;
}
private static Object[] extendConstructorArgs(String methodName, boolean isConstructor, Object[] args)
{
Object[] arr = null;
if (methodName.equals("init"))
{
if (args == null)
{
arr = new Object[]
{ isConstructor };
}
else
{
arr = new Object[args.length + 1];
System.arraycopy(args, 0, arr, 0, args.length);
arr[arr.length - 1] = isConstructor;
}
}
else
{
arr = args;
}
return arr;
}
private static Object dispatchCallJSMethodNative(final int javaObjectID, final String methodName, boolean isConstructor, final Object[] args) throws NativeScriptException
{
return dispatchCallJSMethodNative(javaObjectID, methodName, isConstructor, 0, args);
}
private static Object dispatchCallJSMethodNative(final int javaObjectID, final String methodName, boolean isConstructor, long delay, final Object[] args) throws NativeScriptException
{
Object ret = null;
boolean isMainThread = mainThread.equals(Thread.currentThread());
final Object[] tmpArgs = extendConstructorArgs(methodName, isConstructor, args);
if (isMainThread)
{
Object[] packagedArgs = packageArgs(tmpArgs);
ret = callJSMethodNative(javaObjectID, methodName, packagedArgs);
}
else
{
Handler mainThreadHandler = new Handler(Looper.getMainLooper());
final Object[] arr = new Object[2];
Runnable r = new Runnable()
{
@Override
public void run()
{
synchronized (this)
{
try
{
final Object[] packagedArgs = packageArgs(tmpArgs);
arr[0] = callJSMethodNative(javaObjectID, methodName, packagedArgs);
}
finally
{
this.notify();
arr[1] = Boolean.TRUE;
}
}
}
};
if (delay > 0)
{
try
{
Thread.sleep(delay);
}
catch (InterruptedException e) {}
}
boolean success = mainThreadHandler.post(r);
if (success)
{
synchronized (r)
{
try
{
if (arr[1] == null)
{
r.wait();
}
}
catch (InterruptedException e)
{
ret = e;
}
}
}
ret = arr[0];
}
return ret;
}
public static Context getApplicationContext()
{
return NativeScriptContext;
}
}
|
package start;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import model.BoxReference;
import model.Proof;
import view.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import java.util.prefs.Preferences;
public class MainController implements Initializable {
@FXML
private CheckBox verification;
@FXML
private CheckBox generation;
@FXML
private TabPane tabPane;
private ViewTab currentTab;
@FXML
private Font x3;
@FXML
private Color x4;
//Toolbar buttons
@FXML
private Button loadButton;
@FXML
private Button saveButton;
@FXML
private Button newProofButton;
@FXML
private Button undoButton;
@FXML
private Button redoButton;
@FXML
private Button openBoxButton;
@FXML
private Button newRowButton;
//Inference Rules Buttons
@FXML
private Button andIntroButton;
@FXML
private Button andElim1Button;
@FXML
private Button andElim2Button;
@FXML
private Button orIntro1Button;
@FXML
private Button orIntro2Button;
@FXML
private Button orElimButton;
@FXML
private Button impIntroButton;
@FXML
private Button impElimButton;
@FXML
private Button contraElimButton;
@FXML
private Button negIntroButton;
@FXML
private Button negElimButton;
@FXML
private Button doubleNegElimButton;
@FXML
private Button eqIntroButton;
@FXML
private Button forallIntroButton;
@FXML
private Button forallElimButton;
@FXML
private Button eqElimButton;
@FXML
private Button existsIntroButton;
@FXML
private Button existsElimButton;
@FXML
private Button copyButton;
@FXML
private Button assButton;
@FXML
private Button freshButton;
@FXML
private Button premiseButton;
//Derived Rules Buttons
@FXML
private Button mtButton;
@FXML
private Button doubleNegButton;
@FXML
private Button pbcButton;
@FXML
private Button lemButton;
//Symbol Buttons
@FXML
private Button impButton;
@FXML
private Button andButton;
@FXML
private Button orButton;
@FXML
private Button negButton;
@FXML
private Button forallButton;
@FXML
private Button existsButton;
@FXML
private Button contraButton;
@FXML
void verificationToggle(ActionEvent event) {
Preferences prefs = Preferences.userRoot().node("General");
prefs.putBoolean("Verify",true); //verify set to true by default
List<Tab>tabs=tabPane.getTabs();
for(Tab tab:tabs){
ViewTab vt=(ViewTab) tab;
ProofView pv=convertProofView(vt.getView());
//Gets the proof from every Proofview tab
if(pv!=null&&pv.getProof()!=null){
Proof p = pv.getProof();
List<RowPane> proofViewList=pv.getRowList();
//Updates every row when the box is checked/unchecked
if (this.verification.selectedProperty().getValue()){
prefs.putBoolean("Verify",true);
p.verifyProof(0);
}
else{
prefs.putBoolean("Verify",false);
for(RowPane r:proofViewList) {
r.getExpression().getStyleClass().remove("conclusionReached");
r.getRule().getStyleClass().remove("unVerified");
}
}
}
}
}
@FXML
void setTheme(ActionEvent event) {
Scene scene = tabPane.getScene();
scene.getStylesheets().clear();
MenuItem caller = (MenuItem) event.getSource();
switch (caller.getText()) {
case "Dark theme":
scene.getStylesheets().add("gruvjan.css");
break;
case "Light theme":
scene.getStylesheets().add("minimalistStyle.css");
break;
}
}
@FXML
void generationToggle(ActionEvent event) {
Preferences prefs = Preferences.userRoot().node("General");
if (generation.isIndeterminate())
return;
if (this.generation.selectedProperty().getValue()) {
prefs.putBoolean("generate", true);
verification.setSelected(true);
verificationToggle(event);
} else {
prefs.putBoolean("generate", false);
}
}
@FXML
void newProof(ActionEvent event) {
ProofView pv = new ProofView(tabPane, new Proof());
}
private ProofView convertProofView(View view) {
if (view == null || !(view instanceof ProofView))
return null;
return (ProofView) view;
}
@FXML
void closeTab(ActionEvent event) {
if (currentTab != null)
tabPane.getTabs().remove(currentTab);
}
@FXML
void newRow(ActionEvent event) {
ProofView pv = convertProofView(getCurrentView());
if (pv == null)
return;
pv.newRow();
}
@FXML
void insertBelowAfterMenu(ActionEvent event) {
ProofView pv = convertProofView(getCurrentView());
if (pv == null)
return;
int rowNumber = pv.getRowNumberLastFocusedTF();
if (rowNumber != -1)
pv.addRowAfterBox(rowNumber);
}
@FXML
void openBox(ActionEvent event) { // Remove this later
ProofView pv = convertProofView(getCurrentView());
if (pv == null)
return;
int rowNumber = pv.getRowNumberLastFocusedTF();
if (rowNumber != -1)
pv.insertNewBox(rowNumber);
}
@FXML
void undo(ActionEvent event) {
ProofView pv = convertProofView(getCurrentView());
if (pv == null)
return;
pv.undo();
}
@FXML
void redo(ActionEvent event) {
ProofView pv = convertProofView(getCurrentView());
if (pv == null)
return;
pv.redo();
}
@FXML
void newProofButton(ActionEvent event) { // Remove this later
new WelcomeView(tabPane);
}
@FXML
void showInferenceRules(ActionEvent event) {
new InferenceRuleView(tabPane);
}
@FXML
void symbolButtonPressed(ActionEvent event) {
Object obj = getCurrentView();
if (obj instanceof Symbolic) {
Symbolic sym = (Symbolic) obj;
sym.addSymbol(event);
}
}
@FXML
void ruleButtonPressed(ActionEvent event) {
ProofView pv = convertProofView(getCurrentView());
if (pv != null) {
pv.addRule(event);
}
}
@FXML
void deleteRowMenu(ActionEvent event) {
ProofView pv = convertProofView(getCurrentView());
if (pv == null)
return;
int rowNumber = pv.getRowNumberLastFocusedTF();
if (rowNumber != -1) {
pv.deleteRow(rowNumber);
}
}
@FXML
void insertAboveMenu(ActionEvent event) {
ProofView pv = convertProofView(getCurrentView());
if (pv == null)
return;
int rowNumber = pv.getRowNumberLastFocusedTF();
if (rowNumber != -1)
pv.insertNewRow(rowNumber, BoxReference.BEFORE);
}
@FXML
void insertBelowMenu(ActionEvent event) {
ProofView pv = convertProofView(getCurrentView());
if (pv == null)
return;
int rowNumber = pv.getRowNumberLastFocusedTF();
if (rowNumber != -1)
pv.insertNewRow(rowNumber, BoxReference.AFTER);
}
@FXML
void saveProof(ActionEvent event) {
ProofView pv = convertProofView(getCurrentView());
if (pv == null) {
System.out.println("Not a proof, not saving");
return;
}
if (pv.getPath() == null) {
//if no path is set for current proof, call other method
saveProofAs(null);
return;
}
try {
IOHandler.saveProof(pv.getProof(), pv.getPath());
} catch (Exception e) {
System.out.println("saveProof\n" + e);
//Inform user what went wrong
}
}
@FXML
void saveProofAs(ActionEvent event) {
FileChooser fc = new FileChooser();
fc.getExtensionFilters().addAll(
new ExtensionFilter("Proofs", "*.proof"),
new ExtensionFilter("All Files", "*.*"));
File file = fc.showSaveDialog(tabPane.getScene().getWindow());
if (file == null) {
System.out.println("Path not set, file not saved");
return;
}
if (file.getAbsolutePath().endsWith(".proof") == false) {
file = new File(file.getAbsolutePath() + ".proof");
}
View view = getCurrentView();
if (view instanceof ProofView == false) {
System.out.println("Not a proof, not saving");
return;
} else {
ProofView pView = (ProofView) view;
try {
IOHandler.saveProof(pView.getProof(), file.getPath());
pView.setName(file.getName());
pView.setPath(file.getPath());
pView.getTab().setText(pView.getName());
} catch (Exception e) {
System.out.println("saveProofAs\n" + e);
//e.printStackTrace();
//Inform user what went wrong
}
}
}
@FXML
void exportProofToLatex(ActionEvent event) {
ProofView pView = convertProofView(getCurrentView());
if (pView == null)
return;
FileChooser fc = new FileChooser();
fc.getExtensionFilters().addAll(
new ExtensionFilter("LaTeX", "*.tex"),
new ExtensionFilter("All Files", "*.*"));
File file = fc.showSaveDialog(tabPane.getScene().getWindow());
if (file == null)
return;
if (file.getAbsolutePath().endsWith(".tex") == false) {
file = new File(file.getAbsolutePath() + ".tex");
}
try {
ExportLatex.export(pView.getProof(), file.getPath());
} catch (IOException e) {
e.printStackTrace();
}
}
@FXML
void openProof(ActionEvent event) {
ProofView openedProofView;
try {
openedProofView = IOHandler.openProof(tabPane);
if (openedProofView == null) {
return;
}
openedProofView.displayLoadedProof();
} catch (Exception e) {
System.out.println("MainController.openProof exception:");
System.out.println(e);
e.printStackTrace();
return;
}
}
@FXML
void showUserInstructions(ActionEvent event) {
new InstructionsView(tabPane);
}
@FXML
void showShortcuts(ActionEvent event) {
new ShortcutsView(tabPane);
}
public void createTooltip() {
//Toolbar
saveButton.setTooltip(new Tooltip("Save Proof (CTRL+S)"));
loadButton.setTooltip(new Tooltip("Open Proof (CTRL+O)"));
newProofButton.setTooltip(new Tooltip("New Proof (CTRL+N)"));
undoButton.setTooltip(new Tooltip("Undo (CTRL+Z)"));
redoButton.setTooltip(new Tooltip("Redo (CTRL+Y/CTRL+SHIFT+Z)"));
openBoxButton.setTooltip(new Tooltip("Open Box Button (CTRL+B)"));
newRowButton.setTooltip(new Tooltip("New Row (Shift+Enter)"));
verification.setTooltip(new Tooltip("Verify"));
generation.setTooltip(new Tooltip("Generate"));
//Inference Rules
andIntroButton.setTooltip(new Tooltip("And-Introduction"));
andElim1Button.setTooltip(new Tooltip("And-Elimination 1"));
andElim2Button.setTooltip(new Tooltip("And-Elimination 2"));
orIntro1Button.setTooltip(new Tooltip("Or-Introduction 1"));
orIntro2Button.setTooltip(new Tooltip("Or-Introduction 2"));
orElimButton.setTooltip(new Tooltip("Or-Elimination"));
impIntroButton.setTooltip(new Tooltip("Implication-Introduction"));
impElimButton.setTooltip(new Tooltip("Implication-Elimination"));
contraElimButton.setTooltip(new Tooltip("Contradiction-Elimination"));
negIntroButton.setTooltip(new Tooltip("Negation-Introduction"));
negElimButton.setTooltip(new Tooltip("Negation-Elimination"));
doubleNegElimButton.setTooltip(new Tooltip("Double Negation-Elimination"));
eqIntroButton.setTooltip(new Tooltip("Equality-Introduction"));
forallIntroButton.setTooltip(new Tooltip("For All-Introduction"));
forallElimButton.setTooltip(new Tooltip("For All-Elimination"));
eqElimButton.setTooltip(new Tooltip("Equality-Elimination"));
existsIntroButton.setTooltip(new Tooltip("There Exists-Introduction"));
existsElimButton.setTooltip(new Tooltip("There Exists-Elimination"));
copyButton.setTooltip(new Tooltip("Copy"));
assButton.setTooltip(new Tooltip("Assumption"));
freshButton.setTooltip(new Tooltip("Fresh Variable"));
premiseButton.setTooltip(new Tooltip("Premise"));
//Derived Rules
mtButton.setTooltip(new Tooltip("Modus Tollens"));
doubleNegButton.setTooltip(new Tooltip("Double Negation-Introduction"));
pbcButton.setTooltip(new Tooltip("Proof by Contradiction"));
lemButton.setTooltip(new Tooltip("Law of Excluded Middle"));
//Symbols
impButton.setTooltip(new Tooltip("Implication (type im to insert)"));
andButton.setTooltip(new Tooltip("And (type an to insert)"));
orButton.setTooltip(new Tooltip("Or (type or to insert)"));
negButton.setTooltip(new Tooltip("Negation (type ne to insert)"));
forallButton.setTooltip(new Tooltip("For All (type fa to insert)"));
existsButton.setTooltip(new Tooltip("There Exists (type te to insert)"));
contraButton.setTooltip(new Tooltip("Contradiction (type co to insert)"));
}
@FXML
void showWelcome(ActionEvent event) {
new WelcomeView(tabPane);
}
@Override
public void initialize(URL location, ResourceBundle resources) {
Preferences prefs = Preferences.userRoot().node("General");
if (prefs.getBoolean("generate", true)) {
generation.setSelected(true);
generationToggle(new ActionEvent());
}
tabPane.getSelectionModel().selectedItemProperty().addListener((ov, oldTab, newTab) -> {
if (newTab instanceof ViewTab) {
currentTab = (ViewTab) newTab;
} else {
currentTab = null;
}
});
if (prefs.getBoolean("showWelcome", true)) { // Om showWelcome-paret ej existerar, returnera true
new WelcomeView(tabPane);
}
createTooltip();
}
//Get the view corresponding to the currently active tab
private View getCurrentView() {
if (currentTab != null)
return currentTab.getView();
return null;
}
}
|
package ls_mxc.generator;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import ls_mxc.model.DAG;
import ls_mxc.model.Edge;
import ls_mxc.model.Node;
public class UtilizationGenerator {
private int userU_LO;
private int userU_HI;
private int userCp;
private int nbNodes;
private int nbCores;
private DAG genDAG;
private int edgeProb;
private int uHIinLO;
private int paraDegree;
private int deadline;
private int[][] adjMatrix;
public UtilizationGenerator (int U_LO, int U_HI, int cp, int edgeProb, int UHIinLO, int para) {
this.setUserU_LO(U_LO);
this.setUserU_HI(U_HI);
this.setUserCp(cp);
this.setEdgeProb(edgeProb);
this.setuHIinLO(UHIinLO);
this.setParaDegree(para);
}
/**
* Generates a DAG
*/
public void GenenrateGraphCp() {
// Variables
int id = 0;
setGenDAG(new DAG());
Set<Node> nodes = new HashSet<Node>();
boolean cpReached = false;
int rank = 0;
Random r = new Random();
// Budgets deduced by utilization and CP
int budgetHI = userCp * userU_HI;
int budgetLO = userCp * userU_LO;
int CHIBound = (int) Math.ceil(userCp / userU_HI);
int CLOBound = (int) Math.ceil(userCp / userU_LO);
if (userU_HI == 1)
CHIBound = CLOBound;
// Generate the CP in HI mode
Node last = null;
int toCP = userCp;
while (!cpReached) {
Node n = new Node(id, Integer.toString(id), 0, 0);
n.setRank(rank);
n.setC_HI(r.nextInt(CHIBound) + 2);
// Add egde and update the CP (if not source)
if (id != 0) {
Edge e = new Edge(last, n, false);
last.getSnd_edges().add(e);
n.getRcv_edges().add(e);
}
nodes.add(n);
n.CPfromNode(1);
last = n;
rank++;
id++;
if (toCP - n.getC_HI() > 0) {
toCP = toCP - n.getC_HI();
budgetHI = budgetHI - n.getC_HI();
} else {
n.setC_HI(toCP);
budgetHI = budgetHI - n.getC_HI();
cpReached = true;
}
n.setC_LO(n.getC_HI());
}
// Generate the other HI nodes and the arcs
rank = 0;
while (budgetHI > 0) {
// Roll a number of nodes to add to the level
int nodesPerRank = r.nextInt(paraDegree);
for (int j=0; j < nodesPerRank && budgetHI > 0; j++) {
Node n = new Node(id, Integer.toString(id), 0, 0);
// Roll a C_HI and test if budget is left
n.setC_HI(r.nextInt(CHIBound) + 2);
if (budgetHI - n.getC_HI() > 0) {
budgetHI = budgetHI - n.getC_HI();
} else {
n.setC_HI(budgetHI);
budgetHI = 0;
}
n.setRank(rank);
if (rank != 0) {
Iterator<Node> it_n = nodes.iterator();
while (it_n.hasNext()) {
Node src = it_n.next();
// Test if the rank of the source is lower and if the CP
// is not reached
if (r.nextInt(100) <= edgeProb && n.getRank() > src.getRank()
&& src.getCpFromNode_HI() + n.getC_HI() <= userCp) {
Edge e = new Edge(src, n, false);
src.getSnd_edges().add(e);
n.getRcv_edges().add(e);
}
}
}
n.setC_LO(n.getC_HI());
nodes.add(n);
n.CPfromNode(1);
System.out.println("Node "+ n.getId() + " CP HI in node " + n.getCpFromNode_HI());
id++;
}
rank++;
}
// Deflate HI execution times
int wantedHIinLO = uHIinLO * userCp;
int actualBudget = userU_HI * userCp;
Iterator<Node> it_n;
while (wantedHIinLO <= actualBudget || allHIareMin(nodes)) {
it_n = nodes.iterator();
while (it_n.hasNext()) {
Node n = it_n.next();
n.setC_LO(r.nextInt(n.getC_LO()) + 1);
if (n.getC_LO() == 0)
n.setC_LO(1);
actualBudget = actualBudget - n.getC_LO();
}
}
it_n = nodes.iterator();
while (it_n.hasNext()){
it_n.next().CPfromNode(0);
}
System.out.println("Deflation completed! Actual budget " + actualBudget);
// Add LO nodes
actualBudget = 0;
it_n = nodes.iterator();
while (it_n.hasNext()) {
actualBudget += it_n.next().getC_LO();
}
budgetLO = budgetLO - actualBudget;
System.out.println("\nStarting LO node generation with budget " + budgetLO + " HI in LO budget " + actualBudget);
rank = 0;
while (budgetLO > 0) {
// Roll a number of nodes to add to the level
int nodesPerRank = r.nextInt(paraDegree);
for (int j=0; j < nodesPerRank && budgetLO > 0; j++) {
Node n = new Node(id, Integer.toString(id), 0, 0);
// Roll a C_HI and test if budget is left
n.setC_HI(0);
n.setC_LO(r.nextInt(userCp/2) + 1);
if (n.getC_LO() == 0)
n.setC_LO(1); // Minimal execution time
if (budgetLO - n.getC_LO() > 0) {
budgetLO = budgetLO - n.getC_LO();
} else {
n.setC_LO(budgetLO);
budgetLO = 0;
}
n.setRank(rank);
if (rank != 0) {
Iterator<Node> it = nodes.iterator();
while (it.hasNext()) {
Node src = it.next();
// Test if the rank of the source is lower and if the CP
// is not reached
if (r.nextInt(100) <= edgeProb && n.getRank() > src.getRank()
&& src.getCpFromNode_LO() + n.getC_LO() <= userCp &&
allowedCommunitcation(src, n)) {
Edge e = new Edge(src, n, false);
src.getSnd_edges().add(e);
n.getRcv_edges().add(e);
}
}
}
nodes.add(n);
n.CPfromNode(0);
System.out.println("Node "+ n.getId() + " C LO "+ n.getC_LO() +" CP LO in node " + n.getCpFromNode_LO());
id++;
}
rank++;
}
it_n = nodes.iterator();
while (it_n.hasNext()){
Node n = it_n.next();
n.checkifSink();
n.checkifSource();
}
setNbNodes(id + 1);
genDAG.setNodes(nodes);
setDeadline(genDAG.calcCriticalPath());
//graphSanityCheck(0);
//graphSanityCheck(1);
calcMinCores();
createAdjMatrix();
System.out.println("Finished");
}
/**
* Tests if all HI nodes are minimal execution <=> C LO = 1
* @param nodes
* @return
*/
public boolean allHIareMin (Set<Node> nodes) {
Iterator<Node> it = nodes.iterator();
while (it.hasNext()){
if (it.next().getC_LO() != 1)
return false;
}
return true;
}
/**
* Calculate the minimum number of cores for the Graph.
*/
public void calcMinCores() {
int sumClo = 0;
int sumChi = 0;
int max;
Iterator<Node> it_n = genDAG.getNodes().iterator();
while (it_n.hasNext()) {
Node n = it_n.next();
sumChi += n.getC_HI();
sumClo += n.getC_LO();
}
if (sumChi >= sumClo)
max = sumChi;
else
max = sumClo;
this.setNbCores((int)Math.ceil(max/this.getDeadline()) + 1);
}
public boolean allowedCommunitcation (Node src, Node dest) {
if ((src.getC_HI() > 0 && dest.getC_HI() >= 0) ||
(src.getC_HI() == 0 && dest.getC_HI() == 0))
return true;
return false;
}
public void inflateCHIs(Set<Node> nodes, int budgetHI) {
Iterator<Node> it_n;
while (budgetHI > 0) {
it_n = nodes.iterator();
while (it_n.hasNext() && budgetHI > 0) {
Node n = it_n.next();
if (n.getC_HI() > 0) {
n.setC_HI(n.getC_HI()+1);
budgetHI
}
}
}
}
public void inflateCLOs(Set<Node> nodes, int budgetLO) {
Iterator<Node> it_n;
while (budgetLO > 0) {
it_n = nodes.iterator();
while (it_n.hasNext() && budgetLO > 0) {
Node n = it_n.next();
n.setC_LO(n.getC_LO()+1);
budgetLO
}
}
}
/**
* Sanity check for the graph:
* - Each node has to have at least one edge
*/
public void graphSanityCheck(int mode) {
boolean added = false;
Iterator<Node> it_n = genDAG.getNodes().iterator();
while (it_n.hasNext()) {
Node n = it_n.next();
// It is an independent node with no edges
if (n.getRcv_edges().size() == 0 && n.getSnd_edges().size() == 0) {
Iterator<Node> it_n2 = genDAG.getNodes().iterator();
while (it_n2.hasNext() && added == false) {
if (mode == 0) {
Node n2 = it_n2.next();
if (n.getRank() < n2.getRank() &&
allowedCommunitcation(n, n2) &&
n.getCpFromNode_LO() + n2.getC_LO() <= userCp){
Edge e = new Edge(n, n2, false);
n.getSnd_edges().add(e);
n2.getRcv_edges().add(e);
added = true;
n2.CPfromNode(mode);
} else if (n.getRank() > n2.getRank() &&
allowedCommunitcation(n2,n) &&
n2.getCpFromNode_LO() + n.getC_LO() <= userCp) {
Edge e = new Edge(n2, n, false);
n.getRcv_edges().add(e);
n2.getSnd_edges().add(e);
added = true;
n.CPfromNode(mode);
}
} else {
Node n2 = it_n2.next();
if (n.getRank() < n2.getRank() &&
allowedCommunitcation(n, n2) &&
n.getCpFromNode_HI() + n2.getC_HI() < userCp){
Edge e = new Edge(n, n2, false);
n.getSnd_edges().add(e);
n2.getRcv_edges().add(e);
added = true;
n.CPfromNode(mode);
} else if (n.getRank() > n2.getRank() &&
allowedCommunitcation(n2,n) &&
n2.getCpFromNode_HI() + n.getC_HI() < userCp) {
Edge e = new Edge(n2, n, false);
n.getRcv_edges().add(e);
n2.getSnd_edges().add(e);
added = true;
n.CPfromNode(mode);
}
}
}
added = false;
}
}
}
/**
* Creates the matrix to be written in the files
*/
public void createAdjMatrix(){
adjMatrix = new int[nbNodes][];
for (int i = 0; i < nbNodes; i++)
adjMatrix[i] = new int[nbNodes];
Iterator<Node> it_n = genDAG.getNodes().iterator();
while (it_n.hasNext()){
Node n = it_n.next();
Iterator<Edge> it_e = n.getRcv_edges().iterator();
while (it_e.hasNext()){
Edge e = it_e.next();
adjMatrix[e.getDest().getId()][e.getSrc().getId()] = 1;
}
}
}
/**
*
* @param filename
* @throws IOException
*/
public void toFile(String filename) throws IOException {
BufferedWriter out = null;
try {
File f = new File(filename);
f.createNewFile();
FileWriter fstream = new FileWriter(f);
out = new BufferedWriter(fstream);
// Write number of nodes
out.write("#NbNodes\n");
out.write(Integer.toString(this.getNbNodes()) + "\n\n");
// Write number of cores
out.write("#NbCores\n");
out.write(Integer.toString(this.getNbCores()) + "\n\n");
// Write number of cores
out.write("#Deadline\n");
out.write(Integer.toString(this.getDeadline()) + "\n\n");
//Write C LOs
out.write("#C_LO\n");
for (int i = 0; i < nbNodes - 1; i++) {
Node n = genDAG.getNodebyID(i);
out.write(Integer.toString(n.getC_LO()) + "\n");
}
out.write("\n");
//Write C HIs
out.write("#C_HI\n");
for (int i = 0; i < nbNodes - 1; i++) {
Node n = genDAG.getNodebyID(i);
out.write(Integer.toString(n.getC_HI()) + "\n");
}
out.write("\n");
//Write precedence matrix
out.write("#Pred\n");
for (int i = 0; i < nbNodes - 1; i++) {
for (int j = 0; j < nbNodes - 1; j++){
out.write(Integer.toString(adjMatrix[i][j]));
if (j < nbNodes - 2)
out.write(",");
}
out.write("\n");
}
out.write("\n");
}catch (IOException e){
System.out.print("To File : " + e.getMessage());
}finally{
if(out != null)
out.close();
}
}
/**
*
* @param filename
* @throws IOException
*/
public void toDZN(String filename) throws IOException {
}
/**
* Getters and setters
*/
public int getUserU_LO() {
return userU_LO;
}
public void setUserU_LO(int userU_LO) {
this.userU_LO = userU_LO;
}
public int getUserCp() {
return userCp;
}
public void setUserCp(int userCp) {
this.userCp = userCp;
}
public int getUserU_HI() {
return userU_HI;
}
public void setUserU_HI(int userU_HI) {
this.userU_HI = userU_HI;
}
public int getNbNodes() {
return nbNodes;
}
public void setNbNodes(int nbNodes) {
this.nbNodes = nbNodes;
}
public int getNbCores() {
return nbCores;
}
public void setNbCores(int nbCores) {
this.nbCores = nbCores;
}
public DAG getGenDAG() {
return genDAG;
}
public void setGenDAG(DAG genDAG) {
this.genDAG = genDAG;
}
public int getDeadline() {
return deadline;
}
public void setDeadline(int deadline) {
this.deadline = deadline;
}
public int getEdgeProb() {
return edgeProb;
}
public void setEdgeProb(int edgeProb) {
this.edgeProb = edgeProb;
}
public int getuHIinLO() {
return uHIinLO;
}
public void setuHIinLO(int uHIinLO) {
this.uHIinLO = uHIinLO;
}
public int getParaDegree() {
return paraDegree;
}
public void setParaDegree(int paraDegree) {
this.paraDegree = paraDegree;
}
}
|
// PyJSObjectWrapper.java
package ed.lang.python;
import java.util.*;
import org.python.core.*;
import org.python.expose.*;
import org.python.expose.generate.*;
import ed.js.*;
import ed.js.engine.*;
import static ed.lang.python.Python.*;
@ExposedType(name = "jswrapper")
public class PyJSObjectWrapper extends PyDictionary {
static PyType TYPE = Python.exposeClass(PyJSObjectWrapper.class);
public PyJSObjectWrapper( JSObject jsObject ){
this( jsObject , true );
}
public PyJSObjectWrapper( JSObject jsObject , boolean returnPyNone ){
super( TYPE );
_js = jsObject;
_returnPyNone = returnPyNone;
if ( _js == null )
throw new NullPointerException( "don't think you should create a PyJSObjectWrapper for null" );
}
public PyObject iterkeys(){
return jswrapper_iterkeys();
}
@ExposedMethod
public PyObject jswrapper_iterkeys(){
// FIXME: return an actual iterator
return jswrapper_keys();
}
public PyObject iteritems(){
// FIXME: an actual iterator
return jswrapper_iteritems();
}
@ExposedMethod
public PyObject jswrapper_iteritems(){
final Iterator<String> keys = _js.keySet().iterator();
return new PyIterator(){
public PyObject __iternext__(){
if ( ! keys.hasNext() )
return null;
String key = keys.next();
return new PyTuple( Py.newString( key ) , toPython( _js.get( key ) ) );
}
};
}
public PyList keys(){
return jswrapper_keys();
}
public PyList values(){
return jswrapper_values();
}
@ExposedMethod
public boolean jswrapper_has_key(PyObject key){
return jswrapper___contains__( key );
}
@ExposedMethod
public final PyList jswrapper_keys(){
PyList l = new PyList();
for( String s : _js.keySet() ){
l.append( Py.newString( s ) );
}
return l;
}
@ExposedMethod
public PyList jswrapper_values(){
PyList list = new PyList();
for( String key : _js.keySet() ){
list.append( toPython( _js.get( key ) ) );
}
return list;
}
public int __len__(){
return _js.keySet().size();
}
public PyObject __dir__(){
PyList list = new PyList();
for( String s : _js.keySet() ){
list.append( Py.newString( s ) );
}
return list;
}
@ExposedMethod
public final boolean jswrapper___nonzero__(){
return _js.keySet().size() > 0;
}
public boolean __nonzero__(){
return jswrapper___nonzero__();
}
public PyObject __findattr_ex__(String name) {
if ( D ) System.out.println( "__findattr__ on [" + name + "]" );
// FIXME: more graceful fail-through etc
try{
PyObject p = super.__findattr_ex__( name );
if( p != null )
return p;
}
catch(PyException e){
}
Object res = _js.get( name );
if ( res == null )
res = NativeBridge.getNativeFunc( _js , name );
return _fixReturn( res );
}
public PyObject __finditem__(PyObject key){
if ( D ) System.out.println( "__finditem__ on [" + key + "]" );
// FIXME: more graceful fail-through etc
PyObject p = super.__finditem__(key);
if( p != null )
return p;
Object jkey = toJS( key );
String skey = jkey.toString();
Object o = _js.get( jkey );
if( o == null && _js.containsKey( skey , true ) ){
return Py.None;
}
// We tried to find and got a null -- maybe this means it's not
// contained in the object?
// (Or maybe it is contained and is set to null and we couldn't
// find out, because containsKey throws an exception or something.)
// We better "fail-fast", since we're in Python land.
// Returning null here means "we don't have it", and may raise
// an exception.
if( o == null )
return null;
return _fixReturn( o );
}
private PyObject _fixReturn( Object o ){
if ( o == null && ! _returnPyNone )
return null;
return toPython( o , _js );
}
// FIXME: why is this being unwrapped twice?
// (i.e. once here, once in handleSet)
// When I take it out, I get a bunch of test failures. Look into
public void __setitem__(PyObject key, PyObject value) {
jswrapper___setitem__( key , value );
}
public final void jswrapper___setitem__( PyObject key , PyObject value ){
// PyDictionary.__setitem__ doesn't call invoke("__setitem__")
super.__setitem__(key, value);
this.handleSet( toJS( key ) , toJS( value ) );
}
public void __setattr__( String key , PyObject value ){
super.__setitem__(key, value);
this.handleSet( toJS( key ) , toJS( value ) );
}
public boolean __contains__( PyObject key ){
return jswrapper___contains__( key );
}
@ExposedMethod
public boolean jswrapper___contains__( PyObject key ){
if( key instanceof PyString )
return _js.containsKey( key.toString() );
throw new RuntimeException( "js wrappers cannot contain objects of class " + key.getClass() );
}
public void handleSet( Object key , Object value ){
_js.set( toJS( key ) , toJS( value ) );
}
public void remove( String key ){
// FIXME: check if the key exists and throw an error if not --
// this is Python after all.
try {
super.remove( key );
}
catch( PyException e ){
// Didn't have a cached Python value, no big deal.
}
_js.removeField( key.toString() );
}
@ExposedMethod
public void __delitem__( PyObject key ){
// Although we expose this, we don't use the customary
// the PyObject.__delitem__ method which is intercepted by PyDictionary.
// In order to intercept it from there, we intercept the __delitem__
// method.
// FIXME: Maybe be more rigorous about casting to String here?
remove( key.toString() );
}
public void __delattr__( String key ){
remove( key );
}
@ExposedMethod(names = {"__repr__", "__str__"})
public String toString(){
return _js.toString();
}
public void clear(){
jswrapper_clear();
}
@ExposedMethod
final public PyObject jswrapper_clear(){
throw new RuntimeException("not implemented yet");
}
public PyDictionary copy(){
return jswrapper_copy();
}
@ExposedMethod
final public PyDictionary jswrapper_copy(){
PyDictionary d = new PyDictionary();
for( String key : _js.keySet() ){
d.__setitem__( key.intern() , toPython( _js.get( key ) ) );
}
return d;
}
public PyList items(){
return jswrapper_items();
}
@ExposedMethod
final public PyList jswrapper_items(){
throw new RuntimeException("not implemented yet");
}
public PyList itervalues(){
return jswrapper_itervalues();
}
@ExposedMethod
final public PyList jswrapper_itervalues(){
throw new RuntimeException("not implemented yet");
}
public void update(PyObject dictionary){
jswrapper_update( new PyObject[]{ dictionary } , Py.NoKeywords );
}
@ExposedMethod
final public void jswrapper_update(PyObject[] args, String[] keywords){
// Seasoned copy of PyDictionary.updateCommon
int nargs = args.length - keywords.length;
if (nargs > 1) {
throw PyBuiltinFunction.DefaultInfo.unexpectedCall(nargs, false, "update", 0, 1);
}
if (nargs == 1) {
PyObject arg = args[0];
if (arg.__findattr__("keys") != null) {
merge(arg);
} else {
mergeFromSeq(arg);
}
}
for (int i = 0; i < keywords.length; i++) {
_js.set( keywords[i] , toJS ( args[nargs + i] ) );
}
}
// Following methods were taken from PyDictionary to support easier
// implementation of update().
/**
* Merge another PyObject that supports keys() with this
* dict.
*
* @param other a PyObject with a keys() method
*/
private void merge(PyObject other) {
// Seasoned copy of PyDictionary.merge
if (other instanceof PyDictionary) {
mergeFromKeys(other, ((PyDictionary)other).keys());
} else if (other instanceof PyStringMap) {
mergeFromKeys(other, ((PyStringMap)other).keys());
} else {
mergeFromKeys(other, other.invoke("keys"));
}
}
/**
* Merge another PyObject via its keys() method
*
* @param other a PyObject with a keys() method
* @param keys the result of other's keys() method
*/
private void mergeFromKeys(PyObject other, PyObject keys) {
// Seasoned copy of PyDictionary.mergeFromKeys
for (PyObject key : keys.asIterable()) {
jswrapper___setitem__(key, other.__getitem__(key));
}
}
/**
* Merge any iterable object producing iterable objects of length
* 2 into this dict.
*
* @param other another PyObject
*/
private void mergeFromSeq(PyObject other) {
// Seasoned copy of PyDictionary.mergeFromSeq
PyObject pairs = other.__iter__();
PyObject pair;
for (int i = 0; (pair = pairs.__iternext__()) != null; i++) {
// FIXME: took out call to fastSequence because it's not accessible
// from outside the Jython org.python.core package. Dumb!
int n;
if ((n = pair.__len__()) != 2) {
throw Py.ValueError(String.format("dictionary update sequence element
+ "has length %d; 2 is required", i, n));
}
jswrapper___setitem__(pair.__getitem__(0), pair.__getitem__(1));
}
}
public PyObject get( PyObject key , PyObject default_object ){
return jswrapper_get( key , default_object );
}
@ExposedMethod(defaults = "Py.None")
public final PyObject jswrapper_get( PyObject key , PyObject default_object ){
if( key instanceof PyString ){
String jkey = key.toString();
if( _js.containsKey( jkey , true ) )
return toPython( _js.get( jkey ) );
}
return default_object;
}
public PyObject setdefault( PyObject key , PyObject default_object ){
return jswrapper_setdefault( key , default_object );
}
@ExposedMethod(defaults = "Py.None")
public final PyObject jswrapper_setdefault( PyObject key , PyObject default_object ){
throw new RuntimeException("not implemented");
}
public PyObject pop( PyObject key , PyObject default_object ){
return jswrapper_pop( key , default_object );
}
@ExposedMethod(defaults = "Py.None")
public final PyObject jswrapper_pop( PyObject key , PyObject default_object ){
throw new RuntimeException("not implemented");
}
public PyObject popitem(){
return jswrapper_popitem();
}
@ExposedMethod
public final PyObject jswrapper_popitem(){
throw new RuntimeException("not implemented");
}
final JSObject _js;
final boolean _returnPyNone;
}
|
package ed.lang.python;
import ed.appserver.adapter.wsgi.WSGIAdapter;
import ed.appserver.adapter.cgi.EnvMap;
import ed.appserver.AppRequest;
import ed.appserver.JSFileLibrary;
import ed.appserver.AppContext;
import ed.util.Dependency;
import ed.io.StreamUtil;
import ed.js.engine.Scope;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Set;
import java.util.Properties;
import org.python.core.Py;
import org.python.core.PyObject;
import org.python.core.PySystemState;
import org.python.core.PyFile;
import org.python.util.PythonInterpreter;
/**
* First cut at a WSGI adapter. Designed to use any simple WSGI framework -
* currently depends on the simple WSGI framework that's offered in the spec.
* <p/>
* Right now, this only handles apps that have a clear entry function. WSGI can also
* do Class-based apps (I grok) and instance-based, which I don't think are pertinent
* to us.
*/
public class PythonWSGIAdapter extends WSGIAdapter {
protected final File _file;
protected final JSFileLibrary _lib;
private long _lastCompile;
protected final PythonInterpreter _interp;
protected PyObject _run_with_cgi; // framework entry point
protected PyObject _wsgi_appEntry; // code entry point
/**
* DO basic setup - parse the WSGI framework code and get the functional entry point
*
* @param context app context
* @param f file we are meant to call - this is currently irrelevant as the WSGI entry is fixed.
* We need to fix this to explore the specified file for the WSGI entry point
* @param lib current lib for this app
*/
PythonWSGIAdapter(AppContext context, File f, JSFileLibrary lib) {
_file = f;
_lib = lib;
SiteSystemState ssstate = Python.getSiteSystemState(context, context.getScope());
PythonInterpreter.initialize(System.getProperties(), new Properties(), new String[0]);
PySystemState sys = ssstate.getPyState();
_interp = new PythonInterpreter(null, sys);
PySystemState oldState = Py.getSystemState();
try {
Py.setSystemState(sys);
// just use the standard wsgiref package that comes w/ python
_interp.exec("import wsgiref.handlers\ndef invoke_wsgi(application):\n wsgiref.handlers.CGIHandler().run(application)\n");
_run_with_cgi = _interp.get("invoke_wsgi");
_getAppCode();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
Py.setSystemState(oldState);
}
}
/**
* The actual rendering call - use the framework and the app entry point and stand back!
*
* @param env WSGI env map - includes CGI + specified WSGI elements
* @param stdin input stream
* @param stdout output stream
* @param ar request object for this request
*/
public void handleWSGI(EnvMap env, InputStream stdin, OutputStream stdout, AppRequest ar) {
// TODO - I'm vague on the setup - need to sit down w/ Ethan and refactor this, CGI and Jxp
AppContext ac = ar.getContext();
Scope siteScope = ac.getScope();
SiteSystemState ss = Python.getSiteSystemState(ac, siteScope);
PySystemState pyOld = Py.getSystemState();
ss.flushOld();
ss.ensurePath(_file.getParent());
ss.ensurePath(_lib.getRoot().toString());
ss.ensurePath(_lib.getTopParent().getRoot().toString());
PyObject globals = ss.globals;
globals.__setitem__("__file__", Py.newString(_file.toString()));
PyObject environ = ss.getPyState().getEnviron();
for (String key : env.keySet()) {
Object o = env.get(key);
if (o instanceof PyObject) {
environ.__setitem__(key.intern(), (PyObject) o);
}
else {
// Hail Mary, full of grace...
environ.__setitem__(key.intern(), Py.newString((String) o));
}
}
PythonCGIAdapter.CGIStreamHolder cgiosw = new PythonCGIAdapter.CGIStreamHolder(stdout);
ss.getPyState().stdout = new PythonCGIOutFile();
ss.getPyState().stdin = new PyFile(stdin);
try {
_getAppCode(); // get latest app code
Py.setSystemState(ss.getPyState());
_run_with_cgi.__call__(_wsgi_appEntry);
}
catch (IOException e) {
e.printStackTrace(); // TODO - fix
} finally {
cgiosw.unset();
Py.setSystemState(pyOld);
}
}
public void handleCGI(EnvMap env, InputStream stdin, OutputStream stdout, AppRequest ar) {
handleWSGI(env, stdin, stdout, ar);
}
/**
* Refreshes the application code based on modification time. Will see the internal _wsgi_apEntry
* variable (code entry point of the WSGI app)
*
* @throws IOException if problem w/ specified application file
*/
protected void _getAppCode() throws IOException {
long lastModified = _file.lastModified();
if (_lastCompile < lastModified) {
String code = StreamUtil.readFully(_file);
_interp.exec(code);
_wsgi_appEntry = _interp.get("application"); // TODO - let specify in _init.js or app meta and make reloadable
_lastCompile = lastModified;
}
}
public long lastUpdated(Set<Dependency> visitedDeps) {
return _file.lastModified();
}
public String getName() {
return _file.toString();
}
public File getFile() {
return _file;
}
}
|
package SW9.model_canvas.edges;
import SW9.model_canvas.Removable;
import SW9.utility.helpers.DragHelper;
import SW9.utility.mouse.MouseTracker;
import javafx.beans.binding.When;
import javafx.beans.property.DoubleProperty;
import javafx.beans.value.ObservableDoubleValue;
import javafx.scene.Parent;
import javafx.scene.shape.Circle;
public class Nail extends Circle implements Removable {
private final static double HIDDEN_RADIUS = 0d;
private final static double VISIBLE_RADIUS = 7d;
private final MouseTracker mouseTracker = new MouseTracker(this);
private Edge detachedParent;
int restoreIndex;
public boolean isBeingDragged = false;
public Nail(final ObservableDoubleValue centerX, final ObservableDoubleValue centerY) {
super(centerX.get(), centerY.get(), HIDDEN_RADIUS);
xProperty().bind(centerX);
yProperty().bind(centerY);
// Style the nail
getStyleClass().add("nail");
// Hide the nails so that they do not become rendered right away
visibleProperty().setValue(false);
// Bind the radius to the visibility property (so that we do not get space between links)
radiusProperty().bind(new When(visibleProperty()).then(VISIBLE_RADIUS).otherwise(HIDDEN_RADIUS));
mouseTracker.registerOnMousePressedEventHandler(event -> isBeingDragged = true);
mouseTracker.registerOnMouseReleasedEventHandler(event -> isBeingDragged = false);
// Update the hovered nail of the edge that this nail belong to
mouseTracker.registerOnMouseEnteredEventHandler(e -> getEdgeParent().setHoveredNail(this));
mouseTracker.registerOnMouseExitedEventHandler(e -> {
if (this.equals(getEdgeParent().getHoveredNail())) {
getEdgeParent().setHoveredNail(null);
}
});
DragHelper.makeDraggable(this);
}
@Override
public MouseTracker getMouseTracker() {
return mouseTracker;
}
@Override
public DoubleProperty xProperty() {
return centerXProperty();
}
@Override
public DoubleProperty yProperty() {
return centerYProperty();
}
@Override
public boolean select() {
detachedParent = getEdgeParent();
getStyleClass().add("selected");
return true;
}
@Override
public void deselect() {
getStyleClass().remove("selected");
}
@Override
public void remove() {
getEdgeParent().remove(this);
}
@Override
public void reAdd() {
detachedParent.add(this, restoreIndex);
}
private Edge getEdgeParent() {
Parent parent = getParent();
while (parent != null) {
if (parent instanceof Edge) {
return ((Edge) parent);
}
parent = parent.getParent();
}
return null;
}
}
|
package Services.Books;
import Services.Books.BooksarrayJSON.Books;
import com.google.gson.Gson;
import com.google.gson.*;
import com.google.common.collect.Lists;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.lang.reflect.Type;
import java.net.*;
import java.lang.*;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class BooksService {
private static HashMap<String, String> book ;
private static List<HashMap<String,String>> arrayList ;
private static ArrayList<Books> BooksList ;
private LinkedList<Integer> BooksIDs = new LinkedList<>();// {"00001", "00002"};
// private String[] BooksNames = {"Engineering Psychology and Human Performance", "Some Book"};
private LinkedList<String> BooksNames = new LinkedList<>();
//private String[] BooksAuthors = {"Christopher D. Wickens , Justin G. Hollands, Simon Banbury, Raja Parasuraman", "Many Authors"};
private LinkedList<String> BooksAuthors = new LinkedList<>();
// private String[] BooksCondition = {"New", "Used - Very Good"};
private LinkedList<String> BooksCondition = new LinkedList<>();
// private String[] BooksUniversity = {"University of Pittsburgh", "CMU"};
private LinkedList<String> BooksUniversity = new LinkedList<>();
// private String[] BooksSchool = {"School of Information Science", "CS"};
private LinkedList<String> BooksSchool = new LinkedList<>();
// private String[] BooksDescription = {"Forming connections between human performance and design Engineering Psychology and Human"
// + " Performance, 4e examines human-machine interaction. The book is organized directly from the psychological "
// + "perspective of human information processing. The chapters generally correspond to the flow of information as it is "
// + "processed by a human being--from the senses, through the brain, to action--rather than from the perspective of "
// + "system components or engineering design concepts. This book is ideal for a psychology student, engineering student, "
// + "or actual practitioner in engineering psychology, human performance, and human factors Learning Goals Upon "
// + "completing this book, readers should be able to: * Identify how human ability contributes to the design of "
// + "technology. * Understand the connections within human information processing and human performance. * Challenge the"
// + " way they think about technology's influence on human performance. * show how theoretical advances have been, or "
// + "might be, applied to improving human-machine interaction", "Test Description"};
private LinkedList<String> BooksDescription = new LinkedList<>();
//private String[] BooksISBN13 = {"978-0205021987", "111-2233445566"};
private LinkedList<String> BooksISBN13 = new LinkedList<>();
//private String[] BooksISBN10 = {"0205021980", "1122334455"};
private LinkedList<String> BooksISBN10 = new LinkedList<>();
//private String[] BooksImages = {"book1.jpg", "Book.JPG"};
private LinkedList<String> BooksImages = new LinkedList<>();
//private String[] BooksCourse = {"Human Factors in System Design", "Course Name"};
private LinkedList<String> BooksCourse = new LinkedList<>();
public BooksService(){
// saveListToFile();
}
public List<HashMap<String, String>> getAllBooks(){
return readCurrentList();
}
public List<HashMap<String,String>> getOneBook(Integer id){
List<HashMap<String,String>> Books = readCurrentList();
Integer size = Books.size();
arrayList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i<size; i++){
if(Books.get(i).get("BookID").equals(id.toString())){
book = new HashMap<String, String>();
book.put("BookID",Books.get(i).get("BookID"));
book.put("BookName",Books.get(i).get("BookName"));
book.put("BookAuthors",Books.get(i).get("BookAuthors"));
book.put("BookCondition",Books.get(i).get("BookCondition"));
book.put("BookUniversity",Books.get(i).get("BookUniversity"));
book.put("BookSchool",Books.get(i).get("BookSchool"));
book.put("BookDescription",Books.get(i).get("BookDescription"));
book.put("BookISBN13",Books.get(i).get("BookISBN13"));
book.put("BookISBN10",Books.get(i).get("BookISBN10"));
book.put("BookImages",Books.get(i).get("BookImages"));
book.put("BookCourse",Books.get(i).get("BookCourse"));
arrayList.add(book);
}
}
return arrayList;
}
public void createBook( String bookname, String bookauthors,
String bookcondition, String bookuniversity, String bookschool, String bookcourse,
String bookISBN13, String bookISBN10, String bookimg, String bookdescription){
try {
List<HashMap<String,String>> Books = readCurrentList();
book = new HashMap<String, String>();
Integer size=Books.size();
size = size+1;
book.put("BookID", size.toString());
book.put("BookName", bookname);
book.put("BookAuthors", bookauthors);
book.put("BookCondition", bookcondition);
book.put("BookUniversity", bookuniversity);
book.put("BookSchool", bookschool);
book.put("BookDescription",bookdescription);
book.put("BookISBN13", bookISBN13);
book.put("BookISBN10",bookISBN10);
book.put("BookImages",bookimg);
book.put("BookCourse", bookcourse);
Books.add(book);
Gson gson = new GsonBuilder().create();
String arrayListToJson = gson.toJson(Books);
String filename = "Book_entries.json";
File file = new File("src/main/resources/public",filename);
file.delete();
BufferedWriter buffWriter = new BufferedWriter(new FileWriter(file, true));
buffWriter.append(arrayListToJson);
buffWriter.newLine();
buffWriter.close();
} catch (IOException e) {
}
}
public Integer getNumberOfBooks(){
int size = BooksIDs.size();
return size;
}
public String getbooksname(){
return BooksNames.get(0);
}
public int saveListToFile() {
Books book1 = new Books();
book1.setBookID(1);
book1.setBookName("Engineering Psychology and Human Performance");
book1.setBookAuthor("Christopher D. Wickens , Justin G. Hollands, Simon Banbury, Raja Parasuraman");
book1.setBookCondition("New");
book1.setBookUniversity("University of Pittsburgh");
book1.setBookSchool("School of Information Science");
book1.setBookDescription("Forming connections between human performance and design Engineering Psychology and Human"
+ " Performance, 4e examines human-machine interaction. The book is organized directly from the psychological "
+ "perspective of human information processing. The chapters generally correspond to the flow of information as it is "
+ "processed by a human being--from the senses, through the brain, to action--rather than from the perspective of "
+ "system components or engineering design concepts. This book is ideal for a psychology student, engineering student, "
+ "or actual practitioner in engineering psychology, human performance, and human factors Learning Goals Upon "
+ "completing this book, readers should be able to: * Identify how human ability contributes to the design of "
+ "technology. * Understand the connections within human information processing and human performance. * Challenge the"
+ " way they think about technology's influence on human performance. * show how theoretical advances have been, or "
+ "might be, applied to improving human-machine interaction");
book1.setBookISBN13("978-0205021987");
book1.setBookISBN10("0205021980");
book1.setBookImages("book1.jpg");
book1.setBookCourse("Human Factors in System Design");
Books book2 = new Books();
book2.setBookID(2);
book2.setBookName("Some Book");
book2.setBookAuthor("Many Authors");
book2.setBookCondition("Used - Very Good");
book2.setBookUniversity("CMU");
book2.setBookSchool("CS");
book2.setBookDescription("Test Description");
book2.setBookISBN13("111-2233445566");
book2.setBookISBN10("1122334455");
book2.setBookImages("Book.JPG");
book2.setBookCourse("Course Name");
List<Books> Books = Lists.newArrayList(book1, book2);
Gson gson = new GsonBuilder().create();
String arrayListToJson = gson.toJson(Books);
String filename = "Book_entries.json";
File file = new File("src/main/resources/public",filename);
file.delete();
try {
BufferedWriter buffWriter = new BufferedWriter(new FileWriter(file, true));
buffWriter.append(arrayListToJson);
buffWriter.newLine();
buffWriter.close();
} catch (IOException e) {
return -1;
}
return 0;
}
public List<HashMap<String, String>> readCurrentList() {
String filename = "Book_entries.json";
File file = new File("src/main/resources/public",filename);
List<HashMap<String,String>> Book = null;
Gson gson = new Gson();
try {
BufferedReader buffReader = new BufferedReader(new FileReader(file));
String line;
String jsonString= "";
while ((line = buffReader.readLine()) != null) {
jsonString= jsonString+line;
}
buffReader.close();
@SuppressWarnings("serial")
Type collectionType = new TypeToken<List<HashMap<String,String>>>() {
}.getType();
Book = gson.fromJson(jsonString, collectionType);
return Book;
} catch (IOException e) {
return Book;
}
}
public String getAllUniversities(){
try {
//filename is filepath string
BufferedReader br = new BufferedReader(new FileReader(new File("src/main/resources/public/unixml.xml")));
String line;
StringBuilder sb = new StringBuilder();
while((line=br.readLine())!= null){
sb.append(line.trim());
}
return sb.toString();
}
catch (Exception e) {
return e.toString();
}
}
public static String getOneUniversities(String id){
String output = null;
try {
File fXmlFile = new File("src/main/resources/public/unixml.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
dbFactory.setNamespaceAware(true);
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("University");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
Element element = (Element) node;
if (id.equals(getValue("name", element))) {
output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Universities> <University>" + "<name>" + getValue("name", element)+ "</name></University></Universities>" ;
}
}} catch (Exception ex) {
ex.printStackTrace();}
return output;
}
public static String getValue(String tag, Element element) {
NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodes.item(0);
return node.getNodeValue();
}
}
|
package apoc.cypher;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.ResourceIterator;
import org.neo4j.graphdb.Result;
import org.neo4j.procedure.Context;
import org.neo4j.procedure.Description;
import org.neo4j.procedure.Name;
import org.neo4j.procedure.UserFunction;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static apoc.cypher.Cypher.withParamMapping;
public class CypherFunctions {
@Context
public GraphDatabaseService db;
@UserFunction
@Deprecated
@Description("use either apoc.cypher.runFirstColumnMany for a list return or apoc.cypher.runFirstColumnSingle for returning the first row of the first column")
public Object runFirstColumn(@Name("cypher") String statement, @Name("params") Map<String, Object> params, @Name(value = "expectMultipleValues",defaultValue = "true") boolean expectMultipleValues) {
if (params == null) params = Collections.emptyMap();
String resolvedStatement = withParamMapping(statement, params.keySet());
if (!resolvedStatement.contains(" runtime")) resolvedStatement = "cypher runtime=slotted " + resolvedStatement;
try (Result result = db.execute(resolvedStatement, params)) {
String firstColumn = result.columns().get(0);
try (ResourceIterator<Object> iter = result.columnAs(firstColumn)) {
if (expectMultipleValues) return iter.stream().collect(Collectors.toList());
return iter.hasNext() ? iter.next() : null;
}
}
}
@UserFunction
@Description("apoc.cypher.runFirstColumnMany(statement, params) - executes statement with given parameters, returns first column only collected into a list, params are available as identifiers")
public List<Object> runFirstColumnMany(@Name("cypher") String statement, @Name("params") Map<String, Object> params) {
return (List)runFirstColumn(statement, params, true);
}
@UserFunction
@Description("apoc.cypher.runFirstColumnSingle(statement, params) - executes statement with given parameters, returns first element of the first column only, params are available as identifiers")
public Object runFirstColumnSingle(@Name("cypher") String statement, @Name("params") Map<String, Object> params) {
return runFirstColumn(statement, params, false);
}
}
|
package app.lsgui.model;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.StringProperty;
public interface StreamModel {
public StringProperty getName();
public BooleanProperty getOnline();
}
|
package app.lsgui.utils;
import org.controlsfx.control.PopOver;
import org.controlsfx.control.PopOver.ArrowLocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import app.lsgui.model.IService;
import app.lsgui.model.twitch.TwitchService;
import javafx.geometry.Insets;
import javafx.geometry.Point2D;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Window;
public final class PopOverUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(PopOverUtil.class);
private static final int CORDER_RADIUS = 4;
private static final Insets INSETS = new Insets(8);
private PopOverUtil() {
}
public static PopOver createAddDialog(final Node root, final IService service) {
final PopOver popOver = new PopOver();
popOver.getRoot().getStylesheets().add(PopOverUtil.class
.getResource("/styles/" + Settings.getInstance().getWindowStyle() + ".css").toExternalForm());
final VBox dialogBox = new VBox();
dialogBox.setPadding(INSETS);
final HBox buttonBox = new HBox();
final Button submitButton = new Button("Submit");
final Button cancelButton = new Button("Cancel");
final HBox nameBox = new HBox();
final Label nameLabel = new Label("Name ");
final TextField nameTextField = new TextField();
nameBox.getChildren().add(nameLabel);
nameBox.getChildren().add(nameTextField);
final HBox urlBox = new HBox();
final Label urlLabel = new Label("URL ");
final TextField urlTextField = new TextField();
urlBox.getChildren().add(urlLabel);
urlBox.getChildren().add(urlTextField);
buttonBox.getChildren().add(submitButton);
buttonBox.getChildren().add(cancelButton);
final Button addChannelButton = new Button("Add Channel");
final Button addServiceButton = new Button("Add Service");
addChannelButton.setOnAction(event -> {
dialogBox.getChildren().clear();
dialogBox.getChildren().add(nameBox);
dialogBox.getChildren().add(buttonBox);
});
addServiceButton.setOnAction(event -> {
dialogBox.getChildren().clear();
dialogBox.getChildren().add(nameBox);
dialogBox.getChildren().add(urlBox);
dialogBox.getChildren().add(buttonBox);
});
submitButton.setOnAction(event -> {
if (dialogBox.getChildren().contains(urlBox)) {
final String serviceName = nameTextField.getText();
final String serviceUrl = urlTextField.getText();
LOGGER.info("Adding service");
LsGuiUtils.addService(serviceName, serviceUrl);
} else {
final String channelName = nameTextField.getText();
LOGGER.info("Adding channel");
LsGuiUtils.addChannelToService(channelName, service);
}
popOver.hide();
});
submitButton.setDefaultButton(true);
cancelButton.setOnAction(event -> popOver.hide());
dialogBox.getChildren().add(addChannelButton);
dialogBox.getChildren().add(addServiceButton);
popOver.setContentNode(dialogBox);
popOver.setArrowLocation(ArrowLocation.TOP_LEFT);
popOver.setCornerRadius(CORDER_RADIUS);
popOver.setTitle("Add new Channel or Service");
final Point2D clickedPoint = getClickedPoint(root);
popOver.show(root.getParent(), clickedPoint.getX(), clickedPoint.getY());
return popOver;
}
public static PopOver createImportPopOver(final Node root, final TwitchService service) {
final PopOver popOver = new PopOver();
popOver.getRoot().getStylesheets().add(PopOverUtil.class
.getResource("/styles/" + Settings.getInstance().getWindowStyle() + ".css").toExternalForm());
final VBox dialogBox = new VBox();
dialogBox.setPadding(INSETS);
final HBox buttonBox = new HBox();
final Button submitButton = new Button("Import");
final Button cancelButton = new Button("Cancel");
final TextField nameTextField = new TextField();
buttonBox.getChildren().add(submitButton);
buttonBox.getChildren().add(cancelButton);
dialogBox.getChildren().add(nameTextField);
dialogBox.getChildren().add(buttonBox);
submitButton.setOnAction(event -> {
final String username = nameTextField.getText();
TwitchUtils.addFollowedChannelsToService(username, service);
popOver.hide();
});
submitButton.setDefaultButton(true);
cancelButton.setOnAction(event -> popOver.hide());
popOver.setContentNode(dialogBox);
popOver.setArrowLocation(ArrowLocation.TOP_LEFT);
popOver.setCornerRadius(CORDER_RADIUS);
popOver.setTitle("Import followed Twitch.tv Channels");
final Point2D clickedPoint = getClickedPoint(root);
popOver.show(root.getParent(), clickedPoint.getX(), clickedPoint.getY());
return popOver;
}
private static Point2D getClickedPoint(final Node root) {
final Scene scene = root.getScene();
final Point2D nodeCoord = root.localToScene(0.0D, 25.0D);
final Window sceneWindow = scene.getWindow();
final Point2D windowCoord = new Point2D(sceneWindow.getX(), sceneWindow.getY());
final Point2D sceneCoord = new Point2D(scene.getX(), scene.getY());
final double clickX = Math.round(windowCoord.getX() + sceneCoord.getY() + nodeCoord.getX());
final double clickY = Math.round(windowCoord.getY() + sceneCoord.getY() + nodeCoord.getY());
return new Point2D(clickX, clickY);
}
}
|
package backend.resource;
import backend.resource.serialization.SerializableLabel;
import javafx.scene.Node;
import javafx.scene.control.Tooltip;
import org.eclipse.egit.github.core.Label;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@SuppressWarnings("unused")
public class TurboLabel {
private static final String EXCLUSIVE_DELIMITER = ".";
private static final String NONEXCLUSIVE_DELIMITER = "-";
private void ______SERIALIZED_FIELDS______() {
}
private final String actualName;
private final String colour;
private void ______TRANSIENT_FIELDS______() {
}
private final String repoId;
private void ______CONSTRUCTORS______() {
}
public TurboLabel(String repoId, String name) {
this.actualName = name;
this.colour = "#ffffff";
this.repoId = repoId;
}
public static TurboLabel nonexclusive(String repoId, String group, String name) {
return new TurboLabel(repoId, joinWith(group, name, false));
}
public static TurboLabel exclusive(String repoId, String group, String name) {
return new TurboLabel(repoId, joinWith(group, name, true));
}
public TurboLabel(String repoId, Label label) {
this.actualName = label.getName();
this.colour = label.getColor();
this.repoId = repoId;
}
public TurboLabel(String repoId, SerializableLabel label) {
this.actualName = label.getActualName();
this.colour = label.getColour();
this.repoId = repoId;
}
private void ______METHODS______() {
}
private Optional<String> getDelimiter() {
// Escaping due to constants not being valid regexes
Pattern p = Pattern.compile(String.format("^[^\\%s\\%s]+(\\%s|\\%s)",
EXCLUSIVE_DELIMITER,
NONEXCLUSIVE_DELIMITER,
EXCLUSIVE_DELIMITER,
NONEXCLUSIVE_DELIMITER));
Matcher m = p.matcher(actualName);
if (m.find()) {
return Optional.of(m.group(1));
} else {
return Optional.empty();
}
}
private static String joinWith(String group, String name, boolean exclusive) {
return group + (exclusive ? EXCLUSIVE_DELIMITER : NONEXCLUSIVE_DELIMITER) + name;
}
public boolean isExclusive() {
if (getDelimiter().isPresent()) {
return getDelimiter().get().equals(EXCLUSIVE_DELIMITER);
} else {
return false;
}
}
public Optional<String> getGroup() {
if (getDelimiter().isPresent()) {
String delimiter = getDelimiter().get();
// Escaping due to constants not being valid regexes
String[] segments = actualName.split("\\" + delimiter);
assert segments.length >= 1;
if (segments.length == 1) {
if (actualName.endsWith(delimiter)) {
// group.
return Optional.of(segments[0]);
} else {
// .name
return Optional.empty();
}
} else {
// group.name
assert segments.length == 2;
return Optional.of(segments[0]);
}
} else {
// name
return Optional.empty();
}
}
public String getName() {
if (getDelimiter().isPresent()) {
String delimiter = getDelimiter().get();
// Escaping due to constants not being valid regexes
String[] segments = actualName.split("\\" + delimiter);
assert segments.length >= 1;
if (segments.length == 1) {
if (actualName.endsWith(delimiter)) {
// group.
return "";
} else {
// .name
return segments[0];
}
} else {
// group.name
assert segments.length == 2;
return segments[1];
}
} else {
// name
return actualName;
}
}
private String getStyle() {
String colour = getColour();
int R = Integer.parseInt(colour.substring(0, 2), 16);
int G = Integer.parseInt(colour.substring(2, 4), 16);
int B = Integer.parseInt(colour.substring(4, 6), 16);
double L = 0.2126 * R + 0.7152 * G + 0.0722 * B;
boolean bright = L > 128;
return "-fx-background-color: #" + getColour() + "; -fx-text-fill: " + (bright ? "black" : "white");
}
public Node getNode() {
javafx.scene.control.Label node = new javafx.scene.control.Label(getName());
node.getStyleClass().add("labels");
node.setStyle(getStyle());
if (getGroup().isPresent()) {
Tooltip groupTooltip = new Tooltip(getGroup().get());
node.setTooltip(groupTooltip);
}
return node;
}
@Override
public String toString() {
return actualName;
}
private void ______BOILERPLATE______() {
}
public String getRepoId() {
return repoId;
}
public String getColour() {
return colour;
}
public String getActualName() {
return actualName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TurboLabel that = (TurboLabel) o;
if (!actualName.equals(that.actualName)) return false;
if (!colour.equals(that.colour)) return false;
return true;
}
@Override
public int hashCode() {
int result = actualName.hashCode();
result = 31 * result + colour.hashCode();
return result;
}
}
|
package backend.stub;
import backend.IssueMetadata;
import backend.resource.TurboIssue;
import backend.resource.TurboLabel;
import backend.resource.TurboMilestone;
import backend.resource.TurboUser;
import github.IssueEventType;
import github.TurboIssueEvent;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.eclipse.egit.github.core.Comment;
import org.eclipse.egit.github.core.Label;
import org.eclipse.egit.github.core.User;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
public class DummyRepoState {
private String dummyRepoId;
private TreeMap<Integer, TurboIssue> issues = new TreeMap<>();
private TreeMap<String, TurboLabel> labels = new TreeMap<>();
private TreeMap<Integer, TurboMilestone> milestones = new TreeMap<>();
private TreeMap<String, TurboUser> users = new TreeMap<>();
private TreeMap<Integer, TurboIssue> updatedIssues = new TreeMap<>();
private TreeMap<String, TurboLabel> updatedLabels = new TreeMap<>();
private TreeMap<Integer, TurboMilestone> updatedMilestones = new TreeMap<>();
private TreeMap<String, TurboUser> updatedUsers = new TreeMap<>();
public DummyRepoState(String repoId) {
this.dummyRepoId = repoId;
for (int i = 0; i < 10; i++) {
// Issue #7 is a PR
TurboIssue dummyIssue = (i != 6) ? makeDummyIssue() : makeDummyPR();
// All default issues are treated as if created a long time ago
dummyIssue.setUpdatedAt(LocalDateTime.of(2000 + i, 1, 1, 0, 0));
TurboLabel dummyLabel = makeDummyLabel();
TurboMilestone dummyMilestone = makeDummyMilestone();
TurboUser dummyUser = makeDummyUser();
// Populate state with defaults
issues.put(dummyIssue.getId(), dummyIssue);
labels.put(dummyLabel.getActualName(), dummyLabel);
milestones.put(dummyMilestone.getId(), dummyMilestone);
users.put(dummyUser.getLoginName(), dummyUser);
}
// Issues #1-5 are assigned milestones 1-5 respectively
for (int i = 1; i <= 5; i++) {
issues.get(i).setMilestone(milestones.get(i));
}
// Odd issues are assigned label 1, even issues are assigned label 2
for (int i = 1; i <= 10; i++) {
issues.get(i).addLabel((i % 2 == 0) ? "Label 1" : "Label 2");
}
// We assign a colorful label to issue 10
labels.put("Label 11", new TurboLabel(dummyRepoId, "ffa500", "Label 11"));
issues.get(10).addLabel("Label 11");
// Each user is assigned to his corresponding issue
for (int i = 1; i <= 10; i++) {
issues.get(i).setAssignee("User " + i);
}
// Then put down three comments for issue 10
Comment dummyComment1 = new Comment();
Comment dummyComment2 = new Comment();
Comment dummyComment3 = new Comment();
dummyComment1.setCreatedAt(new Date()); // Recently posted
dummyComment2.setCreatedAt(new Date());
dummyComment3.setCreatedAt(new Date(0)); // Posted very long ago
dummyComment1.setUser(new User().setLogin("User 1"));
dummyComment2.setUser(new User().setLogin("User 2"));
dummyComment3.setUser(new User().setLogin("User 3"));
Comment[] dummyComments = { dummyComment1, dummyComment2, dummyComment3 };
issues.get(10).setMetadata(new IssueMetadata(
new ArrayList<>(),
new ArrayList<>(Arrays.asList(dummyComments))
));
issues.get(10).setCommentCount(3);
issues.get(10).setUpdatedAt(LocalDateTime.now());
// Issue 6 is closed
issues.get(6).setOpen(false);
// add more labels into repo
labels.put("Label 11", new TurboLabel(dummyRepoId, "p.low"));
labels.put("Label 11", new TurboLabel(dummyRepoId, "p.medium"));
labels.put("Label 11", new TurboLabel(dummyRepoId, "p.high"));
}
protected ImmutableTriple<List<TurboIssue>, String, Date>
getUpdatedIssues(String eTag, Date lastCheckTime) {
String currETag = eTag;
if (!updatedIssues.isEmpty() || eTag == null) currETag = UUID.randomUUID().toString();
ImmutableTriple<List<TurboIssue>, String, Date> toReturn = new ImmutableTriple<>(
new ArrayList<>(updatedIssues.values()), currETag, lastCheckTime);
updatedIssues = new TreeMap<>();
return toReturn;
}
protected ImmutablePair<List<TurboLabel>, String> getUpdatedLabels(String eTag) {
String currETag = eTag;
if (!updatedLabels.isEmpty() || eTag == null) currETag = UUID.randomUUID().toString();
ImmutablePair<List<TurboLabel>, String> toReturn
= new ImmutablePair<>(new ArrayList<>(updatedLabels.values()), currETag);
updatedLabels = new TreeMap<>();
return toReturn;
}
protected ImmutablePair<List<TurboMilestone>, String> getUpdatedMilestones(String eTag) {
String currETag = eTag;
if (!updatedMilestones.isEmpty() || eTag == null) currETag = UUID.randomUUID().toString();
ImmutablePair<List<TurboMilestone>, String> toReturn
= new ImmutablePair<>(new ArrayList<>(updatedMilestones.values()), currETag);
updatedMilestones = new TreeMap<>();
return toReturn;
}
protected ImmutablePair<List<TurboUser>, String> getUpdatedCollaborators(String eTag) {
String currETag = eTag;
if (!updatedUsers.isEmpty() || eTag == null) currETag = UUID.randomUUID().toString();
ImmutablePair<List<TurboUser>, String> toReturn
= new ImmutablePair<>(new ArrayList<>(updatedUsers.values()), currETag);
updatedUsers = new TreeMap<>();
return toReturn;
}
protected List<TurboIssue> getIssues() {
return new ArrayList<>(issues.values());
}
protected List<TurboLabel> getLabels() {
return new ArrayList<>(labels.values());
}
protected List<TurboMilestone> getMilestones() {
return new ArrayList<>(milestones.values());
}
protected List<TurboUser> getCollaborators() {
return new ArrayList<>(users.values());
}
private TurboIssue makeDummyIssue() {
return new TurboIssue(dummyRepoId,
issues.size() + 1,
"Issue " + (issues.size() + 1),
"User " + (issues.size() + 1),
LocalDateTime.of(1999 + issues.size(), 1, 1, 0, 0),
false);
}
private TurboIssue makeDummyPR() {
return new TurboIssue(dummyRepoId,
issues.size() + 1,
"PR " + (issues.size() + 1),
"User " + (issues.size() + 1),
LocalDateTime.of(1999 + issues.size(), 1, 1, 0, 0),
true);
}
private TurboLabel makeDummyLabel() {
return new TurboLabel(dummyRepoId, "Label " + (labels.size() + 1));
}
private TurboMilestone makeDummyMilestone() {
return new TurboMilestone(dummyRepoId, milestones.size() + 1, "Milestone " + (milestones.size() + 1));
}
private TurboUser makeDummyUser() {
return new TurboUser(dummyRepoId, "User " + (users.size() + 1));
}
protected List<TurboIssueEvent> getEvents(int issueId) {
TurboIssue issueToGet = issues.get(issueId);
if (issueToGet != null) {
return issueToGet.getMetadata().getEvents();
}
// Fail silently
return new ArrayList<>();
}
protected List<Comment> getComments(int issueId) {
TurboIssue issueToGet = issues.get(issueId);
if (issueToGet != null) {
return issueToGet.getMetadata().getComments();
}
// Fail silently
return new ArrayList<>();
}
// UpdateEvent methods to directly mutate the repo state
protected void makeNewIssue() {
TurboIssue toAdd = makeDummyIssue();
issues.put(toAdd.getId(), toAdd);
updatedIssues.put(toAdd.getId(), toAdd);
}
protected void makeNewLabel() {
TurboLabel toAdd = makeDummyLabel();
labels.put(toAdd.getActualName(), toAdd);
updatedLabels.put(toAdd.getActualName(), toAdd);
}
protected void makeNewMilestone() {
TurboMilestone toAdd = makeDummyMilestone();
milestones.put(toAdd.getId(), toAdd);
updatedMilestones.put(toAdd.getId(), toAdd);
}
protected void makeNewUser() {
TurboUser toAdd = makeDummyUser();
users.put(toAdd.getLoginName(), toAdd);
updatedUsers.put(toAdd.getLoginName(), toAdd);
}
// Only updating of issues and milestones is possible. Labels and users are immutable.
protected TurboIssue updateIssue(int itemId, String updateText) {
TurboIssue issueToUpdate = issues.get(itemId);
if (issueToUpdate != null) {
return renameIssue(issueToUpdate, updateText);
}
return null;
}
private TurboIssue renameIssue(TurboIssue issueToUpdate, String updateText) {
// Not allowed to mutate issueToUpdate itself as it introduces immediate changes in the GUI.
TurboIssue updatedIssue = new TurboIssue(issueToUpdate);
updatedIssue.setTitle(updateText);
// Add renamed event to events list of issue
List<TurboIssueEvent> eventsOfIssue = updatedIssue.getMetadata().getEvents();
// Not deep copy as the same TurboIssueEvent objects of issueToUpdate are the TurboIssueEvents
// of updatedIssue. Might create problems later if eventsOfIssue are to be mutable after downloading
// from repo (which should not be the case).
// (but this approach works if the metadata of the issue is not modified, which is the current case)
// TODO make TurboIssueEvent immutable
eventsOfIssue.add(new TurboIssueEvent(new User().setLogin("test"),
IssueEventType.Renamed,
new Date()));
List<Comment> commentsOfIssue = updatedIssue.getMetadata().getComments();
updatedIssue.setMetadata(new IssueMetadata(eventsOfIssue, commentsOfIssue));
updatedIssue.setUpdatedAt(LocalDateTime.now());
// Add to list of updated issues, and replace issueToUpdate in main issues store.
updatedIssues.put(updatedIssue.getId(), updatedIssue);
issues.put(updatedIssue.getId(), updatedIssue);
return issueToUpdate;
}
protected TurboMilestone updateMilestone(int itemId, String updateText) {
TurboMilestone milestoneToUpdate = milestones.get(itemId);
if (milestoneToUpdate != null) {
return renameMilestone(milestoneToUpdate, updateText);
}
return null;
}
private TurboMilestone renameMilestone(TurboMilestone milestoneToUpdate, String updateText) {
// Similarly to renameIssue, to avoid immediate update of the GUI when we update
// the milestone, milestoneToUpdate is not to be mutated.
TurboMilestone updatedMilestone = new TurboMilestone(milestoneToUpdate);
updatedMilestone.setTitle(updateText);
updatedMilestones.put(updatedMilestone.getId(), updatedMilestone);
milestones.put(updatedMilestone.getId(), updatedMilestone);
return milestoneToUpdate;
}
protected TurboIssue deleteIssue(int itemId) {
updatedIssues.remove(itemId);
return issues.remove(itemId);
}
protected TurboLabel deleteLabel(String idString) {
updatedLabels.remove(idString);
return labels.remove(idString);
}
protected TurboMilestone deleteMilestone(int itemId) {
updatedMilestones.remove(itemId);
return milestones.remove(itemId);
}
protected TurboUser deleteUser(String idString) {
updatedUsers.remove(idString);
return users.remove(idString);
}
protected List<Label> setLabels(int issueId, List<String> labels) {
TurboIssue toSet = new TurboIssue(issues.get(issueId));
// Update issue events
List<TurboIssueEvent> eventsOfIssue = toSet.getMetadata().getEvents();
// TODO change to expression lambdas
List<String> labelsOfIssue = toSet.getLabels();
labelsOfIssue.forEach(labelName ->
eventsOfIssue.add(new TurboIssueEvent(new User().setLogin("test"),
IssueEventType.Unlabeled,
new Date()).setLabelName(labelName))
);
labels.forEach(labelName ->
eventsOfIssue.add(new TurboIssueEvent(new User().setLogin("test"),
IssueEventType.Labeled,
new Date()).setLabelName(labelName))
);
List<Comment> commentsOfIssue = toSet.getMetadata().getComments();
toSet.setMetadata(new IssueMetadata(eventsOfIssue, commentsOfIssue));
toSet.setUpdatedAt(LocalDateTime.now());
// Actually setting label is done after updating issue events
toSet.setLabels(labels);
// Then update the relevant state arrays to reflect changes in UI
issues.put(issueId, toSet);
updatedIssues.put(issueId, toSet);
return labels.stream().map(new Label()::setName).collect(Collectors.toList());
}
}
|
package co.bugg.quickplay.gui;
import co.bugg.quickplay.QuickPlay;
import co.bugg.quickplay.Reference;
import net.minecraft.util.ResourceLocation;
import java.util.LinkedHashMap;
/**
* Hardcoded in all gamemodes along with which game they use in the icons files
* This should be the only file that needs modification to add/remove new buttons
* (With the exception of the GUI image files, of course)
*/
public class Icons {
/**
* How wide and how tall each game are. I don't recommend changing this.
*/
public static int iconWidth = 64;
public static int iconHeight = 64;
public static LinkedHashMap<String, String> arcadeCommands = new LinkedHashMap<>();
static {
arcadeCommands.put("Mini Walls", "arcade_mini_walls");
arcadeCommands.put("Football", "arcade_soccer");
}
public static final Game ARCADE = new Game("Arcade",1,0,0, 0, "arcade", arcadeCommands);
public static LinkedHashMap<String, String> bedwarsCommands = new LinkedHashMap<>();
static {
bedwarsCommands.put("Solo", "bedwars_eight_one");
bedwarsCommands.put("Doubles", "bedwars_eight_two");
bedwarsCommands.put("3v3v3v3", "bedwars_four_three");
bedwarsCommands.put("4v4v4v4", "bedwars_four_four");
}
public static final Game BEDWARS = new Game("Bed Wars",1, 64, 0, 1, "bedwars", bedwarsCommands);
public static final Game LEGACY = new Game("Classic",1,128, 0, 2, "classic", null);
public static LinkedHashMap<String, String> true_combatCommands = new LinkedHashMap<>();
static {
true_combatCommands.put("Solo", "crazy_walls_solo");
true_combatCommands.put("Teams", "crazy_walls_team");
}
public static final Game TRUE_COMBAT = new Game("Crazy Walls",1, 192, 0, 3, "crazy", true_combatCommands);
public static final Game MCGO = new Game("Cops and Crims",1,0, 64, 4, "cvc", null);
// Housing is a special case. "Home" will be recognized as the lobby name and it'll assign the appropriate command.
public static final Game HOUSING = new Game("Housing",1, 64, 64, 5, "home", null);
public static final Game WALLS3 = new Game("Mega Walls",1,128, 64, 6, "megawalls", null);
public static LinkedHashMap<String, String> prototypeCommands = new LinkedHashMap<>();
static {
prototypeCommands.put("Murder Mystery", "prototype_murder_mystery");
prototypeCommands.put("Duels - Classic", "prototype_duels:classic_duel");
prototypeCommands.put("Duels - Bow", "prototype_duels:bow_duel");
prototypeCommands.put("Duels - Potion", "prototype_duels:potion_duel");
prototypeCommands.put("Duels - OP", "prototype_duels:op_duel");
prototypeCommands.put("Duels - MW 1v1", "prototype_duels:mw_duel");
prototypeCommands.put("Duels - MW 2v2", "prototype_duels:mw_doubles");
prototypeCommands.put("Duels - MW 4v4", "prototype_duels:mw_four");
prototypeCommands.put("Duels - UHC 1v1", "prototype_duels:uhc_duel");
prototypeCommands.put("Duels - UHC 2v2", "prototype_duels:uhc_doubles");
prototypeCommands.put("Duels - UHC 4v4", "prototype_duels:uhc_four");
prototypeCommands.put("Zombies - Story (Normal)", "prototype_zombies_story_normal");
prototypeCommands.put("Zombies - Story (Hard)", "prototype_zombies_story_hard");
prototypeCommands.put("Zombies - Story (RIP)", "prototype_zombies_story_rip");
prototypeCommands.put("Zombies - Endless (Normal)", "prototype_zombies_endless_normal");
prototypeCommands.put("Zombies - Endless (Hard)", "prototype_zombies_endless_hard");
prototypeCommands.put("Zombies - Endless (RIP)", "prototype_zombies_endless_rip");
}
public static final Game PROTOTYPE = new Game("Prototype",1,192, 64, 7, "prototype", prototypeCommands);
public static LinkedHashMap<String, String> survival_gamesCommands = new LinkedHashMap<>();
static {
survival_gamesCommands.put("Solo", "blitz_solo_normal");
survival_gamesCommands.put("Teams", "blitz_teams_normal");
survival_gamesCommands.put("No Kits", "blitz_solo_nokits");
}
public static final Game SURVIVAL_GAMES = new Game("Blitz SG",1,0, 128, 8, "blitz", survival_gamesCommands);
public static LinkedHashMap<String, String> skyclashCommands = new LinkedHashMap<>();
static {
skyclashCommands.put("Solo", "skyclash_solo");
skyclashCommands.put("Doubles", "skyclash_doubles");
skyclashCommands.put("Team War", "skyclash_team_war");
}
public static final Game SKYCLASH = new Game("SkyClash",1,64, 128,9, "skyclash", skyclashCommands);
public static LinkedHashMap<String, String> skywarsCommands = new LinkedHashMap<>();
static {
skywarsCommands.put("Solo Normal", "solo_normal");
skywarsCommands.put("Solo Insane", "solo_insane");
skywarsCommands.put("Teams Normal", "teams_normal");
skywarsCommands.put("Teams Insane", "teams_insane");
skywarsCommands.put("Ranked", "ranked_normal");
skywarsCommands.put("Mega", "mega_normal");
skywarsCommands.put("Solo TNT Madness", "solo_insane_tnt_madness");
skywarsCommands.put("Solo Rush", "solo_insane_rush");
skywarsCommands.put("Solo Slime", "solo_insane_slime");
skywarsCommands.put("Teams TNT Madness", "teams_insane_tnt_madness");
skywarsCommands.put("Teams Rush", "teams_insane_rush");
skywarsCommands.put("Teams Slime", "teams_insane_slime");
}
public static final Game SKYWARS = new Game("SkyWars",1,128, 128, 10, "skywars", skywarsCommands);
public static LinkedHashMap<String, String> super_smashCommands = new LinkedHashMap<>();
static {
super_smashCommands.put("Solo", "super_smash_solo_normal");
super_smashCommands.put("Teams", "super_smash_teams_normal");
super_smashCommands.put("Friends", "super_smash_friends_normal");
}
public static final Game SUPER_SMASH = new Game("Smash Heroes",1,192, 128,11, "smash", super_smashCommands);
public static LinkedHashMap<String, String> speed_uhcCommands = new LinkedHashMap<>();
static {
speed_uhcCommands.put("Solo Normal", "speed_solo_normal");
speed_uhcCommands.put("Solo Insane", "speed_solo_insane");
speed_uhcCommands.put("Teams Normal", "speed_team_normal");
speed_uhcCommands.put("Teams Insane", "speed_team_insane");
}
public static final Game SPEED_UHC = new Game("Speed UHC",1,0, 192,12, "speeduhc", speed_uhcCommands);
public static LinkedHashMap<String, String> tntgamesCommands = new LinkedHashMap<>();
static {
tntgamesCommands.put("TNT Run", "tnt_tntrun");
tntgamesCommands.put("PVP Run", "tnt_pvprun");
tntgamesCommands.put("Bow Spleef", "tnt_bowspleef");
tntgamesCommands.put("TNT Tag", "tnt_tnttag");
tntgamesCommands.put("TNT Wizards", "tnt_capture");
}
public static final Game TNTGAMES = new Game("TNT Games",1, 64, 192, 13, "tnt", tntgamesCommands);
public static final Game UHC = new Game("UHC Champions",1,128, 192, 14, "uhc", null);
public static final Game BATTLEGROUND = new Game("Warlords",1, 192, 192, 15, "warlords", null);
public static LinkedHashMap<Integer, Game> map = new LinkedHashMap<>();
static {
map.put(ARCADE.buttonID, ARCADE);
map.put(BEDWARS.buttonID, BEDWARS);
map.put(LEGACY.buttonID, LEGACY);
map.put(TRUE_COMBAT.buttonID, TRUE_COMBAT);
map.put(MCGO.buttonID, MCGO);
map.put(HOUSING.buttonID, HOUSING);
map.put(WALLS3.buttonID, WALLS3);
map.put(PROTOTYPE.buttonID, PROTOTYPE);
map.put(SURVIVAL_GAMES.buttonID, SURVIVAL_GAMES);
map.put(SKYCLASH.buttonID, SKYCLASH);
map.put(SKYWARS.buttonID, SKYWARS);
map.put(SUPER_SMASH.buttonID, SUPER_SMASH);
map.put(SPEED_UHC.buttonID, SPEED_UHC);
map.put(TNTGAMES.buttonID, TNTGAMES);
map.put(UHC.buttonID, UHC);
map.put(BATTLEGROUND.buttonID, BATTLEGROUND);
}
/**
* Registers all GUI files with the mod by adding them to a HashMap.
* fileID provided in the Game constructor corresponds to the Integer provided
* when registering a file here.
*
* Called at preInit
*/
public static void registerFiles() {
QuickPlay.icons.put(1, new ResourceLocation(Reference.MOD_ID, "textures/gui/game-icons1.png"));
}
}
|
package co.yiiu.config;
import co.yiiu.web.interceptor.AdminInterceptor;
import co.yiiu.web.interceptor.CommonInterceptor;
import co.yiiu.web.interceptor.UserInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Autowired
private CommonInterceptor commonInterceptor;
@Autowired
private UserInterceptor userInterceptor;
@Autowired
private AdminInterceptor adminInterceptor;
@Autowired
private SiteConfig siteConfig;
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseSuffixPatternMatch(false);
}
/**
* Add intercepter
*
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(commonInterceptor)
"/topic/*/edit",
"/collect/*/add",
"/collect/*/delete",
|
package com.alibaba.ttl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.Collections;
/**
* {@link TtlRunnable} decorate {@link Runnable}, so as to get {@link TransmittableThreadLocal}
* and transmit it to the time of {@link Runnable} execution, needed when use {@link Runnable} to thread pool.
* <p>
* Use factory methods {@link #get} / {@link #gets} to create instance.
*
* @author Jerry Lee (oldratlee at gmail dot com)
* @see java.util.concurrent.Executor
* @see java.util.concurrent.ExecutorService
* @see java.util.concurrent.ThreadPoolExecutor
* @see java.util.concurrent.ScheduledThreadPoolExecutor
* @see java.util.concurrent.Executors
* @since 0.9.0
*/
public final class TtlRunnable implements Runnable {
private final AtomicReference<Map<TransmittableThreadLocal<?>, Object>> copiedRef;
private final Runnable runnable;
private final boolean releaseTtlValueReferenceAfterRun;
private TtlRunnable(Runnable runnable, boolean releaseTtlValueReferenceAfterRun) {
this.copiedRef = new AtomicReference<Map<TransmittableThreadLocal<?>, Object>>(TransmittableThreadLocal.copy());
this.runnable = runnable;
this.releaseTtlValueReferenceAfterRun = releaseTtlValueReferenceAfterRun;
}
/**
* wrap method {@link Runnable#run()}.
*/
@Override
public void run() {
Map<TransmittableThreadLocal<?>, Object> copied = copiedRef.get();
if (copied == null || releaseTtlValueReferenceAfterRun && !copiedRef.compareAndSet(copied, null)) {
throw new IllegalStateException("TTL value reference is released after run!");
}
Map<TransmittableThreadLocal<?>, Object> backup = TransmittableThreadLocal.backupAndSetToCopied(copied);
try {
runnable.run();
} finally {
TransmittableThreadLocal.restoreBackup(backup);
}
}
/**
* return original/unwrapped {@link Runnable}.
*/
public Runnable getRunnable() {
return runnable;
}
public static TtlRunnable get(Runnable runnable) {
return get(runnable, false, false);
}
public static TtlRunnable get(Runnable runnable, boolean releaseTtlValueReferenceAfterRun) {
return get(runnable, releaseTtlValueReferenceAfterRun, false);
}
public static TtlRunnable get(Runnable runnable, boolean releaseTtlValueReferenceAfterRun, boolean idempotent) {
if (null == runnable) {
return null;
}
if (runnable instanceof TtlRunnable) {
if (idempotent) {
// avoid redundant decoration, and ensure idempotency
return (TtlRunnable) runnable;
} else {
throw new IllegalStateException("Already TtlRunnable!");
}
}
return new TtlRunnable(runnable, releaseTtlValueReferenceAfterRun);
}
public static List<TtlRunnable> gets(Collection<? extends Runnable> tasks) {
return gets(tasks, false, false);
}
public static List<TtlRunnable> gets(Collection<? extends Runnable> tasks, boolean releaseTtlValueReferenceAfterRun) {
return gets(tasks, releaseTtlValueReferenceAfterRun, false);
}
public static List<TtlRunnable> gets(Collection<? extends Runnable> tasks, boolean releaseTtlValueReferenceAfterRun, boolean idempotent) {
if (null == tasks) {
return Collections.emptyList();
}
List<TtlRunnable> copy = new ArrayList<TtlRunnable>();
for (Runnable task : tasks) {
copy.add(TtlRunnable.get(task, releaseTtlValueReferenceAfterRun, idempotent));
}
return copy;
}
}
|
package com.astrazeneca.seq2c;
import org.apache.commons.cli.*;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public class Seq2c {
public static void main(String[] args) throws Exception {
CommandLine cmd = new BasicParser().parse(buildCmdOptions(), args);
String[] cmdArgs = cmd.getArgs();
String sam2bamFile = cmdArgs[0];
final String bedFile = cmdArgs[1];
final String covFile = cmdArgs[2];
String control = "";
if (cmdArgs.length > 3) {
control = cmdArgs[3];
}
Dispatcher.init(getThreadsCount(cmd));
try {
final Map<String, String> sam2bam = Bam2Reads.parseFile(sam2bamFile);
final Collection<Gene> sqrlist = new ArrayList<>();
boolean rewrite = false;
for (final Map.Entry<String, String> entry : sam2bam.entrySet()) {
Seq2cov sec2cov = new Seq2cov(bedFile, entry.getValue(), entry.getKey());
Collection<Gene> cov = sec2cov.process();
//print coverage to the file
printCoverage(cov, covFile, rewrite);
rewrite = true;
sqrlist.addAll(cov);
}
Map<String, Long> stat = Bam2Reads.printStatsToFile(sam2bamFile);
Cov2lr cov2lr = new Cov2lr(true, stat, sqrlist, control);
List<Sample> cov = cov2lr.doWork();
Lr2gene lr2gene = new Lr2gene(cov);
lr2gene.init(cmd);
lr2gene.setUseControl(cov2lr.isUseControlSamples());
lr2gene.process();
} finally {
Dispatcher.shutdown();
}
}
private static void printCoverage(Collection<Gene> sqrlist, String covFile, boolean rewrite) {
try (FileWriter writer = new FileWriter(covFile, rewrite)) {
writer.write("Sample\tGene\tChr\tStart\tEnd\tTag\tLength\tMeanDepth\n");
writer.flush();
for (Gene gene : sqrlist) {
StringBuilder str = new StringBuilder();
str.append(gene.getSample()).append("\t");
str.append(gene.getName()).append("\t");
str.append(gene.getChr()).append("\t");
str.append(gene.getStart()).append("\t");
str.append(gene.getEnd()).append("\t");
str.append(gene.getTag()).append("\t");
str.append(gene.getLen()).append("\t");
str.append(String.format("%.2f", gene.getDepth())).append("\n");
writer.write(str.toString());
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static Options buildCmdOptions() {
Options options = Lr2gene.getOptions();
options.addOption(OptionBuilder.withArgName("number of threads")
.hasOptionalArg()
.withType(Number.class)
.isRequired(false)
.create("i"));
return options;
}
private static int getThreadsCount(CommandLine cmd) throws ParseException {
int threads = 0;
if (cmd.hasOption("i")) {
Object value = cmd.getParsedOptionValue("i");
if (value == null) {
threads = Runtime.getRuntime().availableProcessors();
} else {
threads = ((Number)value).intValue();
}
}
return threads;
}
}
|
package com.conveyal.gtfs;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;
import com.google.common.util.concurrent.ExecutionError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import java.util.zip.ZipFile;
/**
* Fast cache for GTFS feeds stored on S3.
*/
public class GTFSCache {
private static final Logger LOG = LoggerFactory.getLogger(GTFSCache.class);
public final String bucket;
public final String bucketFolder;
public final File cacheDir;
private static final AmazonS3 s3 = new AmazonS3Client();
RemovalListener<String, GTFSFeed> removalListener = new RemovalListener<String, GTFSFeed>() {
@Override
public void onRemoval(RemovalNotification<String, GTFSFeed> removalNotification) {
// delete local files only if using s3
if (bucket != null) {
String id = removalNotification.getKey();
String[] extensions = {".db", ".db.p", ".zip"};
// delete local cache files (including zip) when feed removed from cache
for (String type : extensions) {
File file = new File(cacheDir, id + type);
file.delete();
}
}
}
};
private LoadingCache<String, GTFSFeed> cache = CacheBuilder.newBuilder()
.maximumSize(10)
.removalListener(removalListener)
.build(new CacheLoader<String, GTFSFeed>() {
@Override
public GTFSFeed load(String s) throws Exception {
return retrieveFeed(s);
}
});
/** If bucket is null, work offline and do not use S3 */
public GTFSCache(String bucket, File cacheDir) {
if (bucket == null) LOG.info("No bucket specified; GTFS Cache will run locally");
else LOG.info("Using bucket {} for GTFS Cache", bucket);
this.bucket = bucket;
this.bucketFolder = null;
this.cacheDir = cacheDir;
}
public GTFSCache(String bucket, String bucketFolder, File cacheDir) {
if (bucket == null) LOG.info("No bucket specified; GTFS Cache will run locally");
else LOG.info("Using bucket {} for GTFS Cache", bucket);
this.bucket = bucket;
this.bucketFolder = bucketFolder != null ? bucketFolder.replaceAll("\\/","") : null;
this.cacheDir = cacheDir;
}
/**
* Add a GTFS feed to this cache with the given ID. NB this is not the feed ID, because feed IDs are not
* unique when you load multiple versions of the same feed.
*/
public GTFSFeed put (String id, File feedFile) throws Exception {
return put(id, feedFile, null);
}
/** Add a GTFS feed to this cache where the ID is calculated from the feed itself */
public GTFSFeed put (Function<GTFSFeed, String> idGenerator, File feedFile) throws Exception {
return put(null, feedFile, idGenerator);
}
private GTFSFeed put (String id, File feedFile, Function<GTFSFeed, String> idGenerator) throws Exception {
// generate temporary ID to name files
String tempId = id != null ? id : UUID.randomUUID().toString();
// read the feed
String cleanTempId = cleanId(tempId);
File dbFile = new File(cacheDir, cleanTempId + ".db");
File movedFeedFile = new File(cacheDir, cleanTempId + ".zip");
// don't copy if we're loading from a locally-cached feed
if (!feedFile.equals(movedFeedFile)) Files.copy(feedFile, movedFeedFile);
GTFSFeed feed = new GTFSFeed(dbFile.getAbsolutePath());
feed.loadFromFile(new ZipFile(movedFeedFile));
feed.findPatterns();
if (idGenerator != null) id = idGenerator.apply(feed);
String cleanId = cleanId(id);
feed.close(); // make sure everything is written to disk
if (idGenerator != null) {
new File(cacheDir, cleanTempId + ".zip").renameTo(new File(cacheDir, cleanId + ".zip"));
new File(cacheDir, cleanTempId + ".db").renameTo(new File(cacheDir, cleanId + ".db"));
new File(cacheDir, cleanTempId + ".db.p").renameTo(new File(cacheDir, cleanId + ".db.p"));
}
// upload feed
// TODO best way to do this? Should we zip the files together?
if (bucket != null) {
LOG.info("Writing feed to s3 cache");
String key = bucketFolder != null ? String.join("/", bucketFolder, cleanId) : cleanId;
// write zip to s3 if not already there
if (!s3.doesObjectExist(bucket, key + ".zip")) {
s3.putObject(bucket, key + ".zip", feedFile);
LOG.info("Zip file written.");
}
else {
LOG.info("Zip file already exists on s3.");
}
s3.putObject(bucket, key + ".db", new File(cacheDir, cleanId + ".db"));
s3.putObject(bucket, key + ".db.p", new File(cacheDir, cleanId + ".db.p"));
LOG.info("db files written.");
}
// reconnect to feed database
feed = new GTFSFeed(new File(cacheDir, cleanId + ".db").getAbsolutePath());
cache.put(id, feed);
return feed;
}
public GTFSFeed get (String id) {
try {
return cache.get(id);
} catch (ExecutionException e) {
LOG.info("Error loading local MapDB.", e);
deleteLocalDBFiles(id);
return null;
}
}
public boolean containsId (String id) {
GTFSFeed feed = null;
try {
feed = cache.get(id);
} catch (Exception e) {
return false;
}
return feed != null;
}
/** retrieve a feed from local cache or S3 */
private GTFSFeed retrieveFeed (String originalId) {
// see if we have it cached locally
String id = cleanId(originalId);
String key = bucketFolder != null ? String.join("/", bucketFolder, id) : id;
File dbFile = new File(cacheDir, id + ".db");
if (dbFile.exists()) {
LOG.info("Processed GTFS was found cached locally");
try {
return new GTFSFeed(dbFile.getAbsolutePath());
} catch (Exception e) {
LOG.info("Error loading local MapDB.", e);
deleteLocalDBFiles(id);
}
}
if (bucket != null) {
try {
LOG.info("Attempting to download cached GTFS MapDB.");
S3Object db = s3.getObject(bucket, key + ".db");
InputStream is = db.getObjectContent();
FileOutputStream fos = new FileOutputStream(dbFile);
ByteStreams.copy(is, fos);
is.close();
fos.close();
S3Object dbp = s3.getObject(bucket, key + ".db.p");
InputStream isp = dbp.getObjectContent();
FileOutputStream fosp = new FileOutputStream(new File(cacheDir, id + ".db.p"));
ByteStreams.copy(isp, fosp);
isp.close();
fosp.close();
LOG.info("Returning processed GTFS from S3");
return new GTFSFeed(dbFile.getAbsolutePath());
} catch (AmazonServiceException | IOException e) {
LOG.info("Error retrieving MapDB from S3, will load from original GTFS.", e);
}
}
// see if the
// if we fell through to here, getting the mapdb was unsuccessful
// grab GTFS from S3 if it is not found locally
LOG.info("Loading feed from local cache directory...");
File feedFile = new File(cacheDir, id + ".zip");
if (!feedFile.exists() && bucket != null) {
LOG.info("Feed not found locally, downloading from S3.");
try {
S3Object gtfs = s3.getObject(bucket, key + ".zip");
InputStream is = gtfs.getObjectContent();
FileOutputStream fos = new FileOutputStream(feedFile);
ByteStreams.copy(is, fos);
is.close();
fos.close();
} catch (Exception e) {
LOG.warn("Could not download feed at s3://{}/{}.", bucket, key);
throw new RuntimeException(e);
}
}
if (feedFile.exists()) {
// TODO this will also re-upload the original feed ZIP to S3.
try {
return put(originalId, feedFile);
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
throw new NoSuchElementException(originalId);
}
}
private void deleteLocalDBFiles(String id) {
String[] extensions = {".db", ".db.p"};
// delete ONLY local cache db files
for (String type : extensions) {
File file = new File(cacheDir, id + type);
file.delete();
}
}
public static String cleanId(String id) {
// replace all special characters with `-`, except for underscore `_`
return id.replaceAll("[^A-Za-z0-9_]", "-");
}
}
|
package com.couchbase.lite;
import com.couchbase.lite.internal.RevisionInternal;
import com.couchbase.lite.internal.InterfaceAudience;
import com.couchbase.lite.util.Log;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A CouchbaseLite document.
*/
public final class Document {
/**
* The document's owning database.
*/
private Database database;
/**
* The document's ID.
*/
private String documentId;
/**
* The current/latest revision. This object is cached.
*/
private SavedRevision currentRevision;
/**
* Change Listeners
*/
private List<ChangeListener> changeListeners = new ArrayList<ChangeListener>();
/**
* Constructor
*
* @param database The document's owning database
* @param documentId The document's ID
* @exclude
*/
@InterfaceAudience.Private
public Document(Database database, String documentId) {
this.database = database;
this.documentId = documentId;
}
/**
* Get the document's owning database.
*/
@InterfaceAudience.Public
public Database getDatabase() {
return database;
}
/**
* Get the document's ID
*/
@InterfaceAudience.Public
public String getId() {
return documentId;
}
/**
* Is this document deleted? (That is, does its current revision have the '_deleted' property?)
* @return boolean to indicate whether deleted or not
*/
@InterfaceAudience.Public
public boolean isDeleted() {
try {
return getCurrentRevision() == null && getLeafRevisions().size() > 0;
} catch (CouchbaseLiteException e) {
throw new RuntimeException(e);
}
}
/**
* Get the ID of the current revision
*/
@InterfaceAudience.Public
public String getCurrentRevisionId() {
SavedRevision rev = getCurrentRevision();
if(rev == null){
return null;
}
return rev.getId();
}
/**
* Get the current revision
*/
@InterfaceAudience.Public
public SavedRevision getCurrentRevision() {
if (currentRevision == null) {
currentRevision = getRevisionWithId(null);
}
return currentRevision;
}
/**
* Returns the document's history as an array of CBLRevisions. (See SavedRevision's method.)
*
* @return document's history
* @throws CouchbaseLiteException
*/
@InterfaceAudience.Public
public List<SavedRevision> getRevisionHistory() throws CouchbaseLiteException {
if (getCurrentRevision() == null) {
Log.w(Database.TAG, "getRevisionHistory() called but no currentRevision");
return null;
}
return getCurrentRevision().getRevisionHistory();
}
/**
* Returns all the current conflicting revisions of the document. If the document is not
* in conflict, only the single current revision will be returned.
*
* @return all current conflicting revisions of the document
* @throws CouchbaseLiteException
*/
@InterfaceAudience.Public
public List<SavedRevision> getConflictingRevisions() throws CouchbaseLiteException {
return getLeafRevisions(false);
}
/**
* Returns all the leaf revisions in the document's revision tree,
* including deleted revisions (i.e. previously-resolved conflicts.)
*
* @return all the leaf revisions in the document's revision tree
* @throws CouchbaseLiteException
*/
@InterfaceAudience.Public
public List<SavedRevision> getLeafRevisions() throws CouchbaseLiteException {
return getLeafRevisions(true);
}
/**
* The contents of the current revision of the document.
* This is shorthand for self.currentRevision.properties.
* Any keys in the dictionary that begin with "_", such as "_id" and "_rev", contain CouchbaseLite metadata.
*
* @return contents of the current revision of the document.
*/
@InterfaceAudience.Public
public Map<String,Object> getProperties() {
return getCurrentRevision().getProperties();
}
/**
* The user-defined properties, without the ones reserved by CouchDB.
* This is based on -properties, with every key whose name starts with "_" removed.
*
* @return user-defined properties, without the ones reserved by CouchDB.
*/
@InterfaceAudience.Public
public Map<String,Object> getUserProperties() {
return getCurrentRevision().getUserProperties();
}
/**
* Deletes this document by adding a deletion revision.
* This will be replicated to other databases.
*
* @return boolean to indicate whether deleted or not
* @throws CouchbaseLiteException
*/
@InterfaceAudience.Public
public boolean delete() throws CouchbaseLiteException {
return getCurrentRevision().deleteDocument() != null;
}
/**
* Purges this document from the database; this is more than deletion, it forgets entirely about it.
* The purge will NOT be replicated to other databases.
*
* @throws CouchbaseLiteException
*/
@InterfaceAudience.Public
public void purge() throws CouchbaseLiteException {
Map<String, List<String>> docsToRevs = new HashMap<String, List<String>>();
List<String> revs = new ArrayList<String>();
revs.add("*");
docsToRevs.put(documentId, revs);
database.purgeRevisions(docsToRevs);
database.removeDocumentFromCache(this);
}
/**
* The revision with the specified ID.
*
*
* @param id the revision ID
* @return the SavedRevision object
*/
@InterfaceAudience.Public
public SavedRevision getRevision(String id) {
if (currentRevision != null && id.equals(currentRevision.getId())) {
return currentRevision;
}
EnumSet<Database.TDContentOptions> contentOptions = EnumSet.noneOf(Database.TDContentOptions.class);
RevisionInternal revisionInternal = database.getDocumentWithIDAndRev(getId(), id, contentOptions);
SavedRevision revision = null;
revision = getRevisionFromRev(revisionInternal);
return revision;
}
/**
* Creates an unsaved new revision whose parent is the currentRevision,
* or which will be the first revision if the document doesn't exist yet.
* You can modify this revision's properties and attachments, then save it.
* No change is made to the database until/unless you save the new revision.
*
* @return the newly created revision
*/
@InterfaceAudience.Public
public UnsavedRevision createRevision() {
return new UnsavedRevision(this, getCurrentRevision());
}
/**
* Shorthand for getProperties().get(key)
*/
@InterfaceAudience.Public
public Object getProperty(String key) {
if (getCurrentRevision().getProperties().containsKey(key)){
return getCurrentRevision().getProperties().get(key);
}
return null;
}
/**
* Saves a new revision. The properties dictionary must have a "_rev" property
* whose ID matches the current revision's (as it will if it's a modified
* copy of this document's .properties property.)
*
* @param properties the contents to be saved in the new revision
* @return a new SavedRevision
*/
@InterfaceAudience.Public
public SavedRevision putProperties(Map<String,Object> properties) throws CouchbaseLiteException {
String prevID = (String) properties.get("_rev");
boolean allowConflict = false;
return putProperties(properties, prevID, allowConflict);
}
/**
* Saves a new revision by letting the caller update the existing properties.
* This method handles conflicts by retrying (calling the block again).
* The DocumentUpdater implementation should modify the properties of the new revision and return YES to save or
* NO to cancel. Be careful: the DocumentUpdater can be called multiple times if there is a conflict!
*
* @param updater the callback DocumentUpdater implementation. Will be called on each
* attempt to save. Should update the given revision's properties and then
* return YES, or just return NO to cancel.
* @return The new saved revision, or null on error or cancellation.
* @throws CouchbaseLiteException
*/
@InterfaceAudience.Public
public SavedRevision update(DocumentUpdater updater) throws CouchbaseLiteException {
int lastErrorCode = Status.UNKNOWN;
do {
UnsavedRevision newRev = createRevision();
if (updater.update(newRev) == false) {
break;
}
try {
SavedRevision savedRev = newRev.save();
if (savedRev != null) {
return savedRev;
}
} catch (CouchbaseLiteException e) {
lastErrorCode = e.getCBLStatus().getCode();
}
} while (lastErrorCode == Status.CONFLICT);
return null;
}
@InterfaceAudience.Public
public void addChangeListener(ChangeListener changeListener) {
changeListeners.add(changeListener);
}
@InterfaceAudience.Public
public void removeChangeListener(ChangeListener changeListener) {
changeListeners.remove(changeListener);
}
/**
* A delegate that can be used to update a Document.
*/
@InterfaceAudience.Public
public static interface DocumentUpdater {
public boolean update(UnsavedRevision newRevision);
}
/**
* The type of event raised when a Document changes. This event is not raised in response
* to local Document changes.
*/
@InterfaceAudience.Public
public static class ChangeEvent {
private Document source;
private DocumentChange change;
public ChangeEvent(Document source, DocumentChange documentChange) {
this.source = source;
this.change = documentChange;
}
public Document getSource() {
return source;
}
public DocumentChange getChange() {
return change;
}
}
/**
* A delegate that can be used to listen for Document changes.
*/
@InterfaceAudience.Public
public static interface ChangeListener {
public void changed(ChangeEvent event);
}
/**
* Get the document's abbreviated ID
* @exclude
*/
@InterfaceAudience.Private
public String getAbbreviatedId() {
String abbreviated = documentId;
if (documentId.length() > 10) {
String firstFourChars = documentId.substring(0, 4);
String lastFourChars = documentId.substring(abbreviated.length() - 4);
return String.format("%s..%s", firstFourChars, lastFourChars);
}
return documentId;
}
/**
* @exclude
*/
@InterfaceAudience.Private
/* package */ List<SavedRevision> getLeafRevisions(boolean includeDeleted) throws CouchbaseLiteException {
List<SavedRevision> result = new ArrayList<SavedRevision>();
RevisionList revs = database.getAllRevisionsOfDocumentID(documentId, true);
for (RevisionInternal rev : revs) {
// add it to result, unless we are not supposed to include deleted and it's deleted
if (!includeDeleted && rev.isDeleted()) {
// don't add it
}
else {
result.add(getRevisionFromRev(rev));
}
}
return Collections.unmodifiableList(result);
}
/**
* @exclude
*/
@InterfaceAudience.Private
/* package */ SavedRevision putProperties(Map<String, Object> properties, String prevID, boolean allowConflict) throws CouchbaseLiteException {
String newId = null;
if (properties != null && properties.containsKey("_id")) {
newId = (String) properties.get("_id");
}
if (newId != null && !newId.equalsIgnoreCase(getId())) {
Log.w(Database.TAG, "Trying to put wrong _id to this: %s properties: %s", this, properties);
}
// Process _attachments dict, converting CBLAttachments to dicts:
Map<String, Object> attachments = null;
if (properties != null && properties.containsKey("_attachments")) {
attachments = (Map<String, Object>) properties.get("_attachments");
}
if (attachments != null && attachments.size() > 0) {
Map<String, Object> updatedAttachments = Attachment.installAttachmentBodies(attachments, database);
properties.put("_attachments", updatedAttachments);
}
boolean hasTrueDeletedProperty = false;
if (properties != null) {
hasTrueDeletedProperty = properties.get("_deleted") != null && ((Boolean)properties.get("_deleted")).booleanValue();
}
boolean deleted = (properties == null) || hasTrueDeletedProperty;
RevisionInternal rev = new RevisionInternal(documentId, null, deleted, database);
if (properties != null) {
rev.setProperties(properties);
}
RevisionInternal newRev = database.putRevision(rev, prevID, allowConflict);
if (newRev == null) {
return null;
}
return new SavedRevision(this, newRev);
}
/**
* @exclude
*/
@InterfaceAudience.Private
/* package */ SavedRevision getRevisionFromRev(RevisionInternal internalRevision) {
if (internalRevision == null) {
return null;
}
else if (currentRevision != null && internalRevision.getRevId().equals(currentRevision.getId())) {
return currentRevision;
}
else {
return new SavedRevision(this, internalRevision);
}
}
/**
* @exclude
*/
@InterfaceAudience.Private
/* package */ SavedRevision getRevisionWithId(String revId) {
if (revId != null && currentRevision != null && revId.equals(currentRevision.getId())) {
return currentRevision;
}
return getRevisionFromRev(
database.getDocumentWithIDAndRev(getId(),
revId,
EnumSet.noneOf(Database.TDContentOptions.class))
);
}
/**
* @exclude
*/
@InterfaceAudience.Private
/* package */ void loadCurrentRevisionFrom(QueryRow row) {
if (row.getDocumentRevisionId() == null) {
return;
}
String revId = row.getDocumentRevisionId();
if (currentRevision == null || revIdGreaterThanCurrent(revId)) {
Map<String, Object> properties = row.getDocumentProperties();
if (properties != null) {
RevisionInternal rev = new RevisionInternal(properties, row.getDatabase());
currentRevision = new SavedRevision(this, rev);
}
}
}
/**
* @exclude
*/
@InterfaceAudience.Private
private boolean revIdGreaterThanCurrent(String revId) {
return (RevisionInternal.CBLCompareRevIDs(revId, currentRevision.getId()) > 0);
}
/**
* @exclude
*/
@InterfaceAudience.Private
/* package */ void revisionAdded(DocumentChange documentChange) {
RevisionInternal rev = documentChange.getWinningRevision();
if (rev == null) {
return; // current revision didn't change
}
if (currentRevision != null && !rev.getRevId().equals(currentRevision.getId())) {
if (!rev.isDeleted()) {
currentRevision = new SavedRevision(this, rev);
} else {
currentRevision = null;
}
}
for (ChangeListener listener : changeListeners) {
listener.changed(new ChangeEvent(this, documentChange));
}
}
}
|
package com.cube.storm.ui.view;
import com.cube.storm.ui.model.Model;
import com.cube.storm.ui.view.holder.CheckableListItemHolder;
import com.cube.storm.ui.view.holder.DescriptionListItemHolder;
import com.cube.storm.ui.view.holder.Holder;
import com.cube.storm.ui.view.holder.ImageListItemHolder;
import com.cube.storm.ui.view.holder.ListFooterHolder;
import com.cube.storm.ui.view.holder.ListHeaderHolder;
import com.cube.storm.ui.view.holder.OrderedListItemHolder;
import com.cube.storm.ui.view.holder.StandardListItemHolder;
import com.cube.storm.ui.view.holder.TextListItemHolder;
import com.cube.storm.ui.view.holder.TitleListItemHolder;
import com.cube.storm.ui.view.holder.UnorderedListItemHolder;
/**
* This is the enum class with the list of all supported view types, their model classes and their
* corresponding view holder class. This list should not be modified or overridden
*
* @author Callum Taylor
* @project Storm Test
*/
public enum View
{
/**
* Private views - These are not driven by the CMS, these are internal classes derived from
* the list model.
*/
_ListHeader(com.cube.storm.ui.model.list.List.ListHeader.class, ListHeaderHolder.class),
_ListFooter(com.cube.storm.ui.model.list.List.ListFooter.class, ListFooterHolder.class),
List(com.cube.storm.ui.model.list.List.class, null),
TextListItem(com.cube.storm.ui.model.list.TextListItem.class, TextListItemHolder.class),
ImageListItem(com.cube.storm.ui.model.list.ImageListItem.class, ImageListItemHolder.class),
TitleListItem(com.cube.storm.ui.model.list.TitleListItem.class, TitleListItemHolder.class),
DescriptionListItem(com.cube.storm.ui.model.list.DescriptionListItem.class, DescriptionListItemHolder.class),
StandardListItem(com.cube.storm.ui.model.list.StandardListItem.class, StandardListItemHolder.class),
OrderedListItem(com.cube.storm.ui.model.list.OrderedListItem.class, OrderedListItemHolder.class),
BulletListItem(com.cube.storm.ui.model.list.UnorderedListItem.class, UnorderedListItemHolder.class),
CheckableListItem(com.cube.storm.ui.model.list.CheckableListItem.class, CheckableListItemHolder.class),
ListPage(com.cube.storm.ui.model.page.ListPage.class, null),
/**
* Properties
*/
Image(com.cube.storm.ui.model.property.BundleImageProperty.class, null),
DestinationLink(com.cube.storm.ui.model.property.DestinationLinkProperty.class, null),
InternalLink(com.cube.storm.ui.model.property.InternalLinkProperty.class, null),
ExternalLink(com.cube.storm.ui.model.property.ExternalLinkProperty.class, null),
UriLink(com.cube.storm.ui.model.property.UriLinkProperty.class, null);
private Class<? extends Model> model;
private Class<? extends Holder> holder;
private View(Class<? extends Model> model, Class<? extends Holder> holder)
{
this.model = model;
this.holder = holder;
}
/**
* @return Gets the holder class of the view
*/
public Class<? extends Holder> getHolderClass()
{
return holder;
}
/**
* @return Gets the model class of the view
*/
public Class<? extends Model> getModelClass()
{
return model;
}
}
|
package com.jaamsim.render;
//import com.jaamsim.math.*;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Image;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URL;
import java.nio.IntBuffer;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.media.nativewindow.NativeWindowFactory;
import javax.media.opengl.DebugGL4bc;
import javax.media.opengl.GL;
import javax.media.opengl.GL2GL3;
import javax.media.opengl.GL3;
import javax.media.opengl.GL4bc;
import javax.media.opengl.GLAnimatorControl;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLContext;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.GLException;
import javax.media.opengl.GLProfile;
import com.jaamsim.DisplayModels.DisplayModel;
import com.jaamsim.MeshFiles.MeshData;
import com.jaamsim.font.OverlayString;
import com.jaamsim.font.TessFont;
import com.jaamsim.input.ColourInput;
import com.jaamsim.math.AABB;
import com.jaamsim.math.Color4d;
import com.jaamsim.math.Ray;
import com.jaamsim.math.Vec3d;
import com.jaamsim.math.Vec4d;
import com.jaamsim.render.util.ExceptionLogger;
import com.jaamsim.ui.LogBox;
import com.jogamp.common.util.VersionNumber;
import com.jogamp.newt.event.WindowEvent;
import com.jogamp.newt.event.WindowListener;
import com.jogamp.newt.event.WindowUpdateEvent;
import com.jogamp.newt.opengl.GLWindow;
/**
* The central renderer for JaamSim Renderer, Contains references to all context
* specific data (like shader caches)
*
* @author Matt.Chudleigh
*
*/
public class Renderer implements GLAnimatorControl {
public enum ShaderHandle {
FONT, HULL, OVERLAY_FONT, OVERLAY_FLAT, DEBUG, SKYBOX
}
static private Object idLock = new Object();
static private int nextID = 1;
/**
* Get a system wide unique ID
* @return
*/
public static int getAssetID() {
synchronized(idLock) {
return nextID++;
}
}
private static boolean USE_DEBUG_GL = true;
public static int DIFF_TEX_FLAG = 1;
public static int NUM_MESH_SHADERS = 2; // Should be 2^(max_flag)
private EnumMap<ShaderHandle, Shader> shaders;
private Shader[] meshShaders = new Shader[NUM_MESH_SHADERS];
private GLContext sharedContext = null;
Map<Integer, Integer> sharedVaoMap = new HashMap<Integer, Integer>();
int sharedContextID = getAssetID();
GLWindow dummyWindow;
private GLCapabilities caps = null;
private TexCache texCache = new TexCache(this);
// An initalization time flag specifying if the 'safest' graphical techniques should be used
private boolean safeGraphics;
private final Thread renderThread;
private final Object rendererLock = new Object();
private final Map<MeshProtoKey, MeshProto> protoCache;
private final Map<TessFontKey, TessFont> fontCache;
private final HashMap<Integer, RenderWindow> openWindows;
private final HashMap<Integer, Camera> cameras;
private final Queue<RenderMessage> renderMessages = new ArrayDeque<RenderMessage>();
private final AtomicBoolean displayNeeded = new AtomicBoolean(true);
private final AtomicBoolean initialized = new AtomicBoolean(false);
private final AtomicBoolean shutdown = new AtomicBoolean(false);
private final AtomicBoolean fatalError = new AtomicBoolean(false);
private String errorString; // This is the string that caused the fatal error
private StackTraceElement[] fatalStackTrace; // the stack trace from the fatal error
private final ExceptionLogger exceptionLogger;
private TessFontKey defaultFontKey = new TessFontKey(Font.SANS_SERIF, Font.PLAIN);
private TessFontKey defaultBoldFontKey = new TessFontKey(Font.SANS_SERIF, Font.BOLD);
private final Object sceneLock = new Object();
private ArrayList<RenderProxy> proxyScene = new ArrayList<RenderProxy>();
private boolean allowDelayedTextures;
private double sceneTimeMS;
private double loopTimeMS;
private final Object settingsLock = new Object();
private boolean showDebugInfo = false;
private long usedVRAM = 0;
// A flag to track JOGL's GLAnimatorControl pause feature
private boolean isPaused = false;
// This may not be the best way to cache this
private GLContext drawContext = null;
private Skybox skybox;
private MeshData badData;
private MeshProto badProto;
// A cache of the current scene, needed by the individual windows to render
private ArrayList<Renderable> currentScene = new ArrayList<Renderable>();
private ArrayList<OverlayRenderable> currentOverlay = new ArrayList<OverlayRenderable>();
public Renderer(boolean safeGraphics) throws RenderException {
this.safeGraphics = safeGraphics;
protoCache = new HashMap<MeshProtoKey, MeshProto>();
fontCache = new HashMap<TessFontKey, TessFont>();
exceptionLogger = new ExceptionLogger(1); // Print the call stack on the first exception of any kind
openWindows = new HashMap<Integer, RenderWindow>();
cameras = new HashMap<Integer, Camera>();
renderThread = new Thread(new Runnable() {
@Override
public void run() {
mainRenderLoop();
}
}, "RenderThread");
renderThread.start();
}
private void mainRenderLoop() {
//long startNanos = System.nanoTime();
try {
// GLProfile.initSingleton();
GLProfile glp = GLProfile.get(GLProfile.GL2GL3);
caps = new GLCapabilities(glp);
caps.setSampleBuffers(true);
caps.setNumSamples(4);
caps.setDepthBits(24);
// Create a dummy window
dummyWindow = GLWindow.create(caps);
dummyWindow.setSize(128, 128);
dummyWindow.setPosition(-2000, -2000);
// This is unfortunately necessary due to JOGL's (newt's?) involved
// startup code
// I can not find a way to make a context valid without a visible window
dummyWindow.setVisible(true);
sharedContext = dummyWindow.getContext();
assert (sharedContext != null);
dummyWindow.setVisible(false);
// long endNanos = System.nanoTime();
// long ms = (endNanos - startNanos) /1000000L;
// LogBox.formatRenderLog("Creating shared context at:" + ms + "ms");
checkForIntelDriver();
initSharedContext();
// Notify the main thread we're done
synchronized (initialized) {
initialized.set(true);
initialized.notifyAll();
}
} catch (Exception e) {
fatalError.set(true);
errorString = e.getLocalizedMessage();
fatalStackTrace = e.getStackTrace();
LogBox.renderLog("Renderer encountered a fatal error:");
LogBox.renderLogException(e);
} finally {
if (sharedContext != null && sharedContext.isCurrent())
sharedContext.release();
}
// endNanos = System.nanoTime();
// ms = (endNanos - startNanos) /1000000L;
// LogBox.formatRenderLog("Started renderer loop after:" + ms + "ms");
long lastLoopEnd = System.nanoTime();
// Add a custom shutdown hook to make sure we're finished closing before JOGL tries to shutdown
NativeWindowFactory.addCustomShutdownHook(true, new Runnable() {
@Override
public void run() {
// Block JOGL shutting down until we're dead
shutdown();
while (renderThread.isAlive()) {
synchronized (this) {
try {
queueRedraw(); // Just in case the render thread got stalled somewhere
wait(50);
} catch (InterruptedException ex) {}
}
}
}
});
while (!shutdown.get()) {
try {
// If a fatal error was encountered, clean up the renderer
if (fatalError.get()) {
// We should clean up everything we can, then die
try {
for (Entry<Integer, RenderWindow> entry : openWindows.entrySet()){
entry.getValue().getGLWindowRef().destroy();
entry.getValue().getAWTFrameRef().dispose();
}
} catch(Exception e) {} // Ignore any exceptions, this is just a best effort cleanup
try {
dummyWindow.destroy();
sharedContext.destroy();
dummyWindow = null;
sharedContext = null;
openWindows.clear();
currentScene = null;
currentOverlay = null;
caps = null;
fontCache.clear();
protoCache.clear();
shaders.clear();
} catch (Exception e) { }
break; // Exiting the loop will end the thread
}
displayNeeded.set(false);
updateRenderableScene();
// Run all render messages
RenderMessage message;
boolean moreMessages = false;
do {
// Only lock the queue while reading messages, release it while
// processing them
message = null;
synchronized (renderMessages) {
if (!renderMessages.isEmpty()) {
message = renderMessages.remove();
moreMessages = !renderMessages.isEmpty();
}
}
if (message != null) {
try {
handleMessage(message);
} catch (Throwable t) {
// Log this error but continue processing
logException(t);
}
}
} while (moreMessages);
// Defensive copy the window list (in case a window is closed while we render)
HashMap<Integer, RenderWindow> winds;
synchronized (openWindows) {
winds = new HashMap<Integer, RenderWindow>(openWindows);
}
if (!isPaused) {
for (RenderWindow wind : winds.values()) {
if (shutdown.get())
break;
try {
GLWindow glWin = wind.getGLWindowRef();
GLContext context = glWin.getContext();
if (context != null)
glWin.display();
}
catch (Throwable t) {
// Log it, but move on to the other windows
logException(t);
}
}
}
long loopEnd = System.nanoTime();
loopTimeMS = (loopEnd - lastLoopEnd) / 1000000;
lastLoopEnd = loopEnd;
try {
synchronized (displayNeeded) {
if (!displayNeeded.get()) {
displayNeeded.wait();
}
}
} catch (InterruptedException e) {
// Let's loop anyway...
}
} catch (Throwable t) {
// Any other unexpected exceptions...
logException(t);
}
}
}
/**
* Returns the shader object for this handle, should only be called from the render thread (during a render)
* @param h
* @return
*/
public Shader getShader(ShaderHandle h) {
return shaders.get(h);
}
public Shader getMeshShader(int flags) {
assert(flags < NUM_MESH_SHADERS);
return meshShaders[flags];
}
/**
* Returns the MeshProto for the supplied key, should only be called from the render thread (during a render)
* @param key
* @return
*/
public MeshProto getProto(MeshProtoKey key) {
MeshProto proto = protoCache.get(key);
if (proto == null) {
// This prototype needs to be lazily loaded
loadMeshProtoImp(key);
}
return protoCache.get(key);
}
public TessFont getTessFont(TessFontKey key) {
if (!fontCache.containsKey(key)) {
loadTessFontImp(key); // Try lazy initialization for now
}
return fontCache.get(key);
}
public void setScene(ArrayList<RenderProxy> scene) {
synchronized (sceneLock) {
proxyScene = scene;
}
}
public void queueRedraw() {
synchronized(displayNeeded) {
displayNeeded.set(true);
displayNeeded.notifyAll();
}
}
private void addRenderMessage(RenderMessage msg) {
synchronized(renderMessages) {
renderMessages.add(msg);
queueRedraw();
}
}
public void setCameraInfoForWindow(int windowID, CameraInfo info) {
synchronized (renderMessages) {
addRenderMessage(new SetCameraMessage(windowID, info));
}
}
private void setCameraInfoImp(SetCameraMessage mes) {
synchronized (openWindows) {
Camera cam = cameras.get(mes.windowID);
if (cam == null) {
// Bad windowID
throw new RuntimeException("Bad window ID");
}
cam.setInfo(mes.cameraInfo);
}
}
/**
* Call this from any thread to shutdown the Renderer, will return
* immediately but the renderer will shutdown after the next redraw
*/
public void shutdown() {
shutdown.set(true);
queueRedraw();
}
public GL2GL3 getGL() {
return drawContext.getGL().getGL2GL3();
}
/**
* Get a list of all the IDs of currently open windows
* @return
*/
public ArrayList<Integer> getOpenWindowIDs() {
synchronized(openWindows) {
ArrayList<Integer> ret = new ArrayList<Integer>();
for (int id : openWindows.keySet()) {
ret.add(id);
}
return ret;
}
}
public String getWindowName(int windowID) {
synchronized(openWindows) {
RenderWindow win = openWindows.get(windowID);
if (win == null) {
return null;
}
return win.getName();
}
}
public Frame getAWTFrame(int windowID) {
synchronized(openWindows) {
RenderWindow win = openWindows.get(windowID);
if (win == null) {
return null;
}
return win.getAWTFrameRef();
}
}
public void focusWindow(int windowID) {
synchronized(openWindows) {
RenderWindow win = openWindows.get(windowID);
if (win == null) {
return;
}
win.getAWTFrameRef().setExtendedState(Frame.NORMAL);
win.getAWTFrameRef().toFront();
}
}
/**
* Construct a new window (a NEWT window specifically)
*
* @param width
* @param height
* @return
*/
private void createWindowImp(CreateWindowMessage message) {
RenderGLListener listener = new RenderGLListener();
final RenderWindow window = new RenderWindow(message.x, message.y,
message.width, message.height,
message.title, message.name,
sharedContext,
caps, listener,
message.icon,
message.windowID,
message.viewID,
message.listener);
listener.setWindow(window);
Camera camera = new Camera(Math.PI/3.0, 1, 0.1, 1000);
synchronized (openWindows) {
openWindows.put(message.windowID, window);
cameras.put(message.windowID, camera);
}
window.getGLWindowRef().setAnimator(this);
GLWindowListener wl = new GLWindowListener(window.getWindowID());
window.getGLWindowRef().addWindowListener(wl);
window.getAWTFrameRef().addComponentListener(wl);
window.getGLWindowRef().addMouseListener(new MouseHandler(window, message.listener));
window.getGLWindowRef().addKeyListener(message.listener);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
window.getAWTFrameRef().setVisible(true);
}
});
queueRedraw();
}
public int createWindow(int x, int y, int width, int height, int viewID, String title, String name, Image icon,
WindowInteractionListener listener) {
synchronized (renderMessages) {
int windowID = getAssetID();
addRenderMessage(new CreateWindowMessage(x, y, width, height, title,
name, windowID, viewID, icon, listener));
return windowID;
}
}
public void setWindowDebugInfo(int windowID, String debugString, ArrayList<Long> debugIDs) {
synchronized(openWindows) {
RenderWindow w = openWindows.get(windowID);
if (w != null) {
w.setDebugString(debugString);
w.setDebugIDs(debugIDs);
}
}
}
public void closeWindow(int windowID) {
synchronized (renderMessages) {
addRenderMessage(new CloseWindowMessage(windowID));
}
}
private void closeWindowImp(CloseWindowMessage msg) {
RenderWindow window;
synchronized(openWindows) {
window = openWindows.get(msg.windowID);
if (window == null) {
return;
}
}
windowCleanup(msg.windowID);
window.getGLWindowRef().destroy();
window.getAWTFrameRef().dispose();
}
private String readSource(String file) {
URL res = Renderer.class.getResource(file);
StringBuilder source = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(res.openStream()));
while (true) {
String line = reader.readLine();
if (line == null) break;
source.append(line).append("\n");
}
reader.close();
reader = null;
}
catch (IOException e) {}
return source.toString();
}
private void createShader(ShaderHandle sh, String vert, String frag, GL2GL3 gl) {
String vertsrc = readSource(vert);
String fragsrc = readSource(frag);
Shader s = new Shader(vertsrc, fragsrc, gl);
if (s.isGood()) {
shaders.put(sh, s);
return;
}
String failure = s.getFailureLog();
throw new RenderException("Shader failed: " + sh.toString() + " " + failure);
}
private void createCoreShader(ShaderHandle sh, String vert, String frag, GL2GL3 gl, String version) {
String vertsrc = readSource(vert).replaceAll("@VERSION@", version);
String fragsrc = readSource(frag).replaceAll("@VERSION@", version);
Shader s = new Shader(vertsrc, fragsrc, gl);
if (s.isGood()) {
shaders.put(sh, s);
return;
}
String failure = s.getFailureLog();
throw new RenderException("Shader failed: " + sh.toString() + " " + failure);
}
private String getMeshShaderDefines(int i) {
StringBuilder defines = new StringBuilder();
if ((i & DIFF_TEX_FLAG) != 0) {
defines.append("#define DIFF_TEX\n");
}
return defines.toString();
}
/**
* Create and compile all the shaders
*/
private void initShaders(GL2GL3 gl) throws RenderException {
shaders = new EnumMap<ShaderHandle, Shader>(ShaderHandle.class);
String vert, frag;
vert = "/resources/shaders/font.vert";
frag = "/resources/shaders/font.frag";
createShader(ShaderHandle.FONT, vert, frag, gl);
vert = "/resources/shaders/hull.vert";
frag = "/resources/shaders/hull.frag";
createShader(ShaderHandle.HULL, vert, frag, gl);
vert = "/resources/shaders/overlay-font.vert";
frag = "/resources/shaders/overlay-font.frag";
createShader(ShaderHandle.OVERLAY_FONT, vert, frag, gl);
vert = "/resources/shaders/overlay-flat.vert";
frag = "/resources/shaders/overlay-flat.frag";
createShader(ShaderHandle.OVERLAY_FLAT, vert, frag, gl);
vert = "/resources/shaders/debug.vert";
frag = "/resources/shaders/debug.frag";
createShader(ShaderHandle.DEBUG, vert, frag, gl);
vert = "/resources/shaders/skybox.vert";
frag = "/resources/shaders/skybox.frag";
createShader(ShaderHandle.SKYBOX, vert, frag, gl);
String meshVertSrc = readSource("/resources/shaders/flat.vert");
String meshFragSrc = readSource("/resources/shaders/flat.frag");
// Create the mesh shaders
for (int i = 0; i < NUM_MESH_SHADERS; ++i) {
String defines = getMeshShaderDefines(i);
String definedFragSrc = meshFragSrc.replaceAll("@DEFINES@", defines);
Shader s = new Shader(meshVertSrc, definedFragSrc, gl);
if (!s.isGood()) {
String failure = s.getFailureLog();
throw new RenderException("Mesh Shader failed, flags: " + i + " " + failure);
}
meshShaders[i] = s;
}
}
/**
* Create and compile all the shaders
*/
private void initCoreShaders(GL2GL3 gl, String version) throws RenderException {
shaders = new EnumMap<ShaderHandle, Shader>(ShaderHandle.class);
String vert, frag;
vert = "/resources/shaders_core/font.vert";
frag = "/resources/shaders_core/font.frag";
createCoreShader(ShaderHandle.FONT, vert, frag, gl, version);
vert = "/resources/shaders_core/hull.vert";
frag = "/resources/shaders_core/hull.frag";
createCoreShader(ShaderHandle.HULL, vert, frag, gl, version);
vert = "/resources/shaders_core/overlay-font.vert";
frag = "/resources/shaders_core/overlay-font.frag";
createCoreShader(ShaderHandle.OVERLAY_FONT, vert, frag, gl, version);
vert = "/resources/shaders_core/overlay-flat.vert";
frag = "/resources/shaders_core/overlay-flat.frag";
createCoreShader(ShaderHandle.OVERLAY_FLAT, vert, frag, gl, version);
vert = "/resources/shaders_core/debug.vert";
frag = "/resources/shaders_core/debug.frag";
createCoreShader(ShaderHandle.DEBUG, vert, frag, gl, version);
vert = "/resources/shaders_core/skybox.vert";
frag = "/resources/shaders_core/skybox.frag";
createCoreShader(ShaderHandle.SKYBOX, vert, frag, gl, version);
String meshVertSrc = readSource("/resources/shaders_core/flat.vert").replaceAll("@VERSION@", version);
String meshFragSrc = readSource("/resources/shaders_core/flat.frag").replaceAll("@VERSION@", version);
// Create the mesh shaders
for (int i = 0; i < NUM_MESH_SHADERS; ++i) {
String defines = getMeshShaderDefines(i);
String definedFragSrc = meshFragSrc.replaceAll("@DEFINES@", defines);
Shader s = new Shader(meshVertSrc, definedFragSrc, gl);
if (!s.isGood()) {
String failure = s.getFailureLog();
throw new RenderException("Mesh Shader failed, flags: " + i + " " + failure);
}
meshShaders[i] = s;
}
}
/**
* Basic message dispatch
*
* @param message
*/
private void handleMessage(RenderMessage message) {
assert (Thread.currentThread() == renderThread);
if (message instanceof CreateWindowMessage) {
createWindowImp((CreateWindowMessage) message);
return;
}
if (message instanceof SetCameraMessage) {
setCameraInfoImp((SetCameraMessage) message);
return;
}
if (message instanceof OffScreenMessage) {
offScreenImp((OffScreenMessage) message);
return;
}
if (message instanceof CloseWindowMessage) {
closeWindowImp((CloseWindowMessage) message);
return;
}
if (message instanceof CreateOffscreenTargetMessage) {
populateOffscreenTarget(((CreateOffscreenTargetMessage)message).target);
}
if (message instanceof FreeOffscreenTargetMessage) {
freeOffscreenTargetImp(((FreeOffscreenTargetMessage)message).target);
}
}
private void initSharedContext() {
assert (Thread.currentThread() == renderThread);
assert (drawContext == null);
int res = sharedContext.makeCurrent();
assert (res == GLContext.CONTEXT_CURRENT);
if (USE_DEBUG_GL) {
sharedContext.setGL(new DebugGL4bc((GL4bc)sharedContext.getGL().getGL2GL3()));
}
LogBox.formatRenderLog("Found OpenGL version: %s", sharedContext.getGLVersion());
LogBox.formatRenderLog("Found GLSL: %s", sharedContext.getGLSLVersionString());
VersionNumber vn = sharedContext.getGLVersionNumber();
boolean isCore = sharedContext.isGLCoreProfile();
LogBox.formatRenderLog("OpenGL Major: %d Minor: %d IsCore:%s", vn.getMajor(), vn.getMinor(), isCore);
if (vn.getMajor() < 2) {
throw new RenderException("OpenGL version is too low. OpenGL >= 2.1 is required.");
}
GL2GL3 gl = sharedContext.getGL().getGL2GL3();
if (!isCore)
initShaders(gl);
else
initCoreShaders(gl, sharedContext.getGLSLVersionString());
// Sub system specific intitializations
DebugUtils.init(this, gl);
Polygon.init(this, gl);
MeshProto.init(this, gl);
texCache.init(gl);
// Load the bad mesh proto
badData = MeshDataCache.getBadMesh();
badProto = new MeshProto(badData, safeGraphics, !safeGraphics);
badProto.loadGPUAssets(gl, this);
skybox = new Skybox();
sharedContext.release();
}
private void loadMeshProtoImp(final MeshProtoKey key) {
//long startNanos = System.nanoTime();
assert(drawContext == null || !drawContext.isCurrent());
if (protoCache.get(key) != null) {
return; // This mesh has already been loaded
}
int res = sharedContext.makeCurrent();
assert (res == GLContext.CONTEXT_CURRENT);
GL2GL3 gl = sharedContext.getGL().getGL2GL3();
MeshProto proto;
MeshData data = MeshDataCache.getMeshData(key);
if (data == badData) {
proto = badProto;
} else {
proto = new MeshProto(data, safeGraphics, !safeGraphics);
assert (proto != null);
proto.loadGPUAssets(gl, this);
if (!proto.isLoadedGPU()) {
// This did not load cleanly, clear it out and use the default bad mesh asset
proto.freeResources(gl);
LogBox.formatRenderLog("Could not load GPU assset: %s\n", key.getURI().toString());
proto = badProto;
}
}
protoCache.put(key, proto);
sharedContext.release();
// long endNanos = System.nanoTime();
// long ms = (endNanos - startNanos) /1000000L;
// LogBox.formatRenderLog("LoadMeshProtoImp time:" + ms + "ms");
}
private void loadTessFontImp(TessFontKey key) {
if (fontCache.get(key) != null) {
return; // This font has already been loaded
}
TessFont tf = new TessFont(key);
fontCache.put(key, tf);
}
public int generateVAO(int contextID, GL2GL3 gl) {
assert(Thread.currentThread() == renderThread);
int[] vaos = new int[1];
gl.glGenVertexArrays(1, vaos, 0);
int vao = vaos[0];
synchronized(openWindows) {
RenderWindow wind = openWindows.get(contextID);
if (wind != null) {
wind.addVAO(vao);
}
}
return vao;
}
// Recreate the internal scene based on external input
private void updateRenderableScene() {
synchronized (sceneLock) {
long sceneStart = System.nanoTime();
currentScene = new ArrayList<Renderable>();
currentOverlay = new ArrayList<OverlayRenderable>();
for (RenderProxy proxy : proxyScene) {
proxy.collectRenderables(this, currentScene);
proxy.collectOverlayRenderables(this, currentOverlay);
}
long sceneTime = System.nanoTime() - sceneStart;
sceneTimeMS = sceneTime / 1000000.0;
}
}
public static class PickResult {
public double dist;
public long pickingID;
public PickResult(double dist, long pickingID) {
this.dist = dist;
this.pickingID = pickingID;
}
}
/**
* Cast the provided ray into the current scene and return the list of bounds collisions
* @param ray
* @return
*/
public List<PickResult> pick(Ray pickRay, int viewID, boolean precise) {
synchronized(openWindows) {
ArrayList<PickResult> ret = new ArrayList<PickResult>();
if (currentScene == null) {
return ret;
}
Camera cam = null;
for (RenderWindow wind : openWindows.values()) {
if (wind.getViewID() == viewID) {
cam = cameras.get(wind.getWindowID());
break;
}
}
if (cam == null) {
// Invalid view
return ret;
}
// Do not update the scene while a pick is underway
synchronized (sceneLock) {
for (Renderable r : currentScene) {
double rayDist = r.getCollisionDist(pickRay, precise);
if (rayDist >= 0.0) {
if (r.renderForView(viewID, cam)) {
ret.add(new PickResult(rayDist, r.getPickingID()));
}
}
}
return ret;
}
}
}
public static class WindowMouseInfo {
public int x, y;
public int width, height;
public int viewableX, viewableY;
public boolean mouseInWindow;
public CameraInfo cameraInfo;
}
/**
* Get Window specific information about the mouse. This is very useful for picking on the App side
* @param windowID
* @return
*/
public WindowMouseInfo getMouseInfo(int windowID) {
synchronized(openWindows) {
RenderWindow w = openWindows.get(windowID);
if (w == null) {
return null; // Not a valid window ID, or the window has closed
}
WindowMouseInfo info = new WindowMouseInfo();
info.x = w.getMouseX();
info.y = w.getMouseY();
info.width = w.getViewableWidth();
info.height = w.getViewableHeight();
info.viewableX = w.getViewableX();
info.viewableY = w.getViewableY();
info.mouseInWindow = w.isMouseInWindow();
info.cameraInfo = cameras.get(windowID).getInfo();
return info;
}
}
public CameraInfo getCameraInfo(int windowID) {
synchronized(openWindows) {
Camera cam = cameras.get(windowID);
if (cam == null) {
return null; // Not a valid window ID
}
return cam.getInfo();
}
}
// Common cleanup code for window closing. Applies to both user closed and programatically closed windows
private void windowCleanup(int windowID) {
RenderWindow w;
synchronized(openWindows) {
w = openWindows.get(windowID);
if (w == null) {
return;
}
openWindows.remove(windowID);
}
w.getAWTFrameRef().setVisible(false);
w.getGLWindowRef().destroy();
// Fire the window closing callback
w.getWindowListener().windowClosing();
}
private class GLWindowListener implements WindowListener, ComponentListener {
private int windowID;
public GLWindowListener(int id) {
windowID = id;
}
private WindowInteractionListener getListener() {
synchronized(openWindows) {
RenderWindow w = openWindows.get(windowID);
if (w == null) {
return null; // Not a valid window ID, or the window has closed
}
return w.getWindowListener();
}
}
@Override
public void windowDestroyNotify(WindowEvent we) {
windowCleanup(windowID);
}
@Override
public void windowDestroyed(WindowEvent arg0) {
}
@Override
public void windowGainedFocus(WindowEvent arg0) {
WindowInteractionListener listener = getListener();
if (listener != null) {
listener.windowGainedFocus();
}
}
@Override
public void windowLostFocus(WindowEvent arg0) {
}
@Override
public void windowMoved(WindowEvent arg0) {
}
@Override
public void windowRepaint(WindowUpdateEvent arg0) {
}
@Override
public void windowResized(WindowEvent arg0) {
}
private void updateWindowSizeAndPos() {
RenderWindow w;
synchronized(openWindows) {
w = openWindows.get(windowID);
if (w == null) {
return;
}
}
w.getWindowListener().windowMoved(w.getWindowX(), w.getWindowY(), w.getWindowWidth(), w.getWindowHeight());
}
@Override
public void componentHidden(ComponentEvent arg0) {
}
@Override
public void componentMoved(ComponentEvent arg0) {
updateWindowSizeAndPos();
}
@Override
public void componentResized(ComponentEvent arg0) {
updateWindowSizeAndPos();
}
@Override
public void componentShown(ComponentEvent arg0) {
}
}
private class RenderGLListener implements GLEventListener {
private RenderWindow window;
private long lastFrameNanos = 0;
public void setWindow(RenderWindow win) {
window = win;
}
@Override
public void init(GLAutoDrawable drawable) {
synchronized (rendererLock) {
// Per window initialization
if (USE_DEBUG_GL) {
drawable.setGL(new DebugGL4bc((GL4bc)drawable.getGL().getGL2GL3()));
}
GL2GL3 gl = drawable.getGL().getGL2GL3();
// Some of this is probably redundant, but here goes
gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
gl.glEnable(GL.GL_DEPTH_TEST);
gl.glClearDepth(1.0);
gl.glDepthFunc(GL2GL3.GL_LEQUAL);
gl.glEnable(GL2GL3.GL_CULL_FACE);
gl.glCullFace(GL2GL3.GL_BACK);
gl.glEnable(GL.GL_MULTISAMPLE);
gl.glBlendEquationSeparate(GL2GL3.GL_FUNC_ADD, GL2GL3.GL_MAX);
gl.glBlendFuncSeparate(GL2GL3.GL_SRC_ALPHA, GL2GL3.GL_ONE_MINUS_SRC_ALPHA, GL2GL3.GL_ONE, GL2GL3.GL_ONE);
}
}
@Override
public void dispose(GLAutoDrawable drawable) {
synchronized (rendererLock) {
GL2GL3 gl = drawable.getGL().getGL2GL3();
ArrayList<Integer> vaoArray = window.getVAOs();
int[] vaos = new int[vaoArray.size()];
int index = 0;
for (int vao : vaoArray) {
vaos[index++] = vao;
}
if (vaos.length > 0) {
gl.glDeleteVertexArrays(vaos.length, vaos, 0);
}
}
}
@Override
public void display(GLAutoDrawable drawable) {
synchronized (rendererLock) {
Camera cam = cameras.get(window.getWindowID());
// The ray of the current mouse position (or null if the mouse is not hovering over the window)
Ray pickRay = RenderUtils.getPickRay(getMouseInfo(window.getWindowID()));
PerfInfo pi = new PerfInfo();
long startNanos = System.nanoTime();
allowDelayedTextures = true;
// Cache the current scene. This way we don't need to lock it for the full render
ArrayList<Renderable> scene = new ArrayList<Renderable>(currentScene.size());
ArrayList<OverlayRenderable> overlay = new ArrayList<OverlayRenderable>(currentOverlay.size());
synchronized(sceneLock) {
scene.addAll(currentScene);
overlay.addAll(currentOverlay);
}
renderScene(drawable.getContext(), window.getWindowID(),
scene, overlay,
cam, window.getViewableWidth(), window.getViewableHeight(),
pickRay, window.getViewID(), pi);
GL2GL3 gl = drawable.getContext().getGL().getGL2GL3(); // Just to clean up the code below
boolean showDebug;
synchronized(settingsLock) {
showDebug = showDebugInfo;
}
if (showDebug) {
// Draw a window specific performance counter
gl.glDisable(GL2GL3.GL_DEPTH_TEST);
drawContext = drawable.getContext();
StringBuilder perf = new StringBuilder();
perf.append( String.format( "Objects Culled: %s", pi.objectsCulled) );
perf.append( String.format( " VRAM (MB): %.0f", usedVRAM/(1024.0*1024.0)) );
perf.append( String.format( " Frame time (ms): %.3f", lastFrameNanos/1000000.0) );
perf.append( String.format( " SceneTime (ms): %.3f", sceneTimeMS) );
perf.append( String.format( " Loop Time (ms): %.3f", loopTimeMS) );
TessFont defFont = getTessFont(defaultBoldFontKey);
OverlayString os = new OverlayString(defFont, perf.toString(), ColourInput.BLACK,
10, 10, 15, false, false, DisplayModel.ALWAYS);
os.render(window.getWindowID(), Renderer.this,
window.getViewableWidth(), window.getViewableHeight(), cam, null);
// Also draw this window's debug string
os = new OverlayString(defFont, window.getDebugString(), ColourInput.BLACK,
10, 10, 30, false, false, DisplayModel.ALWAYS);
os.render(window.getWindowID(), Renderer.this,
window.getViewableWidth(), window.getViewableHeight(), cam, null);
drawContext = null;
gl.glEnable(GL2GL3.GL_DEPTH_TEST);
}
gl.glFinish();
long endNanos = System.nanoTime();
lastFrameNanos = endNanos - startNanos;
}
}
@Override
public void reshape(GLAutoDrawable drawable, int x, int y, int width,
int height) {
//_window.resized(width, height);
Camera cam = cameras.get(window.getWindowID());
cam.setAspectRatio((double) width / (double) height);
}
}
/**
* Abstract base type for internal renderer messages
*/
private static class RenderMessage {
@SuppressWarnings("unused")
public long queueTime = System.nanoTime();
}
private static class CreateWindowMessage extends RenderMessage {
public int x, y;
public int width, height;
public String title, name;
public WindowInteractionListener listener;
public int windowID, viewID;
public Image icon;
public CreateWindowMessage(int x, int y, int width, int height, String title,
String name, int windowID, int viewID, Image icon, WindowInteractionListener listener) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.title = title;
this.name = name;
this.listener = listener;
this.windowID = windowID;
this.viewID = viewID;
this.icon = icon;
}
}
private static class SetCameraMessage extends RenderMessage {
public int windowID;
public CameraInfo cameraInfo;
public SetCameraMessage(int windowID, CameraInfo cameraInfo) {
this.windowID = windowID;
this.cameraInfo = cameraInfo;
}
}
private static class OffScreenMessage extends RenderMessage {
public ArrayList<RenderProxy> scene;
public int viewID;
public Camera cam;
public int width, height;
public Future<BufferedImage> result;
public OffscreenTarget target;
OffScreenMessage(ArrayList<RenderProxy> s, int vID, Camera c, int w, int h, Future<BufferedImage> r, OffscreenTarget t) {
scene = s; viewID = vID; cam = c; width = w; height = h; result = r;
target = t;
}
}
private static class CloseWindowMessage extends RenderMessage {
public int windowID;
public CloseWindowMessage(int id) {
windowID = id;
}
}
private static class CreateOffscreenTargetMessage extends RenderMessage {
public OffscreenTarget target;
}
private static class FreeOffscreenTargetMessage extends RenderMessage {
public OffscreenTarget target;
}
public TexCache getTexCache() {
return texCache;
}
public static boolean debugDrawHulls() {
return false;
}
public static boolean debugDrawAABBs() {
return false;
}
public static boolean debugDrawArmatures() {
return false;
}
public boolean isInitialized() {
return initialized.get() && !fatalError.get();
}
public boolean hasFatalError() {
return fatalError.get();
}
public String getErrorString() {
return errorString;
}
public StackTraceElement[] getFatalStackTrace() {
return fatalStackTrace;
}
public TessFontKey getDefaultFont() {
return defaultFontKey;
}
public boolean allowDelayedTextures() {
return allowDelayedTextures;
}
private void logException(Throwable t) {
exceptionLogger.logException(t);
// For now print a synopsis for all exceptions thrown
printExceptionLog();
LogBox.renderLogException(t);
}
private void printExceptionLog() {
LogBox.renderLog("Exceptions from Renderer: ");
exceptionLogger.printExceptionLog();
LogBox.renderLog("");
}
/**
* Queue up an off screen rendering
* @param scene
* @param cam
* @param width
* @param height
* @return
*/
public Future<BufferedImage> renderOffscreen(ArrayList<RenderProxy> scene, int viewID, CameraInfo camInfo,
int width, int height, Runnable runWhenDone, OffscreenTarget target) {
Future<BufferedImage> result = new Future<BufferedImage>(runWhenDone);
Camera cam = new Camera(camInfo, (double)width/(double)height);
synchronized (renderMessages) {
addRenderMessage(new OffScreenMessage(scene, viewID, cam, width, height, result, target));
}
queueRedraw();
return result;
}
public OffscreenTarget createOffscreenTarget(int width, int height) {
OffscreenTarget ret = new OffscreenTarget(width, height);
synchronized (renderMessages) {
CreateOffscreenTargetMessage msg = new CreateOffscreenTargetMessage();
msg.target = ret;
addRenderMessage(msg);
}
return ret;
}
public void freeOffscreenTarget(OffscreenTarget target) {
synchronized (renderMessages) {
FreeOffscreenTargetMessage msg = new FreeOffscreenTargetMessage();
msg.target = target;
addRenderMessage(msg);
}
}
/**
* Create the resources for an OffscreenTarget
*/
private void populateOffscreenTarget(OffscreenTarget target) {
int width = target.getWidth();
int height = target.getHeight();
sharedContext.makeCurrent();
GL3 gl = sharedContext.getGL().getGL3(); // Just to clean up the code below
// This does not support opengl 3, so for now we don't support off screen rendering
if (gl == null) {
sharedContext.release();
return;
}
// Create a new frame buffer for this draw operation
int[] temp = new int[2];
gl.glGenFramebuffers(2, temp, 0);
int drawFBO = temp[0];
int blitFBO = temp[1];
gl.glGenTextures(2, temp, 0);
int drawTex = temp[0];
int blitTex = temp[1];
gl.glGenRenderbuffers(1, temp, 0);
int depthBuf = temp[0];
gl.glBindTexture(GL3.GL_TEXTURE_2D_MULTISAMPLE, drawTex);
gl.glTexImage2DMultisample(GL3.GL_TEXTURE_2D_MULTISAMPLE, 4, GL2GL3.GL_RGBA8, width, height, true);
gl.glBindRenderbuffer(GL2GL3.GL_RENDERBUFFER, depthBuf);
gl.glRenderbufferStorageMultisample(GL2GL3.GL_RENDERBUFFER, 4, GL2GL3.GL_DEPTH_COMPONENT, width, height);
gl.glBindFramebuffer(GL2GL3.GL_FRAMEBUFFER, drawFBO);
gl.glFramebufferTexture2D(GL2GL3.GL_FRAMEBUFFER, GL2GL3.GL_COLOR_ATTACHMENT0, GL3.GL_TEXTURE_2D_MULTISAMPLE, drawTex, 0);
gl.glFramebufferRenderbuffer(GL2GL3.GL_FRAMEBUFFER, GL2GL3.GL_DEPTH_ATTACHMENT, GL2GL3.GL_RENDERBUFFER, depthBuf);
int fbStatus = gl.glCheckFramebufferStatus(GL2GL3.GL_FRAMEBUFFER);
assert(fbStatus == GL2GL3.GL_FRAMEBUFFER_COMPLETE);
gl.glBindTexture(GL2GL3.GL_TEXTURE_2D, blitTex);
gl.glTexImage2D(GL2GL3.GL_TEXTURE_2D, 0, GL2GL3.GL_RGBA8, width, height,
0, GL2GL3.GL_RGBA, GL2GL3.GL_BYTE, null);
gl.glBindFramebuffer(GL2GL3.GL_FRAMEBUFFER, blitFBO);
gl.glFramebufferTexture2D(GL2GL3.GL_FRAMEBUFFER, GL2GL3.GL_COLOR_ATTACHMENT0, GL2GL3.GL_TEXTURE_2D, blitTex, 0);
gl.glBindFramebuffer(GL2GL3.GL_FRAMEBUFFER, 0);
target.load(drawFBO, drawTex, depthBuf, blitFBO, blitTex);
sharedContext.release();
}
private void freeOffscreenTargetImp(OffscreenTarget target) {
if (!target.isLoaded()) {
return; // Nothing to free
}
sharedContext.makeCurrent();
GL2GL3 gl = sharedContext.getGL().getGL2GL3(); // Just to clean up the code below
int[] temp = new int[2];
temp[0] = target.getDrawFBO();
temp[1] = target.getBlitFBO();
gl.glDeleteFramebuffers(2, temp, 0);
temp[0] = target.getDrawTex();
temp[1] = target.getBlitTex();
gl.glDeleteTextures(2, temp, 0);
temp[0] = target.getDepthBuffer();
gl.glDeleteRenderbuffers(1, temp, 0);
target.free();
sharedContext.release();
}
private void offScreenImp(OffScreenMessage message) {
synchronized(rendererLock) {
try {
boolean isTempTarget;
OffscreenTarget target;
if (message.target == null) {
isTempTarget = true;
target = new OffscreenTarget(message.width, message.height);
populateOffscreenTarget(target);
} else {
isTempTarget = false;
target = message.target;
assert(target.getWidth() == message.width);
assert(target.getHeight() == message.height);
}
int width = message.width;
int height = message.height;
if (!target.isLoaded()) {
message.result.setFailed("Contexted not loaded. Is OpenGL 3 supported?");
return;
}
assert(target.isLoaded());
// Collect the renderables
ArrayList<Renderable> renderables;
ArrayList<OverlayRenderable> overlay;
if (message.scene != null) {
renderables = new ArrayList<Renderable>();
overlay = new ArrayList<OverlayRenderable>();
for (RenderProxy p : message.scene) {
p.collectRenderables(this, renderables);
p.collectOverlayRenderables(this, overlay);
}
} else {
// Use the current current scene if one is not provided
synchronized(sceneLock) {
renderables = new ArrayList<Renderable>(currentScene);
overlay = new ArrayList<OverlayRenderable>(currentOverlay);
}
}
sharedContext.makeCurrent();
GL2GL3 gl = sharedContext.getGL().getGL2GL3(); // Just to clean up the code below
gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, target.getDrawFBO());
gl.glClearColor(0, 0, 0, 0);
gl.glViewport(0, 0, width, height);
gl.glEnable(GL2GL3.GL_DEPTH_TEST);
gl.glDepthFunc(GL2GL3.GL_LEQUAL);
allowDelayedTextures = false;
PerfInfo perfInfo = new PerfInfo();
// Okay, now actually render this thing...
renderScene(sharedContext, sharedContextID, renderables, overlay, message.cam,
width, height, null, message.viewID, perfInfo);
gl.glFinish();
gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, target.getBlitFBO());
gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, target.getDrawFBO());
gl.glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL2GL3.GL_COLOR_BUFFER_BIT, GL2GL3.GL_NEAREST);
gl.glBindTexture(GL2GL3.GL_TEXTURE_2D, target.getBlitTex());
IntBuffer pixels = target.getPixelBuffer();
gl.glGetTexImage(GL2GL3.GL_TEXTURE_2D, 0, GL2GL3.GL_BGRA, GL2GL3.GL_UNSIGNED_INT_8_8_8_8_REV, pixels);
gl.glBindTexture(GL2GL3.GL_TEXTURE_2D, 0);
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
for (int h = 0; h < height; ++h) {
// Set this one scan line at a time, in the opposite order as java is y down
img.setRGB(0, h, width, 1, pixels.array(), (height - 1 - h) * width, width);
}
message.result.setComplete(img);
// Clean up
gl.glBindFramebuffer(GL2GL3.GL_READ_FRAMEBUFFER, 0);
gl.glBindFramebuffer(GL2GL3.GL_DRAW_FRAMEBUFFER, 0);
if (isTempTarget) {
freeOffscreenTargetImp(target);
}
} catch (GLException ex){
message.result.setFailed(ex.getMessage());
} finally {
if (sharedContext.isCurrent())
sharedContext.release();
}
} // synchronized(_rendererLock)
}
/**
* Returns true if the current thread is this renderer's render thread
* @return
*/
public boolean isRenderThread() {
return (Thread.currentThread() == renderThread);
}
private static class PerfInfo {
public int objectsCulled = 0;
}
private static class TransSortable implements Comparable<TransSortable> {
public Renderable r;
public double dist;
@Override
public int compareTo(TransSortable o) {
// Sort such that largest distance sorts to front of list
// by reversing argument order in compare.
return Double.compare(o.dist, this.dist);
}
}
private void renderScene(GLContext context, int contextID,
List<Renderable> scene, List<OverlayRenderable> overlay,
Camera cam, int width, int height, Ray pickRay,
int viewID, PerfInfo perfInfo) {
final Vec4d viewDir = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
cam.getViewDir(viewDir);
final Vec3d temp = new Vec3d();
assert (drawContext == null);
drawContext = context;
GL2GL3 gl = drawContext.getGL().getGL2GL3(); // Just to clean up the code below
gl.glClear(GL2GL3.GL_COLOR_BUFFER_BIT
| GL2GL3.GL_DEPTH_BUFFER_BIT);
// The 'height' of a pixel 1 unit from the viewer
double unitPixelHeight = 2 * Math.tan(cam.getFOV()/2.0) / height;
ArrayList<TransSortable> transparents = new ArrayList<TransSortable>();
if (scene == null)
return;
for (Renderable r : scene) {
AABB bounds = r.getBoundsRef();
double dist = cam.distToBounds(bounds);
if (!r.renderForView(viewID, cam)) {
continue;
}
if (!cam.collides(bounds)) {
++perfInfo.objectsCulled;
continue;
}
double apparentSize = 2 * bounds.radius.mag3() / Math.abs(dist);
if (apparentSize < unitPixelHeight) {
// This object is too small to draw
++perfInfo.objectsCulled;
continue;
}
if (r.hasTransparent()) {
// Defer rendering of transparent objects
TransSortable ts = new TransSortable();
ts.r = r;
temp.set3(r.getBoundsRef().center);
temp.sub3(cam.getTransformRef().getTransRef());
ts.dist = temp.dot3(viewDir);
transparents.add(ts);
}
r.render(contextID, this, cam, pickRay);
}
gl.glEnable(GL2GL3.GL_BLEND);
gl.glDepthMask(false);
// Draw the skybox after
skybox.setTexture(cam.getInfoRef().skyboxTexture);
skybox.render(contextID, this, cam);
Collections.sort(transparents);
for (TransSortable ts : transparents) {
AABB bounds = ts.r.getBoundsRef();
if (!cam.collides(bounds)) {
++perfInfo.objectsCulled;
continue;
}
ts.r.renderTransparent(contextID, this, cam, pickRay);
}
gl.glDisable(GL2GL3.GL_BLEND);
gl.glDepthMask(true);
// Debug render AABBs
if (debugDrawAABBs())
{
Color4d yellow = new Color4d(1, 1, 0, 1.0d);
Color4d red = new Color4d(1, 0, 0, 1.0d);
for (Renderable r : scene) {
Color4d aabbColor = yellow;
if (pickRay != null && r.getBoundsRef().collisionDist(pickRay) > 0) {
aabbColor = red;
}
DebugUtils.renderAABB(contextID, this, r.getBoundsRef(), aabbColor, cam);
}
} // for renderables
// Now draw the overlay
gl.glDisable(GL2GL3.GL_DEPTH_TEST);
if (overlay != null) {
for (OverlayRenderable r : overlay) {
if (!r.renderForView(viewID, cam)) {
continue;
}
r.render(contextID, this, width, height, cam, pickRay);
}
}
gl.glEnable(GL2GL3.GL_DEPTH_TEST);
gl.glBindVertexArray(0);
drawContext = null;
}
public void usingVRAM(long bytes) {
usedVRAM += bytes;
}
// Below are functions inherited from GLAnimatorControl
// the interface is a bit of a mess and there's a lot here we don't need
@Override
public long getFPSStartTime() {
// Not supported
assert(false);
return 0;
}
@Override
public float getLastFPS() {
// Not supported
return 0;
}
@Override
public long getLastFPSPeriod() {
// Not supported
return 0;
}
@Override
public long getLastFPSUpdateTime() {
// Not supported
return 0;
}
@Override
public float getTotalFPS() {
// Not supported
return 0;
}
@Override
public long getTotalFPSDuration() {
// Not supported
return 0;
}
@Override
public int getTotalFPSFrames() {
// Not supported
return 0;
}
@Override
public int getUpdateFPSFrames() {
// Not supported
return 0;
}
@Override
public void resetFPSCounter() {
// Not supported
}
@Override
public void setUpdateFPSFrames(int arg0, PrintStream arg1) {
// Not supported
}
@Override
public void add(GLAutoDrawable arg0) {
// Not supported
assert(false);
}
@Override
public Thread getThread() {
return renderThread;
}
@Override
public boolean isAnimating() {
queueRedraw();
return true;
}
@Override
public boolean isPaused() {
synchronized (rendererLock) { // Make sure we aren't currently rendering
return isPaused;
}
}
@Override
public boolean isStarted() {
return true;
}
@Override
public boolean pause() {
synchronized(rendererLock) {
isPaused = true;
return true;
}
}
@Override
public void remove(GLAutoDrawable arg0) {
// Not supported
assert(false);
}
@Override
public boolean resume() {
isPaused = false;
queueRedraw();
return true;
}
@Override
public boolean start() {
// Not supported
assert(false);
return false;
}
@Override
public boolean stop() {
// Not supported
assert(false);
return false;
}
private void checkForIntelDriver() {
int res = sharedContext.makeCurrent();
assert (res == GLContext.CONTEXT_CURRENT);
GL2GL3 gl = sharedContext.getGL().getGL2GL3();
String vendorString = gl.glGetString(GL2GL3.GL_VENDOR).toLowerCase();
boolean intelDriver = vendorString.indexOf("intel") != -1;
if (intelDriver) {
safeGraphics = true;
}
sharedContext.release();
}
public void setDebugInfo(boolean showDebug) {
synchronized(settingsLock) {
showDebugInfo = showDebug;
}
}
@Override
public UncaughtExceptionHandler getUncaughtExceptionHandler() {
return null;
}
@Override
public void setUncaughtExceptionHandler(UncaughtExceptionHandler arg0) {}
}
|
package com.jedrzejewski.slisp;
import com.jedrzejewski.slisp.interpreter.Interpreter;
import com.jedrzejewski.slisp.lexer.Lexer;
import com.jedrzejewski.slisp.lispobjects.LispObject;
import com.jedrzejewski.slisp.parser.Parser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class REPL {
private Interpreter interpreter = new Interpreter();
public void run() {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(System.in));
while (true) {
System.out.print("> ");
String input = "";
try {
input = bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
try {
Lexer lexer = new Lexer(input);
Parser parser = new Parser(lexer);
LispObject lispObject = parser.parse();
if (lispObject != null) {
LispObject result = interpreter.eval(lispObject);
System.out.println(result);
}
} catch (BaseException e) {
System.out.println(e.getFullMessage());
} catch (Throwable e) {
System.out.println("Unhandled error");
}
}
}
}
|
package com.lagodiuk.ga;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
public class Environment<C extends Chromosome<C>, T extends Comparable<T>> {
private static final int ALL_PARENTAL_CHROMOSOMES = Integer.MAX_VALUE;
private class ChromosomesComparator implements Comparator<C> {
private final Map<C, T> cache = new WeakHashMap<C, T>();
@Override
public int compare(C chr1, C chr2) {
T fit1 = this.fit(chr1);
T fit2 = this.fit(chr2);
int ret = fit1.compareTo(fit2);
return ret;
}
private T fit(C chr) {
T fit = this.cache.get(chr);
if (fit == null) {
fit = Environment.this.fitnessFunc.calculate(chr);
this.cache.put(chr, fit);
}
return fit;
};
}
private final ChromosomesComparator chromosomesComparator;
private final Fitness<C, T> fitnessFunc;
private Population<C> population;
// listeners of genetic algorithm iterations (handle callback afterwards)
private final List<IterartionListener<C, T>> iterationListeners = new LinkedList<IterartionListener<C, T>>();
private boolean terminate = false;
// number of parental chromosomes, which survive (and move to new
// population)
private int parentChromosomesSurviveCount = ALL_PARENTAL_CHROMOSOMES;
private int iteration = 0;
public Environment(Population<C> population, Fitness<C, T> fitnessFunc) {
this.population = population;
this.fitnessFunc = fitnessFunc;
this.chromosomesComparator = new ChromosomesComparator();
}
public void iterate() {
int parentPopulationSize = this.population.getSize();
Population<C> newPopulation = new Population<C>();
for (int i = 0; (i < parentPopulationSize) && (i < this.parentChromosomesSurviveCount); i++) {
newPopulation.addChromosome(this.population.getChromosomeByIndex(i));
}
for (int i = 0; i < parentPopulationSize; i++) {
C chromosome = this.population.getChromosomeByIndex(i);
C mutated = chromosome.mutate();
C otherChromosome = this.population.getRandomChromosome();
List<C> crossovered = chromosome.crossover(otherChromosome);
newPopulation.addChromosome(mutated);
for (C c : crossovered) {
newPopulation.addChromosome(c);
}
}
newPopulation.sortPopulationByFitness(this.chromosomesComparator);
newPopulation.trim(parentPopulationSize);
this.population = newPopulation;
}
public void iterate(int count) {
this.terminate = false;
for (int i = 0; i < count; i++) {
if (this.terminate) {
break;
}
this.iterate();
this.iteration = i;
for (IterartionListener<C, T> l : this.iterationListeners) {
l.update(this);
}
}
}
public int getIteration() {
return this.iteration;
}
public void terminate() {
this.terminate = true;
}
public Population<C> getPopulation() {
return this.population;
}
public C getBest() {
return this.population.getChromosomeByIndex(0);
}
public C getWorst() {
return this.population.getChromosomeByIndex(this.population.getSize() - 1);
}
public void setParentChromosomesSurviveCount(int parentChromosomesCount) {
this.parentChromosomesSurviveCount = parentChromosomesCount;
}
public int getParentChromosomesSurviveCount() {
return this.parentChromosomesSurviveCount;
}
public void addIterationListener(IterartionListener<C, T> listener) {
this.iterationListeners.add(listener);
}
public T fitness(C chromosome) {
return this.fitnessFunc.calculate(chromosome);
}
}
|
package com.omnigon.bot;
import com.github.messenger4j.MessengerPlatform;
import com.github.messenger4j.send.MessengerSendClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
/**
* Entry point for the Spring Boot Application. <br>
*
* The Spring Context will be bootstrapped and the application will be configured properly.
* {@code MessengerSendClient} will be exposed as a singleton Spring Bean, so it is injectable.
*
* @author rajesh.kathgave
*/
@SpringBootApplication
public class Application {
private static final Logger logger = LoggerFactory.getLogger(Application.class);
/**
* Initializes the {@code MessengerSendClient}.
*
* @param pageAccessToken the generated {@code Page Access Token}
*/
@Bean
public MessengerSendClient messengerSendClient(@Value("a.pageAccessToken") String pageAccessToken) {
logger.debug("Initializing MessengerSendClient");
return MessengerPlatform.newSendClientBuilder(pageAccessToken).build();
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
|
// samskivert library - useful routines for java programs
package com.samskivert.net;
import java.io.IOException;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.event.TransportEvent;
import javax.mail.event.TransportListener;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.regex.Pattern;
import com.samskivert.util.StringUtil;
import static com.samskivert.net.Log.log;
/**
* The mail util class encapsulates some utility functions related to
* sending emails.
*/
public class MailUtil
{
/**
* Checks the supplied address against a regular expression that (for
* the most part) matches only valid email addresses. It's not
* perfect, but the omissions and inclusions are so obscure that we
* can't be bothered to worry about them.
*/
public static boolean isValidAddress (String address)
{
return _emailre.matcher(address).matches();
}
/**
* @return a normalized form of the specified email address
* (everything after the @ sign is lowercased).
*/
public static String normalizeAddress (String address)
{
// this algorithm is tolerant of bogus input: if address has no
// @ symbol it will cope.
int afterAt = address.indexOf('@') + 1;
return address.substring(0, afterAt) +
address.substring(afterAt).toLowerCase();
}
/**
* Delivers the supplied mail message using the machine's local mail
* SMTP server which must be listening on port 25.
*
* @exception IOException thrown if an error occurs delivering the
* email. See {@link Transport#send} for exceptions that can be thrown
* due to response from the SMTP server.
*/
public static void deliverMail (String recipient, String sender,
String subject, String body)
throws IOException
{
deliverMail(new String[] { recipient }, sender, subject, body);
}
/**
* Delivers the supplied mail message using the machine's local mail
* SMTP server which must be listening on port 25. If the
* <code>mail.smtp.host</code> system property is set, that will be
* used instead of localhost.
*
* @exception IOException thrown if an error occurs delivering the
* email. See {@link Transport#send} for exceptions that can be thrown
* due to response from the SMTP server.
*/
public static void deliverMail (String[] recipients, String sender,
String subject, String body)
throws IOException
{
deliverMail(recipients, sender, subject, body, null, null);
}
/**
* Delivers the supplied mail, with the specified additional headers.
*/
public static void deliverMail (String[] recipients, String sender,
String subject, String body,
String[] headers, String[] values)
throws IOException
{
if (recipients == null || recipients.length < 1) {
throw new IOException("Must specify one or more recipients.");
}
try {
MimeMessage message = createEmptyMessage();
int hcount = (headers == null) ? 0 : headers.length;
for (int ii = 0; ii < hcount; ii++) {
message.addHeader(headers[ii], values[ii]);
}
message.setText(body);
deliverMail(recipients, sender, subject, message);
} catch (Exception e) {
String errmsg = "Failure sending mail [from=" + sender +
", to=" + StringUtil.toString(recipients) +
", subject=" + subject + "]";
IOException ioe = new IOException(errmsg);
ioe.initCause(e);
throw ioe;
}
}
/**
* Delivers an already-formed message to the specified recipients. This
* message can be any mime type including multipart.
*/
public static void deliverMail (String[] recipients, String sender,
String subject, MimeMessage message)
throws IOException
{
checkCreateSession();
try {
message.setFrom(new InternetAddress(sender));
for (String recipient : recipients) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
}
if (subject != null) {
message.setSubject(subject);
}
message.saveChanges();
Address[] recips = message.getAllRecipients();
if (recips == null || recips.length == 0) {
log.info("Not sending mail to zero recipients",
"subject", subject, "message", message);
return;
}
Transport t = _defaultSession.getTransport(recips[0]);
try {
t.addTransportListener(_listener);
t.connect();
t.sendMessage(message, recips);
} finally {
t.close();
}
} catch (Exception e) {
String errmsg = "Failure sending mail [from=" + sender +
", to=" + StringUtil.toString(recipients) +
", subject=" + subject + "]";
IOException ioe = new IOException(errmsg);
ioe.initCause(e);
throw ioe;
}
}
/**
* Returns an initialized, but empty message.
*/
public static final MimeMessage createEmptyMessage ()
{
checkCreateSession();
return new MimeMessage(_defaultSession);
}
/**
* Create our default session if not already created.
*/
protected static void checkCreateSession ()
{
if (_defaultSession == null) { // no need to sync
Properties props = System.getProperties();
if (props.getProperty("mail.smtp.host") == null) {
props.put("mail.smtp.host", "localhost");
}
_defaultSession = Session.getDefaultInstance(props, null);
}
}
/** The session for sending our messages. */
protected static Session _defaultSession;
/** Listens to mail sending transport events. */
protected static TransportListener _listener = new TransportListener()
{
@Override public void messageDelivered (TransportEvent event) {
log.debug("messageDelivered: " + event);
}
@Override public void messageNotDelivered (TransportEvent event) {
logDeliveryError("messageNotDelivered", event);
}
@Override public void messagePartiallyDelivered (TransportEvent event) {
logDeliveryError("messagePartiallyDelivered", event);
}
/**
* Log the details of a delivery error.
*/
protected void logDeliveryError (String what, TransportEvent event)
{
log.warning(what + ": " + event,
"invalidAddresses", event.getInvalidAddresses(),
"validUnsentAddresses", event.getValidUnsentAddresses(),
"message", event.getMessage());
}
};
/** Originally formulated by lambert@nas.nasa.gov. */
protected static final String EMAIL_REGEX = "^([-A-Za-z0-9_.!%+]+@" +
"[-a-zA-Z0-9]+(\\.[-a-zA-Z0-9]+)*\\.[-a-zA-Z0-9]+)$";
/** A compiled version of our email regular expression. */
protected static final Pattern _emailre = Pattern.compile(EMAIL_REGEX);
}
|
package com.thindeck.dynamo;
import com.amazonaws.services.dynamodbv2.model.Select;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.jcabi.dynamo.Attributes;
import com.jcabi.dynamo.Conditions;
import com.jcabi.dynamo.Item;
import com.jcabi.dynamo.QueryValve;
import com.jcabi.dynamo.Region;
import com.thindeck.api.Repo;
import com.thindeck.api.Repos;
import java.io.IOException;
/**
* Dynamo implementation of {@link Repos}.
* @author Krzysztof Krason (Krzysztof.Krason@gmail.com)
* @version $Id$
*/
public final class DyRepos implements Repos {
/**
* Region we're in.
*/
private final transient Region region;
/**
* Constructor.
* @param rgn Region
*/
public DyRepos(final Region rgn) {
this.region = rgn;
}
@Override
public Repo get(final String name) {
return new DyRepo(
this.region.table(DyRepo.TBL)
.frame()
.through(
new QueryValve().withLimit(1)
)
.where(DyRepo.ATTR_NAME, name)
.iterator().next()
);
}
@Override
public Repo add(final String name) {
if (this.region.table(DyRepo.TBL)
.frame()
.through(
new QueryValve().withLimit(1)
)
.where(DyRepo.ATTR_NAME, Conditions.equalTo(name))
.iterator().hasNext()) {
throw new IllegalArgumentException();
}
try {
return new DyRepo(
this.region.table(DyRepo.TBL).put(
new Attributes()
.with(DyRepo.ATTR_NAME, name)
.with(DyRepo.ATTR_UPDATED, System.currentTimeMillis())
)
);
} catch (final IOException ex) {
throw new IllegalStateException(ex);
}
}
@Override
public Iterable<Repo> iterate() {
return Iterables.transform(
this.region.table(DyRepo.TBL)
.frame()
.through(
new QueryValve()
.withConsistentRead(false)
.withSelect(Select.ALL_PROJECTED_ATTRIBUTES)
),
new Function<Item, Repo>() {
@Override
public Repo apply(final Item input) {
return new DyRepo(input);
}
}
);
}
}
|
package com.vokal.db;
import android.content.*;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import java.lang.reflect.Field;
import java.util.*;
public class DatabaseHelper extends SQLiteOpenHelper {
protected static final ArrayList<String> TABLE_NAMES = new ArrayList<String>();
protected static final HashMap<Class, String> TABLE_MAP = new HashMap<Class, String>();
protected static final HashMap<String, Class> CLASS_MAP = new HashMap<String, Class>();
protected static final HashMap<Class, Uri> CONTENT_URI_MAP = new HashMap<Class, Uri>();
private static boolean isOpen;
public DatabaseHelper(Context aContext, String aName, int aVersion) {
super(aContext, aName, null, aVersion);
}
/*
* registers a table with authority, uses lowercase class name as table name(s)
*/
@SafeVarargs
public static void registerModel(Context aContext, Class<?>... aModelClass) {
if (aModelClass != null) {
for (Class<?> clazz : aModelClass) {
registerModel(aContext, clazz, clazz.getSimpleName().toLowerCase(Locale.getDefault()));
}
}
}
/*
* registers a table with provider with authority using specified table name
*/
public static void registerModel(Context aContext, Class<?> aModelClass, String aTableName) {
if (!TABLE_NAMES.contains(aTableName)) {
int matcher_index = TABLE_NAMES.size();
TABLE_NAMES.add(aTableName);
TABLE_MAP.put(aModelClass, aTableName);
CLASS_MAP.put(aTableName, aModelClass);
String authority = SimpleContentProvider.getContentAuthority(aContext);
Uri contentUri = Uri.parse(String.format("content://%s/%s", authority, aTableName));
CONTENT_URI_MAP.put(aModelClass, contentUri);
SimpleContentProvider.URI_MATCHER.addURI(authority, aTableName, matcher_index);
SimpleContentProvider.URI_ID_MATCHER.addURI(authority, aTableName, matcher_index);
}
}
public static Uri getContentUri(Class<?> aTableName) {
return CONTENT_URI_MAP.get(aTableName);
}
public static Uri getJoinedContentUri(Class<?> aTable1, String aColumn1,
Class<?> aTable2, String aColumn2) {
return getJoinedContentUri(aTable1, aColumn1, aTable2, aColumn2, null);
}
public static Uri getJoinedContentUri(Class<?> aTable1, String aColumn1,
Class<?> aTable2, String aColumn2,
Map<String, String> aProjMap) {
String auth = SimpleContentProvider.sContentAuthority;
if (auth == null) throw new IllegalStateException("Register tables with registerModel(..) methods first.");
String tblName1 = TABLE_MAP.get(aTable1);
if (tblName1 == null) throw new IllegalStateException("call registerModel() first for table " + aTable1);
String tblName2 = TABLE_MAP.get(aTable2);
if (tblName2 == null) throw new IllegalStateException("call registerModel() first for table " + aTable2);
String path = tblName1 + "_" + tblName2;
Uri contentUri = Uri.parse(String.format("content://%s/%s", auth, path));
int exists = SimpleContentProvider.URI_JOIN_MATCHER.match(contentUri);
if (exists != UriMatcher.NO_MATCH) {
return contentUri;
}
String table = String.format("%s LEFT OUTER JOIN %s ON (%s.%s = %s.%s)",
tblName1, tblName2,
tblName1, aColumn1,
tblName2, aColumn2);
int nextIndex = SimpleContentProvider.JOIN_TABLES.size();
SimpleContentProvider.JOIN_TABLES.add(table);
SimpleContentProvider.URI_JOIN_MATCHER.addURI(auth, path, nextIndex);
SimpleContentProvider.PROJECTION_MAPS.put(contentUri, aProjMap);
SimpleContentProvider.JOIN_DETAILS.add(new SimpleContentProvider.Join(contentUri,
tblName1, aColumn1,
tblName2, aColumn2));
return contentUri;
}
public static void setProjectionMap(Uri aContentUri, Map<String, String> aProjectionMap) {
SimpleContentProvider.PROJECTION_MAPS.put(aContentUri, aProjectionMap);
}
@Override
public void onCreate(SQLiteDatabase db) {
for (Map.Entry<Class, String> entry : TABLE_MAP.entrySet()) {
SQLiteTable.TableCreator creator = getTableCreator(entry.getKey());
if (creator != null) {
SQLiteTable.Builder builder = new SQLiteTable.Builder(entry.getValue());
SQLiteTable table = creator.buildTableSchema(builder);
if (table != null) {
db.execSQL(table.getCreateSQL());
if (table.getIndicesSQL() != null) {
for (String indexSQL : table.getIndicesSQL()) {
db.execSQL(indexSQL);
}
}
if (table.getSeedValues() != null) {
for (ContentValues values : table.getSeedValues()) {
db.insert(table.getTableName(), table.getNullHack(), values);
}
}
}
}
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Cursor tables = db.query("sqlite_master", null, "type='table'", null, null, null, null);
ArrayList<String> tableNames = new ArrayList<String>();
if (tables != null) {
for (int i = 0; i < tables.getCount(); i++) {
tables.moveToPosition(i);
tableNames.add(tables.getString(tables.getColumnIndex("name")));
}
}
for (Map.Entry<Class, String> entry : TABLE_MAP.entrySet()) {
SQLiteTable.TableCreator creator = getTableCreator(entry.getKey());
if (creator == null) continue;
SQLiteTable table = null;
String tableName = entry.getValue();
if (!tableNames.contains(tableName)) {
SQLiteTable.Builder builder = new SQLiteTable.Builder(tableName);
table = creator.buildTableSchema(builder);
if (table != null) {
db.execSQL(table.getCreateSQL());
}
} else {
SQLiteTable.Updater updater = new SQLiteTable.Updater(tableName);
table = creator.updateTableSchema(updater, oldVersion);
if (table != null) {
String[] updates = table.getUpdateSQL();
for (String updateSQL : updates) {
db.execSQL(updateSQL);
}
}
}
if (table != null) {
if (table.getIndicesSQL() != null) {
for (String indexSQL : table.getIndicesSQL()) {
db.execSQL(indexSQL);
}
}
if (table.getSeedValues() != null) {
for (ContentValues values : table.getSeedValues()) {
db.insert(table.getTableName(), table.getNullHack(), values);
}
}
}
}
}
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
isOpen = true;
}
static SQLiteTable.TableCreator getTableCreator(Class aModelClass) {
String className = aModelClass.getSimpleName();
SQLiteTable.TableCreator creator = null;
try {
Field f = aModelClass.getField("TABLE_CREATOR");
creator = (SQLiteTable.TableCreator) f.get(null);
} catch (ClassCastException e) {
throw new IllegalStateException("ADHD protocol requires the object called TABLE_CREATOR " +
"on class " + className + " to be a SQLiteTable.TableCreator");
} catch (NoSuchFieldException e) {
throw new IllegalStateException("ADHD protocol requires a SQLiteTable.TableCreator " +
"object called TABLE_CREATOR on class " + className);
} catch (IllegalAccessException e) {
throw new IllegalStateException("ADHD protocol requires the TABLE_CREATOR object " +
"to be accessible on class " + className);
} catch (NullPointerException e) {
throw new IllegalStateException("ADHD protocol requires the TABLE_CREATOR " +
"object to be static on class " + className);
}
return creator;
}
static List<String> getTableColumns(SQLiteDatabase aDatabase, String aTableName) {
List<String> columns = new ArrayList<String>();
if (isOpen && aDatabase != null) {
Cursor c = aDatabase.rawQuery(String.format("PRAGMA table_info(%s)", aTableName), null);
if (c.moveToFirst()) {
do {
columns.add(c.getString(1));
} while (c.moveToNext());
}
} else {
Class tableClass = CLASS_MAP.get(aTableName);
if (tableClass != null) {
SQLiteTable.TableCreator creator = getTableCreator(tableClass);
SQLiteTable create = creator.buildTableSchema(new SQLiteTable.Builder(aTableName));
for (SQLiteTable.Column col : create.getColumns()) {
columns.add(col.name);
}
SQLiteTable upgrade = creator.updateTableSchema(new SQLiteTable.Updater(aTableName),
SimpleContentProvider.sDatabaseVersion);
for (SQLiteTable.Column col : upgrade.getColumns()) {
columns.add(col.name);
}
}
}
return columns;
}
static Map<String,String> buildDefaultJoinMap(SimpleContentProvider.Join aJoin, SQLiteDatabase aDb) {
Map<String, String> projection = new HashMap<String, String>();
List<String> columns1 = getTableColumns(aDb, aJoin.table_1);
List<String> columns2 = getTableColumns(aDb, aJoin.table_2);
projection.put("_id", aJoin.table_1.concat("._id as _id"));
for (String col : columns1) {
projection.put(String.format("%s_%s", aJoin.table_1, col),
String.format("%s.%s AS %s_%s", aJoin.table_1, col, aJoin.table_1, col));
}
for (String col : columns2) {
projection.put(String.format("%s_%s", aJoin.table_2, col),
String.format("%s.%s AS %s_%s", aJoin.table_2, col, aJoin.table_2, col));
}
return projection;
}
}
|
package com.yiji.falcon.agent;
import com.yiji.falcon.agent.config.AgentConfiguration;
import com.yiji.falcon.agent.jmx.JMXConnection;
import com.yiji.falcon.agent.plugins.metrics.SNMPV3MetricsValue;
import com.yiji.falcon.agent.plugins.util.PluginExecute;
import com.yiji.falcon.agent.plugins.util.PluginLibraryHelper;
import com.yiji.falcon.agent.util.*;
import com.yiji.falcon.agent.vo.HttpResult;
import com.yiji.falcon.agent.watcher.ConfDirWatcher;
import com.yiji.falcon.agent.watcher.PluginPropertiesWatcher;
import com.yiji.falcon.agent.web.HttpServer;
import org.apache.log4j.PropertyConfigurator;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.DirectSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
/*
* :
* guqiu@yiji.com 2016-06-22 17:48
*/
/**
* agent
* @author guqiu@yiji.com
*/
public class Agent extends Thread{
public static final PrintStream OUT = System.out;
public static final PrintStream ERR = System.err;
public static int falconAgentPid = 0;
private static final Logger log = LoggerFactory.getLogger(Agent.class);
private ServerSocketChannel serverSocketChannel;
private HttpServer httpServer = null;
private static final Charset charset = Charset.forName("UTF-8");
@Override
public void run() {
//Agent
Runtime.getRuntime().addShutdownHook(new Thread(){
@Override
public void run() {
stopAgent();
}
});
try {
this.agentWebServerStart(AgentConfiguration.INSTANCE.getAgentWebPort());
this.agentServerStart(AgentConfiguration.INSTANCE.getAgentPort());
} catch (IOException e) {
log.error("Agent",e);
}
}
/**
* web
* @param port
*/
private void agentWebServerStart(int port){
if(AgentConfiguration.INSTANCE.isWebEnable() && HttpServer.status == 0){
httpServer = new HttpServer(port);
httpServer.setName("agent web server thread");
httpServer.start();
}
}
/**
* agent
* @param port
* @throws IOException
*/
private void agentServerStart(int port) throws IOException {
String agentPushUrl = AgentConfiguration.INSTANCE.getAgentPushUrl();
if(agentPushUrl.contains("127.0.0.1") ||
agentPushUrl.contains("localhost") ||
agentPushUrl.contains("0.0.0.0")){
log.info(" Falcon Agent");
String falconAgentConfFileName = "agent.cfg.json";
String falconAgentConfFile = AgentConfiguration.INSTANCE.getFalconConfDir() + File.separator + falconAgentConfFileName;
if(!FileUtil.isExist(falconAgentConfFile)){
log.error("Agent - Falcon Agent:{} :{} ,",falconAgentConfFileName,AgentConfiguration.INSTANCE.getFalconConfDir());
System.exit(0);
}
String falconAgentConfContent = FileUtil.getTextFileContent(falconAgentConfFile);
if(StringUtils.isEmpty(falconAgentConfContent)){
log.error("Agent - Falcon Agent:{} ",falconAgentConfFile);
System.exit(0);
}
String falconAgentDir = AgentConfiguration.INSTANCE.getFalconDir() + File.separator + "agent";
if(FileUtil.writeTextToTextFile(falconAgentConfContent,falconAgentDir,"cfg.json",false)){
String common = falconAgentDir + File.separator + "control start";
CommandUtilForUnix.ExecuteResult executeResult = CommandUtilForUnix.execWithTimeOut(common,10, TimeUnit.SECONDS);
log.info(" Falcon Agent : {}",executeResult.msg);
String msg = executeResult.msg.trim();
if(msg.contains("falcon-agent started")){
falconAgentPid = Integer.parseInt(msg.substring(
msg.indexOf("pid=") + 4
));
log.info("Falcon Agent ,ID : {}",falconAgentPid);
}else if(msg.contains("falcon-agent now is running already")){
falconAgentPid = Integer.parseInt(msg.substring(
msg.indexOf("pid=") + 4
));
log.info("Falcon Agent ,,ID : {}",falconAgentPid);
}else{
log.error("Agent - Falcon Agent ");
System.exit(0);
}
}else{
log.error("Agent - Falcon Agent,");
System.exit(0);
}
}
if(serverSocketChannel == null){
log.info("Agent");
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().setReuseAddress(true);
}
log.info("Agent:" + port);
serverSocketChannel.socket().bind(new InetSocketAddress(port));
Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
log.error(" {} ",t.getName(),e);
});
work();
for(;;){
try {
SocketChannel socketChannel = serverSocketChannel.accept();
ByteBuffer buffer = ByteBuffer.allocate(27);
socketChannel.read(buffer);
String receive = new String(buffer.array());
if("I am is Falcon Agent Client".equals(receive)){
log.info("" + socketChannel.toString());
Thread talk = new Talk(socketChannel,this);
talk.setName(socketChannel.toString());
talk.start();
}else{
//Agent Client
socketChannel.close();
}
} catch (IOException e) {
break;
}
}
}
void shutdown() {
log.info("");
if(httpServer != null){
try {
log.info("web");
HttpResult response = HttpUtil.get(String.format("http://127.0.0.1:%d/__SHUTDOWN__",AgentConfiguration.INSTANCE.getAgentWebPort()));
log.info("web:{}",response);
} catch (IOException e) {
log.error("web",e);
}
}
try {
serverSocketChannel.close();
} catch (IOException e) {
log.error("serverSocketChannel.close()",e);
}
log.info("
SchedulerFactory sf = DirectSchedulerFactory.getInstance();
//Scheduler
Collection<Scheduler> schedulers;
try {
schedulers = sf.getAllSchedulers();
for (Scheduler scheduler : schedulers) {
try {
log.info("scheduler" + scheduler.getSchedulerName());
scheduler.shutdown(true);
} catch (SchedulerException e) {
log.warn("",e);
try {
log.warn("scheduler" + scheduler.getSchedulerName() + "\nstarted:" + scheduler.isStarted() +
" shutdown:" + scheduler.isShutdown());
} catch (SchedulerException ignored) {
}
}
}
} catch (SchedulerException e) {
log.warn("Schedulers" + e);
log.error("Schedulers " + e.getMessage());
}
log.info("");
log.info("JMX");
JMXConnection.close();
log.info("SNMP");
SNMPV3MetricsValue.closeAllSession();
String agentPushUrl = AgentConfiguration.INSTANCE.getAgentPushUrl();
if(agentPushUrl.contains("127.0.0.1") ||
agentPushUrl.contains("localhost") ||
agentPushUrl.contains("0.0.0.0")){
try {
String falconAgentDir = AgentConfiguration.INSTANCE.getFalconDir() + File.separator + "agent";
String common = falconAgentDir + File.separator + "control stop";
CommandUtilForUnix.ExecuteResult executeResult = CommandUtilForUnix.execWithTimeOut(common,10,TimeUnit.SECONDS);
if(executeResult.isSuccess){
log.info(" Falcon Agent : {}",executeResult.msg);
if(executeResult.msg.contains("falcon-agent stoped")){
log.info("Falcon Agent ");
}
}else{
log.error("Falcon Agent ,,Falcon Agent ID : {}",falconAgentPid);
}
} catch (IOException e) {
log.error("Falcon Agent ,,Falcon Agent ID : {}",falconAgentPid,e);
}
}
log.info("");
ExecuteThreadUtil.shutdown();
log.info("");
System.exit(0);
}
private void work(){
try {
new PluginLibraryHelper().register();
PluginExecute.start();
Thread pluginWatcher = new PluginPropertiesWatcher(AgentConfiguration.INSTANCE.getPluginConfPath());
pluginWatcher.setName("pluginDirWatcher");
pluginWatcher.setDaemon(true);
Thread confWatcher = new ConfDirWatcher(AgentConfiguration.INSTANCE.getAgentConfPath().substring(0,AgentConfiguration.INSTANCE.getAgentConfPath().lastIndexOf("/")));
confWatcher.setName("confDirWatcher");
confWatcher.setDaemon(true);
pluginWatcher.start();
confWatcher.start();
} catch (Exception e) {
log.error("Agent",e);
System.exit(0);
}
}
static String decode(ByteBuffer buffer){
CharBuffer charBuffer = charset.decode(buffer);
return charBuffer.toString();
}
static ByteBuffer encode(String str){
return charset.encode(str);
}
public static void main(String[] args){
String errorMsg = "Syntax: program < start | stop | status >";
if(args.length < 1 ||
!("start".equals(args[0]) ||
"stop".equals(args[0]) ||
"status".equals(args[0])
))
{
ERR.println(errorMsg);
return;
}
switch (args[0]){
case "start":
PropertyConfigurator.configure(AgentConfiguration.INSTANCE.getLog4JConfPath());
Thread main = new Agent();
main.setName("FalconAgent");
main.start();
break;
case "stop":
stopAgent();
break;
case "status":
statusAgent();
break;
default:
OUT.println(errorMsg);
}
}
private static void statusAgent(){
try {
Client client = new Client();
client.start(AgentConfiguration.INSTANCE.getAgentPort());
OUT.println("Agent Started On Port " + AgentConfiguration.INSTANCE.getAgentPort());
client.closeClient();
} catch (IOException e) {
exception(e);
OUT.println("Connection refused ! Agent Not Start");
}
}
private static void stopAgent(){
try {
Client client = new Client();
client.start(AgentConfiguration.INSTANCE.getAgentPort());
client.sendCloseCommend();
client.talk();
} catch (IOException e) {
exception(e);
OUT.println("Connection refused ! Agent Not Start");
}
}
private static void exception(Exception e){
if(e instanceof java.net.ConnectException &&
"Connection refused".equals(e.getMessage())){
return;
}
e.printStackTrace();
}
}
|
package com.yunpian.sdk.api;
import com.google.gson.reflect.TypeToken;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.constant.Code;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.Sign;
import com.yunpian.sdk.model.SignRecord;
import com.yunpian.sdk.util.JsonUtil;
import org.apache.http.NameValuePair;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class SignApi extends YunpianApi {
public static final String NAME = "sign";
@Override
public String name() {
return NAME;
}
@Override
public void init(YunpianClient clnt) {
super.init(clnt);
host(clnt.getConf().getConf(YP_SIGN_HOST, "https://sms.yunpian.com"));
}
public Result<Sign> add(Map<String, String> param) {
Result<Sign> r = new Result<>();
List<NameValuePair> list = param2pair(param, r, APIKEY, SIGN);
if (r.getCode() != Code.OK)
return r;
String data = format2Form(list);
MapResultHandler<Sign> h = new MapResultHandler<Sign>() {
@Override
public Sign data(Map<String, String> rsp) {
switch (version()) {
case VERSION_V2:
return JsonUtil.fromJson(rsp.get(SIGN), Sign.class);
}
return null;
}
@Override
public Integer code(Map<String, String> rsp) {
return YunpianApi.code(rsp, SignApi.this.version());
}
};
try {
return path("add.json").post(uri(), data, h, r);
} catch (Exception e) {
return h.catchExceptoin(e, r);
}
}
public Result<Sign> update(Map<String, String> param) {
Result<Sign> r = new Result<>();
List<NameValuePair> list = param2pair(param, r, APIKEY, OLD_SIGN);
if (r.getCode() != Code.OK)
return r;
String data = format2Form(list);
MapResultHandler<Sign> h = new MapResultHandler<Sign>() {
@Override
public Sign data(Map<String, String> rsp) {
switch (version()) {
case VERSION_V2:
return JsonUtil.fromJson(rsp.get(SIGN), Sign.class);
}
return null;
}
@Override
public Integer code(Map<String, String> rsp) {
return YunpianApi.code(rsp, SignApi.this.version());
}
};
try {
return path("update.json").post(uri(), data, h, r);
} catch (Exception e) {
return h.catchExceptoin(e, r);
}
}
/**
* <h1>API</h1>
* <p>
* <p>
*
* </p>
* <p>
* apikey String 9b11127a9701975c734b8aee81ee3526
* </p>
* <p>
* id Long id 9527
* </p>
* <p>
* sign String
* </p>
* <p>
* page_num Integer 1 1
* </p>
* <p>
* page_size Integer 0 20
* </p>
*
* @param param sign notify page_num page_size
* @return
*/
public Result<SignRecord> get(Map<String, String> param) {
Result<SignRecord> r = new Result<>();
List<Sign> signList = new ArrayList<>();
List<NameValuePair> list = param2pair(param, r, APIKEY);
if (r.getCode() != Code.OK)
return r;
String data = format2Form(list);
MapResultHandler<SignRecord> h = new MapResultHandler<SignRecord>() {
@Override
public SignRecord data(Map<String, String> rsp) {
switch (version()) {
case VERSION_V2:
TypeToken<List<Sign>> token = new TypeToken<List<Sign>>() {
};
List<Sign> signs = JsonUtil.fromJson(rsp.get(SIGN), token.getType());
int total = Integer.valueOf(rsp.get(TOTAL));
SignRecord signRecord = new SignRecord();
signRecord.setSign(signs);
signRecord.setTotal(total);
return signRecord;
}
return null;
}
@Override
public Integer code(Map<String, String> rsp) {
return YunpianApi.code(rsp, SignApi.this.version());
}
};
try {
return path("get.json").post(uri(), data, h, r);
} catch (Exception e) {
return h.catchExceptoin(e, r);
}
}
}
|
package com.zenplanner.sql;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.*;
public class FormMain extends JFrame {
private JPanel panel1;
private JTextField tbSrcServer;
private JTextField tbSrcDb;
private JTextField tbSrcUsername;
private JPasswordField tbSrcPassword;
private JTextField tbDstServer;
private JTextField tbDstDb;
private JTextField tbDstUsername;
private JProgressBar pbMain;
private JButton btnGo;
private JPasswordField tbDstPassword;
private JTextField tbFilterColumn;
private JTextField tbFilterValue;
private JTextArea tbIgnore;
private JLabel lblCurrentTable;
private JLabel lblCurrentRow;
private static final String conTemplate = "jdbc:jtds:sqlserver://%s:1433/%s;user=%s;password=%s";
private final DbComparator comp = new DbComparator();
public FormMain() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(panel1);
setSize(800, 600);
setVisible(true);
pack();
Timer timer = new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
pbMain.setMaximum(comp.getRowCount());
pbMain.setValue(comp.getCurrentRow());
lblCurrentTable.setText(comp.getCurrentTableName());
lblCurrentRow.setText("" + comp.getCurrentRow() + " / " + comp.getRowCount());
}
});
comp.addListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
if(comp.getCurrentTable() > comp.getTableCount()) {
timer.stop();
lblCurrentTable.setText("");
lblCurrentRow.setText("");
btnGo.setEnabled(true);
pbMain.setValue(0);
JOptionPane.showMessageDialog(null, "Synchronization complete!");
}
}
});
}
});
btnGo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
btnGo.setEnabled(false);
new Thread(new Runnable() {
@Override
public void run() {
try {
timer.start();
saveProps();
sync();
} catch (Exception ex) {
throw new RuntimeException("Error syncing DBs!", ex); // TODO: Pop-up
}
}
}).start();
}
});
loadProps();
}
private void sync() throws Exception {
Map<String,Object> filters = new HashMap<String,Object>();
filters.put(tbFilterColumn.getText().toLowerCase(), tbFilterValue.getText());
String srcCon = String.format(conTemplate, tbSrcServer.getText(), tbSrcDb.getText(),
tbSrcUsername.getText(), tbSrcPassword.getText());
String dstCon = String.format(conTemplate, tbDstServer.getText(), tbDstDb.getText(),
tbDstUsername.getText(), tbDstPassword.getText());
java.util.List<String> ignoreTables = Arrays.asList(tbIgnore.getText().split(","));
try (Connection scon = DriverManager.getConnection(srcCon)) {
try (Connection dcon = DriverManager.getConnection(dstCon)) {
comp.synchronize(scon, dcon, filters, ignoreTables);
}
}
}
private File getPropFile() {
File dir = new File(FormMain.class.getProtectionDomain().getCodeSource().getLocation().getPath());
if("classes".equals(dir.getName())) {
dir = dir.getParentFile();
}
File f = new File(dir, "dbsync.properties");
return f;
}
private void loadProps() {
try {
Properties props = new Properties();
try(InputStream is = new FileInputStream( getPropFile() )) {
props.load( is );
tbSrcServer.setText(props.getProperty("SourceServer"));
tbSrcDb.setText(props.getProperty("SourceDb"));
tbSrcUsername.setText(props.getProperty("SourceUsername"));
tbSrcPassword.setText(props.getProperty("SourcePassword"));
tbDstServer.setText(props.getProperty("DestServer"));
tbDstDb.setText(props.getProperty("DestDb"));
tbDstUsername.setText(props.getProperty("DestUsername"));
tbDstPassword.setText(props.getProperty("DestPassword"));
tbFilterColumn.setText(props.getProperty("FilterColumn"));
tbFilterValue.setText(props.getProperty("FilterValue"));
tbIgnore.setText(props.getProperty("IgnoreTables"));
}
} catch (Exception ex) {
ex.printStackTrace();
// If there's an error, they just don't get pre-loaded properties
}
}
private void saveProps() throws Exception {
Properties props = new Properties();
props.setProperty("SourceServer", tbSrcServer.getText());
props.setProperty("SourceDb", tbSrcDb.getText());
props.setProperty("SourceUsername", tbSrcUsername.getText());
props.setProperty("SourcePassword", tbSrcPassword.getText());
props.setProperty("DestServer", tbDstServer.getText());
props.setProperty("DestDb", tbDstDb.getText());
props.setProperty("DestUsername", tbDstUsername.getText());
props.setProperty("DestPassword", tbDstPassword.getText());
props.setProperty("FilterColumn", tbFilterColumn.getText());
props.setProperty("FilterValue", tbFilterValue.getText());
props.setProperty("IgnoreTables", tbIgnore.getText());
try(OutputStream out = new FileOutputStream( getPropFile() )) {
props.store(out, "dbsync properties");
}
}
}
|
package common.base.utils;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.support.annotation.RawRes;
import android.support.annotation.WorkerThread;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ImageUtil {
// public static void loadImage(Context context, String picUrl, int newWidth, int newHeight, Drawable holderDrawable,
// Drawable errorDrawable, ImageView targetIv
// , Callback callback) {
// RequestCreator loadRequest = loadImageRequest(context, picUrl,null,0);
// if (newWidth > 0 && newHeight > 0) {
// loadRequest.resize(newWidth, newHeight);
// loadRequest.centerCrop();
// else{
//// loadRequest.fit();
// if (holderDrawable != null) {
// loadRequest.placeholder(holderDrawable);
// else{
// loadRequest.noPlaceholder();
// if (errorDrawable != null) {
// loadRequest.error(errorDrawable);
// loadRequest.noFade();
// loadRequest.into(targetIv, callback);
public static void loadImage(Context context, String picUrl, int newWidth, int newHeight, Drawable holderDrawable,
Drawable errorDrawable, ImageView targetIv
, RequestListener callback) {
RequestBuilder requestBuilder = loadImageRequest(context, picUrl);
RequestOptions options = new RequestOptions();
if (newWidth > 0 && newHeight > 0) {
options.override(newWidth,newHeight).centerCrop();
}
else{
// loadRequest.fit();
}
if (holderDrawable != null) {
options.placeholder(holderDrawable);
}
else{
// loadRequest.noPlaceholder();
}
if (errorDrawable != null) {
options.error(errorDrawable);
}
options.dontAnimate();
if (callback != null) {
requestBuilder.listener(callback);
}
requestBuilder.apply(options)
.into(targetIv);
}
private static void throwCannotException(String reason) {
throw new IllegalArgumentException("no " + reason + ",can't load image pic...");
}
// private static RequestCreator loadImageRequest(Context context, String picUrl, File localPicFile,int localPicResId) {
// if (Util.isEmpty(picUrl) && null == localPicFile && localPicResId <= 0) {
// throwCannotException("pic path ");
// Picasso picasso = Picasso.with(context);
// if (!Util.isEmpty(picUrl)) {
// return picasso.load(picUrl);
// if (localPicFile != null) {
// return picasso.load(localPicFile);
// return picasso.load(localPicResId);
// public static RequestCreator loadImageRequest(Context context, String picUrlOrPath) {
// if (Util.isEmpty(picUrlOrPath)) {
// throwCannotException("picUrl");
// return loadImageRequest(context, picUrlOrPath, null, 0);
// public static RequestCreator loadImageRequest(Context context, File localPicFile) {
// if (null == localPicFile) {
// throwCannotException("pic file");
// return loadImageRequest(context, null, localPicFile, 0);
// public static RequestCreator loadImageRequest(Context context, int localPicResId) {
// if (localPicResId <= 0) {
// throwCannotException("valid local pic res id");
// return loadImageRequest(context, null, null, localPicResId);
public static void loadImage(Context context, String picUrl, int newWidth, int newHeight, int holderDrawableResId,
int errorDrawableResId, ImageView targetIv
, RequestListener callback){
Resources res = context.getResources();
Drawable holderPic = null;
if (holderDrawableResId > 0) {
holderPic = res.getDrawable(holderDrawableResId);
}
Drawable errorDrawable = null;
if (errorDrawableResId > 0) {
errorDrawable = res.getDrawable(errorDrawableResId);
}
loadImage(context, picUrl, newWidth, newHeight,holderPic,
errorDrawable,
targetIv, callback);
}
public static void loadImage(Context context,String picUrl,int holderDrawableResId,
int errorDrawableResId, ImageView targetIv
, RequestListener callback){
loadImage(context,picUrl,0,0,holderDrawableResId,errorDrawableResId,targetIv,callback);
}
public static void loadImage(Context context, String picUrl, int holderDrawableResId,
int errorDrawableResId, ImageView targetIv) {
loadImage(context,picUrl,holderDrawableResId,errorDrawableResId,targetIv,null);
}
public static void loadImage(Context context, String picUrl, ImageView targetIv, RequestListener callback) {
loadImage(context, picUrl, 0, 0, targetIv, callback);
}
public static void loadImage(Context context, String picUrl, ImageView targetIv) {
loadImage(context, picUrl, targetIv,null);
}
public static void loadResizeImage(Context context, String picUrl, int resizeW, int resizeH, ImageView targetIv) {
loadImage(context, picUrl, resizeW, resizeH, null, null, targetIv, null);
}
public static void loadImage(Context context, Object model) {
Glide.with(context).load(model);
}
public static RequestBuilder<Drawable> loadImageRequest(Context context, Object model) {
return Glide.with(context).load(model);
}
public static RequestBuilder<Bitmap> loadBitmapeRequest(Context context, Object model) {
return Glide.with(context).asBitmap().load(model);
}
public static void loadBitmap(Context context, Object model, Target target) {
Glide.with(context).asBitmap().load(model).into(target);
}
public static void loadGif(Context context, int gifDrawableResId, ImageView ivTarget, int needPlayTime) {
loadGifModel(context, gifDrawableResId,0, ivTarget, needPlayTime);
}
public static void loadGifModel(Context context, Object mayBeGifModel, @RawRes @DrawableRes int defHolderPicRes, ImageView ivTarget, final int needPlayTime) {
if (mayBeGifModel == null) {
return;
}
RequestBuilder<GifDrawable> gifDrawableBuilder = null;
try {
gifDrawableBuilder = Glide.with(context).asGif()
;
} catch (Exception e) {
gifDrawableBuilder = null;
e.printStackTrace();
}
if (gifDrawableBuilder == null) {
return;
}
if (defHolderPicRes != 0) {
gifDrawableBuilder.placeholder(defHolderPicRes)
.error(defHolderPicRes);
}
RequestListener<GifDrawable> loadGifDrawableListener = null;
if (needPlayTime >= 1) {
loadGifDrawableListener = new RequestListener<GifDrawable>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<GifDrawable> target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(GifDrawable resource, Object model, Target<GifDrawable> target, DataSource dataSource, boolean isFirstResource) {
resource.setLoopCount(needPlayTime);
return false;
}
};
gifDrawableBuilder.listener(loadGifDrawableListener);
}
if (mayBeGifModel instanceof Integer) {//:load(Bitmap xx);load(byte[]xxx);loadDrawable(Drawable xx);
Integer gifResId = (Integer) mayBeGifModel;
if (gifResId != 0) {
gifDrawableBuilder.load(gifResId);
}
else {
return;
}
}
else{
gifDrawableBuilder.load(mayBeGifModel);
}
gifDrawableBuilder.into(ivTarget);
}
public static <AsX> void loadImageIntoTarget(Context context, String imageDataUrl, int defPicRes, Class<AsX> resourseClassType, Target<AsX> target) {
Glide.with(context)
.as(resourseClassType)
.load(imageDataUrl)
.error(defPicRes)
.placeholder(defPicRes)
.into(target)
;
}
public static ColorDrawable createDefHolderColorDrawable(int theColor) {
if (theColor <= 0) {
theColor = Color.parseColor("#555555");
}
return new ColorDrawable(theColor);
}
public static void loadImageOrGif(Context context, String imgUrl, @DrawableRes @RawRes int defPicRes, ImageView imageView,int gifPlayTimes) {
if (Util.isEmpty(imgUrl)) {
if (imageView != null) {
imageView.setImageResource(defPicRes);
}
return;
}
if (imgUrl.endsWith(".gif")) {
loadGifModel(context,imgUrl,defPicRes,imageView,gifPlayTimes);
}
else {
loadImage(context,imgUrl,defPicRes,defPicRes,imageView);
}
}
//and so on
private static final int BLUR_RADIUS = 50;
@Nullable
public static Bitmap blur(Bitmap sentBitmap) {
try {
return blur(sentBitmap, BLUR_RADIUS);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static Bitmap blur(Bitmap sentBitmap, int radius) {
Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
if (radius < 1) {
return null;
}
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int[] pix = new int[w * h];
bitmap.getPixels(pix, 0, w, 0, 0, w, h);
int wm = w - 1;
int hm = h - 1;
int wh = w * h;
int div = radius + radius + 1;
int r[] = new int[wh];
int g[] = new int[wh];
int b[] = new int[wh];
int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
int vmin[] = new int[Math.max(w, h)];
int divsum = (div + 1) >> 1;
divsum *= divsum;
int dv[] = new int[256 * divsum];
for (i = 0; i < 256 * divsum; i++) {
dv[i] = (i / divsum);
}
yw = yi = 0;
int[][] stack = new int[div][3];
int stackpointer;
int stackstart;
int[] sir;
int rbs;
int r1 = radius + 1;
int routsum, goutsum, boutsum;
int rinsum, ginsum, binsum;
for (y = 0; y < h; y++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
for (i = -radius; i <= radius; i++) {
p = pix[yi + Math.min(wm, Math.max(i, 0))];
sir = stack[i + radius];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = (p & 0x0000ff);
rbs = r1 - Math.abs(i);
rsum += sir[0] * rbs;
gsum += sir[1] * rbs;
bsum += sir[2] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
} else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
}
stackpointer = radius;
for (x = 0; x < w; x++) {
r[yi] = dv[rsum];
g[yi] = dv[gsum];
b[yi] = dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (y == 0) {
vmin[x] = Math.min(x + radius + 1, wm);
}
p = pix[yw + vmin[x]];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = (p & 0x0000ff);
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[(stackpointer) % div];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi++;
}
yw += w;
}
for (x = 0; x < w; x++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
yp = -radius * w;
for (i = -radius; i <= radius; i++) {
yi = Math.max(0, yp) + x;
sir = stack[i + radius];
sir[0] = r[yi];
sir[1] = g[yi];
sir[2] = b[yi];
rbs = r1 - Math.abs(i);
rsum += r[yi] * rbs;
gsum += g[yi] * rbs;
bsum += b[yi] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
} else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
if (i < hm) {
yp += w;
}
}
yi = x;
stackpointer = radius;
for (y = 0; y < h; y++) {
// Preserve alpha channel: ( 0xff000000 & pix[yi] )
pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (x == 0) {
vmin[y] = Math.min(y + r1, hm) * w;
}
p = x + vmin[y];
sir[0] = r[p];
sir[1] = g[p];
sir[2] = b[p];
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[stackpointer];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi += w;
}
}
bitmap.setPixels(pix, 0, w, 0, 0, w, h);
return bitmap;
}
public static Bitmap resizeImage(Bitmap source, int w, int h) {
int width = source.getWidth();
int height = source.getHeight();
float scaleWidth = ((float) w) / width;
float scaleHeight = ((float) h) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
return Bitmap.createBitmap(source, 0, 0, width, height, matrix, true);
}
public static Bitmap createCircleImage(Bitmap source) {
int length = Math.min(source.getWidth(), source.getHeight());
Paint paint = new Paint();
paint.setAntiAlias(true);
Bitmap target = Bitmap.createBitmap(length, length, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(target);
canvas.drawCircle(length / 2, length / 2, length / 2, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(source, 0, 0, paint);
return target;
}
// /**
// * Glide
// *
// * @param context Context
// * @param fileUrl
// * @param targetLocalFilePath
// * @return file
// */
// private static File download(Context context, String fileUrl,String targetLocalFilePath) {
// if (fileUrl == null || "".equals(fileUrl.trim())) {
// return null;
// File targetFile = null;
// try {
// targetFile = Glide.with(context).download(fileUrl).submit().get();
// } catch (Exception e) {
// e.printStackTrace();
// if (targetLocalFilePath != null && !"".equals(targetLocalFilePath.trim())) {//
// boolean isValidFile = targetFile != null && targetFile.length() > 1;
// if (isValidFile) {
// String downloadFileAbsPath = targetFile.getAbsolutePath();
// if (!targetLocalFilePath.equals(downloadFileAbsPath)) {//
// File targetLocalFile = new File(targetLocalFilePath);
// boolean needCopyToTargetPath = true;
// boolean copySuc = copyFile(targetFile, targetLocalFile);
// if (copySuc) {
// targetFile.delete();
// targetFile = targetLocalFile;
// return targetFile;
public static boolean copyFile(File srcFile, File targetFile) {
if (srcFile == null || srcFile.length() < 1 || targetFile == null) {
return false;
}
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(targetFile, true);
byte[] readBuf = new byte[1024];
int hasReadLen = -1;
while ((hasReadLen = fis.read(readBuf)) != -1) {
byte[] readDatas = new byte[hasReadLen];
System.arraycopy(readBuf, 0, readDatas, 0, hasReadLen);
fos.write(readDatas);
}
fos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}
@WorkerThread
public static File downloadAndCopyToTarget(Context context, String fileUrl, String targetDirPath, String targetFileName, boolean deleteSrcFile) {
File downloadResultFile = download(context, fileUrl);
if (downloadResultFile == null) {
return null;
}
boolean isTargetDirNull = isTextEmpty(targetDirPath);
boolean isTargetFileNameNull = isTextEmpty(targetFileName);
if (!isTargetDirNull) {
boolean isDownloadFileValid = downloadResultFile.length() > 1;
if (isDownloadFileValid) {
String downloadedFileName = downloadResultFile.getName();
CommonLog.e("info", "-->downloadAndCopyToTarget() downloadedFileName = " + downloadedFileName);
String targetWholeFilePath = appendSeparator(targetDirPath);
File targetFile = null;
if (isTargetFileNameNull) {
targetWholeFilePath += downloadedFileName;
targetFile = new File(targetWholeFilePath);
if (targetFile.exists() && targetFile.length() > 1) {
CommonLog.e("info", "-->downloadAndCopyToTarget() not need copy file...");
return targetFile;
}
}
else{
targetWholeFilePath += targetFileName;
}
targetFile = new File(targetWholeFilePath);
boolean isCopySuc = copyFile(downloadResultFile, targetFile);
if (isCopySuc) {
if (deleteSrcFile) {
downloadResultFile.delete();
}
downloadResultFile = targetFile;
}
}
}
return downloadResultFile;
}
public static File download(Context context, String fileUrl) {
if (fileUrl == null || "".equals(fileUrl.trim())) {
return null;
}
File targetFile = null;
try {
targetFile = Glide.with(context).download(fileUrl).submit().get();
} catch (Exception e) {
e.printStackTrace();
}
return targetFile;
}
private static boolean isTextEmpty(String text) {
if (text == null || text.trim().length() == 0) {
return true;
}
return false;
}
private static String appendSeparator(String text) {
if (!isTextEmpty(text)) {
if (!text.endsWith("/")) {
return text + "/";
}
}
return text;
}
}
|
package de.ieg.infra.dao;
import org.springframework.dao.DataAccessException;
import de.ieg.infra.domain.Booking;
import de.ieg.infra.domain.InfImpcIkmcRome1Booking;
import de.ieg.infra.domain.InfImpcIkmcRomeWorkshopBooking;
import de.ieg.infra.domain.InfrafrontierI3KickOffMeetingBooking;
import de.ieg.infra.domain.AthenInfrafrontierBooking;
import de.ieg.infra.domain.ManagementWorkshopBooking;
import de.ieg.infra.domain.MunichWorkshopBooking;
import de.ieg.infra.domain.PragueWorkshopBooking;
import de.ieg.infra.domain.BarcelonaWorkshopBooking;
import de.ieg.infra.domain.IpadMdKoWorkshopBooking;
import de.ieg.infra.domain.MarseilleWorkshopBooking;
/**
* @author steinkamp A dao for booking entities
*
*/
public interface BookingDao {
/**
* Inserts a new booking for a given event
*
* @param eventId
* @param booking
* @throws DataAccessException
*/
public void insertInfrafrontierI3KickOffMeetingBooking(Integer eventId, InfrafrontierI3KickOffMeetingBooking booking) throws DataAccessException;
public void insertInfImpcIkmcRome1Booking(Integer eventId, InfImpcIkmcRome1Booking booking) throws DataAccessException;
public void insertInfImpcIkmcRomeWorkshopBooking(Integer eventId, InfImpcIkmcRomeWorkshopBooking booking) throws DataAccessException;
public void insertInfrafrontierI3AthensMeetingBooking(Integer eventId, AthenInfrafrontierBooking booking) throws DataAccessException;
public void insertMunichWorkshopBooking(Integer eventId, MunichWorkshopBooking booking) throws DataAccessException;
public void insertManagementWorkshopBooking(Integer eventId, ManagementWorkshopBooking booking) throws DataAccessException;
public void insertPragueWorkshopBooking(Integer eventId, PragueWorkshopBooking booking) throws DataAccessException;
public void insertBarcelonaWorkshopBooking(Integer eventId, BarcelonaWorkshopBooking booking) throws DataAccessException;
public void insertMarseilleWorkshopBooking(Integer eventId, MarseilleWorkshopBooking booking) throws DataAccessException;
public void insertIpadMdKoWorkshopBooking(Integer eventId, IpadMdKoWorkshopBooking booking) throws DataAccessException;
}
|
package es.ucm.fdi.iw.model;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
@Entity
public class Proyect {
private long id;
private String description;
private String img;
private String title;
private String date;
private List <User> members;
private List<Language> languages;
private List<Tag> tags;
@Id
@GeneratedValue
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@Column(length=1024)
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
@ManyToMany(targetEntity=User.class, mappedBy="proyects")
public List<User> getMembers() {
return members;
}
public void setMembers(List<User> members) {
this.members = members;
}
@ManyToMany(targetEntity=Language.class, fetch=FetchType.EAGER)
@Fetch(value = FetchMode.SUBSELECT)
public List<Language> getLanguages() {
return languages;
}
public void setLanguages(List<Language> languages){
this.languages = languages;
}
@ManyToMany(targetEntity=Tag.class,cascade = CascadeType.ALL, fetch=FetchType.EAGER)
@Fetch(value = FetchMode.SUBSELECT)
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags){
this.tags = tags;
}
}
|
package focusedCrawler.util;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.ParserProperties;
public abstract class CliTool {
abstract public void execute() throws Exception;
public static void run(String[] args, CliTool tool) {
ParserProperties properties = ParserProperties.defaults().withUsageWidth(80);
CmdLineParser parser = new CmdLineParser(tool, properties);
try {
parser.parseArgument(args);
tool.execute();
} catch (CmdLineException e) {
System.err.println(e.getMessage());
System.err.println();
parser.printUsage(System.err);
System.err.println();
System.exit(1);
} catch (Exception e) {
System.err.println("Execution failed: "+e.getMessage());
e.printStackTrace(System.err);
}
}
}
|
package main.java.gui.application;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.rmi.RemoteException;
import java.util.ArrayList;
import javax.swing.JLabel;
import main.java.data.Data;
import main.java.data.Tile;
import main.java.gui.board.TilePanel;
import main.java.gui.components.AvatarPanel;
import main.java.gui.components.Panel;
import main.java.player.PlayerIHM;
public class PlayerPanel extends Panel{
private static final long serialVersionUID = 1L;
String nameOfPlayer = null;
Color playerColor;
ArrayList<TilePanel> tilePanels = new ArrayList<TilePanel>();
ArrayList<TilePanel> buildingsPanels = new ArrayList<TilePanel>();
int sizeOfCard = 45;
int spaceBetween = 10;
private AvatarPanel avatarPanel = null;
public PlayerPanel(String nameOfPlayer) {
this.setBackground(Color.WHITE);
this.setPreferredSize(new Dimension(285, 175));
this.setLayout(null);
this.nameOfPlayer = nameOfPlayer;
placePlayerAvatar();
placePlayerName();
placePlayerCards();
placePlayerStations();
}
protected void placePlayerAvatar() {
this.avatarPanel = new AvatarPanel();
avatarPanel.setBounds(10, 5, 45, 45);
this.add(avatarPanel);
}
protected void placePlayerName() {
JLabel nameOfPlayerLabel = new JLabel(nameOfPlayer);
nameOfPlayerLabel.setBounds(70, 11, 80, 30);
this.add(nameOfPlayerLabel);
}
protected void placePlayerCards() {
for (int i=0; i < 5; i++) {
TilePanel tilePanel = new TilePanel();
tilePanel.setBounds(sizeOfCard*i + spaceBetween*(i+1), 60, sizeOfCard, sizeOfCard);
this.add(tilePanel);
tilePanels.add(tilePanel);
}
}
protected void placePlayerStations() {
for (int i=0; i<2; i++) {
TilePanel tilePanel = new TilePanel();
tilePanel.setBounds(sizeOfCard*i + spaceBetween*(i+1), 115, sizeOfCard, sizeOfCard);
this.add(tilePanel);
buildingsPanels.add(tilePanel);
}
}
public void refreshPlayerHandCards(String playerName) {
PlayerIHM player = StreetCar.player;
Data data = player.getGameData();
for (int i=0; i<data.getHandSize(playerName); i++) {
Tile tile = data.getHandTile(playerName, i);
TilePanel tilePanel = tilePanels.get(i);
tilePanel.setTile(tile);
}
}
public void refreshStationCards(String playerName) {
PlayerIHM player = StreetCar.player;
Data data = player.getGameData();
try {
if(!player.getPlayerName().equals(playerName)) {
for (int i=0; i < 2; i++) {
TilePanel tilePanel = buildingsPanels.get(i);
tilePanel.setTile(null);
tilePanel.setBackground(Color.GRAY);
}
} else {
Point[] stationsPositions = data.getPlayerAimBuildings(playerName);
for (int i=0; i<stationsPositions.length; i++) {
Point p = stationsPositions[i];
Tile tile = data.getBoard()[p.x][p.y];
TilePanel tilePanel = buildingsPanels.get(i);
tilePanel.setTile(tile);
}
}
} catch (RemoteException e) { e.printStackTrace(); }
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int[] xPoints = {230, 253, 276, 253};
int[] yPoints = {28, 5, 28, 51};
g.drawPolygon(xPoints, yPoints, 4);
}
// Refresh game
public void refreshGame(PlayerIHM player, Data data) {
Color playerColor = data.getPlayerColor(nameOfPlayer);
avatarPanel.setColor(playerColor);
refreshPlayerHandCards(nameOfPlayer);
refreshStationCards(nameOfPlayer);
if (data.isPlayerTurn(nameOfPlayer)) {
this.setBackground(new Color(0xC9ECEE));
} else {
this.setBackground(Color.WHITE);
}
}
}
|
package hu.bme.mit.spaceship;
/**
* A simple spaceship with two proton torpedos and four lasers
*/
public class GT4500 implements SpaceShip {
private TorpedoStore primaryTorpedoStore;
private TorpedoStore secondaryTorpedoStore;
private boolean wasPrimaryFiredLast = false;
public GT4500() {
this.primaryTorpedoStore = new TorpedoStore(10);
this.secondaryTorpedoStore = new TorpedoStore(10);
}
public boolean fireLasers(FiringMode firingMode) {
// TODO not implemented yet
return false;
}
/**
* Tries to fire the torpedo stores of the ship.
*
* @param firingMode how many torpedo bays to fire
* SINGLE: fires only one of the bays.
* - For the first time the primary store is fired.
* - To give some cooling time to the torpedo stores, torpedo stores are fired alternating.
* - But if the store next in line is empty the ship tries to fire the other store.
* - If the fired store reports a failure, the ship does not try to fire the other one.
* ALL: tries to fire both of the torpedo stores.
*
* @return whether at least one torpedo was fired successfully
*/
@Override
public boolean fireTorpedos(FiringMode firingMode) {
boolean firingSuccess = false;
switch (firingMode) {
case SINGLE:
if (wasPrimaryFiredLast) {
// try to fire the secondary first
if (! secondaryTorpedoStore.isEmpty()) {
firingSuccess = secondaryTorpedoStore.fire(1);
wasPrimaryFiredLast = false;
}
else {
// although primary was fired last time, but the secondary is empty
// thus try to fire primary again
if (! primaryTorpedoStore.isEmpty()) {
firingSuccess = primaryTorpedoStore.fire(1);
wasPrimaryFiredLast = true;
}
// if both of the stores are empty, nothing can be done, return failure
}
}
else {
// try to fire the primary first
if (! primaryTorpedoStore.isEmpty()) {
firingSuccess = primaryTorpedoStore.fire(1);
wasPrimaryFiredLast = true;
}
else {
// although secondary was fired last time, but primary is empty
// thus try to fire secondary again
if (! secondaryTorpedoStore.isEmpty()) {
firingSuccess = secondaryTorpedoStore.fire(1);
wasPrimaryFiredLast = false;
}
// if both of the stores are empty, nothing can be done, return failure
}
}
break;
case ALL:
// try to fire both of the torpedos
boolean firingSuccessPrimary = primaryTorpedoStore.fire(1);
boolean firingSuccessSecondary = secondaryTorpedoStore.fire(1);
firingSuccess = firingSuccessPrimary || firingSuccessSecondary;
break;
}
return firingSuccess;
}
}
|
package hu.bme.mit.spaceship;
/**
* A simple spaceship with two proton torpedos and four lasers
*/
public class GT4500 implements SpaceShip {
private TorpedoStore primaryTorpedoStore;
private TorpedoStore secondaryTorpedoStore;
private boolean wasPrimaryFiredLast = false;
public GT4500() {
this.primaryTorpedoStore = new TorpedoStore(10);
this.secondaryTorpedoStore = new TorpedoStore(10);
}
public boolean fireLasers(FiringMode firingMode) {
// TODO not implemented yet
return false;
}
/**
* Tries to fire the torpedo stores of the ship.
*
* @param firingMode how many torpedo bays to fire
* SINGLE: fires only one of the bays.
* - For the first time the primary store is fired.
* - To give some cooling time to the torpedo stores, torpedo stores are fired alternating.
* - But if the store next in line is empty the ship tries to fire the other store.
* - If the fired store reports a failure, the ship does not try to fire the other one.
* ALL: tries to fire both of the torpedo stores.
*
* @return whether at least one torpedo was fired successfully
*/
@Override
public boolean fireTorpedos(FiringMode firingMode) {
boolean firingSuccess = false;
switch (firingMode) {
case SINGLE:
if (wasPrimaryFiredLast) {
// try to fire the secondary first
if (! secondaryTorpedoStore.isEmpty()) {
firingSuccess = secondaryTorpedoStore.fire(1);
wasPrimaryFiredLast = false;
}
else {
// although primary was fired last time, but the secondary is empty
// thus try to fire primary again
if (! primaryTorpedoStore.isEmpty()) {
firingSuccess = primaryTorpedoStore.fire(1);
wasPrimaryFiredLast = true;
}
// if both of the stores are empty, nothing can be done, return failure
}
}
else {
// try to fire the primary first
if (! primaryTorpedoStore.isEmpty()) {
firingSuccess = primaryTorpedoStore.fire(1);
wasPrimaryFiredLast = true;
}
else {
// although secondary was fired last time, but primary is empty
// thus try to fire secondary again
if (! secondaryTorpedoStore.isEmpty()) {
firingSuccess = secondaryTorpedoStore.fire(1);
wasPrimaryFiredLast = false;
}
// if both of the stores are empty, nothing can be done, return failure
}
}
break;
case ALL:
// try to fire both of the torpedos
if (! primaryTorpedoStore.isEmpty() && ! secondaryTorpedoStore.isEmpty()) {
if (wasPrimaryFiredLast) {
firingSuccess = secondaryTorpedoStore.fire(1);
firingSuccess = primaryTorpedoStore.fire(1);
wasPrimaryFiredLast = true;
}
else
{
firingSuccess = primaryTorpedoStore.fire(1);
firingSuccess = secondaryTorpedoStore.fire(1);
wasPrimaryFiredLast = false;
}
}
break;
}
return firingSuccess;
}
}
|
package hudson.plugins.ec2;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.auth.STSAssumeRoleSessionCredentialsProvider;
import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder;
import com.cloudbees.jenkins.plugins.awscredentials.AWSCredentialsImpl;
import com.cloudbees.jenkins.plugins.awscredentials.AmazonWebServicesCredentials;
import com.cloudbees.plugins.credentials.Credentials;
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.CredentialsStore;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardListBoxModel;
import com.cloudbees.plugins.credentials.domains.Domain;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import hudson.security.ACL;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import javax.servlet.ServletException;
import hudson.model.TaskListener;
import hudson.util.ListBoxModel;
import jenkins.model.Jenkins;
import jenkins.model.JenkinsLocationConfiguration;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import com.amazonaws.AmazonClientException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.InstanceProfileCredentialsProvider;
import com.amazonaws.internal.StaticCredentialsProvider;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.CreateKeyPairRequest;
import com.amazonaws.services.ec2.model.DescribeSpotInstanceRequestsRequest;
import com.amazonaws.services.ec2.model.Filter;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.InstanceStateName;
import com.amazonaws.services.ec2.model.InstanceType;
import com.amazonaws.services.ec2.model.KeyPair;
import com.amazonaws.services.ec2.model.KeyPairInfo;
import com.amazonaws.services.ec2.model.Reservation;
import com.amazonaws.services.ec2.model.SpotInstanceRequest;
import com.amazonaws.services.ec2.model.Tag;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import hudson.ProxyConfiguration;
import hudson.model.Computer;
import hudson.model.Descriptor;
import hudson.model.Label;
import hudson.model.Node;
import hudson.slaves.Cloud;
import hudson.slaves.NodeProvisioner.PlannedNode;
import hudson.util.FormValidation;
import hudson.util.HttpResponses;
import hudson.util.Secret;
import hudson.util.StreamTaskListener;
/**
* Hudson's view of EC2.
*
* @author Kohsuke Kawaguchi
*/
public abstract class EC2Cloud extends Cloud {
private static final Logger LOGGER = Logger.getLogger(EC2Cloud.class.getName());
public static final String DEFAULT_EC2_HOST = "us-east-1";
public static final String AWS_URL_HOST = "amazonaws.com";
public static final String EC2_SLAVE_TYPE_SPOT = "spot";
public static final String EC2_SLAVE_TYPE_DEMAND = "demand";
private static final SimpleFormatter sf = new SimpleFormatter();
private transient ReentrantLock slaveCountingLock = new ReentrantLock();
private final boolean useInstanceProfileForCredentials;
private final String roleArn;
private final String roleSessionName;
/**
* Id of the {@link AmazonWebServicesCredentials} used to connect to Amazon ECS
*/
@CheckForNull
private String credentialsId;
@CheckForNull
@Deprecated
private transient String accessId;
@CheckForNull
@Deprecated
private transient Secret secretKey;
protected final EC2PrivateKey privateKey;
/**
* Upper bound on how many instances we may provision.
*/
public final int instanceCap;
private final List<? extends SlaveTemplate> templates;
private transient KeyPair usableKeyPair;
protected transient AmazonEC2 connection;
private static AWSCredentialsProvider awsCredentialsProvider;
protected EC2Cloud(String id, boolean useInstanceProfileForCredentials, String credentialsId, String privateKey,
String instanceCapStr, List<? extends SlaveTemplate> templates, String roleArn, String roleSessionName) {
super(id);
this.useInstanceProfileForCredentials = useInstanceProfileForCredentials;
this.roleArn = roleArn;
this.roleSessionName = roleSessionName;
this.credentialsId = credentialsId;
this.privateKey = new EC2PrivateKey(privateKey);
if (templates == null) {
this.templates = Collections.emptyList();
} else {
this.templates = templates;
}
if (instanceCapStr.isEmpty()) {
this.instanceCap = Integer.MAX_VALUE;
} else {
this.instanceCap = Integer.parseInt(instanceCapStr);
}
readResolve(); // set parents
}
public abstract URL getEc2EndpointUrl() throws IOException;
public abstract URL getS3EndpointUrl() throws IOException;
protected Object readResolve() {
this.slaveCountingLock = new ReentrantLock();
for (SlaveTemplate t : templates)
t.parent = this;
if (this.accessId != null && this.secretKey != null && credentialsId == null) {
String secretKeyEncryptedValue = this.secretKey.getEncryptedValue();
// REPLACE this.accessId and this.secretId by a credential
SystemCredentialsProvider systemCredentialsProvider = SystemCredentialsProvider.getInstance();
// ITERATE ON EXISTING CREDS AND DON'T CREATE IF EXIST
for (Credentials credentials: systemCredentialsProvider.getCredentials()) {
if (credentials instanceof AmazonWebServicesCredentials) {
AmazonWebServicesCredentials awsCreds = (AmazonWebServicesCredentials) credentials;
AWSCredentials awsCredentials = awsCreds.getCredentials();
if (accessId.equals(awsCredentials.getAWSAccessKeyId()) &&
Secret.toString(this.secretKey).equals(awsCredentials.getAWSSecretKey())) {
this.credentialsId = awsCreds.getId();
this.accessId = null;
this.secretKey = null;
return this;
}
}
}
// CREATE
for (CredentialsStore credentialsStore: CredentialsProvider.lookupStores(Jenkins.getInstance())) {
if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
try {
String credsId = UUID.randomUUID().toString();
credentialsStore.addCredentials(Domain.global(), new AWSCredentialsImpl(
CredentialsScope.SYSTEM, credsId, this.accessId, secretKeyEncryptedValue,
"EC2 Cloud - " + getDisplayName()));
this.credentialsId = credsId;
this.accessId = null;
this.secretKey = null;
return this;
} catch (IOException e) {
this.credentialsId = null;
LOGGER.log(Level.WARNING, "Exception converting legacy configuration to the new credentials API", e);
}
}
}
// PROBLEM, GLOBAL STORE NOT FOUND
LOGGER.log(Level.WARNING, "EC2 Plugin could not migrate credentials to the Jenkins Global Credentials Store, EC2 Plugin for cloud {0} must be manually reconfigured", getDisplayName());
}
return this;
}
public boolean isUseInstanceProfileForCredentials() {
return useInstanceProfileForCredentials;
}
public String getRoleArn() {
return roleArn;
}
public String getRoleSessionName() {
return roleSessionName;
}
public String getCredentialsId() {
return credentialsId;
}
public EC2PrivateKey getPrivateKey() {
return privateKey;
}
public String getInstanceCapStr() {
if (instanceCap == Integer.MAX_VALUE)
return "";
else
return String.valueOf(instanceCap);
}
public List<SlaveTemplate> getTemplates() {
return Collections.unmodifiableList(templates);
}
public SlaveTemplate getTemplate(String template) {
for (SlaveTemplate t : templates) {
if (t.description.equals(template)) {
return t;
}
}
return null;
}
/**
* Gets {@link SlaveTemplate} that has the matching {@link Label}.
*/
public SlaveTemplate getTemplate(Label label) {
for (SlaveTemplate t : templates) {
if (t.getMode() == Node.Mode.NORMAL) {
if (label == null || label.matches(t.getLabelSet())) {
return t;
}
} else if (t.getMode() == Node.Mode.EXCLUSIVE) {
if (label != null && label.matches(t.getLabelSet())) {
return t;
}
}
}
return null;
}
/**
* Gets the {@link KeyPairInfo} used for the launch.
*/
public synchronized KeyPair getKeyPair() throws AmazonClientException, IOException {
if (usableKeyPair == null)
usableKeyPair = privateKey.find(connect());
return usableKeyPair;
}
/**
* Debug command to attach to a running instance.
*/
public void doAttach(StaplerRequest req, StaplerResponse rsp, @QueryParameter String id)
throws ServletException, IOException, AmazonClientException {
checkPermission(PROVISION);
SlaveTemplate t = getTemplates().get(0);
StringWriter sw = new StringWriter();
StreamTaskListener listener = new StreamTaskListener(sw);
EC2AbstractSlave node = t.attach(id, listener);
Jenkins.getInstance().addNode(node);
rsp.sendRedirect2(req.getContextPath() + "/computer/" + node.getNodeName());
}
public HttpResponse doProvision(@QueryParameter String template) throws ServletException, IOException {
checkPermission(PROVISION);
if (template == null) {
throw HttpResponses.error(SC_BAD_REQUEST, "The 'template' query parameter is missing");
}
SlaveTemplate t = getTemplate(template);
if (t == null) {
throw HttpResponses.error(SC_BAD_REQUEST, "No such template: " + template);
}
try {
List<EC2AbstractSlave> nodes = getNewOrExistingAvailableSlave(t, 1, true);
if (nodes == null || nodes.isEmpty())
throw HttpResponses.error(SC_BAD_REQUEST, "Cloud or AMI instance cap would be exceeded for: " + template);
//Reconnect a stopped instance, the ADD is invoking the connect only for the node creation
Computer c = nodes.get(0).toComputer();
if (nodes.get(0).getStopOnTerminate() && c != null) {
c.connect(false);
}
Jenkins.getInstance().addNode(nodes.get(0));
return HttpResponses.redirectViaContextPath("/computer/" + nodes.get(0).getNodeName());
} catch (AmazonClientException e) {
throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR, e);
}
}
/**
* Counts the number of instances in EC2 that can be used with the specified image and a template. Also removes any
* nodes associated with canceled requests.
*
* @param template If left null, then all instances are counted.
*/
private int countCurrentEC2Slaves(SlaveTemplate template) throws AmazonClientException {
String jenkinsServerUrl = null;
JenkinsLocationConfiguration jenkinsLocation = JenkinsLocationConfiguration.get();
if (jenkinsLocation != null)
jenkinsServerUrl = jenkinsLocation.getUrl();
if (jenkinsServerUrl == null) {
LOGGER.log(Level.WARNING, "No Jenkins server URL specified, it is strongly recommended to open /configure and set the server URL. " +
"Not having has disabled the per-master instance cap counting (cf. https://github.com/jenkinsci/ec2-plugin/pull/310)");
}
LOGGER.log(Level.FINE, "Counting current slaves: "
+ (template != null ? (" AMI: " + template.getAmi() + " TemplateDesc: " + template.description) : " All AMIS")
+ " Jenkins Server: " + jenkinsServerUrl);
int n = 0;
Set<String> instanceIds = new HashSet<String>();
String description = template != null ? template.description : null;
//FIXME convert to a filter query
for (Reservation r : connect().describeInstances().getReservations()) {
for (Instance i : r.getInstances()) {
if (isEc2ProvisionedAmiSlave(i.getTags(), description)
&& isEc2ProvisionedJenkinsSlave(i.getTags(), jenkinsServerUrl)
&& (template == null || template.getAmi().equals(i.getImageId()))) {
InstanceStateName stateName = InstanceStateName.fromValue(i.getState().getName());
if (stateName != InstanceStateName.Terminated &&
stateName != InstanceStateName.ShuttingDown &&
stateName != InstanceStateName.Stopped ) {
LOGGER.log(Level.FINE, "Existing instance found: " + i.getInstanceId() + " AMI: " + i.getImageId()
+ (template != null ? (" Template: " + description) : "") + " Jenkins Server: " + jenkinsServerUrl);
n++;
instanceIds.add(i.getInstanceId());
}
}
}
}
List<SpotInstanceRequest> sirs = null;
List<Filter> filters = new ArrayList<Filter>();
List<String> values;
if (template != null) {
values = new ArrayList<String>();
values.add(template.getAmi());
filters.add(new Filter("launch.image-id", values));
}
if(jenkinsServerUrl!=null) {
// The instances must match the jenkins server url
filters.add(new Filter("tag:" + EC2Tag.TAG_NAME_JENKINS_SERVER_URL + "=" + jenkinsServerUrl));
}
values = new ArrayList<String>();
values.add(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE);
filters.add(new Filter("tag-key", values));
DescribeSpotInstanceRequestsRequest dsir = new DescribeSpotInstanceRequestsRequest().withFilters(filters);
try {
sirs = connect().describeSpotInstanceRequests(dsir).getSpotInstanceRequests();
} catch (Exception ex) {
// Some ec2 implementations don't implement spot requests (Eucalyptus)
LOGGER.log(Level.FINEST, "Describe spot instance requests failed", ex);
}
Set<SpotInstanceRequest> sirSet = new HashSet<>();
if (sirs != null) {
for (SpotInstanceRequest sir : sirs) {
sirSet.add(sir);
if (sir.getState().equals("open") || sir.getState().equals("active")) {
if (sir.getInstanceId() != null && instanceIds.contains(sir.getInstanceId()))
continue;
if (isEc2ProvisionedAmiSlave(sir.getTags(), description)) {
LOGGER.log(Level.FINE, "Spot instance request found: " + sir.getSpotInstanceRequestId() + " AMI: "
+ sir.getInstanceId() + " state: " + sir.getState() + " status: " + sir.getStatus());
n++;
if (sir.getInstanceId() != null)
instanceIds.add(sir.getInstanceId());
}
} else {
// Canceled or otherwise dead
for (Node node : Jenkins.getInstance().getNodes()) {
try {
if (!(node instanceof EC2SpotSlave))
continue;
EC2SpotSlave ec2Slave = (EC2SpotSlave) node;
if (ec2Slave.getSpotInstanceRequestId().equals(sir.getSpotInstanceRequestId())) {
LOGGER.log(Level.INFO, "Removing dead request: " + sir.getSpotInstanceRequestId() + " AMI: "
+ sir.getInstanceId() + " state: " + sir.getState() + " status: " + sir.getStatus());
Jenkins.getInstance().removeNode(node);
break;
}
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to remove node for dead request: " + sir.getSpotInstanceRequestId()
+ " AMI: " + sir.getInstanceId() + " state: " + sir.getState() + " status: " + sir.getStatus(),
e);
}
}
}
}
}
// Count nodes where the spot request does not yet exist (sometimes it takes time for the request to appear
// in the EC2 API)
for (Node node : Jenkins.getInstance().getNodes()) {
if (!(node instanceof EC2SpotSlave))
continue;
EC2SpotSlave ec2Slave = (EC2SpotSlave) node;
SpotInstanceRequest sir = ec2Slave.getSpotRequest();
if (sir == null) {
LOGGER.log(Level.FINE, "Found spot node without request: " + ec2Slave.getSpotInstanceRequestId());
n++;
continue;
}
if (sirSet.contains(sir))
continue;
sirSet.add(sir);
if (sir.getState().equals("open") || sir.getState().equals("active")) {
if (template != null) {
List<Tag> instanceTags = sir.getTags();
for (Tag tag : instanceTags) {
if (StringUtils.equals(tag.getKey(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE) && StringUtils.equals(tag.getValue(), getSlaveTypeTagValue(EC2_SLAVE_TYPE_SPOT, template.description)) && sir.getLaunchSpecification().getImageId().equals(template.getAmi())) {
if (sir.getInstanceId() != null && instanceIds.contains(sir.getInstanceId()))
continue;
LOGGER.log(Level.FINE, "Spot instance request found (from node): " + sir.getSpotInstanceRequestId() + " AMI: "
+ sir.getInstanceId() + " state: " + sir.getState() + " status: " + sir.getStatus());
n++;
if (sir.getInstanceId() != null)
instanceIds.add(sir.getInstanceId());
}
}
}
}
}
return n;
}
private boolean isEc2ProvisionedJenkinsSlave(List<Tag> tags, String serverUrl) {
for (Tag tag : tags) {
if (StringUtils.equals(tag.getKey(), EC2Tag.TAG_NAME_JENKINS_SERVER_URL)) {
return StringUtils.equals(tag.getValue(), serverUrl);
}
}
return (serverUrl == null);
}
private boolean isEc2ProvisionedAmiSlave(List<Tag> tags, String description) {
for (Tag tag : tags) {
if (StringUtils.equals(tag.getKey(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) {
if (description == null) {
return true;
} else if (StringUtils.equals(tag.getValue(), EC2Cloud.EC2_SLAVE_TYPE_DEMAND)
|| StringUtils.equals(tag.getValue(), EC2Cloud.EC2_SLAVE_TYPE_SPOT)) {
// To handle cases where description is null and also upgrade cases for existing slave nodes.
return true;
} else if (StringUtils.equals(tag.getValue(), getSlaveTypeTagValue(EC2Cloud.EC2_SLAVE_TYPE_DEMAND, description))
|| StringUtils.equals(tag.getValue(), getSlaveTypeTagValue(EC2Cloud.EC2_SLAVE_TYPE_SPOT, description))) {
return true;
} else {
return false;
}
}
}
return false;
}
/**
* Returns the maximum number of possible slaves that can be created.
*/
private int getPossibleNewSlavesCount(SlaveTemplate template) throws AmazonClientException {
int estimatedTotalSlaves = countCurrentEC2Slaves(null);
int estimatedAmiSlaves = countCurrentEC2Slaves(template);
int availableTotalSlaves = instanceCap - estimatedTotalSlaves;
int availableAmiSlaves = template.getInstanceCap() - estimatedAmiSlaves;
LOGGER.log(Level.FINE, "Available Total Slaves: " + availableTotalSlaves + " Available AMI slaves: " + availableAmiSlaves
+ " AMI: " + template.getAmi() + " TemplateDesc: " + template.description);
return Math.min(availableAmiSlaves, availableTotalSlaves);
}
/**
* Obtains a slave whose AMI matches the AMI of the given template, and that also has requiredLabel (if requiredLabel is non-null)
* forceCreateNew specifies that the creation of a new slave is required. Otherwise, an existing matching slave may be re-used
*/
private List<EC2AbstractSlave> getNewOrExistingAvailableSlave(SlaveTemplate t, int number, boolean forceCreateNew) {
try {
slaveCountingLock.lock();
int possibleSlavesCount = getPossibleNewSlavesCount(t);
if (possibleSlavesCount <= 0) {
LOGGER.log(Level.INFO, "{0}. Cannot provision - no capacity for instances: " + possibleSlavesCount, t);
return null;
}
try {
EnumSet<SlaveTemplate.ProvisionOptions> provisionOptions;
if (forceCreateNew)
provisionOptions = EnumSet.of(SlaveTemplate.ProvisionOptions.FORCE_CREATE);
else
provisionOptions = EnumSet.of(SlaveTemplate.ProvisionOptions.ALLOW_CREATE);
if (number > possibleSlavesCount) {
LOGGER.log(Level.INFO, String.format("%d nodes were requested for the template %s, " +
"but because of instance cap only %d can be provisioned", number, t, possibleSlavesCount));
number = possibleSlavesCount;
}
return t.provision(number, provisionOptions);
} catch (IOException e) {
LOGGER.log(Level.WARNING, t + ". Exception during provisioning", e);
return null;
}
} finally { slaveCountingLock.unlock(); }
}
@Override
public Collection<PlannedNode> provision(final Label label, int excessWorkload) {
final SlaveTemplate t = getTemplate(label);
List<PlannedNode> plannedNodes = new ArrayList<>();
try {
LOGGER.log(Level.INFO, "{0}. Attempting to provision slave needed by excess workload of " + excessWorkload + " units", t);
int number = Math.max(excessWorkload / t.getNumExecutors(), 1);
final List<EC2AbstractSlave> slaves = getNewOrExistingAvailableSlave(t, number, false);
if (slaves == null || slaves.isEmpty()) {
LOGGER.warning("Can't raise nodes for " + t);
return Collections.emptyList();
}
for (final EC2AbstractSlave slave : slaves) {
if (slave == null) {
LOGGER.warning("Can't raise node for " + t);
continue;
}
plannedNodes.add(createPlannedNode(t, slave));
excessWorkload -= t.getNumExecutors();
}
LOGGER.log(Level.INFO, "{0}. Attempting provision finished, excess workload: " + excessWorkload, t);
LOGGER.log(Level.INFO, "We have now {0} computers, waiting for {1} more",
new Object[]{Jenkins.getInstance().getComputers().length, plannedNodes.size()});
return plannedNodes;
} catch (AmazonClientException e) {
LOGGER.log(Level.WARNING, t + ". Exception during provisioning", e);
return Collections.emptyList();
}
}
private PlannedNode createPlannedNode(final SlaveTemplate t, final EC2AbstractSlave slave) {
return new PlannedNode(t.getDisplayName(),
Computer.threadPoolForRemoting.submit(new Callable<Node>() {
public Node call() throws Exception {
while (true) {
String instanceId = slave.getInstanceId();
if (slave instanceof EC2SpotSlave) {
if (((EC2SpotSlave) slave).isSpotRequestDead()) {
LOGGER.log(Level.WARNING, "{0} Spot request died, can't do anything. Terminate provisioning", t);
return null;
}
// Spot Instance does not have instance id yet.
if (StringUtils.isEmpty(instanceId)) {
Thread.sleep(5000);
continue;
}
}
Instance instance = CloudHelper.getInstanceWithRetry(instanceId, slave.getCloud());
if (instance == null) {
LOGGER.log(Level.WARNING, "{0} Can't find instance with instance id `{1}` in cloud {2}. Terminate provisioning ",
new Object[]{t, instanceId, slave.cloudName});
return null;
}
InstanceStateName state = InstanceStateName.fromValue(instance.getState().getName());
if (state.equals(InstanceStateName.Running)) {
//Spot instance are not reconnected automatically,
// but could be new orphans that has the option enable
Computer c = slave.toComputer();
if (slave.getStopOnTerminate() && (c != null )) {
c.connect(false);
}
long startTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - instance.getLaunchTime().getTime());
LOGGER.log(Level.INFO, "{0} Node {1} moved to RUNNING state in {2} seconds and is ready to be connected by Jenkins",
new Object[]{t, slave.getNodeName(), startTime});
return slave;
}
if (!state.equals(InstanceStateName.Pending)) {
LOGGER.log(Level.WARNING, "{0}. Node {1} is neither pending, neither running, it's {2}. Terminate provisioning",
new Object[]{t, state, slave.getNodeName()});
return null;
}
Thread.sleep(5000);
}
}
})
, t.getNumExecutors());
}
@Override
public boolean canProvision(Label label) {
return getTemplate(label) != null;
}
protected AWSCredentialsProvider createCredentialsProvider() {
return createCredentialsProvider(useInstanceProfileForCredentials, credentialsId);
}
public static String getSlaveTypeTagValue(String slaveType, String templateDescription) {
return templateDescription != null ? slaveType + "_" + templateDescription : slaveType;
}
public static AWSCredentialsProvider createCredentialsProvider(final boolean useInstanceProfileForCredentials, final String credentialsId) {
if (useInstanceProfileForCredentials) {
return new InstanceProfileCredentialsProvider();
} else if (StringUtils.isBlank(credentialsId)) {
return new DefaultAWSCredentialsProviderChain();
} else {
AmazonWebServicesCredentials credentials = getCredentials(credentialsId);
if (credentials != null)
return new StaticCredentialsProvider(credentials.getCredentials());
}
return new DefaultAWSCredentialsProviderChain();
}
public static AWSCredentialsProvider createCredentialsProvider(
final boolean useInstanceProfileForCredentials,
final String credentialsId,
final String roleArn,
final String roleSessionName,
final String region) {
AWSCredentialsProvider provider = createCredentialsProvider(useInstanceProfileForCredentials, credentialsId);
if (StringUtils.isNotEmpty(roleArn) && StringUtils.isNotEmpty(roleSessionName)) {
return new STSAssumeRoleSessionCredentialsProvider.Builder(roleArn, roleSessionName)
.withStsClient(AWSSecurityTokenServiceClientBuilder.standard()
.withCredentials(provider)
.withRegion(region)
.withClientConfiguration(createClientConfiguration(convertHostName(region)))
.build())
.build();
}
return provider;
}
@CheckForNull
private static AmazonWebServicesCredentials getCredentials(@Nullable String credentialsId) {
if (StringUtils.isBlank(credentialsId)) {
return null;
}
return (AmazonWebServicesCredentials) CredentialsMatchers.firstOrNull(
CredentialsProvider.lookupCredentials(AmazonWebServicesCredentials.class, Jenkins.getInstance(),
ACL.SYSTEM, Collections.emptyList()),
CredentialsMatchers.withId(credentialsId));
}
/**
* Connects to EC2 and returns {@link AmazonEC2}, which can then be used to communicate with EC2.
*/
public AmazonEC2 connect() throws AmazonClientException {
try {
if (connection == null) {
connection = connect(createCredentialsProvider(), getEc2EndpointUrl());
}
return connection;
} catch (IOException e) {
throw new AmazonClientException("Failed to retrieve the endpoint", e);
}
}
/***
* Connect to an EC2 instance.
*
* @return {@link AmazonEC2} client
*/
public synchronized static AmazonEC2 connect(AWSCredentialsProvider credentialsProvider, URL endpoint) {
awsCredentialsProvider = credentialsProvider;
AmazonEC2 client = new AmazonEC2Client(credentialsProvider, createClientConfiguration(endpoint.getHost()));
client.setEndpoint(endpoint.toString());
return client;
}
public static ClientConfiguration createClientConfiguration(final String host) {
ClientConfiguration config = new ClientConfiguration();
config.setMaxErrorRetry(16); // Default retry limit (3) is low and often
// cause problems. Raise it a bit.
config.setSignerOverride("AWS4SignerType");
ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
Proxy proxy = proxyConfig == null ? Proxy.NO_PROXY : proxyConfig.createProxy(host);
if (!proxy.equals(Proxy.NO_PROXY) && proxy.address() instanceof InetSocketAddress) {
InetSocketAddress address = (InetSocketAddress) proxy.address();
config.setProxyHost(address.getHostName());
config.setProxyPort(address.getPort());
if (null != proxyConfig.getUserName()) {
config.setProxyUsername(proxyConfig.getUserName());
config.setProxyPassword(proxyConfig.getPassword());
}
}
return config;
}
/***
* Convert a configured hostname like 'us-east-1' to a FQDN or ip address
*/
public static String convertHostName(String ec2HostName) {
if (ec2HostName == null || ec2HostName.length() == 0)
ec2HostName = DEFAULT_EC2_HOST;
if (!ec2HostName.contains("."))
ec2HostName = "ec2." + ec2HostName + "." + AWS_URL_HOST;
return ec2HostName;
}
/***
* Convert a user entered string into a port number "" -> -1 to indicate default based on SSL setting
*/
public static Integer convertPort(String ec2Port) {
if (ec2Port == null || ec2Port.length() == 0)
return -1;
return Integer.parseInt(ec2Port);
}
/**
* Computes the presigned URL for the given S3 resource.
*
* @param path String like "/bucketName/folder/folder/abc.txt" that represents the resource to request.
*/
public URL buildPresignedURL(String path) throws AmazonClientException {
AWSCredentials credentials = awsCredentialsProvider.getCredentials();
long expires = System.currentTimeMillis() + 60 * 60 * 1000;
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(path, credentials.getAWSSecretKey());
request.setExpiration(new Date(expires));
AmazonS3 s3 = new AmazonS3Client(credentials);
return s3.generatePresignedUrl(request);
}
/* Parse a url or return a sensible error */
public static URL checkEndPoint(String url) throws FormValidation {
try {
return new URL(url);
} catch (MalformedURLException ex) {
throw FormValidation.error("Endpoint URL is not a valid URL");
}
}
public static abstract class DescriptorImpl extends Descriptor<Cloud> {
public InstanceType[] getInstanceTypes() {
return InstanceType.values();
}
public FormValidation doCheckUseInstanceProfileForCredentials(@QueryParameter boolean value) {
if (value) {
try {
new InstanceProfileCredentialsProvider().getCredentials();
} catch (AmazonClientException e) {
return FormValidation.error(Messages.EC2Cloud_FailedToObtainCredentialsFromEC2(), e.getMessage());
}
}
return FormValidation.ok();
}
public FormValidation doCheckPrivateKey(@QueryParameter String value) throws IOException, ServletException {
boolean hasStart = false, hasEnd = false;
BufferedReader br = new BufferedReader(new StringReader(value));
String line;
while ((line = br.readLine()) != null) {
if (line.equals("
hasStart = true;
if (line.equals("
hasEnd = true;
}
if (!hasStart)
return FormValidation.error("This doesn't look like a private key at all");
if (!hasEnd)
return FormValidation
.error("The private key is missing the trailing 'END RSA PRIVATE KEY' marker. Copy&paste error?");
return FormValidation.ok();
}
protected FormValidation doTestConnection(URL ec2endpoint, boolean useInstanceProfileForCredentials, String credentialsId, String privateKey, String roleArn, String roleSessionName, String region)
throws IOException, ServletException {
try {
AWSCredentialsProvider credentialsProvider = createCredentialsProvider(useInstanceProfileForCredentials, credentialsId, roleArn, roleSessionName, region);
AmazonEC2 ec2 = connect(credentialsProvider, ec2endpoint);
ec2.describeInstances();
if (privateKey == null)
return FormValidation.error("Private key is not specified. Click 'Generate Key' to generate one.");
if (privateKey.trim().length() > 0) {
// check if this key exists
EC2PrivateKey pk = new EC2PrivateKey(privateKey);
if (pk.find(ec2) == null)
return FormValidation
.error("The EC2 key pair private key isn't registered to this EC2 region (fingerprint is "
+ pk.getFingerprint() + ")");
}
return FormValidation.ok(Messages.EC2Cloud_Success());
} catch (AmazonClientException e) {
LOGGER.log(Level.WARNING, "Failed to check EC2 credential", e);
return FormValidation.error(e.getMessage());
}
}
public FormValidation doGenerateKey(StaplerResponse rsp, URL ec2EndpointUrl, boolean useInstanceProfileForCredentials, String credentialsId, String roleArn, String roleSessionName, String region)
throws IOException, ServletException {
try {
AWSCredentialsProvider credentialsProvider = createCredentialsProvider(useInstanceProfileForCredentials, credentialsId, roleArn, roleSessionName, region);
AmazonEC2 ec2 = connect(credentialsProvider, ec2EndpointUrl);
List<KeyPairInfo> existingKeys = ec2.describeKeyPairs().getKeyPairs();
int n = 0;
while (true) {
boolean found = false;
for (KeyPairInfo k : existingKeys) {
if (k.getKeyName().equals("hudson-" + n))
found = true;
}
if (!found)
break;
n++;
}
CreateKeyPairRequest request = new CreateKeyPairRequest("hudson-" + n);
KeyPair key = ec2.createKeyPair(request).getKeyPair();
rsp.addHeader("script",
"findPreviousFormItem(button,'privateKey').value='" + key.getKeyMaterial().replace("\n", "\\n") + "'");
return FormValidation.ok(Messages.EC2Cloud_Success());
} catch (AmazonClientException e) {
LOGGER.log(Level.WARNING, "Failed to check EC2 credential", e);
return FormValidation.error(e.getMessage());
}
}
public ListBoxModel doFillCredentialsIdItems() {
return new StandardListBoxModel()
.withEmptySelection()
.withMatching(
CredentialsMatchers.always(),
CredentialsProvider.lookupCredentials(AmazonWebServicesCredentials.class,
Jenkins.getInstance(),
ACL.SYSTEM,
Collections.emptyList()));
}
}
public static void log(Logger logger, Level level, TaskListener listener, String message) {
log(logger, level, listener, message, null);
}
public static void log(Logger logger, Level level, TaskListener listener, String message, Throwable exception) {
logger.log(level, message, exception);
if (listener != null) {
if (exception != null)
message += " Exception: " + exception;
LogRecord lr = new LogRecord(level, message);
lr.setLoggerName(LOGGER.getName());
PrintStream printStream = listener.getLogger();
printStream.print(sf.format(lr));
}
}
}
|
package imagej.ops;
import imagej.command.CommandInfo;
import imagej.command.CommandModule;
import imagej.command.CommandModuleItem;
import imagej.command.CommandService;
import imagej.module.Module;
import imagej.module.ModuleItem;
import imagej.module.ModuleService;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import org.scijava.InstantiableException;
import org.scijava.log.LogService;
import org.scijava.plugin.AbstractPTService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.service.Service;
import org.scijava.util.ConversionUtils;
/**
* Default service that manages and executes {@link Op}s.
*
* @author Curtis Rueden
*/
@Plugin(type = Service.class)
public class DefaultOpService extends AbstractPTService<Op> implements
OpService
{
@Parameter
private ModuleService moduleService;
@Parameter
private CommandService commandService;
@Parameter
private LogService log;
// -- OpService methods --
@Override
public Object run(final String name, final Object... args) {
final Module module = module(name, args);
if (module == null) {
throw new IllegalArgumentException("No matching op: " + name);
}
return run(module);
}
@Override
public Object run(final Op op, final Object... args) {
return run(module(op, args));
}
@Override
public Op op(final String name, final Object... args) {
final Module module = module(name, args);
if (module == null) return null;
return (Op) module.getDelegateObject();
}
@Override
public Module module(final String name, final Object... args) {
for (final CommandInfo info : commandService.getCommandsOfType(Op.class)) {
if (!name.equals(info.getName())) continue;
// the name matches; now check the fields
final Class<?> opClass;
try {
opClass = info.loadClass();
}
catch (final InstantiableException exc) {
log.error("Invalid op: " + info.getClassName());
continue;
}
// check that each parameter is compatible with its argument
int i = 0;
boolean match = true;
for (final ModuleItem<?> item : info.inputs()) {
if (i >= args.length) continue; // too few arguments
final Object arg = args[i++];
if (!canAssign(arg, item)) {
match = false;
break;
}
}
if (!match) continue; // incompatible arguments
if (i != args.length) continue; // too many arguments
// create module and assign the inputs
final CommandModule module = (CommandModule) createModule(info, args);
// make sure the op itself is happy with these arguments
if (Contingent.class.isAssignableFrom(opClass)) {
final Contingent c = (Contingent) module.getCommand();
if (!c.conforms()) continue;
}
if (log.isDebug()) {
log.debug("OpService.module(" + name + "): op=" +
module.getDelegateObject().getClass().getName());
}
// found a match!
return module;
}
return null;
}
@Override
public Module module(final Op op, final Object... args) {
final CommandInfo info = commandService.getCommand(op.getClass());
final Module module = info.createModule(op);
getContext().inject(module.getDelegateObject());
return assignInputs(module, args);
}
@Override
public Object add(final Object... o) {
return run("add", o);
}
// -- PTService methods --
@Override
public Class<Op> getPluginType() {
return Op.class;
}
// -- Helper methods --
private Object run(final Module module) {
module.run();
return result(module);
}
private Object result(final Module module) {
final List<Object> outputs = new ArrayList<Object>();
for (final ModuleItem<?> output : module.getInfo().outputs()) {
final Object value = output.getValue(module);
outputs.add(value);
}
return outputs.size() == 1 ? outputs.get(0) : outputs;
}
private Module createModule(final CommandInfo info, final Object... args) {
final Module module = moduleService.createModule(info);
getContext().inject(module.getDelegateObject());
return assignInputs(module, args);
}
/** Assigns arguments into the given module's inputs. */
private Module assignInputs(final Module module, final Object... args) {
int i = 0;
for (final ModuleItem<?> item : module.getInfo().inputs()) {
assign(module, args[i++], item);
}
return module;
}
private boolean canAssign(final Object arg, final ModuleItem<?> item) {
if (item instanceof CommandModuleItem) {
final CommandModuleItem<?> commandItem = (CommandModuleItem<?>) item;
final Type type = commandItem.getField().getGenericType();
return ConversionUtils.canConvert(arg, type);
}
return ConversionUtils.canConvert(arg, item.getType());
}
private void assign(final Module module, final Object arg,
final ModuleItem<?> item)
{
Object value;
if (item instanceof CommandModuleItem) {
final CommandModuleItem<?> commandItem = (CommandModuleItem<?>) item;
final Type type = commandItem.getField().getGenericType();
value = ConversionUtils.convert(arg, type);
}
else value = ConversionUtils.convert(arg, item.getType());
module.setInput(item.getName(), value);
module.setResolved(item.getName(), true);
}
}
|
package io.hgraphdb;
import io.hgraphdb.mutators.*;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.BufferedMutator;
import org.apache.hadoop.hbase.client.BufferedMutatorParams;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.Mutation;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
public final class HBaseBulkLoader implements AutoCloseable {
private static final Logger LOGGER = LoggerFactory.getLogger(HBaseBulkLoader.class);
private static final BufferedMutator.ExceptionListener LISTENER = (e, mutator) -> {
for (int i = 0; i < e.getNumExceptions(); i++) {
LOGGER.warn("Failed to send put: " + e.getRow(i));
}
};
private final HBaseGraph graph;
private final BufferedMutator edgesMutator;
private final BufferedMutator edgeIndicesMutator;
private final BufferedMutator verticesMutator;
private final BufferedMutator vertexIndicesMutator;
private final boolean skipWAL;
public HBaseBulkLoader(HBaseGraphConfiguration config) {
this(new HBaseGraph(config, HBaseGraphUtils.getConnection(config)));
}
public HBaseBulkLoader(HBaseGraph graph) {
this(graph,
getBufferedMutator(graph, Constants.EDGES),
getBufferedMutator(graph, Constants.EDGE_INDICES),
getBufferedMutator(graph, Constants.VERTICES),
getBufferedMutator(graph, Constants.VERTEX_INDICES));
}
private static BufferedMutator getBufferedMutator(HBaseGraph graph, String tableName) {
try {
HBaseGraphConfiguration config = graph.configuration();
TableName name = HBaseGraphUtils.getTableName(config, tableName);
BufferedMutatorParams params = new BufferedMutatorParams(name).listener(LISTENER);
return graph.connection().getBufferedMutator(params);
} catch (IOException e) {
throw new HBaseGraphException(e);
}
}
public HBaseBulkLoader(HBaseGraph graph,
BufferedMutator edgesMutator,
BufferedMutator edgeIndicesMutator,
BufferedMutator verticesMutator,
BufferedMutator vertexIndicesMutator) {
this.graph = graph;
this.edgesMutator = edgesMutator;
this.edgeIndicesMutator = edgeIndicesMutator;
this.verticesMutator = verticesMutator;
this.vertexIndicesMutator = vertexIndicesMutator;
this.skipWAL = graph.configuration().getBulkLoaderSkipWAL();
}
public HBaseGraph getGraph() {
return graph;
}
public Vertex addVertex(final Object... keyValues) {
try {
ElementHelper.legalPropertyKeyValueArray(keyValues);
Object idValue = ElementHelper.getIdValue(keyValues).orElse(null);
final String label = ElementHelper.getLabelValue(keyValues).orElse(Vertex.DEFAULT_LABEL);
idValue = HBaseGraphUtils.generateIdIfNeeded(idValue);
long now = System.currentTimeMillis();
HBaseVertex vertex = new HBaseVertex(graph, idValue, label, now, now,
HBaseGraphUtils.propertiesToMap(keyValues));
vertex.validate();
Iterator<IndexMetadata> indices = vertex.getIndices(OperationType.WRITE);
indexVertex(vertex, indices);
Creator creator = new VertexWriter(graph, vertex);
if (verticesMutator != null) verticesMutator.mutate(getMutationList(creator.constructInsertions()));
return vertex;
} catch (IOException e) {
throw new HBaseGraphException(e);
}
}
public void indexVertex(Vertex vertex, Iterator<IndexMetadata> indices) {
try {
VertexIndexWriter writer = new VertexIndexWriter(graph, vertex, indices, null);
if (vertexIndicesMutator != null) vertexIndicesMutator.mutate(getMutationList(writer.constructInsertions()));
} catch (IOException e) {
throw new HBaseGraphException(e);
}
}
public Edge addEdge(Vertex outVertex, Vertex inVertex, String label, Object... keyValues) {
try {
if (null == inVertex) throw Graph.Exceptions.argumentCanNotBeNull("inVertex");
ElementHelper.validateLabel(label);
ElementHelper.legalPropertyKeyValueArray(keyValues);
Object idValue = ElementHelper.getIdValue(keyValues).orElse(null);
idValue = HBaseGraphUtils.generateIdIfNeeded(idValue);
long now = System.currentTimeMillis();
HBaseEdge edge = new HBaseEdge(graph, idValue, label, now, now,
HBaseGraphUtils.propertiesToMap(keyValues), inVertex, outVertex);
edge.validate();
Iterator<IndexMetadata> indices = edge.getIndices(OperationType.WRITE);
indexEdge(edge, indices);
EdgeIndexWriter writer = new EdgeIndexWriter(graph, edge, Constants.CREATED_AT);
if (edgeIndicesMutator != null) edgeIndicesMutator.mutate(getMutationList(writer.constructInsertions()));
Creator creator = new EdgeWriter(graph, edge);
if (edgesMutator != null) edgesMutator.mutate(getMutationList(creator.constructInsertions()));
return edge;
} catch (IOException e) {
throw new HBaseGraphException(e);
}
}
public void indexEdge(Edge edge, Iterator<IndexMetadata> indices) {
try {
EdgeIndexWriter indexWriter = new EdgeIndexWriter(graph, edge, indices, null);
if (edgeIndicesMutator != null) edgeIndicesMutator.mutate(getMutationList(indexWriter.constructInsertions()));
} catch (IOException e) {
throw new HBaseGraphException(e);
}
}
public void setProperty(Edge edge, String key, Object value) {
try {
HBaseEdge e = (HBaseEdge) edge;
ElementHelper.validateProperty(key, value);
graph.validateProperty(e.getElementType(), e.label(), key, value);
// delete from index model before setting property
Object oldValue = null;
boolean hasIndex = e.hasIndex(OperationType.WRITE, key);
if (hasIndex) {
// only load old value if using index
oldValue = e.getProperty(key);
if (oldValue != null && !oldValue.equals(value)) {
EdgeIndexRemover indexRemover = new EdgeIndexRemover(graph, e, key, null);
if (edgeIndicesMutator != null) edgeIndicesMutator.mutate(getMutationList(indexRemover.constructMutations()));
}
}
e.getProperties().put(key, value);
e.updatedAt(System.currentTimeMillis());
if (hasIndex) {
if (oldValue == null || !oldValue.equals(value)) {
EdgeIndexWriter indexWriter = new EdgeIndexWriter(graph, e, key);
if (edgeIndicesMutator != null) edgeIndicesMutator.mutate(getMutationList(indexWriter.constructInsertions()));
}
}
PropertyWriter propertyWriter = new PropertyWriter(graph, e, key, value);
if (edgesMutator != null) edgesMutator.mutate(getMutationList(propertyWriter.constructMutations()));
} catch (IOException e) {
throw new HBaseGraphException(e);
}
}
public void setProperty(Vertex vertex, String key, Object value) {
try {
HBaseVertex v = (HBaseVertex) vertex;
ElementHelper.validateProperty(key, value);
graph.validateProperty(v.getElementType(), v.label(), key, value);
// delete from index model before setting property
Object oldValue = null;
boolean hasIndex = v.hasIndex(OperationType.WRITE, key);
if (hasIndex) {
// only load old value if using index
oldValue = v.getProperty(key);
if (oldValue != null && !oldValue.equals(value)) {
VertexIndexRemover indexRemover = new VertexIndexRemover(graph, v, key, null);
if (vertexIndicesMutator != null) vertexIndicesMutator.mutate(getMutationList(indexRemover.constructMutations()));
}
}
v.getProperties().put(key, value);
v.updatedAt(System.currentTimeMillis());
if (hasIndex) {
if (oldValue == null || !oldValue.equals(value)) {
VertexIndexWriter indexWriter = new VertexIndexWriter(graph, v, key);
if (vertexIndicesMutator != null) vertexIndicesMutator.mutate(getMutationList(indexWriter.constructInsertions()));
}
}
PropertyWriter propertyWriter = new PropertyWriter(graph, v, key, value);
if (verticesMutator != null) verticesMutator.mutate(getMutationList(propertyWriter.constructMutations()));
} catch (IOException e) {
throw new HBaseGraphException(e);
}
}
private List<? extends Mutation> getMutationList(Iterator<? extends Mutation> mutations) {
return IteratorUtils.list(IteratorUtils.consume(mutations,
m -> m.setDurability(skipWAL ? Durability.SKIP_WAL : Durability.USE_DEFAULT)));
}
public void close() {
try {
if (edgesMutator != null) edgesMutator.close();
if (edgeIndicesMutator != null) edgeIndicesMutator.close();
if (verticesMutator != null) verticesMutator.close();
if (vertexIndicesMutator != null) vertexIndicesMutator.close();
} catch (IOException e) {
throw new HBaseGraphException(e);
}
}
}
|
package logbook.internal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import logbook.bean.BattleLog;
import logbook.bean.BattleTypes.AirBaseAttack;
import logbook.bean.BattleTypes.CombinedType;
import logbook.bean.BattleTypes.IAirBaseAttack;
import logbook.bean.BattleTypes.IAirbattle;
import logbook.bean.BattleTypes.IBattle;
import logbook.bean.BattleTypes.ICombinedBattle;
import logbook.bean.BattleTypes.IHougeki;
import logbook.bean.BattleTypes.IKouku;
import logbook.bean.BattleTypes.IMidnightBattle;
import logbook.bean.BattleTypes.ISortieHougeki;
import logbook.bean.BattleTypes.ISupport;
import logbook.bean.BattleTypes.Kouku;
import logbook.bean.BattleTypes.Raigeki;
import logbook.bean.BattleTypes.Stage3;
import logbook.bean.BattleTypes.Stage3Combined;
import logbook.bean.BattleTypes.SupportAiratack;
import logbook.bean.BattleTypes.SupportHourai;
import logbook.bean.BattleTypes.SupportInfo;
import logbook.bean.Enemy;
import logbook.bean.Ship;
public class PhaseState {
private CombinedType combinedType = CombinedType.;
private List<Ship> afterFriend = new ArrayList<>();
private List<Ship> afterFriendCombined = new ArrayList<>();
private List<Enemy> afterEnemy = new ArrayList<>();
/**
*
* @param log
*/
public PhaseState(BattleLog log) {
this(log.getCombinedType(), log.getBattle(), log.getDeckMap());
}
/**
*
* @param combinedType
* @param b
* @param deckMap
*/
public PhaseState(CombinedType combinedType, IBattle b, Map<Integer, List<Ship>> deckMap) {
if (b instanceof ICombinedBattle) {
this.combinedType = combinedType;
}
if (b instanceof ICombinedBattle) {
for (Ship ship : deckMap.get(1)) {
this.afterFriend.add(Optional.ofNullable(ship).map(Ship::clone).orElse(null));
}
for (Ship ship : deckMap.get(2)) {
this.afterFriendCombined.add(Optional.ofNullable(ship).map(Ship::clone).orElse(null));
}
} else {
List<Ship> ships = deckMap.get(b.getDockId());
for (Ship ship : ships) {
this.afterFriend.add(Optional.ofNullable(ship).map(Ship::clone).orElse(null));
}
}
for (int i = 1, s = b.getShipKe().size(); i < s; i++) {
if (b.getShipKe().get(i) != -1) {
Enemy e = new Enemy();
e.setShipId(b.getShipKe().get(i));
e.setLv(b.getShipLv().get(i));
e.setSlot(b.getESlot().get(i - 1));
e.setKyouka(b.getEKyouka().get(i - 1));
this.afterEnemy.add(e);
}
}
this.setInitialHp(b);
}
/**
* <br>
* ps
*
* @param ps
*/
public PhaseState(PhaseState ps) {
this.combinedType = ps.combinedType;
for (Ship ship : ps.afterFriend) {
this.afterFriend.add(Optional.ofNullable(ship).map(Ship::clone).orElse(null));
}
for (Ship ship : ps.afterFriendCombined) {
this.afterFriendCombined.add(Optional.ofNullable(ship).map(Ship::clone).orElse(null));
}
for (Enemy enemy : ps.afterEnemy) {
this.afterEnemy.add(Optional.ofNullable(enemy).map(Enemy::clone).orElse(null));
}
}
/**
*
*
* @param airBaseAttack
*/
public void applyAirBaseAttack(IAirBaseAttack airBaseAttack) {
List<AirBaseAttack> attacks = airBaseAttack.getAirBaseAttack();
if (attacks != null) {
for (AirBaseAttack attack : attacks) {
Stage3 stage3 = attack.getStage3();
if (stage3 != null) {
List<Double> edam = stage3.getEdam();
if (edam != null) {
this.applyEnemyDamage(edam, this.afterEnemy);
}
}
}
}
}
/**
*
* @param battle
*/
public void applyKouku(IKouku battle) {
this.applyKouku(battle.getKouku());
}
/**
*
* @param battle
*/
public void applySupport(ISupport battle) {
SupportInfo support = battle.getSupportInfo();
if (support != null) {
SupportAiratack air = support.getSupportAiratack();
if (air != null) {
Stage3 stage3 = air.getStage3();
if (stage3 != null) {
this.applyEnemyDamage(stage3.getEdam(), this.afterEnemy);
}
}
SupportHourai hou = support.getSupportHourai();
if (hou != null) {
this.applyEnemyDamage(hou.getDamage(), this.afterEnemy);
}
}
}
/**
*
* @param battle
*/
public void applySortieHougeki(ISortieHougeki battle) {
this.applyHougeki(battle.getOpeningTaisen(), null);
this.applyRaigeki(battle.getOpeningAtack());
if (this.combinedType == CombinedType.) {
this.applyHougeki(battle.getHougeki1(), this.afterFriend);
this.applyHougeki(battle.getHougeki2(), this.afterFriend);
this.applyRaigeki(battle.getRaigeki());
} else if (this.combinedType == CombinedType. || this.combinedType == CombinedType.) {
this.applyHougeki(battle.getHougeki1(), this.afterFriendCombined);
this.applyRaigeki(battle.getRaigeki());
this.applyHougeki(battle.getHougeki2(), this.afterFriend);
this.applyHougeki(battle.getHougeki3(), this.afterFriend);
} else if (this.combinedType == CombinedType.) {
this.applyHougeki(battle.getHougeki1(), this.afterFriend);
this.applyHougeki(battle.getHougeki2(), this.afterFriend);
this.applyHougeki(battle.getHougeki3(), this.afterFriendCombined);
this.applyRaigeki(battle.getRaigeki());
}
}
/**
*
* @param battle
*/
public void applyAirbattle(IAirbattle battle) {
this.applyKouku(battle.getKouku2());
}
/**
*
* @param battle
*/
public void applyMidnightBattle(IMidnightBattle battle) {
if (this.combinedType == CombinedType.) {
this.applyHougeki(battle.getHougeki(), this.afterFriend);
} else {
this.applyHougeki(battle.getHougeki(), this.afterFriendCombined);
}
}
/**
*
* @param battle
*/
public void apply(IBattle battle) {
if (battle == null) {
return;
}
if (battle instanceof IAirBaseAttack) {
this.applyAirBaseAttack((IAirBaseAttack) battle);
}
if (battle instanceof IKouku) {
if (((IKouku) battle).getKouku() != null) {
this.applyKouku((IKouku) battle);
}
}
if (battle instanceof ISupport) {
if (((ISupport) battle).getSupportInfo() != null) {
this.applySupport((ISupport) battle);
}
}
if (battle instanceof ISortieHougeki) {
this.applySortieHougeki((ISortieHougeki) battle);
}
if (battle instanceof IAirbattle) {
this.applyAirbattle((IAirbattle) battle);
}
if (battle instanceof IMidnightBattle) {
this.applyMidnightBattle((IMidnightBattle) battle);
}
}
/**
*
* @param kouku
*/
private void applyKouku(Kouku kouku) {
if (kouku == null) {
return;
}
Stage3 stage3 = kouku.getStage3();
if (stage3 != null) {
this.applyFriendDamage(stage3.getFdam(), this.afterFriend);
this.applyEnemyDamage(stage3.getEdam(), this.afterEnemy);
}
Stage3Combined stage3Combined = kouku.getStage3Combined();
if (stage3Combined != null) {
this.applyFriendDamage(stage3Combined.getFdam(), this.afterFriendCombined);
}
}
/**
*
* @param raigeki
*/
private void applyRaigeki(Raigeki raigeki) {
if (raigeki == null) {
return;
}
if (this.combinedType != CombinedType.) {
this.applyFriendDamage(raigeki.getFdam(), this.afterFriendCombined);
} else {
this.applyFriendDamage(raigeki.getFdam(), this.afterFriend);
}
this.applyEnemyDamage(raigeki.getEdam(), this.afterEnemy);
}
/**
*
* @param hougeki
* @param friend
*/
private void applyHougeki(IHougeki hougeki, List<Ship> friend) {
if (hougeki == null) {
return;
}
for (int i = 1, s = hougeki.getDamage().size(); i < s; i++) {
// (1-6,7-12)
int df = hougeki.getDfList().get(i).get(0);
int damage = hougeki.getDamage().get(i)
.stream()
.mapToInt(Double::intValue)
.filter(d -> d > 0)
.sum();
if (df <= 6) {
Ship ship = friend.get(df - 1);
if (ship != null) {
ship.setNowhp(ship.getNowhp() - damage);
}
} else {
Enemy enemy = this.afterEnemy.get(df - 1 - 6);
enemy.setNowhp(enemy.getNowhp() - damage);
}
}
}
/**
*
* @param damage (one-based)
* @param friend
*/
private void applyFriendDamage(List<Double> damages, List<Ship> friend) {
for (int i = 1, s = damages.size(); i < s; i++) {
int damage = damages.get(i).intValue();
if (damage != 0) {
Ship ship = friend.get(i - 1);
if (ship != null) {
ship.setNowhp(ship.getNowhp() - damage);
}
}
}
}
/**
*
* @param damage (one-based)
* @param enemies
*/
private void applyEnemyDamage(List<Double> damages, List<Enemy> enemies) {
for (int i = 1, s = damages.size(); i < s; i++) {
int damage = damages.get(i).intValue();
if (damage != 0) {
Enemy enemy = enemies.get(i - 1);
if (enemy != null) {
enemy.setNowhp(enemy.getNowhp() - damage);
}
}
}
}
/**
* HP
* @param b
*/
private void setInitialHp(IBattle b) {
for (int i = 1, s = b.getMaxhps().size(); i < s; i++) {
if (b.getMaxhps().get(i) == -1) {
continue;
}
if (i <= 6) {
int idx = i - 1;
if (this.afterFriend.get(idx) != null) {
this.afterFriend.get(idx).setMaxhp(b.getMaxhps().get(i));
this.afterFriend.get(idx).setNowhp(b.getNowhps().get(i));
}
} else {
int idx = i - 1 - 6;
if (this.afterEnemy.get(idx) != null) {
this.afterEnemy.get(idx).setMaxhp(b.getMaxhps().get(i));
this.afterEnemy.get(idx).setNowhp(b.getNowhps().get(i));
}
}
}
if (b instanceof ICombinedBattle) {
ICombinedBattle cb = (ICombinedBattle) b;
for (int i = 1, s = cb.getMaxhpsCombined().size(); i < s; i++) {
int idx = i - 1;
if (cb.getMaxhpsCombined().get(i) == -1) {
continue;
}
if (this.afterFriendCombined.get(idx) != null) {
this.afterFriendCombined.get(idx).setMaxhp(cb.getMaxhpsCombined().get(i));
this.afterFriendCombined.get(idx).setNowhp(cb.getNowhpsCombined().get(i));
}
}
}
}
/**
* (1)
* @return (1)
*/
public List<Ship> getAfterFriend() {
return this.afterFriend;
}
/**
* (1)
* @param afterFriend (1)
*/
public void setAfterFriend(List<Ship> afterFriend) {
this.afterFriend = afterFriend;
}
/**
* (2)
* @return (2)
*/
public List<Ship> getAfterFriendCombined() {
return this.afterFriendCombined;
}
/**
* (2)
* @param afterFriendCombined (2)
*/
public void setAfterFriendCombined(List<Ship> afterFriendCombined) {
this.afterFriendCombined = afterFriendCombined;
}
/**
*
* @return
*/
public List<Enemy> getAfterEnemy() {
return this.afterEnemy;
}
/**
*
* @param afterEnemy
*/
public void setAfterEnemy(List<Enemy> afterEnemy) {
this.afterEnemy = afterEnemy;
}
}
|
package me.allenz.zlog;
import android.util.Log;
/**
* A Simple implementation for Logger that prints all messages to Logcat.
*
* @author Allenz
* @since 0.1.0-RELEASE
* @see me.allenz.zlog.Logger
* @see android.util.Log
*/
public class SimpleLogger implements Logger {
protected LogLevel level;
protected String tag;
/**
* Create a new SimpleLogger instance.
*
* @param level
* the LogLevel of the logger
* @param tag
* the tag of the logger
*/
public SimpleLogger(final LogLevel level, final String tag) {
this.level = level;
this.tag = tag;
}
/**
* Internal method that prints log message.
*
* @param level
* the LogLevel of the log message
* @param t
* a throwable(exception) object, can be {@code null}
* @param format
* a format string of the log message, can be {@code null}.
* @param args
* an array of arguments, can be {@code null}
*/
protected void println(final LogLevel level, final Throwable t,
final String format, final Object... args) {
if (this.level.includes(level) && (t != null || format != null)) {
String message = null;
if (format != null && format.length() > 0) {
message = (args != null && args.length > 0) ? String.format(
format, args) : format;
}
if (t != null) {
message = message != null ? message + "\n"
+ Log.getStackTraceString(t) : Log
.getStackTraceString(t);
}
Log.println(level.intValue(), tag, message);
}
}
@Override
public void verbose(final String format, final Object... args) {
println(LogLevel.VERBOSE, null, format, args);
}
@Override
public void verbose(final Throwable t) {
println(LogLevel.VERBOSE, t, null);
}
@Override
public void verbose(final Throwable t, final String format,
final Object... args) {
println(LogLevel.VERBOSE, t, null);
}
@Override
public void debug(final String format, final Object... args) {
println(LogLevel.DEBUG, null, format, args);
}
@Override
public void debug(final Throwable t) {
println(LogLevel.DEBUG, t, null);
}
@Override
public void debug(final Throwable t, final String format,
final Object... args) {
println(LogLevel.DEBUG, t, format, args);
}
@Override
public void info(final String format, final Object... args) {
println(LogLevel.INFO, null, format, args);
}
@Override
public void info(final Throwable t) {
println(LogLevel.INFO, t, null);
}
@Override
public void info(final Throwable t, final String format,
final Object... args) {
println(LogLevel.INFO, t, format, args);
}
@Override
public void warn(final String format, final Object... args) {
println(LogLevel.WARN, null, format, args);
}
@Override
public void warn(final Throwable t) {
println(LogLevel.WARN, t, null);
}
@Override
public void warn(final Throwable t, final String format,
final Object... args) {
println(LogLevel.WARN, t, format, args);
}
@Override
public void error(final String format, final Object... args) {
println(LogLevel.ERROR, null, format, args);
}
@Override
public void error(final Throwable t) {
println(LogLevel.ERROR, t, null);
}
@Override
public void error(final Throwable t, final String format,
final Object... args) {
println(LogLevel.ERROR, t, format, args);
}
@Override
public void wtf(final String format, final Object... args) {
println(LogLevel.ASSERT, null, format, args);
}
@Override
public void wtf(final Throwable t) {
println(LogLevel.ASSERT, t, null);
}
@Override
public void wtf(final Throwable t, final String format,
final Object... args) {
println(LogLevel.ASSERT, t, format, args);
}
}
|
package mezz.jei.input;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityPlayerSP;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraftforge.fml.client.FMLClientHandler;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import mezz.jei.config.Config;
import mezz.jei.config.KeyBindings;
import mezz.jei.gui.Focus;
import mezz.jei.gui.ItemListOverlay;
import mezz.jei.gui.RecipesGui;
import mezz.jei.util.Commands;
import mezz.jei.util.MouseHelper;
import mezz.jei.util.Permissions;
public class InputHandler {
private final RecipesGui recipesGui;
private final ItemListOverlay itemListOverlay;
private final MouseHelper mouseHelper;
private final List<IMouseHandler> mouseHandlers = new ArrayList<>();
private final List<IKeyable> keyables = new ArrayList<>();
private final List<IShowsRecipeFocuses> showsRecipeFocuses = new ArrayList<>();
private boolean clickHandled = false;
public InputHandler(RecipesGui recipesGui, ItemListOverlay itemListOverlay, GuiContainer guiContainer) {
this.recipesGui = recipesGui;
this.itemListOverlay = itemListOverlay;
this.mouseHelper = new MouseHelper();
List<ICloseable> objects = new ArrayList<>();
objects.add(recipesGui);
objects.add(itemListOverlay);
objects.add(new GuiContainerWrapper(guiContainer, recipesGui));
for (Object gui : objects) {
if (gui instanceof IMouseHandler) {
mouseHandlers.add((IMouseHandler) gui);
}
if (gui instanceof IKeyable) {
keyables.add((IKeyable) gui);
}
if (gui instanceof IShowsRecipeFocuses) {
showsRecipeFocuses.add((IShowsRecipeFocuses) gui);
}
}
}
public boolean handleMouseEvent(int mouseX, int mouseY) {
boolean cancelEvent = false;
if (Mouse.getEventButton() > -1) {
if (Mouse.getEventButtonState()) {
if (!clickHandled) {
cancelEvent = handleMouseClick(Mouse.getEventButton(), mouseX, mouseY);
clickHandled = true;
}
} else {
clickHandled = false;
}
} else if (Mouse.getEventDWheel() != 0) {
cancelEvent = handleMouseScroll(Mouse.getEventDWheel(), mouseX, mouseY);
}
return cancelEvent;
}
private boolean handleMouseScroll(int dWheel, int mouseX, int mouseY) {
for (IMouseHandler scrollable : mouseHandlers) {
if (scrollable.handleMouseScrolled(mouseX, mouseY, dWheel)) {
return true;
}
}
return false;
}
private boolean handleMouseClick(int mouseButton, int mouseX, int mouseY) {
Focus focus = getFocusUnderMouseForClick(mouseX, mouseY);
if (focus != null) {
if (handleMouseClickedFocus(mouseButton, focus)) {
return true;
}
}
for (IMouseHandler clickable : mouseHandlers) {
if (clickable.handleMouseClicked(mouseX, mouseY, mouseButton)) {
return true;
}
}
return recipesGui.isOpen();
}
@Nullable
private Focus getFocusUnderMouseForClick(int mouseX, int mouseY) {
for (IShowsRecipeFocuses gui : showsRecipeFocuses) {
if (!(gui instanceof IMouseHandler)) {
continue;
}
Focus focus = gui.getFocusUnderMouse(mouseX, mouseY);
if (focus != null) {
return focus;
}
}
return null;
}
@Nullable
private Focus getFocusUnderMouseForKey(int mouseX, int mouseY) {
for (IShowsRecipeFocuses gui : showsRecipeFocuses) {
Focus focus = gui.getFocusUnderMouse(mouseX, mouseY);
if (focus != null) {
return focus;
}
}
return null;
}
private boolean handleMouseClickedFocus(int mouseButton, @Nonnull Focus focus) {
if (Config.editModeEnabled && GuiScreen.isCtrlKeyDown()) {
Boolean wildcard = null;
if (mouseButton == 0) {
wildcard = false;
} else if (mouseButton == 1) {
wildcard = true;
}
if (wildcard != null) {
if (Config.isItemOnConfigBlacklist(focus.getStack(), wildcard)) {
Config.removeItemFromConfigBlacklist(focus.getStack(), wildcard);
} else {
Config.addItemToConfigBlacklist(focus.getStack(), wildcard);
}
return true;
}
}
EntityPlayerSP player = FMLClientHandler.instance().getClientPlayerEntity();
if (Config.cheatItemsEnabled && Permissions.canPlayerSpawnItems(player)) {
if (mouseButton == 0) {
if (focus.getStack() != null) {
Commands.giveFullStack(focus.getStack());
}
return true;
} else if (mouseButton == 1) {
if (focus.getStack() != null) {
Commands.giveOneFromStack(focus.getStack());
}
return true;
}
}
if (mouseButton == 0) {
recipesGui.showRecipes(focus);
return true;
} else if (mouseButton == 1) {
recipesGui.showUses(focus);
return true;
}
return false;
}
public boolean handleKeyEvent() {
boolean cancelEvent = false;
if (Keyboard.getEventKeyState()) {
int eventKey = Keyboard.getEventKey();
cancelEvent = handleKeyDown(eventKey);
}
return cancelEvent;
}
private boolean handleKeyDown(int eventKey) {
for (IKeyable keyable : keyables) {
if (keyable.isOpen() && keyable.hasKeyboardFocus()) {
if (isInventoryCloseKey(eventKey)) {
keyable.setKeyboardFocus(false);
return true;
} else if (keyable.onKeyPressed(eventKey)) {
return true;
}
}
}
if (isInventoryCloseKey(eventKey) || isInventoryToggleKey(eventKey)) {
if (recipesGui.isOpen()) {
recipesGui.close();
return true;
}
}
if (eventKey == KeyBindings.showRecipe.getKeyCode()) {
Focus focus = getFocusUnderMouseForKey(mouseHelper.getX(), mouseHelper.getY());
if (focus != null) {
recipesGui.showRecipes(focus);
return true;
}
} else if (eventKey == KeyBindings.showUses.getKeyCode()) {
Focus focus = getFocusUnderMouseForKey(mouseHelper.getX(), mouseHelper.getY());
if (focus != null) {
recipesGui.showUses(focus);
return true;
}
} else if (eventKey == KeyBindings.toggleOverlay.getKeyCode() && GuiScreen.isCtrlKeyDown()) {
itemListOverlay.toggleEnabled();
return false;
} else if (eventKey == Keyboard.KEY_F && GuiScreen.isCtrlKeyDown()) {
itemListOverlay.setKeyboardFocus(true);
return true;
}
for (IKeyable keyable : keyables) {
if (keyable.isOpen() && keyable.onKeyPressed(eventKey)) {
return true;
}
}
return false;
}
private boolean isInventoryToggleKey(int keyCode) {
return keyCode == Minecraft.getMinecraft().gameSettings.keyBindInventory.getKeyCode();
}
private boolean isInventoryCloseKey(int keyCode) {
return keyCode == Keyboard.KEY_ESCAPE;
}
}
|
package net.imagej.legacy;
import ij.Executer;
import ij.IJ;
import ij.ImageJ;
import ij.ImagePlus;
import ij.Macro;
import ij.Menus;
import ij.OtherInstance;
import ij.WindowManager;
import ij.gui.ImageWindow;
import ij.gui.Toolbar;
import ij.io.DirectoryChooser;
import ij.io.OpenDialog;
import ij.io.Opener;
import ij.io.SaveDialog;
import ij.macro.Interpreter;
import ij.plugin.Commands;
import ij.plugin.PlugIn;
import ij.plugin.filter.PlugInFilter;
import ij.plugin.filter.PlugInFilterRunner;
import ij.plugin.frame.Recorder;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Image;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.Panel;
import java.awt.Window;
import java.awt.image.ImageProducer;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Callable;
import javax.swing.SwingUtilities;
import net.imagej.display.ImageDisplay;
import net.imagej.patcher.LegacyHooks;
import org.scijava.AbstractContextual;
import org.scijava.Context;
import org.scijava.MenuEntry;
import org.scijava.MenuPath;
import org.scijava.event.EventHandler;
import org.scijava.log.LogService;
import org.scijava.module.ModuleInfo;
import org.scijava.platform.event.AppAboutEvent;
import org.scijava.platform.event.AppOpenFilesEvent;
import org.scijava.platform.event.AppPreferencesEvent;
import org.scijava.platform.event.AppQuitEvent;
import org.scijava.plugin.Parameter;
import org.scijava.script.ScriptService;
import org.scijava.util.ClassUtils;
/**
* A helper class to interact with ImageJ 1.x.
* <p>
* The LegacyService needs to patch ImageJ 1.x's classes before they are
* loaded. Unfortunately, this is tricky: if the LegacyService already
* uses those classes, it is a matter of luck whether we can get the patches in
* before those classes are loaded.
* </p>
* <p>
* Therefore, we put as much interaction with ImageJ 1.x as possible into this
* class and keep a reference to it in the LegacyService.
* </p>
*
* @author Johannes Schindelin
*/
public class IJ1Helper extends AbstractContextual {
/** A reference to the legacy service, just in case we need it. */
private final LegacyService legacyService;
@Parameter
private LogService log;
/** Whether we are in the process of forcibly shutting down ImageJ1. */
private boolean disposing;
public IJ1Helper(final LegacyService legacyService) {
setContext(legacyService.getContext());
this.legacyService = legacyService;
}
public void initialize() {
// initialize legacy ImageJ application
final ImageJ ij1 = IJ.getInstance();
if (Menus.getCommands() == null) {
IJ.runPlugIn("ij.IJ.init", "");
}
if (ij1 != null) {
// NB: *Always* call System.exit(0) when quitting:
// - In the case of batch mode, the JVM needs to terminate at the
// conclusion of the macro/script, regardless of the actions performed
// by that macro/script.
// - In the case of GUI mode, the JVM needs to terminate when the user
// quits the program because ImageJ1 has many plugins which do not
// properly clean up their resources. This is a vicious cycle:
// ImageJ1's main method sets exitWhenQuitting to true, which has
// historically masked the problems with these plugins. So we have
// little choice but to continue this tradition, at least with the
// legacy ImageJ1 user interface.
ij1.exitWhenQuitting(true);
// make sure that the Event Dispatch Thread's class loader is set
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Thread.currentThread().setContextClassLoader(IJ.getClassLoader());
}
});
final LegacyImageMap imageMap = legacyService.getImageMap();
for (int i = 1; i <= WindowManager.getImageCount(); i++) {
imageMap.registerLegacyImage(WindowManager.getImage(i));
}
// set icon and title of main window (which are instantiated before the
// initializer is called)
try {
final LegacyHooks hooks =
(LegacyHooks) IJ.class.getField("_hooks").get(null);
ij1.setTitle(hooks.getAppName());
final URL iconURL = hooks.getIconURL();
if (iconURL != null) try {
final Object producer = iconURL.getContent();
final Image image = ij1.createImage((ImageProducer) producer);
ij1.setIconImage(image);
if (IJ.isMacOSX()) try {
// NB: We also need to set the dock icon
final Class<?> clazz = Class.forName("com.apple.eawt.Application");
final Object app = clazz.getMethod("getApplication").invoke(null);
clazz.getMethod("setDockIconImage", Image.class).invoke(app, image);
}
catch (final Throwable t) {
t.printStackTrace();
}
}
catch (final IOException e) {
IJ.handleException(e);
}
}
catch (final Throwable t) {
t.printStackTrace();
}
// FIXME: handle window location via LegacyUI
// This is necessary because the ImageJ 1.x window will not set its location
// if created with mode NO_SHOW, which is exactly how it is created right
// now by the legacy layer. This is a work-around by ensuring the preferred
// (e.g. saved and loaded) location is current at the time the IJ1Helper
// is initialized. Ideally we would like to handle positioning via
// the LegacyUI though, so that we can restore positions on secondary
// monitors and such.
ij1.setLocation(ij1.getPreferredLocation());
}
}
/**
* Forcibly shuts down ImageJ1, with no user interaction or opportunity to
* cancel. If ImageJ1 is not currently initialized, or if ImageJ1 is already
* in the process of quitting (i.e., {@link ij.ImageJ#quitting()} returns
* {@code true}), then this method does nothing.
*/
public synchronized void dispose() {
final ImageJ ij = IJ.getInstance();
if (ij == null) return; // no ImageJ1 to dispose
if (ij.quitting()) return; // ImageJ1 is already on its way out
disposing = true;
closeImageWindows();
disposeNonImageWindows();
// quit legacy ImageJ on the same thread
ij.exitWhenQuitting(false); // do *not* quit the JVM!
ij.run();
disposing = false;
}
/** Whether we are in the process of forcibly shutting down ImageJ1. */
public boolean isDisposing() {
return disposing;
}
/** Add name aliases for ImageJ1 classes to the ScriptService. */
public void addAliases(final ScriptService scriptService) {
scriptService.addAlias(ImagePlus.class);
}
public boolean isVisible() {
final ImageJ ij = IJ.getInstance();
if (ij == null) return false;
return ij.isVisible();
}
/**
* Determines whether <it>Edit>Options>Misc...>Run single instance listener</it> is set.
*
* @return true if <it>Run single instance listener</it> is set
*/
public boolean isRMIEnabled() {
return OtherInstance.isRMIEnabled();
}
private boolean batchMode;
void setBatchMode(boolean batch) {
Interpreter.batchMode = batch;
batchMode = batch;
}
void invalidateInstance() {
try {
final Method cleanup = IJ.class.getDeclaredMethod("cleanup");
cleanup.setAccessible(true);
cleanup.invoke(null);
} catch (Throwable t) {
t.printStackTrace();
log.error(t);
}
}
/**
* Sets {@link WindowManager} {@code checkForDuplicateName} field.
*/
public void setCheckNameDuplicates(final boolean checkDuplicates) {
WindowManager.checkForDuplicateName = checkDuplicates;
}
public void setVisible(boolean toggle) {
if (batchMode) return;
final ImageJ ij = IJ.getInstance();
if (ij != null) {
if (toggle) ij.pack();
ij.setVisible(toggle);
}
// hide/show the legacy ImagePlus instances
final LegacyImageMap imageMap = legacyService.getImageMap();
for (final ImagePlus imp : imageMap.getImagePlusInstances()) {
final ImageWindow window = imp.getWindow();
if (window != null) window.setVisible(toggle);
}
}
public void syncActiveImage(final ImageDisplay activeDisplay) {
final LegacyImageMap imageMap = legacyService.getImageMap();
final ImagePlus activeImagePlus = imageMap.lookupImagePlus(activeDisplay);
// NB - old way - caused probs with 3d Project
// WindowManager.setTempCurrentImage(activeImagePlus);
// NB - new way - test thoroughly
if (activeImagePlus == null) WindowManager.setCurrentWindow(null);
else WindowManager.setCurrentWindow(activeImagePlus.getWindow());
}
public void setKeyDown(int keyCode) {
IJ.setKeyDown(keyCode);
}
public void setKeyUp(int keyCode) {
IJ.setKeyUp(keyCode);
}
public boolean hasInstance() {
return IJ.getInstance() != null;
}
/** Gets the version of ImageJ 1.x. */
public String getVersion() {
// NB: We cannot hardcode a reference to ImageJ.VERSION. Java often inlines
// string constants at compile time. This means that if a different version
// of ImageJ 1.x is used at runtime, this method could return an incorrect
// value. Calling IJ.getVersion() would be more reliable, except that we
// override its behavior to return LegacyHooks#getAppVersion(). So instead,
// we resort to referencing the ImageJ#VERSION constant via reflection.
try {
final Field field = ImageJ.class.getField("VERSION");
if (field != null) {
final Object version = field.get(null);
if (version != null) return version.toString();
}
}
catch (NoSuchFieldException exc) {
log.error(exc);
}
catch (IllegalAccessException exc) {
log.error(exc);
}
return "Unknown";
}
public boolean isMacintosh() {
return IJ.isMacintosh();
}
public void setStatus(String message) {
IJ.showStatus(message);
}
public void setProgress(int val, int max) {
IJ.showProgress(val, max);
}
public Component getToolBar() {
return Toolbar.getInstance();
}
public Panel getStatusBar() {
if (!hasInstance()) return null;
return IJ.getInstance().getStatusBar();
}
public Frame getIJ() {
if (hasInstance()) {
return IJ.getInstance();
}
return null;
}
public void setLocation(final int x, final int y) {
if (!hasInstance()) return;
IJ.getInstance().setLocation(x, y);
}
public int getX() {
if (!hasInstance()) return 0;
return IJ.getInstance().getX();
}
public int getY() {
if (!hasInstance()) return 0;
return IJ.getInstance().getY();
}
public boolean isWindowClosed(Frame window) {
if (window instanceof ImageWindow) {
return ((ImageWindow) window).isClosed();
}
return false;
}
public boolean quitting() {
if (hasInstance()) return IJ.getInstance().quitting();
return false;
}
public int[] getIDList() {
return WindowManager.getIDList();
}
public ImagePlus getImage(int imageID) {
return WindowManager.getImage(imageID);
}
public ClassLoader getClassLoader() {
return IJ.getClassLoader();
}
public void showMessage(String title, String message) {
IJ.showMessage(title, message);
}
public boolean showMessageWithCancel(String title, String message) {
return IJ.showMessageWithCancel(title, message);
}
public String commandsName() {
return Commands.class.getName();
}
public void updateRecentMenu(final String path) {
Menu menu = Menus.getOpenRecentMenu();
if (menu == null) return;
int n = menu.getItemCount();
int index = -1;
for (int i=0; i<n; i++) {
if (menu.getItem(i).getLabel().equals(path)) {
index = i;
break;
}
}
// Move to most recent
if (index > 0) {
final MenuItem item = menu.getItem(index);
menu.remove(index);
menu.insert(item, 0);
}
// not found, so replace oldest
else if (index < 0) {
int count = menu.getItemCount();
if (count >= Menus.MAX_OPEN_RECENT_ITEMS) {
menu.remove(count - 1);
}
final MenuItem item = new MenuItem(path);
final ImageJ instance = IJ.getInstance();
if (instance != null) item.addActionListener(instance);
menu.insert(item, 0);
}
// if index was 0, already at the head so do nothing
}
/**
* Opens an image and adds the path to the <it>File>Open Recent</it> menu.
*
* @param file the image to open
*/
public static void openAndAddToRecent(final File file) {
new Opener().openAndAddToRecent(file.getAbsolutePath());
}
/**
* Records an option in ImageJ 1.x's macro recorder.
*
* @param key the name of the option
* @param value the value of the option
*/
public void recordOption(final String key, final String value) {
Recorder.recordOption(key, value);
}
/**
* Determines whether we're running inside a macro right now.
*
* @return whether we're running a macro right now.
*/
public boolean isMacro() {
return IJ.isMacro();
}
/**
* Gets a macro parameter of type <i>boolean</i>.
*
* @param label
* the name of the macro parameter
* @param defaultValue
* the default value
* @return the boolean value
*/
public boolean getMacroParameter(String label, boolean defaultValue) {
return getMacroParameter(label) != null || defaultValue;
}
/**
* Gets a macro parameter of type <i>double</i>.
*
* @param label
* the name of the macro parameter
* @param defaultValue
* the default value
* @return the double value
*/
public double getMacroParameter(String label, double defaultValue) {
String value = Macro.getValue(getOptions(), label, null);
return value != null ? Double.parseDouble(value) : defaultValue;
}
/**
* Gets a macro parameter of type {@link String}.
*
* @param label
* the name of the macro parameter
* @param defaultValue
* the default value
* @return the value
*/
public String getMacroParameter(String label, String defaultValue) {
return Macro.getValue(getOptions(), label, defaultValue);
}
/**
* Gets a macro parameter of type {@link String}.
*
* @param label
* the name of the macro parameter
* @return the value, <code>null</code> if the parameter was not specified
*/
public String getMacroParameter(String label) {
return Macro.getValue(getOptions(), label, null);
}
/** Gets the SciJava application context linked to the ImageJ 1.x instance. */
public static Context getLegacyContext() {
// NB: This call instantiates a Context if there is none.
// IJ.runPlugIn() will be intercepted by the legacy hooks if they are
// installed and return the current Context.
// If no legacy hooks are installed, ImageJ 1.x will instantiate the Context
// using the PluginClassLoader and the LegacyService will install the legacy
// hooks.
final Object o = IJ.runPlugIn("org.scijava.Context", "");
if (o == null) return null;
if (!(o instanceof Context)) {
throw new IllegalStateException("Unexpected type of context: " +
o.getClass().getName());
}
return (Context) o;
}
/**
* Partial replacement for ImageJ 1.x's MacAdapter.
* <p>
* ImageJ 1.x has a MacAdapter plugin that intercepts MacOSX-specific events
* and handles them. The way it does it is deprecated now, however, and
* unfortunately incompatible with the way ImageJ 2's platform service does
* it.
* </p>
* <p>
* This class implements the same functionality as the MacAdapter, but in a
* way that is compatible with the SciJava platform service.
* </p>
* <p>
* Note that the {@link AppAboutEvent}, {@link AppPreferencesEvent} and
* {@link AppQuitEvent} are handled separately, indirectly, by the
* {@link LegacyImageJApp}. See also {@link IJ1Helper#appAbout},
* {@link IJ1Helper#appPrefs} and {@link IJ1Helper#appQuit}.
* </p>
*
* @author Johannes Schindelin
*/
private static class LegacyEventDelegator extends AbstractContextual {
@Parameter(required = false)
private LegacyService legacyService;
// -- MacAdapter re-implementations --
/** @param event */
@EventHandler
private void onEvent(final AppOpenFilesEvent event) {
if (isLegacyMode()) {
final List<File> files = new ArrayList<File>(event.getFiles());
for (final File file : files) {
openAndAddToRecent(file);
}
}
}
private boolean isLegacyMode() {
// We call setContext() indirectly from LegacyService#initialize,
// therefore legacyService might still be null at this point even if the
// context knows a legacy service now.
if (legacyService == null) {
final Context context = getContext();
if (context != null) legacyService = context.getService(LegacyService.class);
}
return legacyService != null && legacyService.isLegacyMode();
}
}
private static LegacyEventDelegator eventDelegator;
public static void subscribeEvents(final Context context) {
if (context == null) {
eventDelegator = null;
} else {
eventDelegator = new LegacyEventDelegator();
eventDelegator.setContext(context);
}
}
static void run(Class<?> c) {
IJ.resetEscape();
if (PlugIn.class.isAssignableFrom(c)) {
try {
final PlugIn plugin = (PlugIn) c.newInstance();
plugin.run("");
} catch (Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e
: new RuntimeException(e);
}
return;
}
if (PlugInFilter.class.isAssignableFrom(c)) {
try {
final PlugInFilter plugin = (PlugInFilter) c.newInstance();
ImagePlus image = WindowManager.getCurrentImage();
if (image != null && image.isLocked()) {
if (!IJ.showMessageWithCancel("Unlock image?", "The image '" + image.getTitle()
+ "'appears to be locked... Unlock?"))
return;
image.unlock();
}
new PlugInFilterRunner(plugin, c.getName(), "");
} catch (Exception e) {
throw e instanceof RuntimeException ? (RuntimeException) e
: new RuntimeException(e);
}
return;
}
throw new RuntimeException("TODO: construct class loader");
}
private boolean menuInitialized;
/**
* Adds legacy-compatible scripts and commands to the ImageJ1 menu structure.
*/
public synchronized void addMenuItems() {
if (menuInitialized) return;
final Map<String, ModuleInfo> modules =
legacyService.getScriptsAndNonLegacyCommands();
@SuppressWarnings("unchecked")
final Hashtable<String, String> ij1Commands = Menus.getCommands();
final ImageJ ij1 = hasInstance() ? IJ.getInstance() : null;
final IJ1MenuWrapper wrapper = ij1 == null ? null : new IJ1MenuWrapper(ij1);
class Item implements Comparable<Item> {
private double weight;
private MenuPath path;
private String name, identifier;
private ModuleInfo info;
@Override
public int compareTo(Item o) {
if (weight != o.weight) return Double.compare(weight, o.weight);
return compare(path, o.path);
}
public int compare(final MenuPath a, final MenuPath b) {
int i = 0;
while (i < a.size() && i < b.size()) {
final MenuEntry a2 = a.get(i), b2 = b.get(i);
int diff = Double.compare(a.get(i).getWeight(), b.get(i).getWeight());
if (diff != 0) return diff;
diff = a2.getName().compareTo(b2.getName());
if (diff != 0) return diff;
i++;
}
return 0;
}
}
final List<Item> items = new ArrayList<Item>();
for (final Entry<String, ModuleInfo> entry : modules.entrySet()) {
final String key = entry.getKey();
final ModuleInfo info = entry.getValue();
final MenuEntry leaf = info.getMenuPath().getLeaf();
if (leaf == null) continue;
final MenuPath path = info.getMenuPath();
final String name = leaf.getName();
final Item item = new Item();
item.weight = leaf.getWeight();
item.path = path;
item.name = name;
item.identifier = key;
item.info = info;
items.add(item);
}
// sort by menu weight, then alphabetically
Collections.sort(items);
for (final Item item : items) {
if (ij1Commands.containsKey(item.name)) {
log.info("Overriding " + item.name
+ "; identifier: " + item.identifier
+ "; jar: " + ClassUtils.getLocation(item.info.getDelegateClassName()));
if (wrapper != null) try {
wrapper.create(item.path, true);
}
catch (final Throwable t) {
log.error(t);
}
}
else if (wrapper != null) try {
wrapper.create(item.path, false);
}
catch (final Throwable t) {
log.error(t);
}
ij1Commands.put(item.name, item.identifier);
}
menuInitialized = true;
}
/**
* Helper class for wrapping ImageJ2 menu paths to ImageJ1 {@link Menu}
* structures, and inserting them into the proper positions of the
* {@link MenuBar}.
*/
private static class IJ1MenuWrapper {
final ImageJ ij1;
final MenuBar menuBar = Menus.getMenuBar();
final Map<String, Menu> structure = new HashMap<String, Menu>();
final Set<Menu> separators = new HashSet<Menu>();
private IJ1MenuWrapper(final ImageJ ij1) {
this.ij1 = ij1;
}
/**
* Creates a {@link MenuItem} matching the structure of the provided path.
* Expected path structure is:
* <p>
* <ul>Level1 > Level2 > ... > Leaf entry</ul>
* </p>
* <p>
* For example, a valid path would be:
* </p>
* <p>
* <ul>Edit > Options > ImageJ2 plugins > Discombobulator</ul>
* </p>
*/
private MenuItem create(final MenuPath path, final boolean reuseExisting) {
// Find the menu structure where we can insert our command.
// NB: size - 1 is the leaf position, so we want to go to size - 2 to
// find the parent menu location
final Menu menu = getParentMenu(path, path.size() - 2);
final String label = path.getLeaf().getName();
// If we are overriding an item, find the item being overridden
if (reuseExisting) {
for (int i = 0; i < menu.getItemCount(); i++) {
final MenuItem item = menu.getItem(i);
if (label.equals(item.getLabel())) {
return item;
}
}
}
if (!separators.contains(menu)) {
if (menu.getItemCount() > 0) menu.addSeparator();
separators.add(menu);
}
// Otherwise, we are creating a new item
final MenuItem item = new MenuItem(label);
menu.insert(item, getIndex(menu, label));
item.addActionListener(ij1);
return item;
}
/**
* Helper method to look up special cases for menu weighting
*/
private int getIndex(Menu menu, String label) {
// Place export sub-menu after import sub-menu
if (menu.getLabel().equals("File") && label.equals("Export")) {
for (int i=0; i<menu.getItemCount(); i++) {
final MenuItem menuItem = menu.getItem(i);
if (menuItem.getLabel().equals("Import")) return i + 1;
}
}
//TODO pass and use actual command weight from IJ2.. maybe?
// No special case: append to end of menu
return menu.getItemCount();
}
/**
* Recursive helper method to builds the final {@link Menu} structure.
*/
private Menu getParentMenu(final MenuPath menuPath, int depth) {
final MenuEntry currentItem = menuPath.get(depth);
final String currentLabel = currentItem.getName();
// Check to see if we already know the menu associated with the desired
// label/path
final Menu cached = structure.get(currentLabel);
if (cached != null) return cached;
// We are at the root of the menu, so see if we have a matching menu
if (depth == 0) {
// Special case check the help menu
if ("Help".equals(currentLabel)) {
final Menu menu = menuBar.getHelpMenu();
structure.put(currentLabel, menu);
return menu;
}
// Check the other menus of the menu bar to see if our desired label
// already exists
for (int i = 0; i < menuBar.getMenuCount(); i++) {
final Menu menu = menuBar.getMenu(i);
if (currentLabel.equals(menu.getLabel())) {
structure.put(currentLabel, menu);
return menu;
}
}
// Didn't find a match so we have to create a new menu entry
final Menu menu = new Menu(currentLabel);
menuBar.add(menu);
structure.put(currentLabel, menu);
return menu;
}
final Menu parent = getParentMenu(menuPath, depth - 1);
// Once the parent of this entry is obtained, we need to check if it
// already contains the current entry.
for (int i = 0; i < parent.getItemCount(); i++) {
final MenuItem item = parent.getItem(i);
if (currentLabel.equals(item.getLabel())) {
if (item instanceof Menu) {
// Found a menu entry that matches our desired label, so return
final Menu menu = (Menu) item;
structure.put(currentLabel, menu);
return menu;
}
// Found a match but it was an existing non-menu item, so our menu
// structure is invalid.
//TODO consider mangling the IJ2 menu name instead...
throw new IllegalArgumentException("Not a menu: " + currentLabel);
}
}
if (!separators.contains(parent)) {
if (parent.getItemCount() > 0) parent.addSeparator();
separators.add(parent);
}
// An existing entry in the parent menu was not found, so we need to
// create a new entry.
final Menu menu = new Menu(currentLabel);
parent.insert(menu, getIndex(parent, menu.getLabel()));
structure.put(currentLabel, menu);
return menu;
}
}
private<T> T runMacroFriendly(final String type, final Callable<T> call) {
if (EventQueue.isDispatchThread()) {
throw new IllegalStateException("Cannot run macro from the EDT!");
}
final Thread thread = Thread.currentThread();
final String name = thread.getName();
try {
// to make getOptions() work
if (!name.startsWith("Run$_")) thread.setName("Run$_" + name);
// to make Macro.abort() work
if (!name.endsWith("Macro$")) thread.setName(thread.getName() + "Macro$");
return call.call();
}
catch (final RuntimeException e) {
throw e;
} catch (final Exception e) {
throw new RuntimeException(e);
}
finally {
thread.setName(name);
}
}
/**
* Evaluates the specified command.
*
* @param command the command to execute
*/
public void run(final String command) {
runMacroFriendly("macro", new Callable<Void>() {
@Override
public Void call() throws Exception {
IJ.run(command);
return null;
}
});
}
/**
* Evaluates the specified macro.
*
* @param macro the macro to evaluate
* @return the return value
*/
public String runMacro(final String macro) {
return runMacroFriendly("macro", new Callable<String>() {
@Override
public String call() throws Exception {
return IJ.runMacro(macro);
}
});
}
/**
* Evaluates the specified macro.
*
* @param path the macro file to evaluate
* @param arg the macro argument
* @return the return value
*/
public String runMacroFile(final String path, final String arg) {
return runMacroFriendly("macro", new Callable<String>() {
@Override
public String call() throws Exception {
return IJ.runMacroFile(path, arg);
}
});
}
/**
* Opens an image using ImageJ 1.x.
*
* @param path the image file to open
* @return the image
*/
public Object openImage(final String path) {
return openImage(path, false);
}
/**
* Opens an image using ImageJ 1.x.
*
* @param path the image file to open
* @return the image
*/
public Object openImage(final String path, final boolean show) {
final ImagePlus imp = IJ.openImage(path);
if (show && imp != null) imp.show();
return imp;
}
/**
* Opens a path using ImageJ 1.x, bypassing the (javassisted) IJ utility
* class.
*
* @param path the image file to open
*/
public void openPathDirectly(final String path) {
new Opener().open(path);
}
/**
* Enables or disables ImageJ 1.x' debug mode.
*
* @param debug whether to show debug messages or not
*/
public void setDebugMode(final boolean debug) {
IJ.debugMode = debug;
}
/**
* Delegate exception handling to ImageJ 1.x.
*
* @param e the exception to handle
*/
public void handleException(Throwable e) {
IJ.handleException(e);
}
/**
* Ask ImageJ 1.x whether it thinks whether the Shift key is held down.
*
* @return whether the Shift key is considered <i>down</i>
*/
public boolean shiftKeyDown() {
return IJ.shiftKeyDown();
}
/**
* Delegates to ImageJ 1.x' {@link Macro#getOptions()} function.
*
* @return the macro options, or null
*/
public String getOptions() {
final String options = Macro.getOptions();
return options == null ? "" : options;
}
/**
* Delegates to ImageJ 1.x' {@link Macro#setOptions(String)} function.
*
* @param options the macro options, or null to reset
*/
public void setOptions(final String options) {
Macro.setOptions(options);
}
/** Handles shutdown of ImageJ 1.x. */
public void appQuit() {
if (legacyService.isLegacyMode()) {
new Executer("Quit", null); // works with the CommandListener
}
}
/** Displays the About ImageJ 1.x dialog. */
public void appAbout() {
if (legacyService.isLegacyMode()) {
IJ.run("About ImageJ...");
}
}
/** Sets OpenDialog's default directory */
public void setDefaultDirectory(final File directory) {
OpenDialog.setDefaultDirectory(directory.getPath());
}
/** Uses ImageJ 1.x' OpenDialog */
public File openDialog(final String title) {
final OpenDialog openDialog = new OpenDialog(title);
final String directory = openDialog.getDirectory();
final String fileName = openDialog.getFileName();
if (directory != null && fileName != null) {
return new File(directory, fileName);
}
return null;
}
/** Uses ImageJ 1.x' SaveDialog */
public File saveDialog(final String title, final File file, final String extension) {
// Use ImageJ1's SaveDialog.
final int dotIndex = file.getName().indexOf('.');
final String defaultName =
dotIndex > 0 ? file.getName().substring(0, dotIndex) : file
.getName();
final SaveDialog saveDialog =
new SaveDialog(title, defaultName, extension);
final String directory = saveDialog.getDirectory();
final String fileName = saveDialog.getFileName();
if (directory != null && fileName != null) {
return new File(directory, fileName);
}
return null;
}
/** Chooses a directory using ImageJ 1.x' directory chooser. */
public String getDirectory(final String title, final File file) {
final String defaultDir =
file.isDirectory() ? file.getPath() : file.getParent();
DirectoryChooser.setDefaultDirectory(defaultDir);
return new DirectoryChooser(title).getDirectory();
}
/** Handles display of the ImageJ 1.x preferences. */
public void appPrefs() {
if (legacyService.isLegacyMode()) {
IJ.error("The ImageJ preferences are in the Edit>Options menu.");
}
}
// -- Helper methods --
/** Closes all image windows on the event dispatch thread. */
private void closeImageWindows() {
// TODO: Consider using ThreadService#invoke to simplify this logic.
final Runnable run = new Runnable() {
@Override
public void run() {
// close out all image windows, without dialog prompts
while (true) {
final ImagePlus imp = WindowManager.getCurrentImage();
if (imp == null) break;
imp.changes = false;
imp.close();
}
}
};
if (EventQueue.isDispatchThread()) {
run.run();
}
else {
try {
EventQueue.invokeAndWait(run);
}
catch (final Exception e) {
// report & ignore
log.error(e);
}
}
}
private void disposeNonImageWindows() {
disposeNonImageFrames();
disposeOtherNonImageWindows();
}
/**
* Disposes all the non-image window frames, as given by
* {@link WindowManager#getNonImageWindows()}.
*/
private void disposeNonImageFrames() {
for (Frame frame : WindowManager.getNonImageWindows()) {
frame.dispose();
}
}
/**
* Ensures <em>all</em> the non-image windows are closed.
* <p>
* This is a non-trivial problem, as
* {@link WindowManager#getNonImageWindows()} <em>only</em> returns
* {@link Frame}s. However there are non-image, non-{@link Frame} windows that
* are critical to close: for example, the
* {@link ij.plugin.frame.ContrastAdjuster} spawns a polling thread to do its
* work, which will continue to run until the {@code ContrastAdjuster} is
* explicitly closed.
* </p>
*/
private void disposeOtherNonImageWindows() {
// NB: As of v1.49b, getNonImageTitles is not restricted to Frames,
// so we can use it to iterate through the available windows.
for (String title : WindowManager.getNonImageTitles()) {
final Window window = WindowManager.getWindow(title);
// NB: We can NOT set these windows as active and run the Commands
// plugin with argument "close", because the default behavior is to
// try closing the window as an Image. As we know these are not Images,
// that is never the right thing to do.
WindowManager.removeWindow(window);
window.dispose();
}
}
}
|
package org.animotron.walker;
import static org.animotron.graph.AnimoGraph.beginTx;
import static org.animotron.graph.AnimoGraph.finishTx;
import static org.neo4j.graphdb.Direction.OUTGOING;
import java.io.IOException;
import java.util.Iterator;
import org.animotron.Catcher;
import org.animotron.Executor;
import org.animotron.Startable;
import org.animotron.io.PipedInput;
import org.animotron.io.PipedOutput;
import org.animotron.manipulator.Manipulator;
import org.animotron.marker.Marker;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.PropertyContainer;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.Transaction;
/**
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
*
*/
public abstract class Walker implements Runnable, Startable {
private Manipulator m;
private PropertyContainer op;
private PipedOutput out;
private Marker marker;
public Walker(Manipulator m, PropertyContainer op, PipedOutput out, Marker marker) {
this.m = m;
this.op = op;
this.out = out;
this.marker = marker;
if (marker !=null)
marker.mark(op instanceof Node ? (Node) op : ((Relationship) op).getEndNode());
}
@Override
public final void run() {
Catcher catcher = new Catcher();
Transaction tx = beginTx();
try {
if (op instanceof Node)
go((Node) op, out, catcher);
else
go((Relationship) op, out, catcher);
if (marker != null)
marker.drop();
tx.success();
} catch (IOException e) {
e.printStackTrace();
catcher = null;
tx.failure();
} finally {
finishTx(tx);
}
if (catcher != null)
catcher.run();
}
private void go(Relationship op, PipedOutput ot, Catcher catcher) throws IOException {
go(op.getEndNode(), ot, catcher);
}
private final void go(Node node, PipedOutput ot, Catcher catcher) throws IOException {
//System.out.println("Walk node = " + node);
Iterator<Relationship> it = node.getRelationships(OUTGOING).iterator();
while (it.hasNext()) {
Relationship r = it.next();
PipedInput in = null;
PipedOutput out = ot;
if (m.isPiped()) {
in = new PipedInput();
out = new PipedOutput(in);
}
go(r, out, catcher, isLast(it));
if (in != null) {
for (Object n : in) {
ot.write(n);
}
}
if (m.isPiped()) {
out.close();
}
}
ot.close();
}
protected abstract void go(Relationship op, PipedOutput ot, Catcher catcher, boolean isLast) throws IOException;
private boolean isLast(Iterator<?> it) {
return !it.hasNext();
}
protected final Manipulator getManipulator(){
return m;
}
public final void start() {
Executor.execute(this);
}
}
|
package org.avaje.metric;
/**
* Standard JVM metrics built in that we often register.
*/
public interface JvmMetrics {
/**
* Set to only report when the metrics change. This is the default and means
* that metrics that don't change are not reported.
*/
JvmMetrics withReportChangesOnly();
/**
* Set to report the metrics irrespective of whether the metric has changed.
* <p>
* For metrics that generally don't change like max memory or don't change as
* frequently these metrics will be reported every time.
* </p>
*/
JvmMetrics withReportAlways();
/**
* Register all the standard JVM metrics - memory, threads, gc, os load and process memory.
*/
void registerStandardJvmMetrics();
/**
* Register a metric for OS load.
*/
void registerJvmOsLoadMetric();
/**
* Register metrics for GC activity.
*/
void registerJvmGCMetrics();
/**
* Register metrics for the total number of threads allocated.
*/
void registerJvmThreadMetrics();
/**
* Register metrics for heap and non-heap memory.
*/
void registerJvmMemoryMetrics();
/**
* Register metrics for VMRSS process memory (if supported on the platform).
*/
void registerJvmProcessMemoryMetrics();
}
|
package org.databene.commons;
import java.util.Arrays;
import java.util.Collection;
/**
* An assertion utility.<br/><br/>
* Created at 25.04.2008 17:59:43
* @since 0.4.2
* @author Volker Bergmann
*/
public class Assert {
private Assert() {}
public void end(String text, String end) {
if (text == null) {
if (end != null)
throw new AssertionError("String is supposed to end with '" + end + ", but is null.");
} else if (!text.endsWith(end))
throw new AssertionError("String is supposed to end with '" + end + ", but is: " + text);
}
public static void endIgnoreCase(String text, String end) {
if (text == null) {
if (end != null)
throw new AssertionError("String is supposed to end with '" + end + ", but is null.");
} else if (!text.endsWith(end))
throw new AssertionError("String is supposed to case-insensitively end with '" + end
+ ", but is: " + text);
}
public static <T> T notNull(T object, String objectRole) {
if (object == null)
throw new AssertionError(objectRole + " is not supposed to be null");
return object;
}
public static void notEmpty(String text, String message) {
if (text == null || text.length() == 0)
throw new AssertionError(message);
}
public static void notEmpty(Collection<?> collection, String message) {
if (collection == null || collection.size() == 0)
throw new AssertionError(message);
}
@SuppressWarnings("null")
public static void equals(Object a1, Object a2, String message) {
if (a1 == null && a2 == null)
return;
else if ((a1 == null && a2 != null) || (a1 != null && a2 == null))
throw new AssertionError(message);
else if (!a1.equals(a2))
throw new AssertionError(message);
}
@SuppressWarnings("null")
public static <T> void equals(T[] a1, T[] a2) {
if (a1 == null && a2 == null)
return;
else if ((a1 == null && a2 != null) || (a1 != null && a2 == null))
throw new AssertionError("Arrays are not equal, one of them is null");
else if (a1.length != a2.length)
throw new AssertionError("Arrays are not equal, the size differs: [" +
ArrayFormat.format(a1) + "] vs. [" + ArrayFormat.format(a2) + ']');
else if (!Arrays.deepEquals(a1, a2))
throw new AssertionError("Arrays are not equal, content differs: [" +
ArrayFormat.format(a1) + "] vs. [" + ArrayFormat.format(a2) + ']');
}
@SuppressWarnings("null")
public static void equals(byte[] a1, byte[] a2) {
if (a1 == null && a2 == null)
return;
else if ((a1 == null && a2 != null) || (a1 != null && a2 == null))
throw new AssertionError("Arrays are not equal, one of them is null");
else if (a1.length != a2.length)
throw new AssertionError("Arrays are not equal, the size differs: [" +
ArrayFormat.formatBytes(",", a1) + "] vs. [" + ArrayFormat.formatBytes(",", a2) + ']');
else if (!Arrays.equals(a1, a2))
throw new AssertionError("Arrays are not equal, content differs: [" +
ArrayFormat.formatBytes(",", a1) + "] vs. [" + ArrayFormat.formatBytes(",", a2) + ']');
}
public static void length(String string, int length) {
if (string == null || string.length() != length)
throw new AssertionError("Unexpected string length: Expected string of length " + length + ", found: "
+ (string != null ? string.length() : "null"));
}
public static void startsWith(String prefix, String string) {
if (string == null || !string.startsWith(prefix))
throw new AssertionError("Expected prefix '" + prefix + "' is missing in: " + string);
}
public static void endsWith(String suffix, String string) {
if (string == null || !string.endsWith(suffix))
throw new AssertionError("Expected suffix '" + suffix + "' is missing in: " + string);
}
public static void instanceOf(Object object, Class<?> type, String name) {
if (object == null)
throw new AssertionError(name + " is not supposed to be null");
if (!type.isAssignableFrom(object.getClass()))
throw new AssertionError(name + " is expected to be of type " + type.getName() + ", but is " + object.getClass());
}
public static void isTrue(boolean expression, String message) {
if (!expression)
throw new AssertionError(message);
}
public static void found(Object object, String name) {
if (object == null)
throw new AssertionError(name + " not found");
}
public static void notNegative(Number value, String role) {
if (value.doubleValue() < 0)
throw new AssertionError(role + " is less than zero: " + value);
}
public static void positive(Number value, String role) {
if (value.doubleValue() <= 0)
throw new AssertionError(role + " is not positive: " + value);
}
public static void that(boolean flag, String message) {
if (!flag)
throw new AssertionError(message);
}
}
|
package org.gbif.dwc.terms;
import java.io.Serializable;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
public enum GbifTerm implements Term, AlternativeNames, Serializable {
// row types
Description(GbifTerm.GROUP_ROW_TYPE),
Distribution(GbifTerm.GROUP_ROW_TYPE),
Identifier(GbifTerm.GROUP_ROW_TYPE),
Image(GbifTerm.GROUP_ROW_TYPE, "Images"),
Reference(GbifTerm.GROUP_ROW_TYPE, "References"),
SpeciesProfile(GbifTerm.GROUP_ROW_TYPE, "SpeciesMiniProfile", "SpeciesInfo", "SpeciesData", "SpeciesFactsheet"),
TypesAndSpecimen(GbifTerm.GROUP_ROW_TYPE, "Specimen", "Types", "TypeDesignation"),
VernacularName(GbifTerm.GROUP_ROW_TYPE, "VernacularNames", "Vernacular", "Vernaculars"),
Multimedia(GbifTerm.GROUP_ROW_TYPE),
/**
* The UUID key for the dataset registered in GBIF.
*/
datasetKey(GbifTerm.GROUP_DATASET),
/**
* The ISO code of the country of the organization that publishes the dataset to which the occurrence belongs.
*/
publishingCountry(GbifTerm.GROUP_DATASET),
/**
* Numerical, stable identifier assigned by GBIF to an Occurrence record.
*/
gbifID(DwcTerm.GROUP_OCCURRENCE),
/**
* Timestamp of the last time the record has been (re)interpreted by GBIF.
*/
lastInterpreted(DwcTerm.GROUP_OCCURRENCE),
/**
* The uncertainty radius for lat/lon in decimal degrees.
*/
@Deprecated
coordinateAccuracy(DwcTerm.GROUP_OCCURRENCE),
/**
* Elevation in meters above sea level (altitude).
* <p>
* The elevation is the absolute vertical position of the observed location (z-coordinate).
* If depth is given or not will not impact the 3-dimensional position.
* For example a location 100m below the surface of a lake in 2000m altitude has a depth of 100 and
* an elevation of 1900.
* </p>
* <p>
* If minimum and maximum values are given the elevation is calculated using the equation:
* (minimumElevationInMeters + maximumElevationInMeters) / 2.
* For consistency and ease of use GBIF decided to always use a value in meters plus it's accurracy instead of
* min/max values which are sometimes used in Darwin Core. See also depth & distanceAboveSurface.
* </p>
*/
elevation(DwcTerm.GROUP_LOCATION),
/**
* Elevation accuracy is the uncertainty for the elevation in meters.
* <p>
* The elevation accuracy is calculated using the equation: (maximumElevationInMeters - minimumElevationInMeters) / 2
* in case a minimum and maximum verbatim value is given.
* </p>
*/
elevationAccuracy(DwcTerm.GROUP_LOCATION),
/**
* Depth in meters below the surface.
* <p>
* Complimentary and relative to elevation, depth indicates the distance to the earth surface, whether that is water
* or ground.
* For example a location 100m below the surface of a lake in 2000m altitude has a depth of 100 and
* an elevation of 1900.
* </p>
* <p>
* The depth is calculated using the equation: (minimumDepthInMeters + maximumDepthInMeters) / 2.
* For consistency and ease of use GBIF decided to always use a value in meters plus it's accurracy instead of
* min/max values which are sometimes used in Darwin Core. See also elevation & distanceAboveSurface.
* </p>
*/
depth(DwcTerm.GROUP_LOCATION),
/**
* Depth accuracy is the uncertainty for the depth in meters.
* <p>
* The depth accuracy is calculated using the equation: (maximumDepthInMeters - minimumDepthInMeters) / 2
* in case a minimum and maximum verbatim value is given.
* </p>
*/
depthAccuracy(DwcTerm.GROUP_LOCATION),
distanceAboveSurface(DwcTerm.GROUP_LOCATION),
distanceAboveSurfaceAccuracy(DwcTerm.GROUP_LOCATION),
issue(DwcTerm.GROUP_OCCURRENCE),
/**
* The media type given as Dublin Core type values, in particular StillImage, MovingImage or Sound.
*/
mediaType(DwcTerm.GROUP_OCCURRENCE),
// experimental Occurrence properties
verbatimLabel(DwcTerm.GROUP_OCCURRENCE),
infraspecificMarker(DwcTerm.GROUP_OCCURRENCE),
// Types and Specimen checklist extension
typeDesignatedBy(DwcTerm.GROUP_OCCURRENCE),
typeDesignationType(DwcTerm.GROUP_OCCURRENCE),
/**
* Boolean indicating that a valid latitude and longitude exists.
* Even if existing it might still have issues, see hasGeospatialIssues and issue.
*/
hasCoordinate(DwcTerm.GROUP_OCCURRENCE),
/**
* Boolean indicating that some spatial validation rule has not passed.
* Primarily used to indicate that the record should not be displayed on a map.
*/
hasGeospatialIssues(DwcTerm.GROUP_OCCURRENCE),
/**
* The GBIF backbone key.
* <p>
* The best matching, accepted GBIF backbone name usage representing this occurrence.
* In case the verbatim scientific name and its classification can only be matched to a higher rank this will
* represent the lowest matching rank. In the worst case this could just be for example Animalia.
* </p>
* <p>
* In contrast dwc:taxonID is only used for the source ids similar to occurrenceID
* </p>
*/
taxonKey(DwcTerm.GROUP_TAXON),
/**
* The GBIF backbone key of the accepted taxon key.
*/
acceptedTaxonKey(DwcTerm.GROUP_TAXON),
/**
* The key to the accepted kingdom in the GBIF backbone.
*/
kingdomKey(DwcTerm.GROUP_TAXON),
/**
* The key to the accepted phylum in the GBIF backbone.
*/
phylumKey(DwcTerm.GROUP_TAXON),
/**
* The key to the accepted class in the GBIF backbone.
*/
classKey(DwcTerm.GROUP_TAXON),
/**
* The key to the accepted order in the GBIF backbone.
*/
orderKey(DwcTerm.GROUP_TAXON),
/**
* The key to the accepted family in the GBIF backbone.
*/
familyKey(DwcTerm.GROUP_TAXON),
/**
* The key to the accepted genus in the GBIF backbone.
*/
genusKey(DwcTerm.GROUP_TAXON),
/**
* The key to the accepted subgenus in the GBIF backbone.
*/
subgenusKey(DwcTerm.GROUP_TAXON),
/**
* The backbone key to the accepted species.
* In case the taxonKey is of a higher rank than species (e.g. genus) speciesKey is null.
* In case taxonKey represents an infraspecific taxon the speciesKey points to the species
* the infraspecies is classified as. In case of taxonKey being a species the speciesKey is the same.
*/
speciesKey(DwcTerm.GROUP_TAXON),
/**
* The canonical name without authorship of the accepted species.
*/
species(DwcTerm.GROUP_TAXON),
// experimental Taxon properties
canonicalName(DwcTerm.GROUP_TAXON),
nameType(DwcTerm.GROUP_TAXON),
/**
* The genus part of the scientific name.
* <p>
* If the scientific name is considered to be a synonym dwc:genus refers to the accepted genus, not to the
* genus part of the synonym. This genericName always holds the genus part of the name no matter its classification
* or taxonomic status.
* Term proposed in Darwin Core, but not yet ratified.
* </p>
*/
genericName(DwcTerm.GROUP_TAXON),
/**
* The scientific name the type associated acceptedNubKey.
*/
acceptedScientificName(DwcTerm.GROUP_TAXON),
/**
* Scientific name as provided by the source.
*/
verbatimScientificName(DwcTerm.GROUP_TAXON),
/**
* The scientific name the type status of this specimen applies to.
* Term proposed in Darwin Core, but not yet ratified.
*/
typifiedName(DwcTerm.GROUP_IDENTIFICATION),
protocol(GbifTerm.GROUP_CRAWLING),
/**
* The date this record was last parsed from raw xml/json into a verbatim GBIF record.
*/
lastParsed(GbifTerm.GROUP_CRAWLING),
/**
* The date this record was last crawled/harvested by GBIF from the endpoint.
*/
lastCrawled(GbifTerm.GROUP_CRAWLING),
// Species Profile checklist extension
isMarine(GbifTerm.GROUP_SPECIES_PROFILE_EXTENSION),
isTerrestrial(GbifTerm.GROUP_SPECIES_PROFILE_EXTENSION),
isFreshwater(GbifTerm.GROUP_SPECIES_PROFILE_EXTENSION),
isHybrid(GbifTerm.GROUP_SPECIES_PROFILE_EXTENSION),
isExtinct(GbifTerm.GROUP_SPECIES_PROFILE_EXTENSION),
livingPeriod(GbifTerm.GROUP_SPECIES_PROFILE_EXTENSION, "timePeriod"),
lifeForm(GbifTerm.GROUP_SPECIES_PROFILE_EXTENSION),
ageInDays(GbifTerm.GROUP_SPECIES_PROFILE_EXTENSION),
sizeInMillimeter(GbifTerm.GROUP_SPECIES_PROFILE_EXTENSION),
massInGram(GbifTerm.GROUP_SPECIES_PROFILE_EXTENSION, "weightInGram"),
// Vernacular Name checklist extension
organismPart(GbifTerm.GROUP_VERNACULAR_NAME_EXTENSION),
isPlural(GbifTerm.GROUP_VERNACULAR_NAME_EXTENSION),
isPreferredName(GbifTerm.GROUP_VERNACULAR_NAME_EXTENSION),
// Distribution checklist extension
appendixCITES(GbifTerm.GROUP_SPECIES_DISTRIBUTION_EXTENSION),
numberOfOccurrences(GbifTerm.GROUP_SPECIES_DISTRIBUTION_EXTENSION),
/**
* Boolean indicating if the publishing country is different
*/
repatriated(DwcTerm.GROUP_OCCURRENCE),
// Calculated relative organism quantity, based on organism and sample measure types
relativeOrganismQuantity(DwcTerm.GROUP_MATERIAL_SAMPLE);
private static final String PREFIX = "gbif";
private static final String NS = "http://rs.gbif.org/terms/1.0/";
private static final URI NS_URI = URI.create(NS);
public static final String GROUP_CRAWLING = "Crawling";
public static final String GROUP_DATASET = "Dataset";
public static final String GROUP_ROW_TYPE = "RowType";
public static final String GROUP_SPECIES_DISTRIBUTION_EXTENSION = "SpeciesDistribution";
public static final String GROUP_SPECIES_PROFILE_EXTENSION = "SpeciesProfile";
public static final String GROUP_VERNACULAR_NAME_EXTENSION = "VernacularName";
/**
* Lists all GBIF term groups.
*/
public static final String[] GROUPS = {GROUP_CRAWLING, GROUP_DATASET, DwcTerm.GROUP_OCCURRENCE, GROUP_ROW_TYPE,
GROUP_SPECIES_DISTRIBUTION_EXTENSION, GROUP_SPECIES_PROFILE_EXTENSION, DwcTerm.GROUP_TAXON,
GROUP_VERNACULAR_NAME_EXTENSION, DwcTerm.GROUP_LOCATION};
/**
* Lists all GBIF terms in taxon group.
*/
public static final GbifTerm[] TAXONOMIC_TERMS =
{GbifTerm.taxonKey, GbifTerm.acceptedTaxonKey, GbifTerm.kingdomKey, GbifTerm.phylumKey, GbifTerm.classKey,
GbifTerm.orderKey, GbifTerm.familyKey, GbifTerm.genusKey, GbifTerm.subgenusKey, GbifTerm.speciesKey,
GbifTerm.species, GbifTerm.canonicalName, GbifTerm.nameType, GbifTerm.genericName, GbifTerm.acceptedScientificName,
GbifTerm.verbatimScientificName};
private final String groupName;
private final boolean isDeprecated;
public final String[] normAlts;
GbifTerm(String groupName, String... alternatives) {
this.groupName = groupName;
this.normAlts = alternatives;
boolean deprecatedAnnotationPresent = false;
try {
deprecatedAnnotationPresent = GbifTerm.class.getField(this.name()).isAnnotationPresent(Deprecated.class);
} catch (NoSuchFieldException ignore) { }
this.isDeprecated = deprecatedAnnotationPresent;
}
/**
* The simple term name without a namespace.
* For example taxonKey.
*
* @return simple term name
*/
@Override
public String simpleName() {
return name();
}
/**
* Array of alternative simple names in use for the term.
*
* @return simple term name
*/
@Override
public String[] alternativeNames() {
return normAlts;
}
/**
* The optional group the term is grouped in.
* For example Occurrence, Taxon, etc.
*/
public String getGroup() {
return groupName;
}
/**
* List all terms that belong to a given group.
*
* @param group the group to list terms for
* @return the list of GBIF terms in the given group
*/
public static List<GbifTerm> listByGroup(String group) {
List<GbifTerm> terms = new ArrayList<GbifTerm>();
for (GbifTerm t : GbifTerm.values()) {
if (t.getGroup().equalsIgnoreCase(group)) {
terms.add(t);
}
}
return terms;
}
@Override
public String toString() {
return prefixedName();
}
@Override
public boolean isClass() {
return Character.isUpperCase(simpleName().charAt(0));
}
@Override
public String prefix() {
return PREFIX;
}
@Override
public URI namespace() {
return NS_URI;
}
/**
*
* @return true if the Term is annotated with @Deprecated.
*/
public boolean isDeprecated(){
return isDeprecated;
}
}
|
package org.geotools.gis;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.HashSet;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import org.geotools.data.Query;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.feature.FeatureIterator;
import org.geotools.filter.text.cql2.CQL;
import org.geotools.map.Layer;
import org.geotools.swing.JMapFrame;
import org.geotools.swing.action.SafeAction;
import org.geotools.swing.table.FeatureCollectionTableModel;
import org.opengis.feature.Feature;
import org.opengis.feature.type.FeatureType;
import org.opengis.filter.Filter;
import org.opengis.filter.identity.Identifier;
public class DataTables extends JFrame {
public JComboBox featureTypeCBox;
private JTable table;
private JTextField text;
public DataTables() throws Exception {
setExtendedState(JMapFrame.MAXIMIZED_BOTH);
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
getContentPane().setLayout(new BorderLayout());
text = new JTextField(80);
text.setText("include");
getContentPane().add(text, BorderLayout.NORTH);
table = new JTable();
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setModel(new DefaultTableModel(0, 0));
table.setPreferredScrollableViewportSize(new Dimension(500, 200));
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane, BorderLayout.CENTER);
JMenuBar menubar = new JMenuBar();
setJMenuBar(menubar);
JMenu dataMenu = new JMenu("Actions");
menubar.add(dataMenu);
pack();
dataMenu.add(new SafeAction("Show only selected on map") {
public void action(ActionEvent e) throws Throwable {
filterSelectedFeatures();
}
});
dataMenu.add(new SafeAction("Count features by input query") {
public void action(ActionEvent e) throws Throwable {
countFeatures();
}
});
dataMenu.add(new SafeAction("Filter features by input query") {
public void action(ActionEvent e) throws Throwable {
filterFeaturesFromInput();
}
});
dataMenu.add(new SafeAction("Get geometry") {
public void action(ActionEvent e) throws Throwable {
queryFeatures();
}
});
dataMenu.addSeparator();
dataMenu.add(new SafeAction("Show selected features on map") {
public void action(ActionEvent e) throws Throwable {
showSelectedFeaturesOnMap();
}
});
featureTypeCBox = new JComboBox();
menubar.add(featureTypeCBox);
}
private void filterSelectedFeatures() throws Exception {
String typeName = (String) featureTypeCBox.getSelectedItem();
SimpleFeatureSource source = App.dataController.mapData.get(typeName);
Filter filter = App.mapWindow.selectionTool.getSelectedFeatures(
App.dataController.getLayerByName((String) featureTypeCBox.getSelectedItem())
);
SimpleFeatureCollection features = source.getFeatures(filter);
FeatureCollectionTableModel model = new FeatureCollectionTableModel(features);
table.setModel(model);
}
private void filterFeaturesFromInput() throws Exception {
String typeName = (String) featureTypeCBox.getSelectedItem();
SimpleFeatureSource source = App.dataController.mapData.get(typeName);
Filter filter = CQL.toFilter(text.getText());
SimpleFeatureCollection features = source.getFeatures(filter);
FeatureCollectionTableModel model = new FeatureCollectionTableModel(features);
table.setModel(model);
}
private void countFeatures() throws Exception {
String typeName = (String) featureTypeCBox.getSelectedItem();
SimpleFeatureSource source = App.dataController.mapData.get(typeName);
Filter filter = CQL.toFilter(text.getText());
SimpleFeatureCollection features = source.getFeatures(filter);
int count = features.size();
JOptionPane.showMessageDialog(text, "Number of selected features:" + count);
FeatureCollectionTableModel model = new FeatureCollectionTableModel(features);
table.setModel(model);
}
private void queryFeatures() throws Exception {
String typeName = (String) featureTypeCBox.getSelectedItem();
SimpleFeatureSource source = App.dataController.mapData.get(typeName);
FeatureType schema = source.getSchema();
String name = schema.getGeometryDescriptor().getLocalName();
Filter filter = CQL.toFilter(text.getText());
Query query = new Query(typeName, filter, new String[] { name });
SimpleFeatureCollection features = source.getFeatures(query);
FeatureCollectionTableModel model = new FeatureCollectionTableModel(features);
table.setModel(model);
}
private void showSelectedFeaturesOnMap() throws IOException {
if (table.getSelectedRowCount() > 0) {
App.mapWindow.selectionTool.clearSelection();
HashSet<Identifier> selectedIds = new HashSet<Identifier>();
Layer layer = App.dataController.getLayerByName((String) featureTypeCBox.getSelectedItem());
FeatureIterator iterator = layer.getFeatureSource().getFeatures().features();
int selected = 0;
while (iterator.hasNext()) {
Feature feature = iterator.next();
for (int i = 0; i < table.getSelectedRowCount(); i++) {
if (feature.getIdentifier().getID().equals(table.getValueAt(table.getSelectedRows()[i], 0))) {
selectedIds.add(feature.getIdentifier());
selected++;
}
}
if (selected == table.getSelectedRowCount()) {
break;
}
}
App.mapWindow.selectionTool.selectFeatures(layer, selectedIds);
App.mapWindow.show.toFront();
}
}
}
|
package org.javacc.jjtree;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.javacc.Version;
import org.javacc.parser.Options;
import org.javacc.parser.OutputFile;
import org.javacc.utils.OutputFileGenerator;
final class NodeFiles {
private NodeFiles() {}
/**
* ID of the latest version (of JJTree) in which one of the Node classes
* was modified.
*/
static final String nodeVersion = Version.majorDotMinor;
static Set nodesGenerated = new HashSet();
static void ensure(IO io, String nodeType)
{
File file = new File(JJTreeOptions.getJJTreeOutputDirectory(), nodeType + ".java");
if (nodeType.equals("Node")) {
} else if (nodeType.equals("SimpleNode")) {
ensure(io, "Node");
} else {
ensure(io, "SimpleNode");
}
/* Only build the node file if we're dealing with Node.java, or
the NODE_BUILD_FILES option is set. */
if (!(nodeType.equals("Node") || JJTreeOptions.getBuildNodeFiles())) {
return;
}
if (file.exists() && nodesGenerated.contains(file.getName())) {
return;
}
try {
String[] options = new String[] {"MULTI", "NODE_USES_PARSER", "VISITOR", "TRACK_TOKENS", "NODE_PREFIX", "NODE_EXTENDS", "NODE_FACTORY", Options.USEROPTION__SUPPORT_CLASS_VISIBILITY_PUBLIC};
OutputFile outputFile = new OutputFile(file, nodeVersion, options);
outputFile.setToolName("JJTree");
nodesGenerated.add(file.getName());
if (!outputFile.needToWrite) {
return;
}
if (nodeType.equals("Node")) {
generateNode_java(outputFile);
} else if (nodeType.equals("SimpleNode")) {
generateSimpleNode_java(outputFile);
} else {
generateMULTINode_java(outputFile, nodeType);
}
outputFile.close();
} catch (IOException e) {
throw new Error(e.toString());
}
}
static void generatePrologue(PrintWriter ostr)
{
// Output the node's package name. JJTreeGlobals.nodePackageName
// will be the value of NODE_PACKAGE in OPTIONS; if that wasn't set it
// will default to the parser's package name.
// If the package names are different we will need to import classes
// from the parser's package.
if (!JJTreeGlobals.nodePackageName.equals("")) {
ostr.println("package " + JJTreeGlobals.nodePackageName + ";");
ostr.println();
if (!JJTreeGlobals.nodePackageName.equals(JJTreeGlobals.packageName)) {
ostr.println("import " + JJTreeGlobals.packageName + ".*;");
ostr.println();
}
}
}
static String nodeConstants()
{
return JJTreeGlobals.parserName + "TreeConstants";
}
static void generateTreeConstants_java()
{
String name = nodeConstants();
File file = new File(JJTreeOptions.getJJTreeOutputDirectory(), name + ".java");
try {
OutputFile outputFile = new OutputFile(file);
PrintWriter ostr = outputFile.getPrintWriter();
List nodeIds = ASTNodeDescriptor.getNodeIds();
List nodeNames = ASTNodeDescriptor.getNodeNames();
generatePrologue(ostr);
ostr.println("public interface " + name);
ostr.println("{");
for (int i = 0; i < nodeIds.size(); ++i) {
String n = (String)nodeIds.get(i);
ostr.println(" public int " + n + " = " + i + ";");
}
ostr.println();
ostr.println();
ostr.println(" public String[] jjtNodeName = {");
for (int i = 0; i < nodeNames.size(); ++i) {
String n = (String)nodeNames.get(i);
ostr.println(" \"" + n + "\",");
}
ostr.println(" };");
ostr.println("}");
ostr.close();
} catch (IOException e) {
throw new Error(e.toString());
}
}
static String visitorClass()
{
return JJTreeGlobals.parserName + "Visitor";
}
static void generateVisitor_java()
{
if (!JJTreeOptions.getVisitor()) {
return;
}
String name = visitorClass();
File file = new File(JJTreeOptions.getJJTreeOutputDirectory(), name + ".java");
try {
OutputFile outputFile = new OutputFile(file);
PrintWriter ostr = outputFile.getPrintWriter();
List nodeNames = ASTNodeDescriptor.getNodeNames();
generatePrologue(ostr);
ostr.println("public interface " + name);
ostr.println("{");
String ve = mergeVisitorException();
String argumentType = "Object";
if (!JJTreeOptions.getVisitorDataType().equals("")) {
argumentType = JJTreeOptions.getVisitorDataType();
}
ostr.println(" public " + JJTreeOptions.getVisitorReturnType() + " visit(SimpleNode node, " + argumentType + " data)" +
ve + ";");
if (JJTreeOptions.getMulti()) {
for (int i = 0; i < nodeNames.size(); ++i) {
String n = (String)nodeNames.get(i);
if (n.equals("void")) {
continue;
}
String nodeType = JJTreeOptions.getNodePrefix() + n;
ostr.println(" public " + JJTreeOptions.getVisitorReturnType() + " " + getVisitMethodName(nodeType) +
"(" + nodeType +
" node, " + argumentType + " data)" + ve + ";");
}
}
ostr.println("}");
ostr.close();
} catch (IOException e) {
throw new Error(e.toString());
}
}
static String defaultVisitorClass()
{
return JJTreeGlobals.parserName + "DefaultVisitor";
}
private static String getVisitMethodName(String className) {
StringBuffer sb = new StringBuffer("visit");
if (JJTreeOptions.booleanValue("VISITOR_METHOD_NAME_INCLUDES_TYPE_NAME")) {
sb.append(Character.toUpperCase(className.charAt(0)));
for (int i = 1; i < className.length(); i++) {
sb.append(className.charAt(i));
}
}
return sb.toString();
}
static void generateDefaultVisitor_java()
{
if (!JJTreeOptions.getVisitor()) {
return;
}
String className = defaultVisitorClass();
File file = new File(JJTreeOptions.getJJTreeOutputDirectory(), className + ".java");
try {
final OutputFile outputFile = new OutputFile(file);
final PrintWriter ostr = outputFile.getPrintWriter();
final List nodeNames = ASTNodeDescriptor.getNodeNames();
generatePrologue(ostr);
ostr.println("public class " + className + " implements " + visitorClass() + "{");
final String ve = mergeVisitorException();
String argumentType = "Object";
if (!JJTreeOptions.getVisitorDataType().equals("")) {
argumentType = JJTreeOptions.getVisitorDataType().trim();
}
final String returnType = JJTreeOptions.getVisitorReturnType().trim();
final boolean isVoidReturnType = "void".equals(returnType);
ostr.println(" public " + returnType + " defaultVisit(SimpleNode node, " + argumentType + " data)" +
ve + "{");
ostr.println(" node.childrenAccept(this, data);");
ostr.print(" return");
if (!isVoidReturnType) {
if (returnType.equals(argumentType))
ostr.print(" data");
else if ("boolean".equals(returnType))
ostr.print(" false");
else if ("int".equals(returnType))
ostr.print(" 0");
else if ("long".equals(returnType))
ostr.print(" 0L");
else if ("double".equals(returnType))
ostr.print(" 0.0d");
else if ("float".equals(returnType))
ostr.print(" 0.0f");
else if ("short".equals(returnType))
ostr.print(" 0");
else if ("byte".equals(returnType))
ostr.print(" 0");
else if ("char".equals(returnType))
ostr.print(" '\u0000'");
else
ostr.print(" null");
}
ostr.println(";");
ostr.println(" }");
ostr.println(" public " + returnType + " visit(SimpleNode node, " + argumentType + " data)" +
ve + "{");
ostr.println(" " + (isVoidReturnType ? "" : "return ") + "defaultVisit(node, data);");
ostr.println(" }");
if (JJTreeOptions.getMulti()) {
for (int i = 0; i < nodeNames.size(); ++i) {
String n = (String)nodeNames.get(i);
if (n.equals("void")) {
continue;
}
String nodeType = JJTreeOptions.getNodePrefix() + n;
ostr.println(" public " + returnType + " " + getVisitMethodName(nodeType) +
"(" + nodeType +
" node, " + argumentType + " data)" + ve + "{");
ostr.println(" " + (isVoidReturnType ? "" : "return ") + "defaultVisit(node, data);");
ostr.println(" }");
}
}
ostr.println("}");
ostr.close();
} catch (final IOException e) {
throw new Error(e.toString());
}
}
private static String mergeVisitorException() {
String ve = JJTreeOptions.getVisitorException();
if (!"".equals(ve)) {
ve = " throws " + ve;
}
return ve;
}
private static void generateNode_java(OutputFile outputFile) throws IOException
{
PrintWriter ostr = outputFile.getPrintWriter();
generatePrologue(ostr);
Map options = new HashMap(Options.getOptions());
options.put(Options.NONUSER_OPTION__PARSER_NAME, JJTreeGlobals.parserName);
OutputFileGenerator generator = new OutputFileGenerator(
"/templates/Node.template", options);
generator.generate(ostr);
ostr.close();
}
private static void generateSimpleNode_java(OutputFile outputFile) throws IOException
{
PrintWriter ostr = outputFile.getPrintWriter();
generatePrologue(ostr);
Map options = new HashMap(Options.getOptions());
options.put(Options.NONUSER_OPTION__PARSER_NAME, JJTreeGlobals.parserName);
options.put("VISITOR_RETURN_TYPE_VOID", Boolean.valueOf(JJTreeOptions.getVisitorReturnType().equals("void")));
OutputFileGenerator generator = new OutputFileGenerator(
"/templates/SimpleNode.template", options);
generator.generate(ostr);
ostr.close();
}
private static void generateMULTINode_java(OutputFile outputFile, String nodeType) throws IOException
{
PrintWriter ostr = outputFile.getPrintWriter();
generatePrologue(ostr);
Map options = new HashMap(Options.getOptions());
options.put(Options.NONUSER_OPTION__PARSER_NAME, JJTreeGlobals.parserName);
options.put("NODE_TYPE", nodeType);
options.put("VISITOR_RETURN_TYPE_VOID", Boolean.valueOf(JJTreeOptions.getVisitorReturnType().equals("void")));
OutputFileGenerator generator = new OutputFileGenerator(
"/templates/MultiNode.template", options);
generator.generate(ostr);
ostr.close();
}
}
|
package musician101.emergencywhitelist.commands;
import musician101.emergencywhitelist.EmergencyWhitelist;
import musician101.emergencywhitelist.lib.Constants;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
/**
* The code used to run when any command in the plugin is executed.
*
* @author Musician101
*/
public class EWLCommandExecutor implements CommandExecutor
{
EmergencyWhitelist plugin;
/**
* @param plugin References the plugin's main class.
*/
public EWLCommandExecutor(EmergencyWhitelist plugin)
{
this.plugin = plugin;
}
/**
* @param sender Who sent the command.
* @param command Which command was executed
* @param label Alias of the command
* @param args Command parameters
* @return True if the command was successfully executed
*/
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args)
{
boolean enabled = plugin.getConfig().getBoolean("enabled");
if (command.getName().equalsIgnoreCase(Constants.EWL))
{
if (args.length == 0)
{
sender.sendMessage(Constants.getVersionMessage(enabled, plugin.getDescription().getVersion()));
sender.sendMessage(ChatColor.GOLD + "[EmergencyWhitelist] Type /ewl help for a list of commands.");
}
else if (args.length > 0)
{
if (args[0].equalsIgnoreCase(Constants.HELP))
{
new HelpCommand(plugin, sender);
}
else if (args[0].equalsIgnoreCase(Constants.TOGGLE))
{
new ToggleCommand(plugin, sender, enabled);
}
}
return true;
}
return false;
}
}
|
package org.jtrfp.trcl.flow;
import java.awt.Color;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import org.jtrfp.trcl.BackdropSystem;
import org.jtrfp.trcl.NAVSystem;
import org.jtrfp.trcl.OverworldSystem;
import org.jtrfp.trcl.Texture;
import org.jtrfp.trcl.Tunnel;
import org.jtrfp.trcl.TunnelInstaller;
import org.jtrfp.trcl.World;
import org.jtrfp.trcl.core.ResourceManager;
import org.jtrfp.trcl.core.TR;
import org.jtrfp.trcl.file.LVLFile;
import org.jtrfp.trcl.file.Location3D;
import org.jtrfp.trcl.file.NAVFile.NAVSubObject;
import org.jtrfp.trcl.file.NAVFile.START;
import org.jtrfp.trcl.file.TDFFile;
import org.jtrfp.trcl.file.Weapon;
import org.jtrfp.trcl.flow.NAVObjective.Factory;
import org.jtrfp.trcl.gpu.GPU;
import org.jtrfp.trcl.gpu.GlobalDynamicTextureBuffer;
import org.jtrfp.trcl.obj.DebrisFactory;
import org.jtrfp.trcl.obj.Explosion.ExplosionType;
import org.jtrfp.trcl.obj.ExplosionFactory;
import org.jtrfp.trcl.obj.ObjectDirection;
import org.jtrfp.trcl.obj.Player;
import org.jtrfp.trcl.obj.PluralizedPowerupFactory;
import org.jtrfp.trcl.obj.ProjectileFactory;
public class Mission {
private final TR tr;
private final List<NAVObjective> navs= new LinkedList<NAVObjective>();
private final LVLFile lvl;
private final Object missionCompleteBarrier = new Object();
private final HashMap<String,Tunnel> tunnels = new HashMap<String,Tunnel>();
private double [] playerStartPosition= new double[3];
private List<NAVSubObject> navSubObjects;
private ObjectDirection playerStartDirection;
public Mission(TR tr, LVLFile lvl){
this.tr=tr;
this.lvl=lvl;
}//end Mission
public Result go(){
try{
//Set up palette
final ResourceManager rm = tr.getResourceManager();
final Color [] pal = rm.getPalette(lvl.getGlobalPaletteFile());
pal[0]=new Color(0,0,0,0);
tr.setGlobalPalette(pal);
// POWERUPS
rm.setPluralizedPowerupFactory(new PluralizedPowerupFactory(tr));
/// EXPLOSIONS
rm.setExplosionFactory(new ExplosionFactory(tr));
// DEBRIS
rm.setDebrisFactory(new DebrisFactory(tr));
//SETUP PROJECTILE FACTORIES
Weapon [] w = Weapon.values();
ProjectileFactory [] pf = new ProjectileFactory[w.length];
for(int i=0; i<w.length;i++){
pf[i]=new ProjectileFactory(tr, w[i], ExplosionType.Blast);
}//end for(weapons)
rm.setProjectileFactories(pf);
final Player player =new Player(tr,rm.getBINModel("SHIP.BIN", tr.getGlobalPalette(), tr.getGPU().getGl()));
tr.setPlayer(player);
final String startX=System.getProperty("org.jtrfp.trcl.startX");
final String startY=System.getProperty("org.jtrfp.trcl.startY");
final String startZ=System.getProperty("org.jtrfp.trcl.startZ");
final double [] playerPos = player.getPosition();
if(startX!=null && startY!=null&&startZ!=null){
System.out.println("Using user-specified start point");
final int sX=Integer.parseInt(startX);
final int sY=Integer.parseInt(startY);
final int sZ=Integer.parseInt(startZ);
playerPos[0]=sX;
playerPos[1]=sY;
playerPos[2]=sZ;
player.notifyPositionChange();
}
final World world = tr.getWorld();
world.add(player);
final TDFFile tdf = rm.getTDFData(lvl.getTunnelDefinitionFile());
//Install NAVs
final NAVSystem navSystem = tr.getNavSystem();
navSubObjects = rm.getNAVData(lvl.getNavigationFile()).getNavObjects();
tr.setOverworldSystem(new OverworldSystem(world, lvl, tdf));
START s = (START)navSubObjects.get(0);
navSubObjects.remove(0);
Location3D l3d = s.getLocationOnMap();
playerStartPosition[0]=TR.legacy2Modern(l3d.getZ());
playerStartPosition[1]=TR.legacy2Modern(l3d.getY());
playerStartPosition[2]=TR.legacy2Modern(l3d.getX());
playerStartDirection = new ObjectDirection(s.getRoll(),s.getPitch(),s.getYaw());
TunnelInstaller tunnelInstaller = new TunnelInstaller(tdf,world);
Factory f = new NAVObjective.Factory(tr);
for(NAVSubObject obj:navSubObjects){
f.create(tr, obj, navs);
}//end for(navSubObjects)
navSystem.updateNAVState();
tr.setBackdropSystem(new BackdropSystem(world));
//////// INITIAL HEADING
player.setPosition(getPlayerStartPosition());
player.setDirection(getPlayerStartDirection());
player.setHeading(player.getHeading().negate());//Kludge to fix incorrect heading
System.out.println("Start position set to "+player.getPosition());
GPU gpu = tr.getGPU();
//gpu.takeGL();//Remove if tunnels are put back in. TunnelInstaller takes the GL for us.
System.out.println("Building master texture...");
Texture.finalize(gpu);
System.out.println("\t...Done.");
System.out.println("Finalizing GPU memory allocation...");
GlobalDynamicTextureBuffer.finalizeAllocation(gpu,tr);
gpu.releaseGL();
//////// NO GL BEYOND THIS POINT ////////
System.out.println("\t...Done.");
System.out.println("Invoking JVM's garbage collector...");
System.gc();
System.out.println("\t...Ahh, that felt good.");
System.out.println("Attaching to GL Canvas...");
System.out.println("\t...Done.");
System.out.println("Starting animator...");
tr.getThreadManager().start();
System.out.println("\t...Done.");
}catch(Exception e){e.printStackTrace();}
if(System.getProperties().containsKey("org.jtrfp.trcl.flow.Mission.skipNavs")){
try{
final int skips = Integer.parseInt(System.getProperty("org.jtrfp.trcl.flow.Mission.skipNavs"));
System.out.println("Skipping "+skips+" navs.");
for(int i=0; i<skips; i++){
removeNAVObjective(currentNAVObjective());
}//end for(skips)
}catch(NumberFormatException e){
System.err.println("Invalid format for property \"org.jtrfp.trcl.flow.Mission.skipNavs\". Must be integer.");}
}//end if(containsKey)
return new Result(null);//TODO: Replace null with actual value unless end of game.
}//end go()
public NAVObjective currentNAVObjective(){
if(navs.isEmpty())return null;
return navs.get(0);
}
public void removeNAVObjective(NAVObjective o){
navs.remove(o);
if(navs.size()==0){missionCompleteSequence();}
else tr.getNavSystem().updateNAVState();
}//end removeNAVObjective(...)
public class Result{
private final String nextLVL;
public Result(String nextLVL){
this.nextLVL=nextLVL;
}
public String getNextLVL() {
return nextLVL;
}
}//end Result
/**
* @return the playerStartPosition
*/
public double[] getPlayerStartPosition() {
return playerStartPosition;
}
/**
* @return the playerStartDirection
*/
public ObjectDirection getPlayerStartDirection() {
return playerStartDirection;
}
public Tunnel newTunnel(org.jtrfp.trcl.file.TDFFile.Tunnel tun) {
final Tunnel result = new Tunnel(tr.getWorld(),tun);
tunnels.put(tun.getTunnelLVLFile().toUpperCase(), result);
return result;
}
public Tunnel getTunnelByFileName(String tunnelFileName) {
return tunnels.get(tunnelFileName.toUpperCase());
}
public Tunnel getTunnelWhoseEntranceClosestTo(double xInLegacyUnits, double yInLegacyUnits, double zInLegacyUnits){
Tunnel result=null;
double closestDistance=Double.POSITIVE_INFINITY;
for(Tunnel t:tunnels.values()){
TDFFile.Tunnel src =t.getSourceTunnel();
final double distance=Math.sqrt(
Math.pow((xInLegacyUnits-src.getEntrance().getX()),2)+
Math.pow((yInLegacyUnits-src.getEntrance().getY()),2)+
Math.pow((zInLegacyUnits-src.getEntrance().getZ()),2));
if(distance<closestDistance){closestDistance=distance;result=t;}
}//end for(tunnels)
return result;
}//end getTunnelWhoseEntranceClosestTo(...)
private void missionCompleteSequence(){
new Thread(){
@Override
public void run(){
//TODO: Behavior change: Camera XZ static, lag Y by ~16 squares, heading/top affix toward player
//TODO: Turn off all player control behavior
//TODO: Behavior change: Player turns upward, top rolls on heading, speed at full throttle
//TODO: Wait 3 seconds
//TODO: Lightning shell on
//TODO: Wait 1 second
//TODO: Turbo forward
//TODO: Wait 500ms
//TODO: Jet thrust noise
//TODO: Player invisible.
tr.getGame().missionComplete();
}//end run()
}.start();
}
public void playerDestroyed(){
new Thread(){
@Override
public void run(){
//TODO Behavior change: Camera XYZ static, heading/top affix toward player
//TODO: Turn off all player control behavior
//TODO Player behavior change: Slow spin along heading axis, slow downward drift of heading
//TODO: Add behavior: explode and destroy on impact with ground
tr.getGame().missionFailed();
}//end run()
}.start();
}//end playerDestroyed()
public List<NAVObjective> getRemainingNAVObjectives() {
return navs;
}
/**
* @return the navSubObjects
*/
public List<NAVSubObject> getNavSubObjects() {
return navSubObjects;
}
/**
* @param navSubObjects the navSubObjects to set
*/
public void setNavSubObjects(List<NAVSubObject> navSubObjects) {
this.navSubObjects = navSubObjects;
}
}//end Mission
|
package net.java.sip.communicator.plugin.otr;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import org.osgi.framework.*;
import net.java.otr4j.*;
import net.java.sip.communicator.service.contactlist.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.util.swing.*;
/**
* A special {@link Panel} that manages the OTR configuration.
*
* @author George Politis
*/
@SuppressWarnings("serial")
public class OtrConfigurationPanel
extends TransparentPanel
{
/**
* A special {@link Panel} for Private Keys display.
*
* @author George Politis
*/
private static class PrivateKeysPanel
extends TransparentPanel
{
/**
* A special {@link JComboBox} for {@link AccountID} enumeration.
*
* @author George Politis
*/
private static class AccountsComboBox
extends JComboBox
{
/**
* A class hosted in an {@link AccountsComboBox} that holds a single
* {@link AccountID}.
*
* @author George Politis
*/
private static class AccountsComboBoxItem
{
public final AccountID accountID;
public AccountsComboBoxItem(AccountID accountID)
{
this.accountID = accountID;
}
public String toString()
{
return accountID.getDisplayName();
}
}
public AccountsComboBox()
{
List<AccountID> accountIDs = OtrActivator.getAllAccountIDs();
if (accountIDs == null)
return;
for (AccountID accountID : accountIDs)
this.addItem(new AccountsComboBoxItem(accountID));
}
/**
* Gets the selected {@link AccountID} for this
* {@link AccountsComboBox}.
*
* @return
*/
public AccountID getSelectedAccountID()
{
Object selectedItem = this.getSelectedItem();
if (selectedItem instanceof AccountsComboBoxItem)
return ((AccountsComboBoxItem) selectedItem).accountID;
else
return null;
}
}
private AccountsComboBox cbAccounts;
private JLabel lblFingerprint;
private JButton btnGenerate;
public PrivateKeysPanel()
{
this.initComponents();
this.openAccount(cbAccounts.getSelectedAccountID());
}
/**
* Sets up the {@link PrivateKeysPanel} components so that they reflect
* the {@link AccountID} param.
*
* @param account the {@link AccountID} to setup the components for.
*/
private void openAccount(AccountID account)
{
if (account == null)
{
lblFingerprint.setEnabled(false);
btnGenerate.setEnabled(false);
lblFingerprint.setText("No key present");
btnGenerate.setText("Generate");
}
else
{
lblFingerprint.setEnabled(true);
btnGenerate.setEnabled(true);
String fingerprint =
OtrActivator.scOtrKeyManager.getLocalFingerprint(account);
if (fingerprint == null || fingerprint.length() < 1)
{
lblFingerprint.setText("No key present");
btnGenerate.setText("Generate");
}
else
{
lblFingerprint.setText(fingerprint);
btnGenerate.setText("Re-generate");
}
}
}
/**
* Initializes the {@link PrivateKeysPanel} components.
*/
private void initComponents()
{
this.setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(EtchedBorder.LOWERED),
OtrActivator.resourceService
.getI18NString("plugin.otr.configform.MY_PRIVATE_KEYS")));
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JPanel pnlAccounts = new TransparentPanel();
this.add(pnlAccounts);
pnlAccounts.add(new JLabel("Account: "));
cbAccounts = new AccountsComboBox();
cbAccounts.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
openAccount(((AccountsComboBox) e.getSource())
.getSelectedAccountID());
}
});
pnlAccounts.add(cbAccounts);
JPanel pnlFingerprint = new TransparentPanel();
this.add(pnlFingerprint);
pnlFingerprint.add(new JLabel("Fingerprint: "));
lblFingerprint = new JLabel();
pnlFingerprint.add(lblFingerprint);
btnGenerate = new JButton();
btnGenerate.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
AccountID account = cbAccounts.getSelectedAccountID();
if (account == null)
return;
OtrActivator.scOtrKeyManager.generateKeyPair(account);
openAccount(account);
}
});
pnlFingerprint.add(btnGenerate);
}
}
/**
* A special {@link Panel} for fingerprints display.
*
* @author George Politis
*/
private static class KnownFingerprintsPanel
extends TransparentPanel
{
private static class ContactsTableModel
extends AbstractTableModel
{
public final java.util.List<Contact> allContacts =
new Vector<Contact>();
public ContactsTableModel()
{
// Get the protocolproviders
ServiceReference[] protocolProviderRefs = null;
try
{
protocolProviderRefs =
OtrActivator.bundleContext.getServiceReferences(
ProtocolProviderService.class.getName(), null);
}
catch (InvalidSyntaxException ex)
{
return;
}
if (protocolProviderRefs == null
|| protocolProviderRefs.length < 1)
return;
// Get the metacontactlist service.
ServiceReference ref =
OtrActivator.bundleContext
.getServiceReference(MetaContactListService.class
.getName());
MetaContactListService service =
(MetaContactListService) OtrActivator.bundleContext
.getService(ref);
// Populate contacts.
for (int i = 0; i < protocolProviderRefs.length; i++)
{
ProtocolProviderService provider =
(ProtocolProviderService) OtrActivator.bundleContext
.getService(protocolProviderRefs[i]);
Iterator<MetaContact> metaContacts =
service.findAllMetaContactsForProvider(provider);
while (metaContacts.hasNext())
{
MetaContact metaContact = metaContacts.next();
Iterator<Contact> contacts = metaContact.getContacts();
while (contacts.hasNext())
{
allContacts.add(contacts.next());
}
}
}
}
public static final int CONTACTNAME_INDEX = 0;
public static final int VERIFIED_INDEX = 1;
public static final int FINGERPRINT_INDEX = 2;
/*
* Implements AbstractTableModel#getColumnName(int).
*/
public String getColumnName(int column)
{
switch (column)
{
case CONTACTNAME_INDEX:
return "Contact";
case VERIFIED_INDEX:
return "Verified";
case FINGERPRINT_INDEX:
return "Fingerprint";
default:
return null;
}
}
/*
* Implements AbstractTableModel#getValueAt(int,int).
*/
public Object getValueAt(int row, int column)
{
if (row < 0)
return null;
Contact contact = allContacts.get(row);
switch (column)
{
case CONTACTNAME_INDEX:
return contact.getDisplayName();
case VERIFIED_INDEX:
return (OtrActivator.scOtrKeyManager.isVerified(contact)) ? "Yes"
: "No";
case FINGERPRINT_INDEX:
return OtrActivator.scOtrKeyManager
.getRemoteFingerprint(contact);
default:
return null;
}
}
/*
* Implements AbstractTableModel#getRowCount().
*/
public int getRowCount()
{
return allContacts.size();
}
/*
* Implements AbstractTableModel#getColumnCount().
*/
public int getColumnCount()
{
return 3;
}
}
public KnownFingerprintsPanel()
{
this.initComponents();
openContact(getSelectedContact());
}
/**
* Gets the selected {@link Contact} for this
* {@link KnownFingerprintsPanel}.
*
* @return the selected {@link Contact}
*/
private Contact getSelectedContact()
{
ContactsTableModel model =
(ContactsTableModel) contactsTable.getModel();
int index = contactsTable.getSelectedRow();
if (index < 0 || index > model.allContacts.size())
return null;
return model.allContacts.get(index);
}
/**
* Sets up the {@link KnownFingerprintsPanel} components so that they
* reflect the {@link Contact} param.
*
* @param contact the {@link Contact} to setup the components for.
*/
private void openContact(Contact contact)
{
if (contact == null)
{
btnForgetFingerprint.setEnabled(false);
btnVerifyFingerprint.setEnabled(false);
}
else
{
boolean verified =
OtrActivator.scOtrKeyManager.isVerified(contact);
btnForgetFingerprint.setEnabled(verified);
btnVerifyFingerprint.setEnabled(!verified);
}
}
JButton btnVerifyFingerprint;
JButton btnForgetFingerprint;
JTable contactsTable;
/**
* Initializes the {@link KnownFingerprintsPanel} components.
*/
private void initComponents()
{
this
.setBorder(BorderFactory
.createTitledBorder(
BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
OtrActivator.resourceService
.getI18NString("plugin.otr.configform.KNOWN_FINGERPRINTS")));
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
contactsTable = new JTable();
contactsTable.setModel(new ContactsTableModel());
contactsTable
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
contactsTable.setCellSelectionEnabled(false);
contactsTable.setColumnSelectionAllowed(false);
contactsTable.setRowSelectionAllowed(true);
contactsTable.getSelectionModel().addListSelectionListener(
new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent e)
{
if (e.getValueIsAdjusting())
return;
openContact(getSelectedContact());
}
});
JScrollPane pnlContacts = new JScrollPane(contactsTable);
this.add(pnlContacts);
JPanel pnlButtons = new TransparentPanel();
this.add(pnlButtons);
btnVerifyFingerprint = new JButton();
btnVerifyFingerprint.setText("Verify fingerprint");
btnVerifyFingerprint.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
OtrActivator.scOtrKeyManager.verify(getSelectedContact());
}
});
pnlButtons.add(btnVerifyFingerprint);
btnForgetFingerprint = new JButton();
btnForgetFingerprint.setText("Forget fingerprint");
btnForgetFingerprint.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
OtrActivator.scOtrKeyManager.unverify(getSelectedContact());
}
});
pnlButtons.add(btnForgetFingerprint);
}
}
/**
* A special {@link Panel} for OTR policy display.
*
* @author George Politis
*/
private static class DefaultOtrPolicyPanel
extends TransparentPanel
{
// TODO We should listen for configuration value changes.
public DefaultOtrPolicyPanel()
{
this.initComponents();
this.loadPolicy();
}
/**
* Sets up the {@link DefaultOtrPolicyPanel} components so that they
* reflect the global OTR policy.
*
*/
public void loadPolicy()
{
OtrPolicy otrPolicy = OtrActivator.scOtrEngine.getGlobalPolicy();
boolean otrEnabled = otrPolicy.getEnableManual();
cbEnable.setSelected(otrEnabled);
cbAutoInitiate.setEnabled(otrEnabled);
cbRequireOtr.setEnabled(otrEnabled);
cbAutoInitiate.setSelected(otrPolicy.getEnableAlways());
cbRequireOtr.setSelected(otrPolicy.getRequireEncryption());
}
private SIPCommCheckBox cbEnable;
private SIPCommCheckBox cbAutoInitiate;
private SIPCommCheckBox cbRequireOtr;
/**
* Initializes the {@link DefaultOtrPolicyPanel} components.
*/
private void initComponents()
{
this.setBorder(BorderFactory.createTitledBorder(BorderFactory
.createEtchedBorder(EtchedBorder.LOWERED),
OtrActivator.resourceService
.getI18NString("plugin.otr.configform.DEFAULT_SETTINGS")));
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
cbEnable =
new SIPCommCheckBox(OtrActivator.resourceService
.getI18NString("plugin.otr.configform.CB_ENABLE"));
cbEnable.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
OtrPolicy otrPolicy =
OtrActivator.scOtrEngine.getGlobalPolicy();
otrPolicy.setEnableManual(((JCheckBox) e.getSource())
.isSelected());
OtrActivator.scOtrEngine.setGlobalPolicy(otrPolicy);
DefaultOtrPolicyPanel.this.loadPolicy();
}
});
this.add(cbEnable);
cbAutoInitiate =
new SIPCommCheckBox(OtrActivator.resourceService
.getI18NString("plugin.otr.configform.CB_AUTO"));
cbAutoInitiate.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
OtrPolicy otrPolicy =
OtrActivator.scOtrEngine.getGlobalPolicy();
otrPolicy.setEnableAlways(((JCheckBox) e.getSource())
.isSelected());
OtrActivator.scOtrEngine.setGlobalPolicy(otrPolicy);
DefaultOtrPolicyPanel.this.loadPolicy();
}
});
this.add(cbAutoInitiate);
cbRequireOtr =
new SIPCommCheckBox(OtrActivator.resourceService
.getI18NString("plugin.otr.configform.CB_REQUIRE"));
cbRequireOtr.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
OtrPolicy otrPolicy =
OtrActivator.scOtrEngine.getGlobalPolicy();
otrPolicy.setRequireEncryption(((JCheckBox) e.getSource())
.isSelected());
OtrActivator.scOtrEngine.setGlobalPolicy(otrPolicy);
DefaultOtrPolicyPanel.this.loadPolicy();
}
});
this.add(cbRequireOtr);
}
}
public OtrConfigurationPanel()
{
this.initComponents();
}
/**
* Initializes all 3 panels of the {@link OtrConfigurationPanel}
*/
private void initComponents()
{
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1.0;
c.anchor = GridBagConstraints.PAGE_START;
JPanel pnlPrivateKeys = new PrivateKeysPanel();
c.gridy = 0;
this.add(pnlPrivateKeys, c);
JPanel pnlPolicy = new DefaultOtrPolicyPanel();
c.gridy = 1;
this.add(pnlPolicy, c);
JPanel pnlFingerprints = new KnownFingerprintsPanel();
pnlFingerprints.setMinimumSize(new Dimension(Short.MAX_VALUE,
Short.MAX_VALUE));
c.weighty = 1.0;
c.gridy = 2;
this.add(pnlFingerprints, c);
}
}
|
package org.lantern;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.util.Collection;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.lantern.event.Events;
import org.lantern.event.MessageEvent;
import org.lantern.proxy.FallbackProxy;
import org.lantern.state.Model;
import org.lantern.state.Notification.MessageType;
import org.lantern.util.HttpClientFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
/**
* This class continually fetches new Lantern configuration files on S3,
* dispatching events to any interested classes when and if a new configuration
* file is found.
*/
public class S3ConfigFetcher {
private static final Logger log
= LoggerFactory.getLogger(S3ConfigFetcher.class);
// DRY: wrapper.install4j and configureUbuntu.txt
private static final String URL_FILENAME = ".lantern-configurl.txt";
private final Optional<String> url;
private final SecureRandom random = new SecureRandom();
private static final File URL_CONFIG_FILE =
new File(LanternClientConstants.CONFIG_DIR, URL_FILENAME);
private final Timer configCheckTimer = new Timer("S3-Config-Check", true);
private final Model model;
private HttpClientFactory httpClientFactory;
/**
* Creates a new class for fetching the Lantern config from S3.
*
* @param model The persistent settings.
*/
public S3ConfigFetcher(final Model model,
final HttpClientFactory httpClientFactory) {
log.debug("Creating s3 config fetcher...");
this.model = model;
this.url = readUrl();
this.httpClientFactory = httpClientFactory;
}
public void start() {
log.debug("Starting config loading...");
if (LanternUtils.isFallbackProxy()) {
return;
}
if (!this.url.isPresent()) {
log.debug("No url to use for downloading config");
return;
}
final S3Config config = model.getS3Config();
// Always check for a new config right away. We do this on the same
// thread here because a lot depends on this value, particularly on
// the first run of Lantern, and we want to make sure it takes priority.
if (config != null) {
// The config in the model could just be the default, so check
// for actual fallbacks.
final Collection<FallbackProxy> fallbacks = config.getFallbacks();
if (fallbacks == null || fallbacks.isEmpty()) {
recheck();
} else {
log.debug("Using existing config...");
Events.asyncEventBus().post(config);
// If we've already got valid fallbacks, thread this so we
// don't hold up the rest of Lantern initialization.
scheduleConfigRecheck(0.0);
}
} else {
recheck();
}
}
private void scheduleConfigRecheck(final double minutesToSleep) {
log.debug("Scheduling config check...");
configCheckTimer.schedule(new TimerTask() {
@Override
public void run() {
recheck();
}
}, (long)(minutesToSleep * 60000));
}
private void recheck() {
recheckConfig();
final S3Config config = model.getS3Config();
final double newMinutesToSleep
// Temporary network problems? Let's retry in a few seconds.
= (config == null) ? 0.2
: lerp(config.getMinpoll(),
config.getMaxpoll(),
random.nextDouble());
scheduleConfigRecheck(newMinutesToSleep);
}
private void recheckConfig() {
log.debug("Rechecking configuration");
final Optional<S3Config> newConfig = fetchRemoteConfig();
if (!newConfig.isPresent()) {
log.error("Couldn't get new config.");
if (!weHaveFallbacks()) {
Events.asyncEventBus().post(
new MessageEvent(Tr.tr(MessageKey.NO_CONFIG), MessageType.error));
}
return;
}
final S3Config config = this.model.getS3Config();
this.model.setS3Config(newConfig.get());
boolean changed;
if (config == null) {
log.warn("Rechecking config with no old one.");
changed = true;
} else {
changed = !newConfig.get().equals(config);
}
if (changed) {
log.info("Configuration changed! Reapplying...");
Events.eventBus().post(newConfig.get());
} else {
log.debug("Configuration unchanged.");
}
}
/**
* Returns whether or not we have stored fallbacks.
*
* @return <code>true</code> if we have fallbacks, otherwise <code>false</code>.
*/
private boolean weHaveFallbacks() {
final S3Config config = model.getS3Config();
if (config == null) {
return false;
}
final Collection<FallbackProxy> fallbacks = config.getFallbacks();
if (fallbacks == null || fallbacks.isEmpty()) {
return false;
}
return true;
}
/** Linear interpolation. */
private double lerp(double a, double b, double t) {
return a + (b - a) * t;
}
private Optional<String> readUrl() {
try {
copyUrlFile();
if (!URL_CONFIG_FILE.isFile()) {
log.error("Still no config file at {}", URL_CONFIG_FILE);
return Optional.absent();
}
} catch (final IOException e) {
log.warn("Couldn't copy config URL file?", e);
return Optional.absent();
}
try {
final String folder =
FileUtils.readFileToString(URL_CONFIG_FILE, "UTF-8");
log.debug("Read folder from URL file: {}", folder);
return Optional.of(LanternConstants.S3_CONFIG_BASE_URL
+ folder.trim()
+ "/config.json");
} catch (final IOException e) {
log.error("Couldn't read config URL file?", e);
}
return Optional.absent();
}
private Optional<S3Config> fetchRemoteConfig() {
if (!url.isPresent()) {
log.error("URL initialization failed.");
return Optional.absent();
}
try {
final HttpClient direct = this.httpClientFactory.newDirectClient();
return fetchRemoteConfig(direct);
} catch (final IOException e) {
final HttpClient proxied = this.httpClientFactory.newProxiedClient();
try {
return fetchRemoteConfig(proxied);
} catch (IOException ioe) {
log.error("Still could not fetch S3 config using fallback.");
return Optional.absent();
}
}
}
private Optional<S3Config> fetchRemoteConfig(final HttpClient client)
throws IOException {
log.debug("Fetching config at {}", url.get());
final HttpGet get = new HttpGet(url.get());
InputStream is = null;
try {
final HttpResponse res = client.execute(get);
is = res.getEntity().getContent();
final String cfgStr = IOUtils.toString(is);
log.debug("Fetched config:\n{}", cfgStr);
final S3Config cfg =
JsonUtils.OBJECT_MAPPER.readValue(cfgStr, S3Config.class);
return Optional.of(cfg);
} finally {
IOUtils.closeQuietly(is);
get.reset();
}
}
private void copyUrlFile() throws IOException {
log.debug("Copying config URL file");
final File curDir = new File(SystemUtils.getUserDir(), URL_FILENAME);
final Collection<File> filesToTry = Lists.newArrayList(
new File(SystemUtils.getUserHome(), URL_FILENAME),
curDir
);
if (SystemUtils.IS_OS_WINDOWS) {
filesToTry.add(new File(System.getenv("APPDATA")));
}
final File par = LanternClientConstants.CONFIG_DIR;
if (!par.isDirectory() && !par.mkdirs()) {
log.error("Could not make config dir at "+par);
throw new IOException("Could not make config dir at "+par);
}
for (final File from : filesToTry) {
if (!from.getParentFile().isDirectory()) {
log.error("Parent file is not a directory at {}",
from.getParentFile());
}
if (from.isFile() && (isFileNewer(from, URL_CONFIG_FILE) || from == curDir)) {
log.debug("Copying from {} to {}", from, URL_CONFIG_FILE);
try {
Files.copy(from, URL_CONFIG_FILE);
} catch (final IOException e) {
log.error("Could not copy config file from "+
from+" to "+URL_CONFIG_FILE, e);
}
return;
} else {
log.debug("No config file at {}", from);
}
}
if (!URL_CONFIG_FILE.isFile()) {
// If we exit the loop and end up here it means we could not find
// a config file to copy in any of the expected locations.
log.error("Config file not found at any of {}", filesToTry);
}
}
private boolean isFileNewer(final File file, final File reference) {
if (reference == null || !reference.isFile()) {
return true;
}
return FileUtils.isFileNewer(file, reference);
}
}
|
package org.oakgp.operator;
import static org.oakgp.util.Utils.assertEvaluateToSameResult;
import java.util.Optional;
import org.oakgp.Arguments;
import org.oakgp.node.ConstantNode;
import org.oakgp.node.FunctionNode;
import org.oakgp.node.Node;
import org.oakgp.util.NodeComparator;
/** Performs multiplication. */
public final class Multiply extends ArithmeticOperator {
/**
* Returns the result of multiplying the two elements of the specified arguments.
*
* @return the result of multiplying {@code arg1} and {@code arg2}
*/
@Override
protected int evaluate(int arg1, int arg2) {
return arg1 * arg2;
}
@Override
public Optional<Node> simplify(Arguments arguments) {
Node arg1 = arguments.get(0);
Node arg2 = arguments.get(1);
if (new NodeComparator().compare(arg1, arg2) > 0) {
return Optional.of(new FunctionNode(this, Arguments.createArguments(arg2, arg1)));
} else if (ZERO.equals(arg1)) {
return Optional.of(ZERO);
} else if (ZERO.equals(arg2)) {
throw new IllegalArgumentException("arg1 " + arg1 + " arg2 " + arg2);
} else if (ONE.equals(arg1)) {
return Optional.of(arg2);
} else if (ONE.equals(arg2)) {
throw new IllegalArgumentException("arg1 " + arg1 + " arg2 " + arg2);
} else {
if (arg1 instanceof ConstantNode && arg2 instanceof FunctionNode) {
FunctionNode fn = (FunctionNode) arg2;
Operator o = fn.getOperator();
Arguments args = fn.getArguments();
Node fnArg1 = args.get(0);
Node fnArg2 = args.get(1);
if (fnArg1 instanceof ConstantNode) {
int i1 = (int) arg1.evaluate(null);
int i2 = (int) fnArg1.evaluate(null);
int result;
if (o.getClass() == Add.class || o.getClass() == Subtract.class) {
result = i1 * i2;
Node n = new FunctionNode(o, Arguments.createArguments(createConstant(result),
new FunctionNode(this, Arguments.createArguments(arg1, fnArg2))));
return Optional.of(n);
} else if (o.getClass() == Multiply.class) {
return Optional.of(new FunctionNode(this, Arguments.createArguments(createConstant(i1 * i2), fnArg2)));
} else {
throw new IllegalArgumentException();
}
} else if (o.getClass() == Add.class || o.getClass() == Subtract.class) {
Node n = new FunctionNode(o, Arguments.createArguments(new FunctionNode(this, Arguments.createArguments(arg1, fnArg1)), new FunctionNode(
this, Arguments.createArguments(arg1, fnArg2))));
return Optional.of(n);
}
}
FunctionNode in = new FunctionNode(this, Arguments.createArguments(arg1, arg2));
Node out = new ArithmeticExpressionSimplifier().simplify(in);
if (!in.equals(out)) {
assertEvaluateToSameResult(in, out);
return Optional.of(out);
} else {
return Optional.empty();
}
}
}
}
|
package org.omegafactor.robot;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.AbstractExecutionThreadService;
import com.google.common.util.concurrent.Service;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Talon;
import java.util.List;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class Robot extends IterativeRobot {
private final Talon test;
private TeleOp teleOp;
public Robot() {
super();
test = new Talon(2);
teleOp = new TeleOp();
}
@Override
public void robotInit() {
System.out.print("Hi!");
}
@Override
public void teleopInit() {
teleOp = new TeleOp();
teleOp.startAsync();
}
@Override
public void disabledInit() {
teleOp.stopAsync();
try {
teleOp.awaitTerminated(5, TimeUnit.SECONDS);
} catch (TimeoutException e) {
Throwables.propagate(e);
}
}
@Override
public void teleopPeriodic() {
if (!teleOp.isRunning()) {
teleOp.startAsync();
}
}
private class TeleOp extends AbstractExecutionThreadService implements CoreRobotService {
@Override
public String getName() {
return "TeleOp";
}
@Override
public OperationalType getType() {
return OperationalType.TELEOP;
}
@Override
protected void run() throws Exception {
while (isRunning()) {
test.set(1);
}
}
}
}
|
package org.scijava;
import org.scijava.app.App;
import org.scijava.app.AppService;
import org.scijava.app.SciJavaApp;
import org.scijava.app.StatusService;
import org.scijava.command.CommandService;
import org.scijava.console.ConsoleService;
import org.scijava.convert.ConvertService;
import org.scijava.display.DisplayService;
import org.scijava.event.EventHistory;
import org.scijava.event.EventService;
import org.scijava.input.InputService;
import org.scijava.io.IOService;
import org.scijava.io.RecentFileService;
import org.scijava.log.LogService;
import org.scijava.menu.MenuService;
import org.scijava.module.ModuleService;
import org.scijava.object.ObjectService;
import org.scijava.options.OptionsService;
import org.scijava.platform.AppEventService;
import org.scijava.platform.PlatformService;
import org.scijava.plugin.AbstractRichPlugin;
import org.scijava.plugin.PluginService;
import org.scijava.prefs.PrefService;
import org.scijava.script.ScriptService;
import org.scijava.service.Service;
import org.scijava.text.TextService;
import org.scijava.thread.ThreadService;
import org.scijava.tool.IconService;
import org.scijava.tool.ToolService;
import org.scijava.usage.UsageService;
import org.scijava.widget.WidgetService;
/**
* Abstract superclass for {@link Gateway} implementations.
*
* @author Mark Hiner
* @author Curtis Rueden
*/
public abstract class AbstractGateway extends AbstractRichPlugin implements
Gateway
{
private final String appName;
// -- Constructor --
public AbstractGateway() {
this(SciJavaApp.NAME, null);
}
public AbstractGateway(final String appName, final Context context) {
this.appName = appName;
if (context != null) setContext(context);
}
// -- Gateway methods --
@Override
public <S extends Service> S get(final Class<S> serviceClass) {
return context().service(serviceClass);
}
@Override
public Service get(final String serviceClassName) {
return context().service(serviceClassName);
}
// -- Gateway methods - services --
@Override
public AppEventService appEvent() {
return get(AppEventService.class);
}
@Override
public AppService app() {
return get(AppService.class);
}
@Override
public CommandService command() {
return get(CommandService.class);
}
@Override
public ConsoleService console() {
return get(ConsoleService.class);
}
public ConvertService convert() {
return get(ConvertService.class);
}
@Override
public DisplayService display() {
return get(DisplayService.class);
}
@Override
public EventHistory eventHistory() {
return get(EventHistory.class);
}
@Override
public EventService event() {
return get(EventService.class);
}
@Override
public IconService icon() {
return get(IconService.class);
}
@Override
public InputService input() {
return get(InputService.class);
}
@Override
public IOService io() {
return get(IOService.class);
}
@Override
public LogService log() {
return get(LogService.class);
}
@Override
public MenuService menu() {
return get(MenuService.class);
}
@Override
public ModuleService module() {
return get(ModuleService.class);
}
@Override
public ObjectService object() {
return get(ObjectService.class);
}
@Override
public OptionsService options() {
return get(OptionsService.class);
}
@Override
public PlatformService platform() {
return get(PlatformService.class);
}
@Override
public PluginService plugin() {
return get(PluginService.class);
}
public PrefService prefs() {
return get(PrefService.class);
}
@Override
public RecentFileService recentFile() {
return get(RecentFileService.class);
}
@Override
public ScriptService script() {
return get(ScriptService.class);
}
@Override
public StatusService status() {
return get(StatusService.class);
}
@Override
public TextService text() {
return get(TextService.class);
}
@Override
public ThreadService thread() {
return get(ThreadService.class);
}
@Override
public ToolService tool() {
return get(ToolService.class);
}
@Override
public UsageService usage() {
return get(UsageService.class);
}
@Override
public WidgetService widget() {
return get(WidgetService.class);
}
// -- Gateway methods - application --
@Override
public App getApp() {
return app().getApp(appName);
}
@Override
public String getTitle() {
return getApp().getTitle();
}
@Override
public String getVersion() {
return getApp().getVersion();
}
@Override
public String getInfo(final boolean mem) {
return getApp().getInfo(mem);
}
}
|
package org.spoonless;
import java.util.List;
public class StepTokenNode {
private StepToken stepToken;
private StepDescriptor stepDescriptor;
private List<StepTokenNode> nextNodes;
public StepDescriptor getStepDescriptor() {
return stepDescriptor;
}
public void setStepDescriptor(StepDescriptor stepDescriptor) {
this.stepDescriptor = stepDescriptor;
}
}
|
package org.testng.internal;
import static org.testng.internal.invokers.InvokedMethodListenerMethod.AFTER_INVOCATION;
import static org.testng.internal.invokers.InvokedMethodListenerMethod.BEFORE_INVOCATION;
import org.testng.IClass;
import org.testng.IConfigurable;
import org.testng.IConfigurationListener;
import org.testng.IConfigurationListener2;
import org.testng.IHookable;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.IRetryAnalyzer;
import org.testng.ITestClass;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.SkipException;
import org.testng.SuiteRunState;
import org.testng.TestException;
import org.testng.TestNGException;
import org.testng.annotations.IConfigurationAnnotation;
import org.testng.annotations.NoInjection;
import org.testng.collections.Lists;
import org.testng.collections.Maps;
import org.testng.internal.InvokeMethodRunnable.TestNGRuntimeException;
import org.testng.internal.ParameterHolder.ParameterOrigin;
import org.testng.internal.annotations.AnnotationHelper;
import org.testng.internal.annotations.IAnnotationFinder;
import org.testng.internal.annotations.Sets;
import org.testng.internal.invokers.InvokedMethodListenerInvoker;
import org.testng.internal.invokers.InvokedMethodListenerMethod;
import org.testng.internal.thread.ThreadExecutionException;
import org.testng.internal.thread.ThreadUtil;
import org.testng.internal.thread.graph.IWorker;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/**
* This class is responsible for invoking methods:
* - test methods
* - configuration methods
* - possibly in a separate thread
* and then for notifying the result listeners.
*
* @author <a href="mailto:cedric@beust.com">Cedric Beust</a>
* @author <a href='mailto:the_mindstorm@evolva.ro'>Alexandru Popescu</a>
*/
public class Invoker implements IInvoker {
private final ITestContext m_testContext;
private final ITestResultNotifier m_notifier;
private final IAnnotationFinder m_annotationFinder;
private final SuiteRunState m_suiteState;
private final boolean m_skipFailedInvocationCounts;
private final List<IInvokedMethodListener> m_invokedMethodListeners;
private final boolean m_continueOnFailedConfiguration;
/** Group failures must be synced as the Invoker is accessed concurrently */
private Map<String, Boolean> m_beforegroupsFailures = Maps.newHashtable();
/** Class failures must be synced as the Invoker is accessed concurrently */
private Map<Class<?>, Set<Object>> m_classInvocationResults = Maps.newHashtable();
/** Test methods whose configuration methods have failed. */
private Map<ITestNGMethod, Set<Object>> m_methodInvocationResults = Maps.newHashtable();
private IConfiguration m_configuration;
/** Predicate to filter methods */
private static Predicate CAN_RUN_FROM_CLASS = new CanRunFromClassPredicate();
/** Predicate to filter methods */
private static final Predicate SAME_CLASS = new SameClassNamePredicate();
private void setClassInvocationFailure(Class<?> clazz, Object instance) {
Set<Object> instances = m_classInvocationResults.get( clazz );
if (instances == null) {
instances = Sets.newHashSet();
m_classInvocationResults.put(clazz, instances);
}
instances.add(instance);
}
private void setMethodInvocationFailure(ITestNGMethod method, Object instance) {
Set<Object> instances = m_methodInvocationResults.get(method);
if (instances == null) {
instances = Sets.newHashSet();
m_methodInvocationResults.put(method, instances);
}
instances.add(getMethodInvocationToken(method, instance));
}
public Invoker(IConfiguration configuration,
ITestContext testContext,
ITestResultNotifier notifier,
SuiteRunState state,
boolean skipFailedInvocationCounts,
List<IInvokedMethodListener> invokedMethodListeners) {
m_configuration = configuration;
m_testContext= testContext;
m_suiteState= state;
m_notifier= notifier;
m_annotationFinder= configuration.getAnnotationFinder();
m_skipFailedInvocationCounts = skipFailedInvocationCounts;
m_invokedMethodListeners = invokedMethodListeners;
m_continueOnFailedConfiguration = XmlSuite.CONTINUE.equals(testContext.getSuite().getXmlSuite().getConfigFailurePolicy());
}
/**
* Invoke configuration methods if they belong to the same TestClass passed
* in parameter.. <p/>TODO: Calculate ahead of time which methods should be
* invoked for each class. Might speed things up for users who invoke the
* same test class with different parameters in the same suite run.
*
* If instance is non-null, the configuration will be run on it. If it is null,
* the configuration methods will be run on all the instances retrieved
* from the ITestClass.
*/
@Override
public void invokeConfigurations(IClass testClass,
ITestNGMethod[] allMethods,
XmlSuite suite,
Map<String, String> params,
Object[] parameterValues,
Object instance)
{
invokeConfigurations(testClass, null, allMethods, suite, params, parameterValues, instance,
null);
}
private void invokeConfigurations(IClass testClass,
ITestNGMethod currentTestMethod,
ITestNGMethod[] allMethods,
XmlSuite suite,
Map<String, String> params,
Object[] parameterValues,
Object instance,
ITestResult testMethodResult)
{
if(null == allMethods) {
log(5, "No configuration methods found");
return;
}
ITestNGMethod[] methods= filterMethods(testClass, allMethods, SAME_CLASS);
for(ITestNGMethod tm : methods) {
if(null == testClass) {
testClass= tm.getTestClass();
}
ITestResult testResult= new TestResult(testClass,
instance,
tm,
null,
System.currentTimeMillis(),
System.currentTimeMillis(),
m_testContext);
IConfigurationAnnotation configurationAnnotation= null;
try {
Object[] instances= tm.getInstances();
if (instances == null || instances.length == 0) {
instances = new Object[] { instance };
}
Class<?> objectClass= instances[0].getClass();
Method method= tm.getMethod();
// Only run the configuration if
// - the test is enabled and
// - the Configuration method belongs to the same class or a parent
if(MethodHelper.isEnabled(objectClass, m_annotationFinder)) {
configurationAnnotation = AnnotationHelper.findConfiguration(m_annotationFinder, method);
if (MethodHelper.isEnabled(configurationAnnotation)) {
boolean isClassConfiguration = isClassConfiguration(configurationAnnotation);
boolean isSuiteConfiguration = isSuiteConfiguration(configurationAnnotation);
boolean alwaysRun= isAlwaysRun(configurationAnnotation);
if (!confInvocationPassed(tm, currentTestMethod, testClass, instance) && !alwaysRun) {
handleConfigurationSkip(tm, testResult, configurationAnnotation, currentTestMethod, instance, suite);
continue;
}
log(3, "Invoking " + Utils.detailedMethodName(tm, true));
Object[] parameters = Parameters.createConfigurationParameters(tm.getMethod(),
params,
parameterValues,
currentTestMethod,
m_annotationFinder,
suite,
m_testContext,
testMethodResult);
testResult.setParameters(parameters);
Object[] newInstances= (null != instance) ? new Object[] { instance } : instances;
runConfigurationListeners(testResult, true /* before */);
invokeConfigurationMethod(newInstances, tm,
parameters, isClassConfiguration, isSuiteConfiguration, testResult);
// TODO: probably we should trigger the event for each instance???
testResult.setEndMillis(System.currentTimeMillis());
runConfigurationListeners(testResult, false /* after */);
}
else {
log(3,
"Skipping "
+ Utils.detailedMethodName(tm, true)
+ " because it is not enabled");
}
} // if is enabled
else {
log(3,
"Skipping "
+ Utils.detailedMethodName(tm, true)
+ " because "
+ objectClass.getName()
+ " is not enabled");
}
}
catch(InvocationTargetException ex) {
handleConfigurationFailure(ex, tm, testResult, configurationAnnotation, currentTestMethod, instance, suite);
}
catch(TestNGException ex) {
// Don't wrap TestNGExceptions, it could be a missing parameter on a
// @Configuration method
handleConfigurationFailure(ex, tm, testResult, configurationAnnotation, currentTestMethod, instance, suite);
}
catch(Throwable ex) { // covers the non-wrapper exceptions
handleConfigurationFailure(ex, tm, testResult, configurationAnnotation, currentTestMethod, instance, suite);
}
} // for methods
}
/**
* Marks the current <code>TestResult</code> as skipped and invokes the listeners.
*/
private void handleConfigurationSkip(ITestNGMethod tm,
ITestResult testResult,
IConfigurationAnnotation annotation,
ITestNGMethod currentTestMethod,
Object instance,
XmlSuite suite) {
recordConfigurationInvocationFailed(tm, testResult.getTestClass(), annotation, currentTestMethod, instance, suite);
testResult.setStatus(ITestResult.SKIP);
runConfigurationListeners(testResult, false /* after */);
}
/**
* Is the current <code>IConfiguration</code> a class-level method.
*/
private boolean isClassConfiguration(IConfigurationAnnotation configurationAnnotation) {
if (null == configurationAnnotation) {
return false;
}
boolean before = configurationAnnotation.getBeforeTestClass();
boolean after = configurationAnnotation.getAfterTestClass();
return before || after;
}
/**
* Is the current <code>IConfiguration</code> a suite level method.
*/
private boolean isSuiteConfiguration(IConfigurationAnnotation configurationAnnotation) {
if (null == configurationAnnotation) {
return false;
}
boolean before = configurationAnnotation.getBeforeSuite();
boolean after = configurationAnnotation.getAfterSuite();
return before || after;
}
/**
* Is the <code>IConfiguration</code> marked as alwaysRun.
*/
private boolean isAlwaysRun(IConfigurationAnnotation configurationAnnotation) {
if(null == configurationAnnotation) {
return false;
}
boolean alwaysRun= false;
if ((configurationAnnotation.getAfterSuite()
|| configurationAnnotation.getAfterTest()
|| configurationAnnotation.getAfterTestClass()
|| configurationAnnotation.getAfterTestMethod())
&& configurationAnnotation.getAlwaysRun())
{
alwaysRun= true;
}
return alwaysRun;
}
private void handleConfigurationFailure(Throwable ite,
ITestNGMethod tm,
ITestResult testResult,
IConfigurationAnnotation annotation,
ITestNGMethod currentTestMethod,
Object instance,
XmlSuite suite)
{
Throwable cause= ite.getCause() != null ? ite.getCause() : ite;
if(SkipException.class.isAssignableFrom(cause.getClass())) {
SkipException skipEx= (SkipException) cause;
if(skipEx.isSkip()) {
testResult.setThrowable(skipEx);
handleConfigurationSkip(tm, testResult, annotation, currentTestMethod, instance, suite);
return;
}
}
Utils.log("", 3, "Failed to invoke configuration method "
+ tm.getRealClass().getName() + "." + tm.getMethodName() + ":" + cause.getMessage());
handleException(cause, tm, testResult, 1);
runConfigurationListeners(testResult, false /* after */);
// If in TestNG mode, need to take a look at the annotation to figure out
// what kind of @Configuration method we're dealing with
if (null != annotation) {
recordConfigurationInvocationFailed(tm, testResult.getTestClass(), annotation, currentTestMethod, instance, suite);
}
}
/**
* @return All the classes that belong to the same <test> tag as @param cls
*/
private XmlClass[] findClassesInSameTest(Class<?> cls, XmlSuite suite) {
Map<String, XmlClass> vResult= Maps.newHashMap();
String className= cls.getName();
for(XmlTest test : suite.getTests()) {
for(XmlClass testClass : test.getXmlClasses()) {
if(testClass.getName().equals(className)) {
// Found it, add all the classes in this test in the result
for(XmlClass thisClass : test.getXmlClasses()) {
vResult.put(thisClass.getName(), thisClass);
}
// Note: we need to iterate through the entire suite since the same
// class might appear in several <test> tags
}
}
}
XmlClass[] result= vResult.values().toArray(new XmlClass[vResult.size()]);
return result;
}
/**
* Record internally the failure of a Configuration, so that we can determine
* later if @Test should be skipped.
*/
private void recordConfigurationInvocationFailed(ITestNGMethod tm,
IClass testClass,
IConfigurationAnnotation annotation,
ITestNGMethod currentTestMethod,
Object instance,
XmlSuite suite) {
// If beforeTestClass or afterTestClass failed, mark either the config method's
// entire class as failed, or the class under tests as failed, depending on
// the configuration failure policy
if (annotation.getBeforeTestClass() || annotation.getAfterTestClass()) {
// tm is the configuration method, and currentTestMethod is null for BeforeClass
// methods, so we need testClass
if (m_continueOnFailedConfiguration) {
setClassInvocationFailure(testClass.getRealClass(), instance);
} else {
setClassInvocationFailure(tm.getRealClass(), instance);
}
}
// If before/afterTestMethod failed, mark either the config method's entire
// class as failed, or just the current test method as failed, depending on
// the configuration failure policy
else if (annotation.getBeforeTestMethod() || annotation.getAfterTestMethod()) {
if (m_continueOnFailedConfiguration) {
setMethodInvocationFailure(currentTestMethod, instance);
} else {
setClassInvocationFailure(tm.getRealClass(), instance);
}
}
// If beforeSuite or afterSuite failed, mark *all* the classes as failed
// for configurations. At this point, the entire Suite is screwed
else if (annotation.getBeforeSuite() || annotation.getAfterSuite()) {
m_suiteState.failed();
}
// beforeTest or afterTest: mark all the classes in the same
// <test> stanza as failed for configuration
else if (annotation.getBeforeTest() || annotation.getAfterTest()) {
setClassInvocationFailure(tm.getRealClass(), instance);
XmlClass[] classes= findClassesInSameTest(tm.getRealClass(), suite);
for(XmlClass xmlClass : classes) {
setClassInvocationFailure(xmlClass.getSupportClass(), instance);
}
}
String[] beforeGroups= annotation.getBeforeGroups();
if(null != beforeGroups && beforeGroups.length > 0) {
for(String group: beforeGroups) {
m_beforegroupsFailures.put(group, Boolean.FALSE);
}
}
}
/**
* @return true if this class has successfully run all its @Configuration
* method or false if at least one of these methods failed.
*/
private boolean confInvocationPassed(ITestNGMethod method, ITestNGMethod currentTestMethod, IClass testClass, Object instance) {
boolean result= true;
// If continuing on config failure, check invocation results for the class
// under test, otherwise use the method's declaring class
Class<?> cls = m_continueOnFailedConfiguration ?
testClass.getRealClass() : method.getMethod().getDeclaringClass();
if(m_suiteState.isFailed()) {
result= false;
}
else {
if (m_classInvocationResults.containsKey(cls)) {
if (! m_continueOnFailedConfiguration) {
result = !m_classInvocationResults.containsKey(cls);
} else {
result = !m_classInvocationResults.get(cls).contains(instance);
}
}
// if method is BeforeClass, currentTestMethod will be null
else if (m_continueOnFailedConfiguration &&
currentTestMethod != null &&
m_methodInvocationResults.containsKey(currentTestMethod)) {
result = !m_methodInvocationResults.get(currentTestMethod).contains(getMethodInvocationToken(currentTestMethod, instance));
}
else if (! m_continueOnFailedConfiguration) {
for(Class<?> clazz: m_classInvocationResults.keySet()) {
// if (clazz == cls) {
if(clazz.isAssignableFrom(cls)) {
result= false;
break;
}
}
}
}
// check if there are failed @BeforeGroups
String[] groups= method.getGroups();
if(null != groups && groups.length > 0) {
for(String group: groups) {
if(m_beforegroupsFailures.containsKey(group)) {
result= false;
break;
}
}
}
return result;
}
// Creates a token for tracking a unique invocation of a method on an instance.
// Is used when configFailurePolicy=continue.
private Object getMethodInvocationToken(ITestNGMethod method, Object instance) {
return String.format("%s+%d", instance.toString(), method.getCurrentInvocationCount());
}
private void invokeConfigurationMethod(Object[] instances,
ITestNGMethod tm,
Object[] params,
boolean isClass,
boolean isSuite,
ITestResult testResult)
throws InvocationTargetException, IllegalAccessException
{
// Mark this method with the current thread id
tm.setId(ThreadUtil.currentThreadInfo());
// Only a @BeforeMethod/@AfterMethod needs to be run before each instance, all the other
// configuration methods only need to be run once
List<Object> actualInstances = Lists.newArrayList();
if (tm.isBeforeMethodConfiguration() || tm.isAfterMethodConfiguration()) {
actualInstances.addAll(Arrays.asList(instances));
} else {
actualInstances.add(instances[0]);
}
for(Object targetInstance : actualInstances) {
InvokedMethod invokedMethod= new InvokedMethod(targetInstance,
tm,
params,
false, /* isTest */
isClass,
System.currentTimeMillis(),
testResult);
runInvokedMethodListeners(BEFORE_INVOCATION, invokedMethod, testResult);
m_notifier.addInvokedMethod(invokedMethod);
try {
Reporter.setCurrentTestResult(testResult);
Method method = tm.getMethod();
// If this method is a IHookable, invoke its run() method
IConfigurable configurableInstance =
IConfigurable.class.isAssignableFrom(tm.getMethod().getDeclaringClass()) ?
(IConfigurable) targetInstance : m_configuration.getConfigurable();
if (configurableInstance != null) {
// If this method is a IConfigurable, invoke its run() method
MethodInvocationHelper.invokeConfigurable(targetInstance, params, configurableInstance, method,
testResult);
}
else {
// Not a IConfigurable, invoke directly
if (MethodHelper.calculateTimeOut(tm) <= 0) {
MethodInvocationHelper.invokeMethod(method, targetInstance, params);
}
else {
MethodInvocationHelper.invokeWithTimeout(tm, targetInstance, params, testResult);
if (!testResult.isSuccess()) {
// A time out happened
throwConfigurationFailure(testResult, testResult.getThrowable());
throw testResult.getThrowable();
}
}
}
// Only run the method once if it's @BeforeSuite or @AfterSuite
if (isSuite) {
break;
}
}
catch (InvocationTargetException ex) {
throwConfigurationFailure(testResult, ex);
throw ex;
}
catch (IllegalAccessException ex) {
throwConfigurationFailure(testResult, ex);
throw ex;
}
catch (NoSuchMethodException ex) {
throwConfigurationFailure(testResult, ex);
throw new TestNGException(ex);
}
catch (Throwable ex) {
throwConfigurationFailure(testResult, ex);
throw new TestNGException(ex);
}
finally {
Reporter.setCurrentTestResult(testResult);
runInvokedMethodListeners(AFTER_INVOCATION, invokedMethod, testResult);
Reporter.setCurrentTestResult(null);
}
}
}
private void throwConfigurationFailure(ITestResult testResult, Throwable ex)
{
testResult.setStatus(ITestResult.FAILURE);;
testResult.setThrowable(ex.getCause() == null ? ex : ex.getCause());
}
private void runInvokedMethodListeners(InvokedMethodListenerMethod listenerMethod, IInvokedMethod invokedMethod,
ITestResult testResult)
{
if ( noListenersPresent() ) {
return;
}
InvokedMethodListenerInvoker invoker = new InvokedMethodListenerInvoker(listenerMethod, testResult, m_testContext);
for (IInvokedMethodListener currentListener : m_invokedMethodListeners) {
invoker.invokeListener(currentListener, invokedMethod);
}
}
private boolean noListenersPresent() {
return (m_invokedMethodListeners == null) || (m_invokedMethodListeners.size() == 0);
}
// pass both paramValues and paramIndex to be thread safe in case parallel=true + dataprovider.
private ITestResult invokeMethod(Object[] instances,
int instanceIndex,
final ITestNGMethod tm,
Object[] parameterValues,
int parametersIndex,
XmlSuite suite,
Map<String, String> params,
ITestClass testClass,
ITestNGMethod[] beforeMethods,
ITestNGMethod[] afterMethods,
ConfigurationGroupMethods groupMethods) {
TestResult testResult = new TestResult();
// Invoke beforeGroups configurations
Object instance = instances[instanceIndex];
invokeBeforeGroupsConfigurations(testClass, tm, groupMethods, suite, params,
instance);
// Invoke beforeMethods only if
// - firstTimeOnly is not set
// - firstTimeOnly is set, and we are reaching at the first invocationCount
invokeConfigurations(testClass, tm,
filterConfigurationMethods(tm, beforeMethods, true /* beforeMethods */),
suite, params, parameterValues,
instance, testResult);
// Create the ExtraOutput for this method
InvokedMethod invokedMethod = null;
try {
testResult.init(testClass, instance,
tm,
null,
System.currentTimeMillis(),
0,
m_testContext);
testResult.setParameters(parameterValues);
testResult.setHost(m_testContext.getHost());
testResult.setStatus(ITestResult.STARTED);
invokedMethod= new InvokedMethod(instance,
tm,
parameterValues,
true /* isTest */,
false /* isConfiguration */,
System.currentTimeMillis(),
testResult);
// Fix from ansgarkonermann
// invokedMethod is used in the finally, which can be invoked if
// any of the test listeners throws an exception, therefore,
// invokedMethod must have a value before we get here
runTestListeners(testResult);
runInvokedMethodListeners(BEFORE_INVOCATION, invokedMethod, testResult);
m_notifier.addInvokedMethod(invokedMethod);
Method thisMethod= tm.getMethod();
if(confInvocationPassed(tm, tm, testClass, instance)) {
log(3, "Invoking " + thisMethod.getDeclaringClass().getName() + "." +
thisMethod.getName());
// If no timeOut, just invoke the method
if (MethodHelper.calculateTimeOut(tm) <= 0) {
try {
Reporter.setCurrentTestResult(testResult);
// If this method is a IHookable, invoke its run() method
IHookable hookableInstance =
IHookable.class.isAssignableFrom(thisMethod.getDeclaringClass()) ?
(IHookable) instance : m_configuration.getHookable();
if (hookableInstance != null) {
MethodInvocationHelper.invokeHookable(instance,
parameterValues, hookableInstance, thisMethod, testResult);
}
// Not a IHookable, invoke directly
else {
MethodInvocationHelper.invokeMethod(thisMethod, instance,
parameterValues);
}
testResult.setStatus(ITestResult.SUCCESS);
}
finally {
Reporter.setCurrentTestResult(null);
}
}
else {
// Method with a timeout
try {
Reporter.setCurrentTestResult(testResult);
MethodInvocationHelper.invokeWithTimeout(tm, instance, parameterValues, testResult);
}
finally {
Reporter.setCurrentTestResult(null);
}
}
}
else {
testResult.setStatus(ITestResult.SKIP);
}
}
catch(InvocationTargetException ite) {
testResult.setThrowable(ite.getCause());
testResult.setStatus(ITestResult.FAILURE);
}
catch(ThreadExecutionException tee) { // wrapper for TestNGRuntimeException
Throwable cause= tee.getCause();
if(TestNGRuntimeException.class.equals(cause.getClass())) {
testResult.setThrowable(cause.getCause());
}
else {
testResult.setThrowable(cause);
}
testResult.setStatus(ITestResult.FAILURE);
}
catch(Throwable thr) { // covers the non-wrapper exceptions
testResult.setThrowable(thr);
testResult.setStatus(ITestResult.FAILURE);
}
finally {
ExpectedExceptionsHolder expectedExceptionClasses
= MethodHelper.findExpectedExceptions(m_annotationFinder, tm.getMethod());
List<ITestResult> results = Lists.newArrayList();
results.add(testResult);
handleInvocationResults(tm, results, null, 0, expectedExceptionClasses, false,
false /* collect results */);
// If this method has a data provider and just failed, memorize the number
// at which it failed.
// Note: we're not exactly testing that this method has a data provider, just
// that it has parameters, so might have to revisit this if bugs get reported
// for the case where this method has parameters that don't come from a data
// provider
if (testResult.getThrowable() != null && parameterValues.length > 0) {
tm.addFailedInvocationNumber(parametersIndex);
}
// Increment the invocation count for this method
tm.incrementCurrentInvocationCount();
if (testResult != null) {
testResult.setEndMillis(System.currentTimeMillis());
}
// Run invokedMethodListeners after updating TestResult
runInvokedMethodListeners(AFTER_INVOCATION, invokedMethod, testResult);
runTestListeners(testResult);
collectResults(tm, results, testResult);
// Invoke afterMethods only if
// - lastTimeOnly is not set
// - lastTimeOnly is set, and we are reaching the last invocationCount
invokeConfigurations(testClass, tm,
filterConfigurationMethods(tm, afterMethods, false /* beforeMethods */),
suite, params, parameterValues,
instance,
testResult);
// Invoke afterGroups configurations
invokeAfterGroupsConfigurations(testClass, tm, groupMethods, suite,
params, instance);
}
return testResult;
}
private void collectResults(ITestNGMethod testMethod, List<ITestResult> results, TestResult testResult) {
for (int i = 0; i < results.size(); i++) {
// Collect the results
int status = results.get(i).getStatus();
if(ITestResult.SUCCESS == status) {
m_notifier.addPassedTest(testMethod, testResult);
}
else if(ITestResult.SKIP == status) {
m_notifier.addSkippedTest(testMethod, testResult);
}
else if(ITestResult.FAILURE == status) {
m_notifier.addFailedTest(testMethod, testResult);
}
else if(ITestResult.SUCCESS_PERCENTAGE_FAILURE == status) {
m_notifier.addFailedButWithinSuccessPercentageTest(testMethod, testResult);
}
else {
assert false : "UNKNOWN STATUS:" + status;
}
}
}
/**
* The array of methods contains @BeforeMethods if isBefore if true, @AfterMethods
* otherwise. This function removes all the methods that should not be run at this
* point because they are either firstTimeOnly or lastTimeOnly and we haven't reached
* the current invocationCount yet
*/
private ITestNGMethod[] filterConfigurationMethods(ITestNGMethod tm,
ITestNGMethod[] methods, boolean isBefore)
{
List<ITestNGMethod> result = Lists.newArrayList();
for (ITestNGMethod m : methods) {
ConfigurationMethod cm = (ConfigurationMethod) m;
if (isBefore) {
if (! cm.isFirstTimeOnly() ||
(cm.isFirstTimeOnly() && tm.getCurrentInvocationCount() == 0))
{
result.add(m);
}
}
else {
int current = tm.getCurrentInvocationCount();
boolean isLast = false;
// If we have parameters, set the boolean if we are about to run
// the last invocation
if (tm.getParameterInvocationCount() > 0) {
isLast = current == tm.getParameterInvocationCount();
}
// If we have invocationCount > 1, set the boolean if we are about to
// run the last invocation
else if (tm.getInvocationCount() > 1) {
isLast = current == tm.getInvocationCount();
}
if (! cm.isLastTimeOnly() || (cm.isLastTimeOnly() && isLast)) {
result.add(m);
}
}
}
return result.toArray(new ITestNGMethod[result.size()]);
}
/**
* {@link #invokeTestMethods()} eventually converge here to invoke a single @Test method.
* <p/>
* This method is responsible for actually invoking the method. It decides if the invocation
* must be done:
* <ul>
* <li>through an <code>IHookable</code></li>
* <li>directly (through reflection)</li>
* <li>in a separate thread (in case it needs to timeout)
* </ul>
*
* <p/>
* This method is also reponsible for invoking @BeforeGroup, @BeforeMethod, @AfterMethod, @AfterGroup
* if it is the case for the passed in @Test method.
*/
protected List<ITestResult> invokeTestMethod(Object[] instances,
final ITestNGMethod tm,
Object[] parameterValues,
int parametersIndex,
XmlSuite suite,
Map<String, String> params,
ITestClass testClass,
ITestNGMethod[] beforeMethods,
ITestNGMethod[] afterMethods,
ConfigurationGroupMethods groupMethods)
{
List<ITestResult> results = Lists.newArrayList();
// Mark this method with the current thread id
tm.setId(ThreadUtil.currentThreadInfo());
for(int i= 0; i < instances.length; i++) {
results.add(invokeMethod(instances, i, tm, parameterValues, parametersIndex, suite, params,
testClass, beforeMethods, afterMethods, groupMethods));
}
return results;
}
/**
* Filter all the beforeGroups methods and invoke only those that apply
* to the current test method
*/
private void invokeBeforeGroupsConfigurations(ITestClass testClass,
ITestNGMethod currentTestMethod,
ConfigurationGroupMethods groupMethods,
XmlSuite suite,
Map<String, String> params,
Object instance)
{
synchronized(groupMethods) {
List<ITestNGMethod> filteredMethods = Lists.newArrayList();
String[] groups = currentTestMethod.getGroups();
Map<String, List<ITestNGMethod>> beforeGroupMap = groupMethods.getBeforeGroupsMap();
for (String group : groups) {
List<ITestNGMethod> methods = beforeGroupMap.get(group);
if (methods != null) {
filteredMethods.addAll(methods);
}
}
ITestNGMethod[] beforeMethodsArray = filteredMethods.toArray(new ITestNGMethod[filteredMethods.size()]);
// Invoke the right groups methods
if(beforeMethodsArray.length > 0) {
// don't pass the IClass or the instance as the method may be external
// the invocation must be similar to @BeforeTest/@BeforeSuite
invokeConfigurations(null, beforeMethodsArray, suite, params,
null, /* no parameter values */
null);
}
// Remove them so they don't get run again
groupMethods.removeBeforeGroups(groups);
}
}
private void invokeAfterGroupsConfigurations(ITestClass testClass,
ITestNGMethod currentTestMethod,
ConfigurationGroupMethods groupMethods,
XmlSuite suite,
Map<String, String> params,
Object instance)
{
// Skip this if the current method doesn't belong to any group
// (only a method that belongs to a group can trigger the invocation
// of afterGroups methods)
if (currentTestMethod.getGroups().length == 0) {
return;
}
// See if the currentMethod is the last method in any of the groups
// it belongs to
Map<String, String> filteredGroups = Maps.newHashMap();
String[] groups = currentTestMethod.getGroups();
synchronized(groupMethods) {
for (String group : groups) {
if (groupMethods.isLastMethodForGroup(group, currentTestMethod)) {
filteredGroups.put(group, group);
}
}
if(filteredGroups.isEmpty()) {
return;
}
// The list of afterMethods to run
Map<ITestNGMethod, ITestNGMethod> afterMethods = Maps.newHashMap();
// Now filteredGroups contains all the groups for which we need to run the afterGroups
// method. Find all the methods that correspond to these groups and invoke them.
Map<String, List<ITestNGMethod>> map = groupMethods.getAfterGroupsMap();
for (String g : filteredGroups.values()) {
List<ITestNGMethod> methods = map.get(g);
// Note: should put them in a map if we want to make sure the same afterGroups
// doesn't get run twice
if (methods != null) {
for (ITestNGMethod m : methods) {
afterMethods.put(m, m);
}
}
}
// Got our afterMethods, invoke them
ITestNGMethod[] afterMethodsArray = afterMethods.keySet().toArray(new ITestNGMethod[afterMethods.size()]);
// don't pass the IClass or the instance as the method may be external
// the invocation must be similar to @BeforeTest/@BeforeSuite
invokeConfigurations(null, afterMethodsArray, suite, params,
null, /* no parameter values */
null);
// Remove the groups so they don't get run again
groupMethods.removeAfterGroups(filteredGroups.keySet());
}
}
private Object[] getParametersFromIndex(Iterator<Object[]> parametersValues, int index) {
while (parametersValues.hasNext()) {
Object[] parameters = parametersValues.next();
if (index == 0) {
return parameters;
}
index
}
return null;
}
int retryFailed(Object[] instances,
int instanceIndex,
final ITestNGMethod tm,
XmlSuite suite,
ITestClass testClass,
ITestNGMethod[] beforeMethods,
ITestNGMethod[] afterMethods,
ConfigurationGroupMethods groupMethods,
List<ITestResult> result,
int failureCount,
ExpectedExceptionsHolder expectedExceptionHolder,
ITestContext testContext,
Map<String, String> parameters,
int parametersIndex) {
List<Object> failedInstances;
do {
failedInstances = Lists.newArrayList();
Map<String, String> allParameters = Maps.newHashMap();
/**
* TODO: This recreates all the parameters every time when we only need
* one specific set. Should optimize it by only recreating the set needed.
*/
ParameterBag bag = createParameters(tm, parameters,
allParameters, null, suite, testContext, null /* fedInstance */, null /* testResult */);
Object[] parameterValues =
getParametersFromIndex(bag.parameterHolder.parameters, parametersIndex);
result.add(invokeMethod(instances, instanceIndex, tm, parameterValues,parametersIndex, suite,
allParameters, testClass, beforeMethods, afterMethods, groupMethods));
failureCount = handleInvocationResults(tm, result, failedInstances,
failureCount, expectedExceptionHolder, true, true /* collect results */);
}
while (!failedInstances.isEmpty());
return failureCount;
}
private ParameterBag createParameters(ITestNGMethod testMethod,
Map<String, String> parameters,
Map<String, String> allParameterNames,
Object[] parameterValues,
XmlSuite suite,
ITestContext testContext,
Object fedInstance,
ITestResult testResult)
{
Object instance;
if (fedInstance != null) {
instance = fedInstance;
}
else {
instance = testMethod.getInstance();
}
ParameterBag bag= handleParameters(testMethod,
instance, allParameterNames, parameters, parameterValues, suite, testContext, fedInstance,
testResult);
return bag;
}
/**
* Invoke all the test methods. Note the plural: the method passed in
* parameter might be invoked several times if the test class it belongs
* to has more than one instance (i.e., if an @Factory method has been
* declared somewhere that returns several instances of this TestClass).
* If no @Factory method was specified, testMethod will only be invoked
* once.
* <p/>
* Note that this method also takes care of invoking the beforeTestMethod
* and afterTestMethod, if any.
*
* Note (alex): this method can be refactored to use a SingleTestMethodWorker that
* directly invokes
* {@link #invokeTestMethod(Object[], ITestNGMethod, Object[], XmlSuite, Map, ITestClass, ITestNGMethod[], ITestNGMethod[], ConfigurationGroupMethods)}
* and this would simplify the implementation (see how DataTestMethodWorker is used)
*/
@Override
public List<ITestResult> invokeTestMethods(ITestNGMethod testMethod,
ITestNGMethod[] allTestMethods,
int testMethodIndex,
XmlSuite suite,
Map<String, String> parameters,
ConfigurationGroupMethods groupMethods,
Object[] instances,
ITestContext testContext)
{
// Potential bug here if the test method was declared on a parent class
assert null != testMethod.getTestClass()
: "COULDN'T FIND TESTCLASS FOR " + testMethod.getMethod().getDeclaringClass();
List<ITestResult> result = Lists.newArrayList();
if (!MethodHelper.isEnabled(testMethod.getMethod(), m_annotationFinder)) {
/*
* return if the method is not enabled. No need to do any more calculations
*/
return result;
}
ITestClass testClass= testMethod.getTestClass();
long start = System.currentTimeMillis();
// For invocationCount > 1 and threadPoolSize > 1 the method will be invoked on a thread pool
long timeOutInvocationCount = testMethod.getInvocationTimeOut();
//FIXME: Is this correct?
boolean onlyOne = testMethod.getThreadPoolSize() > 1 ||
timeOutInvocationCount > 0;
int invocationCount = onlyOne ? 1 : testMethod.getInvocationCount();
int failureCount = 0;
ExpectedExceptionsHolder expectedExceptionHolder =
MethodHelper.findExpectedExceptions(m_annotationFinder, testMethod.getMethod());
while(invocationCount
boolean okToProceed = checkDependencies(testMethod, allTestMethods);
if (!okToProceed) {
// Not okToProceed. Test is being skipped
ITestResult testResult = new TestResult(testClass, null /* instance */,
testMethod,
null /* cause */,
start,
System.currentTimeMillis(),
m_testContext);
String missingGroup = testMethod.getMissingGroup();
if (missingGroup != null) {
testResult.setThrowable(new Throwable("Method " + testMethod
+ " depends on nonexistent group \"" + missingGroup + "\""));
}
testResult.setStatus(ITestResult.SKIP);
result.add(testResult);
m_notifier.addSkippedTest(testMethod, testResult);
runTestListeners(testResult);
return result;
}
// If threadPoolSize specified, run this method in its own pool thread.
if (testMethod.getThreadPoolSize() > 1 && testMethod.getInvocationCount() > 1) {
return invokePooledTestMethods(testMethod, allTestMethods, suite,
parameters, groupMethods, testContext);
}
// No threads, regular invocation
else {
ITestNGMethod[] beforeMethods = filterMethods(testClass, testClass.getBeforeTestMethods(),
CAN_RUN_FROM_CLASS);
ITestNGMethod[] afterMethods = filterMethods(testClass, testClass.getAfterTestMethods(),
CAN_RUN_FROM_CLASS);
Map<String, String> allParameterNames = Maps.newHashMap();
ParameterBag bag = createParameters(testMethod,
parameters, allParameterNames, null, suite, testContext, instances[0],
null);
if (bag.hasErrors()) {
failureCount = handleInvocationResults(testMethod,
bag.errorResults, null, failureCount, expectedExceptionHolder, true,
true /* collect results */);
ITestResult tr = registerSkippedTestResult(testMethod, instances[0], start,
bag.errorResults.get(0).getThrowable());
result.add(tr);
continue;
}
Iterator<Object[]> allParameterValues = bag.parameterHolder.parameters;
int parametersIndex = 0;
try {
List<TestMethodWithDataProviderMethodWorker> workers = Lists.newArrayList();
if (bag.parameterHolder.origin == ParameterOrigin.ORIGIN_DATA_PROVIDER &&
bag.parameterHolder.dataProviderHolder.annotation.isParallel()) {
while (allParameterValues.hasNext()) {
Object[] parameterValues = injectParameters(allParameterValues.next(),
testMethod.getMethod(), testContext, null /* test result */);
TestMethodWithDataProviderMethodWorker w =
new TestMethodWithDataProviderMethodWorker(this,
testMethod, parametersIndex,
parameterValues, instances, suite, parameters, testClass,
beforeMethods, afterMethods, groupMethods,
expectedExceptionHolder, testContext, m_skipFailedInvocationCounts,
invocationCount, failureCount, m_notifier);
workers.add(w);
// testng387: increment the param index in the bag.
parametersIndex++;
}
PoolService ps = PoolService.getInstance();
List<ITestResult> r = ps.submitTasksAndWait(testMethod, workers);
result.addAll(r);
} else {
while (allParameterValues.hasNext()) {
Object[] parameterValues = injectParameters(allParameterValues.next(),
testMethod.getMethod(), testContext, null /* test result */);
List<ITestResult> tmpResults = Lists.newArrayList();
try {
tmpResults.addAll(invokeTestMethod(instances,
testMethod,
parameterValues,
parametersIndex,
suite,
parameters,
testClass,
beforeMethods,
afterMethods,
groupMethods));
}
finally {
List<Object> failedInstances = Lists.newArrayList();
failureCount = handleInvocationResults(testMethod, tmpResults,
failedInstances, failureCount, expectedExceptionHolder, true,
false /* don't collect results */);
if (failedInstances.isEmpty()) {
result.addAll(tmpResults);
} else {
for (int i = 0; i < failedInstances.size(); i++) {
List<ITestResult> retryResults = Lists.newArrayList();
failureCount =
retryFailed(failedInstances.toArray(),
i, testMethod, suite, testClass, beforeMethods,
afterMethods, groupMethods, retryResults,
failureCount, expectedExceptionHolder,
testContext, parameters, parametersIndex);
result.addAll(retryResults);
}
}
// If we have a failure, skip all the
// other invocationCounts
if (failureCount > 0
&& (m_skipFailedInvocationCounts
|| testMethod.skipFailedInvocations())) {
while (invocationCount
result.add(registerSkippedTestResult(testMethod, instances[0], start, null));
}
break;
}
}// end finally
parametersIndex++;
}
}
}
catch (Throwable cause) {
ITestResult r =
new TestResult(testMethod.getTestClass(),
instances[0],
testMethod,
cause,
start,
System.currentTimeMillis(),
m_testContext);
r.setStatus(TestResult.FAILURE);
result.add(r);
runTestListeners(r);
m_notifier.addFailedTest(testMethod, r);
} // catch
}
}
return result;
} // invokeTestMethod
private ITestResult registerSkippedTestResult(ITestNGMethod testMethod, Object instance,
long start, Throwable throwable) {
ITestResult result =
new TestResult(testMethod.getTestClass(),
instance,
testMethod,
throwable,
start,
System.currentTimeMillis(),
m_testContext);
result.setStatus(TestResult.SKIP);
runTestListeners(result);
return result;
}
/**
* Gets an array of parameter values returned by data provider or the ones that
* are injected based on parameter type. The method also checks for {@code NoInjection}
* annotation
* @param parameterValues parameter values from a data provider
* @param method method to be invoked
* @param context test context
* @param testResult test result
* @return
*/
private Object[] injectParameters(Object[] parameterValues, Method method,
ITestContext context, ITestResult testResult)
throws TestNGException {
List<Object> vResult = Lists.newArrayList();
int i = 0;
int numValues = parameterValues.length;
int numParams = method.getParameterTypes().length;
if (numValues > numParams && ! method.isVarArgs()) {
throw new TestNGException("The data provider is trying to pass " + numValues
+ " parameters but the method "
+ method.getDeclaringClass().getName() + "#" + method.getName()
+ " takes " + numParams);
}
// beyond this, numValues <= numParams
for (Class<?> cls : method.getParameterTypes()) {
Annotation[] annotations = method.getParameterAnnotations()[i];
boolean noInjection = false;
for (Annotation a : annotations) {
if (a instanceof NoInjection) {
noInjection = true;
break;
}
}
Object injected = Parameters.getInjectedParameter(cls, method, context, testResult);
if (injected != null && ! noInjection) {
vResult.add(injected);
} else {
try {
if (method.isVarArgs()) vResult.add(parameterValues);
else vResult.add(parameterValues[i++]);
} catch (ArrayIndexOutOfBoundsException ex) {
throw new TestNGException("The data provider is trying to pass " + numValues
+ " parameters but the method "
+ method.getDeclaringClass().getName() + "#" + method.getName()
+ " takes " + numParams
+ " and TestNG is unable in inject a suitable object", ex);
}
}
}
return vResult.toArray(new Object[vResult.size()]);
}
private ParameterBag handleParameters(ITestNGMethod testMethod,
Object instance,
Map<String, String> allParameterNames,
Map<String, String> parameters,
Object[] parameterValues,
XmlSuite suite,
ITestContext testContext,
Object fedInstance,
ITestResult testResult)
{
try {
return new ParameterBag(
Parameters.handleParameters(testMethod,
allParameterNames,
instance,
new Parameters.MethodParameters(parameters,
testMethod.findMethodParameters(testContext.getCurrentXmlTest()),
parameterValues,
testMethod.getMethod(), testContext, testResult),
suite,
m_annotationFinder,
fedInstance),
null /* TestResult */);
}
// catch(TestNGException ex) {
// throw ex;
catch(Throwable cause) {
return new ParameterBag(null /* ParameterHolder */,
new TestResult(
testMethod.getTestClass(),
instance,
testMethod,
cause,
System.currentTimeMillis(),
System.currentTimeMillis(),
m_testContext));
}
}
/**
* Invokes a method that has a specified threadPoolSize.
*/
private List<ITestResult> invokePooledTestMethods(ITestNGMethod testMethod,
ITestNGMethod[] allTestMethods,
XmlSuite suite,
Map<String, String> parameters,
ConfigurationGroupMethods groupMethods,
ITestContext testContext)
{
// Create the workers
List<IWorker<ITestNGMethod>> workers = Lists.newArrayList();
// Create one worker per invocationCount
for (int i = 0; i < testMethod.getInvocationCount(); i++) {
// we use clones for reporting purposes
ITestNGMethod clonedMethod= testMethod.clone();
clonedMethod.setInvocationCount(1);
clonedMethod.setThreadPoolSize(1);
MethodInstance mi = new MethodInstance(clonedMethod);
workers.add(new SingleTestMethodWorker(this,
mi,
suite,
parameters,
allTestMethods,
testContext));
}
return runWorkers(testMethod, workers, testMethod.getThreadPoolSize(), groupMethods, suite, parameters);
}
/**
* @param testMethod
* @param result
* @param failureCount
* @param expectedExceptionsHolder
* @return
*/
int handleInvocationResults(ITestNGMethod testMethod,
List<ITestResult> result,
List<Object> failedInstances,
int failureCount,
ExpectedExceptionsHolder expectedExceptionsHolder,
boolean triggerListeners,
boolean collectResults)
{
// Go through all the results and create a TestResult for each of them
List<ITestResult> resultsToRetry = Lists.newArrayList();
for (int i = 0; i < result.size(); i++) {
ITestResult testResult = result.get(i);
Throwable ite= testResult.getThrowable();
int status= testResult.getStatus();
// Exception thrown?
if (ite != null) {
// Invocation caused an exception, see if the method was annotated with @ExpectedException
if (isExpectedException(ite, expectedExceptionsHolder)) {
if (messageRegExpMatches(expectedExceptionsHolder.messageRegExp, ite)) {
testResult.setStatus(ITestResult.SUCCESS);
status= ITestResult.SUCCESS;
}
else {
testResult.setThrowable(
new TestException("The exception was thrown with the wrong message:" +
" expected \"" + expectedExceptionsHolder.messageRegExp + "\"" +
" but got \"" + ite.getMessage() + "\"", ite));
status= ITestResult.FAILURE;
}
} else if (SkipException.class.isAssignableFrom(ite.getClass())){
SkipException skipEx= (SkipException) ite;
if(skipEx.isSkip()) {
status = ITestResult.SKIP;
}
else {
handleException(ite, testMethod, testResult, failureCount++);
status = ITestResult.FAILURE;
}
} else if (ite != null && expectedExceptionsHolder != null) {
testResult.setThrowable(
new TestException("Expected exception "
+ expectedExceptionsHolder.expectedClasses[0].getName()
+ " but got " + ite, ite));
status= ITestResult.FAILURE;
} else {
handleException(ite, testMethod, testResult, failureCount++);
status= testResult.getStatus();
}
}
// No exception thrown, make sure we weren't expecting one
else if(status != ITestResult.SKIP && expectedExceptionsHolder != null) {
Class<?>[] classes = expectedExceptionsHolder.expectedClasses;
if (classes != null && classes.length > 0) {
testResult.setThrowable(
new TestException("Method " + testMethod + " should have thrown an exception of "
+ expectedExceptionsHolder.expectedClasses[0]));
status= ITestResult.FAILURE;
}
}
testResult.setStatus(status);
boolean retry = false;
if (testResult.getStatus() == ITestResult.FAILURE) {
IRetryAnalyzer retryAnalyzer = testMethod.getRetryAnalyzer();
if (retryAnalyzer != null && failedInstances != null) {
retry = retryAnalyzer.retry(testResult);
}
if (retry) {
resultsToRetry.add(testResult);
if (failedInstances != null) {
failedInstances.add(testResult.getInstance());
}
}
}
if (collectResults) {
// Collect the results
if(ITestResult.SUCCESS == status) {
m_notifier.addPassedTest(testMethod, testResult);
}
else if(ITestResult.SKIP == status) {
m_notifier.addSkippedTest(testMethod, testResult);
}
else if(ITestResult.FAILURE == status) {
m_notifier.addFailedTest(testMethod, testResult);
}
else if(ITestResult.SUCCESS_PERCENTAGE_FAILURE == status) {
m_notifier.addFailedButWithinSuccessPercentageTest(testMethod, testResult);
}
else {
assert false : "UNKNOWN STATUS:" + status;
}
// if (triggerListeners && status != ITestResult.SUCCESS) {
// runTestListeners(testResult);
}
} // for results
return removeResultsToRetryFromResult(resultsToRetry, result, failureCount);
}
/**
* message / regEx .* other
* null true false
* non-null true match
*/
private boolean messageRegExpMatches(String messageRegExp, Throwable ite) {
if (".*".equals(messageRegExp)) {
return true;
} else {
if (ite.getMessage() == null) {
return false;
} else {
return Pattern.matches(messageRegExp, ite.getMessage());
}
}
}
private int removeResultsToRetryFromResult(List<ITestResult> resultsToRetry,
List<ITestResult> result, int failureCount) {
if (resultsToRetry != null) {
for (ITestResult res : resultsToRetry) {
result.remove(res);
failureCount
}
}
return failureCount;
}
/**
* To reduce thread contention and also to correctly handle thread-confinement
* this method invokes the @BeforeGroups and @AfterGroups corresponding to the current @Test method.
*/
private List<ITestResult> runWorkers(ITestNGMethod testMethod,
List<IWorker<ITestNGMethod>> workers,
int threadPoolSize,
ConfigurationGroupMethods groupMethods,
XmlSuite suite,
Map<String, String> parameters)
{
// Invoke @BeforeGroups on the original method (reduce thread contention,
// and also solve thread confinement)
ITestClass testClass= testMethod.getTestClass();
Object[] instances = testClass.getInstances(true);
for(Object instance: instances) {
invokeBeforeGroupsConfigurations(testClass, testMethod, groupMethods, suite, parameters, instance);
}
long maxTimeOut= -1; // 10 seconds
for(IWorker<ITestNGMethod> tmw : workers) {
long mt= tmw.getTimeOut();
if(mt > maxTimeOut) {
maxTimeOut= mt;
}
}
ThreadUtil.execute(workers, threadPoolSize, maxTimeOut, true);
// Collect all the TestResults
List<ITestResult> result = Lists.newArrayList();
for (IWorker<ITestNGMethod> tmw : workers) {
if (tmw instanceof TestMethodWorker) {
result.addAll(((TestMethodWorker)tmw).getTestResults());
}
}
for(Object instance: instances) {
invokeAfterGroupsConfigurations(testClass, testMethod, groupMethods, suite, parameters, instance);
}
return result;
}
/**
* Checks to see of the test method has certain dependencies that prevents
* TestNG from executing it
* @param testMethod test method being checked for
* @param testClass
* @return dependencies have been run successfully
*/
private boolean checkDependencies(ITestNGMethod testMethod,
ITestNGMethod[] allTestMethods)
{
boolean result = true;
// If this method is marked alwaysRun, no need to check for its dependencies
if (testMethod.isAlwaysRun()) {
return true;
}
// Any missing group?
if (testMethod.getMissingGroup() != null
&& !testMethod.ignoreMissingDependencies()) {
return false;
}
// If this method depends on groups, collect all the methods that
// belong to these groups and make sure they have been run successfully
if (dependsOnGroups(testMethod)) {
String[] groupsDependedUpon = testMethod.getGroupsDependedUpon();
// Get all the methods that belong to the group depended upon
for (String element : groupsDependedUpon) {
ITestNGMethod[] methods =
MethodGroupsHelper.findMethodsThatBelongToGroup(testMethod,
m_testContext.getAllTestMethods(),
element);
result = result && haveBeenRunSuccessfully(testMethod, methods);
}
} // depends on groups
// If this method depends on other methods, make sure all these other
// methods have been run successfully
if (result && dependsOnMethods(testMethod)) {
ITestNGMethod[] methods =
MethodHelper.findDependedUponMethods(testMethod, allTestMethods);
result = result && haveBeenRunSuccessfully(testMethod, methods);
}
return result;
}
/**
* @return the test results that apply to one of the instances of the testMethod.
*/
private Set<ITestResult> keepSameInstances(ITestNGMethod method, Set<ITestResult> results) {
Set<ITestResult> result = Sets.newHashSet();
for (ITestResult r : results) {
for (Object o : method.getInstances()) {
// Keep this instance if 1) It's on a different class or 2) It's on the same class
// and on the same instance
Object instance = r.getInstance() != null
? r.getInstance() : r.getMethod().getInstances()[0];
if (r.getTestClass() != method.getTestClass() || instance == o) result.add(r);
}
}
return result;
}
/**
* @return true if all the methods have been run successfully
*/
private boolean haveBeenRunSuccessfully(ITestNGMethod testMethod, ITestNGMethod[] methods) {
// Make sure the method has been run successfully
for (ITestNGMethod method : methods) {
Set<ITestResult> results = keepSameInstances(testMethod, m_notifier.getPassedTests(method));
Set<ITestResult> failedAndSkippedMethods = Sets.newHashSet();
failedAndSkippedMethods.addAll(m_notifier.getFailedTests(method));
failedAndSkippedMethods.addAll(m_notifier.getSkippedTests(method));
Set<ITestResult> failedresults = keepSameInstances(testMethod, failedAndSkippedMethods);
// If failed results were returned on the same instance, then these tests didn't pass
if (failedresults != null && failedresults.size() > 0) {
return false;
}
for (ITestResult result : results) {
if(!result.isSuccess()) {
return false;
}
}
}
return true;
}
// private boolean containsInstance(Set<ITestResult> failedresults, Object[] instances) {
// for (ITestResult tr : failedresults) {
// for (Object o : instances) {
// if (o == tr.getInstance()) {
// return true;
// return false;
/**
* An exception was thrown by the test, determine if this method
* should be marked as a failure or as failure_but_within_successPercentage
*/
private void handleException(Throwable throwable,
ITestNGMethod testMethod,
ITestResult testResult,
int failureCount) {
testResult.setThrowable(throwable);
int successPercentage= testMethod.getSuccessPercentage();
int invocationCount= testMethod.getInvocationCount();
float numberOfTestsThatCanFail= ((100 - successPercentage) * invocationCount) / 100f;
if(failureCount < numberOfTestsThatCanFail) {
testResult.setStatus(ITestResult.SUCCESS_PERCENTAGE_FAILURE);
}
else {
testResult.setStatus(ITestResult.FAILURE);
}
}
/**
* @param ite The exception that was just thrown
* @param expectedExceptions The list of expected exceptions for this
* test method
* @return true if the exception that was just thrown is part of the
* expected exceptions
*/
private boolean isExpectedException(Throwable ite, ExpectedExceptionsHolder exceptionHolder) {
if (exceptionHolder == null) {
return false;
}
// TestException is the wrapper exception that TestNG will be throwing when an exception was
// expected but not thrown
if (ite.getClass() == TestException.class) {
return false;
}
Class<?>[] exceptions = exceptionHolder.expectedClasses;
Class<?> realExceptionClass= ite.getClass();
for (Class<?> exception : exceptions) {
if (exception.isAssignableFrom(realExceptionClass)) {
return true;
}
}
return false;
}
static interface Predicate<K, T> {
boolean isTrue(K k, T v);
}
static class CanRunFromClassPredicate implements Predicate <ITestNGMethod, IClass> {
@Override
public boolean isTrue(ITestNGMethod m, IClass v) {
return m.canRunFromClass(v);
}
}
static class SameClassNamePredicate implements Predicate<ITestNGMethod, IClass> {
@Override
public boolean isTrue(ITestNGMethod m, IClass c) {
return c == null || m.getTestClass().getName().equals(c.getName());
}
}
/**
* @return Only the ITestNGMethods applicable for this testClass
*/
private ITestNGMethod[] filterMethods(IClass testClass, ITestNGMethod[] methods,
Predicate<ITestNGMethod, IClass> predicate) {
List<ITestNGMethod> vResult= Lists.newArrayList();
for(ITestNGMethod tm : methods) {
if (predicate.isTrue(tm, testClass)) {
log(10, "Keeping method " + tm + " for class " + testClass);
vResult.add(tm);
} else {
log(10, "Filtering out method " + tm + " for class " + testClass);
}
}
ITestNGMethod[] result= vResult.toArray(new ITestNGMethod[vResult.size()]);
return result;
}
/**
* @return true if this method depends on certain groups.
*/
private boolean dependsOnGroups(ITestNGMethod tm) {
String[] groups = tm.getGroupsDependedUpon();
boolean result = (null != groups) && (groups.length > 0);
return result;
}
/**
* @return true if this method depends on certain groups.
*/
private boolean dependsOnMethods(ITestNGMethod tm) {
String[] methods = tm.getMethodsDependedUpon();
boolean result = (null != methods) && (methods.length > 0);
return result;
}
private void runConfigurationListeners(ITestResult tr, boolean before) {
if (before) {
for(IConfigurationListener icl: m_notifier.getConfigurationListeners()) {
if (icl instanceof IConfigurationListener2) {
((IConfigurationListener2) icl).beforeConfiguration(tr);
}
}
} else {
for(IConfigurationListener icl: m_notifier.getConfigurationListeners()) {
switch(tr.getStatus()) {
case ITestResult.SKIP:
icl.onConfigurationSkip(tr);
break;
case ITestResult.FAILURE:
icl.onConfigurationFailure(tr);
break;
case ITestResult.SUCCESS:
icl.onConfigurationSuccess(tr);
break;
}
}
}
}
void runTestListeners(ITestResult tr) {
runTestListeners(tr, m_notifier.getTestListeners());
}
// TODO: move this from here as it is directly called from TestNG
public static void runTestListeners(ITestResult tr, List<ITestListener> listeners) {
for (ITestListener itl : listeners) {
switch(tr.getStatus()) {
case ITestResult.SKIP: {
itl.onTestSkipped(tr);
break;
}
case ITestResult.SUCCESS_PERCENTAGE_FAILURE: {
itl.onTestFailedButWithinSuccessPercentage(tr);
break;
}
case ITestResult.FAILURE: {
itl.onTestFailure(tr);
break;
}
case ITestResult.SUCCESS: {
itl.onTestSuccess(tr);
break;
}
case ITestResult.STARTED: {
itl.onTestStart(tr);
break;
}
default: {
assert false : "UNKNOWN STATUS:" + tr;
}
}
}
}
private void log(int level, String s) {
Utils.log("Invoker " + Thread.currentThread().hashCode(), level, s);
}
/**
* This class holds a {@code ParameterHolder} and in case of an error, a non-null
* {@code TestResult} containing the cause
*/
private static class ParameterBag {
final ParameterHolder parameterHolder;
final List<ITestResult> errorResults = Lists.newArrayList();
public ParameterBag(ParameterHolder params, TestResult tr) {
parameterHolder = params;
if (tr != null) {
errorResults.add(tr);
}
}
public boolean hasErrors() {
return !errorResults.isEmpty();
}
}
}
|
package org.pentaho.di.job.entries.deletefiles;
import java.io.IOException;
import java.util.List;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSelectInfo;
import org.apache.commons.vfs.FileSelector;
import org.apache.commons.vfs.FileType;
import org.eclipse.swt.widgets.Shell;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entry.JobEntryBase;
import org.pentaho.di.job.entry.JobEntryDialogInterface;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.w3c.dom.Node;
/**
* This defines a 'delete files' job entry.
*
* @author Samatar Hassan
* @since 06-05-2007
*/
public class JobEntryDeleteFiles extends JobEntryBase implements Cloneable, JobEntryInterface {
private boolean ignoreErrors;
public boolean argFromPrevious;
public boolean deleteFolder;
public boolean includeSubfolders;
public String arguments[];
public String filemasks[];
public JobEntryDeleteFiles(String n) {
super(n, "");
ignoreErrors = false;
argFromPrevious = false;
arguments = null;
deleteFolder = false;
includeSubfolders = false;
setID(-1L);
setType(JobEntryInterface.TYPE_JOBENTRY_DELETE_FILES);
}
public JobEntryDeleteFiles() {
this("");
}
public JobEntryDeleteFiles(JobEntryBase jeb) {
super(jeb);
}
public Object clone() {
JobEntryDeleteFiles je = (JobEntryDeleteFiles) super.clone();
return je;
}
public String getXML() {
StringBuffer retval = new StringBuffer(300);
retval.append(super.getXML());
retval.append(" ").append(XMLHandler.addTagValue("ignore_errors", ignoreErrors));
retval.append(" ").append(XMLHandler.addTagValue("arg_from_previous", argFromPrevious));
retval.append(" ").append(XMLHandler.addTagValue("delete_folder", deleteFolder));
retval.append(" ").append(XMLHandler.addTagValue("include_subfolders", includeSubfolders));
retval.append(" <fields>").append(Const.CR);
if (arguments != null) {
for (int i = 0; i < arguments.length; i++) {
retval.append(" <field>").append(Const.CR);
retval.append(" ").append(XMLHandler.addTagValue("name", arguments[i]));
retval.append(" ").append(XMLHandler.addTagValue("filemask", filemasks[i]));
retval.append(" </field>").append(Const.CR);
}
}
retval.append(" </fields>").append(Const.CR);
return retval.toString();
}
public void loadXML(Node entrynode, List<DatabaseMeta> databases, Repository rep) throws KettleXMLException {
try {
super.loadXML(entrynode, databases);
ignoreErrors = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "ignore_errors"));
argFromPrevious = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "arg_from_previous"));
deleteFolder = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "delete_folder"));
includeSubfolders = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "include_subfolders"));
Node fields = XMLHandler.getSubNode(entrynode, "fields");
// How many field arguments?
int nrFields = XMLHandler.countNodes(fields, "field");
arguments = new String[nrFields];
filemasks = new String[nrFields];
// Read them all...
for (int i = 0; i < nrFields; i++) {
Node fnode = XMLHandler.getSubNodeByNr(fields, "field", i);
arguments[i] = XMLHandler.getTagValue(fnode, "name");
filemasks[i] = XMLHandler.getTagValue(fnode, "filemask");
}
} catch (KettleXMLException xe) {
throw new KettleXMLException("Unable to load job entry of type 'delete files' from XML node", xe);
}
}
public void loadRep(Repository rep, long id_jobentry, List<DatabaseMeta> databases) throws KettleException {
try {
super.loadRep(rep, id_jobentry, databases);
ignoreErrors = rep.getJobEntryAttributeBoolean(id_jobentry, "ignore_errors");
argFromPrevious = rep.getJobEntryAttributeBoolean(id_jobentry, "arg_from_previous");
deleteFolder = rep.getJobEntryAttributeBoolean(id_jobentry, "delete_folder");
includeSubfolders = rep.getJobEntryAttributeBoolean(id_jobentry, "include_subfolders");
// How many arguments?
int argnr = rep.countNrJobEntryAttributes(id_jobentry, "name");
arguments = new String[argnr];
filemasks = new String[argnr];
// Read them all...
for (int a = 0; a < argnr; a++) {
arguments[a] = rep.getJobEntryAttributeString(id_jobentry, a, "name");
filemasks[a] = rep.getJobEntryAttributeString(id_jobentry, a, "filemask");
}
} catch (KettleException dbe) {
throw new KettleException("Unable to load job entry of type 'delete files' from the repository for id_jobentry="
+ id_jobentry, dbe);
}
}
public void saveRep(Repository rep, long id_job) throws KettleException {
try {
super.saveRep(rep, id_job);
rep.saveJobEntryAttribute(id_job, getID(), "ignore_errors", ignoreErrors);
rep.saveJobEntryAttribute(id_job, getID(), "arg_from_previous", argFromPrevious);
rep.saveJobEntryAttribute(id_job, getID(), "delete_folder", deleteFolder);
rep.saveJobEntryAttribute(id_job, getID(), "include_subfolders", includeSubfolders);
// save the arguments...
if (arguments != null) {
for (int i = 0; i < arguments.length; i++) {
rep.saveJobEntryAttribute(id_job, getID(), i, "name", arguments[i]);
rep.saveJobEntryAttribute(id_job, getID(), i, "filemask", filemasks[i]);
}
}
} catch (KettleDatabaseException dbe) {
throw new KettleException("Unable to save job entry of type 'delete files' to the repository for id_job="
+ id_job, dbe);
}
}
public Result execute(Result result, int nr, Repository rep, Job parentJob) throws KettleException {
LogWriter log = LogWriter.getInstance();
List<RowMetaAndData> rows = result.getRows();
RowMetaAndData resultRow = null;
boolean rcode = true;
String args[] = arguments;
String fmasks[] = filemasks;
result.setResult(true);
rcode = true;
if (argFromPrevious) {
log.logDetailed(toString(), "Found " + (rows != null ? rows.size() : 0) + " previous result rows");
}
if (argFromPrevious && rows != null) // Copy the input row to the (command line) arguments
{
for (int iteration = 0; iteration < rows.size(); iteration++) {
resultRow = (RowMetaAndData) rows.get(iteration);
args = new String[resultRow.size()];
fmasks = new String[resultRow.size()];
args[iteration] = resultRow.getString(0, null);
fmasks[iteration] = resultRow.getString(1, null);
if (rcode) {
// ok we can process this file/folder
log.logDetailed(toString(), "Processing row [" + args[iteration] + "]..wildcard [" + fmasks[iteration]
+ "] ?");
if (!ProcessFile(args[iteration], fmasks[iteration])) {
rcode = false;
}
} else {
log.logDetailed(toString(), "Ignoring row [" + args[iteration] + "]..wildcard [" + fmasks[iteration] + "] ?");
}
}
} else if (arguments != null) {
for (int i = 0; i < arguments.length; i++) {
if (rcode) {
// ok we can process this file/folder
log.logDetailed(toString(), "Processing argument [" + arguments[i] + "].. wildcard [" + filemasks[i] + "] ?");
if (!ProcessFile(arguments[i], filemasks[i])) {
rcode = false;
}
} else {
log.logDetailed(toString(), "Ignoring argument [" + arguments[i] + "].. wildcard [" + filemasks[i] + "] ?");
}
}
}
if (!rcode && ignoreErrors) {
result.setResult(false);
result.setNrErrors(1);
}
result.setResult(rcode);
return result;
}
private boolean ProcessFile(String filename, String wildcard) {
LogWriter log = LogWriter.getInstance();
boolean rcode = false;
FileObject filefolder = null;
String realFilefoldername = environmentSubstitute(filename);
String realwilcard = environmentSubstitute(wildcard);
try {
filefolder = KettleVFS.getFileObject(realFilefoldername);
// Here gc() is explicitly called if e.g. createfile is used in the same
// job for the same file. The problem is that after creating the file the
// file object is not properly garbaged collected and thus the file cannot
// be deleted anymore. This is a known problem in the JVM.
System.gc();
if (filefolder.exists()) {
// the file or folder exists
if (filefolder.getType() == FileType.FOLDER) {
// It's a folder
if (log.isDetailed())
log.logDetailed(toString(), "Processing folder [" + realFilefoldername + "]");
// Delete Files
int Nr = filefolder.delete(new TextFileSelector(realwilcard));
if (log.isDetailed())
log.logDetailed(toString(), "Total deleted subfolders/files = " + Nr);
rcode = true;
} else {
// It's a file
log.logDetailed(toString(), "Processing file [" + realFilefoldername + "]");
boolean deleted = filefolder.delete();
if (!deleted) {
log.logError(toString(), "Could not delete file [" + realFilefoldername + "].");
} else {
log.logBasic(toString(), "File [" + filename + "] deleted!");
rcode = true;
}
}
} else {
// File already deleted, no reason to try to delete it
log.logBasic(toString(), "File or folder [" + realFilefoldername + "] already deleted.");
rcode = true;
}
} catch (IOException e) {
log.logError(toString(), "Could not process [" + realFilefoldername + "], exception: " + e.getMessage());
} finally {
if (filefolder != null) {
try {
filefolder.close();
} catch (IOException ex) {
}
;
}
}
return rcode;
}
private class TextFileSelector implements FileSelector {
LogWriter log = LogWriter.getInstance();
String fileExtension;
public TextFileSelector(String extension) {
if (!Const.isEmpty(extension)) {
fileExtension = extension.replace('.', ' ').replace('*', ' ').replace('$', ' ').trim();
}
}
public boolean includeFile(FileSelectInfo info) {
boolean rcode = false;
try {
String extension = info.getFile().getName().getExtension();
if (extension.equals(fileExtension) || Const.isEmpty(fileExtension)) {
if (info.getFile().getType() == FileType.FOLDER) {
if (deleteFolder && includeSubfolders) {
rcode = true;
} else {
rcode = false;
}
} else {
rcode = true;
}
} else {
rcode = false;
}
} catch (Exception e) {
log.logError(toString(), "Error exception: " + e.getMessage());
}
return rcode;
}
public boolean traverseDescendents(FileSelectInfo info) {
return includeSubfolders;
}
}
public JobEntryDialogInterface getDialog(Shell shell, JobEntryInterface jei, JobMeta jobMeta, String jobName,
Repository rep) {
return new JobEntryDeleteFilesDialog(shell, this, jobMeta);
}
public boolean isIgnoreErrors() {
return ignoreErrors;
}
public void setIgnoreErrors(boolean ignoreErrors) {
this.ignoreErrors = ignoreErrors;
}
public void setDeleteFolder(boolean deleteFolder) {
this.deleteFolder = deleteFolder;
}
public void setIncludeSubfolders(boolean includeSubfolders) {
this.includeSubfolders = includeSubfolders;
}
public boolean evaluates() {
return true;
}
}
|
package se.sics.cooja;
import java.util.Vector;
import se.sics.cooja.interfaces.Radio;
/**
* A radio connection represents a connection between a source radio and zero or
* more destination and interfered radios. Typically the destinations are able
* to receive data sent by the source radio, and the interfered radios are not.
*
* @see RadioMedium
* @author Fredrik Osterlind
*/
public class RadioConnection {
private static int ID = 0; /* Unique radio connection ID. For internal use */
private int id;
private Radio source;
private Vector<Radio> destinations = new Vector<Radio>();
private Vector<Long> destinationDelays = new Vector<Long>();
private Vector<Radio> interfered = new Vector<Radio>();
private long startTime;
/**
* Creates a new radio connection with given source and no destinations.
*
* @param sourceRadio
* Source radio
*/
public RadioConnection(Radio sourceRadio) {
this.source = sourceRadio;
startTime = sourceRadio.getMote().getSimulation().getSimulationTime();
this.id = ID++;
}
public long getStartTime() {
return startTime;
}
/**
* Set source of this connection.
*
* @param radio
* Source radio
*/
public void setSource(Radio radio) {
source = radio;
}
/**
* Adds destination radio.
*
* @param radio
* Radio
*/
public void addDestination(Radio radio) {
destinations.add(radio);
destinationDelays.add(new Long(0));
}
public void addDestination(Radio radio, Long delay) {
destinations.add(radio);
destinationDelays.add(delay);
}
public Long getDestinationDelay(Radio radio) {
int idx = destinations.indexOf(radio);
return destinationDelays.get(idx);
}
/**
* Adds interfered radio.
*
* @param radio
* Radio
*/
public void addInterfered(Radio radio) {
interfered.add(radio);
}
/**
* Removes destination radio.
*
* @param radio
* Radio
*/
public void removeDestination(Radio radio) {
int idx = destinations.indexOf(radio);
if (idx < 0) {
return;
}
destinations.remove(idx);
destinationDelays.remove(idx);
}
/**
* Removes interfered radio.
*
* @param radio
* Radio
*/
public void removeInterfered(Radio radio) {
interfered.remove(radio);
}
/**
* @return Source radio
*/
public Radio getSource() {
return source;
}
/**
* @return All destinations of this connection
*/
public Radio[] getDestinations() {
Radio[] arr = new Radio[destinations.size()];
destinations.toArray(arr);
return arr;
}
/**
* @return All radios interfered by this connection
*/
public Radio[] getInterfered() {
Radio[] arr = new Radio[interfered.size()];
interfered.toArray(arr);
return arr;
}
public String toString() {
if (destinations.size() == 0) {
return id + ": Radio connection: " + source.getMote() + " -> none";
}
if (destinations.size() == 1) {
return id + ": Radio connection: " + source.getMote() + " -> " + destinations.get(0).getMote();
}
return id + ": Radio connection: " + source.getMote() + " -> " + destinations.size() + " motes";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.