code
stringlengths
3
1.18M
language
stringclasses
1 value
package com.anli.busstation.dal.ejb2.entities.vehicles; import com.anli.busstation.dal.ejb2.entities.BSEntityImpl; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.entities.vehicles.GasLabel; import java.math.BigDecimal; public class GasLabelImpl extends BSEntityImpl implements GasLabel { protected String name; protected BigDecimal price; @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public BigDecimal getPrice() { return price; } @Override public void setPrice(BigDecimal price) { this.price = price; } @Override public boolean deepEquals(BSEntity comparee) { if (!this.equals(comparee)) { return false; } GasLabelImpl glComparee = (GasLabelImpl) comparee; return nullableEquals(this.name, glComparee.name) && nullableEquals(this.price, glComparee.price); } @Override public String toString() { return super.toString() + " name = " + name + " price = " + price; } }
Java
package com.anli.busstation.dal.ejb2.entities.vehicles; import com.anli.busstation.dal.ejb2.entities.BSEntityImpl; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.entities.vehicles.GasLabel; import com.anli.busstation.dal.interfaces.entities.vehicles.Model; import java.math.BigDecimal; public class ModelImpl extends BSEntityImpl implements Model { protected String name; protected Integer seatsNumber; protected Integer tankVolume; protected GasLabelImpl gasLabel; protected BigDecimal gasRate; @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public Integer getSeatsNumber() { return seatsNumber; } @Override public void setSeatsNumber(Integer seatsNumber) { this.seatsNumber = seatsNumber; } @Override public Integer getTankVolume() { return tankVolume; } @Override public void setTankVolume(Integer tankVolume) { this.tankVolume = tankVolume; } @Override public GasLabel getGasLabel() { return gasLabel; } @Override public void setGasLabel(GasLabel gasLabel) { this.gasLabel = (GasLabelImpl) gasLabel; } @Override public BigDecimal getGasRate() { return gasRate; } @Override public void setGasRate(BigDecimal gasRate) { this.gasRate = gasRate; } @Override public boolean deepEquals(BSEntity comparee) { if (!this.equals(comparee)) { return false; } ModelImpl modelComparee = (ModelImpl) comparee; return nullableEquals(this.name, modelComparee.name) && nullableEquals(this.seatsNumber, modelComparee.seatsNumber) && nullableEquals(this.tankVolume, modelComparee.tankVolume) && nullableEquals(this.gasRate, modelComparee.gasRate) && nullableDeepEquals(this.gasLabel, modelComparee.gasLabel); } @Override public String toString() { return super.toString() + " name = " + name + " seatsNumber = " + seatsNumber + " tankVolume = " + tankVolume + " gasRate = " + gasRate + " gasLabel = {" + gasLabel + "}"; } }
Java
package com.anli.busstation.dal.interfaces.factories; import com.anli.busstation.dal.interfaces.providers.BSEntityProvider; public interface ProviderFactory { <I extends BSEntityProvider> I getProvider(Class<I> abstraction); }
Java
package com.anli.busstation.dal.interfaces.providers.maintenance; import com.anli.busstation.dal.interfaces.entities.staff.Mechanic; import com.anli.busstation.dal.interfaces.entities.maintenance.TechnicalAssignment; import com.anli.busstation.dal.interfaces.providers.BSEntityProvider; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.List; import org.joda.time.DateTime; public interface GenericTechnicalAssignmentProvider<I extends TechnicalAssignment> extends BSEntityProvider<I> { List<I> findByMechanic(Mechanic mechanic); List<I> findByAnyMechanic(Collection<Mechanic> mechanics); List<I> findByBeginTimeRange(DateTime beginTimeLeft, boolean strictLeft, DateTime beginTimeRight, boolean strictRight); List<I> findByEndTimeRange(DateTime endTimeLeft, boolean strictLeft, DateTime endTimeRight, boolean strictRight); List<I> findByServiceCostRange(BigDecimal serviceCostLeft, boolean strictLeft, BigDecimal serviceCostRight, boolean strictRight); List<BigInteger> collectIdsByMechanic(Mechanic mechanic); List<BigInteger> collectIdsByAnyMechanic(Collection<Mechanic> mechanics); List<BigInteger> collectIdsByBeginTimeRange(DateTime beginTimeLeft, boolean strictLeft, DateTime beginTimeRight, boolean strictRight); List<BigInteger> collectIdsByEndTimeRange(DateTime endTimeLeft, boolean strictLeft, DateTime endTimeRight, boolean strictRight); List<BigInteger> collectIdsByServiceCostRange(BigDecimal serviceCostLeft, boolean strictLeft, BigDecimal serviceCostRight, boolean strictRight); }
Java
package com.anli.busstation.dal.interfaces.providers.maintenance; import com.anli.busstation.dal.interfaces.entities.vehicles.Bus; import com.anli.busstation.dal.interfaces.entities.maintenance.BusService; import java.math.BigInteger; import java.util.Collection; import java.util.List; public interface GenericBusServiceProvider<I extends BusService> extends GenericTechnicalAssignmentProvider<I> { List<I> findByBus(Bus bus); List<I> findByAnyBus(Collection<Bus> buses); List<BigInteger> collectIdsByBus(Bus bus); List<BigInteger> collectIdsByAnyBus(Collection<Bus> buses); }
Java
package com.anli.busstation.dal.interfaces.providers.maintenance; import com.anli.busstation.dal.interfaces.entities.maintenance.BusRepairment; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; public interface BusRepairmentProvider extends GenericBusServiceProvider<BusRepairment> { List<BusRepairment> findByExpendablesPriceRange(BigDecimal expendablesPriceLeft, boolean strictLeft, BigDecimal expendablesPriceRight, boolean strictRight); List<BigInteger> collectIdsByExpendablesPriceRange(BigDecimal expendablesPriceLeft, boolean strictLeft, BigDecimal expendablesPriceRight, boolean strictRight); }
Java
package com.anli.busstation.dal.interfaces.providers.maintenance; import com.anli.busstation.dal.interfaces.entities.maintenance.StationService; import java.math.BigInteger; import java.util.List; public interface StationServiceProvider extends GenericTechnicalAssignmentProvider<StationService> { List<StationService> findByDescriptionRegexp(String descriptionRegexp); List<BigInteger> collectIdsByDescriptionRegexp(String descriptionRegexp); }
Java
package com.anli.busstation.dal.interfaces.providers.maintenance; import com.anli.busstation.dal.interfaces.entities.maintenance.BusService; public interface BusServiceProvider extends GenericBusServiceProvider<BusService> { }
Java
package com.anli.busstation.dal.interfaces.providers.maintenance; import com.anli.busstation.dal.interfaces.entities.maintenance.TechnicalAssignment; public interface TechnicalAssignmentProvider extends GenericTechnicalAssignmentProvider<TechnicalAssignment> { }
Java
package com.anli.busstation.dal.interfaces.providers.maintenance; import com.anli.busstation.dal.interfaces.entities.maintenance.BusRefuelling; import java.math.BigInteger; import java.util.List; public interface BusRefuellingProvider extends GenericBusServiceProvider<BusRefuelling> { List<BusRefuelling> findByVolumeRange(Integer volumeLeft, boolean strictLeft, Integer volumeRight, boolean strictRight); List<BigInteger> collectIdsByVolumeRange(Integer volumeLeft, boolean strictLeft, Integer volumeRight, boolean strictRight); }
Java
package com.anli.busstation.dal.interfaces.providers.traffic; import com.anli.busstation.dal.interfaces.entities.vehicles.Bus; import com.anli.busstation.dal.interfaces.entities.traffic.Ride; import com.anli.busstation.dal.interfaces.entities.traffic.RidePoint; import com.anli.busstation.dal.interfaces.entities.traffic.RideRoad; import com.anli.busstation.dal.interfaces.entities.traffic.Ticket; import com.anli.busstation.dal.interfaces.providers.BSEntityProvider; import java.math.BigInteger; import java.util.Collection; import java.util.List; public interface RideProvider extends BSEntityProvider<Ride> { Ride pullRidePoints(Ride ride); Ride pullRideRoads(Ride ride); Ride pullTickets(Ride ride); List<Ride> findByBus(Bus bus); List<Ride> findByAnyBus(Collection<Bus> buses); List<Ride> findByRidePoint(RidePoint ridePoint); List<Ride> findByAnyRidePoint(Collection<RidePoint> ridePoints); List<Ride> findByRideRoad(RideRoad rideRoad); List<Ride> findByAnyRideRoad(Collection<RideRoad> rideRoads); List<Ride> findByTicket(Ticket ticket); List<Ride> findByAnyTicket(Collection<Ticket> tickets); List<BigInteger> collectIdsByBus(Bus bus); List<BigInteger> collectIdsByAnyBus(Collection<Bus> buses); List<BigInteger> collectIdsByRidePoint(RidePoint ridePoint); List<BigInteger> collectIdsByAnyRidePoint(Collection<RidePoint> ridePoints); List<BigInteger> collectIdsByRideRoad(RideRoad rideRoad); List<BigInteger> collectIdsByAnyRideRoad(Collection<RideRoad> rideRoads); List<BigInteger> collectIdsByTicket(Ticket ticket); List<BigInteger> collectIdsByAnyTicket(Collection<Ticket> tickets); }
Java
package com.anli.busstation.dal.interfaces.providers.traffic; import com.anli.busstation.dal.interfaces.entities.staff.Driver; import com.anli.busstation.dal.interfaces.entities.traffic.RideRoad; import com.anli.busstation.dal.interfaces.entities.geography.Road; import com.anli.busstation.dal.interfaces.providers.BSEntityProvider; import java.math.BigInteger; import java.util.Collection; import java.util.List; public interface RideRoadProvider extends BSEntityProvider<RideRoad> { List<RideRoad> findByRoad(Road road); List<RideRoad> findByAnyRoad(Collection<Road> roads); List<RideRoad> findByDriver(Driver driver); List<RideRoad> findByAnyDriver(Collection<Driver> drivers); List<BigInteger> collectIdsByRoad(Road road); List<BigInteger> collectIdsByAnyRoad(Collection<Road> roads); List<BigInteger> collectIdsByDriver(Driver driver); List<BigInteger> collectIdsByAnyDriver(Collection<Driver> drivers); }
Java
package com.anli.busstation.dal.interfaces.providers.traffic; import com.anli.busstation.dal.interfaces.entities.traffic.RoutePoint; import com.anli.busstation.dal.interfaces.entities.geography.Station; import com.anli.busstation.dal.interfaces.providers.BSEntityProvider; import java.math.BigInteger; import java.util.Collection; import java.util.List; public interface RoutePointProvider extends BSEntityProvider<RoutePoint> { List<RoutePoint> findByStation(Station station); List<RoutePoint> findByAnyStation(Collection<Station> stations); List<BigInteger> collectIdsByStation(Station station); List<BigInteger> collectIdsByAnyStation(Collection<Station> stations); }
Java
package com.anli.busstation.dal.interfaces.providers.traffic; import com.anli.busstation.dal.interfaces.entities.traffic.RidePoint; import com.anli.busstation.dal.interfaces.entities.traffic.RoutePoint; import com.anli.busstation.dal.interfaces.providers.BSEntityProvider; import java.math.BigInteger; import java.util.Collection; import java.util.List; import org.joda.time.DateTime; public interface RidePointProvider extends BSEntityProvider<RidePoint> { List<RidePoint> findByRoutePoint(RoutePoint routePoint); List<RidePoint> findByAnyRoutePoint(Collection<RoutePoint> routePoints); List<RidePoint> findByArrivalTimeRange(DateTime arrivalTimeLeft, boolean strictLeft, DateTime arrivalTimeRight, boolean strictRight); List<RidePoint> findByDepartureTimeRange(DateTime departureTimeLeft, boolean strictLeft, DateTime departureTimeRight, boolean strictRight); List<BigInteger> collectIdsByRoutePoint(RoutePoint routePoint); List<BigInteger> collectIdsByAnyRoutePoint(Collection<RoutePoint> routePoints); List<BigInteger> collectIdsByArrivalTimeRange(DateTime arrivalTimeLeft, boolean strictLeft, DateTime arrivalTimeRight, boolean strictRight); List<BigInteger> collectIdsByDepartureTimeRange(DateTime departureTimeLeft, boolean strictLeft, DateTime departureTimeRight, boolean strictRight); }
Java
package com.anli.busstation.dal.interfaces.providers.traffic; import com.anli.busstation.dal.interfaces.entities.traffic.Ride; import com.anli.busstation.dal.interfaces.entities.traffic.Route; import com.anli.busstation.dal.interfaces.entities.traffic.RoutePoint; import com.anli.busstation.dal.interfaces.providers.BSEntityProvider; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.List; public interface RouteProvider extends BSEntityProvider<Route> { Route pullRoutePoints(Route route); Route pullRides(Route route); List<Route> findByNumCode(String numCode); List<Route> findByAnyNumCode(Collection<String> numCodes); List<Route> findByTicketPriceRange(BigDecimal ticketPriceLeft, boolean strictLeft, BigDecimal ticketPriceRight, boolean strictRight); List<Route> findByRoutePoint(RoutePoint routePoint); List<Route> findByAnyRoutePoint(Collection<RoutePoint> routePoints); List<Route> findByRide(Ride ride); List<Route> findByAnyRide(Collection<Ride> rides); List<BigInteger> collectIdsByNumCode(String numCode); List<BigInteger> collectIdsByAnyNumCode(Collection<String> numCodes); List<BigInteger> collectIdsByTicketPriceRange(BigDecimal ticketPriceLeft, boolean strictLeft, BigDecimal ticketPriceRight, boolean strictRight); List<BigInteger> collectIdsByRoutePoint(RoutePoint routePoint); List<BigInteger> collectIdsByAnyRoutePoint(Collection<RoutePoint> routePoints); List<BigInteger> collectIdsByRide(Ride ride); List<BigInteger> collectIdsByAnyRide(Collection<Ride> rides); }
Java
package com.anli.busstation.dal.interfaces.providers.traffic; import com.anli.busstation.dal.interfaces.entities.traffic.RidePoint; import com.anli.busstation.dal.interfaces.entities.staff.Salesman; import com.anli.busstation.dal.interfaces.entities.traffic.Ticket; import com.anli.busstation.dal.interfaces.providers.BSEntityProvider; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.List; import org.joda.time.DateTime; public interface TicketProvider extends BSEntityProvider<Ticket> { List<Ticket> findByDeparturePoint(RidePoint departurePoint); List<Ticket> findByAnyDeparturePoint(Collection<RidePoint> departurePoints); List<Ticket> findByArrivalPoint(RidePoint arrivalPoint); List<Ticket> findByAnyArrivalPoint(Collection<RidePoint> arrivalPoints); List<Ticket> findBySeat(Integer seat); List<Ticket> findBySeatRange(Integer seatLeft, boolean strictLeft, Integer seatRight, boolean strictRight); List<Ticket> findBySalesman(Salesman salesman); List<Ticket> findByAnySalesman(Collection<Salesman> salesmen); List<Ticket> findBySaleDateRange(DateTime saleDateLeft, boolean strictLeft, DateTime saleDateRight, boolean strictRight); List<Ticket> findByCustomerName(String customerName); List<Ticket> findByCustomerNameRegexp(String customerNameRegexp); List<Ticket> findByPriceRange(BigDecimal priceLeft, boolean strictLeft, BigDecimal priceRight, boolean strictRight); List<Ticket> findBySold(boolean sold); List<BigInteger> collectIdsByDeparturePoint(RidePoint departurePoint); List<BigInteger> collectIdsByAnyDeparturePoint(Collection<RidePoint> departurePoints); List<BigInteger> collectIdsByArrivalPoint(RidePoint arrivalPoint); List<BigInteger> collectIdsByAnyArrivalPoint(Collection<RidePoint> arrivalPoints); List<BigInteger> collectIdsBySeat(Integer seat); List<BigInteger> collectIdsBySeatRange(Integer seatLeft, boolean strictLeft, Integer seatRight, boolean strictRight); List<BigInteger> collectIdsBySalesman(Salesman salesman); List<BigInteger> collectIdsByAnySalesman(Collection<Salesman> salesmen); List<BigInteger> collectIdsBySaleDateRange(DateTime saleDateLeft, boolean strictLeft, DateTime saleDateRight, boolean strictRight); List<BigInteger> collectIdsByCustomerName(String customerName); List<BigInteger> collectIdsByCustomerNameRegexp(String customerNameRegexp); List<BigInteger> collectIdsByPriceRange(BigDecimal priceLeft, boolean strictLeft, BigDecimal priceRight, boolean strictRight); List<BigInteger> collectIdsBySold(boolean sold); }
Java
package com.anli.busstation.dal.interfaces.providers.geography; import com.anli.busstation.dal.interfaces.entities.geography.Road; import com.anli.busstation.dal.interfaces.entities.geography.Station; import com.anli.busstation.dal.interfaces.providers.BSEntityProvider; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.List; public interface RoadProvider extends BSEntityProvider<Road> { List<Road> findByAStation(Station aStation); List<Road> findByAnyAStation(Collection<Station> aStations); List<Road> findByZStation(Station zStation); List<Road> findByAnyZStation(Collection<Station> zStations); List<Road> findByStation(Station station); List<Road> findByAnyStation(Collection<Station> stations); List<Road> findByLengthRange(Integer lengthLeft, boolean strictLeft, Integer lengthRight, boolean strictRight); List<Road> findByRidePriceRange(BigDecimal ridePriceLeft, boolean strictLeft, BigDecimal ridePriceRight, boolean strictRight); List<BigInteger> collectIdsByAStation(Station aStation); List<BigInteger> collectIdsByAnyAStation(Collection<Station> aStations); List<BigInteger> collectIdsByZStation(Station zStation); List<BigInteger> collectIdsByAnyZStation(Collection<Station> zStations); List<BigInteger> collectIdsByStation(Station station); List<BigInteger> collectIdsByAnyStation(Collection<Station> stations); List<BigInteger> collectIdsByLengthRange(Integer lengthLeft, boolean strictLeft, Integer lengthRight, boolean strictRight); List<BigInteger> collectIdsByRidePriceRange(BigDecimal ridePriceLeft, boolean strictLeft, BigDecimal ridePriceRight, boolean strictRight); }
Java
package com.anli.busstation.dal.interfaces.providers.geography; import com.anli.busstation.dal.interfaces.entities.geography.Region; import com.anli.busstation.dal.interfaces.entities.geography.Station; import com.anli.busstation.dal.interfaces.providers.BSEntityProvider; import java.math.BigInteger; import java.util.Collection; import java.util.List; public interface RegionProvider extends BSEntityProvider<Region> { Region pullStations(Region region); List<Region> findByName(String name); List<Region> findByNameRegexp(String nameRegexp); List<Region> findByCode(Integer code); List<Region> findByAnyCode(Collection<Integer> codes); List<Region> findByStation(Station station); List<Region> findByAnyStation(Collection<Station> stations); List<BigInteger> collectIdsByName(String name); List<BigInteger> collectIdsByNameRegexp(String nameRegexp); List<BigInteger> collectIdsByCode(Integer code); List<BigInteger> collectIdsByAnyCode(Collection<Integer> codes); List<BigInteger> collectIdsByStation(Station station); List<BigInteger> collectIdsByAnyStation(Collection<Station> stations); }
Java
package com.anli.busstation.dal.interfaces.providers.geography; import com.anli.busstation.dal.interfaces.entities.vehicles.Bus; import com.anli.busstation.dal.interfaces.entities.staff.Employee; import com.anli.busstation.dal.interfaces.entities.geography.Station; import com.anli.busstation.dal.interfaces.providers.BSEntityProvider; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.List; public interface StationProvider extends BSEntityProvider<Station> { Station pullEmployees(Station station); Station pullBuses(Station station); List<Station> findByName(String name); List<Station> findByNameRegexp(String regexpName); List<Station> findByLatitudeRange(BigDecimal latitudeLeft, boolean strictLeft, BigDecimal latitudeRight, boolean strictRight); List<Station> findByLongitudeRange(BigDecimal longitudeLeft, boolean strictLeft, BigDecimal longitudeRight, boolean strictRight); List<Station> findByEmployee(Employee employee); List<Station> findByAnyEmployee(Collection<Employee> employees); List<Station> findByBus(Bus bus); List<Station> findByAnyBus(Collection<Bus> buses); List<BigInteger> collectIdsByName(String name); List<BigInteger> collectIdsByNameRegexp(String regexpName); List<BigInteger> collectIdsByLatitudeRange(BigDecimal latitudeLeft, boolean strictLeft, BigDecimal latitudeRight, boolean strictRight); List<BigInteger> collectIdsByLongitudeRange(BigDecimal longitudeLeft, boolean strictLeft, BigDecimal longitudeRight, boolean strictRight); List<BigInteger> collectIdsByEmployee(Employee employee); List<BigInteger> collectIdsByAnyEmployee(Collection<Employee> employees); List<BigInteger> collectIdsByBus(Bus bus); List<BigInteger> collectIdsByAnyBus(Collection<Bus> buses); }
Java
package com.anli.busstation.dal.interfaces.providers; import com.anli.busstation.dal.interfaces.entities.BSEntity; import java.math.BigInteger; import java.util.List; public interface BSEntityProvider<I extends BSEntity> { I create(); I save(I entity); void remove(I entity); I findById(BigInteger id); List<I> findAll(); List<BigInteger> collectIdsAll(); }
Java
package com.anli.busstation.dal.interfaces.providers.staff; import com.anli.busstation.dal.interfaces.entities.staff.Employee; public interface EmployeeProvider extends GenericEmployeeProvider<Employee> { }
Java
package com.anli.busstation.dal.interfaces.providers.staff; import com.anli.busstation.dal.interfaces.entities.staff.Mechanic; import com.anli.busstation.dal.interfaces.entities.staff.MechanicSkill; import java.math.BigInteger; import java.util.Collection; import java.util.List; public interface MechanicProvider extends GenericEmployeeProvider<Mechanic> { List<Mechanic> findBySkill(MechanicSkill skill); List<Mechanic> findByAnySkill(Collection<MechanicSkill> skills); List<BigInteger> collectIdsBySkill(MechanicSkill skill); List<BigInteger> collectIdsByAnySkill(Collection<MechanicSkill> skills); }
Java
package com.anli.busstation.dal.interfaces.providers.staff; import com.anli.busstation.dal.interfaces.entities.staff.Salesman; import java.math.BigInteger; import java.util.List; public interface SalesmanProvider extends GenericEmployeeProvider<Salesman> { List<Salesman> findByTotalSalesRange(Integer totalSalesLeft, boolean strictLeft, Integer totalSalesRight, boolean strictRight); List<BigInteger> collectIdsByTotalSalesRange(Integer totalSalesLeft, boolean strictLeft, Integer totalSalesRight, boolean strictRight); }
Java
package com.anli.busstation.dal.interfaces.providers.staff; import com.anli.busstation.dal.interfaces.entities.staff.Driver; import com.anli.busstation.dal.interfaces.entities.staff.DriverSkill; import java.math.BigInteger; import java.util.Collection; import java.util.List; public interface DriverProvider extends GenericEmployeeProvider<Driver> { List<Driver> findBySkill(DriverSkill skill); List<Driver> findByAnySkill(Collection<DriverSkill> skills); List<BigInteger> collectIdsBySkill(DriverSkill skill); List<BigInteger> collectIdsByAnySkill(Collection<DriverSkill> skills); }
Java
package com.anli.busstation.dal.interfaces.providers.staff; import com.anli.busstation.dal.interfaces.entities.staff.Employee; import com.anli.busstation.dal.interfaces.providers.BSEntityProvider; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import org.joda.time.DateTime; public interface GenericEmployeeProvider<I extends Employee> extends BSEntityProvider<I> { List<I> findByName(String name); List<I> findByNameRegexp(String nameRegexp); List<I> findBySalaryRange(BigDecimal salaryLeft, boolean strictLeft, BigDecimal salaryRight, boolean strictRight); List<I> findByHiringDateRange(DateTime hiringDateLeft, boolean strictLeft, DateTime hiringDateRight, boolean strictRight); List<BigInteger> collectIdsByName(String name); List<BigInteger> collectIdsByNameRegexp(String nameRegexp); List<BigInteger> collectIdsBySalaryRange(BigDecimal salaryLeft, boolean strictLeft, BigDecimal salaryRight, boolean strictRight); List<BigInteger> collectIdsByHiringDateRange(DateTime hiringDateLeft, boolean strictLeft, DateTime hiringDateRight, boolean strictRight); }
Java
package com.anli.busstation.dal.interfaces.providers.staff; import com.anli.busstation.dal.interfaces.entities.staff.DriverSkill; import com.anli.busstation.dal.interfaces.providers.BSEntityProvider; import java.math.BigInteger; import java.util.List; public interface DriverSkillProvider extends BSEntityProvider<DriverSkill> { List<DriverSkill> findByName(String name); List<DriverSkill> findByNameRegexp(String nameRegexp); List<DriverSkill> findByMaxRideLengthRange(Integer maxRideLengthLeft, boolean strictLeft, Integer maxRideLengthRight, boolean strictRight); List<DriverSkill> findByMaxPassengersRange(Integer maxPassengersLeft, boolean strictLeft, Integer maxPassengersRight, boolean strictRight); List<BigInteger> collectIdsByName(String name); List<BigInteger> collectIdsByNameRegexp(String nameRegexp); List<BigInteger> collectIdsByMaxRideLengthRange(Integer maxRideLengthLeft, boolean strictLeft, Integer maxRideLengthRight, boolean strictRight); List<BigInteger> collectIdsByMaxPassengersRange(Integer maxPassengersLeft, boolean strictLeft, Integer maxPassengersRight, boolean strictRight); }
Java
package com.anli.busstation.dal.interfaces.providers.staff; import com.anli.busstation.dal.interfaces.entities.staff.MechanicSkill; import com.anli.busstation.dal.interfaces.providers.BSEntityProvider; import java.math.BigInteger; import java.util.List; public interface MechanicSkillProvider extends BSEntityProvider<MechanicSkill> { List<MechanicSkill> findByName(String name); List<MechanicSkill> findByNameRegexp(String nameRegexp); List<MechanicSkill> findByMaxDiffLevelRange(Integer maxDiffLevelLeft, boolean strictLeft, Integer maxDiffLevelRight, boolean strictRight); List<BigInteger> collectIdsByName(String name); List<BigInteger> collectIdsByNameRegexp(String nameRegexp); List<BigInteger> collectIdsByMaxDiffLevelRange(Integer maxDiffLevelLeft, boolean strictLeft, Integer maxDiffLevelRight, boolean strictRight); }
Java
package com.anli.busstation.dal.interfaces.providers.vehicles; import com.anli.busstation.dal.interfaces.entities.vehicles.GasLabel; import com.anli.busstation.dal.interfaces.providers.BSEntityProvider; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; public interface GasLabelProvider extends BSEntityProvider<GasLabel> { List<GasLabel> findByName(String name); List<GasLabel> findByNameRegexp(String nameRegexp); List<GasLabel> findByPriceRange(BigDecimal priceLeft, boolean strictLeft, BigDecimal priceRight, boolean strictRight); List<BigInteger> collectIdsByName(String name); List<BigInteger> collectIdsByNameRegexp(String nameRegexp); List<BigInteger> collectIdsByPriceRange(BigDecimal priceLeft, boolean strictLeft, BigDecimal priceRight, boolean strictRight); }
Java
package com.anli.busstation.dal.interfaces.providers.vehicles; import com.anli.busstation.dal.interfaces.entities.vehicles.GasLabel; import com.anli.busstation.dal.interfaces.entities.vehicles.Model; import com.anli.busstation.dal.interfaces.providers.BSEntityProvider; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collection; import java.util.List; public interface ModelProvider extends BSEntityProvider<Model> { List<Model> findByName(String name); List<Model> findByNameRegexp(String nameRegexp); List<Model> findBySeatsNumberRange(Integer seatsNumberLeft, boolean strictLeft, Integer seatsNumberRight, boolean strictRight); List<Model> findByTankVolumeRange(Integer tankVolumeLeft, boolean strictLeft, Integer tankVolumeRight, boolean strictRight); List<Model> findByGasLabel(GasLabel gasLabel); List<Model> findByAnyGasLabel(Collection<GasLabel> gasLabels); List<Model> findByGasRateRange(BigDecimal gasRateLeft, boolean strictLeft, BigDecimal gasRateRight, boolean strictRight); List<BigInteger> collectIdsByName(String name); List<BigInteger> collectIdsByNameRegexp(String nameRegexp); List<BigInteger> collectIdsBySeatsNumberRange(Integer seatsNumberLeft, boolean strictLeft, Integer seatsNumberRight, boolean strictRight); List<BigInteger> collectIdsByGasLabel(GasLabel gasLabel); List<BigInteger> collectIdsByAnyGasLabel(Collection<GasLabel> gasLabels); List<BigInteger> collectIdsByGasRateRange(BigDecimal gasRateLeft, boolean strictLeft, BigDecimal gasRateRight, boolean strictRight); List<BigInteger> collectIdsByTankVolumeRange(Integer tankVolumeLeft, boolean strictLeft, Integer tankVolumeRight, boolean strictRight); }
Java
package com.anli.busstation.dal.interfaces.providers.vehicles; import com.anli.busstation.dal.interfaces.entities.vehicles.TechnicalState; import com.anli.busstation.dal.interfaces.providers.BSEntityProvider; import java.math.BigInteger; import java.util.List; public interface TechnicalStateProvider extends BSEntityProvider<TechnicalState> { List<TechnicalState> findByDescriptionRegexp(String descriptionRegexp); List<TechnicalState> findByDifficultyLevel(Integer difficultyLevel); List<TechnicalState> findByDifficultyLevelRange(Integer difficultyLevelLeft, boolean strictLeft, Integer difficultyLevelRight, boolean strictRight); List<BigInteger> collectIdsByDescriptionRegexp(String descriptionRegexp); List<BigInteger> collectIdsByDifficultyLevel(Integer difficultyLevel); List<BigInteger> collectIdsByDifficultyLevelRange(Integer difficultyLevelLeft, boolean strictLeft, Integer difficultyLevelRight, boolean strictRight); }
Java
package com.anli.busstation.dal.interfaces.providers.vehicles; import com.anli.busstation.dal.interfaces.entities.vehicles.Bus; import com.anli.busstation.dal.interfaces.entities.vehicles.Model; import com.anli.busstation.dal.interfaces.entities.vehicles.TechnicalState; import com.anli.busstation.dal.interfaces.providers.BSEntityProvider; import java.math.BigInteger; import java.util.Collection; import java.util.List; public interface BusProvider extends BSEntityProvider<Bus> { List<Bus> findByModel(Model model); List<Bus> findByAnyModel(Collection<Model> models); List<Bus> findByState(TechnicalState state); List<Bus> findByAnyState(Collection<TechnicalState> states); List<Bus> findByPlate(String plate); List<BigInteger> collectIdsByModel(Model model); List<BigInteger> collectIdsByAnyModel(Collection<Model> models); List<BigInteger> collectIdsByState(TechnicalState state); List<BigInteger> collectIdsByAnyState(Collection<TechnicalState> states); List<BigInteger> collectIdsByPlate(String plate); }
Java
package com.anli.busstation.dal.interfaces.entities; import java.io.Serializable; import java.math.BigInteger; public interface BSEntity extends Serializable { BigInteger getId(); @Deprecated boolean deepEquals(BSEntity comparee); }
Java
package com.anli.busstation.dal.interfaces.entities.maintenance; import com.anli.busstation.dal.interfaces.entities.vehicles.Bus; public interface BusService extends TechnicalAssignment { Bus getBus(); void setBus(Bus bus); }
Java
package com.anli.busstation.dal.interfaces.entities.maintenance; import java.math.BigDecimal; public interface BusRepairment extends BusService { BigDecimal getExpendablesPrice(); void setExpendablesPrice(BigDecimal expendablesPrice); }
Java
package com.anli.busstation.dal.interfaces.entities.maintenance; public interface BusRefuelling extends BusService { Integer getVolume(); void setVolume(Integer volume); }
Java
package com.anli.busstation.dal.interfaces.entities.maintenance; public interface StationService extends TechnicalAssignment { String getDescription(); void setDescription(String description); }
Java
package com.anli.busstation.dal.interfaces.entities.maintenance; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.entities.staff.Mechanic; import java.math.BigDecimal; import org.joda.time.DateTime; public interface TechnicalAssignment extends BSEntity { Mechanic getMechanic(); void setMechanic(Mechanic mechanic); DateTime getBeginTime(); void setBeginTime(DateTime beginTime); DateTime getEndTime(); void setEndTime(DateTime endTime); BigDecimal getServiceCost(); void setServiceCost(BigDecimal serviceCost); }
Java
package com.anli.busstation.dal.interfaces.entities.traffic; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.entities.staff.Salesman; import java.math.BigDecimal; import org.joda.time.DateTime; public interface Ticket extends BSEntity { RidePoint getDeparturePoint(); void setDeparturePoint(RidePoint departurePoint); RidePoint getArrivalPoint(); void setArrivalPoint(RidePoint arrivalPoint); Integer getSeat(); void setSeat(Integer seat); Salesman getSalesman(); void setSalesman(Salesman salesman); DateTime getSaleDate(); void setSaleDate(DateTime saleDate); String getCustomerName(); void setCustomerName(String customerName); BigDecimal getPrice(); void setPrice(BigDecimal price); boolean isSold(); void setSold(boolean sold); }
Java
package com.anli.busstation.dal.interfaces.entities.traffic; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.entities.staff.Driver; import com.anli.busstation.dal.interfaces.entities.geography.Road; public interface RideRoad extends BSEntity { Road getRoad(); void setRoad(Road road); Driver getDriver(); void setDriver(Driver driver); }
Java
package com.anli.busstation.dal.interfaces.entities.traffic; import com.anli.busstation.dal.interfaces.entities.BSEntity; import org.joda.time.DateTime; public interface RidePoint extends BSEntity { RoutePoint getRoutePoint(); void setRoutePoint(RoutePoint routePoint); DateTime getArrivalTime(); void setArrivalTime(DateTime arrivalTime); DateTime getDepartureTime(); void setDepartureTime(DateTime departureTime); }
Java
package com.anli.busstation.dal.interfaces.entities.traffic; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.entities.geography.Station; public interface RoutePoint extends BSEntity { Station getStation(); void setStation(Station station); }
Java
package com.anli.busstation.dal.interfaces.entities.traffic; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.entities.vehicles.Bus; import java.util.List; public interface Ride extends BSEntity { Bus getBus(); void setBus(Bus bus); List<RidePoint> getRidePoints(); List<RideRoad> getRideRoads(); List<Ticket> getTickets(); }
Java
package com.anli.busstation.dal.interfaces.entities.traffic; import com.anli.busstation.dal.interfaces.entities.BSEntity; import java.math.BigDecimal; import java.util.List; public interface Route extends BSEntity { String getNumCode(); void setNumCode(String numCode); BigDecimal getTicketPrice(); void setTicketPrice(BigDecimal ticketPrice); List<RoutePoint> getRoutePoints(); List<Ride> getRides(); }
Java
package com.anli.busstation.dal.interfaces.entities.geography; import com.anli.busstation.dal.interfaces.entities.BSEntity; import java.math.BigDecimal; public interface Road extends BSEntity { Station getAStation(); void setAStation(Station aStation); Station getZStation(); void setZStation(Station zStation); Integer getLength(); void setLength(Integer length); BigDecimal getRidePrice(); void setRidePrice(BigDecimal ridePrice); }
Java
package com.anli.busstation.dal.interfaces.entities.geography; import com.anli.busstation.dal.interfaces.entities.BSEntity; import java.util.List; public interface Region extends BSEntity { String getName(); void setName(String name); Integer getCode(); void setCode(Integer code); List<Station> getStations(); }
Java
package com.anli.busstation.dal.interfaces.entities.geography; import com.anli.busstation.dal.interfaces.entities.BSEntity; import com.anli.busstation.dal.interfaces.entities.vehicles.Bus; import com.anli.busstation.dal.interfaces.entities.staff.Employee; import java.math.BigDecimal; import java.util.List; public interface Station extends BSEntity { String getName(); void setName(String name); BigDecimal getLatitude(); void setLatitude(BigDecimal latitude); BigDecimal getLongitude(); void setLongitude(BigDecimal longitude); List<Employee> getEmployees(); List<Bus> getBuses(); }
Java
package com.anli.busstation.dal.interfaces.entities.staff; import com.anli.busstation.dal.interfaces.entities.BSEntity; public interface MechanicSkill extends BSEntity { String getName(); void setName(String name); Integer getMaxDiffLevel(); void setMaxDiffLevel(Integer maxDiffLevel); }
Java
package com.anli.busstation.dal.interfaces.entities.staff; public interface Mechanic extends Employee { MechanicSkill getSkill(); void setSkill(MechanicSkill skill); }
Java
package com.anli.busstation.dal.interfaces.entities.staff; import com.anli.busstation.dal.interfaces.entities.BSEntity; import java.math.BigDecimal; import org.joda.time.DateTime; public interface Employee extends BSEntity { String getName(); void setName(String name); BigDecimal getSalary(); void setSalary(BigDecimal salary); DateTime getHiringDate(); void setHiringDate(DateTime hiringDate); }
Java
package com.anli.busstation.dal.interfaces.entities.staff; public interface Salesman extends Employee { Integer getTotalSales(); void setTotalSales(Integer totalSales); }
Java
package com.anli.busstation.dal.interfaces.entities.staff; public interface Driver extends Employee { DriverSkill getSkill(); void setSkill(DriverSkill skill); }
Java
package com.anli.busstation.dal.interfaces.entities.staff; import com.anli.busstation.dal.interfaces.entities.BSEntity; public interface DriverSkill extends BSEntity { String getName(); void setName(String name); Integer getMaxRideLength(); void setMaxRideLength(Integer maxRideLength); Integer getMaxPassengers(); void setMaxPassengers(Integer maxPassengers); }
Java
package com.anli.busstation.dal.interfaces.entities.vehicles; import com.anli.busstation.dal.interfaces.entities.BSEntity; public interface Bus extends BSEntity { Model getModel(); void setModel(Model model); TechnicalState getState(); void setState(TechnicalState state); String getPlate(); void setPlate(String plate); }
Java
package com.anli.busstation.dal.interfaces.entities.vehicles; import com.anli.busstation.dal.interfaces.entities.BSEntity; public interface TechnicalState extends BSEntity { String getDescription(); void setDescription(String description); Integer getDifficultyLevel(); void setDifficultyLevel(Integer difficultyLevel); }
Java
package com.anli.busstation.dal.interfaces.entities.vehicles; import com.anli.busstation.dal.interfaces.entities.BSEntity; import java.math.BigDecimal; public interface GasLabel extends BSEntity { String getName(); void setName(String name); BigDecimal getPrice(); void setPrice(BigDecimal price); }
Java
package com.anli.busstation.dal.interfaces.entities.vehicles; import com.anli.busstation.dal.interfaces.entities.BSEntity; import java.math.BigDecimal; public interface Model extends BSEntity { String getName(); void setName(String name); Integer getSeatsNumber(); void setSeatsNumber(Integer seatsNumber); Integer getTankVolume(); void setTankVolume(Integer tankVolume); GasLabel getGasLabel(); void setGasLabel(GasLabel gasLabel); BigDecimal getGasRate(); void setGasRate(BigDecimal gasRate); }
Java
package com.anli.busstation.dal.exceptions; import com.anli.busstation.dal.interfaces.entities.BSEntity; import java.util.Collection; public class ConsistencyException extends RuntimeException { protected Collection<BSEntity> inconsistentEntities; public ConsistencyException(Collection<BSEntity> inconsistentEntities, Throwable cause) { super(cause); this.inconsistentEntities = inconsistentEntities; } public Collection<BSEntity> getEntities() { return inconsistentEntities; } }
Java
package com.anli.simpleorm.exceptions; import java.util.List; public class NonExistentEntitiesException extends RuntimeException { protected final List entities; public NonExistentEntitiesException(List entities) { super(); this.entities = entities; } public List getEntities() { return entities; } }
Java
package com.anli.simpleorm.handling; import java.util.Collection; public interface EntityGateway<Entity> { EntityBuilder<Entity> getBuilder(String entityName); Object extractSingle(Entity entity, String entityName, String fieldName); Object extractFullReference(Entity entity, String entityName, String fieldName); Collection extractCollectionKeys(Entity entity, String entityName, String fieldName); Collection extractFullCollection(Entity entity, String entityName, String fieldName); Collection extractCollectionByKeys(Entity entity, String entityName, String fieldName, Collection keys); void setCollectionField(Entity entity, String entityName, String fieldName, Collection value); }
Java
package com.anli.simpleorm.handling; public interface EntityBuilder<Entity> { EntityBuilder startBuilding(); EntityBuilder setSingle(String entityName, String fieldName, Object fieldValue); Entity build(); }
Java
package com.anli.simpleorm.handling; import com.anli.simpleorm.definitions.CollectionDefinition; import com.anli.simpleorm.definitions.EntityDefinition; import com.anli.simpleorm.definitions.FieldDefinition; import com.anli.simpleorm.definitions.ReferenceDefinition; import com.anli.simpleorm.exceptions.NonExistentEntitiesException; import com.anli.simpleorm.queries.CharacterFieldQueryCache; import com.anli.simpleorm.queries.CollectionFieldQueryCache; import com.anli.simpleorm.queries.ComparableFieldQueryCache; import com.anli.simpleorm.queries.EntityQueryCache; import com.anli.simpleorm.queries.FieldQueryCache; import com.anli.simpleorm.queries.MySqlQueryBuilder; import com.anli.simpleorm.queries.SingleFieldQueryCache; import com.anli.sqlexecution.execution.SqlExecutor; import com.anli.sqlexecution.handling.ResultSetHandler; import com.anli.sqlexecution.handling.TransformingResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; public class EntityHandler<Entity> { protected final EntityDefinition definition; protected final EntityQueryCache queryCache; protected final EntityGateway<Entity> gateway; protected final EntityHandlerFactory handlerFactory; protected final SqlExecutor executor; protected final EntitySelector selector; protected final KeyCollector keyCollector; public EntityHandler(EntityDefinition definition, MySqlQueryBuilder queryBuilder, EntityGateway<Entity> gateway, EntityHandlerFactory handlerFactory, SqlExecutor executor) { this.definition = definition; this.queryCache = new EntityQueryCache(definition, queryBuilder); this.gateway = gateway; this.executor = executor; this.handlerFactory = handlerFactory; this.selector = new EntitySelector(); this.keyCollector = new KeyCollector(); } public Entity insertEntity(Object primaryKey) { EntityBuilder<Entity> builder = gateway.getBuilder(definition.getName()).startBuilding(); List<String> insertQueries = queryCache.getInsertQueries(); ListIterator<String> queryIterator = insertQueries.listIterator(insertQueries.size()); insertSingle(definition, builder, queryIterator, primaryKey); return builder.build(); } public Entity selectEntity(Object primaryKey) { String selectQuery = queryCache.getSelectQuery(); List<Entity> found = executor.executeSelect(selectQuery, Arrays.asList(primaryKey), selector); return found.isEmpty() ? null : found.iterator().next(); } public boolean isKeyPresent(Object primaryKey) { return !collectKeysByEqualsOrContains(definition.getPrimaryKey().getName(), primaryKey).isEmpty(); } protected List selectKeysByKeyList(Collection keys) { return collectKeysByAny(definition.getPrimaryKey().getName(), new ArrayList(keys)); } public List<Entity> selectAllEntities() { String selectQuery = queryCache.getSelectAllQuery(); return executor.executeSelect(selectQuery, Collections.emptyList(), selector); } public List collectAllKeys() { String collectQuery = queryCache.getSelectAllKeysQuery(); return executor.executeSelect(collectQuery, Collections.emptyList(), keyCollector); } public List<Entity> selectEntitiesByEqualsOrContains(String field, Object value) { FieldQueryCache cache = queryCache.getFieldQueryCache(field); String selectQuery; List parameters; if (value != null) { selectQuery = cache.getSelectFullByEqualsOrContainsQuery(); parameters = Arrays.asList(getParameter(definition.getFieldEntity(field) .getField(field), value)); } else if (cache instanceof CollectionFieldQueryCache) { return Collections.emptyList(); } else { selectQuery = ((SingleFieldQueryCache) cache).getSelectFullByIsNullQuery(); parameters = Collections.emptyList(); } return executor.executeSelect(selectQuery, parameters, selector); } public List collectKeysByEqualsOrContains(String field, Object value) { FieldQueryCache cache = queryCache.getFieldQueryCache(field); String collectQuery; List parameters; if (value != null) { collectQuery = cache.getSelectKeysByEqualsOrContainsQuery(); parameters = Arrays.asList(getParameter(definition.getFieldEntity(field) .getField(field), value)); } else if (cache instanceof CollectionFieldQueryCache) { return Collections.emptyList(); } else { collectQuery = ((SingleFieldQueryCache) cache).getSelectKeysByIsNullQuery(); parameters = Collections.emptyList(); } return executor.executeSelect(collectQuery, parameters, keyCollector); } public List<Entity> selectEntitiesByAny(String field, Collection values) { if (values == null || values.isEmpty()) { return Collections.emptyList(); } String selectQuery = queryCache.getFieldQueryCache(field) .getSelectFullByAnyQuery(values.size()); return executor.executeSelect(selectQuery, getParameterList(definition.getFieldEntity(field).getField(field), values), selector); } public List collectKeysByAny(String field, Collection values) { if (values == null || values.isEmpty()) { return Collections.emptyList(); } String collectQuery = queryCache.getFieldQueryCache(field) .getSelectKeysByAnyQuery(values.size()); return executor.executeSelect(collectQuery, getParameterList(definition.getFieldEntity(field).getField(field), values), keyCollector); } public List<Entity> selectEntitiesByRegexp(String field, String regexp) { String selectQuery = ((CharacterFieldQueryCache) queryCache.getFieldQueryCache(field)) .getSelectFullByRegexpQuery(); return executor.executeSelect(selectQuery, Arrays.asList(regexp), selector); } public List collectKeysByRegexp(String field, String regexp) { String collectQuery = ((CharacterFieldQueryCache) queryCache.getFieldQueryCache(field)) .getSelectKeysByRegexpQuery(); return executor.executeSelect(collectQuery, Arrays.asList(regexp), keyCollector); } public List<Entity> selectEntitiesByRange(String field, Object left, boolean leftStrict, Object right, boolean rightStrict) { if (left == null && right == null) { return selectAllEntities(); } String selectQuery; List params; ComparableFieldQueryCache cache = (ComparableFieldQueryCache) queryCache.getFieldQueryCache(field); if (left != null && right != null) { selectQuery = cache.getSelectFullByClosedRangeQuery(leftStrict, rightStrict); params = Arrays.asList(left, right); } else { boolean isLeft = (left != null); boolean strict = isLeft ? leftStrict : rightStrict; selectQuery = cache.getSelectFullByOpenRangeQuery(isLeft, strict); params = Arrays.asList(isLeft ? left : right); } return executor.executeSelect(selectQuery, params, selector); } public List collectKeysByRange(String field, Object left, boolean leftStrict, Object right, boolean rightStrict) { if (left == null && right == null) { return collectAllKeys(); } String collectQuery; List params; ComparableFieldQueryCache cache = (ComparableFieldQueryCache) queryCache.getFieldQueryCache(field); if (left != null && right != null) { collectQuery = cache.getSelectKeysByClosedRangeQuery(leftStrict, rightStrict); params = Arrays.asList(left, right); } else { boolean isLeft = (left != null); boolean strict = isLeft ? leftStrict : rightStrict; collectQuery = cache.getSelectKeysByOpenRangeQuery(isLeft, strict); params = Arrays.asList(isLeft ? left : right); } return executor.executeSelect(collectQuery, params, keyCollector); } public List<Entity> selectEntitiesByNamedQuery(String queryName, Collection parameters) { List transformedParameters = new LinkedList(); List<Integer> sizes = new LinkedList<>(); if (parameters != null) { for (Object parameter : parameters) { if (parameter instanceof Collection) { Collection collectionParam = (Collection) parameter; transformedParameters.addAll(collectionParam); sizes.add(collectionParam.size()); } else { transformedParameters.add(parameter); } } } String selectQuery = sizes.isEmpty() ? queryCache.getSelectNamedQuery(queryName) : queryCache.getSelectNamedQuery(queryName, sizes); return executor.executeSelect(selectQuery, transformedParameters, selector); } public List collectKeysByNamedQuery(String queryName, Collection parameters) { List transformedParameters = new LinkedList(); List<Integer> sizes = new LinkedList<>(); if (parameters != null) { for (Object parameter : parameters) { if (parameter instanceof Collection) { Collection collectionParam = (Collection) parameter; transformedParameters.addAll(collectionParam); sizes.add(collectionParam.size()); } else { transformedParameters.add(parameter); } } } String collectQuery = sizes.isEmpty() ? queryCache.getSelectKeysNamedQuery(queryName) : queryCache.getSelectKeysNamedQuery(queryName, sizes); return executor.executeSelect(collectQuery, transformedParameters, keyCollector); } public void pullCollection(Entity entity, String field) { checkEntityConsistency(entity); String selectCollectionQuery = ((CollectionFieldQueryCache) queryCache .getFieldQueryCache(field)) .getSelectCollectionQuery(); String entityName = definition.getName(); Object primaryKey = getPrimaryKey(entity); String collectionEntityName = definition.getFieldEntity(field).getCollectionField(field) .getReferencedEntity().getName(); EntityHandler collectionHandler = handlerFactory.getHandler(collectionEntityName); List collection = (List) executor.executeSelect(selectCollectionQuery, Arrays.asList(primaryKey), collectionHandler.selector); gateway.setCollectionField(entity, entityName, field, collection); } public void updateEntity(Entity entity) { checkConsistency(entity); String updateSinglesQuery = queryCache.getUpdateQuery(); List updateSinglesParameters = new LinkedList(); addUpdateParameters(definition, updateSinglesParameters, entity, true, true); updateSinglesParameters.add(getPrimaryKey(entity)); executor.executeUpdate(updateSinglesQuery, updateSinglesParameters); updateAllCollectionLinks(definition, entity, true, true); } public void deleteEntity(Entity entity) { checkEntityConsistency(entity); String deleteQuery = queryCache.getDeleteQuery(); Object primaryKey = getPrimaryKey(entity); executor.executeUpdate(deleteQuery, Arrays.asList(primaryKey)); } protected void insertSingle(EntityDefinition currentDefinition, EntityBuilder<Entity> builder, ListIterator<String> queryIter, Object primaryKey) { String query = queryIter.previous(); EntityDefinition parentDefinition = currentDefinition.getParentEntity(); if (parentDefinition != null) { insertSingle(parentDefinition, builder, queryIter, primaryKey); } builder.setSingle(currentDefinition.getName(), currentDefinition.getPrimaryKey().getName(), primaryKey); executor.executeUpdate(query, Arrays.asList(primaryKey)); } protected void addUpdateParameters(EntityDefinition currentDefinition, List parameters, Entity entity, boolean withChildren, boolean withParent) { EntityDefinition parentDefinition = currentDefinition.getParentEntity(); if (parentDefinition != null && withParent) { addUpdateParameters(parentDefinition, parameters, entity, false, true); } String entityName = currentDefinition.getName(); for (FieldDefinition field : currentDefinition.getSingleFields()) { Object value = gateway.extractSingle(entity, entityName, field.getName()); parameters.add(value); } if (!withChildren) { return; } for (EntityDefinition childDefinition : currentDefinition.getChildrenEntities()) { addUpdateParameters(childDefinition, parameters, entity, true, false); } } protected void updateAllCollectionLinks(EntityDefinition entityDefinition, Entity entity, boolean withChildren, boolean withParent) { EntityDefinition parentDefinition = entityDefinition.getParentEntity(); if (parentDefinition != null && withParent) { updateAllCollectionLinks(parentDefinition, entity, false, true); } for (CollectionDefinition field : entityDefinition.getCollectionFields()) { updateCollectionLink(entityDefinition, entity, field.getName()); } if (!withChildren) { return; } for (EntityDefinition childDefinition : entityDefinition.getChildrenEntities()) { updateAllCollectionLinks(childDefinition, entity, true, false); } } protected void updateCollectionLink(EntityDefinition entityDefinition, Entity entity, String fieldName) { String entityName = entityDefinition.getName(); Collection collectionKeys = gateway.extractCollectionKeys(entity, entityName, fieldName); Object primaryKey = getPrimaryKey(entity); if (collectionKeys == null) { return; } CollectionFieldQueryCache fieldQueryCache = (CollectionFieldQueryCache) queryCache.getFieldQueryCache(fieldName); int size = collectionKeys.size(); int paramSize = size + 1; if (!collectionKeys.isEmpty()) { String linkQuery = fieldQueryCache.getLinkCollectionQuery(size); List linkParamList = new ArrayList(paramSize); linkParamList.addAll(collectionKeys); linkParamList.add(primaryKey); executor.executeUpdate(linkQuery, linkParamList); } String unlinkQuery = fieldQueryCache.getUnlinkCollectionQuery(size); List unlinkParamList = new ArrayList(paramSize); unlinkParamList.add(primaryKey); unlinkParamList.addAll(collectionKeys); executor.executeUpdate(unlinkQuery, unlinkParamList); } protected void checkConsistency(Entity entity) { checkEntityConsistency(entity); List inconsistentEntities = new LinkedList(); checkReferencesConsistency(inconsistentEntities, definition, entity, true, true); if (!inconsistentEntities.isEmpty()) { throw new NonExistentEntitiesException(inconsistentEntities); } } protected void checkEntityConsistency(Entity entity) { Object primaryKey = getPrimaryKey(entity); if (!isKeyPresent(primaryKey)) { throw new NonExistentEntitiesException(Arrays.asList(entity)); } } protected void checkReferencesConsistency(List inconsistent, EntityDefinition entityDefinition, Entity entity, boolean withChildren, boolean withParent) { EntityDefinition parentDefinition = entityDefinition.getParentEntity(); if (parentDefinition != null && withParent) { checkReferencesConsistency(inconsistent, parentDefinition, entity, false, true); } String entityName = entityDefinition.getName(); for (FieldDefinition field : entityDefinition.getSingleFields()) { if (field instanceof ReferenceDefinition) { checkReferenceConsistency((ReferenceDefinition) field, entity, entityName, inconsistent); } } for (CollectionDefinition field : entityDefinition.getCollectionFields()) { checkCollectionConsistency(field, entity, entityName, inconsistent); } if (!withChildren) { return; } for (EntityDefinition childDefinition : entityDefinition.getChildrenEntities()) { checkReferencesConsistency(inconsistent, childDefinition, entity, false, true); } } protected void checkReferenceConsistency(ReferenceDefinition field, Entity entity, String entityName, List inconsistent) { String referenceName = field.getReferencedEntity().getName(); String fieldName = field.getName(); Object key = gateway.extractSingle(entity, entityName, fieldName); if (key != null) { EntityHandler refHandler = handlerFactory.getHandler(referenceName); if (!refHandler.isKeyPresent(key)) { inconsistent.add(gateway.extractFullReference(entity, entityName, fieldName)); } } } protected void checkCollectionConsistency(CollectionDefinition field, Entity entity, String entityName, List inconsistent) { String collectionName = field.getReferencedEntity().getName(); String fieldName = field.getName(); Collection keys = gateway.extractCollectionKeys(entity, entityName, fieldName); if (keys != null) { Set inconsistentKeys = new HashSet(keys); EntityHandler collectionHandler = handlerFactory.getHandler(collectionName); inconsistentKeys.removeAll(collectionHandler.selectKeysByKeyList(keys)); inconsistent.addAll(gateway.extractCollectionByKeys(entity, entityName, fieldName, inconsistentKeys)); } } protected Object getPrimaryKey(Entity entity) { return gateway.extractSingle(entity, definition.getName(), definition.getPrimaryKey().getName()); } protected Object getParameter(FieldDefinition field, Object value) { if (field instanceof ReferenceDefinition) { return handlerFactory.getHandler(((ReferenceDefinition) field).getReferencedEntity() .getName()).getPrimaryKey(value); } return value; } protected List getParameterList(FieldDefinition field, Collection values) { if (field instanceof ReferenceDefinition) { EntityHandler handler = handlerFactory.getHandler(((ReferenceDefinition) field) .getReferencedEntity() .getName()); ArrayList keys = new ArrayList(values.size()); for (Object value : values) { keys.add(handler.getPrimaryKey(value)); } return keys; } return new ArrayList(values); } protected class EntitySelector implements ResultSetHandler<List<Entity>> { @Override public List<Entity> handle(TransformingResultSet resultSet) throws SQLException { List<Entity> entities = new LinkedList<>(); Map<String, Map> referencedEntities = new HashMap<>(); while (resultSet.next()) { entities.add(getEntity(resultSet, referencedEntities)); } return entities; } protected Entity getEntity(TransformingResultSet resultSet, Map<String, Map> referencedEntities) throws SQLException { String actualEntity = getActualEntityName(resultSet, definition, queryCache.getKeysIndices()); EntityBuilder<Entity> builder = gateway.getBuilder(actualEntity).startBuilding(); populateEntity(definition, resultSet, builder, referencedEntities, 0, true, true); return builder.build(); } protected String getActualEntityName(TransformingResultSet resultSet, EntityDefinition currentDefinition, Map<String, Integer> indices) throws SQLException { for (EntityDefinition child : currentDefinition.getChildrenEntities()) { String childName = getActualEntityName(resultSet, child, indices); if (childName != null) { return childName; } } String name = currentDefinition.getName(); int index = indices.get(name); Object key = resultSet.getValue(index, currentDefinition.getPrimaryKey().getJavaClass()); return key != null ? name : null; } protected int populateEntity(EntityDefinition entityDefinition, TransformingResultSet resultSet, EntityBuilder builder, Map<String, Map> referencedEntities, int lastIndex, boolean withChildren, boolean withParent) throws SQLException { EntityDefinition parentDefinition = entityDefinition.getParentEntity(); if (parentDefinition != null && withParent) { lastIndex = populateEntity(parentDefinition, resultSet, builder, referencedEntities, lastIndex, false, true); } String entityName = entityDefinition.getName(); for (FieldDefinition fieldDefinition : entityDefinition.getSingleFields()) { lastIndex++; Object value = resultSet.getValue(lastIndex, fieldDefinition.getJavaClass()); if (fieldDefinition instanceof ReferenceDefinition) { String referenceName = ((ReferenceDefinition) fieldDefinition).getReferencedEntity() .getName(); value = getReference(referencedEntities, referenceName, value); } builder.setSingle(entityName, fieldDefinition.getName(), value); } if (!withChildren) { return lastIndex; } for (EntityDefinition childDefinition : entityDefinition.getChildrenEntities()) { lastIndex = populateEntity(childDefinition, resultSet, builder, referencedEntities, lastIndex, true, false); } return lastIndex; } protected Object getReference(Map<String, Map> map, String entityName, Object key) { if (key == null) { return null; } Map entities = map.get(entityName); if (entities == null) { entities = new HashMap(); map.put(entityName, entities); } Object entity = entities.get(key); if (entity == null) { entity = pullReference(entityName, key); } return entity; } protected Object pullReference(String entityName, Object key) { EntityHandler handler = handlerFactory.getHandler(entityName); return handler.selectEntity(key); } } protected class KeyCollector implements ResultSetHandler<List> { @Override public List handle(TransformingResultSet resultSet) throws SQLException { Class keyClass = definition.getPrimaryKey().getJavaClass(); List keys = new LinkedList(); while (resultSet.next()) { keys.add(resultSet.getValue(1, keyClass)); } return keys; } } }
Java
package com.anli.simpleorm.handling; public interface EntityHandlerFactory { public <Entity> EntityHandler<Entity> getHandler(String entityName); }
Java
package com.anli.simpleorm.handling; import java.util.Collection; import java.util.Map; public class SuperEntityGateway<Entity> implements EntityGateway<Entity> { protected final Map<Class<? extends Entity>, EntityGateway<? extends Entity>> mapping; public SuperEntityGateway (Map<Class<? extends Entity>, EntityGateway<? extends Entity>> mapping) { this.mapping = mapping; } @Override public EntityBuilder<Entity> getBuilder(String entityName) { EntityBuilder<Entity> builder = null; for (EntityGateway<? extends Entity> subGateway : mapping.values()) { builder = (EntityBuilder) subGateway.getBuilder(entityName); if (builder != null) { break; } } return builder; } @Override public Object extractSingle(Entity entity, String entityName, String fieldName) { return getConcreteGateway(entity).extractSingle(entity, entityName, fieldName); } @Override public Object extractFullReference(Entity entity, String entityName, String fieldName) { return getConcreteGateway(entity).extractFullReference(entity, entityName, fieldName); } @Override public Collection extractCollectionKeys(Entity entity, String entityName, String fieldName) { return getConcreteGateway(entity).extractCollectionKeys(entity, entityName, fieldName); } @Override public Collection extractFullCollection(Entity entity, String entityName, String fieldName) { return getConcreteGateway(entity).extractFullCollection(entity, entityName, fieldName); } @Override public Collection extractCollectionByKeys(Entity entity, String entityName, String fieldName, Collection keys) { return getConcreteGateway(entity).extractCollectionByKeys(entity, entityName, fieldName, keys); } @Override public void setCollectionField(Entity entity, String entityName, String fieldName, Collection value) { getConcreteGateway(entity).setCollectionField(entity, entityName, fieldName, value); } protected EntityGateway<Entity> getConcreteGateway(Entity entity) { Class<? extends Entity> entityClass = (Class) entity.getClass(); EntityGateway<Entity> gateway = (EntityGateway) mapping.get(entityClass); if (gateway != null) { return gateway; } for (Class<? extends Entity> clazz : mapping.keySet()) { if (clazz.isAssignableFrom(entityClass)) { return (EntityGateway) mapping.get(clazz); } } return null; } }
Java
package com.anli.simpleorm.definitions; public class PrimitiveDefinition extends FieldDefinition { protected final PrimitiveType type; public PrimitiveDefinition(String name, Class<?> javaClass, String column, PrimitiveType type) { super(name, javaClass, column); this.type = type; } public PrimitiveType getType() { return type; } }
Java
package com.anli.simpleorm.definitions; public class ListDefinition extends CollectionDefinition { protected String orderColumn; public ListDefinition(String name, Class<?> javaClass, String foreignKeyColumn, EntityDefinition referencedEntity, String orderColumn) { super(name, javaClass, foreignKeyColumn, referencedEntity); this.orderColumn = orderColumn; } public String getOrderColumn() { return orderColumn; } }
Java
package com.anli.simpleorm.definitions; public class CollectionDefinition extends ReferenceDefinition { public CollectionDefinition(String name, Class<?> javaClass, String foreignKeyColumn, EntityDefinition referencedEntity) { super(name, javaClass, foreignKeyColumn, referencedEntity); } @Override public String getColumn() { return referencedEntity.getPrimaryKey().getColumn(); } public String getForeignKeyColumn() { return super.getColumn(); } }
Java
package com.anli.simpleorm.definitions; import com.anli.simpleorm.queries.named.NamedQuery; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; public class EntityDefinition { protected String primaryKeyName; protected final String name; protected String table; protected EntityDefinition parentEntity; protected final List<EntityDefinition> childrenEntities; protected final SortedMap<String, FieldDefinition> singleFields; protected final SortedMap<String, CollectionDefinition> collectionFields; protected final Map<String, NamedQuery> namedQueries; public EntityDefinition(String name) { this.name = name; this.singleFields = new TreeMap<>(); this.collectionFields = new TreeMap<>(); this.childrenEntities = new LinkedList<>(); this.namedQueries = new TreeMap<>(); } public void setPrimaryKeyName(String primaryKeyName) { this.primaryKeyName = primaryKeyName; } public void setTable(String table) { this.table = table; } public String getName() { return name; } public FieldDefinition getPrimaryKey() { return singleFields.get(primaryKeyName); } public Collection<FieldDefinition> getSingleFields() { return singleFields.values(); } public FieldDefinition getSingleField(String name) { return singleFields.get(name); } public void addSingleField(FieldDefinition singleField) { singleFields.put(singleField.getName(), singleField); } public Collection<CollectionDefinition> getCollectionFields() { return collectionFields.values(); } public CollectionDefinition getCollectionField(String name) { return collectionFields.get(name); } public void addCollectionField(CollectionDefinition collectionField) { collectionFields.put(collectionField.getName(), collectionField); } public String getTable() { return table; } public EntityDefinition getParentEntity() { return parentEntity; } public List<EntityDefinition> getChildrenEntities() { return childrenEntities; } public void addChildrenEntity(EntityDefinition childrenEntity) { this.childrenEntities.add(childrenEntity); childrenEntity.parentEntity = this; } public void addNamedQuery(NamedQuery query) { this.namedQueries.put(query.getName(), query); } public NamedQuery getNamedQuery(String queryName) { EntityDefinition currentEntity = this; while (currentEntity != null) { NamedQuery query = namedQueries.get(queryName); if (query != null) { return query; } currentEntity = currentEntity.getParentEntity(); } return null; } public FieldDefinition getField(String fieldName) { FieldDefinition field = singleFields.get(fieldName); if (field == null) { field = collectionFields.get(fieldName); } return field; } public EntityDefinition getFieldEntity(String fieldName) { if (singleFields.containsKey(fieldName) || collectionFields.containsKey(fieldName)) { return this; } return parentEntity != null ? parentEntity.getFieldEntity(fieldName) : null; } }
Java
package com.anli.simpleorm.definitions; public class ReferenceDefinition extends FieldDefinition { protected EntityDefinition referencedEntity; public ReferenceDefinition(String name, Class<?> javaClass, String column, EntityDefinition referencedEntity) { super(name, javaClass, column); this.referencedEntity = referencedEntity; } public EntityDefinition getReferencedEntity() { return referencedEntity; } }
Java
package com.anli.simpleorm.definitions; public enum PrimitiveType { STRING(false, true), NUMERIC(true, false), BOOLEAN(false, false), DATE(true, false), REFERENCE(false, false), OTHER(false, false); protected final boolean comparable; protected final boolean character; private PrimitiveType(boolean comparable, boolean character) { this.comparable = comparable; this.character = character; } public boolean isComparable() { return comparable; } public boolean isCharacter() { return character; } }
Java
package com.anli.simpleorm.definitions; public abstract class FieldDefinition { protected String name; protected Class<?> javaClass; protected String column; public FieldDefinition(String name, Class<?> javaClass, String column) { this.name = name; this.javaClass = javaClass; this.column = column; } public String getName() { return name; } public Class<?> getJavaClass() { return javaClass; } public String getColumn() { return column; } }
Java
package com.anli.simpleorm.queries; import com.anli.simpleorm.definitions.EntityDefinition; import com.anli.simpleorm.definitions.PrimitiveDefinition; public class CharacterFieldQueryCache extends SingleFieldQueryCache { protected String selectFullByRegexp; protected String selectKeysByRegexp; public CharacterFieldQueryCache(EntityDefinition mainDefinition, EntityDefinition fieldEntityDefinition, PrimitiveDefinition fieldDefinition, MySqlQueryBuilder queryBuilder) { super(mainDefinition, fieldEntityDefinition, fieldDefinition, queryBuilder); } public String getSelectFullByRegexpQuery() { if (selectFullByRegexp == null) { selectFullByRegexp = buildSelectByRegexpQuery(true); } return selectFullByRegexp; } public String getSelectKeysByRegexpQuery() { if (selectKeysByRegexp == null) { selectKeysByRegexp = buildSelectByRegexpQuery(false); } return selectKeysByRegexp; } protected String buildSelectByRegexpQuery(boolean full) { return queryBuilder.buildSelectEntityByStringRegexp(mainDefinition, fieldEntityDefinition, fieldDefinition, full); } }
Java
package com.anli.simpleorm.queries; import com.anli.simpleorm.definitions.EntityDefinition; import com.anli.simpleorm.definitions.FieldDefinition; public class SingleFieldQueryCache extends FieldQueryCache { protected String selectFullByIsNull; protected String selectKeysByIsNull; public SingleFieldQueryCache(EntityDefinition mainDefinition, EntityDefinition fieldEntityDefinition, FieldDefinition fieldDefinition, MySqlQueryBuilder queryBuilder) { super(mainDefinition, fieldEntityDefinition, fieldDefinition, queryBuilder); } public String getSelectFullByIsNullQuery() { if (selectFullByIsNull == null) { selectFullByIsNull = buildSelectByIsNullQuery(true); } return selectFullByIsNull; } public String getSelectKeysByIsNullQuery() { if (selectKeysByIsNull == null) { selectKeysByIsNull = buildSelectByIsNullQuery(false); } return selectKeysByIsNull; } protected String buildSelectByIsNullQuery(boolean full) { return queryBuilder.buildSelectEntityBySingleFieldNull(mainDefinition, fieldEntityDefinition, fieldDefinition, full); } }
Java
package com.anli.simpleorm.queries; import com.anli.simpleorm.definitions.EntityDefinition; import com.anli.simpleorm.definitions.FieldDefinition; public class FieldQueryCache { protected final EntityDefinition mainDefinition; protected final EntityDefinition fieldEntityDefinition; protected final FieldDefinition fieldDefinition; protected final MySqlQueryBuilder queryBuilder; protected String selectFullByEqualsOrContains; protected String selectKeysByEqualsOrContains; protected String selectFullByAnyTemplate; protected String selectKeysByAnyTemplate; public FieldQueryCache(EntityDefinition mainDefinition, EntityDefinition fieldEntityDefinition, FieldDefinition fieldDefinition, MySqlQueryBuilder queryBuilder) { this.mainDefinition = mainDefinition; this.fieldEntityDefinition = fieldEntityDefinition; this.fieldDefinition = fieldDefinition; this.queryBuilder = queryBuilder; } public String getSelectFullByEqualsOrContainsQuery() { if (selectFullByEqualsOrContains == null) { selectFullByEqualsOrContains = buildSelectByEqualsOrContainsQuery(true); } return selectFullByEqualsOrContains; } public String getSelectKeysByEqualsOrContainsQuery() { if (selectKeysByEqualsOrContains == null) { selectKeysByEqualsOrContains = buildSelectByEqualsOrContainsQuery(false); } return selectKeysByEqualsOrContains; } public String getSelectFullByAnyQuery(int size) { if (selectFullByAnyTemplate == null) { selectFullByAnyTemplate = buildSelectByAnyTemplate(true); } return String.format(selectFullByAnyTemplate, queryBuilder.buildParametersList(size)); } public String getSelectKeysByAnyQuery(int size) { if (selectKeysByAnyTemplate == null) { selectKeysByAnyTemplate = buildSelectByAnyTemplate(false); } return String.format(selectKeysByAnyTemplate, queryBuilder.buildParametersList(size)); } protected String buildSelectByEqualsOrContainsQuery(boolean full) { return queryBuilder.buildSelectEntityBySingleFieldEquals(mainDefinition, fieldEntityDefinition, fieldDefinition, full); } protected String buildSelectByAnyTemplate(boolean full) { return queryBuilder.buildSelectEntityBySingleFieldInListTemplate(mainDefinition, fieldEntityDefinition, fieldDefinition, full); } }
Java
package com.anli.simpleorm.queries; import com.anli.simpleorm.definitions.EntityDefinition; import com.anli.simpleorm.definitions.PrimitiveDefinition; public class ComparableFieldQueryCache extends SingleFieldQueryCache { protected static final String GREATER = ">"; protected static final String LESS = "<"; protected static final String EQUALS = "="; protected String selectFullByOpenRangeTemplate; protected String selectKeysByOpenRangeTemplate; protected String selectFullByClosedRangeTemplate; protected String selectKeysByClosedRangeTemplate; public ComparableFieldQueryCache(EntityDefinition mainDefinition, EntityDefinition fieldEntityDefinition, PrimitiveDefinition fieldDefinition, MySqlQueryBuilder queryBuilder) { super(mainDefinition, fieldEntityDefinition, fieldDefinition, queryBuilder); } public String getSelectFullByOpenRangeQuery(boolean left, boolean strict) { if (selectFullByOpenRangeTemplate == null) { selectFullByOpenRangeTemplate = buildSelectByOpenRangeTemplate(true); } return String.format(selectFullByOpenRangeTemplate, buildOperator(left, strict)); } public String getSelectKeysByOpenRangeQuery(boolean left, boolean strict) { if (selectKeysByOpenRangeTemplate == null) { selectKeysByOpenRangeTemplate = buildSelectByOpenRangeTemplate(false); } return String.format(selectKeysByOpenRangeTemplate, buildOperator(left, strict)); } public String getSelectFullByClosedRangeQuery(boolean leftStrict, boolean rightStrict) { if (selectFullByClosedRangeTemplate == null) { selectFullByClosedRangeTemplate = buildSelectByClosedRangeTemplate(true); } return String.format(selectFullByClosedRangeTemplate, buildOperator(true, leftStrict), buildOperator(false, rightStrict)); } public String getSelectKeysByClosedRangeQuery(boolean leftStrict, boolean rightStrict) { if (selectKeysByClosedRangeTemplate == null) { selectKeysByClosedRangeTemplate = buildSelectByClosedRangeTemplate(false); } return String.format(selectKeysByClosedRangeTemplate, buildOperator(true, leftStrict), buildOperator(false, rightStrict)); } protected String buildSelectByOpenRangeTemplate(boolean full) { return queryBuilder.buildSelectEntityBySingleFieldOpenRangeTemplate(mainDefinition, fieldEntityDefinition, fieldDefinition, full); } protected String buildSelectByClosedRangeTemplate(boolean full) { return queryBuilder.buildSelectEntityBySingleFieldClosedRangeTemplate(mainDefinition, fieldEntityDefinition, fieldDefinition, full); } protected String buildOperator(boolean left, boolean strict) { String operator = left ? GREATER : LESS; if (!strict) { operator += EQUALS; } return operator; } }
Java
package com.anli.simpleorm.queries; import com.anli.simpleorm.definitions.CollectionDefinition; import com.anli.simpleorm.definitions.EntityDefinition; import com.anli.simpleorm.definitions.ListDefinition; public class CollectionFieldQueryCache extends FieldQueryCache { protected String selectCollection; protected String linkCollectionTemplate; protected String unlinkNonEmptyCollectionTemplate; protected String clearCollection; public CollectionFieldQueryCache(EntityDefinition mainDefinition, EntityDefinition fieldEntityDefinition, CollectionDefinition fieldDefinition, MySqlQueryBuilder queryBuilder) { super(mainDefinition, fieldEntityDefinition, fieldDefinition, queryBuilder); } public String getSelectCollectionQuery() { if (selectCollection == null) { selectCollection = buildSelectCollectionQuery(); } return selectCollection; } public String getLinkCollectionQuery(int size) { if (linkCollectionTemplate == null) { linkCollectionTemplate = buildLinkCollectionTemplate(); } return String.format(linkCollectionTemplate, buildLinkagePart(size)); } public String getUnlinkCollectionQuery(int size) { if (size == 0) { if (clearCollection == null) { clearCollection = buildClearCollectionQuery(); } return clearCollection; } else { if (unlinkNonEmptyCollectionTemplate == null) { unlinkNonEmptyCollectionTemplate = buildUnlinkNonEmptyCollectionTemplate(); } return String.format(unlinkNonEmptyCollectionTemplate, queryBuilder.buildParametersList(size)); } } protected String buildSelectCollectionQuery() { return queryBuilder.buildSelectCollection((CollectionDefinition) fieldDefinition); } protected String buildLinkCollectionTemplate() { return queryBuilder.buildLinkCollectionQueryTemplate((CollectionDefinition) fieldDefinition); } protected String buildUnlinkNonEmptyCollectionTemplate() { return queryBuilder.buildUnlinkCollectionTemplate((CollectionDefinition) fieldDefinition, false); } protected String buildClearCollectionQuery() { return queryBuilder.buildUnlinkCollectionTemplate((CollectionDefinition) fieldDefinition, true); } protected String buildLinkagePart(int size) { if (fieldDefinition instanceof ListDefinition) { return queryBuilder.buildListOrderingSubquery((ListDefinition) fieldDefinition, size); } else { throw new UnsupportedOperationException(); } } @Override protected String buildSelectByEqualsOrContainsQuery(boolean full) { return queryBuilder.buildSelectEntityByCollectionFieldContainsSingle(mainDefinition, fieldEntityDefinition, (CollectionDefinition) fieldDefinition, full); } @Override protected String buildSelectByAnyTemplate(boolean full) { return queryBuilder.buildSelectEntityByCollectionFieldContainsListTemplate(mainDefinition, fieldEntityDefinition, (CollectionDefinition) fieldDefinition, full); } }
Java
package com.anli.simpleorm.queries.named; import org.apache.commons.lang.StringUtils; public class NamedQuery { protected static final String LIST_MACRO = "${list}"; protected final String name; protected final String additionalJoins; protected final String criteria; protected final int macroCount; public static String getListMacro() { return LIST_MACRO; } public NamedQuery(String name, String additionalJoins, String criteria) { this.name = name; this.additionalJoins = additionalJoins != null ? additionalJoins : ""; this.criteria = criteria != null ? criteria : ""; this.macroCount = StringUtils.countMatches(this.additionalJoins, LIST_MACRO) + StringUtils.countMatches(this.criteria, LIST_MACRO); } public String getName() { return name; } public String getAdditionalJoins() { return additionalJoins; } public String getCriteria() { return criteria; } public boolean isTemplate() { return macroCount > 0; } public int getMacroCount() { return macroCount; } }
Java
package com.anli.simpleorm.queries; import com.anli.simpleorm.definitions.CollectionDefinition; import com.anli.simpleorm.definitions.EntityDefinition; import com.anli.simpleorm.definitions.FieldDefinition; import com.anli.simpleorm.definitions.PrimitiveDefinition; import com.anli.simpleorm.definitions.PrimitiveType; import com.anli.simpleorm.queries.named.NamedQuery; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class EntityQueryCache { protected final EntityDefinition definition; protected final MySqlQueryBuilder queryBuilder; protected List<String> insertQueries; protected String deleteQuery; protected String updateQuery; protected String selectAllQuery; protected String selectAllKeysQuery; protected Map<String, Integer> keysIndices; protected final Map<String, FieldQueryCache> fieldCaches; protected final Map<String, String> selectNamedQueries; protected final Map<String, String> selectKeysNamedQueries; public EntityQueryCache(EntityDefinition definition, MySqlQueryBuilder queryBuilder) { this.definition = definition; this.queryBuilder = queryBuilder; this.fieldCaches = new HashMap<>(); this.selectNamedQueries = new HashMap<>(); this.selectKeysNamedQueries = new HashMap<>(); } public List<String> getInsertQueries() { if (insertQueries == null) { LinkedList<String> tempQueries = new LinkedList<>(); EntityDefinition currentDefinition = definition; while (currentDefinition != null) { tempQueries.addFirst(queryBuilder.buildInsertEntityQuery(currentDefinition)); currentDefinition = currentDefinition.getParentEntity(); } insertQueries = new ArrayList<>(tempQueries); } return insertQueries; } public String getDeleteQuery() { if (deleteQuery == null) { deleteQuery = queryBuilder.buildDeleteEntityQuery(definition); } return deleteQuery; } public String getUpdateQuery() { if (updateQuery == null) { updateQuery = queryBuilder.buildUpdateEntityQuery(definition); } return updateQuery; } public String getSelectQuery() { return getFieldQueryCache(definition.getPrimaryKey().getName()) .getSelectFullByEqualsOrContainsQuery(); } public String getSelectAllQuery() { if (selectAllQuery == null) { selectAllQuery = queryBuilder.buildSelectAllEntities(definition, true); } return selectAllQuery; } public String getSelectAllKeysQuery() { if (selectAllKeysQuery == null) { selectAllKeysQuery = queryBuilder.buildSelectAllEntities(definition, false); } return selectAllKeysQuery; } public Map<String, Integer> getKeysIndices() { if (keysIndices == null) { keysIndices = queryBuilder.getKeysIndices(definition); } return keysIndices; } public FieldQueryCache getFieldQueryCache(String fieldName) { FieldQueryCache cache = fieldCaches.get(fieldName); if (cache == null) { EntityDefinition fieldDef = definition.getFieldEntity(fieldName); cache = createFieldQueryCache(fieldDef, fieldDef.getField(fieldName)); fieldCaches.put(fieldName, cache); } return cache; } public String getSelectNamedQuery(String queryName) { NamedQuery namedQuery = definition.getNamedQuery(queryName); if (namedQuery.isTemplate()) { return null; } String selectQuery = selectNamedQueries.get(queryName); if (selectQuery == null) { selectQuery = queryBuilder.buildSelectByNamedQuery(definition, namedQuery, true); selectNamedQueries.put(queryName, selectQuery); } return selectQuery; } public String getSelectKeysNamedQuery(String queryName) { NamedQuery namedQuery = definition.getNamedQuery(queryName); if (namedQuery.isTemplate()) { return null; } String selectQuery = selectKeysNamedQueries.get(queryName); if (selectQuery == null) { selectQuery = queryBuilder.buildSelectByNamedQuery(definition, namedQuery, false); selectKeysNamedQueries.put(queryName, selectQuery); } return selectQuery; } public String getSelectNamedQuery(String queryName, List<Integer> sizes) { NamedQuery namedQuery = definition.getNamedQuery(queryName); if (!namedQuery.isTemplate()) { return null; } String selectQuery = selectNamedQueries.get(queryName); if (selectQuery == null) { selectQuery = queryBuilder.buildSelectByNamedQuery(definition, namedQuery, true); selectNamedQueries.put(queryName, selectQuery); } String[] lists = new String[namedQuery.getMacroCount()]; int count = 0; for (Integer size : sizes) { lists[count] = queryBuilder.buildParametersList(size); count++; } return String.format(selectQuery, (Object[]) lists); } public String getSelectKeysNamedQuery(String queryName, List<Integer> sizes) { NamedQuery namedQuery = definition.getNamedQuery(queryName); if (!namedQuery.isTemplate()) { return null; } String selectQuery = selectKeysNamedQueries.get(queryName); if (selectQuery == null) { selectQuery = queryBuilder.buildSelectByNamedQuery(definition, namedQuery, false); selectKeysNamedQueries.put(queryName, selectQuery); } String[] lists = new String[namedQuery.getMacroCount()]; int count = 0; for (Integer size : sizes) { lists[count] = queryBuilder.buildParametersList(size); count++; } return String.format(selectQuery, (Object[]) lists); } protected FieldQueryCache createFieldQueryCache(EntityDefinition fieldEntityDefinition, FieldDefinition fieldDefinition) { if (fieldDefinition instanceof CollectionDefinition) { return new CollectionFieldQueryCache(definition, fieldEntityDefinition, (CollectionDefinition) fieldDefinition, queryBuilder); } if (fieldDefinition instanceof PrimitiveDefinition) { PrimitiveDefinition primitiveDefinition = (PrimitiveDefinition) fieldDefinition; PrimitiveType type = primitiveDefinition.getType(); if (type.isCharacter()) { return new CharacterFieldQueryCache(definition, fieldEntityDefinition, primitiveDefinition, queryBuilder); } else if (type.isComparable()) { return new ComparableFieldQueryCache(definition, fieldEntityDefinition, primitiveDefinition, queryBuilder); } } return new SingleFieldQueryCache(definition, fieldEntityDefinition, fieldDefinition, queryBuilder); } }
Java
package com.anli.simpleorm.queries; import com.anli.simpleorm.definitions.CollectionDefinition; import com.anli.simpleorm.definitions.EntityDefinition; import com.anli.simpleorm.definitions.FieldDefinition; import com.anli.simpleorm.definitions.ListDefinition; import com.anli.simpleorm.queries.named.NamedQuery; import java.util.HashMap; import java.util.Map; public class MySqlQueryBuilder { protected static final String ORDERING_SUBQUERY_ALIAS = "ordering_subquery"; protected void appendSelectFromClause(StringBuilder query, EntityDefinition definition, boolean full) { appendSelectClause(query, definition, full); query.append(" "); appendFullFromClause(query, definition); } protected void appendSelectClause(StringBuilder query, EntityDefinition definition, boolean full) { query.append("select distinct "); if (full) { appendFieldList(query, definition, true, true); } else { appendPrimaryKeyField(query, definition); } } protected void appendPrimaryKeyField(StringBuilder query, EntityDefinition definition) { query.append(definition.getName().toLowerCase()).append(".").append(definition.getPrimaryKey().getColumn()); } protected void appendFieldList(StringBuilder query, EntityDefinition definition, boolean withChildren, boolean withParent) { boolean isCommaNeeded = false; if (definition.getParentEntity() != null && withParent) { appendFieldList(query, definition.getParentEntity(), false, true); isCommaNeeded = true; } String name = definition.getName().toLowerCase(); for (FieldDefinition field : definition.getSingleFields()) { if (isCommaNeeded) { query.append(", "); } else { isCommaNeeded = true; } StringBuilder element = new StringBuilder(); element.append(name).append(".").append(field.getColumn()); query.append(element); } if (!withChildren) { return; } for (EntityDefinition child : definition.getChildrenEntities()) { if (isCommaNeeded) { query.append(", "); } else { isCommaNeeded = true; } appendFieldList(query, child, true, false); } } protected void appendFullFromClause(StringBuilder query, EntityDefinition definition) { query.append("from ").append(definition.getTable()).append(" as ") .append(definition.getName().toLowerCase()); appendJoinClauses(query, definition, true, true); } protected void appendFullUpdateClause(StringBuilder query, EntityDefinition definition) { query.append("update ").append(definition.getTable()).append(" as ") .append(definition.getName().toLowerCase()); appendJoinClauses(query, definition, true, true); } protected void appendFullDeleteClause(StringBuilder query, EntityDefinition definition) { query.append("delete "); appendTableListDelete(query, definition, true, true); query.append(" "); appendFullFromClause(query, definition); } protected void appendTableListDelete(StringBuilder query, EntityDefinition definition, boolean withChildren, boolean withParent) { EntityDefinition parent = definition.getParentEntity(); if (parent != null && withParent) { appendTableListDelete(query, parent, false, true); query.append(", "); } query.append(definition.getName().toLowerCase()); if (!withChildren) { return; } for (EntityDefinition child : definition.getChildrenEntities()) { query.append(", "); appendTableListDelete(query, child, true, false); } } protected void appendJoinClauses(StringBuilder query, EntityDefinition definition, boolean withChildren, boolean withParent) { EntityDefinition parentDefinition = definition.getParentEntity(); if (parentDefinition != null && withParent) { query.append(" "); appendJoinClause(query, definition, parentDefinition, false); appendJoinClauses(query, parentDefinition, false, true); } if (!withChildren) { return; } for (EntityDefinition childDefinition : definition.getChildrenEntities()) { query.append(" "); appendJoinClause(query, definition, childDefinition, true); appendJoinClauses(query, childDefinition, true, false); } } protected void appendJoinClause(StringBuilder query, EntityDefinition mainDefinition, EntityDefinition joinedDefinition, boolean isLeft) { if (isLeft) { query.append("left "); } String joinedName = joinedDefinition.getName().toLowerCase(); query.append("join "); query.append(joinedDefinition.getTable()).append(" as ").append(joinedName); query.append(" on ").append(mainDefinition.getName().toLowerCase()).append(".") .append(mainDefinition.getPrimaryKey().getColumn()); query.append(" = ").append(joinedName) .append(".").append(joinedDefinition.getPrimaryKey().getColumn()); } protected void appendJoinByForeignKeyClause(StringBuilder query, EntityDefinition fieldEntityDefinition, CollectionDefinition fieldDefinition) { String joinedTable = fieldDefinition.getReferencedEntity().getTable(); String joinedAlias = fieldDefinition.getName().toLowerCase() + fieldDefinition.getReferencedEntity().getName().toLowerCase(); query.append("join ").append(joinedTable).append(" as ") .append(joinedAlias); query.append(" on ").append(fieldEntityDefinition.getName().toLowerCase()).append(".") .append(fieldEntityDefinition.getPrimaryKey().getColumn()); query.append(" = ").append(joinedAlias).append(".").append(fieldDefinition.getForeignKeyColumn()); } protected void appendFullSetClause(StringBuilder query, EntityDefinition definition) { query.append("set "); appendSetFieldList(query, definition, true, true); } protected void appendSetFieldList(StringBuilder query, EntityDefinition definition, boolean withChildren, boolean withParent) { boolean isCommaNeeded = false; EntityDefinition parentDefinition = definition.getParentEntity(); if (parentDefinition != null && withParent) { appendSetFieldList(query, parentDefinition, false, true); isCommaNeeded = true; } String name = definition.getName().toLowerCase(); for (FieldDefinition field : definition.getSingleFields()) { if (isCommaNeeded) { query.append(", "); } else { isCommaNeeded = true; } StringBuilder element = new StringBuilder(name); element.append(".").append(field.getColumn()).append(" = ?"); query.append(element); } if (!withChildren) { return; } for (EntityDefinition child : definition.getChildrenEntities()) { if (isCommaNeeded) { query.append(", "); } else { isCommaNeeded = true; } appendSetFieldList(query, child, true, false); } } public String buildListOrderingSubquery(ListDefinition listField, int size) { String primaryKeyColumn = listField.getReferencedEntity().getPrimaryKey().getColumn(); String orderingColumn = listField.getOrderColumn(); StringBuilder subquery = new StringBuilder(); boolean isUnionNeeded = false; for (int i = 0; i < size; i++) { if (isUnionNeeded) { subquery.append(" union all "); } else { isUnionNeeded = true; } subquery.append("select ? as ").append(primaryKeyColumn).append(", ") .append(i).append(" as ").append(orderingColumn).append(" from dual"); } return subquery.toString(); } protected void appendSetForeignKeysAndOrdering(StringBuilder query, ListDefinition listField) { String name = listField.getReferencedEntity().getName().toLowerCase(); String orderingColumn = listField.getOrderColumn(); query.append("set ").append(name).append(".") .append(listField.getForeignKeyColumn()).append(" = ?"); query.append(", ").append(name).append(".").append(orderingColumn) .append(" = ").append(ORDERING_SUBQUERY_ALIAS).append(".").append(orderingColumn); } protected void appendLinkListQueryTemplate(StringBuilder query, ListDefinition listField) { String table = listField.getReferencedEntity().getTable(); String name = listField.getReferencedEntity().getName().toLowerCase(); String primaryKeyColumn = listField.getReferencedEntity().getPrimaryKey().getColumn(); query.append("update ").append(table).append(" as ").append(name).append(" join (") .append("%s").append(")").append(ORDERING_SUBQUERY_ALIAS); query.append(" on ").append(name).append(".").append(primaryKeyColumn) .append(" = ").append(ORDERING_SUBQUERY_ALIAS).append(".").append(primaryKeyColumn); query.append(" "); appendSetForeignKeysAndOrdering(query, listField); } protected void appendSetClearedForeignKeysAndOrdering(StringBuilder query, ListDefinition listField) { String name = listField.getReferencedEntity().getName().toLowerCase(); String foreignKeyColumn = listField.getForeignKeyColumn(); query.append("set ").append(name).append(".").append(foreignKeyColumn) .append(" = null, ").append(name).append(".").append(listField.getOrderColumn()) .append(" = null"); } protected void appendUnlinkCollectionWhereClauseTemplate(StringBuilder query, CollectionDefinition field, boolean isEmpty) { String primaryKeyColumn = field.getReferencedEntity().getPrimaryKey().getColumn(); String name = field.getReferencedEntity().getName().toLowerCase(); query.append("where ").append(name).append(".").append(field.getForeignKeyColumn()) .append(" = ?"); if (!isEmpty) { query.append(" and ").append(name).append(".").append(primaryKeyColumn) .append(" not in (%s)"); } } public String buildParametersList(int size) { StringBuilder list = new StringBuilder(); boolean isCommaNeeded = false; for (int i = 0; i < size; i++) { if (isCommaNeeded) { list.append(", "); } else { isCommaNeeded = true; } list.append("?"); } return list.toString(); } protected void appendSelectListWhereOrderByClause(StringBuilder query, ListDefinition listField) { String name = listField.getReferencedEntity().getName().toLowerCase(); query.append("where ").append(name).append(".").append(listField.getForeignKeyColumn()) .append(" = ?"); query.append(" order by ").append(name).append(".").append(listField.getOrderColumn()); } protected void appendWhereEqualsClause(StringBuilder query, EntityDefinition definition, FieldDefinition field) { String name = (field instanceof CollectionDefinition) ? field.getName().toLowerCase() + ((CollectionDefinition) field).getReferencedEntity().getName().toLowerCase() : definition.getName().toLowerCase(); query.append("where ").append(name).append(".").append(field.getColumn()) .append(" = ?"); } protected void appendWhereStringRegexpClause(StringBuilder query, EntityDefinition definition, FieldDefinition field) { query.append("where ").append(definition.getName().toLowerCase()).append(".").append(field.getColumn()) .append(" regexp ?"); } protected void appendWhereInListClauseTemplate(StringBuilder query, EntityDefinition definition, FieldDefinition field) { String name = (field instanceof CollectionDefinition) ? field.getName().toLowerCase() + ((CollectionDefinition) field).getReferencedEntity().getName().toLowerCase() : definition.getName().toLowerCase(); query.append("where ").append(name).append(".").append(field.getColumn()) .append(" in (%s)"); } protected void appendWhereIsNullClause(StringBuilder query, EntityDefinition definition, FieldDefinition field) { query.append("where ").append(definition.getName().toLowerCase()).append(".").append(field.getColumn()) .append(" is null"); } protected void appendWhereOpenRangeTemplate(StringBuilder query, EntityDefinition definition, FieldDefinition field) { query.append("where ").append(definition.getName().toLowerCase()).append(".").append(field.getColumn()) .append(" %s ?"); } protected void appendWhereClosedRangeTemplate(StringBuilder query, EntityDefinition definition, FieldDefinition field) { String name = definition.getName().toLowerCase(); String column = field.getColumn(); query.append("where ").append(name).append(".").append(column) .append(" %s ?"); query.append(" and ").append(name).append(".").append(column) .append(" %s ?"); } protected void appendFullInsertClause(StringBuilder query, EntityDefinition definition) { query.append("insert into ").append(definition.getTable()).append("("); query.append(definition.getPrimaryKey().getColumn()); query.append(") values (?)"); } public String buildUpdateEntityQuery(EntityDefinition definition) { StringBuilder query = new StringBuilder(); appendFullUpdateClause(query, definition); query.append(" set "); appendSetFieldList(query, definition, true, true); query.append(" "); appendWhereEqualsClause(query, definition, definition.getPrimaryKey()); return query.toString(); } public String buildDeleteEntityQuery(EntityDefinition definition) { StringBuilder query = new StringBuilder(); appendFullDeleteClause(query, definition); query.append(" "); appendWhereEqualsClause(query, definition, definition.getPrimaryKey()); return query.toString(); } public String buildInsertEntityQuery(EntityDefinition definition) { StringBuilder query = new StringBuilder(); appendFullInsertClause(query, definition); return query.toString(); } public String buildSelectAllEntities(EntityDefinition definition, boolean full) { StringBuilder query = new StringBuilder(); appendSelectFromClause(query, definition, full); return query.toString(); } public String buildSelectEntityBySingleFieldEquals(EntityDefinition definition, EntityDefinition fieldEntityDefinition, FieldDefinition fieldDefinition, boolean full) { StringBuilder query = new StringBuilder(); appendSelectFromClause(query, definition, full); query.append(" "); appendWhereEqualsClause(query, fieldEntityDefinition, fieldDefinition); return query.toString(); } public String buildSelectEntityBySingleFieldNull(EntityDefinition definition, EntityDefinition fieldEntityDefinition, FieldDefinition fieldDefinition, boolean full) { StringBuilder query = new StringBuilder(); appendSelectFromClause(query, definition, full); query.append(" "); appendWhereIsNullClause(query, fieldEntityDefinition, fieldDefinition); return query.toString(); } public String buildSelectEntityByStringRegexp(EntityDefinition definition, EntityDefinition fieldEntityDefinition, FieldDefinition fieldDefinition, boolean full) { StringBuilder query = new StringBuilder(); appendSelectFromClause(query, definition, full); query.append(" "); appendWhereStringRegexpClause(query, fieldEntityDefinition, fieldDefinition); return query.toString(); } public String buildSelectEntityBySingleFieldInListTemplate(EntityDefinition definition, EntityDefinition fieldEntityDefinition, FieldDefinition fieldDefinition, boolean full) { StringBuilder query = new StringBuilder(); appendSelectFromClause(query, definition, full); query.append(" "); appendWhereInListClauseTemplate(query, fieldEntityDefinition, fieldDefinition); return query.toString(); } public String buildSelectEntityBySingleFieldOpenRangeTemplate(EntityDefinition definition, EntityDefinition fieldEntityDefinition, FieldDefinition fieldDefinition, boolean full) { StringBuilder query = new StringBuilder(); appendSelectFromClause(query, definition, full); query.append(" "); appendWhereOpenRangeTemplate(query, fieldEntityDefinition, fieldDefinition); return query.toString(); } public String buildSelectEntityBySingleFieldClosedRangeTemplate(EntityDefinition definition, EntityDefinition fieldEntityDefinition, FieldDefinition fieldDefinition, boolean full) { StringBuilder query = new StringBuilder(); appendSelectFromClause(query, definition, full); query.append(" "); appendWhereClosedRangeTemplate(query, fieldEntityDefinition, fieldDefinition); return query.toString(); } public String buildSelectEntityByCollectionFieldContainsSingle(EntityDefinition definition, EntityDefinition fieldEntityDefinition, CollectionDefinition fieldDefinition, boolean full) { StringBuilder query = new StringBuilder(); appendSelectFromClause(query, definition, full); query.append(" "); appendJoinByForeignKeyClause(query, fieldEntityDefinition, fieldDefinition); query.append(" "); appendWhereEqualsClause(query, fieldEntityDefinition, fieldDefinition); return query.toString(); } public String buildSelectEntityByCollectionFieldContainsListTemplate(EntityDefinition definition, EntityDefinition fieldEntityDefinition, CollectionDefinition fieldDefinition, boolean full) { StringBuilder query = new StringBuilder(); appendSelectFromClause(query, definition, full); query.append(" "); appendJoinByForeignKeyClause(query, fieldEntityDefinition, fieldDefinition); query.append(" "); appendWhereInListClauseTemplate(query, definition, fieldDefinition); return query.toString(); } public String buildSelectCollection(CollectionDefinition fieldDefinition) { StringBuilder query = new StringBuilder(); appendSelectFromClause(query, fieldDefinition.getReferencedEntity(), true); query.append(" "); if (fieldDefinition instanceof ListDefinition) { appendSelectListWhereOrderByClause(query, (ListDefinition) fieldDefinition); } else { throw new UnsupportedOperationException(); } return query.toString(); } public String buildLinkCollectionQueryTemplate(CollectionDefinition fieldDefinition) { StringBuilder query = new StringBuilder(); if (fieldDefinition instanceof ListDefinition) { appendLinkListQueryTemplate(query, (ListDefinition) fieldDefinition); } else { throw new UnsupportedOperationException(); } return query.toString(); } public String buildUnlinkCollectionTemplate(CollectionDefinition fieldDefinition, boolean isEmpty) { StringBuilder query = new StringBuilder(); query.append("update ").append(fieldDefinition.getReferencedEntity().getTable()).append(" ") .append(" as ").append(fieldDefinition.getReferencedEntity().getName().toLowerCase()); query.append(" "); if (fieldDefinition instanceof ListDefinition) { appendSetClearedForeignKeysAndOrdering(query, (ListDefinition) fieldDefinition); } else { throw new UnsupportedOperationException(); } query.append(" "); appendUnlinkCollectionWhereClauseTemplate(query, fieldDefinition, isEmpty); return query.toString(); } public String buildSelectByNamedQuery(EntityDefinition definition, NamedQuery namedQuery, boolean full) { StringBuilder query = new StringBuilder(); appendSelectFromClause(query, definition, full); query.append(" "); query.append(resolveListMacros(namedQuery.getAdditionalJoins())); query.append(" "); query.append(resolveListMacros(namedQuery.getCriteria())); return query.toString(); } protected String resolveListMacros(String clause) { return clause.replace(NamedQuery.getListMacro(), "%s"); } public Map<String, Integer> getKeysIndices(EntityDefinition definition) { Map<String, Integer> keyMap = new HashMap<>(); int lastIndex = countSingleFields(definition.getParentEntity()); addKeyIndex(definition, lastIndex, keyMap); return keyMap; } protected int countSingleFields(EntityDefinition definition) { if (definition == null) { return 0; } int counter = countSingleFields(definition.getParentEntity()); return counter + definition.getSingleFields().size(); } protected int addKeyIndex(EntityDefinition definition, int lastIndex, Map<String, Integer> keyMap) { FieldDefinition primaryKey = definition.getPrimaryKey(); String entityName = definition.getName(); for (FieldDefinition field : definition.getSingleFields()) { lastIndex++; if (field == primaryKey) { keyMap.put(entityName, lastIndex); } } for (EntityDefinition child : definition.getChildrenEntities()) { lastIndex = addKeyIndex(child, lastIndex, keyMap); } return lastIndex; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.mobicents.diameter.server.bootstrap; import gnu.getopt.Getopt; import gnu.getopt.LongOpt; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Properties; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.xml.DOMConfigurator; import org.jboss.dependency.spi.Controller; import org.jboss.dependency.spi.ControllerContext; import org.jboss.kernel.Kernel; import org.jboss.kernel.plugins.bootstrap.basic.BasicBootstrap; import org.jboss.kernel.plugins.deployment.xml.BasicXMLDeployer; import org.jboss.util.StringPropertyReplacer; /** * @author <a href="mailto:ales.justin@jboss.com">Ales Justin</a> * @author <a href="mailto:amit.bhayani@jboss.com">amit bhayani</a> * @author baranowb */ public class Main { private final static String HOME_DIR = "DIA_HOME"; private final static String BOOT_URL = "/conf/bootstrap-beans.xml"; private final static String LOG4J_URL = "/conf/log4j.properties"; private final static String LOG4J_URL_XML = "/conf/log4j.xml"; public static final String DIA_HOME = "dia.home.dir"; public static final String DIA_BIND_ADDRESS = "dia.bind.address"; private static int index = 0; private Kernel kernel; private BasicXMLDeployer kernelDeployer; private Controller controller; private static Logger logger = Logger.getLogger(Main.class); public static void main(String[] args) throws Throwable { String homeDir = getHomeDir(args); System.setProperty(DIA_HOME, homeDir); if (!initLOG4JProperties(homeDir) && !initLOG4JXml(homeDir)) { //logger.error("Failed to initialize loggin, no configuration. Defaults are used."); System.err.println("Failed to initialize loggin, no configuration. Defaults are used."); }else { logger.info("log4j configured"); } URL bootURL = getBootURL(args); Main main = new Main(); main.processCommandLine(args); logger.info("Booting from " + bootURL); main.boot(bootURL); } private void processCommandLine(String[] args) { String programName = System.getProperty("program.name", "Mobicents Diameter Test Server"); int c; String arg; LongOpt[] longopts = { new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h'), new LongOpt("host", LongOpt.REQUIRED_ARGUMENT, null, 'b') }; Getopt g = new Getopt("MMS", args, "-:b:h", longopts); g.setOpterr(false); // We'll do our own error handling // while ((c = g.getopt()) != -1) { switch (c) { // case 'b': arg = g.getOptarg(); System.setProperty(DIA_BIND_ADDRESS, arg); break; // case 'h': System.out.println("usage: " + programName + " [options]"); System.out.println(); System.out.println("options:"); System.out.println(" -h, --help Show this help message"); System.out.println(" -b, --host=<host or ip> Bind address for all Mobicents Media Server services"); System.out.println(); System.exit(0); break; case ':': System.out.println("You need an argument for option " + (char) g.getOptopt()); System.exit(0); break; // case '?': System.out.println("The option '" + (char) g.getOptopt() + "' is not valid"); System.exit(0); break; // default: System.out.println("getopt() returned " + c); break; } } if (System.getProperty(DIA_BIND_ADDRESS) == null) { System.setProperty(DIA_BIND_ADDRESS, "127.0.0.1"); } } private static boolean initLOG4JProperties(String homeDir) { String Log4jURL = homeDir + LOG4J_URL; try { URL log4jurl = getURL(Log4jURL); InputStream inStreamLog4j = log4jurl.openStream(); Properties propertiesLog4j = new Properties(); try { propertiesLog4j.load(inStreamLog4j); PropertyConfigurator.configure(propertiesLog4j); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { // e.printStackTrace(); logger.info("Failed to initialize LOG4J with properties file."); return false; } return true; } private static boolean initLOG4JXml(String homeDir) { String Log4jURL = homeDir + LOG4J_URL_XML; try { URL log4jurl = getURL(Log4jURL); DOMConfigurator.configure(log4jurl); } catch (Exception e) { // e.printStackTrace(); logger.info("Failed to initialize LOG4J with xml file."); return false; } return true; } /** * Gets the Media Server Home directory. * * @param args * the command line arguments * @return the path to the home directory. */ private static String getHomeDir(String args[]) { if (System.getenv(HOME_DIR) == null) { if (args.length > index) { return args[index++]; } else { return "."; } } else { return System.getenv(HOME_DIR); } } /** * Gets the URL which points to the boot descriptor. * * @param args * command line arguments. * @return URL of the boot descriptor. */ private static URL getBootURL(String args[]) throws Exception { String bootURL = "${" + DIA_HOME + "}" + BOOT_URL; return getURL(bootURL); } protected void boot(URL bootURL) throws Throwable { BasicBootstrap bootstrap = new BasicBootstrap(); bootstrap.run(); registerShutdownThread(); kernel = bootstrap.getKernel(); kernelDeployer = new BasicXMLDeployer(kernel); kernelDeployer.deploy(bootURL); kernelDeployer.validate(); controller = kernel.getController(); start(kernel, kernelDeployer); } public void start(Kernel kernel, BasicXMLDeployer kernelDeployer) { ControllerContext context = controller.getInstalledContext("MainDeployer"); if (context != null) { MainDeployer deployer = (MainDeployer) context.getTarget(); deployer.start(kernel, kernelDeployer); } } public static URL getURL(String url) throws Exception { // replace ${} inputs url = StringPropertyReplacer.replaceProperties(url, System.getProperties()); File file = new File(url); if (file.exists() == false) { throw new IllegalArgumentException("No such file: " + url); } return file.toURI().toURL(); } protected void registerShutdownThread() { Runtime.getRuntime().addShutdownHook(new Thread(new ShutdownThread())); } private class ShutdownThread implements Runnable { public void run() { System.out.println("Shutting down"); kernelDeployer.shutdown(); kernelDeployer = null; kernel.getController().shutdown(); kernel = null; } } }
Java
/* * Mobicents, Communications Middleware * * Copyright (c) 2008, Red Hat Middleware LLC or third-party * contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * * Boston, MA 02110-1301 USA */ package org.mobicents.diameter.server.bootstrap; import java.io.File; import java.net.MalformedURLException; import java.net.URL; /** * * @author kulikov */ public class Deployment { private File file; private boolean isDirectory; private long lastModified; public Deployment(File file) { this.file = file; this.isDirectory = file.isDirectory(); this.lastModified = file.lastModified(); } public boolean isDirectory() { return this.isDirectory; } public URL getURL() { try { return file.toURI().toURL(); } catch (MalformedURLException e) { return null; } } public long lastModified() { return lastModified; } public void update(long lastModified) { this.lastModified = lastModified; } }
Java
package org.mobicents.diameter.server.bootstrap; import java.io.File; import java.io.FileFilter; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; /** * * @author amit bhayani * */ public class FileFilterImpl implements FileFilter { /** The file suffixes */ private static Set<String> fileSuffixes = new CopyOnWriteArraySet<String>(); static { fileSuffixes.add("-beans.xml"); fileSuffixes.add("-conf.xml"); } public FileFilterImpl() { } public FileFilterImpl(Set<String> suffixes) { if (suffixes == null) throw new IllegalArgumentException("Null suffixes"); fileSuffixes.clear(); fileSuffixes.addAll(suffixes); } public boolean accept(File pathname) { for (String suffix : fileSuffixes) { String filePathName = pathname.getName(); if (filePathName.endsWith(suffix)) return true; } return false; } public Set<String> getSuffixes() { return fileSuffixes; } public static boolean addFileSuffix(String suffix) { if (suffix == null) throw new IllegalArgumentException("Null suffix"); return fileSuffixes.add(suffix); } public static boolean removeFileSuffix(String suffix) { if (suffix == null) throw new IllegalArgumentException("Null suffix"); return fileSuffixes.remove(suffix); } }
Java
package org.mobicents.diameter.server.bootstrap; public interface ContainerOperations { public void terminateContainer(); }
Java
/* * Mobicents, Communications Middleware * * Copyright (c) 2008, Red Hat Middleware LLC or third-party * contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * * Boston, MA 02110-1301 USA */ package org.mobicents.diameter.server.bootstrap; import java.io.File; import java.io.FileFilter; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import org.jboss.kernel.Kernel; import org.jboss.kernel.plugins.deployment.xml.BasicXMLDeployer; /** * Simplified deployement framework designed for hot deployement of endpoints and media components. * * Deployement is represented by tree of folders. Each folder may contains one or more deployement descriptors. The most * top deployment directory is referenced as root. Maindeployer creates recursively HDScanner for root and each nested * directoty. The HDScanner corresponding to the root directory is triggered periodicaly by local timer and in it order * starts nested scanners recursively. * * @author kulikov * @author amit bhayani */ public class MainDeployer implements ContainerOperations{ /** JBoss microconatiner kernel */ private Kernel kernel; /** Basic deployer */ private BasicXMLDeployer kernelDeployer; /** Interval for scanning root deployment directory */ private int scanPeriod; /** Filter for selecting descriptors */ private FileFilter fileFilter; /** Root deployment directory as string */ private Set<String> path; /** Root deployment directory as file object */ private File[] root; /** Scanner trigger */ private ScheduledExecutorService executor = null; /** Trigger's controller */ private ScheduledFuture activeScan; /** Logger instance */ private Logger logger = Logger.getLogger(MainDeployer.class); /** * Creates new instance of deployer. */ public MainDeployer() { executor = Executors.newSingleThreadScheduledExecutor(new ScannerThreadFactory()); } /** * Gets the current value of the period used for scanning deployement directory. * * @return the value of the period in milliseconds. */ public int getScanPeriod() { return scanPeriod; } /** * Modifies value of the period used to scan deployement directory. * * @param scanPeriod * the value of the period in milliseconds. */ public void setScanPeriod(int scanPeriod) { this.scanPeriod = scanPeriod; } /** * Gets the path to the to the root deployment directory. * * @return path to deployment directory. */ public Set<String> getPath() { return path; } /** * Modify the path to the root deployment directory * * @param path */ public void setPath(Set<String> path) { this.path = path; root = new File[path.size()]; int count = 0; for (String s : path) { root[count++] = new File(s); } } /** * Gets the filter used by Deployer to select files for deployement. * * @return the file filter object. */ public FileFilter getFileFilter() { return fileFilter; } /** * Assigns file filter used for selection files for deploy. * * @param fileFilter * the file filter object. */ public void setFileFilter(FileFilter fileFilter) { this.fileFilter = fileFilter; } /** * Starts main deployer. * * @param kernel * the jboss microntainer kernel instance. * @param kernelDeployer * the jboss basic deployer. */ public void start(Kernel kernel, BasicXMLDeployer kernelDeployer) { this.kernel = kernel; this.kernelDeployer = kernelDeployer; // If scanPeriod is set to -ve, reset to 0 if (scanPeriod < 0) { this.scanPeriod = 0; } // If scanPeriod is set to less than 1 sec but greater than 0 millisec, re-set to 1 sec if (scanPeriod < 1000 && scanPeriod > 0) { this.scanPeriod = 1000; } for (File f : root) { // create deployement scanner and do first deployement HDScanner scanner = new HDScanner(f); scanner.run(); // hot-deployment disabled for scan period set to 0 if (!(scanPeriod == 0)) { activeScan = executor.scheduleAtFixedRate(scanner, scanPeriod, scanPeriod, TimeUnit.MILLISECONDS); } else { if (logger.isDebugEnabled()) { logger.debug("scanPeriod is set to 0. Hot deployment disabled"); } } } logger.info("[[[[[[[[[ Started " + "]]]]]]]]]"); } /** * Shuts down deployer. */ public void stop() { if (activeScan != null) { activeScan.cancel(true); } logger.info("Stopped"); } /** * Deploys components using specified deployement descriptor. * * @param file * the reference to the deployment descriptor * @throws java.lang.Throwable */ private void deploy(File file) { logger.info("Deploying " + file); String filePath = file.getPath(); if (filePath.endsWith(".xml")) { try { kernelDeployer.deploy(file.toURI().toURL()); kernelDeployer.validate(); logger.info("Deployed " + file); } catch (Throwable t) { logger.info("Could not deploy " + file, t); } } } /** * Undeploys components specified in deployment descriptor. * * @param file * the reference to the deployment descriptor. */ private void undeploy(File file) { logger.info("Undeploying " + file); String filePath = file.getPath(); if (filePath.endsWith(".xml")) { try { kernelDeployer.undeploy(file.toURI().toURL()); } catch (MalformedURLException e) { } logger.info("Undeployed " + file); } } /** * Redeploys components specified in deployment descriptor. * * This method subsequently performs undeployment and deployment procedures. * * @param file * the reference to the deployment descriptor. */ private void redeploy(File file) { undeploy(file); deploy(file); } /** * Deployment scanner. * * The scanner relates to a directory in the deployement structure. It is responsible for processing all descriptors * in this directotry and for triggering nested scanners. */ private class HDScanner implements Runnable { /** directory to which scanner relates */ private File dir; /** nested scanners */ private HashMap<File, HDScanner> scanners = new HashMap(); /** map between descriptor and last deployed time */ private HashMap<File, Deployment> deployments = new HashMap(); /** * Creates new instance of the scanner. * * @param dir * the directory releated to this scanner. */ public HDScanner(File dir) { // we do not any check for file (is it directory) because we know that // always directory this.dir = dir; } /** * This methods is called by local timer. * * It shoudl find changes in the deployement structure and execute corresponding method: * * -deploy for new descriptors; -undeploy for removed descriptors; -redeploy for updated descriptors; -create * nested scanner for new nested directories; -remove nested scanner for deleted nested directories; -run nested * scanners recursively. */ public void run() { // get the fresh list of nested files File[] files = dir.listFiles(); // select list of new files and process this list Collection<File> list = getNew(files); if (!list.isEmpty()) { for (File file : list) { // again, for directories we are creating nested scanners // and deploying desciptors if (file.isDirectory()) { HDScanner childScanner = new HDScanner(file); scanners.put(file, childScanner); // keep reference to nested directory because we need to track // the case when directory will be deleted } else if (file.isFile() && fileFilter.accept(file)) { deploy(file); } deployments.put(file, new Deployment(file)); } } // now same for removed. // determine list of removed files list = getRemoved(files); for (File file : list) { Deployment d = deployments.remove(file); if (d == null) { continue; } if (d.isDirectory()) { HDScanner scanner = scanners.remove(file); if (scanner != null) { scanner.undeployAll(); } } else { undeploy(file); } } // redeploying list = getUpdates(files); for (File file : list) { // ignore directories if (file.isFile() && fileFilter.accept(file)) { redeploy(file); } } // Processing nested deployments Collection<HDScanner> nested = scanners.values(); for (HDScanner scanner : nested) { scanner.run(); } } private void undeployAll() { // undeploy descriptors Set<File> list = deployments.keySet(); for (File file : list) { if (!deployments.get(file).isDirectory()) { undeploy(file); } } deployments.clear(); // recursively undeploy nested directories Collection<HDScanner> nested = scanners.values(); for (HDScanner scanner : nested) { scanner.undeployAll(); } } /** * Collects added descriptors from the specified list. * * @param files * the list of descriptors. * @return the list of new new descriptors. */ private Collection<File> getNew(File[] files) { ArrayList<File> list = new ArrayList(); for (File f : files) { if (!deployments.containsKey(f)) { list.add(f); } } return list; } /** * Collects descriptors that were deleted. * * @param files * the list of currently available descriptors * @return the list of deleted descriptors. */ private Collection<File> getRemoved(File[] files) { List<File> removed = new ArrayList(); Set<File> list = deployments.keySet(); for (File descriptor : list) { boolean found = false; for (File file : files) { if (descriptor.equals(file)) { found = true; break; } } if (!found) { removed.add(descriptor); } } return removed; } /** * Collects descriptors that were updates. * * @param files * the fresh list of descriptors. * @return the list of updated descriptors. */ private Collection<File> getUpdates(File[] files) { ArrayList<File> list = new ArrayList(); for (File f : files) { if (deployments.containsKey(f)) { long lastModified = deployments.get(f).lastModified(); if (lastModified < f.lastModified()) { deployments.get(f).update(f.lastModified()); list.add(f); } } } return list; } } /** * Scanner thread factory. */ private class ScannerThreadFactory implements ThreadFactory { /** * Creates new thread. * * @param r * main deployer. * @return thread object. */ public Thread newThread(Runnable r) { return new Thread(r, "MainDeployer"); } } //hook jmx method to terminate container public void terminateContainer() { //this will trigger shoot down hook, which nicely kills container. System.exit(0); } }
Java
package org.mobicents.diameter.server.bootstrap; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.lang.reflect.UndeclaredThrowableException; import java.util.Hashtable; import java.util.ArrayList; import java.util.Properties; import java.io.BufferedReader; import java.io.InputStreamReader; import javax.management.MBeanServerConnection; import javax.management.ObjectName; import javax.naming.Context; import javax.naming.InitialContext; import gnu.getopt.Getopt; import gnu.getopt.LongOpt; import org.jboss.security.SecurityAssociation; import org.jboss.security.SimplePrincipal; import org.jnp.interfaces.NamingContext; /** * Based on org.jboss.Shutdown by S.Stark and J. Dillon * @author baranowb */ public class Shutdown { ///////////////////////////////////////////////////////////////////////// // Command Line Support // ///////////////////////////////////////////////////////////////////////// public static final String PROGRAM_NAME = System.getProperty("program.name", "shutdown"); protected static void displayUsage() { System.out.println("A JMX client to shutdown (exit or halt) a remote JBoss server."); System.out.println(); System.out.println("usage: " + PROGRAM_NAME + " [options] <operation>"); System.out.println(); System.out.println("options:"); System.out.println(" -h, --help Show this help message (default)"); System.out.println(" -D<name>[=<value>] Set a system property"); System.out.println(" -- Stop processing options"); System.out.println(" -s, --server=<url> Specify the JNDI URL of the remote server"); System.out.println(" -a, --adapter=<name> Specify JNDI name of the MBeanServerConnection to use"); System.out.println(" -u, --user=<name> Specify the username for authentication"); System.out.println(" -p, --password=<name> Specify the password for authentication"); } public static void main(final String[] args) throws Exception { if (args.length == 0) { displayUsage(); System.exit(0); } ObjectName serverJMXName = new ObjectName("mobicents:service=ContainerStopper"); String sopts = "-:hD:s:a:u:p:"; LongOpt[] lopts = { new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h'), new LongOpt("server", LongOpt.REQUIRED_ARGUMENT, null, 's'), new LongOpt("adapter", LongOpt.REQUIRED_ARGUMENT, null, 'a'), new LongOpt("user", LongOpt.REQUIRED_ARGUMENT, null, 'u'), new LongOpt("password", LongOpt.REQUIRED_ARGUMENT, null, 'p'), }; Getopt getopt = new Getopt(PROGRAM_NAME, args, sopts, lopts); int code; String arg; String serverURL = null; String adapterName = "jmx/rmi/RMIAdaptor"; String username = null; String password = null; boolean exit = false; boolean halt = false; int exitcode = -1; while ((code = getopt.getopt()) != -1) { switch (code) { case ':': case '?': // for now both of these should exit with error status System.exit(1); break; case 1: // this will catch non-option arguments // (which we don't currently care about) System.err.println(PROGRAM_NAME + ": unused non-option argument: " + getopt.getOptarg()); break; case 'h': displayUsage(); System.exit(0); break; case 'D': { // set a system property arg = getopt.getOptarg(); String name, value; int i = arg.indexOf("="); if (i == -1) { name = arg; value = "true"; } else { name = arg.substring(0, i); value = arg.substring(i + 1, arg.length()); } System.setProperty(name, value); break; } case 's': serverURL = getopt.getOptarg(); break; case 'S': // nothing... break; case 'a': adapterName = getopt.getOptarg(); break; case 'u': username = getopt.getOptarg(); SecurityAssociation.setPrincipal(new SimplePrincipal(username)); break; case 'p': password = getopt.getOptarg(); SecurityAssociation.setCredential(password); break; } } InitialContext ctx; // If there was a username specified, but no password prompt for it if( username != null && password == null ) { System.out.print("Enter password for "+username+": "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); password = br.readLine(); SecurityAssociation.setCredential(password); } if (serverURL == null) { Properties props = new Properties(); props.setProperty( "java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory" ); props.setProperty( "java.naming.provider.url", "127.0.0.1:1099" ); props.setProperty( "java.naming.factory.url.pkgs", "org.jboss.naming" ); ctx = new InitialContext(props); } else { //not tested Properties props = new Properties(); props.setProperty( "java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory" ); props.setProperty( "java.naming.provider.url", serverURL ); props.setProperty( "java.naming.factory.url.pkgs", "org.jboss.naming" ); props.put(NamingContext.JNP_DISABLE_DISCOVERY, "true"); ctx = new InitialContext(props); } Object obj = ctx.lookup(adapterName); if (!(obj instanceof MBeanServerConnection)) { throw new RuntimeException("Object not of type: MBeanServerConnection, but: " + (obj == null ? "not found" : obj.getClass().getName())); } MBeanServerConnection adaptor = (MBeanServerConnection) obj; ServerProxyHandler handler = new ServerProxyHandler(adaptor, serverJMXName); Class[] ifaces = {ContainerOperations.class}; ClassLoader tcl = Thread.currentThread().getContextClassLoader(); ContainerOperations server = (ContainerOperations) Proxy.newProxyInstance(tcl, ifaces, handler); server.terminateContainer(); System.out.println("Shutdown message has been posted to the server."); System.out.println("Server shutdown may take a while - check logfiles for completion"); } private static class ServerProxyHandler implements InvocationHandler { ObjectName serverName; MBeanServerConnection server; ServerProxyHandler(MBeanServerConnection server, ObjectName serverName) { this.server = server; this.serverName = serverName; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); Class[] sigTypes = method.getParameterTypes(); ArrayList sigStrings = new ArrayList(); for(int s = 0; s < sigTypes.length; s ++) sigStrings.add(sigTypes[s].getName()); String[] sig = new String[sigTypes.length]; sigStrings.toArray(sig); Object value = null; try { value = server.invoke(serverName, methodName, args, sig); } catch(UndeclaredThrowableException e) { System.out.println("getUndeclaredThrowable: "+e.getUndeclaredThrowable()); throw e.getUndeclaredThrowable(); } return value; } } }
Java
package org.mobicents.tests.diameter.sh; import java.io.InputStream; import org.apache.log4j.Level; import org.jdiameter.api.Answer; import org.jdiameter.api.ApplicationId; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpDataException; import org.jdiameter.api.AvpSet; import org.jdiameter.api.IllegalDiameterStateException; import org.jdiameter.api.InternalException; import org.jdiameter.api.Network; import org.jdiameter.api.OverloadException; import org.jdiameter.api.Request; import org.jdiameter.api.RouteException; import org.jdiameter.api.app.AppAnswerEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.app.StateChangeListener; import org.jdiameter.api.sh.ClientShSession; import org.jdiameter.api.sh.ClientShSessionListener; import org.jdiameter.api.sh.ServerShSession; import org.jdiameter.api.sh.ServerShSessionListener; import org.jdiameter.api.sh.events.ProfileUpdateAnswer; import org.jdiameter.api.sh.events.ProfileUpdateRequest; import org.jdiameter.api.sh.events.PushNotificationAnswer; import org.jdiameter.api.sh.events.PushNotificationRequest; import org.jdiameter.api.sh.events.SubscribeNotificationsAnswer; import org.jdiameter.api.sh.events.SubscribeNotificationsRequest; import org.jdiameter.api.sh.events.UserDataAnswer; import org.jdiameter.api.sh.events.UserDataRequest; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.client.impl.app.sh.ShClientSessionImpl; import org.jdiameter.common.api.app.IAppSessionFactory; import org.jdiameter.common.api.app.sh.IShMessageFactory; import org.jdiameter.common.impl.app.sh.ProfileUpdateAnswerImpl; import org.jdiameter.common.impl.app.sh.ProfileUpdateRequestImpl; import org.jdiameter.common.impl.app.sh.PushNotificationAnswerImpl; import org.jdiameter.common.impl.app.sh.PushNotificationRequestImpl; import org.jdiameter.common.impl.app.sh.ShSessionFactoryImpl; import org.jdiameter.common.impl.app.sh.SubscribeNotificationsAnswerImpl; import org.jdiameter.common.impl.app.sh.SubscribeNotificationsRequestImpl; import org.jdiameter.common.impl.app.sh.UserDataAnswerImpl; import org.jdiameter.common.impl.app.sh.UserDataRequestImpl; import org.jdiameter.server.impl.app.sh.ShServerSessionImpl; import org.mobicents.tests.diameter.AbstractStackRunner; public class SH extends AbstractStackRunner implements ServerShSessionListener, ClientShSessionListener, StateChangeListener<AppSession>, IShMessageFactory { private ApplicationId shAuthApplicationId = ApplicationId.createByAuthAppId(10415, 16777217); private ShSessionFactoryImpl shSessionFactory; public SH() { super(); // TODO Auto-generated constructor stub } @Override public void configure(InputStream f) throws Exception { // TODO Auto-generated method stub super.configure(f); this.shSessionFactory = new ShSessionFactoryImpl(super.factory); this.shSessionFactory.setClientShSessionListener(this); this.shSessionFactory.setServerShSessionListener(this); Network network = stack.unwrap(Network.class); network.addNetworkReqListener(this, shAuthApplicationId); ((ISessionFactory) super.factory).registerAppFacory(ServerShSession.class, this.shSessionFactory); ((ISessionFactory) super.factory).registerAppFacory(ClientShSession.class, this.shSessionFactory); } public Answer processRequest(Request request) { int commandCode = request.getCommandCode(); if (commandCode != 308 && commandCode != 306 && commandCode != 309) { if (log.isEnabledFor(Level.ERROR)) { log.error("Received command with wrong code: " + commandCode); super.dumpMessage(request, false); } return null; } if (commandCode == 308 || commandCode == 306) { try { ShServerSessionImpl session = ((ISessionFactory) super.factory).getNewAppSession(request.getSessionId(), shAuthApplicationId, ServerShSession.class, null); // session. session.addStateChangeNotification(this); session.processRequest(request); } catch (InternalException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { try { ShClientSessionImpl session = ((ISessionFactory) super.factory).getNewAppSession(request.getSessionId(), shAuthApplicationId, ClientShSession.class, null); // session. session.processRequest(request); session.addStateChangeNotification(this); } catch (InternalException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; } public void receivedSuccessMessage(Request arg0, Answer arg1) { // we should not do that if (super.log.isEnabledFor(Level.ERROR)) { super.log.error("Received answer"); dumpMessage(arg1, false); new Exception().printStackTrace(); } } public void timeoutExpired(Request arg0) { if (super.log.isInfoEnabled()) { super.log.info("Timeout expired"); dumpMessage(arg0, true); } } public void doOtherEvent(AppSession arg0, AppRequestEvent arg1, AppAnswerEvent arg2) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } public void doProfileUpdateRequestEvent(ServerShSession arg0, ProfileUpdateRequest arg1) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } public void doPushNotificationAnswerEvent(ServerShSession arg0, PushNotificationRequest arg1, PushNotificationAnswer arg2) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { if (log.isEnabledFor(Level.DEBUG)) { log.error("Received PNA"); super.dumpMessage(arg1.getMessage(), false); } } public void doSubscribeNotificationsRequestEvent(ServerShSession appSession, SubscribeNotificationsRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { try { // create answer, we will do that always Answer answer = (Answer) super.createAnswer((Request) request.getMessage(), 2001, this.shAuthApplicationId); AvpSet set = answer.getAvps(); // Auth-Session-State set.addAvp(277, 0); if (log.isDebugEnabled()) { log.info("Recievend SNR in App Session."); super.dumpMessage(request.getMessage(), false); log.info("Sending SNA in App Session."); super.dumpMessage(answer, true); } appSession.sendSubscribeNotificationsAnswer((SubscribeNotificationsAnswer) this.createSubscribeNotificationsAnswer(answer)); // if we have subscribe, we need to send PNR set = request.getMessage().getAvps(); Avp a = set.getAvp(705, 10415L); if (a == null) { if (log.isEnabledFor(Level.ERROR)) { log.error("No subs req type!!"); } return; } int v = -1; try { v = a.getInteger32(); } catch (AvpDataException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (v == 0) { // other side waits for PNR try { Request pnrRaw = appSession.getSessions().get(0).createRequest(309, this.shAuthApplicationId, request.getOriginRealm(), request.getOriginHost()); set = pnrRaw.getAvps(); // Auth-Session-State set.addAvp(277, 0); // User-Identity set.addAvp(request.getMessage().getAvps().getAvp(700, 10415L)); // User-Data set.addAvp(702, "XXXXXXXX", 10415L, true, false, true); appSession.sendPushNotificationRequest((PushNotificationRequest) this.createPushNotificationRequest(pnrRaw)); } catch (AvpDataException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } } public void doUserDataRequestEvent(ServerShSession appSession, UserDataRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { try { // create answer, we will do that always Answer answer = (Answer) super.createAnswer((Request) request.getMessage(), 2001, this.shAuthApplicationId); AvpSet set = answer.getAvps(); // Auth-Session-State set.addAvp(277, 0); if (log.isDebugEnabled()) { log.info("Recievend UDR in App Session."); super.dumpMessage(request.getMessage(), false); log.info("Sending UDA in App Session."); super.dumpMessage(answer, true); } appSession.sendUserDataAnswer((UserDataAnswer) this.createUserDataAnswer(answer)); } catch (Exception e) { e.printStackTrace(); } } // ////////////////// // Client methods // // ////////////////// public void doProfileUpdateAnswerEvent(ClientShSession arg0, ProfileUpdateRequest arg1, ProfileUpdateAnswer arg2) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } public void doPushNotificationRequestEvent(ClientShSession appSession, PushNotificationRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { try { // create answer, we will do that always Answer answer = (Answer) super.createAnswer((Request) request.getMessage(), 2001, this.shAuthApplicationId); AvpSet set = answer.getAvps(); // Auth-Session-State set.addAvp(277, 0); if (log.isDebugEnabled()) { log.info("Recievend PNR in App Session."); super.dumpMessage(request.getMessage(), false); log.info("Sending PNA in App Session."); super.dumpMessage(answer, true); } appSession.sendPushNotificationAnswer((PushNotificationAnswer) this.createPushNotificationAnswer(answer)); } catch (Exception e) { e.printStackTrace(); } } public void doSubscribeNotificationsAnswerEvent(ClientShSession arg0, SubscribeNotificationsRequest arg1, SubscribeNotificationsAnswer arg2) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } public void doUserDataAnswerEvent(ClientShSession arg0, UserDataRequest arg1, UserDataAnswer arg2) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } public void stateChanged(Enum arg0, Enum arg1) { if (log.isDebugEnabled()) { log.debug("State changed from[" + arg0 + "] to[" + arg1 + "]"); } } public void stateChanged(AppSession source, Enum arg0, Enum arg1) { this.stateChanged(arg0, arg1); } public AppAnswerEvent createProfileUpdateAnswer(Answer answer) { return new ProfileUpdateAnswerImpl(answer); } public AppRequestEvent createProfileUpdateRequest(Request request) { return new ProfileUpdateRequestImpl(request); } public AppAnswerEvent createPushNotificationAnswer(Answer answer) { return new PushNotificationAnswerImpl(answer); } public AppRequestEvent createPushNotificationRequest(Request request) { return new PushNotificationRequestImpl(request); } public AppAnswerEvent createSubscribeNotificationsAnswer(Answer answer) { return new SubscribeNotificationsAnswerImpl(answer); } public AppRequestEvent createSubscribeNotificationsRequest(Request request) { return new SubscribeNotificationsRequestImpl(request); } public AppAnswerEvent createUserDataAnswer(Answer answer) { return new UserDataAnswerImpl(answer); } public AppRequestEvent createUserDataRequest(Request request) { return new UserDataRequestImpl(request); } public long getApplicationId() { return this.shAuthApplicationId.getAuthAppId(); } public long getMessageTimeout() { // TODO Auto-generated method stub return 5000; } }
Java
/** * */ package org.mobicents.tests.diameter.base.acr; import static org.jdiameter.common.api.app.acc.ServerAccSessionState.IDLE; import java.io.InputStream; import org.apache.log4j.Level; import org.jdiameter.api.Answer; import org.jdiameter.api.ApplicationId; import org.jdiameter.api.AvpDataException; import org.jdiameter.api.AvpSet; import org.jdiameter.api.IllegalDiameterStateException; import org.jdiameter.api.InternalException; import org.jdiameter.api.Message; import org.jdiameter.api.Network; import org.jdiameter.api.OverloadException; import org.jdiameter.api.Request; import org.jdiameter.api.RouteException; import org.jdiameter.api.acc.ServerAccSession; import org.jdiameter.api.acc.ServerAccSessionListener; import org.jdiameter.api.acc.events.AccountRequest; import org.jdiameter.api.app.AppAnswerEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.app.StateChangeListener; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.common.impl.app.acc.AccSessionFactoryImpl; import org.jdiameter.common.impl.app.acc.AccountAnswerImpl; import org.jdiameter.server.impl.app.acc.ServerAccSessionImpl; import org.mobicents.tests.diameter.AbstractStackRunner; /** * @author baranowb * */ public class ACR extends AbstractStackRunner implements ServerAccSessionListener { private ApplicationId acrAppId = ApplicationId.createByAccAppId(193, 19302); private AccSessionFactoryImpl accSessionFactory; public ACR() { super(); // TODO Auto-generated constructor stub } @Override public void configure(InputStream f) throws Exception { // TODO Auto-generated method stub super.configure(f); // we must add ourselves Network network = stack.unwrap(Network.class); network.addNetworkReqListener(this, acrAppId); accSessionFactory = new AccSessionFactoryImpl(super.factory); accSessionFactory.setServerSessionListener(this); ((ISessionFactory) super.factory).registerAppFacory(ServerAccSession.class, accSessionFactory); } public Answer processRequest(Request request) { // here we should get ACR, and respond with ACA if (request.getCommandCode() != 271) { if (super.log.isEnabledFor(Level.ERROR)) { super.log.error("Received non ACR message, discarding."); dumpMessage(request, false); } return null; } ApplicationId appId = request.getApplicationIdAvps().isEmpty() ? null : request.getApplicationIdAvps().iterator().next(); try { // msg is processed as part of creation in this case. ServerAccSession session = ((ISessionFactory) stack.getSessionFactory()).getNewAppSession(request.getSessionId(), appId, ServerAccSession.class, request); session.addStateChangeNotification(new LocalStateChangeListener(session)); ((ServerAccSessionImpl)session).processRequest(request); } catch (InternalException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalDiameterStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public void receivedSuccessMessage(Request arg0, Answer arg1) { // we should not do that if (super.log.isEnabledFor(Level.ERROR)) { super.log.error("Received answer"); dumpMessage(arg1, false); } } public void timeoutExpired(Request arg0) { if (super.log.isInfoEnabled()) { super.log.info("Timeout expired"); dumpMessage(arg0, true); } } // ACR listener methods. public void doAccRequestEvent(ServerAccSession session, AccountRequest arg1) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // this is called when app session is created. Message answer = super.createAnswer((Request) arg1.getMessage(), 2001, arg1.getMessage().getApplicationIdAvps().iterator().next()); AvpSet set = answer.getAvps(); // { Accounting-Record-Type } try { set.addAvp(480, arg1.getAccountingRecordType()); } catch (AvpDataException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // { Accounting-Record-Number } try { set.addAvp(485, arg1.getAccountingRecordNumber(), true); } catch (AvpDataException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // hack. for Seagull to work..... try { AvpSet vendorSpecificApplicationId = set.getAvp(260).getGrouped(); // zero auth app id. vendorSpecificApplicationId.addAvp(258, 0l, true); } catch (AvpDataException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (log.isInfoEnabled()) { log .info("Received Request: " + ((Request) arg1.getMessage()).getCommandCode() + "\nE2E:" + ((Request) arg1.getMessage()).getEndToEndIdentifier() + "\nHBH:" + ((Request) arg1.getMessage()).getHopByHopIdentifier() + "\nAppID:" + ((Request) arg1.getMessage()).getApplicationId()); log.info("Request AVPS: \n"); try { printAvps(((Request) arg1.getMessage()).getAvps()); } catch (AvpDataException e) { // TODO Auto-generated catch block e.printStackTrace(); } log.info("Created answer: " + answer.getCommandCode() + "\nE2E:" + answer.getEndToEndIdentifier() + "\nHBH:" + answer.getHopByHopIdentifier() + "\nAppID:" + answer.getApplicationId()); log.info("Answer AVPS: \n"); try { printAvps(answer.getAvps()); } catch (AvpDataException e) { // TODO Auto-generated catch block e.printStackTrace(); } } AccountAnswerImpl ans = new AccountAnswerImpl((Answer) answer); session.sendAccountAnswer(ans); } public void doOtherEvent(AppSession arg0, AppRequestEvent arg1, AppAnswerEvent arg2) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } private class LocalStateChangeListener implements StateChangeListener<AppSession> { private ServerAccSession session; public LocalStateChangeListener(ServerAccSession session) { super(); this.session = session; } public void stateChanged(Enum oldState, Enum newState) { if (session.isStateless() && newState == IDLE) { session.release(); } if (log.isInfoEnabled()) { log.info("Application changed state from[" + oldState + "] to[" + newState + "]"); } } public void stateChanged(AppSession source, Enum oldState, Enum newState) { this.stateChanged(oldState, newState); } } }
Java
package org.mobicents.tests.diameter.cca; import java.io.InputStream; import java.util.concurrent.ScheduledFuture; import org.apache.log4j.Level; import org.jdiameter.api.Answer; import org.jdiameter.api.ApplicationId; import org.jdiameter.api.AvpDataException; import org.jdiameter.api.AvpSet; import org.jdiameter.api.EventListener; import org.jdiameter.api.IllegalDiameterStateException; import org.jdiameter.api.InternalException; import org.jdiameter.api.Message; import org.jdiameter.api.Network; import org.jdiameter.api.NetworkReqListener; import org.jdiameter.api.OverloadException; import org.jdiameter.api.Request; import org.jdiameter.api.RouteException; import org.jdiameter.api.app.AppAnswerEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.app.StateChangeListener; import org.jdiameter.api.auth.events.ReAuthAnswer; import org.jdiameter.api.auth.events.ReAuthRequest; import org.jdiameter.api.cca.ClientCCASession; import org.jdiameter.api.cca.ClientCCASessionListener; import org.jdiameter.api.cca.ServerCCASession; import org.jdiameter.api.cca.ServerCCASessionListener; import org.jdiameter.api.cca.events.JCreditControlAnswer; import org.jdiameter.api.cca.events.JCreditControlRequest; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.client.impl.app.cca.ClientCCASessionImpl; import org.jdiameter.common.api.app.IAppSessionFactory; import org.jdiameter.common.api.app.cca.ICCAMessageFactory; import org.jdiameter.common.api.app.cca.IClientCCASessionContext; import org.jdiameter.common.api.app.cca.IServerCCASessionContext; import org.jdiameter.common.api.app.cca.ServerCCASessionState; import org.jdiameter.common.impl.app.auth.ReAuthAnswerImpl; import org.jdiameter.common.impl.app.auth.ReAuthRequestImpl; import org.jdiameter.common.impl.app.cca.CCASessionFactoryImpl; import org.jdiameter.common.impl.app.cca.JCreditControlAnswerImpl; import org.jdiameter.common.impl.app.cca.JCreditControlRequestImpl; import org.jdiameter.server.impl.app.cca.ServerCCASessionImpl; import org.mobicents.tests.diameter.AbstractStackRunner; public class CCR extends AbstractStackRunner implements NetworkReqListener, EventListener<Request, Answer>, ServerCCASessionListener, IServerCCASessionContext, StateChangeListener<AppSession> { protected boolean isEventBased = true; protected ApplicationId authApplicationId = ApplicationId.createByAuthAppId(0, 4); // its miliseconds protected long messageTimeout = 5000; protected int defaultDirectDebitingFailureHandling = 0; protected int defaultCreditControlFailureHandling = 0; // its seconds protected long defaultValidityTime = 30; protected long defaultTxTimerValue = 10; protected CCASessionFactoryImpl ccaSessionFactory; public CCR() { super(); } @Override public void configure(InputStream f) throws Exception { // TODO Auto-generated method stub super.configure(f); this.ccaSessionFactory = new CCASessionFactoryImpl(super.factory); this.ccaSessionFactory.setServerSessionListener(this); this.ccaSessionFactory.setServerContextListener(this); Network network = stack.unwrap(Network.class); network.addNetworkReqListener(this, authApplicationId); ((ISessionFactory) super.factory).registerAppFacory(ServerCCASession.class, ccaSessionFactory); } public void doCreditControlRequest(ServerCCASession session, JCreditControlRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { if (log.isInfoEnabled()) { log.info("Received Request: " + ((Request) request.getMessage()).getCommandCode() + "\nE2E:" + ((Request) request.getMessage()).getEndToEndIdentifier() + "\nHBH:" + ((Request) request.getMessage()).getHopByHopIdentifier() + "\nAppID:" + ((Request) request.getMessage()).getApplicationId()); log.info("Request AVPS: \n"); try { printAvps(((Request) request.getMessage()).getAvps()); } catch (AvpDataException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { // INITIAL_REQUEST 1,UPDATE_REQUEST 2,TERMINATION_REQUEST // 3,EVENT_REQUEST 4 JCreditControlAnswer answer = null; switch (request.getRequestTypeAVPValue()) { case 1: JCreditControlAnswerImpl local = new JCreditControlAnswerImpl((Request) request.getMessage(), 2000); answer = local; AvpSet reqSet = request.getMessage().getAvps(); AvpSet set = local.getMessage().getAvps(); int c = 0; set.removeAvp(293); set.removeAvp(283); // set.removeAvp(296); // set.removeAvp(264); // set.addAvp(296,"mobicents.org",true); // set.addAvp(264,"aaa://192.168.1.103:3868",true); set.addAvp(reqSet.getAvp(416), reqSet.getAvp(415), reqSet.getAvp(258)); if (answer != null) { if (log.isInfoEnabled()) { log.info("Created answer: " + answer.getCommandCode() + "\nE2E:" + answer.getMessage().getEndToEndIdentifier() + "\nHBH:" + answer.getMessage().getHopByHopIdentifier() + "\nAppID:" + answer.getMessage().getApplicationId()); log.info("Answer AVPS: \n"); try { printAvps(answer.getMessage().getAvps()); } catch (AvpDataException e) { // TODO Auto-generated catch block e.printStackTrace(); } } session.sendCreditControlAnswer(answer); } break; case 2: local = new JCreditControlAnswerImpl((Request) request.getMessage(), 2000); answer = local; reqSet = request.getMessage().getAvps(); set = local.getMessage().getAvps(); c = 0; set.removeAvp(293); set.removeAvp(283); // set.removeAvp(296); // set.removeAvp(264); // set.addAvp(296,"mobicents.org",true); // set.addAvp(264,"aaa://192.168.1.103:3868",true); set.addAvp(reqSet.getAvp(416), reqSet.getAvp(415), reqSet.getAvp(258)); if (answer != null) { if (log.isInfoEnabled()) { log.info("Created answer: " + answer.getCommandCode() + "\nE2E:" + answer.getMessage().getEndToEndIdentifier() + "\nHBH:" + answer.getMessage().getHopByHopIdentifier() + "\nAppID:" + answer.getMessage().getApplicationId()); log.info("Answer AVPS: \n"); try { printAvps(answer.getMessage().getAvps()); } catch (AvpDataException e) { // TODO Auto-generated catch block e.printStackTrace(); } } session.sendCreditControlAnswer(answer); } break; case 3: local = new JCreditControlAnswerImpl((Request) request.getMessage(), 2000); answer = local; reqSet = request.getMessage().getAvps(); set = local.getMessage().getAvps(); c = 0; set.removeAvp(293); set.removeAvp(283); // set.removeAvp(296); // set.removeAvp(264); // set.addAvp(296,"mobicents.org",true); // set.addAvp(264,"aaa://192.168.1.103:3868",true); set.addAvp(reqSet.getAvp(416), reqSet.getAvp(415), reqSet.getAvp(258)); if (answer != null) { if (log.isInfoEnabled()) { log.info("Created answer: " + answer.getCommandCode() + "\nE2E:" + answer.getMessage().getEndToEndIdentifier() + "\nHBH:" + answer.getMessage().getHopByHopIdentifier() + "\nAppID:" + answer.getMessage().getApplicationId()); log.info("Answer AVPS: \n"); try { printAvps(answer.getMessage().getAvps()); } catch (AvpDataException e) { // TODO Auto-generated catch block e.printStackTrace(); } } session.sendCreditControlAnswer(answer); } break; case 4: local = new JCreditControlAnswerImpl((Request) request.getMessage(), 2000); answer = local; reqSet = request.getMessage().getAvps(); set = local.getMessage().getAvps(); c = 0; set.removeAvp(293); set.removeAvp(283); // set.removeAvp(296); // set.removeAvp(264); // set.addAvp(296,"mobicents.org",true); // set.addAvp(264,"aaa://192.168.1.103:3868",true); set.addAvp(reqSet.getAvp(416), reqSet.getAvp(415), reqSet.getAvp(258)); if (answer != null) { if (log.isInfoEnabled()) { log.info("Created answer: " + answer.getCommandCode() + "\nE2E:" + answer.getMessage().getEndToEndIdentifier() + "\nHBH:" + answer.getMessage().getHopByHopIdentifier() + "\nAppID:" + answer.getMessage().getApplicationId()); log.info("Answer AVPS: \n"); try { printAvps(answer.getMessage().getAvps()); } catch (AvpDataException e) { // TODO Auto-generated catch block e.printStackTrace(); } } session.sendCreditControlAnswer(answer); } break; default: if (log.isEnabledFor(Level.ERROR)) { log.error("No REQ type present?: " + request.getRequestTypeAVPValue()); } } } catch (Exception e) { e.printStackTrace(); } } /* (non-Javadoc) * @see org.jdiameter.api.app.StateChangeListener#stateChanged(java.lang.Object, java.lang.Enum, java.lang.Enum) */ public void stateChanged(AppSession source, Enum oldState, Enum newState) { this.stateChanged(oldState, newState); } public void stateChanged(Enum oldState, Enum newState) { if (log.isInfoEnabled()) { log.info("Diameter CCA SessionFactory :: stateChanged :: oldState[" + oldState + "], newState[" + newState + "]"); } } // //////////////////// // GENERIC HANDLERS // // //////////////////// public Answer processRequest(Request request) { if (request.getCommandCode() != 272) { if (super.log.isEnabledFor(Level.ERROR)) { // super.log.error("Received non CCR message, discarding: " + // toString(request)); super.dumpMessage(request, false); } return null; } if (log.isInfoEnabled()) { log.info("===Received=== Request: " + request.getCommandCode() + "\nE2E:" + request.getEndToEndIdentifier() + "\nHBH:" + request.getHopByHopIdentifier() + "\nAppID:" + request.getApplicationId()); log.info("Request AVPS: \n"); try { printAvps(request.getAvps()); } catch (AvpDataException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { ServerCCASessionImpl session = ((ISessionFactory) super.factory).getNewAppSession(request.getSessionId(), ApplicationId .createByAuthAppId(0, 4), ServerCCASession.class, null); // session. session.addStateChangeNotification(this); session.processRequest(request); } catch (InternalException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public long[] getApplicationIds() { // FIXME: ??? return new long[] { 4 }; } public long getDefaultValidityTime() { return this.defaultValidityTime; } public JCreditControlAnswer createCreditControlAnswer(Answer answer) { return new JCreditControlAnswerImpl(answer); } public JCreditControlRequest createCreditControlRequest(Request req) { return new JCreditControlRequestImpl(req); } public ReAuthAnswer createReAuthAnswer(Answer answer) { return new ReAuthAnswerImpl(answer); } public ReAuthRequest createReAuthRequest(Request req) { return new ReAuthRequestImpl(req); } // ///////////////////// // // CONTEXT METHODS // < - we dont care about them // ///////////////////// public void sessionSupervisionTimerReStarted(ServerCCASession session, ScheduledFuture future) { // TODO Auto-generated method stub } public void sessionSupervisionTimerStarted(ServerCCASession session, ScheduledFuture future) { // TODO Auto-generated method stub } public void sessionSupervisionTimerStopped(ServerCCASession session, ScheduledFuture future) { // TODO Auto-generated method stub } public void timeoutExpired(Request request) { // FIXME ??? } public void denyAccessOnDeliverFailure(ClientCCASession clientCCASessionImpl, Message request) { // TODO Auto-generated method stub } public void denyAccessOnFailureMessage(ClientCCASession clientCCASessionImpl) { // TODO Auto-generated method stub } public int getDefaultCCFHValue() { return defaultCreditControlFailureHandling; } public int getDefaultDDFHValue() { return defaultDirectDebitingFailureHandling; } public long getDefaultTxTimerValue() { return defaultTxTimerValue; } public void grantAccessOnDeliverFailure(ClientCCASession clientCCASessionImpl, Message request) { // TODO Auto-generated method stub } public void grantAccessOnFailureMessage(ClientCCASession clientCCASessionImpl) { // TODO Auto-generated method stub } public void grantAccessOnTxExpire(ClientCCASession clientCCASessionImpl) { // TODO Auto-generated method stub } public void indicateServiceError(ClientCCASession clientCCASessionImpl) { // TODO Auto-generated method stub } public void receivedSuccessMessage(Request request, Answer answer) { } public void doCreditControlAnswer(ClientCCASession arg0, JCreditControlRequest arg1, JCreditControlAnswer arg2) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } public void doOtherEvent(AppSession arg0, AppRequestEvent arg1, AppAnswerEvent arg2) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } public void doReAuthRequest(ClientCCASession arg0, ReAuthRequest arg1) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } public void doReAuthAnswer(ServerCCASession arg0, ReAuthRequest arg1, ReAuthAnswer arg2) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } public void sessionSupervisionTimerExpired(ServerCCASession arg0) { // TODO Auto-generated method stub } public void denyAccessOnTxExpire(ClientCCASession arg0) { // TODO Auto-generated method stub } public void txTimerExpired(ClientCCASession arg0) { // TODO Auto-generated method stub } }
Java
package org.mobicents.tests.diameter.cxdx; import java.io.File; import java.io.InputStream; import org.apache.log4j.Level; import org.jdiameter.api.Answer; import org.jdiameter.api.ApplicationId; import org.jdiameter.api.AvpSet; import org.jdiameter.api.IllegalDiameterStateException; import org.jdiameter.api.InternalException; import org.jdiameter.api.Network; import org.jdiameter.api.OverloadException; import org.jdiameter.api.Request; import org.jdiameter.api.RouteException; import org.jdiameter.api.app.AppAnswerEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.app.StateChangeListener; import org.jdiameter.api.cxdx.ClientCxDxSession; import org.jdiameter.api.cxdx.ClientCxDxSessionListener; import org.jdiameter.api.cxdx.ServerCxDxSession; import org.jdiameter.api.cxdx.ServerCxDxSessionListener; import org.jdiameter.api.cxdx.events.JLocationInfoAnswer; import org.jdiameter.api.cxdx.events.JLocationInfoRequest; import org.jdiameter.api.cxdx.events.JMultimediaAuthAnswer; import org.jdiameter.api.cxdx.events.JMultimediaAuthRequest; import org.jdiameter.api.cxdx.events.JPushProfileAnswer; import org.jdiameter.api.cxdx.events.JPushProfileRequest; import org.jdiameter.api.cxdx.events.JRegistrationTerminationAnswer; import org.jdiameter.api.cxdx.events.JRegistrationTerminationRequest; import org.jdiameter.api.cxdx.events.JServerAssignmentAnswer; import org.jdiameter.api.cxdx.events.JServerAssignmentRequest; import org.jdiameter.api.cxdx.events.JUserAuthorizationAnswer; import org.jdiameter.api.cxdx.events.JUserAuthorizationRequest; import org.jdiameter.api.sh.ClientShSession; import org.jdiameter.api.sh.ServerShSession; import org.jdiameter.api.sh.events.UserDataAnswer; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.client.impl.app.cxdx.CxDxClientSessionImpl; import org.jdiameter.common.api.app.IAppSessionFactory; import org.jdiameter.common.api.app.cxdx.CxDxSessionState; import org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory; import org.jdiameter.common.impl.app.cxdx.CxDxSessionFactoryImpl; import org.jdiameter.common.impl.app.cxdx.JLocationInfoAnswerImpl; import org.jdiameter.common.impl.app.cxdx.JLocationInfoRequestImpl; import org.jdiameter.common.impl.app.cxdx.JMultimediaAuthAnswerImpl; import org.jdiameter.common.impl.app.cxdx.JMultimediaAuthRequestImpl; import org.jdiameter.common.impl.app.cxdx.JPushProfileAnswerImpl; import org.jdiameter.common.impl.app.cxdx.JPushProfileRequestImpl; import org.jdiameter.common.impl.app.cxdx.JRegistrationTerminationAnswerImpl; import org.jdiameter.common.impl.app.cxdx.JRegistrationTerminationRequestImpl; import org.jdiameter.common.impl.app.cxdx.JServerAssignmentAnswerImpl; import org.jdiameter.common.impl.app.cxdx.JServerAssignmentRequestImpl; import org.jdiameter.common.impl.app.cxdx.JUserAuthorizationAnswerImpl; import org.jdiameter.common.impl.app.cxdx.JUserAuthorizationRequestImpl; import org.jdiameter.server.impl.app.cxdx.CxDxServerSessionImpl; import org.mobicents.tests.diameter.AbstractStackRunner; public class CXDX extends AbstractStackRunner implements ServerCxDxSessionListener,ClientCxDxSessionListener, StateChangeListener<AppSession>, ICxDxMessageFactory{ private ApplicationId cxdxAuthApplicationId = ApplicationId.createByAuthAppId(10415, 16777216); private CxDxSessionFactoryImpl cxdxSessionFactory; public CXDX() { super(); // TODO Auto-generated constructor stub } @Override public void configure(InputStream f) throws Exception { // TODO Auto-generated method stub super.configure(f); this.cxdxSessionFactory = new CxDxSessionFactoryImpl(super.factory); this.cxdxSessionFactory.setClientSessionListener(this); this.cxdxSessionFactory.setServerSessionListener(this); Network network = stack.unwrap(Network.class); network.addNetworkReqListener(this, cxdxAuthApplicationId); ((ISessionFactory) super.factory).registerAppFacory(ClientCxDxSession.class, cxdxSessionFactory); ((ISessionFactory) super.factory).registerAppFacory(ServerCxDxSession.class, cxdxSessionFactory); } public Answer processRequest(Request request) { //if we act as server, we will get UserAuthorizationRequest == 300 int commandCode = request.getCommandCode(); if(commandCode == 300) { //we act as server try { CxDxServerSessionImpl session = ((ISessionFactory) super.factory).getNewAppSession(request.getSessionId(), cxdxAuthApplicationId, ServerCxDxSession.class, null); session.addStateChangeNotification(this); session.processRequest(request); return null; } catch (InternalException e) { // TODO Auto-generated catch block e.printStackTrace(); } //Client RTR }else if(commandCode == 304) { try { CxDxClientSessionImpl session = ((ISessionFactory) super.factory).getNewAppSession(request.getSessionId(), cxdxAuthApplicationId, ClientCxDxSession.class, null); session.addStateChangeNotification(this); session.processRequest(request); return null; } catch (InternalException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; } public void receivedSuccessMessage(Request arg0, Answer arg1) { //we should not do that if(super.log.isEnabledFor(Level.ERROR)) { super.log.error("Received answer"); dumpMessage(arg1,false); } } public void timeoutExpired(Request arg0) { if(super.log.isInfoEnabled()) { super.log.info("Timeout expired"); dumpMessage(arg0,true); } } /* (non-Javadoc) * @see org.jdiameter.api.app.StateChangeListener#stateChanged(java.lang.Object, java.lang.Enum, java.lang.Enum) */ public void stateChanged(AppSession source, Enum oldState, Enum newState) { this.stateChanged(oldState, newState); } public void stateChanged(Enum oldState, Enum newState) { if (log.isInfoEnabled()) { log.info("Diameter CCA SessionFactory :: stateChanged :: oldState[" + oldState + "], newState[" + newState + "]"); } } public void doLocationInformationRequest(ServerCxDxSession arg0, JLocationInfoRequest arg1) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } public void doMultimediaAuthRequest(ServerCxDxSession arg0, JMultimediaAuthRequest arg1) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } public void doOtherEvent(AppSession arg0, AppRequestEvent arg1, AppAnswerEvent arg2) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } public void doPushProfileAnswer(ServerCxDxSession arg0, JPushProfileRequest arg1, JPushProfileAnswer arg2) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } public void doRegistrationTerminationAnswer(ServerCxDxSession arg0, JRegistrationTerminationRequest arg1, JRegistrationTerminationAnswer arg2) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } public void doServerAssignmentRequest(ServerCxDxSession arg0, JServerAssignmentRequest arg1) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } public void doUserAuthorizationRequest(ServerCxDxSession appSession, JUserAuthorizationRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { //we simply answer try { // create answer, we will do that always Answer answer = (Answer) super.createAnswer((Request) request.getMessage(), 2001, this.cxdxAuthApplicationId); AvpSet set = answer.getAvps(); // Auth-Session-State set.addAvp(277, 0); if (log.isDebugEnabled()) { log.info("Recievend UAR in App Session."); super.dumpMessage(request.getMessage(),false); log.info("Sending UAA in App Session."); super.dumpMessage(answer,true); } appSession.sendUserAuthorizationAnswer((JUserAuthorizationAnswer) this.createUserAuthorizationAnswer(answer)); } catch (Exception e) { e.printStackTrace(); } } public long getApplicationId() { return this.cxdxAuthApplicationId.getAuthAppId(); } public void doLocationInformationAnswer(ClientCxDxSession arg0, JLocationInfoRequest arg1, JLocationInfoAnswer arg2) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } public void doMultimediaAuthAnswer(ClientCxDxSession arg0, JMultimediaAuthRequest arg1, JMultimediaAuthAnswer arg2) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } public void doPushProfileRequest(ClientCxDxSession arg0, JPushProfileRequest arg1) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } public void doRegistrationTerminationRequest(ClientCxDxSession appSession, JRegistrationTerminationRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { //we simply answer try { // create answer, we will do that always Answer answer = (Answer) super.createAnswer((Request) request.getMessage(), 2001, this.cxdxAuthApplicationId); AvpSet set = answer.getAvps(); // Auth-Session-State set.addAvp(277, 0); if (log.isDebugEnabled()) { log.info("Recievend RTR in App Session."); super.dumpMessage(request.getMessage(),false); log.info("Sending RTA in App Session."); super.dumpMessage(answer,true); } appSession.sendRegistrationTerminationAnswer((JRegistrationTerminationAnswer) this.createRegistrationTerminationAnswer(answer)); } catch (Exception e) { e.printStackTrace(); } } public void doServerAssignmentAnswer(ClientCxDxSession arg0, JServerAssignmentRequest arg1, JServerAssignmentAnswer arg2) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } public void doUserAuthorizationAnswer(ClientCxDxSession arg0, JUserAuthorizationRequest arg1, JUserAuthorizationAnswer arg2) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } /* (non-Javadoc) * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createLocationInfoAnswer(org.jdiameter.api.Answer) */ public AppAnswerEvent createLocationInfoAnswer(Answer answer) { return new JLocationInfoAnswerImpl(answer); } /* (non-Javadoc) * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createLocationInfoRequest(org.jdiameter.api.Request) */ public AppRequestEvent createLocationInfoRequest(Request request) { return new JLocationInfoRequestImpl(request); } /* (non-Javadoc) * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createMultimediaAuthAnswer(org.jdiameter.api.Answer) */ public AppAnswerEvent createMultimediaAuthAnswer(Answer answer) { return new JMultimediaAuthAnswerImpl(answer); } /* (non-Javadoc) * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createMultimediaAuthRequest(org.jdiameter.api.Request) */ public AppRequestEvent createMultimediaAuthRequest(Request request) { return new JMultimediaAuthRequestImpl(request); } /* (non-Javadoc) * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createPushProfileAnswer(org.jdiameter.api.Answer) */ public AppAnswerEvent createPushProfileAnswer(Answer answer) { return new JPushProfileAnswerImpl(answer); } /* (non-Javadoc) * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createPushProfileRequest(org.jdiameter.api.Request) */ public AppRequestEvent createPushProfileRequest(Request request) { // TODO Auto-generated method stub return new JPushProfileRequestImpl(request); } /* (non-Javadoc) * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createRegistrationTerminationAnswer(org.jdiameter.api.Answer) */ public AppAnswerEvent createRegistrationTerminationAnswer(Answer answer) { return new JRegistrationTerminationAnswerImpl(answer); } /* (non-Javadoc) * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createRegistrationTerminationRequest(org.jdiameter.api.Request) */ public AppRequestEvent createRegistrationTerminationRequest(Request request) { return new JRegistrationTerminationRequestImpl(request); } /* (non-Javadoc) * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createServerAssignmentAnswer(org.jdiameter.api.Answer) */ public AppAnswerEvent createServerAssignmentAnswer(Answer answer) { return new JServerAssignmentAnswerImpl(answer); } /* (non-Javadoc) * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createServerAssignmentRequest(org.jdiameter.api.Request) */ public AppRequestEvent createServerAssignmentRequest(Request request) { return new JServerAssignmentRequestImpl(request); } /* (non-Javadoc) * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createUserAuthorizationAnswer(org.jdiameter.api.Answer) */ public AppAnswerEvent createUserAuthorizationAnswer(Answer answer) { return new JUserAuthorizationAnswerImpl(answer); } /* (non-Javadoc) * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createUserAuthorizationRequest(org.jdiameter.api.Request) */ public AppRequestEvent createUserAuthorizationRequest(Request request) { return new JUserAuthorizationRequestImpl(request); } }
Java
/** * */ package org.mobicents.tests.diameter; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.log4j.Logger; import org.jdiameter.api.Answer; import org.jdiameter.api.ApplicationId; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpDataException; import org.jdiameter.api.AvpSet; import org.jdiameter.api.Configuration; import org.jdiameter.api.EventListener; import org.jdiameter.api.IllegalDiameterStateException; import org.jdiameter.api.InternalException; import org.jdiameter.api.Message; import org.jdiameter.api.MetaData; import org.jdiameter.api.Network; import org.jdiameter.api.NetworkReqListener; import org.jdiameter.api.Request; import org.jdiameter.api.SessionFactory; import org.jdiameter.api.Stack; import org.jdiameter.api.StackType; import org.jdiameter.client.impl.parser.MessageImpl; import org.jdiameter.client.impl.parser.MessageParser; import org.jdiameter.server.impl.StackImpl; import org.jdiameter.server.impl.helpers.XMLConfiguration; import org.mobicents.diameter.dictionary.AvpDictionary; import org.mobicents.diameter.dictionary.AvpRepresentation; /** * Base class for all soak/cps tests * * @author baranowb * */ public abstract class AbstractStackRunner implements NetworkReqListener, EventListener<Request, Answer> { protected final Logger log = Logger.getLogger(getClass()); //protected static String clientHost = "uac.mobicents.org"; //protected static String clientPort = "13868"; //protected static String clientURI = "aaa://" + clientHost + ":" + clientPort; // protected static String serverHost = "127.0.0.1"; protected static String serverHost = "uas.mobicents.org"; protected static String serverPort = "3868"; protected static String serverURI = "aaa://" + serverHost + ":" + serverPort; protected static String realmName = "mobicents.org"; protected final int[] prefilledAVPs = new int[] { Avp.DESTINATION_HOST, Avp.DESTINATION_REALM, Avp.ORIGIN_HOST, Avp.ORIGIN_REALM, Avp.SESSION_ID, Avp.VENDOR_SPECIFIC_APPLICATION_ID }; protected MessageParser parser = new MessageParser(); protected Stack stack; protected SessionFactory factory; protected InputStream configFile; protected AvpDictionary dictionary = AvpDictionary.INSTANCE; private boolean run = true; /** * */ public AbstractStackRunner() { // TODO Auto-generated constructor stub } public void configure(InputStream f) throws Exception { this.configFile = f; // add more try { dictionary.parseDictionary(this.getClass().getClassLoader().getResourceAsStream("dictionary.xml")); log.info("AVP Dictionary successfully parsed."); } catch (Exception e) { e.printStackTrace(); } initStack(); } private void initStack() { if (log.isInfoEnabled()) { log.info("Initializing Stack..."); } try { this.stack = new StackImpl(); } catch (Exception e) { e.printStackTrace(); stack.destroy(); return; } try { InputStream is; if (configFile != null) { is = this.configFile; } else { String configFile = "jdiameter-config.xml"; is = this.getClass().getClassLoader().getResourceAsStream(configFile); } Configuration config = new XMLConfiguration(is); factory = stack.init(config); if (log.isInfoEnabled()) { log.info("Stack Configuration successfully loaded."); } Network network = stack.unwrap(Network.class); Set<org.jdiameter.api.ApplicationId> appIds = stack.getMetaData().getLocalPeer().getCommonApplications(); log.info("Diameter Stack :: Supporting " + appIds.size() + " applications."); // network.addNetworkReqListener(this, // ApplicationId.createByAccAppId( 193, 19302 )); for (org.jdiameter.api.ApplicationId appId : appIds) { log.info("Diameter Stack Mux :: Adding Listener for [" + appId + "]."); network.addNetworkReqListener(this, appId); } } catch (Exception e) { e.printStackTrace(); stack.destroy(); return; } MetaData metaData = stack.getMetaData(); if (metaData.getStackType() != StackType.TYPE_SERVER || metaData.getMinorVersion() <= 0) { stack.destroy(); if (log.isEnabledFor(org.apache.log4j.Level.ERROR)) { log.error("Incorrect driver"); } return; } try { if (log.isInfoEnabled()) { log.info("Starting stack"); } stack.start(); if (log.isInfoEnabled()) { log.info("Stack is running."); } } catch (Exception e) { e.printStackTrace(); stack.destroy(); return; } if (log.isInfoEnabled()) { log.info("Stack initialization successfully completed."); } } /** * @return the run */ public boolean isRun() { return run; } /** * @param run the run to set */ public void setRun(boolean run) { this.run = run; } public void performTestRun() { log.info("Press 'q' to stop execution"); while (run) { try { Thread.sleep(1000); if (System.in.available() > 0) { int r = System.in.read(); if (r == 'q') { run = false; break; } } } catch (Exception e) { e.printStackTrace(); } } clean(); } protected void clean() { if (stack != null) { try { stack.stop(10, TimeUnit.SECONDS); stack = null; factory = null; } catch (IllegalDiameterStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InternalException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } protected void dumpMessage(Message message, boolean sending) { if (log.isInfoEnabled()) { log.info((sending?"Sending ":"Received ") + (message.isRequest() ? "Request: " : "Answer: ") + message.getCommandCode() + "\nE2E:" + message.getEndToEndIdentifier() + "\nHBH:" + message.getHopByHopIdentifier() + "\nAppID:" + message.getApplicationId()); log.info("Request AVPS: \n"); try { printAvps(message.getAvps()); } catch (AvpDataException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } protected Message createAnswer(Request request, int answerCode, ApplicationId appId) throws InternalException, IllegalDiameterStateException { int commandCode = 0; long endToEndId = 0; long hopByHopId = 0; commandCode = request.getCommandCode(); endToEndId = request.getEndToEndIdentifier(); hopByHopId = request.getHopByHopIdentifier(); Message raw = stack.getSessionFactory().getNewRawSession().createMessage(commandCode, appId, hopByHopId, endToEndId); AvpSet avps = raw.getAvps(); // inser session iD avps.insertAvp(0, 263, request.getSessionId(), false); // add result //asUnsignedInt32 avps.addAvp(268, 2001l, true); // origin host avps.addAvp(264, serverHost, true); // origin realm avps.addAvp(296, realmName, true); raw.setProxiable(true); raw.setRequest(false); // ((MessageImpl)raw).setPeer(((MessageImpl)request).getPeer()); return raw; } protected void printAvps(AvpSet avpSet) throws AvpDataException { printAvpsAux(avpSet, 0); } /** * Prints the AVPs present in an AvpSet with a specified 'tab' level * * @param avpSet * the AvpSet containing the AVPs to be printed * @param level * an int representing the number of 'tabs' to make a pretty * print * @throws AvpDataException */ private void printAvpsAux(AvpSet avpSet, int level) throws AvpDataException { String prefix = " ".substring(0, level * 2); for (Avp avp : avpSet) { AvpRepresentation avpRep = AvpDictionary.INSTANCE.getAvp(avp.getCode(), avp.getVendorId()); if (avpRep != null && avpRep.getType().equals("Grouped")) { log.info(prefix + "<avp name=\"" + avpRep.getName() + "\" code=\"" + avp.getCode() + "\" vendor=\"" + avp.getVendorId() + "\">"); printAvpsAux(avp.getGrouped(), level + 1); log.info(prefix + "</avp>"); } else if (avpRep != null) { String value = ""; if (avpRep.getType().equals("Integer32")) value = String.valueOf(avp.getInteger32()); else if (avpRep.getType().equals("Integer64") || avpRep.getType().equals("Unsigned64")) value = String.valueOf(avp.getInteger64()); else if (avpRep.getType().equals("Unsigned32")) value = String.valueOf(avp.getUnsigned32()); else if (avpRep.getType().equals("Float32")) value = String.valueOf(avp.getFloat32()); else value = avp.getOctetString(); log.info(prefix + "<avp name=\"" + avpRep.getName() + "\" code=\"" + avp.getCode() + "\" vendor=\"" + avp.getVendorId() + "\" value=\"" + value + "\" />"); } } } }
Java
package org.mobicents.tests.diameter; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import gnu.getopt.Getopt; import gnu.getopt.LongOpt; /** * Class which sets up everything for test and waits till test is not * terminated. * * @author baranowb * */ public class CLIRunner { private static final LongOpt[] _LONG_OPTS = new LongOpt[18]; private static final String _GETOPT_PARAMS_STRING = "h:q:w"; private static final Logger log = Logger.getLogger(CLIRunner.class); private static final String _DIA_HOME_DIR = "dia.home.dir"; static { // This should expand, to get all stack props. for nwo its hardcoded. _LONG_OPTS[0] = new LongOpt("usage", LongOpt.NO_ARGUMENT, null, 'h'); _LONG_OPTS[1] = new LongOpt("testclass", LongOpt.REQUIRED_ARGUMENT, null, 'q'); _LONG_OPTS[2] = new LongOpt("config", LongOpt.REQUIRED_ARGUMENT, null, 'w'); //check for dia.home.dir if(System.getenv(_DIA_HOME_DIR) == null && System.getProperty(_DIA_HOME_DIR)==null ) { //this is for cli mode, if we are here, it means we are not run by micocontainer configLog4j(); } } private boolean configured = false; private InputStream configurationFile; private AbstractStackRunner runnerClassInstance; /** * @param args */ public static void main(String[] args) { CLIRunner runner = new CLIRunner(); runner.parseArgs(args); if (runner.isConfigured()) { runner.performTask(); } } private void parseArgs(String[] args) { Getopt getOpt = new Getopt("CLIRunner", args, _GETOPT_PARAMS_STRING, _LONG_OPTS); getOpt.setOpterr(true); int c = -1; String v = null; while ((c = getOpt.getopt()) != -1) { switch (c) { case 'h': usage(); System.exit(0); case 'q': v = getOpt.getOptarg(); setTestClass(v); break; case 'w': v = getOpt.getOptarg(); setConfigurationFile(v); break; default: log.error("Wrong parameter!! ---> " + Character.toString((char) c)); } } } // private void usage() { StringBuffer sb = new StringBuffer(); sb.append("java " + CLIRunner.class.getName() + " [OPTIONS] \n"); sb.append("Where options can be:\n"); sb.append("--usage : prints this message.\n"); sb.append("--testclass : FQDN of test class to run.\n"); sb.append("--config : absolute url to jdiameter config file.\n"); log.info("Usage: \n" + sb); } private void performTask() { if (this.runnerClassInstance != null) try { this.runnerClassInstance.configure(this.configurationFile); this.runnerClassInstance.performTestRun(); } catch (Exception e) { log.error("Failed to run due to exception.", e); } } private boolean isConfigured() { return this.configured; } private static void configLog4j() { InputStream inStreamLog4j = CLIRunner.class.getClassLoader().getResourceAsStream("log4j.properties"); Properties propertiesLog4j = new Properties(); try { propertiesLog4j.load(inStreamLog4j); PropertyConfigurator.configure(propertiesLog4j); } catch (Exception e) { e.printStackTrace(); } log.debug("log4j configured"); } //Bean methods and fields for MC runn public void setConfigurationFile(String v) { try { File f = new File(v); if (!f.exists() || !f.canRead() || !f.isFile()) { if(Thread.currentThread().getContextClassLoader().getResource(v)!=null) { //this is double check to test runner classes, but we require it to be sure if deployment in mc is ok this.configurationFile = Thread.currentThread().getContextClassLoader().getResourceAsStream(v); }else { this.configured = false; log.error("File \"" + v + "\" does not exists, is not readable or is not a file."); this.configurationFile = null; } }else { this.configurationFile = new FileInputStream(f); } if(this.runnerClassInstance!=null) { configured = true; } } catch (Exception e) { e.printStackTrace(); log.error("Failed to init test class: " + v); this.configured = false; } } public String getConfigurationFile() { if(this.configurationFile!=null) { return this.configurationFile.toString(); }else { return null; } } public void setTestClass(String v) { try { Class clazz = Class.forName(v); this.runnerClassInstance = (AbstractStackRunner) clazz.newInstance(); if(this.configurationFile!=null) { configured = true; } } catch (Exception e) { e.printStackTrace(); log.error("Failed to init test class: " + v); this.configured = false; } } public String getTestClass() { if(this.runnerClassInstance!=null) { return this.runnerClassInstance.toString(); }else { return null; } } public void start() throws Exception { if(isConfigured()) { this.runnerClassInstance.configure(this.configurationFile); //now here we should be able to receive all data. }else { throw new IllegalStateException("Runner is not configured"); } } public void stop() { if(isConfigured()) { this.runnerClassInstance.clean(); } } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual * contributors as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a full listing * of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License, v. 2.0. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License, * v. 2.0 along with this distribution; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.mobicents.diameter.stack.functional.sh.base; import org.jdiameter.api.Answer; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpSet; import org.jdiameter.api.IllegalDiameterStateException; import org.jdiameter.api.InternalException; import org.jdiameter.api.NetworkReqListener; import org.jdiameter.api.OverloadException; import org.jdiameter.api.Request; import org.jdiameter.api.RouteException; import org.jdiameter.api.app.AppAnswerEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.sh.ServerShSession; import org.jdiameter.api.sh.events.ProfileUpdateAnswer; import org.jdiameter.api.sh.events.ProfileUpdateRequest; import org.jdiameter.api.sh.events.PushNotificationAnswer; import org.jdiameter.api.sh.events.PushNotificationRequest; import org.jdiameter.api.sh.events.SubscribeNotificationsRequest; import org.jdiameter.api.sh.events.UserDataRequest; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.common.impl.app.sh.ProfileUpdateAnswerImpl; import org.mobicents.diameter.stack.functional.Utils; /** * Base implementation of Server * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class ServerPUR extends org.mobicents.diameter.stack.functional.sh.AbstractServer { protected boolean sentSubscribeNotifications; protected boolean sentProfileUpdate; protected boolean sentUserData; protected boolean sentPushNotification; protected boolean receiveSubscribeNotifications; protected boolean receiveProfileUpdate; protected boolean receiveUserData; protected boolean receivePushNotification; protected ProfileUpdateRequest profileUpdateRequest; // ------- send methods to trigger answer public void sendProfileUpdate() throws Exception { if (!this.receiveProfileUpdate || this.profileUpdateRequest == null) { fail("Did not receive UPDATE or answer already sent.", null); throw new Exception("Did not receive UPDATE or answer already sent. Request: " + this.profileUpdateRequest); } ProfileUpdateAnswer answer = new ProfileUpdateAnswerImpl((Request) this.profileUpdateRequest.getMessage(), 2001); AvpSet reqSet = profileUpdateRequest.getMessage().getAvps(); AvpSet set = answer.getMessage().getAvps(); set.removeAvp(Avp.DESTINATION_HOST); set.removeAvp(Avp.DESTINATION_REALM); set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID)); this.serverShSession.sendProfileUpdateAnswer(answer); Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true); this.profileUpdateRequest = null; } // ------- initial, this will be triggered for first msg. /* * (non-Javadoc) * * @see org.jdiameter.api.NetworkReqListener#processRequest(org.jdiameter.api.Request) */ @Override public Answer processRequest(Request request) { int code = request.getCommandCode(); if (code != ProfileUpdateRequest.code) { fail("Received Request with code not used by Sh!. Code[" + request.getCommandCode() + "]", null); return null; } if (super.serverShSession == null) { try { super.serverShSession = ((ISessionFactory) this.sessionFactory).getNewAppSession(request.getSessionId(), getApplicationId(), ServerShSession.class, (Object) null); ((NetworkReqListener) this.serverShSession).processRequest(request); } catch (Exception e) { fail(null, e); } } else { // do fail? fail("Received Request in base listener, not in app specific!" + code, null); } return null; } // ------------- specific, app session listener. /* * (non-Javadoc) * * @see org.jdiameter.api.cca.ServerRoSessionListener#doOtherEvent(org.jdiameter.api.app.AppSession, * org.jdiameter.api.app.AppRequestEvent, org.jdiameter.api.app.AppAnswerEvent) */ public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { fail("Received \"Other\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); } public void doSubscribeNotificationsRequestEvent(ServerShSession session, SubscribeNotificationsRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { this.receiveSubscribeNotifications = true; fail("Received \"SNR\" event, request[" + request + "], on session[" + session + "]", null); } public void doProfileUpdateRequestEvent(ServerShSession session, ProfileUpdateRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { if (this.receiveProfileUpdate) { fail("Received UPDATE more than once!", null); } this.receiveProfileUpdate = true; this.profileUpdateRequest = request; } public void doPushNotificationAnswerEvent(ServerShSession session, PushNotificationRequest request, PushNotificationAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { fail("Received \"PNA\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); this.receivePushNotification = true; } public void doUserDataRequestEvent(ServerShSession session, UserDataRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { fail("Received \"UDR\" event, request[" + request + "], on session[" + session + "]", null); this.receiveUserData = true; } public boolean isSentSubscribeNotifications() { return sentSubscribeNotifications; } public boolean isSentProfileUpdate() { return sentProfileUpdate; } public boolean isSentUserData() { return sentUserData; } public boolean isSentPushNotification() { return sentPushNotification; } public boolean isReceiveSubscribeNotifications() { return receiveSubscribeNotifications; } public boolean isReceiveProfileUpdate() { return receiveProfileUpdate; } public boolean isReceiveUserData() { return receiveUserData; } public boolean isReceivePushNotification() { return receivePushNotification; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual * contributors as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a full listing * of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License, v. 2.0. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License, * v. 2.0 along with this distribution; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.mobicents.diameter.stack.functional.sh.base; import org.jdiameter.api.Answer; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpSet; import org.jdiameter.api.IllegalDiameterStateException; import org.jdiameter.api.InternalException; import org.jdiameter.api.NetworkReqListener; import org.jdiameter.api.OverloadException; import org.jdiameter.api.Request; import org.jdiameter.api.RouteException; import org.jdiameter.api.app.AppAnswerEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.sh.ClientShSession; import org.jdiameter.api.sh.events.ProfileUpdateAnswer; import org.jdiameter.api.sh.events.ProfileUpdateRequest; import org.jdiameter.api.sh.events.PushNotificationAnswer; import org.jdiameter.api.sh.events.PushNotificationRequest; import org.jdiameter.api.sh.events.SubscribeNotificationsAnswer; import org.jdiameter.api.sh.events.SubscribeNotificationsRequest; import org.jdiameter.api.sh.events.UserDataAnswer; import org.jdiameter.api.sh.events.UserDataRequest; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.common.impl.app.sh.ProfileUpdateRequestImpl; import org.jdiameter.common.impl.app.sh.PushNotificationAnswerImpl; import org.jdiameter.common.impl.app.sh.SubscribeNotificationsRequestImpl; import org.jdiameter.common.impl.app.sh.UserDataRequestImpl; import org.mobicents.diameter.stack.functional.Utils; import org.mobicents.diameter.stack.functional.sh.AbstractClient; /** * Base implementation of Client * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class Client extends AbstractClient { protected boolean sentSubscribeNotifications; protected boolean sentProfileUpdate; protected boolean sentUserData; protected boolean sentPushNotification; protected boolean receiveSubscribeNotifications; protected boolean receiveProfileUpdate; protected boolean receiveUserData; protected boolean receivePushNotification; protected PushNotificationRequest request; /** * */ public Client() { } public void sendSubscribeNotifications() throws Exception { SubscribeNotificationsRequest request = new SubscribeNotificationsRequestImpl(super.clientShSession.getSessions().get(0) .createRequest(SubscribeNotificationsRequest.code, getApplicationId(), getServerRealmName())); AvpSet avpSet = request.getMessage().getAvps(); // < Subscribe-Notifications-Request > ::= < Diameter Header: 308, REQ, PXY, 16777217 > // < Session-Id > // { Vendor-Specific-Application-Id } AvpSet vendorSpecificApplicationId = avpSet.addGroupedAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, 0, false, false); // 1* [ Vendor-Id ] vendorSpecificApplicationId.addAvp(Avp.VENDOR_ID, getApplicationId().getVendorId(), true); // 0*1{ Auth-Application-Id } vendorSpecificApplicationId.addAvp(Avp.AUTH_APPLICATION_ID, getApplicationId().getAuthAppId(), true); // 0*1{ Acct-Application-Id } // { Auth-Session-State } avpSet.addAvp(Avp.AUTH_SESSION_STATE, 1); // { Origin-Host } avpSet.removeAvp(Avp.ORIGIN_HOST); avpSet.addAvp(Avp.ORIGIN_HOST, getClientURI(), true); // { Origin-Realm } // [ Destination-Host ] // { Destination-Realm } // *[ Supported-Features ] // { User-Identity } // [ Wildcarded-PSI ] // [ Wildcarded-IMPU ] // *[ Service-Indication ] // [ Send-Data-Indication ] // [ Server-Name ] // { Subs-Req-Type } // *{ Data-Reference } avpSet.addAvp(Avp.DATA_REFERENCE, 0); // *[ Identity-Set ] // [ Expiry-Time ] // *[ DSAI-Tag ] // *[ AVP ] // *[ Proxy-Info ] // *[ Route-Record ] Utils.printMessage(log, super.stack.getDictionary(), request.getMessage(), true); super.clientShSession.sendSubscribeNotificationsRequest(request); this.sentSubscribeNotifications = true; } public void sendProfileUpdate() throws Exception { ProfileUpdateRequest request = new ProfileUpdateRequestImpl(super.clientShSession.getSessions().get(0) .createRequest(ProfileUpdateRequest.code, getApplicationId(), getServerRealmName())); AvpSet avpSet = request.getMessage().getAvps(); // < Profile-Update-Request > ::= < Diameter Header: 307, REQ, PXY, 16777217 > // < Session-Id > AvpSet vendorSpecificApplicationId = avpSet.addGroupedAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, 0, false, false); // 1* [ Vendor-Id ] vendorSpecificApplicationId.addAvp(Avp.VENDOR_ID, getApplicationId().getVendorId(), true); // 0*1{ Auth-Application-Id } vendorSpecificApplicationId.addAvp(Avp.AUTH_APPLICATION_ID, getApplicationId().getAuthAppId(), true); // 0*1{ Acct-Application-Id } // { Auth-Session-State } avpSet.addAvp(Avp.AUTH_SESSION_STATE, 1); // { Origin-Host } avpSet.removeAvp(Avp.ORIGIN_HOST); avpSet.addAvp(Avp.ORIGIN_HOST, getClientURI(), true); // { Origin-Realm } // [ Destination-Host ] // { Destination-Realm } // *[ Supported-Features ] // { User-Identity } AvpSet userIdentity = avpSet.addGroupedAvp(Avp.USER_IDENTITY, getApplicationId().getVendorId(), true, false); // User-Identity ::= <AVP header: 700 10415> // [Public-Identity] userIdentity.addAvp(Avp.PUBLIC_IDENTITY, "tralalalal user", getApplicationId().getVendorId(), true, false, false); // [MSISDN] // *[AVP] // [ Wildcarded-PSI ] // [ Wildcarded-IMPU ] // { Data-Reference } avpSet.addAvp(Avp.DATA_REFERENCE, 0); // { User-Data } // *[ AVP ] super.clientShSession.sendProfileUpdateRequest(request); Utils.printMessage(log, super.stack.getDictionary(), request.getMessage(), true); this.sentProfileUpdate = true; } public void sendUserData() throws Exception { UserDataRequest request = new UserDataRequestImpl(super.clientShSession.getSessions().get(0).createRequest(UserDataRequest.code, getApplicationId(), getServerRealmName())); AvpSet avpSet = request.getMessage().getAvps(); // < User-Data -Request> ::= < Diameter Header: 306, REQ, PXY, 16777217 > // < Session-Id > AvpSet vendorSpecificApplicationId = avpSet.addGroupedAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, 0, false, false); // 1* [ Vendor-Id ] vendorSpecificApplicationId.addAvp(Avp.VENDOR_ID, getApplicationId().getVendorId(), true); // 0*1{ Auth-Application-Id } vendorSpecificApplicationId.addAvp(Avp.AUTH_APPLICATION_ID, getApplicationId().getAuthAppId(), true); // 0*1{ Acct-Application-Id } // { Auth-Session-State } avpSet.addAvp(Avp.AUTH_SESSION_STATE, 1); // { Origin-Host } avpSet.removeAvp(Avp.ORIGIN_HOST); avpSet.addAvp(Avp.ORIGIN_HOST, getClientURI(), true); // { Origin-Realm } // [ Destination-Host ] // { Destination-Realm } // *[ Supported-Features ] // { User-Identity } AvpSet userIdentity = avpSet.addGroupedAvp(Avp.USER_IDENTITY, getApplicationId().getVendorId(), true, false); // User-Identity ::= <AVP header: 700 10415> // [Public-Identity] userIdentity.addAvp(Avp.PUBLIC_IDENTITY, "tralalalal user", getApplicationId().getVendorId(), true, false, false); // [MSISDN] // *[AVP] // [ Wildcarded-PSI ] // [ Wildcarded-IMPU ] // [ Server-Name ] // *[ Service-Indication ] // *{ Data-Reference } avpSet.addAvp(Avp.DATA_REFERENCE, 0); // *[ Identity-Set ] // [ Requested-Domain ] // [ Current-Location ] // *[ DSAI-Tag ] // *[ AVP ] // *[ Proxy-Info ] // *[ Route-Record ] Utils.printMessage(log, super.stack.getDictionary(), request.getMessage(), true); super.clientShSession.sendUserDataRequest(request); this.sentUserData = true; } public void sendPushNotification() throws Exception { if (!this.receivePushNotification || this.request == null) { fail("Did not receive NOTIFICATION or answer already sent.", null); throw new Exception("Did not receive NOTIFICATION or answer already sent. Request: " + this.request); } PushNotificationAnswer answer = new PushNotificationAnswerImpl((Request) request.getMessage(), 2001); AvpSet reqSet = request.getMessage().getAvps(); AvpSet set = answer.getMessage().getAvps(); set.removeAvp(Avp.DESTINATION_HOST); set.removeAvp(Avp.DESTINATION_REALM); set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID)); request = null; Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true); // < Push-Notification-Answer > ::=< Diameter Header: 309, PXY, 16777217 > // < Session-Id > // { Vendor-Specific-Application-Id } if (set.getAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID) == null) { AvpSet vendorSpecificApplicationId = set.addGroupedAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, 0, false, false); // 1* [ Vendor-Id ] vendorSpecificApplicationId.addAvp(Avp.VENDOR_ID, getApplicationId().getVendorId(), true); // 0*1{ Auth-Application-Id } vendorSpecificApplicationId.addAvp(Avp.AUTH_APPLICATION_ID, getApplicationId().getAuthAppId(), true); } // [ Result-Code ] // [ Experimental-Result ] // { Auth-Session-State } // { Origin-Host } // { Origin-Realm } // *[ Supported-Features ] // *[ AVP ] // *[ Failed-AVP ] // *[ Proxy-Info ] // *[ Route-Record ] Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true); super.clientShSession.sendPushNotificationAnswer(answer); this.sentPushNotification = true; } // ------------ event handlers; public void doSubscribeNotificationsAnswerEvent(ClientShSession session, SubscribeNotificationsRequest request, SubscribeNotificationsAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { receiveSubscribeNotifications = true; } public void doProfileUpdateAnswerEvent(ClientShSession session, ProfileUpdateRequest request, ProfileUpdateAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { receiveProfileUpdate = true; } public void doPushNotificationRequestEvent(ClientShSession session, PushNotificationRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { receivePushNotification = true; this.request = request; } public void doUserDataAnswerEvent(ClientShSession session, UserDataRequest request, UserDataAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { receiveUserData = true; } public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { fail("Received \"Other\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); } /* * (non-Javadoc) * * @see org.jdiameter.api.NetworkReqListener#processRequest(org.jdiameter.api.Request) */ @Override public Answer processRequest(Request request) { int code = request.getCommandCode(); if (code != PushNotificationRequest.code) { fail("Received Request with code not used by Sh!. Code[" + request.getCommandCode() + "]", null); return null; } if (super.clientShSession.getSessionId().equals(request.getSessionId())) { // do fail? fail("Received Request in base listener, not in app specific!" + code, null); } else { super.clientShSession.release(); try { super.clientShSession = ((ISessionFactory) this.sessionFactory).getNewAppSession(request.getSessionId(), getApplicationId(), ClientShSession.class, (Object) null); ((NetworkReqListener) this.clientShSession).processRequest(request); } catch (Exception e) { e.printStackTrace(); fail(null, e); } } return null; } @Override protected String getClientURI() { return clientURI; } public boolean isSentSubscribeNotifications() { return sentSubscribeNotifications; } public boolean isSentProfileUpdate() { return sentProfileUpdate; } public boolean isSentUserData() { return sentUserData; } public boolean isSentPushNotification() { return sentPushNotification; } public boolean isReceiveSubscribeNotifications() { return receiveSubscribeNotifications; } public boolean isReceiveProfileUpdate() { return receiveProfileUpdate; } public boolean isReceiveUserData() { return receiveUserData; } public boolean isReceivePushNotification() { return receivePushNotification; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual * contributors as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a full listing * of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License, v. 2.0. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License, * v. 2.0 along with this distribution; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.mobicents.diameter.stack.functional.sh.base; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpSet; import org.jdiameter.api.IllegalDiameterStateException; import org.jdiameter.api.InternalException; import org.jdiameter.api.OverloadException; import org.jdiameter.api.RouteException; import org.jdiameter.api.app.AppAnswerEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.sh.ClientShSession; import org.jdiameter.api.sh.events.ProfileUpdateAnswer; import org.jdiameter.api.sh.events.ProfileUpdateRequest; import org.jdiameter.api.sh.events.PushNotificationRequest; import org.jdiameter.api.sh.events.SubscribeNotificationsAnswer; import org.jdiameter.api.sh.events.SubscribeNotificationsRequest; import org.jdiameter.api.sh.events.UserDataAnswer; import org.jdiameter.api.sh.events.UserDataRequest; import org.jdiameter.common.impl.app.sh.UserDataRequestImpl; import org.mobicents.diameter.stack.functional.Utils; import org.mobicents.diameter.stack.functional.sh.AbstractClient; /** * Base implementation of Client * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class ClientUDR extends AbstractClient { protected boolean sentSubscribeNotifications; protected boolean sentProfileUpdate; protected boolean sentUserData; protected boolean sentPushNotification; protected boolean receiveSubscribeNotifications; protected boolean receiveProfileUpdate; protected boolean receiveUserData; protected boolean receivePushNotification; /** * */ public ClientUDR() { } public void sendUserData() throws Exception { UserDataRequest request = new UserDataRequestImpl(super.clientShSession.getSessions().get(0).createRequest(UserDataRequest.code, getApplicationId(), getServerRealmName())); AvpSet avpSet = request.getMessage().getAvps(); // < User-Data -Request> ::= < Diameter Header: 306, REQ, PXY, 16777217 > // < Session-Id > AvpSet vendorSpecificApplicationId = avpSet.addGroupedAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, 0, false, false); // 1* [ Vendor-Id ] vendorSpecificApplicationId.addAvp(Avp.VENDOR_ID, getApplicationId().getVendorId(), true); // 0*1{ Auth-Application-Id } vendorSpecificApplicationId.addAvp(Avp.AUTH_APPLICATION_ID, getApplicationId().getAuthAppId(), true); // 0*1{ Acct-Application-Id } // { Auth-Session-State } avpSet.addAvp(Avp.AUTH_SESSION_STATE, 1); // { Origin-Host } avpSet.removeAvp(Avp.ORIGIN_HOST); avpSet.addAvp(Avp.ORIGIN_HOST, getClientURI(), true); // { Origin-Realm } // [ Destination-Host ] // { Destination-Realm } // *[ Supported-Features ] // { User-Identity } // [ Wildcarded-PSI ] // [ Wildcarded-IMPU ] // [ Server-Name ] // *[ Service-Indication ] // *{ Data-Reference } // *[ Identity-Set ] // [ Requested-Domain ] // [ Current-Location ] // *[ DSAI-Tag ] // *[ AVP ] // *[ Proxy-Info ] // *[ Route-Record ] Utils.printMessage(log, super.stack.getDictionary(), request.getMessage(), true); super.clientShSession.sendUserDataRequest(request); this.sentUserData = true; } // ------------ event handlers; public void doSubscribeNotificationsAnswerEvent(ClientShSession session, SubscribeNotificationsRequest request, SubscribeNotificationsAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { receiveSubscribeNotifications = true; fail("Received \"SNA\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); } public void doProfileUpdateAnswerEvent(ClientShSession session, ProfileUpdateRequest request, ProfileUpdateAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { receiveProfileUpdate = true; fail("Received \"PUA\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); } public void doPushNotificationRequestEvent(ClientShSession session, PushNotificationRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { receivePushNotification = true; fail("Received \"PNR\" event, request[" + request + "], on session[" + session + "]", null); } public void doUserDataAnswerEvent(ClientShSession session, UserDataRequest request, UserDataAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { receiveUserData = true; } public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { fail("Received \"Other\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); } @Override protected String getClientURI() { return clientURI; } public boolean isSentSubscribeNotifications() { return sentSubscribeNotifications; } public boolean isSentProfileUpdate() { return sentProfileUpdate; } public boolean isSentUserData() { return sentUserData; } public boolean isSentPushNotification() { return sentPushNotification; } public boolean isReceiveSubscribeNotifications() { return receiveSubscribeNotifications; } public boolean isReceiveProfileUpdate() { return receiveProfileUpdate; } public boolean isReceiveUserData() { return receiveUserData; } public boolean isReceivePushNotification() { return receivePushNotification; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual * contributors as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a full listing * of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License, v. 2.0. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License, * v. 2.0 along with this distribution; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.mobicents.diameter.stack.functional.sh.base; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpSet; import org.jdiameter.api.IllegalDiameterStateException; import org.jdiameter.api.InternalException; import org.jdiameter.api.OverloadException; import org.jdiameter.api.RouteException; import org.jdiameter.api.app.AppAnswerEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.sh.ClientShSession; import org.jdiameter.api.sh.events.ProfileUpdateAnswer; import org.jdiameter.api.sh.events.ProfileUpdateRequest; import org.jdiameter.api.sh.events.PushNotificationRequest; import org.jdiameter.api.sh.events.SubscribeNotificationsAnswer; import org.jdiameter.api.sh.events.SubscribeNotificationsRequest; import org.jdiameter.api.sh.events.UserDataAnswer; import org.jdiameter.api.sh.events.UserDataRequest; import org.jdiameter.common.impl.app.sh.SubscribeNotificationsRequestImpl; import org.mobicents.diameter.stack.functional.Utils; import org.mobicents.diameter.stack.functional.sh.AbstractClient; /** * Base implementation of Client * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class ClientSNR extends AbstractClient { protected boolean sentSubscribeNotifications; protected boolean sentProfileUpdate; protected boolean sentUserData; protected boolean sentPushNotification; protected boolean receiveSubscribeNotifications; protected boolean receiveProfileUpdate; protected boolean receiveUserData; protected boolean receivePushNotification; /** * */ public ClientSNR() { } public void sendSubscribeNotifications() throws Exception { SubscribeNotificationsRequest request = new SubscribeNotificationsRequestImpl(super.clientShSession.getSessions().get(0) .createRequest(SubscribeNotificationsRequest.code, getApplicationId(), getServerRealmName())); AvpSet avpSet = request.getMessage().getAvps(); // < Subscribe-Notifications-Request > ::= < Diameter Header: 308, REQ, PXY, 16777217 > // < Session-Id > // { Vendor-Specific-Application-Id } AvpSet vendorSpecificApplicationId = avpSet.addGroupedAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, 0, false, false); // 1* [ Vendor-Id ] vendorSpecificApplicationId.addAvp(Avp.VENDOR_ID, getApplicationId().getVendorId(), true); // 0*1{ Auth-Application-Id } vendorSpecificApplicationId.addAvp(Avp.AUTH_APPLICATION_ID, getApplicationId().getAuthAppId(), true); // 0*1{ Acct-Application-Id } // { Auth-Session-State } avpSet.addAvp(Avp.AUTH_SESSION_STATE, 1); // { Origin-Host } avpSet.removeAvp(Avp.ORIGIN_HOST); avpSet.addAvp(Avp.ORIGIN_HOST, getClientURI(), true); // { Origin-Realm } // [ Destination-Host ] // { Destination-Realm } // *[ Supported-Features ] // { User-Identity } // [ Wildcarded-PSI ] // [ Wildcarded-IMPU ] // *[ Service-Indication ] // [ Send-Data-Indication ] // [ Server-Name ] // { Subs-Req-Type } // *{ Data-Reference } avpSet.addAvp(Avp.DATA_REFERENCE, 0); // *[ Identity-Set ] // [ Expiry-Time ] // *[ DSAI-Tag ] // *[ AVP ] // *[ Proxy-Info ] // *[ Route-Record ] Utils.printMessage(log, super.stack.getDictionary(), request.getMessage(), true); super.clientShSession.sendSubscribeNotificationsRequest(request); this.sentSubscribeNotifications = true; } // ------------ event handlers; public void doSubscribeNotificationsAnswerEvent(ClientShSession session, SubscribeNotificationsRequest request, SubscribeNotificationsAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { receiveSubscribeNotifications = true; } public void doProfileUpdateAnswerEvent(ClientShSession session, ProfileUpdateRequest request, ProfileUpdateAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { receiveProfileUpdate = true; fail("Received \"PUA\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); } public void doPushNotificationRequestEvent(ClientShSession session, PushNotificationRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { receivePushNotification = true; fail("Received \"PNR\" event, request[" + request + "], on session[" + session + "]", null); } public void doUserDataAnswerEvent(ClientShSession session, UserDataRequest request, UserDataAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { receiveUserData = true; fail("Received \"UDR\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); } public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { fail("Received \"Other\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); } @Override protected String getClientURI() { return clientURI; } public boolean isSentSubscribeNotifications() { return sentSubscribeNotifications; } public boolean isSentProfileUpdate() { return sentProfileUpdate; } public boolean isSentUserData() { return sentUserData; } public boolean isSentPushNotification() { return sentPushNotification; } public boolean isReceiveSubscribeNotifications() { return receiveSubscribeNotifications; } public boolean isReceiveProfileUpdate() { return receiveProfileUpdate; } public boolean isReceiveUserData() { return receiveUserData; } public boolean isReceivePushNotification() { return receivePushNotification; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual * contributors as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a full listing * of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License, v. 2.0. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License, * v. 2.0 along with this distribution; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.mobicents.diameter.stack.functional.sh.base; import org.jdiameter.api.Answer; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpSet; import org.jdiameter.api.IllegalDiameterStateException; import org.jdiameter.api.InternalException; import org.jdiameter.api.NetworkReqListener; import org.jdiameter.api.OverloadException; import org.jdiameter.api.Request; import org.jdiameter.api.RouteException; import org.jdiameter.api.app.AppAnswerEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.sh.ServerShSession; import org.jdiameter.api.sh.events.ProfileUpdateRequest; import org.jdiameter.api.sh.events.PushNotificationAnswer; import org.jdiameter.api.sh.events.PushNotificationRequest; import org.jdiameter.api.sh.events.SubscribeNotificationsRequest; import org.jdiameter.api.sh.events.UserDataAnswer; import org.jdiameter.api.sh.events.UserDataRequest; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.common.impl.app.sh.UserDataAnswerImpl; import org.mobicents.diameter.stack.functional.Utils; /** * Base implementation of Server * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class ServerUDR extends org.mobicents.diameter.stack.functional.sh.AbstractServer { protected boolean sentSubscribeNotifications; protected boolean sentProfileUpdate; protected boolean sentUserData; protected boolean sentPushNotification; protected boolean receiveSubscribeNotifications; protected boolean receiveProfileUpdate; protected boolean receiveUserData; protected boolean receivePushNotification; protected UserDataRequest userDataRequest; // ------- send methods to trigger answer public void sendUserData() throws Exception { if (!this.receiveUserData || this.userDataRequest == null) { fail("Did not receive USER DATA or answer already sent.", null); throw new Exception("Did not receive USER DATA or answer already sent. Request: " + this.userDataRequest); } UserDataAnswer answer = new UserDataAnswerImpl((Request) this.userDataRequest.getMessage(), 2001); AvpSet reqSet = userDataRequest.getMessage().getAvps(); AvpSet set = answer.getMessage().getAvps(); set.removeAvp(Avp.DESTINATION_HOST); set.removeAvp(Avp.DESTINATION_REALM); set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID)); this.serverShSession.sendUserDataAnswer(answer); Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true); this.userDataRequest = null; } // ------- initial, this will be triggered for first msg. /* * (non-Javadoc) * * @see org.jdiameter.api.NetworkReqListener#processRequest(org.jdiameter.api.Request) */ @Override public Answer processRequest(Request request) { int code = request.getCommandCode(); if (code != UserDataRequest.code) { fail("Received Request with code not used by Sh!. Code[" + request.getCommandCode() + "]", null); return null; } if (super.serverShSession == null) { try { super.serverShSession = ((ISessionFactory) this.sessionFactory).getNewAppSession(request.getSessionId(), getApplicationId(), ServerShSession.class, (Object) null); ((NetworkReqListener) this.serverShSession).processRequest(request); } catch (Exception e) { fail(null, e); } } else { // do fail? fail("Received Request in base listener, not in app specific!" + code, null); } return null; } // ------------- specific, app session listener. /* * (non-Javadoc) * * @see org.jdiameter.api.cca.ServerRoSessionListener#doOtherEvent(org.jdiameter.api.app.AppSession, * org.jdiameter.api.app.AppRequestEvent, org.jdiameter.api.app.AppAnswerEvent) */ public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { fail("Received \"Other\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); } public void doSubscribeNotificationsRequestEvent(ServerShSession session, SubscribeNotificationsRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { this.receiveSubscribeNotifications = true; fail("Received \"SNR\" event, request[" + request + "], on session[" + session + "]", null); } public void doProfileUpdateRequestEvent(ServerShSession session, ProfileUpdateRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { this.receiveProfileUpdate = true; fail("Received \"PUR\" event, request[" + request + "], on session[" + session + "]", null); } public void doPushNotificationAnswerEvent(ServerShSession session, PushNotificationRequest request, PushNotificationAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { fail("Received \"PNA\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); this.receivePushNotification = true; } public void doUserDataRequestEvent(ServerShSession session, UserDataRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { if (this.receiveUserData) { fail("Received USER DATA more than once!", null); } this.receiveUserData = true; this.userDataRequest = request; } @Override public void receivedSuccessMessage(Request request, Answer answer) { fail("Received \"SuccessMessage\" event, request[" + request + "], answer[" + answer + "]", null); } @Override public void timeoutExpired(Request request) { fail("Received \"Timoeout\" event, request[" + request + "]", null); } public boolean isSentSubscribeNotifications() { return sentSubscribeNotifications; } public boolean isSentProfileUpdate() { return sentProfileUpdate; } public boolean isSentUserData() { return sentUserData; } public boolean isSentPushNotification() { return sentPushNotification; } public boolean isReceiveSubscribeNotifications() { return receiveSubscribeNotifications; } public boolean isReceiveProfileUpdate() { return receiveProfileUpdate; } public boolean isReceiveUserData() { return receiveUserData; } public boolean isReceivePushNotification() { return receivePushNotification; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual * contributors as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a full listing * of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License, v. 2.0. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License, * v. 2.0 along with this distribution; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.mobicents.diameter.stack.functional.sh.base; import org.jdiameter.api.Answer; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpSet; import org.jdiameter.api.IllegalDiameterStateException; import org.jdiameter.api.InternalException; import org.jdiameter.api.NetworkReqListener; import org.jdiameter.api.OverloadException; import org.jdiameter.api.Request; import org.jdiameter.api.RouteException; import org.jdiameter.api.app.AppAnswerEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.sh.ServerShSession; import org.jdiameter.api.sh.events.ProfileUpdateAnswer; import org.jdiameter.api.sh.events.ProfileUpdateRequest; import org.jdiameter.api.sh.events.PushNotificationAnswer; import org.jdiameter.api.sh.events.PushNotificationRequest; import org.jdiameter.api.sh.events.SubscribeNotificationsAnswer; import org.jdiameter.api.sh.events.SubscribeNotificationsRequest; import org.jdiameter.api.sh.events.UserDataAnswer; import org.jdiameter.api.sh.events.UserDataRequest; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.common.impl.app.sh.ProfileUpdateAnswerImpl; import org.jdiameter.common.impl.app.sh.PushNotificationRequestImpl; import org.jdiameter.common.impl.app.sh.SubscribeNotificationsAnswerImpl; import org.jdiameter.common.impl.app.sh.UserDataAnswerImpl; import org.mobicents.diameter.stack.functional.Utils; /** * Base implementation of Server * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class Server extends org.mobicents.diameter.stack.functional.sh.AbstractServer { protected boolean sentSubscribeNotifications; protected boolean sentProfileUpdate; protected boolean sentUserData; protected boolean sentPushNotification; protected boolean receiveSubscribeNotifications; protected boolean receiveProfileUpdate; protected boolean receiveUserData; protected boolean receivePushNotification; protected SubscribeNotificationsRequest subscribeNotificationsRequest; protected ProfileUpdateRequest profileUpdateRequest; protected UserDataRequest userDataRequest; // ------- send methods to trigger answer public void sendSubscribeNotifications() throws Exception { if (!this.receiveSubscribeNotifications || this.subscribeNotificationsRequest == null) { fail("Did not receive SUBSCRIBE or answer already sent.", null); throw new Exception("Did not receive SUBSCRIBE or answer already sent. Request: " + this.subscribeNotificationsRequest); } SubscribeNotificationsAnswer answer = new SubscribeNotificationsAnswerImpl((Request) this.subscribeNotificationsRequest.getMessage(), 2001); AvpSet reqSet = subscribeNotificationsRequest.getMessage().getAvps(); AvpSet set = answer.getMessage().getAvps(); set.removeAvp(Avp.DESTINATION_HOST); set.removeAvp(Avp.DESTINATION_REALM); set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID)); this.serverShSession.sendSubscribeNotificationsAnswer(answer); Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true); this.subscribeNotificationsRequest = null; } public void sendProfileUpdate() throws Exception { if (!this.receiveProfileUpdate || this.profileUpdateRequest == null) { fail("Did not receive UPDATE or answer already sent.", null); throw new Exception("Did not receive UPDATE or answer already sent. Request: " + this.profileUpdateRequest); } ProfileUpdateAnswer answer = new ProfileUpdateAnswerImpl((Request) this.profileUpdateRequest.getMessage(), 2001); AvpSet reqSet = profileUpdateRequest.getMessage().getAvps(); AvpSet set = answer.getMessage().getAvps(); set.removeAvp(Avp.DESTINATION_HOST); set.removeAvp(Avp.DESTINATION_REALM); set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID)); this.serverShSession.sendProfileUpdateAnswer(answer); Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true); this.profileUpdateRequest = null; } public void sendUserData() throws Exception { if (!this.receiveUserData || this.userDataRequest == null) { fail("Did not receive USER DATA or answer already sent.", null); throw new Exception("Did not receive USER DATA or answer already sent. Request: " + this.userDataRequest); } UserDataAnswer answer = new UserDataAnswerImpl((Request) this.userDataRequest.getMessage(), 2001); AvpSet reqSet = userDataRequest.getMessage().getAvps(); AvpSet set = answer.getMessage().getAvps(); set.removeAvp(Avp.DESTINATION_HOST); set.removeAvp(Avp.DESTINATION_REALM); set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID)); this.serverShSession.sendUserDataAnswer(answer); Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true); this.userDataRequest = null; } public void sendPushNotification() throws Exception { if (super.serverShSession == null) { super.serverShSession = ((ISessionFactory) this.sessionFactory).getNewAppSession(this.sessionFactory.getSessionId("xxTESTxx"), getApplicationId(), ServerShSession.class, (Object) null); } PushNotificationRequest request = new PushNotificationRequestImpl(super.serverShSession.getSessions().get(0) .createRequest(PushNotificationRequestImpl.code, getApplicationId(), getClientRealmName())); AvpSet avpSet = request.getMessage().getAvps(); // < Push-Notification-Request > ::= < Diameter Header: 309, REQ, PXY, 16777217 > // < Session-Id > // { Vendor-Specific-Application-Id } AvpSet vendorSpecificApplicationId = avpSet.addGroupedAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, 0, false, false); // 1* [ Vendor-Id ] vendorSpecificApplicationId.addAvp(Avp.VENDOR_ID, getApplicationId().getVendorId(), true); // 0*1{ Auth-Application-Id } vendorSpecificApplicationId.addAvp(Avp.AUTH_APPLICATION_ID, getApplicationId().getAuthAppId(), true); // avpSet.addAvp(Avp.AUTH_SESSION_STATE,1); // { Origin-Host } avpSet.removeAvp(Avp.ORIGIN_HOST); avpSet.addAvp(Avp.ORIGIN_HOST, getServerURI(), true); // { Origin-Realm } // { Destination-Host } avpSet.addAvp(Avp.ORIGIN_HOST, getClientURI(), true); // { Destination-Realm } // *[ Supported-Features ] // { User-Identity } AvpSet userIdentity = avpSet.addGroupedAvp(Avp.USER_IDENTITY, getApplicationId().getVendorId(), true, false); // User-Identity ::= <AVP header: 700 10415> // [Public-Identity] userIdentity.addAvp(Avp.PUBLIC_IDENTITY, "tralalalal user", getApplicationId().getVendorId(), true, false, false); // [MSISDN] // *[AVP] // [ Wildcarded-PSI ] // [ Wildcarded-IMPU ] // { User-Data } avpSet.addAvp(Avp.USER_DATA_SH, "<xml><morexml></morexml></xml>", true); // *[ AVP ] // *[ Proxy-Info ] // *[ Route-Record ] this.serverShSession.sendPushNotificationRequest(request); this.sentPushNotification = true; Utils.printMessage(log, super.stack.getDictionary(), request.getMessage(), true); } // ------- initial, this will be triggered for first msg. /* * (non-Javadoc) * * @see org.jdiameter.api.NetworkReqListener#processRequest(org.jdiameter.api.Request) */ @Override public Answer processRequest(Request request) { int code = request.getCommandCode(); if (code != ProfileUpdateRequest.code && code != UserDataRequest.code && code != SubscribeNotificationsRequest.code) { fail("Received Request with code not used by Sh!. Code[" + request.getCommandCode() + "]", null); return null; } if (super.serverShSession == null) { try { super.serverShSession = ((ISessionFactory) this.sessionFactory).getNewAppSession(request.getSessionId(), getApplicationId(), ServerShSession.class, (Object) null); ((NetworkReqListener) this.serverShSession).processRequest(request); } catch (Exception e) { fail(null, e); } } else { // do fail? fail("Received Request in base listener, not in app specific!" + code, null); } return null; } // ------------- specific, app session listener. /* * (non-Javadoc) * * @see org.jdiameter.api.cca.ServerRoSessionListener#doOtherEvent(org.jdiameter.api.app.AppSession, * org.jdiameter.api.app.AppRequestEvent, org.jdiameter.api.app.AppAnswerEvent) */ public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { fail("Received \"Other\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); } public void doSubscribeNotificationsRequestEvent(ServerShSession session, SubscribeNotificationsRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { if (this.receiveSubscribeNotifications) { fail("Received SUBSCRIBE more than once!", null); } this.receiveSubscribeNotifications = true; this.subscribeNotificationsRequest = request; } public void doProfileUpdateRequestEvent(ServerShSession session, ProfileUpdateRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { if (this.receiveProfileUpdate) { fail("Received UPDATE more than once!", null); } this.receiveProfileUpdate = true; this.profileUpdateRequest = request; } public void doPushNotificationAnswerEvent(ServerShSession session, PushNotificationRequest request, PushNotificationAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { if (this.receivePushNotification) { fail("Received NOTIFICATION more than once!", null); } this.receivePushNotification = true; } public void doUserDataRequestEvent(ServerShSession session, UserDataRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { if (this.receiveUserData) { fail("Received USER DATA more than once!", null); } this.receiveUserData = true; this.userDataRequest = request; } @Override public void receivedSuccessMessage(Request request, Answer answer) { fail("Received \"SuccessMessage\" event, request[" + request + "], answer[" + answer + "]", null); } @Override public void timeoutExpired(Request request) { fail("Received \"Timoeout\" event, request[" + request + "]", null); } public boolean isSentSubscribeNotifications() { return sentSubscribeNotifications; } public boolean isSentProfileUpdate() { return sentProfileUpdate; } public boolean isSentUserData() { return sentUserData; } public boolean isSentPushNotification() { return sentPushNotification; } public boolean isReceiveSubscribeNotifications() { return receiveSubscribeNotifications; } public boolean isReceiveProfileUpdate() { return receiveProfileUpdate; } public boolean isReceiveUserData() { return receiveUserData; } public boolean isReceivePushNotification() { return receivePushNotification; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual * contributors as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a full listing * of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License, v. 2.0. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License, * v. 2.0 along with this distribution; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.mobicents.diameter.stack.functional.sh.base; import org.jdiameter.api.Answer; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpSet; import org.jdiameter.api.IllegalDiameterStateException; import org.jdiameter.api.InternalException; import org.jdiameter.api.NetworkReqListener; import org.jdiameter.api.OverloadException; import org.jdiameter.api.Request; import org.jdiameter.api.RouteException; import org.jdiameter.api.app.AppAnswerEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.sh.ServerShSession; import org.jdiameter.api.sh.events.ProfileUpdateAnswer; import org.jdiameter.api.sh.events.ProfileUpdateRequest; import org.jdiameter.api.sh.events.PushNotificationAnswer; import org.jdiameter.api.sh.events.PushNotificationRequest; import org.jdiameter.api.sh.events.SubscribeNotificationsAnswer; import org.jdiameter.api.sh.events.SubscribeNotificationsRequest; import org.jdiameter.api.sh.events.UserDataAnswer; import org.jdiameter.api.sh.events.UserDataRequest; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.common.impl.app.sh.ProfileUpdateAnswerImpl; import org.jdiameter.common.impl.app.sh.PushNotificationRequestImpl; import org.jdiameter.common.impl.app.sh.SubscribeNotificationsAnswerImpl; import org.jdiameter.common.impl.app.sh.UserDataAnswerImpl; import org.mobicents.diameter.stack.functional.Utils; /** * Base implementation of Server * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class ServerPNR extends org.mobicents.diameter.stack.functional.sh.AbstractServer { protected boolean sentSubscribeNotifications; protected boolean sentProfileUpdate; protected boolean sentUserData; protected boolean sentPushNotification; protected boolean receiveSubscribeNotifications; protected boolean receiveProfileUpdate; protected boolean receiveUserData; protected boolean receivePushNotification; protected SubscribeNotificationsRequest subscribeNotificationsRequest; protected ProfileUpdateRequest profileUpdateRequest; protected UserDataRequest userDataRequest; // ------- send methods to trigger answer public void sendSubscribeNotifications() throws Exception { if (!this.receiveSubscribeNotifications || this.subscribeNotificationsRequest == null) { fail("Did not receive SUBSCRIBE or answer already sent.", null); throw new Exception("Did not receive SUBSCRIBE or answer already sent. Request: " + this.subscribeNotificationsRequest); } SubscribeNotificationsAnswer answer = new SubscribeNotificationsAnswerImpl((Request) this.subscribeNotificationsRequest.getMessage(), 2001); AvpSet reqSet = subscribeNotificationsRequest.getMessage().getAvps(); AvpSet set = answer.getMessage().getAvps(); set.removeAvp(Avp.DESTINATION_HOST); set.removeAvp(Avp.DESTINATION_REALM); set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID)); this.serverShSession.sendSubscribeNotificationsAnswer(answer); Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true); this.subscribeNotificationsRequest = null; } public void sendProfileUpdate() throws Exception { if (!this.receiveProfileUpdate || this.profileUpdateRequest == null) { fail("Did not receive UPDATE or answer already sent.", null); throw new Exception("Did not receive UPDATE or answer already sent. Request: " + this.profileUpdateRequest); } ProfileUpdateAnswer answer = new ProfileUpdateAnswerImpl((Request) this.profileUpdateRequest.getMessage(), 2001); AvpSet reqSet = profileUpdateRequest.getMessage().getAvps(); AvpSet set = answer.getMessage().getAvps(); set.removeAvp(Avp.DESTINATION_HOST); set.removeAvp(Avp.DESTINATION_REALM); set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID)); this.serverShSession.sendProfileUpdateAnswer(answer); Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true); this.profileUpdateRequest = null; } public void sendUserData() throws Exception { if (!this.receiveUserData || this.userDataRequest == null) { fail("Did not receive USER DATA or answer already sent.", null); throw new Exception("Did not receive USER DATA or answer already sent. Request: " + this.userDataRequest); } UserDataAnswer answer = new UserDataAnswerImpl((Request) this.userDataRequest.getMessage(), 2001); AvpSet reqSet = userDataRequest.getMessage().getAvps(); AvpSet set = answer.getMessage().getAvps(); set.removeAvp(Avp.DESTINATION_HOST); set.removeAvp(Avp.DESTINATION_REALM); set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID)); this.serverShSession.sendUserDataAnswer(answer); Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true); this.userDataRequest = null; } public void sendPushNotification() throws Exception { if (super.serverShSession == null) { super.serverShSession = ((ISessionFactory) this.sessionFactory).getNewAppSession(this.sessionFactory.getSessionId("xxTESTxx"), getApplicationId(), ServerShSession.class, (Object) null); } PushNotificationRequest request = new PushNotificationRequestImpl(super.serverShSession.getSessions().get(0) .createRequest(PushNotificationRequestImpl.code, getApplicationId(), getClientRealmName())); AvpSet avpSet = request.getMessage().getAvps(); // < Push-Notification-Request > ::= < Diameter Header: 309, REQ, PXY, 16777217 > // < Session-Id > // { Vendor-Specific-Application-Id } AvpSet vendorSpecificApplicationId = avpSet.addGroupedAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, 0, false, false); // 1* [ Vendor-Id ] vendorSpecificApplicationId.addAvp(Avp.VENDOR_ID, getApplicationId().getVendorId(), true); // 0*1{ Auth-Application-Id } vendorSpecificApplicationId.addAvp(Avp.AUTH_APPLICATION_ID, getApplicationId().getAuthAppId(), true); // avpSet.addAvp(Avp.AUTH_SESSION_STATE,1); // { Origin-Host } avpSet.removeAvp(Avp.ORIGIN_HOST); avpSet.addAvp(Avp.ORIGIN_HOST, getServerURI(), true); // { Origin-Realm } // { Destination-Host } avpSet.addAvp(Avp.ORIGIN_HOST, getClientURI(), true); // { Destination-Realm } // *[ Supported-Features ] // { User-Identity } AvpSet userIdentity = avpSet.addGroupedAvp(Avp.USER_IDENTITY, getApplicationId().getVendorId(), true, false); // User-Identity ::= <AVP header: 700 10415> // [Public-Identity] userIdentity.addAvp(Avp.PUBLIC_IDENTITY, "tralalalal user", getApplicationId().getVendorId(), true, false, false); // [MSISDN] // *[AVP] // [ Wildcarded-PSI ] // [ Wildcarded-IMPU ] // { User-Data } avpSet.addAvp(Avp.USER_DATA_SH, "<xml><morexml></morexml></xml>", true); // *[ AVP ] // *[ Proxy-Info ] // *[ Route-Record ] this.serverShSession.sendPushNotificationRequest(request); this.sentPushNotification = true; Utils.printMessage(log, super.stack.getDictionary(), request.getMessage(), true); } // ------- initial, this will be triggered for first msg. /* * (non-Javadoc) * * @see org.jdiameter.api.NetworkReqListener#processRequest(org.jdiameter.api.Request) */ @Override public Answer processRequest(Request request) { int code = request.getCommandCode(); if (code != ProfileUpdateRequest.code && code != UserDataRequest.code && code != SubscribeNotificationsRequest.code) { fail("Received Request with code not used by Sh!. Code[" + request.getCommandCode() + "]", null); return null; } if (super.serverShSession == null) { try { super.serverShSession = ((ISessionFactory) this.sessionFactory).getNewAppSession(request.getSessionId(), getApplicationId(), ServerShSession.class, (Object) null); ((NetworkReqListener) this.serverShSession).processRequest(request); } catch (Exception e) { fail(null, e); } } else { // do fail? fail("Received Request in base listener, not in app specific!" + code, null); } return null; } // ------------- specific, app session listener. /* * (non-Javadoc) * * @see org.jdiameter.api.cca.ServerRoSessionListener#doOtherEvent(org.jdiameter.api.app.AppSession, * org.jdiameter.api.app.AppRequestEvent, org.jdiameter.api.app.AppAnswerEvent) */ public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { fail("Received \"Other\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); } public void doSubscribeNotificationsRequestEvent(ServerShSession session, SubscribeNotificationsRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { if (this.receiveSubscribeNotifications) { fail("Received SUBSCRIBE more than once!", null); } this.receiveSubscribeNotifications = true; this.subscribeNotificationsRequest = request; } public void doProfileUpdateRequestEvent(ServerShSession session, ProfileUpdateRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { if (this.receiveProfileUpdate) { fail("Received UPDATE more than once!", null); } this.receiveProfileUpdate = true; this.profileUpdateRequest = request; } public void doPushNotificationAnswerEvent(ServerShSession session, PushNotificationRequest request, PushNotificationAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { if (this.receivePushNotification) { fail("Received NOTIFICATION more than once!", null); } this.receivePushNotification = true; } public void doUserDataRequestEvent(ServerShSession session, UserDataRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { if (this.receiveUserData) { fail("Received USER DATA more than once!", null); } this.receiveUserData = true; this.userDataRequest = request; } @Override public void receivedSuccessMessage(Request request, Answer answer) { fail("Received \"SuccessMessage\" event, request[" + request + "], answer[" + answer + "]", null); } @Override public void timeoutExpired(Request request) { fail("Received \"Timoeout\" event, request[" + request + "]", null); } public boolean isSentSubscribeNotifications() { return sentSubscribeNotifications; } public boolean isSentProfileUpdate() { return sentProfileUpdate; } public boolean isSentUserData() { return sentUserData; } public boolean isSentPushNotification() { return sentPushNotification; } public boolean isReceiveSubscribeNotifications() { return receiveSubscribeNotifications; } public boolean isReceiveProfileUpdate() { return receiveProfileUpdate; } public boolean isReceiveUserData() { return receiveUserData; } public boolean isReceivePushNotification() { return receivePushNotification; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual * contributors as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a full listing * of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License, v. 2.0. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License, * v. 2.0 along with this distribution; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.mobicents.diameter.stack.functional.sh.base; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpSet; import org.jdiameter.api.IllegalDiameterStateException; import org.jdiameter.api.InternalException; import org.jdiameter.api.OverloadException; import org.jdiameter.api.RouteException; import org.jdiameter.api.app.AppAnswerEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.sh.ClientShSession; import org.jdiameter.api.sh.events.ProfileUpdateAnswer; import org.jdiameter.api.sh.events.ProfileUpdateRequest; import org.jdiameter.api.sh.events.PushNotificationRequest; import org.jdiameter.api.sh.events.SubscribeNotificationsAnswer; import org.jdiameter.api.sh.events.SubscribeNotificationsRequest; import org.jdiameter.api.sh.events.UserDataAnswer; import org.jdiameter.api.sh.events.UserDataRequest; import org.jdiameter.common.impl.app.sh.ProfileUpdateRequestImpl; import org.mobicents.diameter.stack.functional.Utils; import org.mobicents.diameter.stack.functional.sh.AbstractClient; /** * Base implementation of Client * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class ClientPUR extends AbstractClient { protected boolean sentSubscribeNotifications; protected boolean sentProfileUpdate; protected boolean sentUserData; protected boolean sentPushNotification; protected boolean receiveSubscribeNotifications; protected boolean receiveProfileUpdate; protected boolean receiveUserData; protected boolean receivePushNotification; /** * */ public ClientPUR() { } public void sendProfileUpdate() throws Exception { ProfileUpdateRequest request = new ProfileUpdateRequestImpl(super.clientShSession.getSessions().get(0) .createRequest(ProfileUpdateRequest.code, getApplicationId(), getServerRealmName())); AvpSet avpSet = request.getMessage().getAvps(); // < Profile-Update-Request > ::= < Diameter Header: 307, REQ, PXY, 16777217 > // < Session-Id > AvpSet vendorSpecificApplicationId = avpSet.addGroupedAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, 0, false, false); // 1* [ Vendor-Id ] vendorSpecificApplicationId.addAvp(Avp.VENDOR_ID, getApplicationId().getVendorId(), true); // 0*1{ Auth-Application-Id } vendorSpecificApplicationId.addAvp(Avp.AUTH_APPLICATION_ID, getApplicationId().getAuthAppId(), true); // 0*1{ Acct-Application-Id } // { Auth-Session-State } avpSet.addAvp(Avp.AUTH_SESSION_STATE, 1); // { Origin-Host } avpSet.removeAvp(Avp.ORIGIN_HOST); avpSet.addAvp(Avp.ORIGIN_HOST, getClientURI(), true); // { Origin-Realm } // [ Destination-Host ] // { Destination-Realm } // *[ Supported-Features ] // { User-Identity } AvpSet userIdentity = avpSet.addGroupedAvp(Avp.USER_IDENTITY, getApplicationId().getVendorId(), true, false); // User-Identity ::= <AVP header: 700 10415> // [Public-Identity] userIdentity.addAvp(Avp.PUBLIC_IDENTITY, "tralalalal user", getApplicationId().getVendorId(), true, false, false); // [MSISDN] // *[AVP] // [ Wildcarded-PSI ] // [ Wildcarded-IMPU ] // { Data-Reference } avpSet.addAvp(Avp.DATA_REFERENCE, 0); // { User-Data } // *[ AVP ] super.clientShSession.sendProfileUpdateRequest(request); Utils.printMessage(log, super.stack.getDictionary(), request.getMessage(), true); this.sentProfileUpdate = true; } // ------------ event handlers; public void doSubscribeNotificationsAnswerEvent(ClientShSession session, SubscribeNotificationsRequest request, SubscribeNotificationsAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { receiveSubscribeNotifications = true; fail("Received \"SNA\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); } public void doProfileUpdateAnswerEvent(ClientShSession session, ProfileUpdateRequest request, ProfileUpdateAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { receiveProfileUpdate = true; } public void doPushNotificationRequestEvent(ClientShSession session, PushNotificationRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { receivePushNotification = true; fail("Received \"PNR\" event, request[" + request + "], on session[" + session + "]", null); } public void doUserDataAnswerEvent(ClientShSession session, UserDataRequest request, UserDataAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { receiveUserData = true; fail("Received \"UDA\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); } public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { fail("Received \"Other\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); } @Override protected String getClientURI() { return clientURI; } public boolean isSentSubscribeNotifications() { return sentSubscribeNotifications; } public boolean isSentProfileUpdate() { return sentProfileUpdate; } public boolean isSentUserData() { return sentUserData; } public boolean isSentPushNotification() { return sentPushNotification; } public boolean isReceiveSubscribeNotifications() { return receiveSubscribeNotifications; } public boolean isReceiveProfileUpdate() { return receiveProfileUpdate; } public boolean isReceiveUserData() { return receiveUserData; } public boolean isReceivePushNotification() { return receivePushNotification; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual * contributors as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a full listing * of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License, v. 2.0. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License, * v. 2.0 along with this distribution; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.mobicents.diameter.stack.functional.sh.base; import java.io.InputStream; import org.jdiameter.api.Answer; import org.jdiameter.api.ApplicationId; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpSet; import org.jdiameter.api.IllegalDiameterStateException; import org.jdiameter.api.InternalException; import org.jdiameter.api.NetworkReqListener; import org.jdiameter.api.OverloadException; import org.jdiameter.api.Request; import org.jdiameter.api.RouteException; import org.jdiameter.api.app.AppAnswerEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.sh.ClientShSession; import org.jdiameter.api.sh.ServerShSession; import org.jdiameter.api.sh.events.ProfileUpdateAnswer; import org.jdiameter.api.sh.events.ProfileUpdateRequest; import org.jdiameter.api.sh.events.PushNotificationAnswer; import org.jdiameter.api.sh.events.PushNotificationRequest; import org.jdiameter.api.sh.events.SubscribeNotificationsAnswer; import org.jdiameter.api.sh.events.SubscribeNotificationsRequest; import org.jdiameter.api.sh.events.UserDataAnswer; import org.jdiameter.api.sh.events.UserDataRequest; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.common.impl.app.sh.PushNotificationAnswerImpl; import org.jdiameter.common.impl.app.sh.ShSessionFactoryImpl; import org.mobicents.diameter.stack.functional.Utils; import org.mobicents.diameter.stack.functional.sh.AbstractClient; /** * Base implementation of Client * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class ClientPNR extends AbstractClient { protected boolean sentSubscribeNotifications; protected boolean sentProfileUpdate; protected boolean sentUserData; protected boolean sentPushNotification; protected boolean receiveSubscribeNotifications; protected boolean receiveProfileUpdate; protected boolean receiveUserData; protected boolean receivePushNotification; protected PushNotificationRequest request; /** * */ public ClientPNR() { } // override init, so we dont create session public void init(InputStream configStream, String clientID) throws Exception { try { super.init(configStream, clientID, ApplicationId.createByAuthAppId(10415, 16777217)); ShSessionFactoryImpl shSessionFactory = new ShSessionFactoryImpl(this.sessionFactory); ((ISessionFactory) sessionFactory).registerAppFacory(ServerShSession.class, shSessionFactory); ((ISessionFactory) sessionFactory).registerAppFacory(ClientShSession.class, shSessionFactory); shSessionFactory.setClientShSessionListener(this); } finally { try { configStream.close(); } catch (Exception e) { e.printStackTrace(); } } } public void sendPushNotification() throws Exception { if (!this.receivePushNotification || this.request == null) { fail("Did not receive NOTIFICATION or answer already sent.", null); throw new Exception("Did not receive NOTIFICATION or answer already sent. Request: " + this.request); } PushNotificationAnswer answer = new PushNotificationAnswerImpl((Request) request.getMessage(), 2001); AvpSet reqSet = request.getMessage().getAvps(); AvpSet set = answer.getMessage().getAvps(); set.removeAvp(Avp.DESTINATION_HOST); set.removeAvp(Avp.DESTINATION_REALM); set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID)); request = null; Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true); // < Push-Notification-Answer > ::=< Diameter Header: 309, PXY, 16777217 > // < Session-Id > // { Vendor-Specific-Application-Id } if (set.getAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID) == null) { AvpSet vendorSpecificApplicationId = set.addGroupedAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, 0, false, false); // 1* [ Vendor-Id ] vendorSpecificApplicationId.addAvp(Avp.VENDOR_ID, getApplicationId().getVendorId(), true); // 0*1{ Auth-Application-Id } vendorSpecificApplicationId.addAvp(Avp.AUTH_APPLICATION_ID, getApplicationId().getAuthAppId(), true); } // [ Result-Code ] // [ Experimental-Result ] // { Auth-Session-State } // { Origin-Host } // { Origin-Realm } // *[ Supported-Features ] // *[ AVP ] // *[ Failed-AVP ] // *[ Proxy-Info ] // *[ Route-Record ] Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true); super.clientShSession.sendPushNotificationAnswer(answer); this.sentPushNotification = true; } // ------------ event handlers; public void doSubscribeNotificationsAnswerEvent(ClientShSession session, SubscribeNotificationsRequest request, SubscribeNotificationsAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { receiveSubscribeNotifications = true; fail("Received \"SNR\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); } public void doProfileUpdateAnswerEvent(ClientShSession session, ProfileUpdateRequest request, ProfileUpdateAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { receiveProfileUpdate = true; fail("Received \"PUR\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); } public void doPushNotificationRequestEvent(ClientShSession session, PushNotificationRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { receivePushNotification = true; this.request = request; } public void doUserDataAnswerEvent(ClientShSession session, UserDataRequest request, UserDataAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { receiveUserData = true; fail("Received \"UDR\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); } public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { fail("Received \"Other\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); } /* * (non-Javadoc) * * @see org.jdiameter.api.NetworkReqListener#processRequest(org.jdiameter.api.Request) */ @Override public Answer processRequest(Request request) { int code = request.getCommandCode(); if (code != PushNotificationRequest.code) { fail("Received Request with code not used by Sh!. Code[" + request.getCommandCode() + "]", null); return null; } if (super.clientShSession != null) { // do fail? fail("Received Request in base listener, not in app specific!" + code, null); } else { try { super.clientShSession = ((ISessionFactory) this.sessionFactory).getNewAppSession(request.getSessionId(), getApplicationId(), ClientShSession.class, (Object) null); ((NetworkReqListener) this.clientShSession).processRequest(request); } catch (Exception e) { e.printStackTrace(); fail(null, e); } } return null; } @Override protected String getClientURI() { return clientURI; } public boolean isSentSubscribeNotifications() { return sentSubscribeNotifications; } public boolean isSentProfileUpdate() { return sentProfileUpdate; } public boolean isSentUserData() { return sentUserData; } public boolean isSentPushNotification() { return sentPushNotification; } public boolean isReceiveSubscribeNotifications() { return receiveSubscribeNotifications; } public boolean isReceiveProfileUpdate() { return receiveProfileUpdate; } public boolean isReceiveUserData() { return receiveUserData; } public boolean isReceivePushNotification() { return receivePushNotification; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual * contributors as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a full listing * of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License, v. 2.0. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License, * v. 2.0 along with this distribution; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.mobicents.diameter.stack.functional.sh.base; import org.jdiameter.api.Answer; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpSet; import org.jdiameter.api.IllegalDiameterStateException; import org.jdiameter.api.InternalException; import org.jdiameter.api.NetworkReqListener; import org.jdiameter.api.OverloadException; import org.jdiameter.api.Request; import org.jdiameter.api.RouteException; import org.jdiameter.api.app.AppAnswerEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.sh.ServerShSession; import org.jdiameter.api.sh.events.ProfileUpdateRequest; import org.jdiameter.api.sh.events.PushNotificationAnswer; import org.jdiameter.api.sh.events.PushNotificationRequest; import org.jdiameter.api.sh.events.SubscribeNotificationsAnswer; import org.jdiameter.api.sh.events.SubscribeNotificationsRequest; import org.jdiameter.api.sh.events.UserDataRequest; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.common.impl.app.sh.SubscribeNotificationsAnswerImpl; import org.mobicents.diameter.stack.functional.Utils; /** * Base implementation of Server * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class ServerSNR extends org.mobicents.diameter.stack.functional.sh.AbstractServer { protected boolean sentSubscribeNotifications; protected boolean sentProfileUpdate; protected boolean sentUserData; protected boolean sentPushNotification; protected boolean receiveSubscribeNotifications; protected boolean receiveProfileUpdate; protected boolean receiveUserData; protected boolean receivePushNotification; protected SubscribeNotificationsRequest subscribeNotificationsRequest; // ------- send methods to trigger answer public void sendSubscribeNotifications() throws Exception { if (!this.receiveSubscribeNotifications || this.subscribeNotificationsRequest == null) { fail("Did not receive SUBSCRIBE or answer already sent.", null); throw new Exception("Did not receive SUBSCRIBE or answer already sent. Request: " + this.subscribeNotificationsRequest); } SubscribeNotificationsAnswer answer = new SubscribeNotificationsAnswerImpl((Request) this.subscribeNotificationsRequest.getMessage(), 2001); AvpSet reqSet = subscribeNotificationsRequest.getMessage().getAvps(); AvpSet set = answer.getMessage().getAvps(); set.removeAvp(Avp.DESTINATION_HOST); set.removeAvp(Avp.DESTINATION_REALM); set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID)); this.serverShSession.sendSubscribeNotificationsAnswer(answer); Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true); this.subscribeNotificationsRequest = null; } // ------------- specific, app session listener. /* * (non-Javadoc) * * @see org.jdiameter.api.NetworkReqListener#processRequest(org.jdiameter.api.Request) */ @Override public Answer processRequest(Request request) { int code = request.getCommandCode(); if (code != SubscribeNotificationsRequest.code) { fail("Received Request with code not used by Sh!. Code[" + request.getCommandCode() + "]", null); return null; } if (super.serverShSession == null) { try { super.serverShSession = ((ISessionFactory) this.sessionFactory).getNewAppSession(request.getSessionId(), getApplicationId(), ServerShSession.class, (Object) null); ((NetworkReqListener) this.serverShSession).processRequest(request); } catch (Exception e) { fail(null, e); } } else { // do fail? fail("Received Request in base listener, not in app specific!" + code, null); } return null; } /* * (non-Javadoc) * * @see org.jdiameter.api.cca.ServerRoSessionListener#doOtherEvent(org.jdiameter.api.app.AppSession, * org.jdiameter.api.app.AppRequestEvent, org.jdiameter.api.app.AppAnswerEvent) */ public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { fail("Received \"Other\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); } public void doSubscribeNotificationsRequestEvent(ServerShSession session, SubscribeNotificationsRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { if (this.receiveSubscribeNotifications) { fail("Received SUBSCRIBE more than once!", null); } this.receiveSubscribeNotifications = true; this.subscribeNotificationsRequest = request; } public void doProfileUpdateRequestEvent(ServerShSession session, ProfileUpdateRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { fail("Received \"PUR\" event, request[" + request + "], on session[" + session + "]", null); this.receiveProfileUpdate = true; } public void doPushNotificationAnswerEvent(ServerShSession session, PushNotificationRequest request, PushNotificationAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { fail("Received \"PUA\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null); this.receivePushNotification = true; } public void doUserDataRequestEvent(ServerShSession session, UserDataRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { fail("Received \"UDR\" event, request[" + request + "], on session[" + session + "]", null); this.receiveUserData = true; } public boolean isSentSubscribeNotifications() { return sentSubscribeNotifications; } public boolean isSentProfileUpdate() { return sentProfileUpdate; } public boolean isSentUserData() { return sentUserData; } public boolean isSentPushNotification() { return sentPushNotification; } public boolean isReceiveSubscribeNotifications() { return receiveSubscribeNotifications; } public boolean isReceiveProfileUpdate() { return receiveProfileUpdate; } public boolean isReceiveUserData() { return receiveUserData; } public boolean isReceivePushNotification() { return receivePushNotification; } }
Java