code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package ru.gelin.android.weather.openweathermap;
import android.content.Context;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import ru.gelin.android.weather.*;
import ru.gelin.android.weather.notification.skin.impl.WeatherConditionFormat;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* Weather implementation which constructs from the JSON received from openweathermap.org
*/
public class OpenWeatherMapWeather implements Weather {
String FORECAST_URL_TEMPLATE="http://openweathermap.org/city/%d";
/** City ID */
int cityId = 0;
/** Forecast URL */
URL forecastURL;
/** Weather location */
SimpleLocation location = new SimpleLocation("");
/** Weather time */
Date time = new Date();
/** Query time */
Date queryTime = new Date();
/** Weather conditions */
List<SimpleWeatherCondition> conditions = new ArrayList<SimpleWeatherCondition>();
/** Emptyness flag */
boolean empty = true;
/** Condition text format */
WeatherConditionFormat conditionFormat;
public OpenWeatherMapWeather(Context context) {
this.conditionFormat = new WeatherConditionFormat(context);
}
public OpenWeatherMapWeather(Context context, JSONObject jsonObject) throws WeatherException {
this(context);
parseCurrentWeather(jsonObject);
}
@Override
public Location getLocation() {
return this.location;
}
@Override
public Date getTime() {
return new Date(this.time.getTime());
}
@Override
public Date getQueryTime() {
return new Date(this.queryTime.getTime());
}
@Override
public UnitSystem getUnitSystem() {
return UnitSystem.SI;
}
@Override
public List<WeatherCondition> getConditions() {
return Collections.unmodifiableList(new ArrayList<WeatherCondition>(this.conditions));
}
List<SimpleWeatherCondition> getOpenWeatherMapConditions() {
return this.conditions;
}
@Override
public boolean isEmpty() {
return this.empty;
}
public int getCityId() {
return this.cityId;
}
public URL getForecastURL() {
return this.forecastURL;
}
void parseCurrentWeather(JSONObject json) throws WeatherException {
try {
int code = json.getInt("cod");
if (code != 200) {
this.empty = true;
return;
}
parseCityId(json);
parseLocation(json);
parseTime(json);
WeatherParser parser = new CurrentWeatherParser(json);
parser.parseCondition();
} catch (JSONException e) {
throw new WeatherException("cannot parse the weather", e);
}
this.empty = false;
}
void parseDailyForecast(JSONObject json) throws WeatherException {
try {
JSONArray list = json.getJSONArray("list");
SimpleWeatherCondition condition = getCondition(0);
if (list.length() > 0) {
appendForecastTemperature(condition, list.getJSONObject(0));
condition.setConditionText(this.conditionFormat.getText(condition));
}
for (int i = 1; i < 4 && i < list.length(); i++) {
condition = getCondition(i);
parseForecast(condition, list.getJSONObject(i));
condition.setConditionText(this.conditionFormat.getText(condition));
}
} catch (JSONException e) {
throw new WeatherException("cannot parse forecasts", e);
}
}
private void parseCityId(JSONObject json) throws JSONException {
this.cityId = json.getInt("id");
try {
this.forecastURL = new URL(String.format(FORECAST_URL_TEMPLATE, this.cityId));
} catch (MalformedURLException e) {
this.forecastURL = null;
}
}
private void parseLocation(JSONObject json) {
try {
this.location = new SimpleLocation(json.getString("name"), false);
} catch (JSONException e) {
this.location = new SimpleLocation("", false);
}
}
private void parseTime(JSONObject json) {
try {
long timestamp = json.getLong("dt");
this.time = new Date(timestamp * 1000);
} catch (JSONException e) {
this.time = new Date();
}
}
private abstract class WeatherParser {
JSONObject json;
WeatherParser(JSONObject json) {
this.json = json;
}
public void parseCondition() {
SimpleWeatherCondition condition = new SimpleWeatherCondition();
condition.setTemperature(parseTemperature());
condition.setWind(parseWind());
condition.setHumidity(parseHumidity());
condition.setPrecipitation(parsePrecipitation());
condition.setCloudiness(parseCloudiness());
parseWeatherType(condition);
condition.setConditionText(OpenWeatherMapWeather.this.conditionFormat.getText(condition));
OpenWeatherMapWeather.this.conditions.add(condition);
}
private SimpleTemperature parseTemperature() {
AppendableTemperature temperature = new AppendableTemperature(TemperatureUnit.K);
JSONObject main;
if (!hasTemp()) {
//temp is optional
return temperature;
}
try {
double currentTemp = getCurrentTemp();
temperature.setCurrent((int)currentTemp, TemperatureUnit.K);
} catch (JSONException e) {
//temp is optional
}
try {
double minTemp = getMinTemp();
temperature.setLow((int)minTemp, TemperatureUnit.K);
} catch (JSONException e) {
//min temp is optional
}
try {
double maxTemp = getMaxTemp();
temperature.setHigh((int)maxTemp, TemperatureUnit.K);
} catch (JSONException e) {
//max temp is optional
}
return temperature;
}
protected abstract boolean hasTemp();
protected abstract double getCurrentTemp() throws JSONException;
protected abstract double getMinTemp() throws JSONException;
protected abstract double getMaxTemp() throws JSONException;
private SimpleWind parseWind() {
SimpleWind wind = new SimpleWind(WindSpeedUnit.MPS);
if (!hasWind()) {
return wind;
}
try {
double speed = getWindSpeed();
wind.setSpeed((int)Math.round(speed), WindSpeedUnit.MPS);
} catch (JSONException e) {
//wind speed is optional
}
try {
double deg = getWindDeg();
wind.setDirection(WindDirection.valueOf((int) deg));
} catch (JSONException e) {
//wind direction is optional
}
wind.setText(String.format("Wind: %s, %d m/s", String.valueOf(wind.getDirection()), wind.getSpeed()));
return wind;
}
protected abstract boolean hasWind();
protected abstract double getWindSpeed() throws JSONException;
protected abstract double getWindDeg() throws JSONException;
private SimpleHumidity parseHumidity() {
SimpleHumidity humidity = new SimpleHumidity();
try {
double humidityValue = getHumidity();
humidity.setValue((int)humidityValue);
humidity.setText(String.format("Humidity: %d%%", humidity.getValue()));
} catch (JSONException e) {
//humidity is optional
}
return humidity;
}
protected abstract double getHumidity() throws JSONException;
private SimplePrecipitation parsePrecipitation() {
SimplePrecipitation precipitation = new SimplePrecipitation(PrecipitationUnit.MM);
try {
precipitation.setValue(getPrecipitation(), PrecipitationPeriod.PERIOD_3H);
} catch (JSONException e) {
//no rain
}
return precipitation;
}
protected abstract float getPrecipitation() throws JSONException;
public SimpleCloudiness parseCloudiness() {
SimpleCloudiness cloudiness = new SimpleCloudiness(CloudinessUnit.PERCENT);
try {
cloudiness.setValue(getCloudiness(), CloudinessUnit.PERCENT);
} catch (JSONException e) {
//no clouds
}
return cloudiness;
}
protected abstract int getCloudiness() throws JSONException;
public void parseWeatherType(SimpleWeatherCondition condition) {
try {
JSONArray weathers = this.json.getJSONArray("weather");
for (int i = 0; i < weathers.length(); i++) {
JSONObject weather = weathers.getJSONObject(i);
WeatherConditionType type = WeatherConditionTypeFactory.fromId(weather.getInt("id"));
condition.addConditionType(type);
}
} catch (JSONException e) {
//no weather type
}
}
}
private class CurrentWeatherParser extends WeatherParser {
CurrentWeatherParser(JSONObject json) {
super(json);
}
@Override
protected boolean hasTemp() {
try {
this.json.getJSONObject("main");
return true;
} catch (JSONException e) {
return false;
}
}
@Override
protected double getCurrentTemp() throws JSONException {
return this.json.getJSONObject("main").getDouble("temp");
}
@Override
protected double getMinTemp() throws JSONException {
return this.json.getJSONObject("main").getDouble("temp_min");
}
@Override
protected double getMaxTemp() throws JSONException {
return this.json.getJSONObject("main").getDouble("temp_max");
}
@Override
protected boolean hasWind() {
try {
this.json.getJSONObject("wind");
return true;
} catch (JSONException e) {
return false;
}
}
@Override
protected double getWindSpeed() throws JSONException {
return this.json.getJSONObject("wind").getDouble("speed");
}
@Override
protected double getWindDeg() throws JSONException {
return this.json.getJSONObject("wind").getDouble("deg");
}
@Override
protected double getHumidity() throws JSONException {
return this.json.getJSONObject("main").getDouble("humidity");
}
@Override
protected float getPrecipitation() throws JSONException {
return (float)this.json.getJSONObject("rain").getDouble("3h");
}
@Override
protected int getCloudiness() throws JSONException {
return (int)this.json.getJSONObject("clouds").getDouble("all");
}
}
private class ForecastWeatherParser extends WeatherParser {
ForecastWeatherParser(JSONObject json) {
super(json);
}
@Override
protected boolean hasTemp() {
try {
this.json.getJSONObject("temp");
return true;
} catch (JSONException e) {
return false;
}
}
@Override
protected double getCurrentTemp() throws JSONException {
throw new JSONException("no current temp in forecast");
}
@Override
protected double getMinTemp() throws JSONException {
return this.json.getJSONObject("temp").getDouble("min");
}
@Override
protected double getMaxTemp() throws JSONException {
return this.json.getJSONObject("temp").getDouble("max");
}
@Override
protected boolean hasWind() {
return true; //considering forecasts always have wind
}
@Override
protected double getWindSpeed() throws JSONException {
return this.json.getDouble("speed");
}
@Override
protected double getWindDeg() throws JSONException {
return this.json.getDouble("deg");
}
@Override
protected double getHumidity() throws JSONException {
return this.json.getDouble("humidity");
}
@Override
protected float getPrecipitation() throws JSONException {
return (float)this.json.getDouble("rain");
}
@Override
protected int getCloudiness() throws JSONException {
return (int)this.json.getDouble("clouds");
}
}
private SimpleWeatherCondition getCondition(int i) {
while (i >= this.conditions.size()) {
SimpleWeatherCondition condition = new SimpleWeatherCondition();
condition.setConditionText("");
condition.setTemperature(new AppendableTemperature(TemperatureUnit.K));
condition.setHumidity(new SimpleHumidity());
condition.setWind(new SimpleWind(WindSpeedUnit.MPS));
condition.setPrecipitation(new SimplePrecipitation(PrecipitationUnit.MM));
condition.setCloudiness(new SimpleCloudiness(CloudinessUnit.PERCENT));
this.conditions.add(condition);
}
return this.conditions.get(i);
}
private void appendForecastTemperature(SimpleWeatherCondition condition, JSONObject json)
throws JSONException {
WeatherParser parser = new ForecastWeatherParser(json);
AppendableTemperature existedTemp = (AppendableTemperature)condition.getTemperature();
SimpleTemperature newTemp = parser.parseTemperature();
existedTemp.append(newTemp);
}
private void parseForecast(SimpleWeatherCondition condition, JSONObject json)
throws JSONException {
appendForecastTemperature(condition, json);
WeatherParser parser = new ForecastWeatherParser(json);
condition.setHumidity(parser.parseHumidity());
condition.setWind(parser.parseWind());
condition.setPrecipitation(parser.parsePrecipitation());
condition.setCloudiness(parser.parseCloudiness());
parser.parseWeatherType(condition);
}
}
| Java |
package ru.gelin.android.weather.openweathermap;
import android.content.Context;
import org.apache.http.client.methods.HttpGet;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import ru.gelin.android.weather.*;
import ru.gelin.android.weather.source.DebugDumper;
import ru.gelin.android.weather.source.HttpWeatherSource;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Locale;
/**
* Weather source implementation which uses openweathermap.org
*/
public class OpenWeatherMapSource extends HttpWeatherSource implements WeatherSource {
/** Base API URL */
static final String API_BASE_URL = "http://openweathermap.org/data/2.5";
/** Current weather API URL */
static final String API_WEATHER_URL = API_BASE_URL + "/weather?";
/** Forecasts API URL */
static final String API_FORECAST_URL = API_BASE_URL + "/forecast/daily?cnt=4&id=";
/** API key */
static final String API_KEY = "616a1aaacb2a1e3e3ca80c8e78455f76";
private final Context context;
private final DebugDumper debugDumper;
public OpenWeatherMapSource(Context context) {
this.context = context;
this.debugDumper = new DebugDumper(context, API_BASE_URL);
}
@Override
public Weather query(Location location) throws WeatherException {
if (location == null) {
throw new WeatherException("null location");
}
if (location.getText().startsWith("-")) {
return new TestWeather(Integer.parseInt(location.getText()));
}
if (location.getText().startsWith("+")) {
return new TestWeather(Integer.parseInt(location.getText().substring(1)));
}
OpenWeatherMapWeather weather = new OpenWeatherMapWeather(this.context);
weather.parseCurrentWeather(queryCurrentWeather(location));
if (weather.isEmpty()) {
return weather;
}
weather.parseDailyForecast(queryDailyForecast(weather.getCityId()));
return weather;
}
@Override
public Weather query(Location location, Locale locale) throws WeatherException {
return query(location);
//TODO: what to do with locale?
}
@Override
protected void prepareRequest(HttpGet request) {
request.addHeader("X-API-Key", API_KEY);
}
JSONObject queryCurrentWeather(Location location) throws WeatherException {
String url = API_WEATHER_URL + location.getQuery();
JSONTokener parser = new JSONTokener(readJSON(url));
try {
return (JSONObject)parser.nextValue();
} catch (JSONException e) {
throw new WeatherException("can't parse weather", e);
}
}
JSONObject queryDailyForecast(int cityId) throws WeatherException {
String url = API_FORECAST_URL + String.valueOf(cityId);
JSONTokener parser = new JSONTokener(readJSON(url));
try {
return (JSONObject)parser.nextValue();
} catch (JSONException e) {
throw new WeatherException("can't parse forecast", e);
}
}
String readJSON(String url) throws WeatherException {
StringBuilder result = new StringBuilder();
InputStreamReader reader = getReaderForURL(url);
char[] buf = new char[1024];
try {
int read = reader.read(buf);
while (read >= 0) {
result.append(buf, 0 , read);
read = reader.read(buf);
}
} catch (IOException e) {
throw new WeatherException("can't read weather", e);
}
String content = result.toString();
this.debugDumper.dump(url, content);
return content;
}
}
| Java |
/*
* Weather API.
* Copyright (C) 2012 Denis Nelubin aka Gelin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* http://gelin.ru
* mailto:den@gelin.ru
*/
package ru.gelin.android.weather.openweathermap;
import ru.gelin.android.weather.Location;
/**
* Wrapper for Android location to query OpenWeatherMap.org API with geo coordinates.
*/
public class AndroidOpenWeatherMapLocation implements Location {
/** Query template */
static final String QUERY = "lat=%s&lon=%s"; //lat=54.96&lon=73.38
/** Android location */
android.location.Location location;
/**
* Creates the location from Android location.
*/
public AndroidOpenWeatherMapLocation(android.location.Location location) {
this.location = location;
}
/**
* Creates the query with geo coordinates.
* For example: "lat=54.96&lon=73.38"
*/
//@Override
public String getQuery() {
if (location == null) {
return "";
}
return String.format(QUERY,
String.valueOf(location.getLatitude()),
String.valueOf(location.getLongitude()));
}
//@Override
public String getText() {
if (location == null) {
return "";
}
return android.location.Location.convert(location.getLatitude(),
android.location.Location.FORMAT_DEGREES) +
"," +
android.location.Location.convert(location.getLongitude(),
android.location.Location.FORMAT_DEGREES);
}
//@Override
public boolean isEmpty() {
return this.location == null;
}
@Override
public boolean isGeo() {
return true;
}
}
| Java |
package ru.gelin.android.weather.openweathermap;
import ru.gelin.android.weather.WeatherConditionType;
import java.util.HashMap;
import java.util.Map;
/**
* Creates the weather condition type by the ID.
*/
public class WeatherConditionTypeFactory {
static private Map<Integer, WeatherConditionType> ID_MAP = new HashMap<Integer, WeatherConditionType>();
static {
ID_MAP.put(200, WeatherConditionType.THUNDERSTORM_RAIN_LIGHT);
ID_MAP.put(201, WeatherConditionType.THUNDERSTORM_RAIN);
ID_MAP.put(202, WeatherConditionType.THUNDERSTORM_RAIN_HEAVY);
ID_MAP.put(210, WeatherConditionType.THUNDERSTORM_LIGHT);
ID_MAP.put(211, WeatherConditionType.THUNDERSTORM);
ID_MAP.put(212, WeatherConditionType.THUNDERSTORM_HEAVY);
ID_MAP.put(221, WeatherConditionType.THUNDERSTORM_RAGGED);
ID_MAP.put(230, WeatherConditionType.THUNDERSTORM_DRIZZLE_LIGHT);
ID_MAP.put(231, WeatherConditionType.THUNDERSTORM_DRIZZLE);
ID_MAP.put(232, WeatherConditionType.THUNDERSTORM_DRIZZLE_HEAVY);
ID_MAP.put(300, WeatherConditionType.DRIZZLE_LIGHT);
ID_MAP.put(301, WeatherConditionType.DRIZZLE);
ID_MAP.put(302, WeatherConditionType.DRIZZLE_HEAVY);
ID_MAP.put(310, WeatherConditionType.DRIZZLE_RAIN_LIGHT);
ID_MAP.put(311, WeatherConditionType.DRIZZLE_RAIN);
ID_MAP.put(312, WeatherConditionType.DRIZZLE_RAIN_HEAVY);
ID_MAP.put(321, WeatherConditionType.DRIZZLE_SHOWER);
ID_MAP.put(500, WeatherConditionType.RAIN_LIGHT);
ID_MAP.put(501, WeatherConditionType.RAIN);
ID_MAP.put(502, WeatherConditionType.RAIN_HEAVY);
ID_MAP.put(503, WeatherConditionType.RAIN_VERY_HEAVY);
ID_MAP.put(504, WeatherConditionType.RAIN_EXTREME);
ID_MAP.put(511, WeatherConditionType.RAIN_FREEZING);
ID_MAP.put(520, WeatherConditionType.RAIN_SHOWER_LIGHT);
ID_MAP.put(521, WeatherConditionType.RAIN_SHOWER);
ID_MAP.put(522, WeatherConditionType.RAIN_SHOWER_HEAVY);
ID_MAP.put(600, WeatherConditionType.SNOW_LIGHT);
ID_MAP.put(601, WeatherConditionType.SNOW);
ID_MAP.put(602, WeatherConditionType.SNOW_HEAVY);
ID_MAP.put(611, WeatherConditionType.SLEET);
ID_MAP.put(621, WeatherConditionType.SNOW_SHOWER);
ID_MAP.put(701, WeatherConditionType.MIST);
ID_MAP.put(711, WeatherConditionType.SMOKE);
ID_MAP.put(721, WeatherConditionType.HAZE);
ID_MAP.put(731, WeatherConditionType.SAND_WHIRLS);
ID_MAP.put(741, WeatherConditionType.FOG);
ID_MAP.put(800, WeatherConditionType.CLOUDS_CLEAR);
ID_MAP.put(801, WeatherConditionType.CLOUDS_FEW);
ID_MAP.put(802, WeatherConditionType.CLOUDS_SCATTERED);
ID_MAP.put(803, WeatherConditionType.CLOUDS_BROKEN);
ID_MAP.put(804, WeatherConditionType.CLOUDS_OVERCAST);
ID_MAP.put(900, WeatherConditionType.TORNADO);
ID_MAP.put(901, WeatherConditionType.TROPICAL_STORM);
ID_MAP.put(902, WeatherConditionType.HURRICANE);
ID_MAP.put(903, WeatherConditionType.COLD);
ID_MAP.put(904, WeatherConditionType.HOT);
ID_MAP.put(905, WeatherConditionType.WINDY);
ID_MAP.put(906, WeatherConditionType.HAIL);
}
static public WeatherConditionType fromId(int id) {
return ID_MAP.get(id);
}
private WeatherConditionTypeFactory() {
//avoid instantiation
}
}
| Java |
/*
* Weather API.
* Copyright (C) 2012 Denis Nelubin aka Gelin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* http://gelin.ru
* mailto:den@gelin.ru
*/
package ru.gelin.android.weather.openweathermap;
import ru.gelin.android.weather.Location;
import ru.gelin.android.weather.source.HttpWeatherSource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* Wrapper for a text query to ask OpenWeatherMap.org API by the city name.
* The lat and lon parameters are passed to API for tracking purposes.
*/
public class NameOpenWeatherMapLocation implements Location {
/** Query template */
static final String QUERY = "q=%s"; //q=omsk
/** Query template */
static final String QUERY_WITH_LOCATION = "q=%s&lat=%s&lon=%s"; //q=omsk&lat=54.96&lon=73.38
/** Name */
String name;
/** Android location */
android.location.Location location;
/**
* Creates the location for the name and android location
*/
public NameOpenWeatherMapLocation(String name, android.location.Location location) {
this.name = name;
this.location = location;
}
/**
* Creates the query with name.
*/
//@Override
public String getQuery() {
try {
if (this.location == null) {
return String.format(QUERY,
URLEncoder.encode(this.name, HttpWeatherSource.ENCODING));
} else {
return String.format(QUERY_WITH_LOCATION,
URLEncoder.encode(this.name, HttpWeatherSource.ENCODING),
String.valueOf(location.getLatitude()),
String.valueOf(location.getLongitude()));
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); //never happens
}
}
//@Override
public String getText() {
return this.name;
}
//@Override
public boolean isEmpty() {
return this.name == null;
}
@Override
public boolean isGeo() {
return false;
}
}
| Java |
package com.custom.collegeannotation;
public class Foo {
public static void main(String[] args) {
try {
// System.out.println(10/0);
System.out.println("Added Syss ");
System.out.println(getInfo("hello"));
// Try with multi catch block
} catch (ArithmeticException | NullPointerException exception) {
System.out.println(exception);
}
}
public static String getInfo(String s) {
s.toLowerCase();
return null;
}
}
| Java |
package com.custom.collegeannotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Inherited
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface CollegeDetails {
public String name() default "";
public String value() default "mfcs";
public String id();
}
| Java |
package com.college.library;
import com.custom.collegeannotation.CollegeDetails;
@CollegeDetails(name="jbiet", id = "hello")
public class Library {
private String deptId;
private String studentName;
private String collegeName;
public Library()
{
//no operations
}
public Library(String deptId, String studentName, String collegeName) {
//super();
this.deptId = deptId;
this.studentName = studentName;
this.collegeName = collegeName;
}
public void getDetails()
{
System.out.println("hello");
System.out.println("Update");
}
}
| Java |
package com.college.library;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import com.custom.collegeannotation.CollegeDetails;
public class Test {
public static void main(String[] args) {
Library library = new Library("naveen", "hyd", "banglore");
library.getDetails();
Class<? extends Library> c = library.getClass();
System.out.println(c);
CollegeDetails cg = c.getAnnotation(CollegeDetails.class);
System.out.println(cg);
System.out.println("class::" + cg.value());
// c.getAnnotation(Class<A> CollegeDetails.class);
// System.out.println(o);
Constructor<Library>[] cc = (Constructor<Library>[]) c
.getConstructors();
for (Constructor<Library> l : cc) {
Annotation[] a = l.getAnnotations();
for (Annotation aa : a) {
// System.out.println(((CollegeDetails)aa).name());
}
}
/*
* Annotation[] annon=c.getAnnotations();
* //System.out.println(annon[0]); for(Annotation ann:annon) {
* System.out.println(((CollegeDetails)ann).name());
*
* }
*/
Method[] m = c.getMethods();
for (Method mm : m) {
Annotation[] a = mm.getDeclaredAnnotations();
for (Annotation cd : a) {
/*
* System.out.println(((CollegeDetails) cd).name());
* System.out.println(((CollegeDetails) cd).value());
*/
}
}
// System.out.println(d.name());
// System.out.println(d.value());
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* 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.smsc.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 |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* 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.smsc.server.bootstrap;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.log4j.Logger;
/**
*
* @author kulikov
*/
public class Configuration {
private final static String HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n " +
"<deployment xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
"xsi:schemaLocation=\"urn:jboss:bean-deployer:2.0 bean-deployer_2_0.xsd\" " +
"xmlns=\"urn:jboss:bean-deployer:2.0\">\n";
private final static String FOOTER = "</deployment>";
private File file;
private File directory;
private boolean isDirectory;
private long lastModified;
private Logger logger = Logger.getLogger(Configuration.class);
public Configuration(String s, File directory) {
this.directory = directory;
}
public String getBeans() throws IOException {
String config = "";
File[] files = directory.listFiles();
for (File file : files) {
if (!file.isDirectory()) {
logger.info("Configuring " + file);
String description = read(file);
int p1 = description.indexOf("<xml");
int p2 = description.indexOf('>', p1);
description = description.substring(p2 + 1);
p1 = description.indexOf("<deployment");
p2 = description.indexOf('>', p1);
description = description.substring(p2 + 1);
description = description.replaceFirst("</deployment>", "");
config += "\n" + description;
} else {
logger.info("Reading directory " + file);
Configuration conf = new Configuration("",file);
config += conf.getBeans();
}
}
return config;
}
public URL getConfig() throws IOException {
String s = HEADER + getBeans() + FOOTER;
//creating temp dir on one level top
File tempDir = new File(directory.getParent() + File.separator + "temp");
tempDir.mkdir();
//creating aggegated deployement descriptor
String temp = tempDir.getPath() + File.separator + "deployment-beans.xml";
//write descriptor
FileOutputStream fout = new FileOutputStream(temp, false);
fout.write(s.getBytes());
fout.flush();
fout.close();
File deployment = new File(temp);
return deployment.toURI().toURL();
}
private String read(File file) throws IOException {
//create local buffer
ByteArrayOutputStream bout = new ByteArrayOutputStream();
//opening file
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
} catch (FileNotFoundException e) {
}
//fetching data from file to local buffer
try {
int b = -1;
while ((b = fin.read()) != -1) {
bout.write(b);
}
} finally {
fin.close();
}
//creating string
return new String(bout.toByteArray());
}
public Configuration(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 |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* 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.smsc.server.bootstrap;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Set;
import org.apache.log4j.Logger;
import org.jboss.kernel.Kernel;
import org.jboss.kernel.plugins.deployment.xml.BasicXMLDeployer;
import org.jboss.kernel.spi.deployment.KernelDeployment;
/**
* 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 {
/** JBoss microconatiner kernel */
private Kernel kernel;
/** Basic deployer */
private BasicXMLDeployer kernelDeployer;
private KernelDeployment deployment;
/** Filter for selecting descriptors */
private FileFilter fileFilter;
/** Root deployment directory as string */
private String path;
/** Root deployment directory as file object */
private File root;
/** Logger instance */
private Logger logger = Logger.getLogger(MainDeployer.class);
/**
* Creates new instance of deployer.
*/
public MainDeployer() {
}
/**
* Gets the path to the to the root deployment directory.
*
* @return path to deployment directory.
*/
public String getPath() {
return path;
}
/**
* Modify the path to the root deployment directory
*
* @param path
*/
public void setPath(String path) {
this.path = path;
root = new File(path);
}
/**
* 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) throws Throwable {
TestVersion version = TestVersion.instance;
this.kernel = kernel;
this.kernelDeployer = kernelDeployer;
try {
Configuration d = new Configuration("root", root);
URL url = d.getConfig();
deployment = kernelDeployer.deploy(url);
kernelDeployer.validate();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("[[[[[[[[[ " + version.toString() + " Started " + "]]]]]]]]]");
}
/**
* Shuts down deployer.
*/
public void stop() {
kernelDeployer.undeploy(deployment);
logger.info("Stopped");
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* 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.smsc.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>
*/
public class Main {
private final static String HOME_DIR = "SMSC_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 SMSC_HOME = "smsc.home.dir";
public static final String SMSC_DATA = "smsc.data.dir";
public static final String SMSC_BIND_ADDRESS = "smsc.bind.address";
private static final String LINKSET_PERSIST_DIR_KEY = "linkset.persist.dir";
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(SMSC_HOME, homeDir);
System.setProperty(SMSC_DATA, homeDir + File.separator + "data" + File.separator);
//This is for SS7 configuration file persistence
System.setProperty(LINKSET_PERSIST_DIR_KEY, homeDir + File.separator + "ss7" );
if (!initLOG4JProperties(homeDir) && !initLOG4JXml(homeDir)) {
logger.error("Failed to initialize loggin, no configuration. Defaults are used.");
}
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 Media Server");
int c;
String arg;
LongOpt[] longopts = new LongOpt[2];
longopts[0] = new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h');
longopts[1] = new LongOpt("host", LongOpt.REQUIRED_ARGUMENT, null, 'b');
Getopt g = new Getopt("SMSC", 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(SMSC_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 SMSC 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(SMSC_BIND_ADDRESS) == null) {
System.setProperty(SMSC_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 = "${" + SMSC_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) throws Throwable {
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 |
package org.mobicents.smsc.ihub;
import org.mobicents.protocols.ss7.map.MAPStackImpl;
import org.mobicents.protocols.ss7.map.api.MAPProvider;
import org.mobicents.protocols.ss7.sccp.impl.SccpStackImpl;
public class MAPSimulator {
// MAP
private MAPStackImpl mapStack;
private MAPProvider mapProvider;
// SCCP
private SccpStackImpl sccpStack;
// SSn
private int ssn;
private MAPListener mapListener = null;
public MAPSimulator() {
}
public SccpStackImpl getSccpStack() {
return sccpStack;
}
public void setSccpStack(SccpStackImpl sccpStack) {
this.sccpStack = sccpStack;
}
public int getSsn() {
return ssn;
}
public void setSsn(int ssn) {
this.ssn = ssn;
}
public void start() {
// Create MAP Stack and register listener
this.mapStack = new MAPStackImpl(this.sccpStack.getSccpProvider(), this.getSsn());
this.mapProvider = this.mapStack.getMAPProvider();
this.mapListener = new MAPListener(this);
this.mapProvider.addMAPDialogListener(this.mapListener);
this.mapProvider.getMAPServiceSms().addMAPServiceListener(this.mapListener);
this.mapProvider.getMAPServiceSms().acivate();
this.mapStack.start();
}
public void stop() {
this.mapStack.stop();
}
protected MAPProvider getMapProvider() {
return mapProvider;
}
}
| Java |
package org.mobicents.smsc.ihub;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.log4j.Logger;
import org.mobicents.protocols.ss7.map.api.MAPDialog;
import org.mobicents.protocols.ss7.map.api.MAPDialogListener;
import org.mobicents.protocols.ss7.map.api.MAPException;
import org.mobicents.protocols.ss7.map.api.MAPMessage;
import org.mobicents.protocols.ss7.map.api.dialog.MAPAbortProviderReason;
import org.mobicents.protocols.ss7.map.api.dialog.MAPAbortSource;
import org.mobicents.protocols.ss7.map.api.dialog.MAPNoticeProblemDiagnostic;
import org.mobicents.protocols.ss7.map.api.dialog.MAPRefuseReason;
import org.mobicents.protocols.ss7.map.api.dialog.MAPUserAbortChoice;
import org.mobicents.protocols.ss7.map.api.errors.AbsentSubscriberDiagnosticSM;
import org.mobicents.protocols.ss7.map.api.errors.MAPErrorMessage;
import org.mobicents.protocols.ss7.map.api.errors.MAPErrorMessageAbsentSubscriberSM;
import org.mobicents.protocols.ss7.map.api.errors.MAPErrorMessageFactory;
import org.mobicents.protocols.ss7.map.api.primitives.AddressNature;
import org.mobicents.protocols.ss7.map.api.primitives.AddressString;
import org.mobicents.protocols.ss7.map.api.primitives.IMSI;
import org.mobicents.protocols.ss7.map.api.primitives.ISDNAddressString;
import org.mobicents.protocols.ss7.map.api.primitives.MAPExtensionContainer;
import org.mobicents.protocols.ss7.map.api.primitives.NumberingPlan;
import org.mobicents.protocols.ss7.map.api.service.sms.AlertServiceCentreRequest;
import org.mobicents.protocols.ss7.map.api.service.sms.AlertServiceCentreResponse;
import org.mobicents.protocols.ss7.map.api.service.sms.ForwardShortMessageRequest;
import org.mobicents.protocols.ss7.map.api.service.sms.ForwardShortMessageResponse;
import org.mobicents.protocols.ss7.map.api.service.sms.InformServiceCentreRequest;
import org.mobicents.protocols.ss7.map.api.service.sms.LocationInfoWithLMSI;
import org.mobicents.protocols.ss7.map.api.service.sms.MAPDialogSms;
import org.mobicents.protocols.ss7.map.api.service.sms.MAPServiceSmsListener;
import org.mobicents.protocols.ss7.map.api.service.sms.MoForwardShortMessageRequest;
import org.mobicents.protocols.ss7.map.api.service.sms.MoForwardShortMessageResponse;
import org.mobicents.protocols.ss7.map.api.service.sms.MtForwardShortMessageRequest;
import org.mobicents.protocols.ss7.map.api.service.sms.MtForwardShortMessageResponse;
import org.mobicents.protocols.ss7.map.api.service.sms.ReportSMDeliveryStatusRequest;
import org.mobicents.protocols.ss7.map.api.service.sms.ReportSMDeliveryStatusResponse;
import org.mobicents.protocols.ss7.map.api.service.sms.SendRoutingInfoForSMRequest;
import org.mobicents.protocols.ss7.map.api.service.sms.SendRoutingInfoForSMResponse;
import org.mobicents.protocols.ss7.map.api.service.sms.SmsSignalInfo;
import org.mobicents.protocols.ss7.map.api.smstpdu.AddressField;
import org.mobicents.protocols.ss7.map.api.smstpdu.SmsSubmitTpdu;
import org.mobicents.protocols.ss7.map.api.smstpdu.SmsTpdu;
import org.mobicents.protocols.ss7.map.api.smstpdu.SmsTpduType;
import org.mobicents.protocols.ss7.map.primitives.IMSIImpl;
import org.mobicents.protocols.ss7.map.primitives.ISDNAddressStringImpl;
import org.mobicents.protocols.ss7.map.service.sms.LocationInfoWithLMSIImpl;
import org.mobicents.protocols.ss7.tcap.asn.ApplicationContextName;
import org.mobicents.protocols.ss7.tcap.asn.comp.Problem;
public class MAPListener implements MAPDialogListener, MAPServiceSmsListener {
private static final Logger logger = Logger.getLogger(MAPListener.class);
private MAPSimulator iHubManagement = null;
private final AtomicLong mapMessagesReceivedCounter = new AtomicLong(0);
private long currentMapMessageCount = 0;
private final MAPErrorMessageFactory mAPErrorMessageFactory;
protected MAPListener(MAPSimulator iHubManagement) {
this.iHubManagement = iHubManagement;
this.mAPErrorMessageFactory = this.iHubManagement.getMapProvider().getMAPErrorMessageFactory();
}
/**
* Dialog Listener
*/
@Override
public void onDialogAccept(MAPDialog arg0, MAPExtensionContainer arg1) {
// TODO Auto-generated method stub
}
@Override
public void onDialogClose(MAPDialog arg0) {
// TODO Auto-generated method stub
}
@Override
public void onDialogDelimiter(MAPDialog arg0) {
// TODO Auto-generated method stub
}
@Override
public void onDialogNotice(MAPDialog arg0, MAPNoticeProblemDiagnostic arg1) {
// TODO Auto-generated method stub
}
@Override
public void onDialogProviderAbort(MAPDialog arg0, MAPAbortProviderReason arg1, MAPAbortSource arg2,
MAPExtensionContainer arg3) {
// TODO Auto-generated method stub
}
@Override
public void onDialogRelease(MAPDialog arg0) {
// TODO Auto-generated method stub
}
@Override
public void onDialogRequest(MAPDialog arg0, AddressString arg1, AddressString arg2, MAPExtensionContainer arg3) {
// TODO Auto-generated method stub
this.currentMapMessageCount = this.mapMessagesReceivedCounter.incrementAndGet();
}
@Override
public void onDialogRequestEricsson(MAPDialog arg0, AddressString arg1, AddressString arg2, IMSI arg3,
AddressString arg4) {
// TODO Auto-generated method stub
}
@Override
public void onDialogTimeout(MAPDialog arg0) {
// TODO Auto-generated method stub
}
@Override
public void onDialogUserAbort(MAPDialog arg0, MAPUserAbortChoice arg1, MAPExtensionContainer arg2) {
// TODO Auto-generated method stub
}
/**
* Component Listener
*/
@Override
public void onErrorComponent(MAPDialog arg0, Long arg1, MAPErrorMessage arg2) {
// TODO Auto-generated method stub
}
@Override
public void onInvokeTimeout(MAPDialog arg0, Long arg1) {
// TODO Auto-generated method stub
}
@Override
public void onMAPMessage(MAPMessage arg0) {
// TODO Auto-generated method stub
}
/**
* SMS Listener
*/
@Override
public void onAlertServiceCentreRequest(AlertServiceCentreRequest arg0) {
// TODO Auto-generated method stub
}
@Override
public void onAlertServiceCentreResponse(AlertServiceCentreResponse arg0) {
// TODO Auto-generated method stub
}
@Override
public void onForwardShortMessageRequest(ForwardShortMessageRequest event) {
if (logger.isInfoEnabled()) {
logger.info("Rx : onForwardShortMessageRequest=" + event);
}
// Lets first close the Dialog
MAPDialogSms mapDialogSms = event.getMAPDialog();
if (this.currentMapMessageCount % 7 == 0) {
// Send back AbsentSubscriber for every 7th MtSMS
try {
// MAPErrorMessageAbsentSubscriberSM createMAPErrorMessageAbsentSubscriberSM(
// AbsentSubscriberDiagnosticSM absentSubscriberDiagnosticSM, MAPExtensionContainer extensionContainer,
// AbsentSubscriberDiagnosticSM additionalAbsentSubscriberDiagnosticSM);
MAPErrorMessage mapErrorMessage = mAPErrorMessageFactory.createMAPErrorMessageAbsentSubscriberSM(AbsentSubscriberDiagnosticSM.IMSIDetached,
null, null);
mapDialogSms.sendErrorComponent(event.getInvokeId(), mapErrorMessage);
mapDialogSms.close(false);
} catch (MAPException e) {
logger.error("Error while sending MAPErrorMessageAbsentSubscriberSM ", e);
}
} else {
try {
mapDialogSms.addForwardShortMessageResponse(event.getInvokeId());
mapDialogSms.close(false);
} catch (MAPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void onForwardShortMessageResponse(ForwardShortMessageResponse arg0) {
// TODO Auto-generated method stub
}
@Override
public void onInformServiceCentreRequest(InformServiceCentreRequest arg0) {
// TODO Auto-generated method stub
}
@Override
public void onMoForwardShortMessageRequest(MoForwardShortMessageRequest request) {
if (logger.isDebugEnabled()) {
logger.debug("Rx : MoForwardShortMessageRequestIndication=" + request);
}
MAPDialogSms dialog = request.getMAPDialog();
try {
// TODO Should we add PENDING SMS TPDU here itself?
dialog.addMoForwardShortMessageResponse(request.getInvokeId(), null, null);
dialog.close(false);
} catch (MAPException e) {
logger.error("Error while sending MoForwardShortMessageResponse ", e);
}
try {
SmsSignalInfo smsSignalInfo = request.getSM_RP_UI();
SmsTpdu smsTpdu = smsSignalInfo.decodeTpdu(true);
if (smsTpdu.getSmsTpduType() != SmsTpduType.SMS_SUBMIT) {
// TODO : Error, we should always receive SMS_SUBMIT for
// MoForwardShortMessageRequestIndication
logger.error("Rx : MoForwardShortMessageRequestIndication, but SmsTpduType is not SMS_SUBMIT. SmsTpdu="
+ smsTpdu);
return;
}
SmsSubmitTpdu smsSubmitTpdu = (SmsSubmitTpdu) smsTpdu;
AddressField destinationAddress = smsSubmitTpdu.getDestinationAddress();
// TODO Normalize
} catch (MAPException e1) {
logger.error("Error while decoding SmsSignalInfo ", e1);
}
}
@Override
public void onMoForwardShortMessageResponse(MoForwardShortMessageResponse arg0) {
// TODO Auto-generated method stub
}
@Override
public void onMtForwardShortMessageRequest(MtForwardShortMessageRequest event) {
if (logger.isInfoEnabled()) {
logger.info("Rx : onMtForwardShortMessageIndication=" + event);
}
// Lets first close the Dialog
MAPDialogSms mapDialogSms = event.getMAPDialog();
if (this.currentMapMessageCount % 7 == 0) {
// Send back AbsentSubscriber for every 7th MtSMS
try {
MAPErrorMessage mapErrorMessage = mAPErrorMessageFactory.createMAPErrorMessageAbsentSubscriberSM(AbsentSubscriberDiagnosticSM.IMSIDetached,
null, null);
mapDialogSms.sendErrorComponent(event.getInvokeId(), mapErrorMessage);
mapDialogSms.close(false);
} catch (MAPException e) {
logger.error("Error while sending MAPErrorMessageAbsentSubscriberSM ", e);
}
} else {
try {
mapDialogSms.addMtForwardShortMessageResponse(event.getInvokeId(), null, null);
mapDialogSms.close(false);
} catch (MAPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void onMtForwardShortMessageResponse(MtForwardShortMessageResponse arg0) {
// TODO Auto-generated method stub
}
@Override
public void onReportSMDeliveryStatusRequest(ReportSMDeliveryStatusRequest arg0) {
// TODO Auto-generated method stub
}
@Override
public void onReportSMDeliveryStatusResponse(ReportSMDeliveryStatusResponse arg0) {
// TODO Auto-generated method stub
}
@Override
public void onSendRoutingInfoForSMRequest(SendRoutingInfoForSMRequest event) {
if (logger.isInfoEnabled()) {
logger.info("Rx : SendRoutingInfoForSMRequestIndication=" + event);
}
IMSI imsi = new IMSIImpl("410035001692061");
ISDNAddressString nnn = new ISDNAddressStringImpl(AddressNature.international_number, NumberingPlan.ISDN,
"923330052001");
LocationInfoWithLMSI li = new LocationInfoWithLMSIImpl(nnn, null, null, null, null);
MAPDialogSms mapDialogSms = event.getMAPDialog();
try {
// void addSendRoutingInfoForSMResponse(long invokeId, IMSI imsi, LocationInfoWithLMSI locationInfoWithLMSI,
// MAPExtensionContainer extensionContainer, Boolean mwdSet) throws MAPException;
mapDialogSms.addSendRoutingInfoForSMResponse(event.getInvokeId(), imsi, li, null, null);
mapDialogSms.close(false);
} catch (MAPException e) {
e.printStackTrace();
}
}
@Override
public void onSendRoutingInfoForSMResponse(SendRoutingInfoForSMResponse arg0) {
// TODO Auto-generated method stub
}
@Override
public void onRejectComponent(MAPDialog mapDialog, Long invokeId, Problem problem, boolean isLocalOriginated) {
// TODO Auto-generated method stub
}
@Override
public void onDialogReject(MAPDialog mapDialog, MAPRefuseReason refuseReason, ApplicationContextName alternativeApplicationContext,
MAPExtensionContainer extensionContainer) {
// TODO Auto-generated method stub
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright XXXX, Red Hat Middleware LLC, 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 A
* 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.smsc.server.bootstrap;
import java.io.InputStream;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
/**
* Version class reads the version.properties packaged with media-server.jar for
* run time display of Media Server Version
*
* @author amit.bhayani
*
*/
public final class Version {
/**
* The single instance.
*/
public final static Version instance = new Version();
/**
* The version properties.
*/
private Properties props;
/**
* Do not allow direct public construction.
*/
private Version() {
props = loadProperties();
}
/**
* Returns an unmodifiable map of version properties.
*
* @return
*/
public Map getProperties() {
return Collections.unmodifiableMap(props);
}
/**
* Returns the value for the given property name.
*
* @param name -
* The name of the property.
* @return The property value or null if the property is not set.
*/
public String getProperty(final String name) {
return props.getProperty(name);
}
/**
* Returns the version information as a string.
*
* @return Basic information as a string.
*/
public String toString() {
StringBuilder sb = new StringBuilder("Mobicents SMSC Server: ");
boolean first = true;
for (Object key : props.keySet()) {
if (first) {
first = false;
} else {
sb.append(",");
}
sb.append(key).append('=').append(props.get(key));
}
return sb.toString();
}
/**
* Load the version properties from a resource.
*/
private Properties loadProperties() {
props = new Properties();
try {
InputStream in = Version.class
.getResourceAsStream("version.properties");
props.load(in);
in.close();
} catch (Exception e) {
throw new Error("Missing version.properties");
}
return props;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* 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.smsc.server.bootstrap;
/**
*
* @author kulikov
*/
public interface SS7ServiceMBean {
public static final String ONAME = "org.mobicents.ss7:service=SS7Service";
public void start() throws Exception;
public void stop();
/**
* Returns SCCP Provider jndi name.
*/
public String getJndiName();
/**
* Returns SS7 Name for this release
* @return
*/
public String getSS7Name();
/**
* Get Vendor supporting this SS7
* @return
*/
public String getSS7Vendor();
/**
* Return SS7 version of this release
* @return
*/
public String getSS7Version();
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* 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.smsc.server.bootstrap;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.log4j.Logger;
import org.jboss.system.ServiceMBeanSupport;
/**
* @author amit bhayani
*/
public class SS7Service extends ServiceMBeanSupport implements SS7ServiceMBean {
private static final Logger logger = Logger.getLogger(SS7Service.class);
private Object stack;
private String jndiName;
private static final String rLogo = " ]]]]]]]]] ";
private static final String lLogo = " [[[[[[[[[ ";
@Override
public void startService() throws Exception {
// starting
rebind(stack);
logger.info(generateMessageWithLogo("service started"));
}
private String generateMessageWithLogo(String message) {
return lLogo + getSS7Name() + " " + getSS7Version() + " " + message + rLogo;
}
public String getSS7Name() {
String name = Version.instance.getProperty("name");
if (name != null) {
return name;
} else {
return "Mobicents SMSC";
}
}
public String getSS7Vendor() {
String vendor = Version.instance.getProperty("vendor");
if (vendor != null) {
return vendor;
} else {
return "JBoss, a division of Red Hat";
}
}
public String getSS7Version() {
String version = Version.instance.getProperty("version");
if (version != null) {
return version;
} else {
return "2.0";
}
}
public void setJndiName(String jndiName) {
this.jndiName = jndiName;
}
public String getJndiName() {
return jndiName;
}
public Object getStack() {
return stack;
}
public void setStack(Object stack) {
this.stack = stack;
}
@Override
public void stopService() {
try {
unbind(jndiName);
} catch (Exception e) {
}
logger.info(generateMessageWithLogo("service stopped"));
}
/**
* Binds trunk object to the JNDI under the jndiName.
*/
private void rebind(Object stack) throws NamingException {
Context ctx = new InitialContext();
String tokens[] = jndiName.split("/");
for (int i = 0; i < tokens.length - 1; i++) {
if (tokens[i].trim().length() > 0) {
try {
ctx = (Context) ctx.lookup(tokens[i]);
} catch (NamingException e) {
ctx = ctx.createSubcontext(tokens[i]);
}
}
}
ctx.bind(tokens[tokens.length - 1], stack);
}
/**
* Unbounds object under specified name.
*
* @param jndiName
* the JNDI name of the object to be unbound.
*/
private void unbind(String jndiName) throws NamingException {
InitialContext initialContext = new InitialContext();
initialContext.unbind(jndiName);
}
} | Java |
package org.mobicents.smsc.slee.resources.smpp.server.events;
import com.cloudhopper.smpp.pdu.PduRequest;
public class PduRequestTimeout {
private final PduRequest pduRequest;
private final String systemId;
public PduRequestTimeout(PduRequest pduRequest, String systemId) {
this.pduRequest = pduRequest;
this.systemId = systemId;
}
protected PduRequest getPduRequest() {
return pduRequest;
}
protected String getSystemId() {
return systemId;
}
@Override
public String toString() {
return "PduRequestTimeout [pduRequest=" + pduRequest + ", systemId=" + systemId + "]";
}
}
| Java |
package org.mobicents.smsc.slee.resources.smpp.server.events;
public interface EventsType {
public static final String REQUEST_TIMEOUT = "org.mobicents.resources.smpp.server.REQUEST_TIMEOUT";
public static final String SUBMIT_SM = "org.mobicents.resources.smpp.server.SUBMIT_SM";
public static final String DATA_SM = "org.mobicents.resources.smpp.server.DATA_SM";
public static final String DELIVER_SM = "org.mobicents.resources.smpp.server.DELIVER_SM";
public static final String SUBMIT_SM_RESP = "org.mobicents.resources.smpp.server.SUBMIT_SM_RESP";
public static final String DATA_SM_RESP = "org.mobicents.resources.smpp.server.DATA_SM_RESP";
public static final String DELIVER_SM_RESP = "org.mobicents.resources.smpp.server.DELIVER_SM_RESP";
public static final String RECOVERABLE_PDU_EXCEPTION = "org.mobicents.resources.smpp.server.RECOVERABLE_PDU_EXCEPTION";
public static final String UNRECOVERABLE_PDU_EXCEPTION = "org.mobicents.resources.smpp.server.UNRECOVERABLE_PDU_EXCEPTION";
}
| Java |
package org.mobicents.smsc.slee.resources.smpp.server;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.slee.facilities.Tracer;
import javolution.util.FastMap;
import org.mobicents.smsc.slee.resources.smpp.server.events.EventsType;
import org.mobicents.smsc.slee.resources.smpp.server.events.PduRequestTimeout;
import org.mobicents.smsc.smpp.SmppSessionHandlerInterface;
import com.cloudhopper.smpp.PduAsyncResponse;
import com.cloudhopper.smpp.SmppBindType;
import com.cloudhopper.smpp.SmppConstants;
import com.cloudhopper.smpp.SmppSessionHandler;
import com.cloudhopper.smpp.pdu.BaseBindResp;
import com.cloudhopper.smpp.pdu.DataSm;
import com.cloudhopper.smpp.pdu.DataSmResp;
import com.cloudhopper.smpp.pdu.DeliverSmResp;
import com.cloudhopper.smpp.pdu.Pdu;
import com.cloudhopper.smpp.pdu.PduRequest;
import com.cloudhopper.smpp.pdu.PduResponse;
import com.cloudhopper.smpp.pdu.SubmitSm;
import com.cloudhopper.smpp.type.RecoverablePduException;
import com.cloudhopper.smpp.type.SmppProcessingException;
import com.cloudhopper.smpp.type.UnrecoverablePduException;
public class SmppServerSessionsImpl implements SmppServerSessions {
private static Tracer tracer;
private SmppServerResourceAdaptor smppServerResourceAdaptor = null;
private FastMap<String, SmppServerSessionImpl> smppServerSessions = new FastMap<String, SmppServerSessionImpl>()
.shared();
protected SmppSessionHandlerInterfaceImpl smppSessionHandlerInterfaceImpl = null;
private final AtomicLong messageIdGenerator = new AtomicLong(0);
public SmppServerSessionsImpl(SmppServerResourceAdaptor smppServerResourceAdaptor) {
this.smppServerResourceAdaptor = smppServerResourceAdaptor;
if (tracer == null) {
tracer = this.smppServerResourceAdaptor.getRAContext().getTracer(
SmppSessionHandlerInterfaceImpl.class.getSimpleName());
}
this.smppSessionHandlerInterfaceImpl = new SmppSessionHandlerInterfaceImpl();
}
public SmppServerSession getSmppSession(byte ton, byte npi, String address) {
for (FastMap.Entry<String, SmppServerSessionImpl> e = smppServerSessions.head(), end = smppServerSessions
.tail(); (e = e.getNext()) != end;) {
SmppServerSessionImpl smppServerSessionImpl = e.getValue();
SmppBindType sessionBindType = smppServerSessionImpl.getBindType();
if (sessionBindType == SmppBindType.TRANSCEIVER || sessionBindType == SmppBindType.RECEIVER) {
Pattern p = smppServerSessionImpl.getAddressRangePattern();
if(p == null){
continue;
}
Matcher m = p.matcher(address);
if (m.matches()) {
return smppServerSessionImpl;
}
}
}
tracer.warning(String.format("No SmppServerSession found for address range=%s", address));
return null;
}
public SmppServerSession getSmppSession(String systemId) {
return this.smppServerSessions.get(systemId);
}
protected SmppSessionHandlerInterface getSmppSessionHandlerInterface() {
return this.smppSessionHandlerInterfaceImpl;
}
protected void closeSmppSessions() {
tracer.info(String.format("smppServerSessions.size()=%d", smppServerSessions.size()));
for (FastMap.Entry<String, SmppServerSessionImpl> e = smppServerSessions.head(), end = smppServerSessions
.tail(); (e = e.getNext()) != end;) {
String key = e.getKey();
SmppServerSessionImpl session = e.getValue();
session.getWrappedSmppServerSession().close();
if (tracer.isInfoEnabled()) {
tracer.info(String.format("Closed Session=%s", key));
}
}
this.smppServerSessions.clear();
}
protected class SmppSessionHandlerInterfaceImpl implements SmppSessionHandlerInterface {
public SmppSessionHandlerInterfaceImpl() {
}
@Override
public SmppSessionHandler sessionCreated(Long sessionId, com.cloudhopper.smpp.SmppServerSession session,
BaseBindResp preparedBindResponse) throws SmppProcessingException {
SmppServerSessionImpl smppServerSessionImpl = new SmppServerSessionImpl(session, smppServerResourceAdaptor);
smppServerSessions.put(session.getConfiguration().getSystemId(), smppServerSessionImpl);
if (tracer.isInfoEnabled()) {
tracer.info(String.format("Added Session=%s to list of maintained sessions", session.getConfiguration()
.getSystemId()));
}
return new SmppSessionHandlerImpl(smppServerSessionImpl);
}
@Override
public void sessionDestroyed(Long sessionId, com.cloudhopper.smpp.SmppServerSession session) {
SmppServerSessionImpl smppSession = smppServerSessions.remove(session.getConfiguration().getSystemId());
if (smppSession != null) {
if (tracer.isInfoEnabled()) {
tracer.info(String.format("Removed Session=%s from list of maintained sessions", session
.getConfiguration().getSystemId()));
}
} else {
tracer.warning(String.format("Session destroyed for=%, but was not maintained in list of sessions",
session.getConfiguration().getSystemId()));
}
}
}
protected class SmppSessionHandlerImpl implements SmppSessionHandler {
private SmppServerSessionImpl smppServerSessionImpl;
public SmppSessionHandlerImpl(SmppServerSessionImpl smppServerSessionImpl) {
this.smppServerSessionImpl = smppServerSessionImpl;
}
@Override
public PduResponse firePduRequestReceived(PduRequest pduRequest) {
PduResponse response = pduRequest.createResponse();
try {
SmppServerTransactionImpl smppServerTransaction = null;
SmppServerTransactionHandle smppServerTransactionHandle = null;
switch (pduRequest.getCommandId()) {
case SmppConstants.CMD_ID_ENQUIRE_LINK:
break;
case SmppConstants.CMD_ID_UNBIND:
break;
case SmppConstants.CMD_ID_SUBMIT_SM:
smppServerTransactionHandle = new SmppServerTransactionHandle(
this.smppServerSessionImpl.getSmppSessionConfigurationName(),
pduRequest.getSequenceNumber(), SmppTransactionType.INCOMING);
smppServerTransaction = new SmppServerTransactionImpl(pduRequest, this.smppServerSessionImpl,
smppServerTransactionHandle, smppServerResourceAdaptor);
smppServerResourceAdaptor.startNewSmppServerTransactionActivity(smppServerTransaction);
smppServerResourceAdaptor.fireEvent(EventsType.SUBMIT_SM,
smppServerTransaction.getActivityHandle(), (SubmitSm) pduRequest);
// Return null. Let SBB send response back
return null;
case SmppConstants.CMD_ID_DATA_SM:
smppServerTransactionHandle = new SmppServerTransactionHandle(
this.smppServerSessionImpl.getSystemId(), pduRequest.getSequenceNumber(),
SmppTransactionType.INCOMING);
smppServerTransaction = new SmppServerTransactionImpl(pduRequest, this.smppServerSessionImpl,
smppServerTransactionHandle, smppServerResourceAdaptor);
smppServerResourceAdaptor.startNewSmppServerTransactionActivity(smppServerTransaction);
smppServerResourceAdaptor.fireEvent(EventsType.DATA_SM, smppServerTransaction.getActivityHandle(),
(DataSm) pduRequest);
// Return null. Let SBB send response back
return null;
default:
tracer.severe(String.format("Rx : Non supported PduRequest=%s. Will not fire event", pduRequest));
break;
}
} catch (Exception e) {
tracer.severe(String.format("Error while processing PduRequest=%s", pduRequest), e);
response.setCommandStatus(SmppConstants.STATUS_SYSERR);
}
return response;
}
@Override
public String lookupResultMessage(int arg0) {
return null;
}
@Override
public String lookupTlvTagName(short arg0) {
return null;
}
@Override
public void fireChannelUnexpectedlyClosed() {
tracer.severe(String
.format("Rx : fireChannelUnexpectedlyClosed for SmppServerSessionImpl=%s Default handling is to discard an unexpected channel closed",
this.smppServerSessionImpl.getSystemId()));
}
@Override
public void fireExpectedPduResponseReceived(PduAsyncResponse pduAsyncResponse) {
PduRequest pduRequest = pduAsyncResponse.getRequest();
PduResponse pduResponse = pduAsyncResponse.getResponse();
SmppServerTransactionImpl smppServerTransaction = (SmppServerTransactionImpl) pduRequest
.getReferenceObject();
if (smppServerTransaction == null) {
tracer.severe(String
.format("Rx : fireExpectedPduResponseReceived for SmppServerSessionImpl=%s PduAsyncResponse=%s but SmppServerTransactionImpl is null",
this.smppServerSessionImpl.getSystemId(), pduAsyncResponse));
return;
}
try {
switch (pduResponse.getCommandId()) {
case SmppConstants.CMD_ID_DELIVER_SM_RESP:
smppServerResourceAdaptor.fireEvent(EventsType.DELIVER_SM_RESP,
smppServerTransaction.getActivityHandle(), (DeliverSmResp) pduResponse);
break;
case SmppConstants.CMD_ID_DATA_SM_RESP:
smppServerResourceAdaptor.fireEvent(EventsType.DATA_SM_RESP,
smppServerTransaction.getActivityHandle(), (DataSmResp) pduResponse);
break;
default:
tracer.severe(String
.format("Rx : fireExpectedPduResponseReceived for SmppServerSessionImpl=%s PduAsyncResponse=%s but PduResponse is unidentified. Event will not be fired ",
this.smppServerSessionImpl.getSystemId(), pduAsyncResponse));
break;
}
} catch (Exception e) {
tracer.severe(String.format("Error while processing PduAsyncResponse=%s", pduAsyncResponse), e);
} finally {
if (smppServerTransaction != null) {
smppServerResourceAdaptor.endActivity(smppServerTransaction);
}
}
}
@Override
public void firePduRequestExpired(PduRequest pduRequest) {
tracer.warning(String.format("PduRequestExpired=%s", pduRequest));
SmppServerTransactionImpl smppServerTransaction = (SmppServerTransactionImpl) pduRequest
.getReferenceObject();
if (smppServerTransaction == null) {
tracer.severe(String
.format("Rx : firePduRequestExpired for SmppServerSessionImpl=%s PduRequest=%s but SmppServerTransactionImpl is null",
this.smppServerSessionImpl.getSystemId(), pduRequest));
return;
}
PduRequestTimeout event = new PduRequestTimeout(pduRequest, this.smppServerSessionImpl.getSystemId());
try {
smppServerResourceAdaptor.fireEvent(EventsType.REQUEST_TIMEOUT,
smppServerTransaction.getActivityHandle(), event);
} catch (Exception e) {
tracer.severe(String.format("Received firePduRequestExpired. Error while processing PduRequest=%s",
pduRequest), e);
} finally {
if (smppServerTransaction != null) {
smppServerResourceAdaptor.endActivity(smppServerTransaction);
}
}
}
@Override
public void fireRecoverablePduException(RecoverablePduException recoverablePduException) {
tracer.warning("Received fireRecoverablePduException", recoverablePduException);
Pdu partialPdu = recoverablePduException.getPartialPdu();
SmppServerTransactionImpl smppServerTransaction = (SmppServerTransactionImpl) partialPdu
.getReferenceObject();
if (smppServerTransaction == null) {
tracer.severe(
String.format(
"Rx : fireRecoverablePduException for SmppServerSessionImpl=%s but SmppServerTransactionImpl is null",
this.smppServerSessionImpl.getSystemId()), recoverablePduException);
return;
}
try {
smppServerResourceAdaptor.fireEvent(EventsType.RECOVERABLE_PDU_EXCEPTION,
smppServerTransaction.getActivityHandle(), recoverablePduException);
} catch (Exception e) {
tracer.severe(String.format(
"Received fireRecoverablePduException. Error while processing RecoverablePduException=%s",
recoverablePduException), e);
} finally {
if (smppServerTransaction != null) {
smppServerResourceAdaptor.endActivity(smppServerTransaction);
}
}
}
@Override
public void fireUnrecoverablePduException(UnrecoverablePduException unrecoverablePduException) {
tracer.severe("Received fireUnrecoverablePduException", unrecoverablePduException);
// TODO : recommendation is to close session
}
@Override
public void fireUnexpectedPduResponseReceived(PduResponse pduResponse) {
tracer.severe("Received fireUnexpectedPduResponseReceived PduResponse=" + pduResponse);
}
@Override
public void fireUnknownThrowable(Throwable throwable) {
tracer.severe("Received fireUnknownThrowable", throwable);
// TODO what here?
}
}
@Override
public String getNextMessageId() {
return Long.toString(this.messageIdGenerator.incrementAndGet());
}
}
| Java |
package org.mobicents.smsc.slee.resources.smpp.server;
import javax.slee.resource.ActivityHandle;
public class SmppServerTransactionHandle implements ActivityHandle {
private final String smppSessionConfigurationName;
private final SmppTransactionType smppTransactionType;
private final int seqNumnber;
private transient SmppServerTransactionImpl activity;
public SmppServerTransactionHandle(String smppSessionConfigurationName, int seqNumnber,
SmppTransactionType smppTransactionType) {
this.smppSessionConfigurationName = smppSessionConfigurationName;
this.seqNumnber = seqNumnber;
this.smppTransactionType = smppTransactionType;
}
public SmppServerTransactionImpl getActivity() {
return activity;
}
public void setActivity(SmppServerTransactionImpl activity) {
this.activity = activity;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + seqNumnber;
result = prime * result + smppTransactionType.hashCode();
result = prime * result + smppSessionConfigurationName.hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SmppServerTransactionHandle other = (SmppServerTransactionHandle) obj;
if (seqNumnber != other.seqNumnber)
return false;
if (smppTransactionType != other.smppTransactionType)
return false;
if (!smppSessionConfigurationName.equals(other.smppSessionConfigurationName))
return false;
return true;
}
@Override
public String toString() {
return "SmppServerTransactionHandle [smppSessionConfigurationName=" + smppSessionConfigurationName
+ ", smppTransactionType=" + smppTransactionType + ", seqNumnber=" + seqNumnber + "]";
}
}
| Java |
package org.mobicents.smsc.slee.resources.smpp.server;
import com.cloudhopper.smpp.pdu.PduRequest;
public class SmppServerTransactionImpl implements SmppServerTransaction {
private final SmppServerSessionImpl smppSession;
private final SmppServerResourceAdaptor ra;
private SmppServerTransactionHandle activityHandle;
private PduRequest wrappedPduRequest;
protected SmppServerTransactionImpl(PduRequest wrappedPduRequest, SmppServerSessionImpl smppSession,
SmppServerTransactionHandle smppServerTransactionHandle, SmppServerResourceAdaptor ra) {
this.wrappedPduRequest = wrappedPduRequest;
this.wrappedPduRequest.setReferenceObject(this);
this.smppSession = smppSession;
this.activityHandle = smppServerTransactionHandle;
this.activityHandle.setActivity(this);
this.ra = ra;
}
public SmppServerSession getSmppSession() {
return smppSession;
}
public SmppServerTransactionHandle getActivityHandle() {
return this.activityHandle;
}
public PduRequest getWrappedPduRequest() {
return this.wrappedPduRequest;
}
protected SmppServerResourceAdaptor getRa() {
return ra;
}
public void clear() {
// TODO Any more cleaning here?
if (this.activityHandle != null) {
this.activityHandle.setActivity(null);
this.activityHandle = null;
}
if (this.wrappedPduRequest != null) {
this.wrappedPduRequest.setReferenceObject(null);
this.wrappedPduRequest = null;
}
}
}
| Java |
package org.mobicents.smsc.slee.resources.smpp.server;
import javax.naming.InitialContext;
import javax.slee.Address;
import javax.slee.AddressPlan;
import javax.slee.SLEEException;
import javax.slee.facilities.EventLookupFacility;
import javax.slee.facilities.Tracer;
import javax.slee.resource.ActivityAlreadyExistsException;
import javax.slee.resource.ActivityFlags;
import javax.slee.resource.ActivityHandle;
import javax.slee.resource.ActivityIsEndingException;
import javax.slee.resource.ConfigProperties;
import javax.slee.resource.FailureReason;
import javax.slee.resource.FireEventException;
import javax.slee.resource.FireableEventType;
import javax.slee.resource.IllegalEventException;
import javax.slee.resource.InvalidConfigurationException;
import javax.slee.resource.Marshaler;
import javax.slee.resource.ReceivableService;
import javax.slee.resource.ResourceAdaptor;
import javax.slee.resource.ResourceAdaptorContext;
import javax.slee.resource.SleeEndpoint;
import javax.slee.resource.StartActivityException;
import javax.slee.resource.UnrecognizedActivityHandleException;
import org.mobicents.smsc.smpp.DefaultSmppServerHandler;
public class SmppServerResourceAdaptor implements ResourceAdaptor {
private static final String CONF_JNDI = "jndiName";
private transient Tracer tracer;
private transient ResourceAdaptorContext raContext;
private transient SleeEndpoint sleeEndpoint = null;
private transient EventLookupFacility eventLookup = null;
private EventIDCache eventIdCache = null;
private SmppServerSessionsImpl smppServerSession = null;
private DefaultSmppServerHandler defaultSmppServerHandler = null;
private transient static final Address address = new Address(AddressPlan.IP, "localhost");
private String jndiName = null;
public SmppServerResourceAdaptor() {
// TODO Auto-generated constructor stub
}
@Override
public void activityEnded(ActivityHandle activityHandle) {
if (this.tracer.isFineEnabled()) {
this.tracer.fine("Activity with handle " + activityHandle + " ended");
}
SmppServerTransactionHandle serverTxHandle = (SmppServerTransactionHandle) activityHandle;
final SmppServerTransactionImpl serverTx = serverTxHandle.getActivity();
serverTxHandle.setActivity(null);
if (serverTx != null) {
serverTx.clear();
}
}
@Override
public void activityUnreferenced(ActivityHandle arg0) {
// TODO Auto-generated method stub
}
@Override
public void administrativeRemove(ActivityHandle arg0) {
// TODO Auto-generated method stub
}
@Override
public void eventProcessingFailed(ActivityHandle arg0, FireableEventType arg1, Object arg2, Address arg3,
ReceivableService arg4, int arg5, FailureReason arg6) {
// TODO Auto-generated method stub
}
@Override
public void eventProcessingSuccessful(ActivityHandle arg0, FireableEventType arg1, Object arg2, Address arg3,
ReceivableService arg4, int arg5) {
// TODO Auto-generated method stub
}
@Override
public void eventUnreferenced(ActivityHandle arg0, FireableEventType arg1, Object arg2, Address arg3,
ReceivableService arg4, int arg5) {
// TODO Auto-generated method stub
}
@Override
public Object getActivity(ActivityHandle activityHandle) {
SmppServerTransactionHandle serverTxHandle = (SmppServerTransactionHandle) activityHandle;
return serverTxHandle.getActivity();
}
@Override
public ActivityHandle getActivityHandle(Object activity) {
if (activity instanceof SmppServerTransactionImpl) {
final SmppServerTransactionImpl wrapper = ((SmppServerTransactionImpl) activity);
if (wrapper.getRa() == this) {
return wrapper.getActivityHandle();
}
}
return null;
}
@Override
public Marshaler getMarshaler() {
// TODO Auto-generated method stub
return null;
}
@Override
public Object getResourceAdaptorInterface(String arg0) {
return this.smppServerSession;
}
@Override
public void queryLiveness(ActivityHandle activityHandle) {
final SmppServerTransactionHandle handle = (SmppServerTransactionHandle) activityHandle;
final SmppServerTransactionImpl smppServerTxActivity = handle.getActivity();
if (smppServerTxActivity == null || smppServerTxActivity.getWrappedPduRequest() == null) {
sleeEndpoint.endActivity(handle);
}
}
@Override
public void raActive() {
try {
InitialContext ic = new InitialContext();
this.defaultSmppServerHandler = (DefaultSmppServerHandler) ic.lookup(this.jndiName);
this.defaultSmppServerHandler.setSmppSessionHandlerInterface(this.smppServerSession
.getSmppSessionHandlerInterface());
if (tracer.isInfoEnabled()) {
tracer.info("Activated RA Entity " + this.raContext.getEntityName());
}
} catch (Exception e) {
this.tracer.severe("Failed to activate SMPP Server RA ", e);
}
}
@Override
public void raConfigurationUpdate(ConfigProperties properties) {
raConfigure(properties);
}
@Override
public void raConfigure(ConfigProperties properties) {
if (tracer.isFineEnabled()) {
tracer.fine("Configuring RA Entity " + this.raContext.getEntityName());
}
try {
this.jndiName = (String) properties.getProperty(CONF_JNDI).getValue();
} catch (Exception e) {
tracer.severe("Configuring of SMPP Server RA failed ", e);
}
}
@Override
public void raInactive() {
this.smppServerSession.closeSmppSessions();
this.defaultSmppServerHandler.setSmppSessionHandlerInterface(null);
this.defaultSmppServerHandler = null;
if (tracer.isInfoEnabled()) {
tracer.info("Inactivated RA Entity " + this.raContext.getEntityName());
}
}
@Override
public void raStopping() {
// TODO Auto-generated method stub
}
@Override
public void raUnconfigure() {
this.jndiName = null;
}
@Override
public void raVerifyConfiguration(ConfigProperties properties) throws InvalidConfigurationException {
try {
String jndiName = (String) properties.getProperty(CONF_JNDI).getValue();
if (jndiName == null) {
throw new InvalidConfigurationException("JNDI Name cannot be null");
}
} catch (Exception e) {
throw new InvalidConfigurationException(e.getMessage(), e);
}
}
@Override
public void serviceActive(ReceivableService arg0) {
// TODO Auto-generated method stub
}
@Override
public void serviceInactive(ReceivableService arg0) {
// TODO Auto-generated method stub
}
@Override
public void serviceStopping(ReceivableService arg0) {
// TODO Auto-generated method stub
}
@Override
public void setResourceAdaptorContext(ResourceAdaptorContext raContext) {
this.tracer = raContext.getTracer(getClass().getSimpleName());
this.raContext = raContext;
this.sleeEndpoint = raContext.getSleeEndpoint();
this.eventLookup = raContext.getEventLookupFacility();
this.eventIdCache = new EventIDCache(raContext);
this.smppServerSession = new SmppServerSessionsImpl(this);
}
@Override
public void unsetResourceAdaptorContext() {
this.raContext = null;
this.sleeEndpoint = null;
this.eventLookup = null;
this.eventIdCache = null;
this.smppServerSession = null;
}
/**
* Protected
*/
protected void startNewSmppServerTransactionActivity(SmppServerTransactionImpl txImpl)
throws ActivityAlreadyExistsException, NullPointerException, IllegalStateException, SLEEException,
StartActivityException {
sleeEndpoint.startActivity(txImpl.getActivityHandle(), txImpl, ActivityFlags.REQUEST_ENDED_CALLBACK);
}
protected void startNewSmppTransactionSuspendedActivity(SmppServerTransactionImpl txImpl)
throws ActivityAlreadyExistsException, NullPointerException, IllegalStateException, SLEEException,
StartActivityException {
sleeEndpoint.startActivitySuspended(txImpl.getActivityHandle(), txImpl, ActivityFlags.REQUEST_ENDED_CALLBACK);
}
protected void endActivity(SmppServerTransactionImpl txImpl) {
try {
this.sleeEndpoint.endActivity(txImpl.getActivityHandle());
} catch (Exception e) {
this.tracer.severe("Error while Ending Activity " + txImpl, e);
}
}
protected ResourceAdaptorContext getRAContext() {
return this.raContext;
}
/**
* Private methods
*/
protected void fireEvent(String eventName, ActivityHandle handle, Object event) {
FireableEventType eventID = eventIdCache.getEventId(this.eventLookup, eventName);
if (eventID == null) {
tracer.severe("Event id for " + eventID + " is unknown, cant fire!!!");
} else {
try {
sleeEndpoint.fireEvent(handle, eventID, event, address, null);
} catch (UnrecognizedActivityHandleException e) {
this.tracer.severe("Error while firing event", e);
} catch (IllegalEventException e) {
this.tracer.severe("Error while firing event", e);
} catch (ActivityIsEndingException e) {
this.tracer.severe("Error while firing event", e);
} catch (NullPointerException e) {
this.tracer.severe("Error while firing event", e);
} catch (SLEEException e) {
this.tracer.severe("Error while firing event", e);
} catch (FireEventException e) {
this.tracer.severe("Error while firing event", e);
}
}
}
}
| Java |
package org.mobicents.smsc.slee.resources.smpp.server;
public enum SmppTransactionType {
INCOMING, OUTGOING;
}
| Java |
package org.mobicents.smsc.slee.resources.smpp.server;
import java.util.regex.Pattern;
import javax.slee.SLEEException;
import javax.slee.resource.ActivityAlreadyExistsException;
import javax.slee.resource.StartActivityException;
import org.apache.log4j.Logger;
import com.cloudhopper.commons.util.windowing.WindowFuture;
import com.cloudhopper.smpp.SmppBindType;
import com.cloudhopper.smpp.SmppServerSession;
import com.cloudhopper.smpp.SmppSession.Type;
import com.cloudhopper.smpp.impl.DefaultSmppSession;
import com.cloudhopper.smpp.pdu.PduRequest;
import com.cloudhopper.smpp.pdu.PduResponse;
import com.cloudhopper.smpp.type.Address;
import com.cloudhopper.smpp.type.RecoverablePduException;
import com.cloudhopper.smpp.type.SmppChannelException;
import com.cloudhopper.smpp.type.SmppTimeoutException;
import com.cloudhopper.smpp.type.UnrecoverablePduException;
public class SmppServerSessionImpl implements org.mobicents.smsc.slee.resources.smpp.server.SmppServerSession {
private static final Logger logger = Logger.getLogger(SmppServerSessionImpl.class);
private final SmppServerSession wrappedSmppServerSession;
private SmppServerResourceAdaptor smppServerResourceAdaptor = null;
private final Pattern pattern;
public SmppServerSessionImpl(SmppServerSession wrappedSmppServerSession,
SmppServerResourceAdaptor smppServerResourceAdaptor) {
this.wrappedSmppServerSession = wrappedSmppServerSession;
this.smppServerResourceAdaptor = smppServerResourceAdaptor;
if (this.wrappedSmppServerSession.getConfiguration().getAddressRange().getAddress() != null) {
this.pattern = Pattern.compile(this.wrappedSmppServerSession.getConfiguration().getAddressRange()
.getAddress());
} else {
this.pattern = null;
}
}
protected Pattern getAddressRangePattern() {
return this.pattern;
}
protected SmppServerSession getWrappedSmppServerSession() {
return this.wrappedSmppServerSession;
}
public String getSmppSessionConfigurationName() {
return this.wrappedSmppServerSession.getConfiguration().getName();
}
@Override
public String getSystemId() {
return this.wrappedSmppServerSession.getConfiguration().getSystemId();
}
@Override
public SmppBindType getBindType() {
return this.wrappedSmppServerSession.getBindType();
}
@Override
public Type getLocalType() {
return this.wrappedSmppServerSession.getLocalType();
}
@Override
public Type getRemoteType() {
return this.wrappedSmppServerSession.getRemoteType();
}
@Override
public String getStateName() {
return this.wrappedSmppServerSession.getStateName();
}
@Override
public byte getInterfaceVersion() {
return this.wrappedSmppServerSession.getInterfaceVersion();
}
@Override
public boolean areOptionalParametersSupported() {
return this.wrappedSmppServerSession.areOptionalParametersSupported();
}
@Override
public boolean isOpen() {
return this.wrappedSmppServerSession.isOpen();
}
@Override
public boolean isBinding() {
return this.wrappedSmppServerSession.isBinding();
}
@Override
public boolean isBound() {
return this.wrappedSmppServerSession.isBound();
}
@Override
public boolean isUnbinding() {
return this.wrappedSmppServerSession.isUnbinding();
}
@Override
public boolean isClosed() {
return this.wrappedSmppServerSession.isClosed();
}
@Override
public long getBoundTime() {
return this.wrappedSmppServerSession.getBoundTime();
}
@Override
public Address getAddress() {
return this.wrappedSmppServerSession.getConfiguration().getAddressRange();
}
@Override
public SmppServerTransaction sendRequestPdu(PduRequest request, long timeoutMillis) throws RecoverablePduException,
UnrecoverablePduException, SmppTimeoutException, SmppChannelException, InterruptedException,
ActivityAlreadyExistsException, NullPointerException, IllegalStateException, SLEEException,
StartActivityException {
if (!request.hasSequenceNumberAssigned()) {
// assign the next PDU sequence # if its not yet assigned
request.setSequenceNumber(((DefaultSmppSession) this.wrappedSmppServerSession).getSequenceNumber().next());
}
SmppServerTransactionHandle smppServerTransactionHandle = new SmppServerTransactionHandle(
this.getSmppSessionConfigurationName(), request.getSequenceNumber(), SmppTransactionType.OUTGOING);
SmppServerTransactionImpl smppServerTransaction = new SmppServerTransactionImpl(request, this,
smppServerTransactionHandle, smppServerResourceAdaptor);
smppServerResourceAdaptor.startNewSmppTransactionSuspendedActivity(smppServerTransaction);
try {
WindowFuture<Integer, PduRequest, PduResponse> windowFuture = this.wrappedSmppServerSession.sendRequestPdu(
request, timeoutMillis, false);
} catch (RecoverablePduException e) {
this.smppServerResourceAdaptor.endActivity(smppServerTransaction);
throw e;
} catch (UnrecoverablePduException e) {
this.smppServerResourceAdaptor.endActivity(smppServerTransaction);
throw e;
} catch (SmppTimeoutException e) {
this.smppServerResourceAdaptor.endActivity(smppServerTransaction);
throw e;
} catch (SmppChannelException e) {
this.smppServerResourceAdaptor.endActivity(smppServerTransaction);
throw e;
} catch (InterruptedException e) {
this.smppServerResourceAdaptor.endActivity(smppServerTransaction);
throw e;
}
return smppServerTransaction;
}
@Override
public void sendResponsePdu(PduRequest request, PduResponse response) throws RecoverablePduException,
UnrecoverablePduException, SmppChannelException, InterruptedException {
SmppServerTransactionImpl smppServerTransactionImpl = null;
try {
if (request.getSequenceNumber() != response.getSequenceNumber()) {
throw new UnrecoverablePduException("Sequence number of response is not same as request");
}
smppServerTransactionImpl = (SmppServerTransactionImpl) request.getReferenceObject();
this.wrappedSmppServerSession.sendResponsePdu(response);
} finally {
if (smppServerTransactionImpl == null) {
logger.error(String.format(
"SmppServerTransactionImpl Activity is null while trying to send PduResponse=%s", response));
} else {
this.smppServerResourceAdaptor.endActivity(smppServerTransactionImpl);
}
}
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* 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.smsc.slee.resources.smpp.server;
import java.util.concurrent.ConcurrentHashMap;
import javax.slee.EventTypeID;
import javax.slee.facilities.EventLookupFacility;
import javax.slee.facilities.Tracer;
import javax.slee.resource.FireableEventType;
import javax.slee.resource.ResourceAdaptorContext;
/**
*
* @author amit bhayani
*
*/
public class EventIDCache {
private ConcurrentHashMap<String, FireableEventType> eventIds = new ConcurrentHashMap<String, FireableEventType>();
private static final String EVENT_VENDOR = "org.mobicents";
private static final String EVENT_VERSION = "1.0";
private Tracer tracer;
protected EventIDCache(ResourceAdaptorContext raContext) {
tracer = raContext.getTracer(EventIDCache.class.getSimpleName());
}
protected FireableEventType getEventId(EventLookupFacility eventLookupFacility, String eventName) {
FireableEventType eventType = eventIds.get(eventName);
if (eventType == null) {
try {
eventType = eventLookupFacility.getFireableEventType(new EventTypeID(eventName, EVENT_VENDOR,
EVENT_VERSION));
} catch (Throwable e) {
this.tracer.severe("Error while looking up for SMPP Server Events", e);
}
if (eventType != null) {
eventIds.put(eventName, eventType);
}
}
return eventType;
}
}
| Java |
package org.mobicents.smsc.slee.resources.smpp.server;
public interface SmppServerSessions {
//TODO : May be rename this method as we want SmppServerSession to send SMS to ESME
public SmppServerSession getSmppSession(byte ton, byte npi, String address);
public SmppServerSession getSmppSession(String systemId);
public String getNextMessageId();
}
| Java |
package org.mobicents.smsc.slee.resources.smpp.server;
public interface SmppServerTransactionACIFactory {
javax.slee.ActivityContextInterface getActivityContextInterface(SmppServerTransaction txn);
}
| Java |
package org.mobicents.smsc.slee.resources.smpp.server;
import javax.slee.SLEEException;
import javax.slee.resource.ActivityAlreadyExistsException;
import javax.slee.resource.StartActivityException;
import com.cloudhopper.smpp.SmppBindType;
import com.cloudhopper.smpp.SmppSession.Type;
import com.cloudhopper.smpp.pdu.PduRequest;
import com.cloudhopper.smpp.pdu.PduResponse;
import com.cloudhopper.smpp.type.Address;
import com.cloudhopper.smpp.type.RecoverablePduException;
import com.cloudhopper.smpp.type.SmppChannelException;
import com.cloudhopper.smpp.type.SmppTimeoutException;
import com.cloudhopper.smpp.type.UnrecoverablePduException;
public interface SmppServerSession {
/**
* Returns the SystemId
*
* @return
*/
public String getSystemId();
/**
* Gets the type of bind for this session such as "transceiver", "receiver",
* or "transmitter".
*
* @return The type of bind for this session
*/
public SmppBindType getBindType();
/**
* Gets the session type of the local system. If the local type is ESME,
* then we are connected to an SMSC. We are permitted to send submit_sm or
* data_sm requests.
*
* @return The session type of the local system
*/
public Type getLocalType();
/**
* Gets the session type of the remote system. If the remote type is SMSC,
* then we are the ESME. We are permitted to send submit_sm or data_sm
* requests.
*
* @return The session type of the remote system
*/
public Type getRemoteType();
/**
* Gets the name of the current state of the session.
*
* @return The current state of the session by name such as "CLOSED"
*/
public String getStateName();
/**
* Gets the interface version currently in use between local and remote
* endpoints. This interface version is negotiated during the bind process
* to mainly ensure that optional parameters are supported.
*
* @return The interface version currently in use between local and remote
* endpoints.
*/
public byte getInterfaceVersion();
/**
* Returns whether optional parameters are supported with the remote
* endpoint. If the interface version currently in use is >= 3.4, then this
* method returns true, otherwise will return false.
*
* @return True if optional parameters are supported, otherwise false.
*/
public boolean areOptionalParametersSupported();
/**
* Checks if the session is currently in the "OPEN" state. The "OPEN" state
* means the session is connected and a bind is pending.
*
* @return True if session is currently in the "OPEN" state, otherwise
* false.
*/
public boolean isOpen();
/**
* Checks if the session is currently in the "BINDING" state. The "BINDING"
* state means the session is in the process of binding. If local is ESME,
* we sent the bind request, but have not yet received the bind response. If
* the local is SMSC, then the ESME initiated a bind request, but we have't
* responded yet.
*
* @return True if session is currently in the "BINDING" state, otherwise
* false.
*/
public boolean isBinding();
/**
* Checks if the session is currently in the "BOUND" state. The "BOUND"
* state means the session is bound and ready to process requests.
*
* @return True if session is currently in the "BOUND" state, otherwise
* false.
*/
public boolean isBound();
/**
* Checks if the session is currently in the "UNBINDING" state. The
* "UNBINDING" state means the session is in the process of unbinding. This
* may have been initiated by us or them.
*
* @return True if session is currently in the "UNBINDING" state, otherwise
* false.
*/
public boolean isUnbinding();
/**
* Checks if the session is currently in the "CLOSED" state. The "CLOSED"
* state means the session is unbound and closed (destroyed).
*
* @return True if session is currently in the "CLOSED" state, otherwise
* false.
*/
public boolean isClosed();
/**
* Returns the System.currentTimeMillis() value of when this session reached
* the "BOUND" state.
*
* @return The System.currentTimeMillis() value when the session was bound.
*/
public long getBoundTime();
/**
* ESME Address
* @return
*/
public Address getAddress();
/**
* Main underlying method for sending a request PDU to the remote endpoint.
* If no sequence number was assigned to the PDU, this method will assign
* one. The PDU will be converted into a sequence of bytes by the underlying
* transcoder. Also, adds the request to the underlying request "window" by
* either taking or waiting for an open slot. This is not "synchronous",
* then the eventual response will be passed to the
* "fireExpectedPduResponseReceived" method on the session handler. Please
* note that its possible th response PDU really isn't the correct PDU we
* were waiting for, so the caller should verify it. For example it is
* possible that a "Generic_Nack" could be returned by the remote endpoint
* in response to a PDU.
*
* @param requestPdu
* The request PDU to send
* @param timeoutMillis
* If synchronous is true, this represents the time to wait for a
* slot to open in the underlying window AND the time to wait for
* a response back from the remote endpoint. If synchronous is
* false, this only represents the time to wait for a slot to
* open in the underlying window.
*
* @return SmppServerTransaction Activity Object.
*
* @throws RecoverablePduException
* Thrown when a recoverable PDU error occurs. A recoverable PDU
* error includes the partially decoded PDU in order to generate
* a negative acknowledgment (NACK) response.
* @throws UnrecoverablePduException
* Thrown when an unrecoverable PDU error occurs. This indicates
* a serious error occurred and usually indicates the session
* should be immediately terminated.
* @throws SmppTimeoutException
* A timeout occurred while waiting for a response from the
* remote endpoint. A timeout can either occur with an
* unresponsive remote endpoint or the bytes were not written in
* time.
* @throws SmppChannelException
* Thrown when the underlying socket/channel was unable to write
* the request.
* @throws InterruptedException
* The calling thread was interrupted while waiting to acquire a
* lock or write/read the bytes from the socket/channel.
*/
public SmppServerTransaction sendRequestPdu(PduRequest request, long timeoutMillis) throws RecoverablePduException,
UnrecoverablePduException, SmppTimeoutException, SmppChannelException, InterruptedException,
ActivityAlreadyExistsException, NullPointerException, IllegalStateException, SLEEException,
StartActivityException;
/**
* Main underlying method for sending a response PDU to the remote endpoint.
* The PDU will be converted into a sequence of bytes by the underlying
* transcoder. Writes the bytes out to the socket/channel.
*
* @param request
* The original request received.
* @param response
* The response PDU to send
* @throws RecoverablePduException
* Thrown when a recoverable PDU error occurs. A recoverable PDU
* error includes the partially decoded PDU in order to generate
* a negative acknowledgment (NACK) response.
* @throws UnrecoverablePduException
* Thrown when an unrecoverable PDU error occurs. This indicates
* a serious error occurred and usually indicates the session
* should be immediately terminated.
* @throws SmppChannelException
* Thrown when the underlying socket/channel was unable to write
* the request.
* @throws InterruptedException
* The calling thread was interrupted while waiting to acquire a
* lock or write/read the bytes from the socket/channel.
*/
public void sendResponsePdu(PduRequest request, PduResponse response) throws RecoverablePduException,
UnrecoverablePduException, SmppChannelException, InterruptedException;
}
| Java |
package org.mobicents.smsc.slee.resources.smpp.server;
public interface SmppServerTransaction {
public SmppServerSession getSmppSession();
}
| Java |
package org.mobicents.smsc.slee.services.smpp.server.events;
import java.io.Serializable;
import java.sql.Timestamp;
public class SmsEvent implements Serializable {
/**
* Mobicents SMSC variables
*/
private String messageId;
/**
* System ID is the ESME System ID. Used only when SMS is coming from ESME
*/
private String systemId;
/**
* Time when this SMS was received
*/
private Timestamp submitDate;
/**
* From SUBMIT_SM
*/
private byte sourceAddrTon;
private byte sourceAddrNpi;
private String sourceAddr;
private byte destAddrTon;
private byte destAddrNpi;
private String destAddr;
private byte esmClass;
private byte protocolId; // not present in data_sm
private byte priority; // not present in data_sm
private String scheduleDeliveryTime; // not present in data_sm
private String validityPeriod; // not present in data_sm
protected byte registeredDelivery;
private byte replaceIfPresent; // not present in data_sm
protected byte dataCoding;
private byte defaultMsgId; // not present in data_sm, not used in deliver_sm
private byte[] shortMessage; // not present in data_sm
public SmsEvent() {
}
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public String getSystemId() {
return systemId;
}
public void setSystemId(String systemId) {
this.systemId = systemId;
}
public byte getSourceAddrTon() {
return sourceAddrTon;
}
public void setSourceAddrTon(byte sourceAddrTon) {
this.sourceAddrTon = sourceAddrTon;
}
public byte getSourceAddrNpi() {
return sourceAddrNpi;
}
public void setSourceAddrNpi(byte sourceAddrNpi) {
this.sourceAddrNpi = sourceAddrNpi;
}
public String getSourceAddr() {
return sourceAddr;
}
public void setSourceAddr(String sourceAddr) {
this.sourceAddr = sourceAddr;
}
public byte getDestAddrTon() {
return destAddrTon;
}
public void setDestAddrTon(byte destAddrTon) {
this.destAddrTon = destAddrTon;
}
public byte getDestAddrNpi() {
return destAddrNpi;
}
public void setDestAddrNpi(byte destAddrNpi) {
this.destAddrNpi = destAddrNpi;
}
public String getDestAddr() {
return destAddr;
}
public void setDestAddr(String destAddr) {
this.destAddr = destAddr;
}
public byte getEsmClass() {
return esmClass;
}
public void setEsmClass(byte esmClass) {
this.esmClass = esmClass;
}
public byte getProtocolId() {
return protocolId;
}
public void setProtocolId(byte protocolId) {
this.protocolId = protocolId;
}
public byte getPriority() {
return priority;
}
public void setPriority(byte priority) {
this.priority = priority;
}
public String getScheduleDeliveryTime() {
return scheduleDeliveryTime;
}
public void setScheduleDeliveryTime(String scheduleDeliveryTime) {
this.scheduleDeliveryTime = scheduleDeliveryTime;
}
public String getValidityPeriod() {
return validityPeriod;
}
public void setValidityPeriod(String validityPeriod) {
this.validityPeriod = validityPeriod;
}
public byte getRegisteredDelivery() {
return registeredDelivery;
}
public void setRegisteredDelivery(byte registeredDelivery) {
this.registeredDelivery = registeredDelivery;
}
public byte getReplaceIfPresent() {
return replaceIfPresent;
}
public void setReplaceIfPresent(byte replaceIfPresent) {
this.replaceIfPresent = replaceIfPresent;
}
public byte getDataCoding() {
return dataCoding;
}
public void setDataCoding(byte dataCoding) {
this.dataCoding = dataCoding;
}
public byte getDefaultMsgId() {
return defaultMsgId;
}
public void setDefaultMsgId(byte defaultMsgId) {
this.defaultMsgId = defaultMsgId;
}
public byte[] getShortMessage() {
return shortMessage;
}
public void setShortMessage(byte[] shortMessage) {
this.shortMessage = shortMessage;
}
public Timestamp getSubmitDate() {
return submitDate;
}
public void setSubmitDate(Timestamp submitDate) {
this.submitDate = submitDate;
}
@Override
public String toString() {
return "SmsEvent [messageId=" + messageId + ", systemId=" + systemId + ", sourceAddrTon=" + sourceAddrTon
+ ", sourceAddrNpi=" + sourceAddrNpi + ", sourceAddr=" + sourceAddr + ", destAddrTon=" + destAddrTon
+ ", destAddrNpi=" + destAddrNpi + ", destAddr=" + destAddr + ", esmClass=" + esmClass
+ ", protocolId=" + protocolId + ", priority=" + priority + ", scheduleDeliveryTime="
+ scheduleDeliveryTime + ", validityPeriod=" + validityPeriod + ", registeredDelivery="
+ registeredDelivery + ", replaceIfPresent=" + replaceIfPresent + ", dataCoding=" + dataCoding
+ ", defaultMsgId=" + defaultMsgId + "]";
}
// @Override
// public int hashCode() {
// final int prime = 71;
// int result = 1;
// result = prime * result + (int) (messageId ^ (messageId >>> 32));
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// SmsEvent other = (SmsEvent) obj;
// if (messageId != other.messageId)
// return false;
// return true;
// }
}
| Java |
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* 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.smsc.slee.services.mt;
import javax.slee.ActivityContextInterface;
import javax.slee.ChildRelation;
import javax.slee.CreateException;
import javax.slee.EventContext;
import org.mobicents.protocols.ss7.indicator.NatureOfAddress;
import org.mobicents.protocols.ss7.indicator.NumberingPlan;
import org.mobicents.protocols.ss7.indicator.RoutingIndicator;
import org.mobicents.protocols.ss7.map.api.MAPApplicationContext;
import org.mobicents.protocols.ss7.map.api.MAPApplicationContextName;
import org.mobicents.protocols.ss7.map.api.MAPException;
import org.mobicents.protocols.ss7.map.api.dialog.MAPRefuseReason;
import org.mobicents.protocols.ss7.map.api.primitives.AddressNature;
import org.mobicents.protocols.ss7.map.api.primitives.ISDNAddressString;
import org.mobicents.protocols.ss7.map.api.service.sms.MAPDialogSms;
import org.mobicents.protocols.ss7.map.api.service.sms.SendRoutingInfoForSMRequest;
import org.mobicents.protocols.ss7.map.api.service.sms.SendRoutingInfoForSMResponse;
import org.mobicents.protocols.ss7.sccp.parameter.GT0100;
import org.mobicents.protocols.ss7.sccp.parameter.SccpAddress;
import org.mobicents.protocols.ss7.tcap.asn.ApplicationContextName;
import org.mobicents.slee.resource.map.events.DialogProviderAbort;
import org.mobicents.slee.resource.map.events.DialogReject;
import org.mobicents.slee.resource.map.events.DialogTimeout;
import org.mobicents.slee.resource.map.events.ErrorComponent;
import org.mobicents.smsc.slee.services.smpp.server.events.SmsEvent;
/**
*
*
* @author amit bhayani
*
*/
public abstract class SriSbb extends MtCommonSbb {
private static final String className = "SriSbb";
// Keep timeout for event suspend to be maximum
private static final int EVENT_SUSPEND_TIMEOUT = 1000 * 60 * 3;
private MAPApplicationContext sriMAPApplicationContext = null;
public SriSbb() {
super(className);
}
/**
* Event Handlers
*/
public void onSms(SmsEvent event, ActivityContextInterface aci, EventContext eventContext) {
// Reduce the events pending to be fired on this ACI
MtActivityContextInterface mtSbbActivityContextInterface = this.asSbbActivityContextInterface(aci);
int pendingEventsOnNullActivity = mtSbbActivityContextInterface.getPendingEventsOnNullActivity();
if (this.logger.isInfoEnabled()) {
this.logger.info("Received SMS. pendingEventsOnNullActivity=" + pendingEventsOnNullActivity + " event= "
+ event + "this=" + this);
}
pendingEventsOnNullActivity = pendingEventsOnNullActivity - 1;
mtSbbActivityContextInterface.setPendingEventsOnNullActivity(pendingEventsOnNullActivity);
// Suspend the delivery of event till unsuspended by other
// event-handlers
eventContext.suspendDelivery(EVENT_SUSPEND_TIMEOUT);
this.setNullActivityEventContext(eventContext);
// TODO: Some mechanism to check if this MSISDN is not available in
// which case persist this even in database
// This MSISDN is available. Begin SRI and let Mt process begin
this.sendSRI(event.getDestAddr(), this.getSRIMAPApplicationContext());
}
/**
* Components Events override from MtCommonSbb that we care
*/
@Override
public void onErrorComponent(ErrorComponent event, ActivityContextInterface aci) {
super.onErrorComponent(event, aci);
// TODO : Take care of error condition and marking status for MSISDN
}
/**
* Dialog Events override from MtCommonSbb that we care
*/
@Override
public void onDialogReject(DialogReject evt, ActivityContextInterface aci) {
MAPRefuseReason mapRefuseReason = evt.getRefuseReason();
// If ACN not supported, lets use the new one suggested
if (mapRefuseReason == MAPRefuseReason.ApplicationContextNotSupported) {
// lets detach so we don't get onDialogRelease() which will start
// delivering SMS waiting in queue for same MSISDN
aci.detach(this.sbbContext.getSbbLocalObject());
// Now send new SRI with supported ACN
ApplicationContextName tcapApplicationContextName = evt.getAlternativeApplicationContext();
MAPApplicationContext supportedMAPApplicationContext = MAPApplicationContext
.getInstance(tcapApplicationContextName.getOid());
SmsEvent event = this.getOriginalSmsEvent();
this.sendSRI(event.getDestAddr(), supportedMAPApplicationContext);
} else {
super.onDialogReject(evt, aci);
}
}
@Override
public void onDialogProviderAbort(DialogProviderAbort evt, ActivityContextInterface aci) {
super.onDialogProviderAbort(evt, aci);
// TODO : SmsEvent should now be handed to StoreAndForwardSbb to store
// this event.
// TODO : Set flag for this MSISDN so no more Mt process is tried,
// rather handed to Mt directly
}
@Override
public void onDialogTimeout(DialogTimeout evt, ActivityContextInterface aci) {
super.onDialogTimeout(evt, aci);
// TODO : SmsEvent should now be handed to StoreAndForwardSbb to store
// this event.
// TODO : Set flag for this MSISDN so no more Mt process is tried,
// rather handed to Mt directly
}
/**
* MAP SMS Events
*/
/**
* Received SRI request. But this is error, we should never receive this
* request
*
* @param evt
* @param aci
*/
public void onSendRoutingInfoForSMRequest(SendRoutingInfoForSMRequest evt, ActivityContextInterface aci) {
this.logger.severe("Received SEND_ROUTING_INFO_FOR_SM_REQUEST = " + evt);
}
/**
* Received response for SRI sent earlier
*
* @param evt
* @param aci
*/
public void onSendRoutingInfoForSMResponse(SendRoutingInfoForSMResponse evt, ActivityContextInterface aci) {
if (this.logger.isInfoEnabled()) {
this.logger.info("Received SEND_ROUTING_INFO_FOR_SM_RESPONSE = " + evt + " Dialog=" + evt.getMAPDialog());
}
// lets detach so we don't get onDialogRelease() which will start
// delivering SMS waiting in queue for same MSISDN
aci.detach(this.sbbContext.getSbbLocalObject());
MtSbbLocalObject mtSbbLocalObject = null;
try {
ChildRelation relation = getMtSbb();
mtSbbLocalObject = (MtSbbLocalObject) relation.create();
mtSbbLocalObject.setupMtForwardShortMessageRequest(evt.getLocationInfoWithLMSI().getNetworkNodeNumber(),
evt.getIMSI(), this.getNullActivityEventContext());
} catch (CreateException e) {
this.logger.severe("Could not create Child SBB", e);
MtActivityContextInterface mtSbbActivityContextInterface = this.asSbbActivityContextInterface(this
.getNullActivityEventContext().getActivityContextInterface());
this.resumeNullActivityEventDelivery(mtSbbActivityContextInterface, this.getNullActivityEventContext());
} catch (Exception e) {
this.logger.severe("Exception while trying to creat MtSbb child", e);
MtActivityContextInterface mtSbbActivityContextInterface = this.asSbbActivityContextInterface(this
.getNullActivityEventContext().getActivityContextInterface());
this.resumeNullActivityEventDelivery(mtSbbActivityContextInterface, this.getNullActivityEventContext());
}
}
/**
* Get Mt child SBB
*
* @return
*/
public abstract ChildRelation getMtSbb();
/**
* Private methods
*/
private ISDNAddressString getCalledPartyISDNAddressString(String destinationAddress) {
// TODO save the ISDNAddressString in CMP to avoid creation everytime?
return this.mapParameterFactory.createISDNAddressString(AddressNature.international_number,
org.mobicents.protocols.ss7.map.api.primitives.NumberingPlan.ISDN, destinationAddress);
}
private void sendSRI(String destinationAddress, MAPApplicationContext mapApplicationContext) {
// Send out SMS
MAPDialogSms mapDialogSms = null;
try {
// 1. Create Dialog first and add the SRI request to it
mapDialogSms = this.setupRoutingInfoForSMRequestIndication(destinationAddress, mapApplicationContext);
// 2. Create the ACI and attach this SBB
ActivityContextInterface sriDialogACI = this.mapAcif.getActivityContextInterface(mapDialogSms);
sriDialogACI.attach(this.sbbContext.getSbbLocalObject());
// 3. Finally send the request
mapDialogSms.send();
} catch (MAPException e) {
logger.severe("Error while trying to send SendRoutingInfoForSMRequest", e);
// something horrible, release MAPDialog and free resources
if (mapDialogSms != null) {
mapDialogSms.release();
}
MtActivityContextInterface mtSbbActivityContextInterface = this.asSbbActivityContextInterface(this
.getNullActivityEventContext().getActivityContextInterface());
this.resumeNullActivityEventDelivery(mtSbbActivityContextInterface, this.getNullActivityEventContext());
// TODO : Take care of error condition
}
}
private MAPDialogSms setupRoutingInfoForSMRequestIndication(String destinationAddress,
MAPApplicationContext mapApplicationContext) throws MAPException {
// this.mapParameterFactory.creat
SccpAddress destinationReference = this.convertAddressFieldToSCCPAddress(destinationAddress);
MAPDialogSms mapDialogSms = this.mapProvider.getMAPServiceSms().createNewDialog(mapApplicationContext,
this.getServiceCenterSccpAddress(), null, destinationReference, null);
mapDialogSms.addSendRoutingInfoForSMRequest(this.getCalledPartyISDNAddressString(destinationAddress), true,
this.getServiceCenterAddressString(), null, false, null, null, null);
return mapDialogSms;
}
private SccpAddress convertAddressFieldToSCCPAddress(String address) {
GT0100 gt = new GT0100(0, NumberingPlan.ISDN_TELEPHONY, NatureOfAddress.INTERNATIONAL, address);
return new SccpAddress(RoutingIndicator.ROUTING_BASED_ON_GLOBAL_TITLE, 0, gt,
smscPropertiesManagement.getHlrSsn());
}
private MAPApplicationContext getSRIMAPApplicationContext() {
if (this.sriMAPApplicationContext == null) {
this.sriMAPApplicationContext = MAPApplicationContext.getInstance(
MAPApplicationContextName.shortMsgGatewayContext, this.maxMAPApplicationContextVersion);
}
return this.sriMAPApplicationContext;
}
}
| Java |
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* 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.smsc.slee.services.mt;
import javax.slee.EventContext;
import org.mobicents.protocols.ss7.map.api.primitives.IMSI;
import org.mobicents.protocols.ss7.map.api.primitives.ISDNAddressString;
/**
*
* @author amit bhayani
*
*/
public interface MtForwardSmsInterface {
public void setupMtForwardShortMessageRequest(ISDNAddressString networkNode, IMSI imsi,
EventContext nullActivityEventContext);
}
| Java |
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* 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.smsc.slee.services.mt;
import javax.slee.SbbLocalObject;
/**
*
* @author amit bhayani
*
*/
public interface MtSbbLocalObject extends SbbLocalObject, MtForwardSmsInterface {
}
| Java |
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* 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.smsc.slee.services.mt;
import java.sql.Timestamp;
import javax.slee.ActivityContextInterface;
import javax.slee.EventContext;
import org.mobicents.protocols.ss7.indicator.NatureOfAddress;
import org.mobicents.protocols.ss7.indicator.NumberingPlan;
import org.mobicents.protocols.ss7.indicator.RoutingIndicator;
import org.mobicents.protocols.ss7.map.api.MAPApplicationContext;
import org.mobicents.protocols.ss7.map.api.MAPApplicationContextName;
import org.mobicents.protocols.ss7.map.api.MAPException;
import org.mobicents.protocols.ss7.map.api.dialog.MAPRefuseReason;
import org.mobicents.protocols.ss7.map.api.primitives.IMSI;
import org.mobicents.protocols.ss7.map.api.primitives.ISDNAddressString;
import org.mobicents.protocols.ss7.map.api.service.sms.ForwardShortMessageRequest;
import org.mobicents.protocols.ss7.map.api.service.sms.ForwardShortMessageResponse;
import org.mobicents.protocols.ss7.map.api.service.sms.MAPDialogSms;
import org.mobicents.protocols.ss7.map.api.service.sms.MtForwardShortMessageRequest;
import org.mobicents.protocols.ss7.map.api.service.sms.MtForwardShortMessageResponse;
import org.mobicents.protocols.ss7.map.api.service.sms.SM_RP_DA;
import org.mobicents.protocols.ss7.map.api.service.sms.SM_RP_OA;
import org.mobicents.protocols.ss7.map.api.smstpdu.AddressField;
import org.mobicents.protocols.ss7.map.api.smstpdu.NumberingPlanIdentification;
import org.mobicents.protocols.ss7.map.api.smstpdu.TypeOfNumber;
import org.mobicents.protocols.ss7.map.service.sms.SmsSignalInfoImpl;
import org.mobicents.protocols.ss7.map.smstpdu.AbsoluteTimeStampImpl;
import org.mobicents.protocols.ss7.map.smstpdu.AddressFieldImpl;
import org.mobicents.protocols.ss7.map.smstpdu.DataCodingSchemeImpl;
import org.mobicents.protocols.ss7.map.smstpdu.ProtocolIdentifierImpl;
import org.mobicents.protocols.ss7.map.smstpdu.SmsDeliverTpduImpl;
import org.mobicents.protocols.ss7.map.smstpdu.UserDataImpl;
import org.mobicents.protocols.ss7.sccp.parameter.GT0100;
import org.mobicents.protocols.ss7.sccp.parameter.SccpAddress;
import org.mobicents.protocols.ss7.tcap.asn.ApplicationContextName;
import org.mobicents.slee.resource.map.events.DialogProviderAbort;
import org.mobicents.slee.resource.map.events.DialogReject;
import org.mobicents.slee.resource.map.events.DialogTimeout;
import org.mobicents.slee.resource.map.events.ErrorComponent;
import org.mobicents.smsc.slee.services.smpp.server.events.SmsEvent;
public abstract class MtSbb extends MtCommonSbb implements MtForwardSmsInterface {
private static final String className = "MtSbb";
private MAPApplicationContext mtFoSMSMAPApplicationContext = null;
public MtSbb() {
super(className);
}
/**
* Components Events override from MtCommonSbb that we care
*/
@Override
public void onErrorComponent(ErrorComponent event, ActivityContextInterface aci) {
super.onErrorComponent(event, aci);
// TODO : Take care of error condition and Store and Forward
// TODO : Its possible to receive two MAP Components in same TCAP
// Dialog, one error and other informServiceCenter. Look at packet 28 of
// wiresharktrace smsc_sv01apsmsc01.pcap. Handle this situation
}
/**
* Dialog Events override from MtCommonSbb that we care
*/
@Override
public void onDialogProviderAbort(DialogProviderAbort evt, ActivityContextInterface aci) {
super.onDialogProviderAbort(evt, aci);
// TODO : SmsEvent should now be handed to StoreAndForwardSbb to store
// this event.
// TODO : Set flag for this MSISDN so no more Mt process is tried,
// rather handed to Mt directly
}
@Override
public void onDialogTimeout(DialogTimeout evt, ActivityContextInterface aci) {
super.onDialogTimeout(evt, aci);
// TODO : SmsEvent should now be handed to StoreAndForwardSbb to store
// this event.
// TODO : Set flag for this MSISDN so no more Mt process is tried,
// rather handed to Mt directly
}
@Override
public void onDialogReject(DialogReject evt, ActivityContextInterface aci) {
MAPRefuseReason mapRefuseReason = evt.getRefuseReason();
// If ACN not supported, lets use the new one suggested
if (mapRefuseReason == MAPRefuseReason.ApplicationContextNotSupported) {
// lets detach so we don't get onDialogRelease() which will start
// delivering SMS waiting in queue for same MSISDN
aci.detach(this.sbbContext.getSbbLocalObject());
// Now send new SRI with supported ACN
ApplicationContextName tcapApplicationContextName = evt.getAlternativeApplicationContext();
MAPApplicationContext supportedMAPApplicationContext = MAPApplicationContext
.getInstance(tcapApplicationContextName.getOid());
SmsEvent event = this.getOriginalSmsEvent();
this.sendMtSms(this.getNetworkNode(), this.getImsi(), event, supportedMAPApplicationContext);
} else {
super.onDialogReject(evt, aci);
}
}
/**
* SMS Event Handlers
*/
/**
* Received MT SMS. This is error we should never receive this
*
* @param evt
* @param aci
*/
public void onForwardShortMessageRequest(ForwardShortMessageRequest evt, ActivityContextInterface aci) {
this.logger.severe("Received FORWARD_SHORT_MESSAGE_REQUEST = " + evt);
}
/**
* Received ACK for MT Forward SMS sent earlier
*
* @param evt
* @param aci
*/
public void onForwardShortMessageResponse(ForwardShortMessageResponse evt, ActivityContextInterface aci) {
if (this.logger.isInfoEnabled()) {
this.logger.info("Received FORWARD_SHORT_MESSAGE_RESPONSE = " + evt);
}
SmsEvent smsEvent = this.getOriginalSmsEvent();
if (smsEvent != null) {
try {
if (smsEvent.getSystemId() != null) {
sendSuccessDeliverSmToEsms(smsEvent);
} else {
// TODO : This is destined for Mobile user, send
// SMS-STATUS-REPORT
}
} catch (Exception e) {
this.logger.severe(
String.format("Exception while trying to send Delivery Report for SmsEvent=%s", smsEvent), e);
}
}
}
/**
* Received MT SMS. This is error we should never receive this
*
* @param evt
* @param aci
*/
public void onMtForwardShortMessageRequest(MtForwardShortMessageRequest evt, ActivityContextInterface aci) {
this.logger.severe("Received MT_FORWARD_SHORT_MESSAGE_REQUEST = " + evt);
}
/**
* Received ACK for MT Forward SMS sent earlier
*
* @param evt
* @param aci
*/
public void onMtForwardShortMessageResponse(MtForwardShortMessageResponse evt, ActivityContextInterface aci) {
if (this.logger.isInfoEnabled()) {
this.logger.info("Received MT_FORWARD_SHORT_MESSAGE_RESPONSE = " + evt);
}
SmsEvent smsEvent = this.getOriginalSmsEvent();
if (smsEvent != null) {
try {
if (smsEvent.getSystemId() != null) {
sendSuccessDeliverSmToEsms(smsEvent);
} else {
// TODO : This is destined for Mobile user, send
// SMS-STATUS-REPORT
}
} catch (Exception e) {
this.logger.severe(
String.format("Exception while trying to send Delivery Report for SmsEvent=%s", smsEvent), e);
}
}
// Amit (12 Aug 2012): this is also done in onDialogRelease why repeat
// here?
// aci.detach(this.sbbContext.getSbbLocalObject());
// MtActivityContextInterface mtSbbActivityContextInterface =
// this.asSbbActivityContextInterface(this
// .getNullActivityEventContext().getActivityContextInterface());
// this.resumeNullActivityEventDelivery(mtSbbActivityContextInterface,
// this.getNullActivityEventContext());
}
/**
* SBB Local Object Methods
*
* @throws MAPException
*/
@Override
public void setupMtForwardShortMessageRequest(ISDNAddressString networkNode, IMSI imsi,
EventContext nullActivityEventContext) {
if (this.logger.isInfoEnabled()) {
this.logger.info("Received setupMtForwardShortMessageRequestIndication ISDNAddressString= " + networkNode
+ " nullActivityEventContext" + nullActivityEventContext);
}
this.setNullActivityEventContext(nullActivityEventContext);
this.setNetworkNode(networkNode);
this.setImsi(imsi);
SmsEvent smsEvent = (SmsEvent) nullActivityEventContext.getEvent();
this.sendMtSms(networkNode, imsi, smsEvent, this.getMtFoSMSMAPApplicationContext());
}
/**
* CMPs
*/
/**
* Set the ISDNAddressString of network node where Mt SMS is to be submitted
*
* @param networkNode
*/
public abstract void setNetworkNode(ISDNAddressString networkNode);
public abstract ISDNAddressString getNetworkNode();
/**
* Set the IMSI of destination MSISDN
*
* @param imsi
*/
public abstract void setImsi(IMSI imsi);
public abstract IMSI getImsi();
/**
* Private Methods
*/
private void sendMtSms(ISDNAddressString networkNode, IMSI imsi, SmsEvent smsEvent,
MAPApplicationContext mapApplicationContext) {
MAPDialogSms mapDialogSms = null;
try {
mapDialogSms = this.mapProvider.getMAPServiceSms().createNewDialog(mapApplicationContext,
this.getServiceCenterSccpAddress(), null, this.getMSCSccpAddress(networkNode), null);
SM_RP_DA sm_RP_DA = this.mapParameterFactory.createSM_RP_DA(imsi);
SM_RP_OA sm_RP_OA = this.mapParameterFactory.createSM_RP_OA_ServiceCentreAddressOA(this
.getServiceCenterAddressString());
UserDataImpl ud = new UserDataImpl(new String(smsEvent.getShortMessage()), new DataCodingSchemeImpl(
smsEvent.getDataCoding()), null, null);
// TODO : Should this be SubmitDate or currentDate?
Timestamp submitDate = smsEvent.getSubmitDate();
AbsoluteTimeStampImpl serviceCentreTimeStamp = new AbsoluteTimeStampImpl((submitDate.getYear() % 100),
(submitDate.getMonth() + 1), submitDate.getDate(), submitDate.getHours(), submitDate.getMinutes(),
submitDate.getSeconds(), (submitDate.getTimezoneOffset() / 15));
// TODO : Can this be constant?
ProtocolIdentifierImpl pi = new ProtocolIdentifierImpl(0);
// TODO : Take care of esm_class to include UDHI. See SMPP specs
SmsDeliverTpduImpl smsDeliverTpduImpl = new SmsDeliverTpduImpl(false, false, false, true,
this.getSmsTpduOriginatingAddress(smsEvent.getSourceAddrTon(), smsEvent.getSourceAddrNpi(),
smsEvent.getSourceAddr()), pi, serviceCentreTimeStamp, ud);
SmsSignalInfoImpl SmsSignalInfoImpl = new SmsSignalInfoImpl(smsDeliverTpduImpl, null);
switch (mapApplicationContext.getApplicationContextVersion()) {
case version3:
mapDialogSms.addMtForwardShortMessageRequest(sm_RP_DA, sm_RP_OA, SmsSignalInfoImpl, false, null);
break;
case version2:
mapDialogSms.addForwardShortMessageRequest(sm_RP_DA, sm_RP_OA, SmsSignalInfoImpl, false);
break;
default:
// TODO take care of this, but should this ever happen?
logger.severe(String.format("Trying to send Mt SMS with version=%d. This is serious!!",
mapApplicationContext.getApplicationContextVersion().getVersion()));
break;
}
ActivityContextInterface mtFOSmsDialogACI = this.mapAcif.getActivityContextInterface(mapDialogSms);
mtFOSmsDialogACI.attach(this.sbbContext.getSbbLocalObject());
mapDialogSms.send();
} catch (MAPException e) {
// TODO : Take care of error
logger.severe("Error while trying to send MtForwardShortMessageRequestIndication", e);
// something horrible, release MAPDialog and free resources
if (mapDialogSms != null) {
mapDialogSms.release();
}
MtActivityContextInterface mtSbbActivityContextInterface = this.asSbbActivityContextInterface(this
.getNullActivityEventContext().getActivityContextInterface());
this.resumeNullActivityEventDelivery(mtSbbActivityContextInterface, this.getNullActivityEventContext());
}
}
private MAPApplicationContext getMtFoSMSMAPApplicationContext() {
if (this.mtFoSMSMAPApplicationContext == null) {
this.mtFoSMSMAPApplicationContext = MAPApplicationContext.getInstance(
MAPApplicationContextName.shortMsgMTRelayContext, this.maxMAPApplicationContextVersion);
}
return this.mtFoSMSMAPApplicationContext;
}
private SccpAddress getMSCSccpAddress(ISDNAddressString networkNodeNumber) {
// TODO : use the networkNodeNumber also to derive if its
// International / ISDN?
GT0100 gt = new GT0100(0, NumberingPlan.ISDN_TELEPHONY, NatureOfAddress.INTERNATIONAL,
networkNodeNumber.getAddress());
return new SccpAddress(RoutingIndicator.ROUTING_BASED_ON_GLOBAL_TITLE, 0, gt,
smscPropertiesManagement.getMscSsn());
}
private AddressField getSmsTpduOriginatingAddress(byte ton, byte npi, String address) {
return new AddressFieldImpl(TypeOfNumber.getInstance(ton), NumberingPlanIdentification.getInstance(npi),
address);
}
}
| Java |
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* 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.smsc.slee.services.mt;
import javax.slee.ActivityContextInterface;
/**
*
* @author amit bhayani
*
*/
public interface MtActivityContextInterface extends ActivityContextInterface {
public int getPendingEventsOnNullActivity();
public void setPendingEventsOnNullActivity(int events);
}
| Java |
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* 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.smsc.slee.services.mt;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.slee.ActivityContextInterface;
import javax.slee.CreateException;
import javax.slee.EventContext;
import javax.slee.RolledBackContext;
import javax.slee.Sbb;
import javax.slee.SbbContext;
import javax.slee.facilities.Tracer;
import javax.slee.nullactivity.NullActivity;
import org.mobicents.protocols.ss7.indicator.NatureOfAddress;
import org.mobicents.protocols.ss7.indicator.NumberingPlan;
import org.mobicents.protocols.ss7.indicator.RoutingIndicator;
import org.mobicents.protocols.ss7.map.api.MAPApplicationContextVersion;
import org.mobicents.protocols.ss7.map.api.MAPParameterFactory;
import org.mobicents.protocols.ss7.map.api.MAPProvider;
import org.mobicents.protocols.ss7.map.api.primitives.AddressNature;
import org.mobicents.protocols.ss7.map.api.primitives.AddressString;
import org.mobicents.protocols.ss7.sccp.parameter.GT0100;
import org.mobicents.protocols.ss7.sccp.parameter.SccpAddress;
import org.mobicents.slee.SbbContextExt;
import org.mobicents.slee.resource.map.MAPContextInterfaceFactory;
import org.mobicents.slee.resource.map.events.DialogAccept;
import org.mobicents.slee.resource.map.events.DialogClose;
import org.mobicents.slee.resource.map.events.DialogDelimiter;
import org.mobicents.slee.resource.map.events.DialogNotice;
import org.mobicents.slee.resource.map.events.DialogProviderAbort;
import org.mobicents.slee.resource.map.events.DialogReject;
import org.mobicents.slee.resource.map.events.DialogRelease;
import org.mobicents.slee.resource.map.events.DialogRequest;
import org.mobicents.slee.resource.map.events.DialogTimeout;
import org.mobicents.slee.resource.map.events.DialogUserAbort;
import org.mobicents.slee.resource.map.events.ErrorComponent;
import org.mobicents.slee.resource.map.events.InvokeTimeout;
import org.mobicents.slee.resource.map.events.RejectComponent;
import org.mobicents.smsc.slee.services.smpp.server.events.SmsEvent;
import org.mobicents.smsc.smpp.SmscPropertiesManagement;
import com.cloudhopper.commons.charset.CharsetUtil;
import com.cloudhopper.smpp.util.SmppUtil;
public abstract class MtCommonSbb implements Sbb {
private static final byte ESME_DELIVERY_ACK = 0x08;
private static final String DELIVERY_ACK_ID = "id:";
private static final String DELIVERY_ACK_SUB = " sub:";
private static final String DELIVERY_ACK_DLVRD = " dlvrd:";
private static final String DELIVERY_ACK_SUBMIT_DATE = " submit date:";
private static final String DELIVERY_ACK_DONE_DATE = " done date:";
private static final String DELIVERY_ACK_STAT = " stat:";
private static final String DELIVERY_ACK_ERR = " err:";
private static final String DELIVERY_ACK_TEXT = " text:";
private static final String DELIVERY_ACK_STATE_DELIVERED = "DELIVRD";
private static final String DELIVERY_ACK_STATE_EXPIRED = "EXPIRED";
private static final String DELIVERY_ACK_STATE_DELETED = "DELETED";
private static final String DELIVERY_ACK_STATE_UNDELIVERABLE = "UNDELIV";
private static final String DELIVERY_ACK_STATE_ACCEPTED = "ACCEPTD";
private static final String DELIVERY_ACK_STATE_UNKNOWN = "UNKNOWN";
private static final String DELIVERY_ACK_STATE_REJECTED = "REJECTD";
protected static final SmscPropertiesManagement smscPropertiesManagement = SmscPropertiesManagement.getInstance();
private final SimpleDateFormat DELIVERY_ACK_DATE_FORMAT = new SimpleDateFormat("yyMMddHHmm");
private final String className;
protected Tracer logger;
protected SbbContextExt sbbContext;
protected MAPContextInterfaceFactory mapAcif;
protected MAPProvider mapProvider;
protected MAPParameterFactory mapParameterFactory;
private AddressString serviceCenterAddress;
private SccpAddress serviceCenterSCCPAddress = null;
protected MAPApplicationContextVersion maxMAPApplicationContextVersion = null;
public MtCommonSbb(String className) {
this.className = className;
}
/**
* MAP Components Events
*/
public void onInvokeTimeout(InvokeTimeout evt, ActivityContextInterface aci) {
if (logger.isInfoEnabled()) {
this.logger.info("Rx : onInvokeTimeout" + evt);
}
}
public void onErrorComponent(ErrorComponent event, ActivityContextInterface aci) {
if (this.logger.isInfoEnabled()) {
this.logger.info("Rx : onErrorComponent " + event + " Dialog=" + event.getMAPDialog());
}
// if (mapErrorMessage.isEmAbsentSubscriberSM()) {
// this.sendReportSMDeliveryStatusRequest(SMDeliveryOutcome.absentSubscriber);
// }
SmsEvent original = this.getOriginalSmsEvent();
if (original != null) {
if (original.getSystemId() != null) {
this.sendFailureDeliverSmToEsms(original);
}
}
}
// public void onProviderErrorComponent(ProviderErrorComponent event, ActivityContextInterface aci) {
// this.logger.severe("Rx : onProviderErrorComponent" + event);
//
// SmsEvent original = this.getOriginalSmsEvent();
//
// if (original != null) {
// if (original.getSystemId() != null) {
// this.sendFailureDeliverSmToEsms(original);
// }
// }
// }
public void onRejectComponent(RejectComponent event, ActivityContextInterface aci) {
this.logger.severe("Rx : onRejectComponent" + event);
SmsEvent original = this.getOriginalSmsEvent();
if (original != null) {
if (original.getSystemId() != null) {
this.sendFailureDeliverSmToEsms(original);
}
}
}
/**
* Dialog Events
*/
public void onDialogDelimiter(DialogDelimiter evt, ActivityContextInterface aci) {
if (logger.isFineEnabled()) {
this.logger.fine("Rx : onDialogDelimiter=" + evt);
}
}
public void onDialogAccept(DialogAccept evt, ActivityContextInterface aci) {
if (logger.isFineEnabled()) {
this.logger.fine("Rx : onDialogAccept=" + evt);
}
}
public void onDialogReject(DialogReject evt, ActivityContextInterface aci) {
if (logger.isWarningEnabled()) {
this.logger.warning("Rx : onDialogReject=" + evt);
}
// TODO : Error condition. Take care
SmsEvent original = this.getOriginalSmsEvent();
if (original != null) {
if (original.getSystemId() != null) {
this.sendFailureDeliverSmToEsms(original);
}
}
}
public void onDialogUserAbort(DialogUserAbort evt, ActivityContextInterface aci) {
this.logger.severe("Rx : onDialogUserAbort=" + evt);
// TODO : Error condition. Take care
SmsEvent original = this.getOriginalSmsEvent();
if (original != null) {
if (original.getSystemId() != null) {
this.sendFailureDeliverSmToEsms(original);
}
}
}
public void onDialogProviderAbort(DialogProviderAbort evt, ActivityContextInterface aci) {
this.logger.severe("Rx : onDialogProviderAbort=" + evt);
SmsEvent original = this.getOriginalSmsEvent();
if (original != null) {
if (original.getSystemId() != null) {
this.sendFailureDeliverSmToEsms(original);
}
}
}
public void onDialogClose(DialogClose evt, ActivityContextInterface aci) {
if (logger.isFineEnabled()) {
this.logger.fine("Rx : onDialogClose" + evt);
}
}
public void onDialogNotice(DialogNotice evt, ActivityContextInterface aci) {
if (logger.isInfoEnabled()) {
this.logger.info("Rx : onDialogNotice" + evt);
}
}
public void onDialogTimeout(DialogTimeout evt, ActivityContextInterface aci) {
this.logger.severe("Rx : onDialogTimeout" + evt);
}
public void onDialogRequest(DialogRequest evt, ActivityContextInterface aci) {
if (logger.isFineEnabled()) {
this.logger.fine("Rx : onDialogRequest" + evt);
}
}
public void onDialogRelease(DialogRelease evt, ActivityContextInterface aci) {
if (logger.isInfoEnabled()) {
// TODO : Should be fine
this.logger.info("Rx : DialogRelease" + evt);
}
MtActivityContextInterface mtSbbActivityContextInterface = this.asSbbActivityContextInterface(this
.getNullActivityEventContext().getActivityContextInterface());
this.resumeNullActivityEventDelivery(mtSbbActivityContextInterface, this.getNullActivityEventContext());
}
/**
* Life cycle methods
*/
@Override
public void sbbActivate() {
// TODO Auto-generated method stub
}
@Override
public void sbbCreate() throws CreateException {
// TODO Auto-generated method stub
}
@Override
public void sbbExceptionThrown(Exception arg0, Object arg1, ActivityContextInterface arg2) {
// TODO Auto-generated method stub
}
@Override
public void sbbLoad() {
// TODO Auto-generated method stub
}
@Override
public void sbbPassivate() {
// TODO Auto-generated method stub
}
@Override
public void sbbPostCreate() throws CreateException {
// TODO Auto-generated method stub
}
@Override
public void sbbRemove() {
// TODO Auto-generated method stub
}
@Override
public void sbbRolledBack(RolledBackContext arg0) {
// TODO Auto-generated method stub
}
@Override
public void sbbStore() {
// TODO Auto-generated method stub
}
@Override
public void setSbbContext(SbbContext sbbContext) {
this.sbbContext = (SbbContextExt) sbbContext;
try {
Context ctx = (Context) new InitialContext().lookup("java:comp/env");
this.mapAcif = (MAPContextInterfaceFactory) ctx.lookup("slee/resources/map/2.0/acifactory");
this.mapProvider = (MAPProvider) ctx.lookup("slee/resources/map/2.0/provider");
this.mapParameterFactory = this.mapProvider.getMAPParameterFactory();
this.logger = this.sbbContext.getTracer(this.className);
this.maxMAPApplicationContextVersion = MAPApplicationContextVersion.getInstance(smscPropertiesManagement.getMaxMapVersion());
} catch (Exception ne) {
logger.severe("Could not set SBB context:", ne);
}
// TODO : Handle proper error
}
@Override
public void unsetSbbContext() {
}
/**
* Fire SmsEvent
*
* @param event
* @param aci
* @param address
*/
public abstract void fireSendDeliveryReportSms(SmsEvent event, ActivityContextInterface aci,
javax.slee.Address address);
/**
* CMPs
*/
public abstract void setNullActivityEventContext(EventContext eventContext);
public abstract EventContext getNullActivityEventContext();
/**
* Sbb ACI
*/
public abstract MtActivityContextInterface asSbbActivityContextInterface(ActivityContextInterface aci);
/**
* TODO : This is repetitive in each Sbb. Find way to make it static
* probably?
*
* This is our own number. We are Service Center.
*
* @return
*/
protected AddressString getServiceCenterAddressString() {
if (this.serviceCenterAddress == null) {
this.serviceCenterAddress = this.mapParameterFactory.createAddressString(
AddressNature.international_number,
org.mobicents.protocols.ss7.map.api.primitives.NumberingPlan.ISDN,
smscPropertiesManagement.getServiceCenterGt());
}
return this.serviceCenterAddress;
}
/**
* TODO: This should be configurable and static as well
*
* This is our (Service Center) SCCP Address for GT
*
* @return
*/
protected SccpAddress getServiceCenterSccpAddress() {
if (this.serviceCenterSCCPAddress == null) {
GT0100 gt = new GT0100(0, NumberingPlan.ISDN_TELEPHONY, NatureOfAddress.INTERNATIONAL,
smscPropertiesManagement.getServiceCenterGt());
this.serviceCenterSCCPAddress = new SccpAddress(RoutingIndicator.ROUTING_BASED_ON_GLOBAL_TITLE, 0, gt,
smscPropertiesManagement.getServiceCenterSsn());
}
return this.serviceCenterSCCPAddress;
}
protected void resumeNullActivityEventDelivery(MtActivityContextInterface mtSbbActivityContextInterface,
EventContext nullActivityEventContext) {
if (mtSbbActivityContextInterface.getPendingEventsOnNullActivity() == 0) {
// If no more events pending, lets end NullActivity
NullActivity nullActivity = (NullActivity) nullActivityEventContext.getActivityContextInterface()
.getActivity();
nullActivity.endActivity();
if (logger.isInfoEnabled()) {
this.logger.info(String.format("No more events to be fired on NullActivity=%s: Ended", nullActivity));
}
}
// Resume delivery for rest of the SMS's for this MSISDN
if (nullActivityEventContext.isSuspended()) {
nullActivityEventContext.resumeDelivery();
}
}
protected SmsEvent getOriginalSmsEvent() {
EventContext nullActivityEventContext = this.getNullActivityEventContext();
SmsEvent smsEvent = null;
try {
smsEvent = (SmsEvent) nullActivityEventContext.getEvent();
} catch (Exception e) {
this.logger.severe(
String.format("Exception while trying to retrieve SmsEvent from NullActivity EventContext"), e);
}
return smsEvent;
}
protected void sendFailureDeliverSmToEsms(SmsEvent original) {
// TODO check if SmppSession available for this SystemId, if not send to
// SnF module
byte registeredDelivery = original.getRegisteredDelivery();
// Send Delivery Receipt only if requested
if (SmppUtil.isSmscDeliveryReceiptRequested(registeredDelivery)
|| SmppUtil.isSmscDeliveryReceiptOnFailureRequested(registeredDelivery)) {
SmsEvent deliveryReport = new SmsEvent();
deliveryReport.setSourceAddr(original.getDestAddr());
deliveryReport.setSourceAddrNpi(original.getDestAddrNpi());
deliveryReport.setSourceAddrTon(original.getDestAddrTon());
deliveryReport.setDestAddr(original.getSourceAddr());
deliveryReport.setDestAddrNpi(original.getSourceAddrNpi());
deliveryReport.setDestAddrTon(original.getSourceAddrTon());
// Setting SystemId as null, so RxSmppServerSbb actually tries to
// find real SmppServerSession from Destination TON, NPI and address
// range
deliveryReport.setSystemId(null);
deliveryReport.setSubmitDate(original.getSubmitDate());
deliveryReport.setMessageId(original.getMessageId());
// TODO : Set appropriate error code in err:
StringBuffer sb = new StringBuffer();
sb.append(DELIVERY_ACK_ID).append(original.getMessageId()).append(DELIVERY_ACK_SUB).append("001")
.append(DELIVERY_ACK_DLVRD).append("001").append(DELIVERY_ACK_SUBMIT_DATE)
.append(DELIVERY_ACK_DATE_FORMAT.format(original.getSubmitDate())).append(DELIVERY_ACK_DONE_DATE)
.append(DELIVERY_ACK_DATE_FORMAT.format(new Timestamp(System.currentTimeMillis())))
.append(DELIVERY_ACK_STAT).append(DELIVERY_ACK_STATE_UNDELIVERABLE).append(DELIVERY_ACK_ERR)
.append("001").append(DELIVERY_ACK_TEXT)
.append(this.getFirst20CharOfSMS(original.getShortMessage()));
byte[] textBytes = CharsetUtil.encode(sb.toString(), CharsetUtil.CHARSET_GSM);
deliveryReport.setShortMessage(textBytes);
deliveryReport.setEsmClass(ESME_DELIVERY_ACK);
NullActivity nullActivity = this.sbbContext.getNullActivityFactory().createNullActivity();
ActivityContextInterface nullActivityContextInterface = this.sbbContext
.getNullActivityContextInterfaceFactory().getActivityContextInterface(nullActivity);
this.fireSendDeliveryReportSms(deliveryReport, nullActivityContextInterface, null);
}
}
protected void sendSuccessDeliverSmToEsms(SmsEvent original) {
// TODO check if SmppSession available for this SystemId, if not send to
// SnF module
byte registeredDelivery = original.getRegisteredDelivery();
// Send Delivery Receipt only if requested
if (SmppUtil.isSmscDeliveryReceiptRequested(registeredDelivery)) {
SmsEvent deliveryReport = new SmsEvent();
deliveryReport.setSourceAddr(original.getDestAddr());
deliveryReport.setSourceAddrNpi(original.getDestAddrNpi());
deliveryReport.setSourceAddrTon(original.getDestAddrTon());
deliveryReport.setDestAddr(original.getSourceAddr());
deliveryReport.setDestAddrNpi(original.getSourceAddrNpi());
deliveryReport.setDestAddrTon(original.getSourceAddrTon());
// Setting SystemId as null, so RxSmppServerSbb actually tries to
// find real SmppServerSession from Destination TON, NPI and address
// range
deliveryReport.setSystemId(null);
deliveryReport.setSubmitDate(original.getSubmitDate());
deliveryReport.setMessageId(original.getMessageId());
StringBuffer sb = new StringBuffer();
sb.append(DELIVERY_ACK_ID).append(original.getMessageId()).append(DELIVERY_ACK_SUB).append("001")
.append(DELIVERY_ACK_DLVRD).append("001").append(DELIVERY_ACK_SUBMIT_DATE)
.append(DELIVERY_ACK_DATE_FORMAT.format(original.getSubmitDate())).append(DELIVERY_ACK_DONE_DATE)
.append(DELIVERY_ACK_DATE_FORMAT.format(new Timestamp(System.currentTimeMillis())))
.append(DELIVERY_ACK_STAT).append(DELIVERY_ACK_STATE_DELIVERED).append(DELIVERY_ACK_ERR)
.append("000").append(DELIVERY_ACK_TEXT)
.append(this.getFirst20CharOfSMS(original.getShortMessage()));
byte[] textBytes = CharsetUtil.encode(sb.toString(), CharsetUtil.CHARSET_GSM);
deliveryReport.setShortMessage(textBytes);
deliveryReport.setEsmClass(ESME_DELIVERY_ACK);
NullActivity nullActivity = this.sbbContext.getNullActivityFactory().createNullActivity();
ActivityContextInterface nullActivityContextInterface = this.sbbContext
.getNullActivityContextInterfaceFactory().getActivityContextInterface(nullActivity);
this.fireSendDeliveryReportSms(deliveryReport, nullActivityContextInterface, null);
}
}
private String getFirst20CharOfSMS(byte[] rawSms) {
String first20CharOfSms = new String(rawSms);
if (first20CharOfSms.length() > 20) {
first20CharOfSms = first20CharOfSms.substring(0, 20);
}
return first20CharOfSms;
}
}
| Java |
package org.mobicents.smsc.slee.services.mo;
import javax.slee.SbbLocalObject;
public interface MoSbbLocalObject extends SbbLocalObject {
}
| Java |
package org.mobicents.smsc.slee.services.mo;
import java.sql.Timestamp;
import javax.slee.ActivityContextInterface;
import javax.slee.InitialEventSelector;
import javax.slee.facilities.ActivityContextNamingFacility;
import javax.slee.facilities.NameAlreadyBoundException;
import javax.slee.nullactivity.NullActivity;
import org.mobicents.protocols.ss7.map.api.MAPApplicationContextName;
import org.mobicents.protocols.ss7.map.api.MAPException;
import org.mobicents.protocols.ss7.map.api.primitives.AddressString;
import org.mobicents.protocols.ss7.map.api.service.sms.ForwardShortMessageRequest;
import org.mobicents.protocols.ss7.map.api.service.sms.ForwardShortMessageResponse;
import org.mobicents.protocols.ss7.map.api.service.sms.MAPDialogSms;
import org.mobicents.protocols.ss7.map.api.service.sms.MoForwardShortMessageRequest;
import org.mobicents.protocols.ss7.map.api.service.sms.MoForwardShortMessageResponse;
import org.mobicents.protocols.ss7.map.api.service.sms.SM_RP_OA;
import org.mobicents.protocols.ss7.map.api.service.sms.SmsSignalInfo;
import org.mobicents.protocols.ss7.map.api.smstpdu.AddressField;
import org.mobicents.protocols.ss7.map.api.smstpdu.SmsDeliverTpdu;
import org.mobicents.protocols.ss7.map.api.smstpdu.SmsSubmitTpdu;
import org.mobicents.protocols.ss7.map.api.smstpdu.SmsTpdu;
import org.mobicents.protocols.ss7.map.api.smstpdu.UserData;
import org.mobicents.slee.resource.map.events.DialogRequest;
import org.mobicents.smsc.slee.resources.smpp.server.SmppServerSession;
import org.mobicents.smsc.slee.services.smpp.server.events.SmsEvent;
import com.cloudhopper.smpp.SmppConstants;
public abstract class MoSbb extends MoCommonSbb {
private static final String className = "MoSbb";
public MoSbb() {
super(className);
}
/**
* SMS Event Handlers
*/
/**
* Received incoming SMS for ACN v3. Send back ack
*
* @param evt
* @param aci
*/
public void onMoForwardShortMessageRequest(MoForwardShortMessageRequest evt, ActivityContextInterface aci) {
if (this.logger.isInfoEnabled()) {
this.logger.info("Received MO_FORWARD_SHORT_MESSAGE_REQUEST = " + evt);
}
SmsSignalInfo smsSignalInfo = evt.getSM_RP_UI();
SM_RP_OA smRPOA = evt.getSM_RP_OA();
AddressString callingPartyAddress = smRPOA.getMsisdn();
if (callingPartyAddress == null) {
callingPartyAddress = smRPOA.getServiceCentreAddressOA();
}
SmsTpdu smsTpdu = null;
try {
smsTpdu = smsSignalInfo.decodeTpdu(true);
switch (smsTpdu.getSmsTpduType()) {
case SMS_SUBMIT:
SmsSubmitTpdu smsSubmitTpdu = (SmsSubmitTpdu) smsTpdu;
if (this.logger.isInfoEnabled()) {
this.logger.info("Received SMS_SUBMIT = " + smsSubmitTpdu);
}
this.handleSmsSubmitTpdu(smsSubmitTpdu, callingPartyAddress);
break;
case SMS_DELIVER:
SmsDeliverTpdu smsDeliverTpdu = (SmsDeliverTpdu) smsTpdu;
this.logger.severe("Received SMS_DELIVER = " + smsDeliverTpdu);
break;
default:
this.logger.severe("Received non SMS_SUBMIT or SMS_DELIVER = " + smsTpdu);
break;
}
} catch (MAPException e1) {
logger.severe("Error while decoding SmsSignalInfo ", e1);
}
MAPDialogSms dialog = evt.getMAPDialog();
try {
dialog.addMoForwardShortMessageResponse(evt.getInvokeId(), null, null);
dialog.close(false);
} catch (MAPException e) {
logger.severe("Error while sending ForwardShortMessageResponse ", e);
}
}
/**
* Received Ack for MO SMS. But this is error we should never receive this
*
* @param evt
* @param aci
*/
public void onMoForwardShortMessageResponse(MoForwardShortMessageResponse evt, ActivityContextInterface aci) {
this.logger.severe("Received MO_FORWARD_SHORT_MESSAGE_RESPONSE = " + evt);
}
public void onForwardShortMessageRequest(ForwardShortMessageRequest evt, ActivityContextInterface aci) {
if (this.logger.isInfoEnabled()) {
this.logger.info("Received FORWARD_SHORT_MESSAGE_REQUEST = " + evt);
}
}
/**
* Received Ack for MO SMS. But this is error we should never receive this
*
* @param evt
* @param aci
*/
public void onForwardShortMessageResponse(ForwardShortMessageResponse evt, ActivityContextInterface aci) {
this.logger.severe("Received FORWARD_SHORT_MESSAGE_RESPONSE = " + evt);
}
/**
* Initial event selector method to check if the Event should initalize the
*/
public InitialEventSelector initialEventSelect(InitialEventSelector ies) {
Object event = ies.getEvent();
DialogRequest dialogRequest = null;
if (event instanceof DialogRequest) {
dialogRequest = (DialogRequest) event;
if (MAPApplicationContextName.shortMsgMORelayContext == dialogRequest.getMAPDialog()
.getApplicationContext().getApplicationContextName()) {
ies.setInitialEvent(true);
ies.setActivityContextSelected(true);
} else {
ies.setInitialEvent(false);
}
}
return ies;
}
/**
* Fire the SUBMIT_SM event to be consumed by MtSbb to send it to Mobile
*
* @param event
* @param aci
* @param address
*/
public abstract void fireSubmitSm(SmsEvent event, ActivityContextInterface aci, javax.slee.Address address);
/**
* Fire DELIVER_SM event to be consumed by RxSmppServerSbb to send it to
* ESME
*
* @param event
* @param aci
* @param address
*/
public abstract void fireDeliverSm(SmsEvent event, ActivityContextInterface aci, javax.slee.Address address);
/**
* Private Methods
*
* @throws MAPException
*/
private void handleSmsSubmitTpdu(SmsSubmitTpdu smsSubmitTpdu, AddressString callingPartyAddress)
throws MAPException {
AddressField destinationAddress = smsSubmitTpdu.getDestinationAddress();
UserData userData = smsSubmitTpdu.getUserData();
// TODO : Is decoding correct? May be we should send the raw data
// userData.decode();
// String decodedMessage = userData.getDecodedMessage();
//
// if (this.logger.isInfoEnabled()) {
// this.logger.info("decodedMessage SMS_SUBMIT = " + decodedMessage);
// }
SmsEvent rxSMS = new SmsEvent();
rxSMS.setSourceAddr(callingPartyAddress.getAddress());
rxSMS.setSourceAddrNpi((byte) callingPartyAddress.getNumberingPlan().getIndicator());
rxSMS.setSourceAddrTon((byte) callingPartyAddress.getAddressNature().getIndicator());
rxSMS.setDestAddr(destinationAddress.getAddressValue());
rxSMS.setDestAddrNpi((byte) destinationAddress.getNumberingPlanIdentification().getCode());
rxSMS.setSourceAddrTon((byte) destinationAddress.getTypeOfNumber().getCode());
//
// deliveryReport.setSystemId(original.getSystemId());
//
rxSMS.setSubmitDate(new Timestamp(System.currentTimeMillis()));
rxSMS.setShortMessage(userData.getEncodedData());
if (smsSubmitTpdu.getStatusReportRequest()) {
rxSMS.setRegisteredDelivery(SmppConstants.REGISTERED_DELIVERY_SMSC_RECEIPT_REQUESTED);
}
// How do we set Esm Class?
// rxSMS.setEsmClass(ESME_DELIVERY_ACK);
rxSMS.setDataCoding((byte) userData.getDataCodingScheme().getCode());
// TODO More parameters
SmppServerSession smppSession = smppServerSessions.getSmppSession(rxSMS.getDestAddrTon(),
rxSMS.getDestAddrNpi(), rxSMS.getDestAddr());
if (smppSession == null) {
if (this.logger.isInfoEnabled()) {
this.logger.info(String.format("No SmppServerSession for MoSMS=%s Will send to to Mt module", rxSMS));
}
this.processSubmitSM(rxSMS);
} else if (!smppSession.isBound()) {
this.logger.severe(String.format("Received MoSMS=%s but SmppSession=%s is not BOUND", rxSMS,
smppSession.getSystemId()));
// TODO : Add to SnF module
} else {
rxSMS.setSystemId(smppSession.getSystemId());
NullActivity nullActivity = this.sbbContext.getNullActivityFactory().createNullActivity();
ActivityContextInterface nullActivityContextInterface = this.sbbContext
.getNullActivityContextInterfaceFactory().getActivityContextInterface(nullActivity);
this.fireDeliverSm(rxSMS, nullActivityContextInterface, null);
}
}
private void processSubmitSM(SmsEvent event) {
String destAddr = event.getDestAddr();
ActivityContextNamingFacility activityContextNamingFacility = this.sbbContext
.getActivityContextNamingFacility();
ActivityContextInterface nullActivityContextInterface = null;
try {
nullActivityContextInterface = activityContextNamingFacility.lookup(destAddr);
} catch (Exception e) {
logger.severe(String.format(
"Exception while lookup NullActivityContextInterface for jndi name=%s for SmsEvent=%s", destAddr,
event), e);
}
NullActivity nullActivity = null;
if (nullActivityContextInterface == null) {
// If null means there are no SMS handled by Mt for this destination
// address. Lets create new NullActivity and bind it to
// naming-facility
if (this.logger.isInfoEnabled()) {
this.logger.info(String
.format("lookup of NullActivityContextInterface returned null, create new NullActivity"));
}
nullActivity = this.sbbContext.getNullActivityFactory().createNullActivity();
nullActivityContextInterface = this.sbbContext.getNullActivityContextInterfaceFactory()
.getActivityContextInterface(nullActivity);
try {
activityContextNamingFacility.bind(nullActivityContextInterface, destAddr);
} catch (NameAlreadyBoundException e) {
// Kill existing nullActivity
nullActivity.endActivity();
// If name already bound, we do lookup again because this is one
// of the race conditions
try {
nullActivityContextInterface = activityContextNamingFacility.lookup(destAddr);
} catch (Exception ex) {
logger.severe(
String.format(
"Exception while second lookup NullActivityContextInterface for jndi name=%s for SmsEvent=%s",
destAddr, event), ex);
// TODO take care of error conditions.
return;
}
} catch (Exception e) {
logger.severe(String.format(
"Exception while binding NullActivityContextInterface to jndi name=%s for SmsEvent=%s",
destAddr, event), e);
if (nullActivity != null) {
nullActivity.endActivity();
}
// TODO take care of error conditions.
return;
}
}// if (nullActivityContextInterface == null)
MoActivityContextInterface txSmppServerSbbActivityContextInterface = this
.asSbbActivityContextInterface(nullActivityContextInterface);
int pendingEventsOnNullActivity = txSmppServerSbbActivityContextInterface.getPendingEventsOnNullActivity();
pendingEventsOnNullActivity = pendingEventsOnNullActivity + 1;
if (this.logger.isInfoEnabled()) {
this.logger.info(String.format("pendingEventsOnNullActivity = %d", pendingEventsOnNullActivity));
}
txSmppServerSbbActivityContextInterface.setPendingEventsOnNullActivity(pendingEventsOnNullActivity);
// We have NullActivityContextInterface, lets fire SmsEvent on this
this.fireSubmitSm(event, nullActivityContextInterface, null);
}
}
| Java |
package org.mobicents.smsc.slee.services.mo;
import javax.slee.ActivityContextInterface;
public interface MoActivityContextInterface extends ActivityContextInterface {
public int getPendingEventsOnNullActivity();
public void setPendingEventsOnNullActivity(int events);
}
| Java |
package org.mobicents.smsc.slee.services.mo;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.slee.ActivityContextInterface;
import javax.slee.CreateException;
import javax.slee.RolledBackContext;
import javax.slee.Sbb;
import javax.slee.SbbContext;
import javax.slee.facilities.Tracer;
import org.mobicents.protocols.ss7.map.api.MAPParameterFactory;
import org.mobicents.protocols.ss7.map.api.MAPProvider;
import org.mobicents.slee.SbbContextExt;
import org.mobicents.slee.resource.map.MAPContextInterfaceFactory;
import org.mobicents.slee.resource.map.events.DialogAccept;
import org.mobicents.slee.resource.map.events.DialogClose;
import org.mobicents.slee.resource.map.events.DialogDelimiter;
import org.mobicents.slee.resource.map.events.DialogNotice;
import org.mobicents.slee.resource.map.events.DialogProviderAbort;
import org.mobicents.slee.resource.map.events.DialogReject;
import org.mobicents.slee.resource.map.events.DialogRelease;
import org.mobicents.slee.resource.map.events.DialogRequest;
import org.mobicents.slee.resource.map.events.DialogTimeout;
import org.mobicents.slee.resource.map.events.DialogUserAbort;
import org.mobicents.slee.resource.map.events.ErrorComponent;
import org.mobicents.slee.resource.map.events.InvokeTimeout;
import org.mobicents.slee.resource.map.events.RejectComponent;
import org.mobicents.smsc.slee.resources.smpp.server.SmppServerSessions;
public abstract class MoCommonSbb implements Sbb {
private final String className;
protected Tracer logger;
protected SbbContextExt sbbContext;
protected MAPContextInterfaceFactory mapAcif;
protected MAPProvider mapProvider;
protected MAPParameterFactory mapParameterFactory;
protected SmppServerSessions smppServerSessions = null;
public MoCommonSbb(String className) {
this.className = className;
}
/**
* MAP Components Events
*/
public void onInvokeTimeout(InvokeTimeout evt, ActivityContextInterface aci) {
if (logger.isInfoEnabled()) {
this.logger.info("Rx : onInvokeTimeout" + evt);
}
}
public void onErrorComponent(ErrorComponent event, ActivityContextInterface aci) {
if (this.logger.isInfoEnabled()) {
this.logger.info("Rx : onErrorComponent " + event + " Dialog=" + event.getMAPDialog());
}
}
// public void onProviderErrorComponent(ProviderErrorComponent event, ActivityContextInterface aci) {
// this.logger.severe("Rx : onProviderErrorComponent" + event);
// }
public void onRejectComponent(RejectComponent event, ActivityContextInterface aci) {
this.logger.severe("Rx : onRejectComponent" + event);
}
/**
* Dialog Events
*/
public void onDialogDelimiter(DialogDelimiter evt, ActivityContextInterface aci) {
if (logger.isFineEnabled()) {
this.logger.fine("Rx : onDialogDelimiter=" + evt);
}
}
public void onDialogAccept(DialogAccept evt, ActivityContextInterface aci) {
if (logger.isFineEnabled()) {
this.logger.fine("Rx : onDialogAccept=" + evt);
}
}
public void onDialogReject(DialogReject evt, ActivityContextInterface aci) {
if (logger.isWarningEnabled()) {
this.logger.warning("Rx : onDialogReject=" + evt);
}
// TODO : Error condition. Take care
}
public void onDialogUserAbort(DialogUserAbort evt, ActivityContextInterface aci) {
this.logger.severe("Rx : onDialogUserAbort=" + evt);
// TODO : Error condition. Take care
}
public void onDialogProviderAbort(DialogProviderAbort evt, ActivityContextInterface aci) {
this.logger.severe("Rx : onDialogProviderAbort=" + evt);
}
public void onDialogClose(DialogClose evt, ActivityContextInterface aci) {
if (logger.isFineEnabled()) {
this.logger.fine("Rx : onDialogClose" + evt);
}
}
public void onDialogNotice(DialogNotice evt, ActivityContextInterface aci) {
if (logger.isInfoEnabled()) {
this.logger.info("Rx : onDialogNotice" + evt);
}
}
public void onDialogTimeout(DialogTimeout evt, ActivityContextInterface aci) {
this.logger.severe("Rx : onDialogTimeout" + evt);
}
public void onDialogRequest(DialogRequest evt, ActivityContextInterface aci) {
if (logger.isFineEnabled()) {
this.logger.fine("Rx : onDialogRequest" + evt);
}
}
public void onDialogRelease(DialogRelease evt, ActivityContextInterface aci) {
if (logger.isInfoEnabled()) {
// TODO : Should be fine
this.logger.info("Rx : DialogRelease" + evt);
}
}
/**
* Life cycle methods
*/
@Override
public void sbbActivate() {
// TODO Auto-generated method stub
}
@Override
public void sbbCreate() throws CreateException {
// TODO Auto-generated method stub
}
@Override
public void sbbExceptionThrown(Exception arg0, Object arg1, ActivityContextInterface arg2) {
// TODO Auto-generated method stub
}
@Override
public void sbbLoad() {
// TODO Auto-generated method stub
}
@Override
public void sbbPassivate() {
// TODO Auto-generated method stub
}
@Override
public void sbbPostCreate() throws CreateException {
// TODO Auto-generated method stub
}
@Override
public void sbbRemove() {
// TODO Auto-generated method stub
}
@Override
public void sbbRolledBack(RolledBackContext arg0) {
// TODO Auto-generated method stub
}
@Override
public void sbbStore() {
// TODO Auto-generated method stub
}
@Override
public void setSbbContext(SbbContext sbbContext) {
this.sbbContext = (SbbContextExt) sbbContext;
try {
Context ctx = (Context) new InitialContext().lookup("java:comp/env");
this.mapAcif = (MAPContextInterfaceFactory) ctx.lookup("slee/resources/map/2.0/acifactory");
this.mapProvider = (MAPProvider) ctx.lookup("slee/resources/map/2.0/provider");
this.mapParameterFactory = this.mapProvider.getMAPParameterFactory();
this.smppServerSessions = (SmppServerSessions) ctx.lookup("slee/resources/smpp/server/1.0/provider");
this.logger = this.sbbContext.getTracer(this.className);
} catch (Exception ne) {
logger.severe("Could not set SBB context:", ne);
}
// TODO : Handle proper error
}
@Override
public void unsetSbbContext() {
}
/**
* Sbb ACI
*/
public abstract MoActivityContextInterface asSbbActivityContextInterface(ActivityContextInterface aci);
}
| Java |
package org.mobicents.smsc.slee.services.alert;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.slee.ActivityContextInterface;
import javax.slee.CreateException;
import javax.slee.InitialEventSelector;
import javax.slee.RolledBackContext;
import javax.slee.Sbb;
import javax.slee.SbbContext;
import javax.slee.facilities.Tracer;
import org.mobicents.protocols.ss7.map.api.MAPApplicationContext;
import org.mobicents.protocols.ss7.map.api.MAPApplicationContextName;
import org.mobicents.protocols.ss7.map.api.MAPException;
import org.mobicents.protocols.ss7.map.api.MAPParameterFactory;
import org.mobicents.protocols.ss7.map.api.MAPProvider;
import org.mobicents.protocols.ss7.map.api.service.sms.AlertServiceCentreRequest;
import org.mobicents.protocols.ss7.map.api.service.sms.MAPDialogSms;
import org.mobicents.slee.SbbContextExt;
import org.mobicents.slee.resource.map.MAPContextInterfaceFactory;
import org.mobicents.slee.resource.map.events.DialogAccept;
import org.mobicents.slee.resource.map.events.DialogClose;
import org.mobicents.slee.resource.map.events.DialogDelimiter;
import org.mobicents.slee.resource.map.events.DialogNotice;
import org.mobicents.slee.resource.map.events.DialogProviderAbort;
import org.mobicents.slee.resource.map.events.DialogReject;
import org.mobicents.slee.resource.map.events.DialogRelease;
import org.mobicents.slee.resource.map.events.DialogRequest;
import org.mobicents.slee.resource.map.events.DialogTimeout;
import org.mobicents.slee.resource.map.events.DialogUserAbort;
import org.mobicents.slee.resource.map.events.ErrorComponent;
import org.mobicents.slee.resource.map.events.InvokeTimeout;
import org.mobicents.slee.resource.map.events.RejectComponent;
public abstract class AlertSbb implements Sbb {
protected Tracer logger;
protected SbbContextExt sbbContext;
protected MAPContextInterfaceFactory mapAcif;
protected MAPProvider mapProvider;
protected MAPParameterFactory mapParameterFactory;
private MAPApplicationContext shortMsgAlertContext = null;
public AlertSbb() {
}
/**
* MAP Components Events
*/
public void onInvokeTimeout(InvokeTimeout evt, ActivityContextInterface aci) {
if (logger.isInfoEnabled()) {
this.logger.info("Rx : onInvokeTimeout" + evt);
}
}
public void onErrorComponent(ErrorComponent event, ActivityContextInterface aci) {
if (this.logger.isInfoEnabled()) {
this.logger.info("Rx : onErrorComponent " + event + " Dialog=" + event.getMAPDialog());
}
}
// public void onProviderErrorComponent(ProviderErrorComponent event, ActivityContextInterface aci) {
// this.logger.severe("Rx : onProviderErrorComponent" + event);
// }
public void onRejectComponent(RejectComponent event, ActivityContextInterface aci) {
this.logger.severe("Rx : onRejectComponent" + event);
}
/**
* Dialog Events
*/
public void onDialogDelimiter(DialogDelimiter evt, ActivityContextInterface aci) {
if (logger.isFineEnabled()) {
this.logger.fine("Rx : onDialogDelimiter=" + evt);
}
}
public void onDialogAccept(DialogAccept evt, ActivityContextInterface aci) {
if (logger.isFineEnabled()) {
this.logger.fine("Rx : onDialogAccept=" + evt);
}
}
public void onDialogReject(DialogReject evt, ActivityContextInterface aci) {
if (logger.isWarningEnabled()) {
this.logger.warning("Rx : onDialogReject=" + evt);
}
}
public void onDialogUserAbort(DialogUserAbort evt, ActivityContextInterface aci) {
this.logger.severe("Rx : onDialogUserAbort=" + evt);
}
public void onDialogProviderAbort(DialogProviderAbort evt, ActivityContextInterface aci) {
this.logger.severe("Rx : onDialogProviderAbort=" + evt);
}
public void onDialogClose(DialogClose evt, ActivityContextInterface aci) {
if (logger.isFineEnabled()) {
this.logger.fine("Rx : onDialogClose" + evt);
}
}
public void onDialogNotice(DialogNotice evt, ActivityContextInterface aci) {
if (logger.isInfoEnabled()) {
this.logger.info("Rx : onDialogNotice" + evt);
}
}
public void onDialogTimeout(DialogTimeout evt, ActivityContextInterface aci) {
this.logger.severe("Rx : onDialogTimeout" + evt);
}
public void onDialogRequest(DialogRequest evt, ActivityContextInterface aci) {
if (logger.isFineEnabled()) {
this.logger.fine("Rx : onDialogRequest" + evt);
}
}
public void onDialogRelease(DialogRelease evt, ActivityContextInterface aci) {
if (logger.isInfoEnabled()) {
// TODO : Should be fine
this.logger.info("Rx : DialogRelease" + evt);
}
}
public void onAlertServiceCentreRequest(AlertServiceCentreRequest evt, ActivityContextInterface aci) {
try {
MAPDialogSms mapDialogSms = evt.getMAPDialog();
mapDialogSms.addAlertServiceCentreResponse(evt.getInvokeId());
mapDialogSms.close(false);
} catch (MAPException e) {
logger.severe("Exception while trying to send back AlertServiceCentreResponse", e);
}
}
/**
* Life cycle
*/
@Override
public void sbbActivate() {
// TODO Auto-generated method stub
}
@Override
public void sbbCreate() throws CreateException {
// TODO Auto-generated method stub
}
@Override
public void sbbExceptionThrown(Exception arg0, Object arg1, ActivityContextInterface arg2) {
// TODO Auto-generated method stub
}
@Override
public void sbbLoad() {
// TODO Auto-generated method stub
}
@Override
public void sbbPassivate() {
// TODO Auto-generated method stub
}
@Override
public void sbbPostCreate() throws CreateException {
// TODO Auto-generated method stub
}
@Override
public void sbbRemove() {
// TODO Auto-generated method stub
}
@Override
public void sbbRolledBack(RolledBackContext arg0) {
// TODO Auto-generated method stub
}
@Override
public void sbbStore() {
// TODO Auto-generated method stub
}
@Override
public void setSbbContext(SbbContext sbbContext) {
this.sbbContext = (SbbContextExt) sbbContext;
try {
Context ctx = (Context) new InitialContext().lookup("java:comp/env");
this.mapAcif = (MAPContextInterfaceFactory) ctx.lookup("slee/resources/map/2.0/acifactory");
this.mapProvider = (MAPProvider) ctx.lookup("slee/resources/map/2.0/provider");
this.mapParameterFactory = this.mapProvider.getMAPParameterFactory();
this.logger = this.sbbContext.getTracer(AlertSbb.class.getSimpleName());
} catch (Exception ne) {
logger.severe("Could not set SBB context:", ne);
}
}
@Override
public void unsetSbbContext() {
// TODO Auto-generated method stub
}
/**
* Initial event selector method to check if the Event should initalize the
*/
public InitialEventSelector initialEventSelect(InitialEventSelector ies) {
Object event = ies.getEvent();
DialogRequest dialogRequest = null;
if (event instanceof DialogRequest) {
dialogRequest = (DialogRequest) event;
if (MAPApplicationContextName.shortMsgAlertContext == dialogRequest.getMAPDialog().getApplicationContext()
.getApplicationContextName()) {
ies.setInitialEvent(true);
ies.setActivityContextSelected(true);
} else {
ies.setInitialEvent(false);
}
}
return ies;
}
}
| Java |
package org.mobicents.smsc.slee.services.smpp.server.rx;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.slee.ActivityContextInterface;
import javax.slee.CreateException;
import javax.slee.EventContext;
import javax.slee.RolledBackContext;
import javax.slee.Sbb;
import javax.slee.SbbContext;
import javax.slee.facilities.Tracer;
import javax.slee.nullactivity.NullActivity;
import org.mobicents.slee.SbbContextExt;
import org.mobicents.smsc.slee.resources.smpp.server.SmppServerSession;
import org.mobicents.smsc.slee.resources.smpp.server.SmppServerSessions;
import org.mobicents.smsc.slee.resources.smpp.server.SmppServerTransaction;
import org.mobicents.smsc.slee.resources.smpp.server.SmppServerTransactionACIFactory;
import org.mobicents.smsc.slee.resources.smpp.server.events.PduRequestTimeout;
import org.mobicents.smsc.slee.services.smpp.server.events.SmsEvent;
import com.cloudhopper.smpp.pdu.DeliverSm;
import com.cloudhopper.smpp.pdu.DeliverSmResp;
import com.cloudhopper.smpp.type.Address;
import com.cloudhopper.smpp.type.RecoverablePduException;
public abstract class RxSmppServerSbb implements Sbb {
private Tracer logger;
private SbbContextExt sbbContext;
private SmppServerTransactionACIFactory smppServerTransactionACIFactory = null;
private SmppServerSessions smppServerSessions = null;
public RxSmppServerSbb() {
// TODO Auto-generated constructor stub
}
public void onDeliverSm(SmsEvent event, ActivityContextInterface aci, EventContext eventContext) {
try {
String systemId = event.getSystemId();
SmppServerSession smppServerSession = null;
if (systemId == null) {
//Try to find SmppServerSession from dest TON, NPI and Range
smppServerSession = smppServerSessions.getSmppSession(event.getDestAddrTon(), event.getDestAddrNpi(),
event.getDestAddr());
} else {
smppServerSession = smppServerSessions.getSmppSession(systemId);
}
if (smppServerSession == null) {
this.logger.severe(String.format("Received DELIVER_SM SmsEvent=%s but no SmppServerSession found",
event));
return;
}
if (!smppServerSession.isBound()) {
this.logger.severe(String.format(
"Received DELIVER_SM SmsEvent=%s but SmppServerSession=%s is not BOUND", event,
smppServerSession.getSystemId()));
// TODO : Add to SnF module
return;
}
DeliverSm deliverSm = new DeliverSm();
deliverSm.setSourceAddress(new Address(event.getSourceAddrTon(), event.getSourceAddrNpi(), event
.getSourceAddr()));
deliverSm.setDestAddress(new Address(event.getDestAddrTon(), event.getDestAddrNpi(), event.getDestAddr()));
deliverSm.setEsmClass(event.getEsmClass());
deliverSm.setShortMessage(event.getShortMessage());
// TODO : waiting for 2 secs for window to accept our request, is it
// good? Should time be more here?
SmppServerTransaction smppServerTransaction = smppServerSession.sendRequestPdu(deliverSm, 2000);
ActivityContextInterface smppTxaci = this.smppServerTransactionACIFactory
.getActivityContextInterface(smppServerTransaction);
smppTxaci.attach(this.sbbContext.getSbbLocalObject());
} catch (Exception e) {
logger.severe(
String.format("Exception while trying to send DELIVERY Report for received SmsEvent=%s", event), e);
} finally {
NullActivity nullActivity = (NullActivity) aci.getActivity();
nullActivity.endActivity();
}
}
public void onDeliverSmResp(DeliverSmResp event, ActivityContextInterface aci, EventContext eventContext) {
if (logger.isInfoEnabled()) {
logger.info(String.format("onDeliverSmResp : DeliverSmResp=%s", event));
}
// TODO : Handle this
}
public void onPduRequestTimeout(PduRequestTimeout event, ActivityContextInterface aci, EventContext eventContext) {
logger.severe(String.format("onPduRequestTimeout : PduRequestTimeout=%s", event));
// TODO : Handle this
}
public void onRecoverablePduException(RecoverablePduException event, ActivityContextInterface aci,
EventContext eventContext) {
logger.severe(String.format("onRecoverablePduException : RecoverablePduException=%s", event));
// TODO : Handle this
}
@Override
public void sbbActivate() {
// TODO Auto-generated method stub
}
@Override
public void sbbCreate() throws CreateException {
// TODO Auto-generated method stub
}
@Override
public void sbbExceptionThrown(Exception arg0, Object arg1, ActivityContextInterface arg2) {
// TODO Auto-generated method stub
}
@Override
public void sbbLoad() {
// TODO Auto-generated method stub
}
@Override
public void sbbPassivate() {
// TODO Auto-generated method stub
}
@Override
public void sbbPostCreate() throws CreateException {
// TODO Auto-generated method stub
}
@Override
public void sbbRemove() {
// TODO Auto-generated method stub
}
@Override
public void sbbRolledBack(RolledBackContext arg0) {
// TODO Auto-generated method stub
}
@Override
public void sbbStore() {
// TODO Auto-generated method stub
}
@Override
public void setSbbContext(SbbContext sbbContext) {
this.sbbContext = (SbbContextExt) sbbContext;
try {
Context ctx = (Context) new InitialContext().lookup("java:comp/env");
this.smppServerTransactionACIFactory = (SmppServerTransactionACIFactory) ctx
.lookup("slee/resources/smppp/server/1.0/acifactory");
this.smppServerSessions = (SmppServerSessions) ctx.lookup("slee/resources/smpp/server/1.0/provider");
this.logger = this.sbbContext.getTracer(getClass().getSimpleName());
} catch (Exception ne) {
logger.severe("Could not set SBB context:", ne);
}
}
@Override
public void unsetSbbContext() {
// TODO Auto-generated method stub
}
}
| Java |
package org.mobicents.smsc.slee.services.smpp.server.tx;
import java.sql.Timestamp;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.slee.ActivityContextInterface;
import javax.slee.CreateException;
import javax.slee.EventContext;
import javax.slee.RolledBackContext;
import javax.slee.Sbb;
import javax.slee.SbbContext;
import javax.slee.facilities.ActivityContextNamingFacility;
import javax.slee.facilities.NameAlreadyBoundException;
import javax.slee.facilities.Tracer;
import javax.slee.nullactivity.NullActivity;
import org.mobicents.slee.SbbContextExt;
import org.mobicents.smsc.slee.resources.smpp.server.SmppServerSession;
import org.mobicents.smsc.slee.resources.smpp.server.SmppServerSessions;
import org.mobicents.smsc.slee.resources.smpp.server.SmppServerTransaction;
import org.mobicents.smsc.slee.resources.smpp.server.SmppServerTransactionACIFactory;
import org.mobicents.smsc.slee.resources.smpp.server.events.PduRequestTimeout;
import org.mobicents.smsc.slee.services.smpp.server.events.SmsEvent;
import com.cloudhopper.smpp.pdu.DataSmResp;
import com.cloudhopper.smpp.pdu.SubmitSmResp;
import com.cloudhopper.smpp.type.RecoverablePduException;
public abstract class TxSmppServerSbb implements Sbb {
private Tracer logger;
private SbbContextExt sbbContext;
private SmppServerTransactionACIFactory smppServerTransactionACIFactory = null;
private SmppServerSessions smppServerSessions = null;
public TxSmppServerSbb() {
// TODO Auto-generated constructor stub
}
/**
* Event Handlers
*/
public void onSubmitSm(com.cloudhopper.smpp.pdu.SubmitSm event, ActivityContextInterface aci) {
SmppServerTransaction smppServerTransaction = (SmppServerTransaction) aci.getActivity();
SmppServerSession smppServerSession = smppServerTransaction.getSmppSession();
String systemId = smppServerSession.getSystemId();
if (this.logger.isInfoEnabled()) {
this.logger.info("Received SUBMIT_SM = " + event + " from SystemId=" + systemId);
}
String messageId = this.smppServerSessions.getNextMessageId();
SmsEvent smsEvent = new SmsEvent();
smsEvent.setSubmitDate(new Timestamp(System.currentTimeMillis()));
smsEvent.setMessageId(messageId);
smsEvent.setSystemId(systemId);
smsEvent.setSourceAddrTon(event.getSourceAddress().getTon());
smsEvent.setSourceAddrNpi(event.getSourceAddress().getNpi());
smsEvent.setSourceAddr(event.getSourceAddress().getAddress());
// TODO : Normalise Dest Address
smsEvent.setDestAddrTon(event.getDestAddress().getTon());
smsEvent.setDestAddrNpi(event.getDestAddress().getNpi());
smsEvent.setDestAddr(event.getDestAddress().getAddress());
smsEvent.setEsmClass(event.getEsmClass());
smsEvent.setProtocolId(event.getProtocolId());
smsEvent.setPriority(event.getPriority());
// TODO : respect schedule delivery
smsEvent.setScheduleDeliveryTime(event.getScheduleDeliveryTime());
// TODO : Check for validity period. If validity period null, set SMSC
// default validity period
smsEvent.setValidityPeriod(event.getValidityPeriod());
smsEvent.setRegisteredDelivery(event.getRegisteredDelivery());
// TODO : Respect replace if present
smsEvent.setReplaceIfPresent(event.getReplaceIfPresent());
smsEvent.setDataCoding(event.getDataCoding());
smsEvent.setDefaultMsgId(event.getDefaultMsgId());
smsEvent.setShortMessage(event.getShortMessage());
this.processSms(smsEvent);
// Lets send the Response here
SubmitSmResp response = event.createResponse();
response.setMessageId(messageId);
try {
smppServerSession.sendResponsePdu(event, response);
} catch (Exception e) {
this.logger.severe("Error while trying to send SubmitSmResponse=" + response, e);
}
}
public void onDataSm(com.cloudhopper.smpp.pdu.DataSm event, ActivityContextInterface aci) {
SmppServerTransaction smppServerTransaction = (SmppServerTransaction) aci.getActivity();
SmppServerSession smppServerSession = smppServerTransaction.getSmppSession();
String systemId = smppServerSession.getSystemId();
if (this.logger.isInfoEnabled()) {
this.logger.info("Received DATA_SM = " + event + " from SystemId=" + systemId);
}
DataSmResp response = event.createResponse();
// Lets send the Response here
try {
smppServerSession.sendResponsePdu(event, response);
} catch (Exception e) {
this.logger.severe("Error while trying to send DataSmResponse=" + response, e);
}
}
public void onPduRequestTimeout(PduRequestTimeout event, ActivityContextInterface aci, EventContext eventContext) {
logger.severe(String.format("onPduRequestTimeout : PduRequestTimeout=%s", event));
// TODO : Handle this
}
public void onRecoverablePduException(RecoverablePduException event, ActivityContextInterface aci,
EventContext eventContext) {
logger.severe(String.format("onRecoverablePduException : RecoverablePduException=%s", event));
// TODO : Handle this
}
public abstract void fireSms(SmsEvent event, ActivityContextInterface aci, javax.slee.Address address);
@Override
public void sbbActivate() {
// TODO Auto-generated method stub
}
@Override
public void sbbCreate() throws CreateException {
// TODO Auto-generated method stub
}
@Override
public void sbbExceptionThrown(Exception arg0, Object arg1, ActivityContextInterface arg2) {
// TODO Auto-generated method stub
}
@Override
public void sbbLoad() {
// TODO Auto-generated method stub
}
@Override
public void sbbPassivate() {
// TODO Auto-generated method stub
}
@Override
public void sbbPostCreate() throws CreateException {
// TODO Auto-generated method stub
}
@Override
public void sbbRemove() {
// TODO Auto-generated method stub
}
@Override
public void sbbRolledBack(RolledBackContext arg0) {
// TODO Auto-generated method stub
}
@Override
public void sbbStore() {
// TODO Auto-generated method stub
}
@Override
public void setSbbContext(SbbContext sbbContext) {
this.sbbContext = (SbbContextExt) sbbContext;
try {
Context ctx = (Context) new InitialContext().lookup("java:comp/env");
this.smppServerTransactionACIFactory = (SmppServerTransactionACIFactory) ctx
.lookup("slee/resources/smppp/server/1.0/acifactory");
this.smppServerSessions = (SmppServerSessions) ctx.lookup("slee/resources/smpp/server/1.0/provider");
this.logger = this.sbbContext.getTracer(getClass().getSimpleName());
} catch (Exception ne) {
logger.severe("Could not set SBB context:", ne);
}
}
@Override
public void unsetSbbContext() {
// TODO Auto-generated method stub
}
/**
* Sbb ACI
*/
public abstract TxSmppServerSbbActivityContextInterface asSbbActivityContextInterface(ActivityContextInterface aci);
/**
* Private
*/
public void processSms(SmsEvent event) {
String destAddr = event.getDestAddr();
ActivityContextNamingFacility activityContextNamingFacility = this.sbbContext
.getActivityContextNamingFacility();
ActivityContextInterface nullActivityContextInterface = null;
try {
nullActivityContextInterface = activityContextNamingFacility.lookup(destAddr);
} catch (Exception e) {
logger.severe(String.format(
"Exception while lookup NullActivityContextInterface for jndi name=%s for SmsEvent=%s", destAddr,
event), e);
}
NullActivity nullActivity = null;
if (nullActivityContextInterface == null) {
// If null means there are no SMS handled by Mt for this destination
// address. Lets create new NullActivity and bind it to
// naming-facility
if (this.logger.isInfoEnabled()) {
this.logger.info(String
.format("lookup of NullActivityContextInterface returned null, create new NullActivity"));
}
nullActivity = this.sbbContext.getNullActivityFactory().createNullActivity();
nullActivityContextInterface = this.sbbContext.getNullActivityContextInterfaceFactory()
.getActivityContextInterface(nullActivity);
try {
activityContextNamingFacility.bind(nullActivityContextInterface, destAddr);
} catch (NameAlreadyBoundException e) {
// Kill existing nullActivity
nullActivity.endActivity();
// If name already bound, we do lookup again because this is one
// of the race conditions
try {
nullActivityContextInterface = activityContextNamingFacility.lookup(destAddr);
} catch (Exception ex) {
logger.severe(
String.format(
"Exception while second lookup NullActivityContextInterface for jndi name=%s for SmsEvent=%s",
destAddr, event), ex);
// TODO take care of error conditions.
return;
}
} catch (Exception e) {
logger.severe(String.format(
"Exception while binding NullActivityContextInterface to jndi name=%s for SmsEvent=%s",
destAddr, event), e);
if (nullActivity != null) {
nullActivity.endActivity();
}
// TODO take care of error conditions.
return;
}
}// if (nullActivityContextInterface == null)
TxSmppServerSbbActivityContextInterface txSmppServerSbbActivityContextInterface = this
.asSbbActivityContextInterface(nullActivityContextInterface);
int pendingEventsOnNullActivity = txSmppServerSbbActivityContextInterface.getPendingEventsOnNullActivity();
pendingEventsOnNullActivity = pendingEventsOnNullActivity + 1;
if (this.logger.isInfoEnabled()) {
this.logger.info(String.format("pendingEventsOnNullActivity = %d", pendingEventsOnNullActivity));
}
txSmppServerSbbActivityContextInterface.setPendingEventsOnNullActivity(pendingEventsOnNullActivity);
// We have NullActivityContextInterface, lets fire SmsEvent on this
this.fireSms(event, nullActivityContextInterface, null);
}
}
| Java |
package org.mobicents.smsc.slee.services.smpp.server.tx;
import javax.slee.ActivityContextInterface;
public interface TxSmppServerSbbActivityContextInterface extends ActivityContextInterface {
public int getPendingEventsOnNullActivity();
public void setPendingEventsOnNullActivity(int events);
}
| Java |
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* 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.smsc.smpp;
import java.util.List;
import com.cloudhopper.smpp.SmppBindType;
import com.cloudhopper.smpp.type.Address;
public interface EsmeManagementMBean {
public List<Esme> getEsmes();
public Esme getEsme(String systemId);
public Esme createEsme(String systemId, String password, String host, String port, SmppBindType smppBindType,
String systemType, SmppInterfaceVersionType smppIntVersion, Address address) throws Exception;
public Esme destroyEsme(String systemId) throws Exception;
}
| Java |
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* 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.smsc.smpp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import javolution.text.TextBuilder;
import javolution.xml.XMLBinding;
import javolution.xml.XMLObjectReader;
import javolution.xml.XMLObjectWriter;
import javolution.xml.stream.XMLStreamException;
import org.apache.log4j.Logger;
public class SmscPropertiesManagement implements SmscPropertiesManagementMBean {
private static final Logger logger = Logger.getLogger(SmscPropertiesManagement.class);
private static final String SC_GT = "scgt";
private static final String SC_SSN = "scssn";
private static final String HLR_SSN = "hlrssn";
private static final String MSC_SSN = "mscssn";
private static final String MAX_MAP_VERSION = "maxmapv";
private static final String TAB_INDENT = "\t";
private static final String CLASS_ATTRIBUTE = "type";
private static final XMLBinding binding = new XMLBinding();
private static final String PERSIST_FILE_NAME = "smscproperties.xml";
private static SmscPropertiesManagement instance;
private final String name;
private String persistDir = null;
private final TextBuilder persistFile = TextBuilder.newInstance();
private String serviceCenterGt = null;
private int serviceCenterSsn = -1;
private int hlrSsn = -1;
private int mscSsn = -1;
private int maxMapVersion = 3;
private SmscPropertiesManagement(String name) {
this.name = name;
binding.setClassAttribute(CLASS_ATTRIBUTE);
}
protected static SmscPropertiesManagement getInstance(String name){
if(instance == null){
instance = new SmscPropertiesManagement(name);
}
return instance;
}
public static SmscPropertiesManagement getInstance(){
return instance;
}
public String getName() {
return name;
}
public String getPersistDir() {
return persistDir;
}
public void setPersistDir(String persistDir) {
this.persistDir = persistDir;
}
public String getServiceCenterGt() {
return serviceCenterGt;
}
public void setServiceCenterGt(String serviceCenterGt) {
this.serviceCenterGt = serviceCenterGt;
this.store();
}
public int getServiceCenterSsn() {
return serviceCenterSsn;
}
public void setServiceCenterSsn(int serviceCenterSsn) {
this.serviceCenterSsn = serviceCenterSsn;
this.store();
}
public int getHlrSsn() {
return hlrSsn;
}
public void setHlrSsn(int hlrSsn) {
this.hlrSsn = hlrSsn;
this.store();
}
public int getMscSsn() {
return mscSsn;
}
public void setMscSsn(int mscSsn) {
this.mscSsn = mscSsn;
this.store();
}
public int getMaxMapVersion() {
return maxMapVersion;
}
public void setMaxMapVersion(int maxMapVersion) {
this.maxMapVersion = maxMapVersion;
this.store();
}
public void start() throws Exception {
this.persistFile.clear();
if (persistDir != null) {
this.persistFile.append(persistDir).append(File.separator).append(this.name).append("_")
.append(PERSIST_FILE_NAME);
} else {
persistFile
.append(System.getProperty(SmscManagement.SMSC_PERSIST_DIR_KEY,
System.getProperty(SmscManagement.USER_DIR_KEY))).append(File.separator).append(this.name)
.append("_").append(PERSIST_FILE_NAME);
}
logger.info(String.format("Loading SMSC Properties from %s", persistFile.toString()));
try {
this.load();
} catch (FileNotFoundException e) {
logger.warn(String.format("Failed to load the SMSC configuration file. \n%s", e.getMessage()));
}
}
public void stop() throws Exception {
this.store();
}
/**
* Persist
*/
public void store() {
// TODO : Should we keep reference to Objects rather than recreating
// everytime?
try {
XMLObjectWriter writer = XMLObjectWriter.newInstance(new FileOutputStream(persistFile.toString()));
writer.setBinding(binding);
// Enables cross-references.
// writer.setReferenceResolver(new XMLReferenceResolver());
writer.setIndentation(TAB_INDENT);
writer.write(this.serviceCenterGt, SC_GT, String.class);
writer.write(this.serviceCenterSsn, SC_SSN, Integer.class);
writer.write(this.hlrSsn, HLR_SSN, Integer.class);
writer.write(this.mscSsn, MSC_SSN, Integer.class);
writer.write(this.maxMapVersion, MAX_MAP_VERSION, Integer.class);
writer.close();
} catch (Exception e) {
logger.error("Error while persisting the Rule state in file", e);
}
}
/**
* Load and create LinkSets and Link from persisted file
*
* @throws Exception
*/
public void load() throws FileNotFoundException {
XMLObjectReader reader = null;
try {
reader = XMLObjectReader.newInstance(new FileInputStream(persistFile.toString()));
reader.setBinding(binding);
this.serviceCenterGt = reader.read(SC_GT, String.class);
this.serviceCenterSsn = reader.read(SC_SSN, Integer.class);
this.hlrSsn = reader.read(HLR_SSN, Integer.class);
this.mscSsn = reader.read(MSC_SSN, Integer.class);
this.maxMapVersion = reader.read(MAX_MAP_VERSION, Integer.class);
reader.close();
} catch (XMLStreamException ex) {
// this.logger.info(
// "Error while re-creating Linksets from persisted file", ex);
}
}
}
| Java |
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* 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.smsc.smpp;
import java.util.Arrays;
import java.util.List;
import org.apache.log4j.Logger;
import org.mobicents.ss7.management.console.ShellExecutor;
import com.cloudhopper.smpp.SmppBindType;
import com.cloudhopper.smpp.type.Address;
/**
* @author amit bhayani
* @author zaheer abbas
*
*/
public class SMSCShellExecutor implements ShellExecutor {
private static final Logger logger = Logger.getLogger(SMSCShellExecutor.class);
private SmscManagement smscManagement;
private static final SmscPropertiesManagement smscPropertiesManagement = SmscPropertiesManagement.getInstance();
public SMSCShellExecutor() {
}
/**
* @return the m3uaManagement
*/
public SmscManagement getSmscManagement() {
return smscManagement;
}
/**
* @param m3uaManagement
* the m3uaManagement to set
*/
public void setSmscManagement(SmscManagement smscManagement) {
this.smscManagement = smscManagement;
}
/**
* smsc esme create <Any 4/5 digit number> <Specify password> <host-ip>
* <port> <TRANSCEIVER|TRANSMITTER|RECEIVER> system-type <sms | vms | ota >
* interface-version <3.3 | 3.4 | 5.0> esme-ton <esme address ton> esme-npi
* <esme address npi> esme-range <esme address range>
*
* @param args
* @return
*/
private String createEsme(String[] args) throws Exception {
if (args.length < 5 || args.length > 20) {
return SMSCOAMMessages.INVALID_COMMAND;
}
// Create new Rem ESME
String systemId = args[3];
if (systemId == null) {
return SMSCOAMMessages.INVALID_COMMAND;
}
String password = args[4];
if (password == null) {
return SMSCOAMMessages.INVALID_COMMAND;
}
String host = args[5];
if (host == null) {
return SMSCOAMMessages.INVALID_COMMAND;
}
String strPort = args[6];
int intPort = -1;
if (strPort == null) {
return SMSCOAMMessages.INVALID_COMMAND;
} else {
try {
intPort = Integer.parseInt(strPort);
} catch (Exception e) {
return SMSCOAMMessages.INVALID_COMMAND;
}
}
SmppBindType smppBindType = null;
String smppBindTypeStr = args[7];
if (smppBindTypeStr == null) {
return SMSCOAMMessages.INVALID_COMMAND;
}
if (SmppBindType.TRANSCEIVER.toString().equals(smppBindTypeStr)) {
smppBindType = SmppBindType.TRANSCEIVER;
} else if (SmppBindType.TRANSMITTER.toString().equals(smppBindTypeStr)) {
smppBindType = SmppBindType.TRANSMITTER;
} else if (SmppBindType.RECEIVER.toString().equals(smppBindTypeStr)) {
smppBindType = SmppBindType.RECEIVER;
} else {
return SMSCOAMMessages.INVALID_COMMAND;
}
String systemType = null;
SmppInterfaceVersionType smppVersionType = null;
byte esmeTonType = 0;
byte esmeNpiType = 0;
String esmeAddrRange = null;
int count = 8;
while (count < args.length) {
// These are all optional parameters for a Tx/Rx/Trx binds
String key = args[count++];
if (key == null) {
return SMSCOAMMessages.INVALID_COMMAND;
}
if (key.equals("system-type")) {
systemType = args[count++];
} else if (key.equals("interface-version")) {
smppVersionType = SmppInterfaceVersionType.getInterfaceVersionType(args[count++]);
if (smppVersionType == null) {
smppVersionType = SmppInterfaceVersionType.SMPP34;
}
} else if (key.equals("esme-ton")) {
esmeTonType = Byte.parseByte(args[count++]);
} else if (key.equals("esme-npi")) {
esmeNpiType = Byte.parseByte(args[count++]);
} else if (key.equals("esme-range")) {
esmeAddrRange = /* Regex */args[count++];
} else {
return SMSCOAMMessages.INVALID_COMMAND;
}
}
if ((SmppBindType.TRANSCEIVER == smppBindType || SmppBindType.RECEIVER == smppBindType)
&& esmeAddrRange == null) {
return SMSCOAMMessages.NULL_ESME_ADDRESS_RANGE;
}
Address address = new Address(esmeTonType, esmeNpiType, esmeAddrRange);
Esme esme = this.smscManagement.getEsmeManagement().createEsme(systemId, password, host, strPort, smppBindType,
systemType, smppVersionType, address);
return String.format(SMSCOAMMessages.CREATE_ESME_SUCCESSFULL, esme.getSystemId());
}
/**
* smsc esme destroy <SystemId - 4/5 digit number>
*
* @param args
* @return
* @throws Exception
*/
private String destroyEsme(String[] args) throws Exception {
if (args.length < 4) {
return SMSCOAMMessages.INVALID_COMMAND;
}
String systemId = args[3];
if (systemId == null) {
return SMSCOAMMessages.INVALID_COMMAND;
}
Esme esme = this.smscManagement.getEsmeManagement().destroyEsme(systemId);
return String.format(SMSCOAMMessages.DELETE_ESME_SUCCESSFUL, systemId);
}
private String showEsme() {
List<Esme> esmes = this.smscManagement.getEsmeManagement().getEsmes();
if (esmes.size() == 0) {
return SMSCOAMMessages.NO_ESME_DEFINED_YET;
}
StringBuffer sb = new StringBuffer();
for (Esme esme : esmes) {
sb.append(SMSCOAMMessages.NEW_LINE);
esme.show(sb);
}
return sb.toString();
}
private String executeSmsc(String[] args) {
try {
if (args.length < 2 || args.length > 20) {
// any command will have atleast 3 args
return SMSCOAMMessages.INVALID_COMMAND;
}
if (args[1] == null) {
return SMSCOAMMessages.INVALID_COMMAND;
}
if (args[1].equals("esme")) {
String rasCmd = args[2];
if (rasCmd == null) {
return SMSCOAMMessages.INVALID_COMMAND;
}
if (rasCmd.equals("create")) {
return this.createEsme(args);
} else if (rasCmd.equals("delete")) {
return this.destroyEsme(args);
} else if (rasCmd.equals("show")) {
return this.showEsme();
}
return SMSCOAMMessages.INVALID_COMMAND;
} else if (args[1].equals("set")) {
return this.manageSet(args);
} else if (args[1].equals("get")) {
return this.manageGet(args);
}
return SMSCOAMMessages.INVALID_COMMAND;
} catch (Exception e) {
logger.error(String.format("Error while executing comand %s", Arrays.toString(args)), e);
return e.getMessage();
}
}
private String manageSet(String[] options) throws Exception {
if (options.length < 4) {
return SMSCOAMMessages.INVALID_COMMAND;
}
String parName = options[2].toLowerCase();
if (parName.equals("scgt")) {
smscPropertiesManagement.setServiceCenterGt(options[3]);
} else if (parName.equals("scssn")) {
int val = Integer.parseInt(options[3]);
smscPropertiesManagement.setServiceCenterSsn(val);
} else if (parName.equals("hlrssn")) {
int val = Integer.parseInt(options[3]);
smscPropertiesManagement.setHlrSsn(val);
} else if (parName.equals("mscssn")) {
int val = Integer.parseInt(options[3]);
smscPropertiesManagement.setMscSsn(val);
} else if (parName.equals("maxmapv")) {
int val = Integer.parseInt(options[3]);
smscPropertiesManagement.setMaxMapVersion(val);
} else {
return SMSCOAMMessages.INVALID_COMMAND;
}
return SMSCOAMMessages.PARAMETER_SUCCESSFULLY_SET;
}
private String manageGet(String[] options) throws Exception {
if (options.length == 3) {
String parName = options[2].toLowerCase();
StringBuilder sb = new StringBuilder();
sb.append(options[2]);
sb.append(" = ");
if (parName.equals("scgt")) {
sb.append(smscPropertiesManagement.getServiceCenterGt());
} else if (parName.equals("scssn")) {
sb.append(smscPropertiesManagement.getServiceCenterSsn());
} else if (parName.equals("hlrssn")) {
sb.append(smscPropertiesManagement.getHlrSsn());
} else if (parName.equals("mscssn")) {
sb.append(smscPropertiesManagement.getMscSsn());
} else if (parName.equals("maxmapv")) {
sb.append(smscPropertiesManagement.getMaxMapVersion());
} else {
return SMSCOAMMessages.INVALID_COMMAND;
}
return sb.toString();
} else {
StringBuilder sb = new StringBuilder();
sb.append("scgt = ");
sb.append(smscPropertiesManagement.getServiceCenterGt());
sb.append("\n");
sb.append("scssn = ");
sb.append(smscPropertiesManagement.getServiceCenterSsn());
sb.append("\n");
sb.append("hlrssn = ");
sb.append(smscPropertiesManagement.getHlrSsn());
sb.append("\n");
sb.append("mscssn = ");
sb.append(smscPropertiesManagement.getMscSsn());
sb.append("\n");
sb.append("maxmapv = ");
sb.append(smscPropertiesManagement.getMaxMapVersion());
sb.append("\n");
return sb.toString();
}
}
public String execute(String[] args) {
if (args[0].equals("smsc")) {
return this.executeSmsc(args);
}
return SMSCOAMMessages.INVALID_COMMAND;
}
@Override
public boolean handles(String command) {
return "smsc".equals(command);
}
}
| Java |
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* 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.smsc.smpp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;
import javolution.text.TextBuilder;
import javolution.util.FastList;
import javolution.xml.XMLBinding;
import javolution.xml.XMLObjectReader;
import javolution.xml.XMLObjectWriter;
import javolution.xml.stream.XMLStreamException;
import org.apache.log4j.Logger;
import com.cloudhopper.smpp.SmppBindType;
import com.cloudhopper.smpp.type.Address;
/**
*
* @author amit bhayani
*
*/
public class EsmeManagement implements EsmeManagementMBean {
private static final Logger logger = Logger.getLogger(EsmeManagement.class);
private static final String ESME_LIST = "esmeList";
private static final String TAB_INDENT = "\t";
private static final String CLASS_ATTRIBUTE = "type";
private static final XMLBinding binding = new XMLBinding();
private static final String PERSIST_FILE_NAME = "esme.xml";
private final String name;
private String persistDir = null;
protected FastList<Esme> esmes = new FastList<Esme>();
private final TextBuilder persistFile = TextBuilder.newInstance();
public EsmeManagement(String name) {
this.name = name;
binding.setClassAttribute(CLASS_ATTRIBUTE);
binding.setAlias(Esme.class, "esme");
}
public String getName() {
return name;
}
public String getPersistDir() {
return persistDir;
}
public void setPersistDir(String persistDir) {
this.persistDir = persistDir;
}
public List<Esme> getEsmes() {
return esmes.unmodifiable();
}
public Esme getEsme(String systemId) {
for (FastList.Node<Esme> n = esmes.head(), end = esmes.tail(); (n = n.getNext()) != end;) {
Esme esme = n.getValue();
if (esme.getSystemId().equals(systemId)) {
return esme;
}
}
return null;
}
/**
* <p>
* Create new {@link Esme}
* </p>
* <p>
* Command is smsc esme create <Any 4/5 digit number> <Specify password>
* <host-ip> <port> system-type <sms | vms | ota > interface-version <3.3 |
* 3.4 | 5.0> esme-ton <esme address ton> esme-npi <esme address npi>
* esme-range <esme address range>
* </p>
* <p>
* where system-type, interface-version, esme-ton, esme-npi, esme-range are
* optional, by default interface-version is 3.4.
*
* </p>
*
* @param args
* @return
* @throws Exception
*/
public Esme createEsme(String systemId, String password, String host, String port, SmppBindType smppBindType,
String systemType, SmppInterfaceVersionType smppIntVersion, Address address) throws Exception {
/* Esme system id should be unique and mandatory for each esme */
Esme esme = this.getEsme(systemId);
if (esme != null) {
throw new Exception(String.format(SMSCOAMMessages.CREATE_EMSE_FAIL_ALREADY_EXIST, systemId));
}
// TODO check if RC is already taken?
if (smppIntVersion == null) {
smppIntVersion = SmppInterfaceVersionType.SMPP34;
}
esme = new Esme(systemId, password, host, port, smppBindType, systemType, smppIntVersion, address);
esmes.add(esme);
this.store();
return esme;
}
public Esme destroyEsme(String systemId) throws Exception {
Esme esme = this.getEsme(systemId);
if (esme == null) {
throw new Exception(String.format(SMSCOAMMessages.DELETE_ESME_FAILED_NO_ESME_FOUND, systemId));
}
esmes.remove(esme);
this.store();
return esme;
}
public void start() throws Exception {
this.persistFile.clear();
if (persistDir != null) {
this.persistFile.append(persistDir).append(File.separator).append(this.name).append("_")
.append(PERSIST_FILE_NAME);
} else {
persistFile
.append(System.getProperty(SmscManagement.SMSC_PERSIST_DIR_KEY,
System.getProperty(SmscManagement.USER_DIR_KEY))).append(File.separator).append(this.name)
.append("_").append(PERSIST_FILE_NAME);
}
logger.info(String.format("Loading ESME configuration from %s", persistFile.toString()));
try {
this.load();
} catch (FileNotFoundException e) {
logger.warn(String.format("Failed to load the SS7 configuration file. \n%s", e.getMessage()));
}
}
public void stop() throws Exception {
this.store();
}
/**
* Persist
*/
public void store() {
// TODO : Should we keep reference to Objects rather than recreating
// everytime?
try {
XMLObjectWriter writer = XMLObjectWriter.newInstance(new FileOutputStream(persistFile.toString()));
writer.setBinding(binding);
// Enables cross-references.
// writer.setReferenceResolver(new XMLReferenceResolver());
writer.setIndentation(TAB_INDENT);
writer.write(esmes, ESME_LIST, FastList.class);
writer.close();
} catch (Exception e) {
logger.error("Error while persisting the Rule state in file", e);
}
}
/**
* Load and create LinkSets and Link from persisted file
*
* @throws Exception
*/
public void load() throws FileNotFoundException {
XMLObjectReader reader = null;
try {
reader = XMLObjectReader.newInstance(new FileInputStream(persistFile.toString()));
reader.setBinding(binding);
esmes = reader.read(ESME_LIST, FastList.class);
reader.close();
} catch (XMLStreamException ex) {
// this.logger.info(
// "Error while re-creating Linksets from persisted file", ex);
}
}
}
| Java |
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* 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.smsc.smpp;
public interface SmscPropertiesManagementMBean {
public String getServiceCenterGt();
public void setServiceCenterGt(String serviceCenterGt);
public int getServiceCenterSsn();
public void setServiceCenterSsn(int serviceCenterSsn);
public int getHlrSsn();
public void setHlrSsn(int hlrSsn);
public int getMscSsn();
public void setMscSsn(int mscSsn);
public int getMaxMapVersion();
public void setMaxMapVersion(int maxMapVersion);
}
| Java |
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* 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.smsc.smpp;
import java.io.Serializable;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.StandardMBean;
import org.apache.log4j.Logger;
import org.jboss.mx.util.MBeanServerLocator;
import com.cloudhopper.smpp.SmppBindType;
import com.cloudhopper.smpp.SmppConstants;
import com.cloudhopper.smpp.SmppServerHandler;
import com.cloudhopper.smpp.SmppServerSession;
import com.cloudhopper.smpp.SmppSessionConfiguration;
import com.cloudhopper.smpp.SmppSessionHandler;
import com.cloudhopper.smpp.impl.DefaultSmppSession;
import com.cloudhopper.smpp.jmx.DefaultSmppSessionMXBean;
import com.cloudhopper.smpp.pdu.BaseBind;
import com.cloudhopper.smpp.pdu.BaseBindResp;
import com.cloudhopper.smpp.type.Address;
import com.cloudhopper.smpp.type.SmppProcessingException;
public class DefaultSmppServerHandler implements SmppServerHandler, Serializable {
private static int SESSION_INDEX = 0;
private static final Logger logger = Logger.getLogger(DefaultSmppServerHandler.class);
private transient SmppSessionHandlerInterface smppSessionHandlerInterface = null;
private transient EsmeManagement esmeManagement = null;
private MBeanServer mbeanServer = null;
public DefaultSmppServerHandler() {
}
public void setEsmeManagement(EsmeManagement esmeManagement) {
this.esmeManagement = esmeManagement;
}
public SmppSessionHandlerInterface getSmppSessionHandlerInterface() {
return smppSessionHandlerInterface;
}
public void setSmppSessionHandlerInterface(SmppSessionHandlerInterface smppSessionHandlerInterface) {
this.smppSessionHandlerInterface = smppSessionHandlerInterface;
}
@Override
public void sessionBindRequested(Long sessionId, SmppSessionConfiguration sessionConfiguration,
final BaseBind bindRequest) throws SmppProcessingException {
if (this.smppSessionHandlerInterface == null) {
logger.error("No SmppSessionHandlerInterface registered yet! Will close SmppServerSession");
throw new SmppProcessingException(SmppConstants.STATUS_BINDFAIL);
}
Esme esme = this.esmeManagement.getEsme(bindRequest.getSystemId());
if (esme == null) {
logger.error(String.format("No ESME configured for SystemId=%s", bindRequest.getSystemId()));
throw new SmppProcessingException(SmppConstants.STATUS_INVSYSID);
}
if (!(esme.getPassword().equals(bindRequest.getPassword()))) {
logger.error(String.format("Invalid password for SystemId=%s", bindRequest.getSystemId()));
throw new SmppProcessingException(SmppConstants.STATUS_INVPASWD);
}
// Check of BIND is correct?
if ((bindRequest.getCommandId() == SmppConstants.CMD_ID_BIND_RECEIVER)
&& esme.getSmppBindType() != SmppBindType.RECEIVER) {
logger.error(String.format("Received BIND_RECEIVER for SystemId=%s but configured=%s",
bindRequest.getSystemId(), esme.getSmppBindType()));
throw new SmppProcessingException(SmppConstants.STATUS_INVBNDSTS);
} else if ((bindRequest.getCommandId() == SmppConstants.CMD_ID_BIND_TRANSMITTER)
&& esme.getSmppBindType() != SmppBindType.TRANSMITTER) {
logger.error(String.format("Received BIND_TRANSMITTER for SystemId=%s but configured=%s",
bindRequest.getSystemId(), esme.getSmppBindType()));
throw new SmppProcessingException(SmppConstants.STATUS_INVBNDSTS);
} else if ((bindRequest.getCommandId() == SmppConstants.CMD_ID_BIND_TRANSCEIVER)
&& esme.getSmppBindType() != SmppBindType.TRANSCEIVER) {
logger.error(String.format("Received BIND_TRANSCEIVER for SystemId=%s but configured=%s",
bindRequest.getSystemId(), esme.getSmppBindType()));
throw new SmppProcessingException(SmppConstants.STATUS_INVBNDSTS);
}
// Check if TON, NPI and Address Range matches
Address esmeAddressRange = esme.getAddress();
Address bindRequestAddressRange = bindRequest.getAddressRange();
if (esmeAddressRange.getTon() != bindRequestAddressRange.getTon()) {
logger.error(String.format("Received BIND request with TON=%d but configured TON=%d",
bindRequestAddressRange.getTon(), esmeAddressRange.getTon()));
throw new SmppProcessingException(SmppConstants.STATUS_INVBNDSTS);
}
if (esmeAddressRange.getNpi() != bindRequestAddressRange.getNpi()) {
logger.error(String.format("Received BIND request with NPI=%d but configured NPI=%d",
bindRequestAddressRange.getNpi(), esmeAddressRange.getNpi()));
throw new SmppProcessingException(SmppConstants.STATUS_INVBNDSTS);
}
//TODO : we are checking with empty String, is this correct?
if (bindRequestAddressRange.getAddress() == null || bindRequestAddressRange.getAddress() == "") {
// If ESME doesn't know we set it up from our config
bindRequestAddressRange.setAddress(esmeAddressRange.getAddress());
} else if (!bindRequestAddressRange.getAddress().equals(esmeAddressRange.getAddress())) {
logger.error(String.format("Received BIND request with Address_Range=%s but configured Address_Range=%s",
bindRequestAddressRange.getAddress(), esmeAddressRange.getAddress()));
throw new SmppProcessingException(SmppConstants.STATUS_INVBNDSTS);
}
sessionConfiguration.setAddressRange(bindRequestAddressRange);
// TODO More parameters to compare
// test name change of sessions
// this name actually shows up as thread context....
sessionConfiguration
.setName("Application.SMPP." + (SESSION_INDEX++) + "." + sessionConfiguration.getSystemId());
// throw new SmppProcessingException(SmppConstants.STATUS_BINDFAIL,
// null);
}
@Override
public void sessionCreated(Long sessionId, SmppServerSession session, BaseBindResp preparedBindResponse)
throws SmppProcessingException {
if (logger.isInfoEnabled()) {
logger.info(String.format("Session created: %s", session.getConfiguration().getSystemId()));
}
// TODO smppSessionHandlerInterface should also expose boolean
// indicating listener is ready to process the request
if (this.smppSessionHandlerInterface == null) {
logger.error("No SmppSessionHandlerInterface registered yet! Will close SmppServerSession");
throw new SmppProcessingException(SmppConstants.STATUS_BINDFAIL);
}
if (!logger.isDebugEnabled()) {
session.getConfiguration().getLoggingOptions().setLogBytes(false);
session.getConfiguration().getLoggingOptions().setLogPdu(false);
}
SmppSessionHandler smppSessionHandler = this.smppSessionHandlerInterface.sessionCreated(sessionId, session,
preparedBindResponse);
// need to do something it now (flag we're ready)
session.serverReady(smppSessionHandler);
this.registerMBean(sessionId, session);
Esme esme = this.esmeManagement.getEsme(session.getConfiguration().getSystemId());
esme.setState(session.getStateName());
}
@Override
public void sessionDestroyed(Long sessionId, SmppServerSession session) {
if (logger.isInfoEnabled()) {
logger.info(String.format("Session destroyed: %s", session.getConfiguration().getSystemId()));
}
if (this.smppSessionHandlerInterface != null) {
this.smppSessionHandlerInterface.sessionDestroyed(sessionId, session);
}
// print out final stats
if (session.hasCounters()) {
logger.info(String.format("final session rx-submitSM: %s", session.getCounters().getRxSubmitSM()));
}
// make sure it's really shutdown
session.destroy();
this.unregisterMBean(sessionId, session);
Esme esme = this.esmeManagement.getEsme(session.getConfiguration().getSystemId());
esme.setState(session.getStateName());
}
private void registerMBean(Long sessionId, SmppServerSession session) {
SmppSessionConfiguration configuration = session.getConfiguration();
try {
this.mbeanServer = MBeanServerLocator.locateJBoss();
ObjectName name = new ObjectName(SmscManagement.JMX_DOMAIN + ":type=" + configuration.getName()
+ "Sessions,name=" + sessionId);
StandardMBean mxBean = new StandardMBean(((DefaultSmppSession) session), DefaultSmppSessionMXBean.class,
true);
this.mbeanServer.registerMBean(mxBean, name);
} catch (Exception e) {
// log the error, but don't throw an exception for this datasource
logger.error(String.format("Unable to register DefaultSmppSessionMXBean %s", configuration.getName()), e);
}
}
private void unregisterMBean(Long sessionId, SmppServerSession session) {
SmppSessionConfiguration configuration = session.getConfiguration();
try {
if (this.mbeanServer != null) {
ObjectName name = new ObjectName(SmscManagement.JMX_DOMAIN + ":type=" + configuration.getName()
+ "Sessions,name=" + sessionId);
this.mbeanServer.unregisterMBean(name);
}
} catch (Exception e) {
logger.error(String.format("Unable to unregister DefaultSmppServerMXBean %s", configuration.getName()), e);
}
}
}
| Java |
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* 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.smsc.smpp;
/**
*
* @author zaheer abbas
*
*/
public interface SMSCOAMMessages {
/**
* Pre defined messages
*/
public static final String INVALID_COMMAND = "Invalid Command";
/*
* public static final String ADD_ROUTING_RULE_SUCESSFULL =
* "Successfully added Routing rule name=%s";
*
* public static final String ADD_ROUTING_RULE_FAIL_NO_SYSTEM_ID =
* "Creation of Routing rule failed, as no ESME added with the System Id name=%s"
* ;
*/
public static final String ESME_START_SUCCESSFULL = "Successfully started ESME name=%s";
public static final String ESME_STOP_SUCCESSFULL = "Successfully stopped ESME name=%s";
public static final String CREATE_ESME_SUCCESSFULL = "Successfully created ESME name=%s";
public static final String CREATE_EMSE_FAIL_ALREADY_EXIST = "Creation of EMSE failed. Other ESME with name=%s already exist"; // name
// =
// systemid
public static final String CREATE_ROUTING_RULE_SUCCESSFULL = "Successfully created Routing rule name=%s";
public static final String CREATE_ROUTING_RULE_FAIL_ALREADY_EXIST = "Creation of Routing rule failed. Other Route with name=%s already exist"; // name
// =
// systemid
public static final String NOT_SUPPORTED_YET = "Not supported yet";
public static final String NO_ESME_DEFINED_YET = "No ESME defined yet";
public static final String NO_ROUTING_RULE_DEFINED_YET = "No Routing rule defined yet";
public static final String DELETE_ESME_FAILED_NO_ESME_FOUND = "No Esme found with given systemId %s";
public static final String DELETE_ESME_SUCCESSFUL = "Successfully deleted Esme with given systemId %s";
public static final String NULL_ESME_ADDRESS_RANGE = "esme-range is compulsory for TRANSCEIVER and RECEIVER";
public static final String PARAMETER_SUCCESSFULLY_SET = "Parameter has been successfully set";
/**
* Generic constants
*/
public static final String TAB = " ";
public static final String NEW_LINE = "\n";
public static final String COMMA = ",";
/**
* Show command specific constants
*/
public static final String SHOW_ASSIGNED_TO = "Assigned to :\n";
public static final String SHOW_ESME_SYSTEM_ID = "ESME systemId=";
public static final String SHOW_ESME_STATE = " state=";
public static final String SHOW_ESME_PASSWORD = " password=";
public static final String SHOW_ESME_HOST = " host=";
public static final String SHOW_ESME_PORT = " port=";
public static final String SHOW_ESME_BIND_TYPE = " bindType=";
public static final String SHOW_ESME_SYSTEM_TYPE = " systemType=";
public static final String SHOW_ESME_INTERFACE_VERSION = " smppInterfaceVersion=";
public static final String SHOW_ESME_TON = " ton=";
public static final String SHOW_ESME_NPI = " npi=";
public static final String SHOW_ESME_ADDRESS_RANGE = " addressRange=";
public static final String SHOW_ROUTING_RULE_NAME = "Routing rule name=";
public static final String SHOW_STARTED = " started=";
public static final String SHOW_ADDRESS = " address=";
}
| Java |
package org.mobicents.smsc.smpp;
public interface SMPPServerServiceMBean {
public static final String ONAME = "org.mobicents.smsc:service=SMPPServerService";
public void start() throws Exception;
public void stop();
/**
* Returns DefaultSmppServerHandler jndi name.
*/
public String getJndiName();
}
| Java |
package org.mobicents.smsc.smpp;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.log4j.Logger;
import org.jboss.system.ServiceMBeanSupport;
public class SMPPServerService extends ServiceMBeanSupport implements SMPPServerServiceMBean {
private static final Logger logger = Logger.getLogger(SMPPServerService.class);
private DefaultSmppServerHandler defaultSmppServerHandler = null;
private String jndiName;
public SMPPServerService() {
}
public void setJndiName(String jndiName) {
this.jndiName = jndiName;
}
@Override
public String getJndiName() {
return this.jndiName;
}
public DefaultSmppServerHandler getDefaultSmppServerHandler() {
return defaultSmppServerHandler;
}
public void setDefaultSmppServerHandler(DefaultSmppServerHandler defaultSmppServerHandler) {
this.defaultSmppServerHandler = defaultSmppServerHandler;
}
@Override
public void startService() throws Exception {
// starting
rebind(this.defaultSmppServerHandler);
logger.info("SMPPServerService started .... ");
}
@Override
public void stopService() {
try {
unbind(jndiName);
logger.info("SMPPServerService stopped .... ");
} catch (Exception e) {
}
}
/**
* Binds trunk object to the JNDI under the jndiName.
*/
private void rebind(DefaultSmppServerHandler defaultSmppServerHandler) throws NamingException {
Context ctx = new InitialContext();
String tokens[] = jndiName.split("/");
for (int i = 0; i < tokens.length - 1; i++) {
if (tokens[i].trim().length() > 0) {
try {
ctx = (Context) ctx.lookup(tokens[i]);
} catch (NamingException e) {
ctx = ctx.createSubcontext(tokens[i]);
}
}
}
ctx.bind(tokens[tokens.length - 1], defaultSmppServerHandler);
}
/**
* Unbounds object under specified name.
*
* @param jndiName
* the JNDI name of the object to be unbound.
*/
private void unbind(String jndiName) throws NamingException {
InitialContext initialContext = new InitialContext();
initialContext.unbind(jndiName);
}
}
| Java |
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* 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.smsc.smpp;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.StandardMBean;
import org.apache.log4j.Logger;
import org.jboss.mx.util.MBeanServerLocator;
import com.cloudhopper.smpp.SmppConstants;
import com.cloudhopper.smpp.SmppServerConfiguration;
import com.cloudhopper.smpp.SmppServerHandler;
import com.cloudhopper.smpp.impl.DefaultSmppServer;
import com.cloudhopper.smpp.jmx.DefaultSmppServerMXBean;
import com.cloudhopper.smpp.type.SmppChannelException;
public class SmppServer {
private static final Logger logger = Logger.getLogger(SmppServer.class);
private String name = "SmppServer";
private int port = 2775;
// length of time to wait for a bind request
private long bindTimeout = 5000;
private String systemId = "MobicentsSMSC";
// if true, <= 3.3 for interface version normalizes to version 3.3
// if true, >= 3.4 for interface version normalizes to version 3.4 and
// optional sc_interface_version is set to 3.4
private boolean autoNegotiateInterfaceVersion = true;
// smpp version the server supports
private double interfaceVersion = 3.4;
// max number of connections/sessions this server will expect to handle
// this number corrosponds to the number of worker threads handling reading
// data from sockets and the thread things will be processed under
private int maxConnectionSize = SmppConstants.DEFAULT_SERVER_MAX_CONNECTION_SIZE;
private int defaultWindowSize = SmppConstants.DEFAULT_WINDOW_SIZE;
private long defaultWindowWaitTimeout = SmppConstants.DEFAULT_WINDOW_WAIT_TIMEOUT;
private long defaultRequestExpiryTimeout = SmppConstants.DEFAULT_REQUEST_EXPIRY_TIMEOUT;
private long defaultWindowMonitorInterval = SmppConstants.DEFAULT_WINDOW_MONITOR_INTERVAL;
private boolean defaultSessionCountersEnabled = false;
private DefaultSmppServer defaultSmppServer = null;
private SmppServerHandler smppServerHandler = null;
private MBeanServer mbeanServer = null;
private EsmeManagement esmeManagement = null;
public SmppServer() {
}
public void setEsmeManagement(EsmeManagement esmeManagement) {
this.esmeManagement = esmeManagement;
((DefaultSmppServerHandler)this.smppServerHandler).setEsmeManagement(esmeManagement);
}
public void setName(String name) {
this.name = name;
}
protected String getName() {
return name;
}
public void setPort(int port) {
this.port = port;
}
public void setBindTimeout(long bindTimeout) {
this.bindTimeout = bindTimeout;
}
public void setSystemId(String systemId) {
this.systemId = systemId;
}
public void setAutoNegotiateInterfaceVersion(boolean autoNegotiateInterfaceVersion) {
this.autoNegotiateInterfaceVersion = autoNegotiateInterfaceVersion;
}
public void setInterfaceVersion(double interfaceVersion) throws Exception {
if (interfaceVersion != 3.4 && interfaceVersion != 3.3) {
throw new Exception("Only SMPP version 3.4 or 3.3 is supported");
}
this.interfaceVersion = interfaceVersion;
}
public void setMaxConnectionSize(int maxConnectionSize) {
this.maxConnectionSize = maxConnectionSize;
}
public void setDefaultWindowSize(int defaultWindowSize) {
this.defaultWindowSize = defaultWindowSize;
}
public void setDefaultWindowWaitTimeout(long defaultWindowWaitTimeout) {
this.defaultWindowWaitTimeout = defaultWindowWaitTimeout;
}
public void setDefaultRequestExpiryTimeout(long defaultRequestExpiryTimeout) {
this.defaultRequestExpiryTimeout = defaultRequestExpiryTimeout;
}
public void setDefaultWindowMonitorInterval(long defaultWindowMonitorInterval) {
this.defaultWindowMonitorInterval = defaultWindowMonitorInterval;
}
public void setDefaultSessionCountersEnabled(boolean defaultSessionCountersEnabled) {
this.defaultSessionCountersEnabled = defaultSessionCountersEnabled;
}
public void start() throws SmppChannelException {
// for monitoring thread use, it's preferable to create your own
// instance of an executor and cast it to a ThreadPoolExecutor from
// Executors.newCachedThreadPool() this permits exposing thinks like
// executor.getActiveCount() via JMX possible no point renaming the
// threads in a factory since underlying Netty framework does not easily
// allow you to customize your thread names
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
// to enable automatic expiration of requests, a second scheduled
// executor
// is required which is what a monitor task will be executed with - this
// is probably a thread pool that can be shared with between all client
// bootstraps
ScheduledThreadPoolExecutor monitorExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1,
new ThreadFactory() {
private AtomicInteger sequence = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("SmppServerSessionWindowMonitorPool-" + sequence.getAndIncrement());
return t;
}
});
// create a server configuration
SmppServerConfiguration configuration = new SmppServerConfiguration();
configuration.setName(this.name);
configuration.setPort(this.port);
configuration.setBindTimeout(this.bindTimeout);
configuration.setSystemId(this.systemId);
configuration.setAutoNegotiateInterfaceVersion(this.autoNegotiateInterfaceVersion);
if (this.interfaceVersion == 3.4) {
configuration.setInterfaceVersion(SmppConstants.VERSION_3_4);
} else if (this.interfaceVersion == 3.3) {
configuration.setInterfaceVersion(SmppConstants.VERSION_3_3);
}
configuration.setMaxConnectionSize(this.maxConnectionSize);
configuration.setNonBlockingSocketsEnabled(true);
// SMPP Request sent would wait for 30000 milli seconds before throwing
// exception
configuration.setDefaultRequestExpiryTimeout(this.defaultRequestExpiryTimeout);
configuration.setDefaultWindowMonitorInterval(this.defaultWindowMonitorInterval);
// The "window" is the amount of unacknowledged requests that are
// permitted to be outstanding/unacknowledged at any given time.
configuration.setDefaultWindowSize(this.defaultWindowSize);
// Set the amount of time to wait until a slot opens up in the
// sendWindow.
configuration.setDefaultWindowWaitTimeout(this.defaultWindowWaitTimeout);
configuration.setDefaultSessionCountersEnabled(this.defaultSessionCountersEnabled);
// We bind to JBoss MBean
configuration.setJmxEnabled(false);
this.smppServerHandler = new DefaultSmppServerHandler();
// create a server, start it up
this.defaultSmppServer = new DefaultSmppServer(configuration, smppServerHandler, executor, monitorExecutor);
this.registerMBean();
logger.info("Starting SMPP server...");
this.defaultSmppServer.start();
logger.info("SMPP server started");
}
public void stop() {
logger.info("Stopping SMPP server...");
this.defaultSmppServer.stop();
logger.info("SMPP server stopped");
logger.info(String.format("Server counters: %s", this.defaultSmppServer.getCounters()));
}
public void destroy() {
this.unregisterMBean();
}
private void registerMBean() {
try {
this.mbeanServer = MBeanServerLocator.locateJBoss();
ObjectName name = new ObjectName(SmscManagement.JMX_DOMAIN + ":name=" + this.name);
final StandardMBean mxBean = new StandardMBean(this.defaultSmppServer, DefaultSmppServerMXBean.class, true);
this.mbeanServer.registerMBean(mxBean, name);
} catch (Exception e) {
// log the error, but don't throw an exception for this datasource
logger.error(String.format("Unable to register DefaultSmppServerMXBean %s", this.name), e);
}
}
private void unregisterMBean() {
try {
if (this.mbeanServer != null) {
ObjectName name = new ObjectName(SmscManagement.JMX_DOMAIN + ":name=" + this.name);
this.mbeanServer.unregisterMBean(name);
}
} catch (Exception e) {
logger.error(String.format("Unable to unregister DefaultSmppServerMXBean %s", this.name), e);
}
}
public DefaultSmppServerHandler getDefaultSmppServerHandler() {
return (DefaultSmppServerHandler) smppServerHandler;
}
}
| Java |
package org.mobicents.smsc.smpp;
public enum SmppInterfaceVersionType {
SMPP33("3.3"), SMPP34("3.4"), SMPP50("5.0");
private static final String TYPE_SMPP33 = "3.3";
private static final String TYPE_SMPP34 = "3.4";
private static final String TYPE_SMPP50 = "5.0";
private String type = null;
private SmppInterfaceVersionType(String type) {
this.type = type;
}
public static SmppInterfaceVersionType getInterfaceVersionType(String type) {
if (TYPE_SMPP33.equals(type)) {
return SMPP33;
} else if (TYPE_SMPP34.equals(type)) {
return SMPP34;
} else if (TYPE_SMPP50.equals(type)) {
return SMPP50;
} else {
return null;
}
}
public String getType() {
return this.type;
}
}
| Java |
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* 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.smsc.smpp;
import javolution.xml.XMLFormat;
import javolution.xml.XMLSerializable;
import javolution.xml.stream.XMLStreamException;
import org.apache.log4j.Logger;
import com.cloudhopper.smpp.SmppBindType;
import com.cloudhopper.smpp.SmppSession;
import com.cloudhopper.smpp.type.Address;
/**
* @author amit bhayani
* @author zaheer abbas
*
*/
public class Esme implements XMLSerializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(Esme.class);
private static final String ESME_SYSTEM_ID = "systemId";
private static final String ESME_PASSWORD = "password";
private static final String REMOTE_HOST_IP = "host";
private static final String REMOTE_HOST_PORT = "port";
private static final String SMPP_BIND_TYPE = "smppBindType";
private static final String ESME_SYSTEM_TYPE = "systemType";
private static final String ESME_INTERFACE_VERSION = "smppVersion";
private static final String ESME_TON = "ton";
private static final String ESME_NPI = "npi";
private static final String ESME_ADDRESS_RANGE = "addressRange";
private String systemId;
private String password;
private String host;
private String port;
private String systemType;
private SmppInterfaceVersionType smppVersion = null;
private Address address = null;
private SmppBindType smppBindType;
protected SmscManagement smscManagement = null;
private String state = SmppSession.STATES[SmppSession.STATE_CLOSED];
public Esme() {
}
public Esme(String systemId, String pwd, String host, String port, SmppBindType smppBindType, String systemType,
SmppInterfaceVersionType version, Address address) {
this.systemId = systemId;
this.password = pwd;
this.host = host;
this.port = port;
this.systemType = systemType;
this.smppVersion = version;
this.address = address;
this.smppBindType = smppBindType;
}
/**
* Every As has unique name
*
* @return String name of this As
*/
public String getSystemId() {
return this.systemId;
}
/**
* @param systemId
* the systemId to set
*/
public void setSystemId(String systemId) {
this.systemId = systemId;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password
* the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the host
*/
public String getHost() {
return host;
}
/**
* @param host
* the host to set
*/
public void setHost(String host) {
this.host = host;
}
/**
* @return the port
*/
public String getPort() {
return port;
}
/**
* @param port
* the port to set
*/
public void setPort(String port) {
this.port = port;
}
protected SmppBindType getSmppBindType() {
return smppBindType;
}
protected void setSmppBindType(SmppBindType smppBindType) {
this.smppBindType = smppBindType;
}
/**
* @return the systemType
*/
public String getSystemType() {
return systemType;
}
/**
* @param systemType
* the systemType to set
*/
public void setSystemType(String systemType) {
this.systemType = systemType;
}
/**
* @return the smppVersion
*/
public SmppInterfaceVersionType getSmppVersion() {
return smppVersion;
}
/**
* @param smppVersion
* the smppVersion to set
*/
public void setSmppVersion(SmppInterfaceVersionType smppVersion) {
this.smppVersion = smppVersion;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
protected String getState() {
return state;
}
protected void setState(String state) {
this.state = state;
}
/**
* XML Serialization/Deserialization
*/
protected static final XMLFormat<Esme> ESME_XML = new XMLFormat<Esme>(Esme.class) {
@Override
public void read(javolution.xml.XMLFormat.InputElement xml, Esme esme) throws XMLStreamException {
esme.systemId = xml.getAttribute(ESME_SYSTEM_ID, "");
esme.password = xml.getAttribute(ESME_PASSWORD, "");
esme.host = xml.getAttribute(REMOTE_HOST_IP, "");
esme.port = xml.getAttribute(REMOTE_HOST_PORT, "");
String smppBindTypeStr = xml.getAttribute(SMPP_BIND_TYPE, "TRANSCEIVER");
if (SmppBindType.TRANSCEIVER.toString().equals(smppBindTypeStr)) {
esme.smppBindType = SmppBindType.TRANSCEIVER;
} else if (SmppBindType.TRANSMITTER.toString().equals(smppBindTypeStr)) {
esme.smppBindType = SmppBindType.TRANSMITTER;
} else if (SmppBindType.RECEIVER.toString().equals(smppBindTypeStr)) {
esme.smppBindType = SmppBindType.RECEIVER;
}
esme.systemType = xml.getAttribute(ESME_SYSTEM_TYPE, "");
esme.smppVersion = SmppInterfaceVersionType.getInterfaceVersionType(xml.getAttribute(
ESME_INTERFACE_VERSION, ""));
byte ton = xml.getAttribute(ESME_TON, (byte) 0);
byte npi = xml.getAttribute(ESME_NPI, (byte) 0);
String addressRange = xml.getAttribute(ESME_ADDRESS_RANGE, null);
esme.address = new Address(ton, npi, addressRange);
}
@Override
public void write(Esme esme, javolution.xml.XMLFormat.OutputElement xml) throws XMLStreamException {
xml.setAttribute(ESME_SYSTEM_ID, esme.systemId);
xml.setAttribute(ESME_PASSWORD, esme.password);
xml.setAttribute(REMOTE_HOST_IP, esme.host);
xml.setAttribute(REMOTE_HOST_PORT, esme.port);
xml.setAttribute(SMPP_BIND_TYPE, esme.smppBindType.toString());
xml.setAttribute(ESME_INTERFACE_VERSION, esme.smppVersion.getType());
if (esme.systemType != null) {
xml.setAttribute(ESME_SYSTEM_TYPE, esme.systemType);
}
xml.setAttribute(ESME_TON, esme.address.getTon());
xml.setAttribute(ESME_NPI, esme.address.getNpi());
xml.setAttribute(ESME_ADDRESS_RANGE, esme.address.getAddress());
}
};
public void show(StringBuffer sb) {
sb.append(SMSCOAMMessages.SHOW_ESME_SYSTEM_ID).append(this.systemId).append(SMSCOAMMessages.SHOW_ESME_STATE)
.append(this.state).append(SMSCOAMMessages.SHOW_ESME_PASSWORD).append(this.password)
.append(SMSCOAMMessages.SHOW_ESME_HOST).append(this.host).append(SMSCOAMMessages.SHOW_ESME_PORT)
.append(this.port).append(SMSCOAMMessages.SHOW_ESME_BIND_TYPE).append(this.smppBindType)
.append(SMSCOAMMessages.SHOW_ESME_SYSTEM_TYPE).append(this.systemType)
.append(SMSCOAMMessages.SHOW_ESME_INTERFACE_VERSION).append(this.smppVersion)
.append(SMSCOAMMessages.SHOW_ADDRESS).append(this.address);
sb.append(SMSCOAMMessages.NEW_LINE);
}
}
| Java |
package org.mobicents.smsc.smpp;
import com.cloudhopper.smpp.SmppServerSession;
import com.cloudhopper.smpp.SmppSessionHandler;
import com.cloudhopper.smpp.pdu.BaseBindResp;
import com.cloudhopper.smpp.type.SmppProcessingException;
public interface SmppSessionHandlerInterface {
public SmppSessionHandler sessionCreated(Long sessionId, SmppServerSession session,
BaseBindResp preparedBindResponse) throws SmppProcessingException;
public void sessionDestroyed(Long sessionId, SmppServerSession session);
}
| Java |
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* and individual contributors
* 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.smsc.smpp;
import java.io.File;
import java.io.FileNotFoundException;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.StandardMBean;
import javolution.text.TextBuilder;
import javolution.xml.XMLBinding;
import org.apache.log4j.Logger;
import org.jboss.mx.util.MBeanServerLocator;
/**
* @author Amit Bhayani
*
*/
public class SmscManagement {
private static final Logger logger = Logger.getLogger(SmscManagement.class);
public static final String JMX_DOMAIN = "org.mobicents.smsc";
private static final String ROUTING_RULE_LIST = "routingRuleList";
protected static final String SMSC_PERSIST_DIR_KEY = "smsc.persist.dir";
protected static final String USER_DIR_KEY = "user.dir";
private static final String PERSIST_FILE_NAME = "smsc.xml";
private static final XMLBinding binding = new XMLBinding();
private static final String TAB_INDENT = "\t";
private static final String CLASS_ATTRIBUTE = "type";
private final TextBuilder persistFile = TextBuilder.newInstance();
private final String name;
private String persistDir = null;
private SmppServer smppServer = null;
private EsmeManagement esmeManagement = null;
private SmscPropertiesManagement smscPropertiesManagement = null;
private MBeanServer mbeanServer = null;
public SmscManagement(String name) {
this.name = name;
binding.setClassAttribute(CLASS_ATTRIBUTE);
binding.setAlias(Esme.class, "esme");
}
public String getName() {
return name;
}
public String getPersistDir() {
return persistDir;
}
public void setPersistDir(String persistDir) {
this.persistDir = persistDir;
}
public SmppServer getSmppServer() {
return smppServer;
}
public void setSmppServer(SmppServer smppServer) {
this.smppServer = smppServer;
}
public EsmeManagement getEsmeManagement() {
return esmeManagement;
}
public void start() throws Exception {
if (this.smppServer == null) {
throw new Exception("SmppServer not set");
}
this.esmeManagement = new EsmeManagement(this.name);
this.esmeManagement.setPersistDir(this.persistDir);
this.esmeManagement.start();
this.smscPropertiesManagement = SmscPropertiesManagement.getInstance(this.name);
this.smscPropertiesManagement.setPersistDir(this.persistDir);
this.smscPropertiesManagement.start();
// Register the MBeans
this.mbeanServer = MBeanServerLocator.locateJBoss();
ObjectName esmeObjNname = new ObjectName(SmscManagement.JMX_DOMAIN + ":name=EsmeManagement");
StandardMBean esmeMxBean = new StandardMBean(this.esmeManagement, EsmeManagementMBean.class, true);
this.mbeanServer.registerMBean(esmeMxBean, esmeObjNname);
ObjectName smscObjNname = new ObjectName(SmscManagement.JMX_DOMAIN + ":name=SmscPropertiesManagement");
StandardMBean smscMxBean = new StandardMBean(this.smscPropertiesManagement,
SmscPropertiesManagementMBean.class, true);
this.mbeanServer.registerMBean(smscMxBean, smscObjNname);
this.persistFile.clear();
if (persistDir != null) {
this.persistFile.append(persistDir).append(File.separator).append(this.name).append("_")
.append(PERSIST_FILE_NAME);
} else {
persistFile.append(System.getProperty(SMSC_PERSIST_DIR_KEY, System.getProperty(USER_DIR_KEY)))
.append(File.separator).append(this.name).append("_").append(PERSIST_FILE_NAME);
}
logger.info(String.format("SMSC configuration file path %s", persistFile.toString()));
try {
this.load();
} catch (FileNotFoundException e) {
logger.warn(String.format("Failed to load the SS7 configuration file. \n%s", e.getMessage()));
}
this.smppServer.setEsmeManagement(this.esmeManagement);
logger.info("Started SmscManagement");
}
public void stop() throws Exception {
this.esmeManagement.stop();
this.smscPropertiesManagement.stop();
this.store();
if (this.mbeanServer != null) {
ObjectName esmeObjNname = new ObjectName(SmscManagement.JMX_DOMAIN + ":name=EsmeManagement");
this.mbeanServer.unregisterMBean(esmeObjNname);
ObjectName smscObjNname = new ObjectName(SmscManagement.JMX_DOMAIN + ":name=SmscPropertiesManagement");
this.mbeanServer.unregisterMBean(smscObjNname);
}
}
/**
* Persist
*/
public void store() {
// TODO : Should we keep reference to Objects rather than recreating
// everytime?
// try {
// XMLObjectWriter writer = XMLObjectWriter.newInstance(new
// FileOutputStream(persistFile.toString()));
// writer.setBinding(binding);
// // Enables cross-references.
// // writer.setReferenceResolver(new XMLReferenceResolver());
// writer.setIndentation(TAB_INDENT);
// writer.write(esmes, ESME_LIST, FastList.class);
//
// writer.close();
// } catch (Exception e) {
// logger.error("Error while persisting the Rule state in file", e);
// }
}
/**
* Load and create LinkSets and Link from persisted file
*
* @throws Exception
*/
public void load() throws FileNotFoundException {
// XMLObjectReader reader = null;
// try {
// reader = XMLObjectReader.newInstance(new
// FileInputStream(persistFile.toString()));
//
// reader.setBinding(binding);
// esmes = reader.read(ESME_LIST, FastList.class);
//
// } catch (XMLStreamException ex) {
// // this.logger.info(
// // "Error while re-creating Linksets from persisted file", ex);
// }
}
}
| Java |
package org.mobicents.ss7.management.console.impl;
import org.mobicents.ss7.management.console.CommandContext;
import org.mobicents.ss7.management.console.CommandHandlerWithHelp;
import org.mobicents.ss7.management.console.Tree;
import org.mobicents.ss7.management.console.Tree.Node;
/**
* @author amit bhayani
*
*/
public class SmscCommandHandler extends CommandHandlerWithHelp {
static final Tree commandTree = new Tree("smsc");
static {
Node parent = commandTree.getTopNode();
Node esme = parent.addChild("esme");
esme.addChild("create");
esme.addChild("delete");
esme.addChild("show");
Node set = parent.addChild("set");
set.addChild("scgt");
set.addChild("scssn");
set.addChild("hlrssn");
set.addChild("mscssn");
set.addChild("maxmapv");
Node get = parent.addChild("get");
get.addChild("scgt");
get.addChild("scssn");
get.addChild("hlrssn");
get.addChild("mscssn");
get.addChild("maxmapv");
};
public SmscCommandHandler() {
super(commandTree, CONNECT_MANDATORY_FLAG);
}
/*
* (non-Javadoc)
*
* @see
* org.mobicents.ss7.management.console.CommandHandler#isValid(java.lang
* .String)
*/
@Override
public void handle(CommandContext ctx, String commandLine) {
// TODO Validate command
if (commandLine.contains("--help")) {
this.printHelp(commandLine, ctx);
return;
}
ctx.sendMessage(commandLine);
}
/*
* (non-Javadoc)
*
* @see
* org.mobicents.ss7.management.console.CommandHandler#isAvailable(org.mobicents
* .ss7.management.console.CommandContext)
*/
@Override
public boolean isAvailable(CommandContext ctx) {
if (!ctx.isControllerConnected()) {
ctx.printLine("The command is not available in the current context. Please connnect first");
return false;
}
return true;
}
}
| Java |
package pl.koziolekweb.annotations;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PACKAGE;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value = { TYPE, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER })
@Retention(value = RetentionPolicy.SOURCE)
@Documented
public @interface TodoList {
Todo[] todoList();
}
| Java |
package pl.koziolekweb.annotations;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PACKAGE;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value = { TYPE, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER })
@Retention(value = RetentionPolicy.SOURCE)
@Documented
public @interface Todo {
String description() default "";
}
| Java |
package de.mpg.mpiz.koeln.anna.listener.progresslistener;
import java.util.Collection;
import java.util.Formatter;
import de.kerner.commons.file.FileUtils;
import de.mpg.koeln.anna.core.events.AnnaEvent;
import de.mpg.koeln.anna.core.events.StepStateChangeEvent;
import de.mpg.mpiz.koeln.anna.listener.abstractlistener.AbstractEventListener;
import de.mpg.mpiz.koeln.anna.step.AnnaStep;
public class ProgressMonitor extends AbstractEventListener {
private final static String PRE_LINE = "+++++++++++++++ MONITOR +++++++++++++++";
private final static String POST_LINE = "+++++++++++++++++++++++++++++++++++++++";
public void eventOccoured(AnnaEvent event) {
AnnaStep lastChanged = null;
if (event instanceof StepStateChangeEvent){
lastChanged = ((StepStateChangeEvent) event).getStep();
} else {
logger.info(this, event);
}
printStepStates(event, lastChanged);
}
private synchronized void printStepStates(AnnaEvent event, AnnaStep lastChangedStep) {
final Collection<AnnaStep> steps = event.getRegisteredSteps();
logger.info(this, PRE_LINE);
for (AnnaStep s :steps) {
final String s1 = s.toString();
final String s2 = "state=" + s.getState();
final StringBuilder sb = new StringBuilder();
// TODO better: String.format();
final Formatter f = new Formatter();
sb.append(f.format("\t%-28s\t%-22s", s1, s2).toString());
if (lastChangedStep != null && lastChangedStep.equals(s)) {
sb.append("\t(changed)");
}
logger.info(this, sb.toString());
}
logger.info(this, POST_LINE);
}
@Override
public String toString() {
return this.getClass().getSimpleName();
}
}
| Java |
package de.mpg.mpiz.koeln.anna.listener.progresslistener;
import java.util.Collection;
import java.util.Formatter;
import de.kerner.commons.file.FileUtils;
import de.mpg.koeln.anna.core.events.AnnaEvent;
import de.mpg.koeln.anna.core.events.StepStateChangeEvent;
import de.mpg.mpiz.koeln.anna.listener.abstractlistener.AbstractEventListener;
import de.mpg.mpiz.koeln.anna.step.AnnaStep;
public class ProgressMonitor extends AbstractEventListener {
private final static String PRE_LINE = "+++++++++++++++ MONITOR +++++++++++++++";
private final static String POST_LINE = "+++++++++++++++++++++++++++++++++++++++";
public void eventOccoured(AnnaEvent event) {
AnnaStep lastChanged = null;
if (event instanceof StepStateChangeEvent){
lastChanged = ((StepStateChangeEvent) event).getStep();
} else {
logger.info(this, event);
}
printStepStates(event, lastChanged);
}
private synchronized void printStepStates(AnnaEvent event, AnnaStep lastChangedStep) {
final Collection<AnnaStep> steps = event.getRegisteredSteps();
logger.info(this, PRE_LINE);
for (AnnaStep s :steps) {
final String s1 = s.toString();
final String s2 = "state=" + s.getState();
final StringBuilder sb = new StringBuilder();
// TODO better: String.format();
final Formatter f = new Formatter();
sb.append(f.format("\t%-28s\t%-22s", s1, s2).toString());
if (lastChangedStep != null && lastChangedStep.equals(s)) {
sb.append("\t(changed)");
}
logger.info(this, sb.toString());
}
logger.info(this, POST_LINE);
}
@Override
public String toString() {
return this.getClass().getSimpleName();
}
}
| Java |
package de.mpg.mpiz.koeln.anna.step.repeatmasker.local;
import java.io.File;
import java.util.List;
import de.kerner.commons.CommandStringBuilder;
import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher;
import de.mpg.mpiz.koeln.anna.step.common.AbstractStepProcessBuilder;
import de.mpg.mpiz.koeln.anna.step.repeatmasker.common.AbstractStepRepeatMasker;
import de.mpg.mpiz.koeln.anna.step.repeatmasker.common.RepeatMaskerConstants;
public class StepRepeatMaskerLocal extends AbstractStepRepeatMasker {
private class Process extends AbstractStepProcessBuilder {
private final File inFile;
protected Process(File executableDir, File stepWorkingDir,
LogDispatcher logger, File inFile) {
super(executableDir, stepWorkingDir, logger);
this.inFile = inFile;
}
public String toString() {
return this.getClass().getSimpleName();
}
@Override
protected List<String> getCommandList() {
// ./RepeatMasker -pa 2 -s -gff
// /home/proj/kerner/diplom/conrad/trainingAndCrossValidationWithProvidedData/test3/ref.fasta
final CommandStringBuilder builder = new CommandStringBuilder(new File(
executableDir, RepeatMaskerConstants.EXE).getAbsolutePath());
// builder.addValueCommand("-pa", "2");
// builder.addAllFlagCommands("-s");
builder.addFlagCommand("-gff");
builder.addFlagCommand("-qq");
builder.addFlagCommand(inFile.getAbsolutePath());
return builder.getCommandList();
}
}
@Override
protected AbstractStepProcessBuilder getProcess(File inFile) {
return new Process(exeDir, workingDir
, logger, inFile);
}
}
| Java |
package de.mpg.mpiz.koeln.anna.step.repeatmasker.local;
import java.io.File;
import java.util.List;
import de.kerner.commons.CommandStringBuilder;
import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher;
import de.mpg.mpiz.koeln.anna.step.common.AbstractStepProcessBuilder;
import de.mpg.mpiz.koeln.anna.step.repeatmasker.common.AbstractStepRepeatMasker;
import de.mpg.mpiz.koeln.anna.step.repeatmasker.common.RepeatMaskerConstants;
public class RepeatMaskerLocal extends AbstractStepRepeatMasker {
private class Process extends AbstractStepProcessBuilder {
private final File inFile;
protected Process(File executableDir, File stepWorkingDir,
LogDispatcher logger, File inFile) {
super(executableDir, stepWorkingDir, logger);
this.inFile = inFile;
}
public String toString() {
return this.getClass().getSimpleName();
}
@Override
protected List<String> getCommandList() {
// ./RepeatMasker -pa 2 -s -gff
// /home/proj/kerner/diplom/conrad/trainingAndCrossValidationWithProvidedData/test3/ref.fasta
final CommandStringBuilder builder = new CommandStringBuilder(new File(
executableDir, RepeatMaskerConstants.EXE).getAbsolutePath());
// builder.addValueCommand("-pa", "2");
// builder.addAllFlagCommands("-s");
builder.addFlagCommand("-gff");
builder.addFlagCommand("-qq");
builder.addFlagCommand(inFile.getAbsolutePath());
return builder.getCommandList();
}
}
@Override
protected AbstractStepProcessBuilder getProcess(File inFile) {
return new Process(exeDir, workingDir
, logger, inFile);
}
}
| Java |
package de.mpg.mpiz.koeln.anna.step.conrad.data.adapter;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import de.bioutils.gff.GFFFormatErrorException;
import de.bioutils.gff.element.NewGFFElement;
import de.bioutils.gff.element.NewGFFElementBuilder;
import de.bioutils.gff.file.NewGFFFile;
import de.bioutils.gff.file.NewGFFFileImpl;
import de.bioutils.gff3.attribute.AttributeLine;
import de.bioutils.gff3.element.GFF3Element;
import de.bioutils.gff3.file.GFF3File;
import de.bioutils.gff3.file.GFF3FileImpl;
public class GFF3ConverterImpl implements GFF3Converter {
public NewGFFFile convert(GFF3File file) {
final ArrayList<NewGFFElement> result = new ArrayList<NewGFFElement>();
for (GFF3Element e : file.getElements()) {
final NewGFFElementBuilder b = new NewGFFElementBuilder(e);
String s = e.getAttributeLine().toString();
s = s.replaceAll("=", " ");
final List<String> l = Arrays.asList(s.split(AttributeLine.ATTRIBUTE_SEPARATOR));
b.setAttributes(new ArrayList<String>(l));
result.add(b.build());
}
return new NewGFFFileImpl(result);
}
public static void main(String[] args) {
final File f = new File("/home/pcb/kerner/Desktop/ref.gtf");
final File f3 = new File("/home/pcb/kerner/Desktop/ref.new");
try {
final GFF3File f2 = GFF3FileImpl.convertFromGFF(f);
final NewGFFFile f4 = new GFF3ConverterImpl().convert(f2);
f4.write(f3);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GFFFormatErrorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| Java |
package de.mpg.mpiz.koeln.anna.step.conrad.data.adapter;
import de.bioutils.gff.file.NewGFFFile;
import de.bioutils.gff3.file.GFF3File;
public interface GFF3Converter {
NewGFFFile convert(GFF3File file);
}
| Java |
package de.mpg.mpiz.koeln.anna.step.conrad.predict.lsf;
import java.io.File;
import java.util.List;
import de.kerner.commons.CommandStringBuilder;
import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher;
import de.mpg.mpiz.koeln.anna.step.common.AbstractStepProcessBuilder;
import de.mpg.mpiz.koeln.anna.step.common.lsf.LSF;
import de.mpg.mpiz.koeln.anna.step.conrad.common.AbstractConradPredictStep;
import de.mpg.mpiz.koeln.anna.step.conrad.common.ConradConstants;
/**
* @cleaned 2009-07-28
* @author Alexander Kerner
*
*/
public class PredictLSF extends AbstractConradPredictStep {
private class Process extends AbstractStepProcessBuilder {
protected Process(File executableDir, File workingDir,
LogDispatcher logger) {
super(executableDir, workingDir, logger);
}
@Override
protected List<String> getCommandList() {
final CommandStringBuilder builder = new CommandStringBuilder(
LSF.BSUB_EXE);
builder.addAllFlagCommands(LSF.getBsubFlagCommandStrings());
builder.addAllValueCommands(LSF
.getBsubValueCommandStrings(workingDir));
builder.addFlagCommand(ConradConstants.CONRAD_EXE);
builder.addFlagCommand("predict");
builder.addFlagCommand(trainingFile.getAbsolutePath());
builder.addFlagCommand(workingDir.getAbsolutePath());
// necessary, because "result" parameter will result in a file named
// result.gtf. If we here hand over "result.gtf" we later receive
// file named "result.gtf.gtf"
builder.addFlagCommand(resultFile.getParentFile().getAbsolutePath() + File.separator + "result");
return builder.getCommandList();
}
}
@Override
protected AbstractStepProcessBuilder getProcess() {
return new Process(exeDir, workingDir, logger);
}
}
| Java |
package de.mpg.mpiz.koeln.anna.step.conrad.predict.lsf;
import java.io.File;
import java.util.List;
import de.kerner.commons.CommandStringBuilder;
import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher;
import de.mpg.mpiz.koeln.anna.step.common.AbstractStepProcessBuilder;
import de.mpg.mpiz.koeln.anna.step.common.lsf.LSF;
import de.mpg.mpiz.koeln.anna.step.conrad.common.AbstractConradPredictStep;
import de.mpg.mpiz.koeln.anna.step.conrad.common.ConradConstants;
/**
* @cleaned 2009-07-28
* @author Alexander Kerner
*
*/
public class PredictLSF extends AbstractConradPredictStep {
private class Process extends AbstractStepProcessBuilder {
protected Process(File executableDir, File workingDir,
LogDispatcher logger) {
super(executableDir, workingDir, logger);
}
@Override
protected List<String> getCommandList() {
final CommandStringBuilder builder = new CommandStringBuilder(
LSF.BSUB_EXE);
builder.addAllFlagCommands(LSF.getBsubFlagCommandStrings());
builder.addAllValueCommands(LSF
.getBsubValueCommandStrings(workingDir));
builder.addFlagCommand(ConradConstants.CONRAD_EXE);
builder.addFlagCommand("predict");
builder.addFlagCommand(trainingFile.getAbsolutePath());
builder.addFlagCommand(workingDir.getAbsolutePath());
// necessary, because "result" parameter will result in a file named
// result.gtf. If we here hand over "result.gtf" we later receive
// file named "result.gtf.gtf"
builder.addFlagCommand(resultFile.getParentFile().getAbsolutePath() + File.separator + "result");
return builder.getCommandList();
}
}
@Override
protected AbstractStepProcessBuilder getProcess() {
return new Process(exeDir, workingDir, logger);
}
}
| Java |
package de.mpg.mpiz.koeln.anna.step.common.lsf;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author Alexander Kerner
* @ThreadSave stateless
* @lastVisit 2009-08-12
* @Exceptions nothing to do
*
*/
public class LSF {
public final static String BSUB_EXE = "bsub";
private LSF(){}
public static Map<String, String> getBsubValueCommandStrings(File workingDir) {
final File LSFout = new File(workingDir, "lsf-%J-%I.out");
final File LSFerr = new File(workingDir, "lsf-%J-%I.err");
final Map<String, String> map = new HashMap<String,String>();
// map.put("-m", "pcbcn64");
map.put("-m", "pcbcomputenodes");
// map.put("-R", "rusage[mem=4000:swp=2000]");
map.put("-R", "rusage[mem=4000]");
map.put("-eo", LSFerr.getAbsolutePath());
map.put("-oo", LSFout.getAbsolutePath());
return map;
}
public static List<String> getBsubFlagCommandStrings() {
final List<String> list = new ArrayList<String>();
list.add("-K");
return list;
}
}
| Java |
package de.mpg.mpiz.koeln.anna.step.common.lsf;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author Alexander Kerner
* @ThreadSave stateless
* @lastVisit 2009-08-12
* @Exceptions nothing to do
*
*/
public class LSF {
public final static String BSUB_EXE = "bsub";
private LSF(){}
public static Map<String, String> getBsubValueCommandStrings(File workingDir) {
final File LSFout = new File(workingDir, "lsf-%J-%I.out");
final File LSFerr = new File(workingDir, "lsf-%J-%I.err");
final Map<String, String> map = new HashMap<String,String>();
// map.put("-m", "pcbcn64");
map.put("-m", "pcbcomputenodes");
// map.put("-R", "rusage[mem=4000:swp=2000]");
map.put("-R", "rusage[mem=4000]");
map.put("-eo", LSFerr.getAbsolutePath());
map.put("-oo", LSFout.getAbsolutePath());
return map;
}
public static List<String> getBsubFlagCommandStrings() {
final List<String> list = new ArrayList<String>();
list.add("-K");
return list;
}
}
| Java |
package de.mpg.mpiz.koeln.anna.step.getresults;
import de.mpg.mpiz.koeln.anna.abstractstep.AbstractGFF3AnnaStep;
import de.mpg.mpiz.koeln.anna.server.data.GFF3DataBean;
import de.mpg.mpiz.koeln.anna.server.dataproxy.DataProxy;
import de.mpg.mpiz.koeln.anna.step.common.StepExecutionException;
public class GetResults extends AbstractGFF3AnnaStep {
@Override
public boolean canBeSkipped(DataProxy<GFF3DataBean> proxy)
throws StepExecutionException {
return false;
}
@Override
public boolean requirementsSatisfied(DataProxy<GFF3DataBean> proxy)
throws StepExecutionException {
return true;
}
@Override
public boolean run(DataProxy<GFF3DataBean> proxy)
throws StepExecutionException {
logger.debug(this, "IM RUNNING!!");
return false;
}
public boolean isCyclic() {
return true;
}
@Override
public String toString() {
return this.getClass().getSimpleName();
}
}
| Java |
package de.mpg.mpiz.koeln.anna.step.getresults;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import de.bioutils.gff3.element.GFF3Element;
import de.bioutils.gff3.file.GFF3FileImpl;
import de.kerner.commons.file.FileUtils;
import de.mpg.mpiz.koeln.anna.abstractstep.AbstractGFF3AnnaStep;
import de.mpg.mpiz.koeln.anna.server.data.DataBeanAccessException;
import de.mpg.mpiz.koeln.anna.server.data.GFF3DataBean;
import de.mpg.mpiz.koeln.anna.server.dataproxy.DataProxy;
import de.mpg.mpiz.koeln.anna.step.common.StepExecutionException;
import de.mpg.mpiz.koeln.anna.step.common.StepUtils;
public class GetResults extends AbstractGFF3AnnaStep {
private final static String OUT_DIR_KEY = "anna.step.getResults.outDir";
private final static String OUT_FILE_NAME_KEY = "anna.step.getResults.fileName";
@Override
public boolean run(DataProxy<GFF3DataBean> proxy)
throws StepExecutionException {
boolean success = false;
final File outDir = new File(super.getStepProperties().getProperty(
OUT_DIR_KEY));
logger.debug(this, "got outdir=" + outDir);
success = FileUtils.dirCheck(outDir, true);
try {
writeFile(outDir, proxy);
} catch (Exception e) {
StepUtils.handleException(this, e);
}
return success;
}
private void writeFile(File outDir, DataProxy<GFF3DataBean> proxy)
throws DataBeanAccessException, IOException {
logger.debug(this, "retrieving GFF for predicted genes");
final Collection<GFF3Element> predicted = proxy.viewData()
.getPredictedGenesGFF();
logger.debug(this, "retrieving GFF for predicted genes done (elements="
+ predicted.size() + ")");
logger.debug(this, "retrieving GFF for repetetive elements");
final Collection<GFF3Element> repeat = proxy.viewData()
.getRepeatMaskerGFF();
logger.debug(this,
"retrieving GFF for repetetive elements done (elements="
+ repeat.size() + ")");
logger.debug(this, "merging");
final Collection<GFF3Element> merged = new ArrayList<GFF3Element>();
if(predicted.size() != 0)
merged.addAll(predicted);
if(repeat.size() != 0)
merged.addAll(repeat);
logger.debug(this, "merging done (elements="
+ merged.size() + ")");
if(merged.size() == 0){
logger.debug(this, "nothing to write");
return;
}
final File outFile = new File(outDir, super.getStepProperties()
.getProperty(OUT_FILE_NAME_KEY));
logger.info(this, "writing results to " + outFile);
new GFF3FileImpl(merged).write(outFile);
logger.debug(this, "done writing results to " + outFile);
}
@Override
public boolean canBeSkipped(DataProxy<GFF3DataBean> proxy)
throws StepExecutionException {
return false;
}
@Override
public boolean requirementsSatisfied(DataProxy<GFF3DataBean> proxy)
throws StepExecutionException {
return true;
}
public boolean isCyclic() {
return true;
}
@Override
public String toString() {
return this.getClass().getSimpleName();
}
}
| Java |
package de.mpg.mpiz.koeln.anna.step.repeatmasker.lsf;
import java.io.File;
import java.util.List;
import de.kerner.commons.CommandStringBuilder;
import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher;
import de.mpg.mpiz.koeln.anna.step.common.AbstractStepProcessBuilder;
import de.mpg.mpiz.koeln.anna.step.common.lsf.LSF;
import de.mpg.mpiz.koeln.anna.step.repeatmasker.common.AbstractStepRepeatMasker;
import de.mpg.mpiz.koeln.anna.step.repeatmasker.common.RepeatMaskerConstants;
public class RepeatMaskerLSF extends AbstractStepRepeatMasker {
private class Process extends AbstractStepProcessBuilder {
private final File inFile;
protected Process(File executableDir, File stepWorkingDir,
LogDispatcher logger, File inFile) {
super(executableDir, stepWorkingDir, logger);
this.inFile = inFile;
}
public String toString() {
return this.getClass().getSimpleName();
}
@Override
protected List<String> getCommandList() {
final CommandStringBuilder builder = new CommandStringBuilder(LSF.BSUB_EXE);
builder.addAllFlagCommands(LSF.getBsubFlagCommandStrings());
builder.addAllValueCommands(LSF.getBsubValueCommandStrings(workingDir));
builder.addFlagCommand(new File(
executableDir, RepeatMaskerConstants.EXE).getAbsolutePath());
// builder.addAllFlagCommands("-s");
builder.addFlagCommand("-gff");
builder.addFlagCommand(inFile.getAbsolutePath());
return builder.getCommandList();
}
}
@Override
protected AbstractStepProcessBuilder getProcess(File inFile) {
return new Process(exeDir, workingDir
, logger, inFile);
}
}
| Java |
package de.mpg.mpiz.koeln.anna.step.repeatmasker.lsf;
import java.io.File;
import java.util.List;
import de.kerner.commons.CommandStringBuilder;
import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher;
import de.mpg.mpiz.koeln.anna.step.common.AbstractStepProcessBuilder;
import de.mpg.mpiz.koeln.anna.step.common.lsf.LSF;
import de.mpg.mpiz.koeln.anna.step.repeatmasker.common.AbstractStepRepeatMasker;
import de.mpg.mpiz.koeln.anna.step.repeatmasker.common.RepeatMaskerConstants;
public class RepeatMaskerLSF extends AbstractStepRepeatMasker {
private class Process extends AbstractStepProcessBuilder {
private final File inFile;
protected Process(File executableDir, File stepWorkingDir,
LogDispatcher logger, File inFile) {
super(executableDir, stepWorkingDir, logger);
this.inFile = inFile;
}
public String toString() {
return this.getClass().getSimpleName();
}
@Override
protected List<String> getCommandList() {
final CommandStringBuilder builder = new CommandStringBuilder(LSF.BSUB_EXE);
builder.addAllFlagCommands(LSF.getBsubFlagCommandStrings());
builder.addAllValueCommands(LSF.getBsubValueCommandStrings(workingDir));
builder.addFlagCommand(new File(
executableDir, RepeatMaskerConstants.EXE).getAbsolutePath());
// builder.addAllFlagCommands("-s");
builder.addFlagCommand("-gff");
builder.addFlagCommand(inFile.getAbsolutePath());
return builder.getCommandList();
}
}
@Override
protected AbstractStepProcessBuilder getProcess(File inFile) {
return new Process(exeDir, workingDir
, logger, inFile);
}
}
| Java |
package de.mpg.mpiz.koeln.anna.step.inputsequencereader;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import de.bioutils.fasta.FASTAElement;
import de.bioutils.fasta.NewFASTAFileImpl;
import de.mpg.mpiz.koeln.anna.abstractstep.AbstractGFF3AnnaStep;
import de.mpg.mpiz.koeln.anna.server.data.GFF3DataBean;
import de.mpg.mpiz.koeln.anna.server.dataproxy.DataModifier;
import de.mpg.mpiz.koeln.anna.server.dataproxy.DataProxy;
import de.mpg.mpiz.koeln.anna.step.common.StepExecutionException;
import de.mpg.mpiz.koeln.anna.step.common.StepUtils;
public class InputSequenceReader extends AbstractGFF3AnnaStep {
private final static String INFILE_KEY = "anna.step.inputsequencereader.infile";
public boolean requirementsSatisfied(DataProxy<GFF3DataBean> data)
throws StepExecutionException {
logger.debug(this, "no requirements needed");
return true;
}
public boolean canBeSkipped(DataProxy<GFF3DataBean> data) throws StepExecutionException {
try {
final boolean inputSequences = (data.viewData().getInputSequence() != null);
final boolean inputSequencesSize = (data.viewData().getInputSequence().size() != 0);
logger.debug(this, "need to run:");
logger.debug(this, "\tinputSequences=" + inputSequences);
logger.debug(this, "\tinputSequencesSize=" + inputSequencesSize);
return (inputSequences && inputSequencesSize);
} catch (Exception e) {
StepUtils.handleException(this, e, logger);
// cannot be reached
return false;
}
}
public boolean run(DataProxy<GFF3DataBean> data)
throws StepExecutionException {
try {
final File inFile = new File(getStepProperties().getProperty(
INFILE_KEY));
logger.debug(this, "reading file " + inFile);
final Collection<? extends FASTAElement> fastas = NewFASTAFileImpl.parse(inFile).getElements();
if (fastas == null || fastas.size() == 0) {
logger.warn(this, "file " + inFile + " is invalid");
return false;
}
logger.debug(this, "got input sequences:"
+ fastas.iterator().next().getHeader() + " [...]");
data.modifiyData(new DataModifier<GFF3DataBean>() {
public void modifiyData(GFF3DataBean v) {
v.setInputSequence(new ArrayList<FASTAElement>(fastas));
}
});
return true;
} catch (Exception e) {
StepUtils.handleException(this, e, logger);
// cannot be reached
return false;
}
}
@Override
public String toString() {
return this.getClass().getSimpleName();
}
public boolean isCyclic() {
return false;
}
}
| Java |
package de.mpg.mpiz.koeln.anna.step.inputsequencereader;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import de.bioutils.fasta.FASTAElement;
import de.bioutils.fasta.NewFASTAFileImpl;
import de.mpg.mpiz.koeln.anna.abstractstep.AbstractGFF3AnnaStep;
import de.mpg.mpiz.koeln.anna.server.data.GFF3DataBean;
import de.mpg.mpiz.koeln.anna.server.dataproxy.DataModifier;
import de.mpg.mpiz.koeln.anna.server.dataproxy.DataProxy;
import de.mpg.mpiz.koeln.anna.step.common.StepExecutionException;
import de.mpg.mpiz.koeln.anna.step.common.StepUtils;
public class InputSequenceReader extends AbstractGFF3AnnaStep {
private final static String INFILE_KEY = "anna.step.inputsequencereader.infile";
public boolean requirementsSatisfied(DataProxy<GFF3DataBean> data)
throws StepExecutionException {
logger.debug(this, "no requirements needed");
return true;
}
public boolean canBeSkipped(DataProxy<GFF3DataBean> data) throws StepExecutionException {
try {
final boolean inputSequences = (data.viewData().getInputSequence() != null);
final boolean inputSequencesSize = (data.viewData().getInputSequence().size() != 0);
logger.debug(this, "need to run:");
logger.debug(this, "\tinputSequences=" + inputSequences);
logger.debug(this, "\tinputSequencesSize=" + inputSequencesSize);
return (inputSequences && inputSequencesSize);
} catch (Exception e) {
StepUtils.handleException(this, e, logger);
// cannot be reached
return false;
}
}
public boolean run(DataProxy<GFF3DataBean> data)
throws StepExecutionException {
try {
final File inFile = new File(getStepProperties().getProperty(
INFILE_KEY));
logger.debug(this, "reading file " + inFile);
final Collection<? extends FASTAElement> fastas = NewFASTAFileImpl.parse(inFile).getElements();
if (fastas == null || fastas.size() == 0) {
logger.warn(this, "file " + inFile + " is invalid");
return false;
}
logger.debug(this, "got input sequences:"
+ fastas.iterator().next().getHeader() + " [...]");
data.modifiyData(new DataModifier<GFF3DataBean>() {
public void modifiyData(GFF3DataBean v) {
v.setInputSequence(new ArrayList<FASTAElement>(fastas));
}
});
return true;
} catch (Exception e) {
StepUtils.handleException(this, e, logger);
// cannot be reached
return false;
}
}
@Override
public String toString() {
return this.getClass().getSimpleName();
}
public boolean isCyclic() {
return false;
}
}
| Java |
package de.mpg.mpiz.koeln.anna.step.repeatmasker.common;
public class RepeatMaskerConstants {
private RepeatMaskerConstants(){}
public final static String WORKING_DIR_KEY = "anna.step.repeatMasker.workingDir";
public final static String EXE_DIR_KEY = "anna.step.repeatMasker.exeDir";
public final static String TMP_FILENAME = "repMask";
public final static String OUTFILE_POSTFIX = ".out.gff";
public final static String EXE = "RepeatMasker";
}
| Java |
package de.mpg.mpiz.koeln.anna.step.repeatmasker.common;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.osgi.framework.BundleContext;
import de.bioutils.fasta.NewFASTAFileImpl;
import de.bioutils.gff.GFFFormatErrorException;
import de.bioutils.gff.element.NewGFFElement;
import de.bioutils.gff.file.NewGFFFileImpl;
import de.kerner.commons.file.FileUtils;
import de.mpg.mpiz.koeln.anna.abstractstep.AbstractGFF3AnnaStep;
import de.mpg.mpiz.koeln.anna.server.data.DataBeanAccessException;
import de.mpg.mpiz.koeln.anna.server.data.GFF3DataBean;
import de.mpg.mpiz.koeln.anna.server.dataproxy.DataModifier;
import de.mpg.mpiz.koeln.anna.server.dataproxy.DataProxy;
import de.mpg.mpiz.koeln.anna.step.common.AbstractStepProcessBuilder;
import de.mpg.mpiz.koeln.anna.step.common.StepExecutionException;
import de.mpg.mpiz.koeln.anna.step.common.StepUtils;
public abstract class AbstractStepRepeatMasker extends AbstractGFF3AnnaStep {
protected File exeDir;
protected File workingDir;
@Override
public String toString() {
return this.getClass().getSimpleName();
}
@Override
protected synchronized void init(BundleContext context) throws StepExecutionException {
super.init(context);
assignProperties();
validateProperties();
printProperties();
}
private void assignProperties() {
exeDir = new File(getStepProperties().getProperty(RepeatMaskerConstants.EXE_DIR_KEY));
workingDir = new File(getStepProperties().getProperty(RepeatMaskerConstants.WORKING_DIR_KEY));
}
private void validateProperties() throws StepExecutionException {
if (!FileUtils.dirCheck(exeDir, false))
throw new StepExecutionException(
"cannot access repeatmasker working dir");
if (!FileUtils.dirCheck(workingDir, true))
throw new StepExecutionException("cannot access step working dir");
}
private void printProperties() {
logger.debug(this, " created, properties:");
logger.debug(this, "\tstepWorkingDir=" + workingDir);
logger.debug(this, "\texeDir=" + exeDir);
}
public boolean canBeSkipped(DataProxy<GFF3DataBean> data)
throws StepExecutionException {
try {
// must this two actions be atomar?
final boolean repeatGtf = (data.viewData().getRepeatMaskerGFF() != null);
final boolean repeatGtfSize = (data.viewData()
.getRepeatMaskerGFF().size() != 0);
return (repeatGtf && repeatGtfSize);
} catch (Throwable t) {
StepUtils.handleException(this, t, logger);
// cannot be reached
return false;
}
}
public boolean requirementsSatisfied(DataProxy<GFF3DataBean> data)
throws StepExecutionException {
try {
// must this two actions be atomar?
final boolean sequence = (data.viewData().getInputSequence() != null);
final boolean sequenceSize = (data.viewData()
.getInputSequence().size() != 0);
return (sequence && sequenceSize);
} catch (Throwable t) {
StepUtils.handleException(this, t, logger);
// cannot be reached
return false;
}
}
public boolean run(DataProxy<GFF3DataBean> data)
throws StepExecutionException {
logger.debug(this, "running");
final File inFile = new File(workingDir, RepeatMaskerConstants.TMP_FILENAME);
final File outFile = new File(workingDir, RepeatMaskerConstants.TMP_FILENAME
+ RepeatMaskerConstants.OUTFILE_POSTFIX);
logger.debug(this, "inFile="+inFile);
logger.debug(this, "outFile="+outFile);
final AbstractStepProcessBuilder worker = getProcess(inFile);
boolean success = true;
try{
new NewFASTAFileImpl(data.viewData().getInputSequence())
.write(inFile);
worker.addResultFile(true, outFile);
success = worker.createAndStartProcess();
if (success) {
update(data, outFile);
}
} catch (Throwable t) {
StepUtils.handleException(this, t, logger);
// cannot be reached
return false;
}
return success;
}
private void update(DataProxy<GFF3DataBean> data, final File outFile) throws DataBeanAccessException, IOException, GFFFormatErrorException{
logger.debug(this, "updating data");
final ArrayList<NewGFFElement> result = new ArrayList<NewGFFElement>();
result.addAll(NewGFFFileImpl.parseFile(outFile).getElements());
data.modifiyData(new DataModifier<GFF3DataBean>() {
public void modifiyData(GFF3DataBean v) {
v.setRepeatMaskerGFF(result);
}
});
}
public boolean isCyclic() {
return false;
}
protected abstract AbstractStepProcessBuilder getProcess(File inFile);
}
| Java |
package de.mpg.mpiz.koeln.anna.step.repeatmasker.common;
public class RepeatMaskerConstants {
private RepeatMaskerConstants(){}
public final static String WORKING_DIR_KEY = "anna.step.repeatMasker.workingDir";
public final static String EXE_DIR_KEY = "anna.step.repeatMasker.exeDir";
public final static String TMP_FILENAME = "repMask";
public final static String OUTFILE_POSTFIX = ".out.gff";
public final static String EXE = "RepeatMasker";
}
| Java |
package de.mpg.mpiz.koeln.anna.step.repeatmasker.common;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import org.osgi.framework.BundleContext;
import de.bioutils.fasta.NewFASTAFileImpl;
import de.bioutils.gff.GFFFormatErrorException;
import de.bioutils.gff3.element.GFF3Element;
import de.bioutils.gff3.file.GFF3FileImpl;
import de.kerner.commons.file.FileUtils;
import de.mpg.mpiz.koeln.anna.abstractstep.AbstractGFF3AnnaStep;
import de.mpg.mpiz.koeln.anna.server.data.DataBeanAccessException;
import de.mpg.mpiz.koeln.anna.server.data.GFF3DataBean;
import de.mpg.mpiz.koeln.anna.server.dataproxy.DataModifier;
import de.mpg.mpiz.koeln.anna.server.dataproxy.DataProxy;
import de.mpg.mpiz.koeln.anna.step.common.AbstractStepProcessBuilder;
import de.mpg.mpiz.koeln.anna.step.common.StepExecutionException;
import de.mpg.mpiz.koeln.anna.step.common.StepUtils;
import de.mpg.mpiz.koeln.anna.step.repeatmasker.adapter.ResultsPreprocessor;
public abstract class AbstractStepRepeatMasker extends AbstractGFF3AnnaStep {
protected File exeDir;
protected File workingDir;
@Override
public String toString() {
return this.getClass().getSimpleName();
}
@Override
protected synchronized void init(BundleContext context) throws StepExecutionException {
super.init(context);
assignProperties();
validateProperties();
printProperties();
}
private void assignProperties() {
exeDir = new File(getStepProperties().getProperty(RepeatMaskerConstants.EXE_DIR_KEY));
workingDir = new File(getStepProperties().getProperty(RepeatMaskerConstants.WORKING_DIR_KEY));
}
private void validateProperties() throws StepExecutionException {
if (!FileUtils.dirCheck(exeDir, false))
throw new StepExecutionException(
"cannot access repeatmasker working dir");
if (!FileUtils.dirCheck(workingDir, true))
throw new StepExecutionException("cannot access step working dir");
}
private void printProperties() {
logger.debug(this, " created, properties:");
logger.debug(this, "\tstepWorkingDir=" + workingDir);
logger.debug(this, "\texeDir=" + exeDir);
}
public boolean canBeSkipped(DataProxy<GFF3DataBean> data)
throws StepExecutionException {
try {
// must this two actions be atomar?
final boolean repeatGtf = (data.viewData().getRepeatMaskerGFF() != null);
final boolean repeatGtfSize = (data.viewData()
.getRepeatMaskerGFF().size() != 0);
return (repeatGtf && repeatGtfSize);
} catch (Throwable t) {
StepUtils.handleException(this, t, logger);
// cannot be reached
return false;
}
}
public boolean requirementsSatisfied(DataProxy<GFF3DataBean> data)
throws StepExecutionException {
try {
// must this two actions be atomar?
final boolean sequence = (data.viewData().getInputSequence() != null);
final boolean sequenceSize = (data.viewData()
.getInputSequence().size() != 0);
return (sequence && sequenceSize);
} catch (Throwable t) {
StepUtils.handleException(this, t, logger);
// cannot be reached
return false;
}
}
public boolean run(DataProxy<GFF3DataBean> data)
throws StepExecutionException {
logger.debug(this, "running");
final File inFile = new File(workingDir, RepeatMaskerConstants.TMP_FILENAME);
final File outFile = new File(workingDir, RepeatMaskerConstants.TMP_FILENAME
+ RepeatMaskerConstants.OUTFILE_POSTFIX);
logger.debug(this, "inFile="+inFile);
logger.debug(this, "outFile="+outFile);
final AbstractStepProcessBuilder worker = getProcess(inFile);
boolean success = true;
try{
new NewFASTAFileImpl(data.viewData().getInputSequence())
.write(inFile);
worker.addResultFile(true, outFile);
success = worker.createAndStartProcess();
if (success) {
update(data, outFile);
}
} catch (Throwable t) {
StepUtils.handleException(this, t, logger);
// cannot be reached
return false;
}
return success;
}
private void update(DataProxy<GFF3DataBean> data, final File outFile) throws DataBeanAccessException, IOException, GFFFormatErrorException{
logger.debug(this, "updating data");
final ArrayList<GFF3Element> result = new ArrayList<GFF3Element>();
new ResultsPreprocessor().process(outFile, outFile);
result.addAll(GFF3FileImpl.convertFromGFF(outFile).getElements());
data.modifiyData(new DataModifier<GFF3DataBean>() {
public void modifiyData(GFF3DataBean v) {
v.setRepeatMaskerGFF(result);
}
});
}
public boolean isCyclic() {
return false;
}
protected abstract AbstractStepProcessBuilder getProcess(File inFile);
}
| Java |
package de.mpg.mpiz.koeln.anna.server.dataproxy;
public interface DataModifier<V> {
void modifiyData(V v);
}
| Java |
package de.mpg.mpiz.koeln.anna.server.dataproxy;
import de.mpg.mpiz.koeln.anna.server.data.DataBeanAccessException;
public interface DataProxy<V> {
/**
*
* <p>
* Atomar operation on data. Data will be synchronized bevor and after this
* operation.
* </p>
*
* @param v
* Type of Data, that is accessed.
* @throws DataBeanAccessException
*/
void modifiyData(DataModifier<V> v) throws DataBeanAccessException;
/**
*
* <p>
* Use this method for reading data only. If you make changes to the data
* you get from this method, these changes will not be synchronized! If you
* want to write data, use {@link modifiyData()} instead.
*
* @return the data object.
* @throws DataBeanAccessException
*/
V viewData() throws DataBeanAccessException;
}
| Java |
package de.mpg.mpiz.koeln.anna.server.dataproxy.impl;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.StreamCorruptedException;
import de.kerner.osgi.commons.logger.dispatcher.ConsoleLogger;
import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher;
import de.mpg.mpiz.koeln.anna.server.data.DataBean;
import de.mpg.mpiz.koeln.anna.server.data.DataBeanAccessException;
/**
*
* @author Alexander Kerner
* @lastVisit 2009-09-21
*
*/
abstract class AbstractDiskSerialisation implements SerialisationStrategy {
protected final LogDispatcher logger;
AbstractDiskSerialisation() {
this.logger = new ConsoleLogger();
}
AbstractDiskSerialisation(LogDispatcher logger) {
this.logger = logger;
}
protected void objectToFile(Serializable s, File file) throws IOException {
if (s == null || file == null)
throw new NullPointerException(s + " + " + file
+ " must not be null");
OutputStream fos = null;
ObjectOutputStream outStream = null;
try {
fos = new FileOutputStream(file);
outStream = new ObjectOutputStream(fos);
outStream.writeObject(s);
} finally {
if (outStream != null)
outStream.close();
if (fos != null)
fos.close();
}
}
protected <V> V fileToObject(Class<V> c, File file) throws IOException,
ClassNotFoundException {
if (c == null || file == null)
throw new NullPointerException(c + " + " + file
+ " must not be null");
InputStream fis = null;
ObjectInputStream inStream = null;
try {
fis = new FileInputStream(file);
inStream = new ObjectInputStream(fis);
V v = c.cast(inStream.readObject());
return v;
} finally {
if (inStream != null)
inStream.close();
if (fis != null)
fis.close();
}
}
protected <V extends DataBean> V handleCorruptData(File file, Throwable t) {
logger.warn(this, file.toString() + " corrupt, returning new one");
if (file.delete()) {
logger.info(this, "deleted corrupted data");
} else {
logger.warn(this, "could not delete corrupt data " + file);
}
return getNewDataBean();
}
public synchronized <V extends DataBean> V readDataBean(File file,
Class<V> v) throws DataBeanAccessException {
try {
final V data = fileToObject(v, file);
logger.debug(this, "reading data from file");
return data;
} catch (EOFException e) {
logger.warn(this, e.getLocalizedMessage(), e);
return handleCorruptData(file, e);
} catch (StreamCorruptedException e) {
logger.warn(this, e.getLocalizedMessage(), e);
return handleCorruptData(file, e);
} catch (Throwable t) {
logger.error(this, t.getLocalizedMessage(), t);
throw new DataBeanAccessException(t);
}
}
public synchronized <V extends DataBean> void writeDataBean(V v, File file)
throws DataBeanAccessException {
try {
logger.debug(this, "writing data to file");
objectToFile(v, file);
} catch (IOException e) {
logger.error(this, e.toString(), e);
throw new DataBeanAccessException(e);
}
}
}
| Java |
package de.mpg.mpiz.koeln.anna.server.dataproxy.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import de.kerner.commons.file.FileUtils;
import de.kerner.osgi.commons.logger.dispatcher.ConsoleLogger;
import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher;
import de.mpg.mpiz.koeln.anna.server.data.DataBeanAccessException;
import de.mpg.mpiz.koeln.anna.server.data.GFF3DataBean;
import de.mpg.mpiz.koeln.anna.server.dataproxy.DataModifier;
import de.mpg.mpiz.koeln.anna.server.dataproxy.GFF3DataProxy;
/**
*
* @author Alexander Kerner
* @lastVisit 2009-09-21
*
*/
public class GFF3DataProxyImpl implements GFF3DataProxy{
final static String WORKING_DIR_KEY = "anna.server.data.workingDir";
final static File PROPERTIES_FILE = new File(FileUtils.WORKING_DIR,
"configuration" + File.separatorChar + "data.properties");
final static String DATA_FILE_NAME = "data.ser";
private final SerialisationStrategy strategy;
private final Properties properties;
private final File workingDir;
private final File file;
private final LogDispatcher logger;
public GFF3DataProxyImpl(final SerialisationStrategy strategy) throws FileNotFoundException {
this.strategy = strategy;
this.logger = new ConsoleLogger();
properties = getPropertes();
workingDir = new File(properties.getProperty(WORKING_DIR_KEY));
if(!FileUtils.dirCheck(workingDir, true)){
final FileNotFoundException e = new FileNotFoundException("cannot access working dir " + workingDir);
logger.error(this, e, e);
throw e;
}
file = new File(workingDir, DATA_FILE_NAME);
printProperties();
}
public GFF3DataProxyImpl() throws FileNotFoundException {
this.strategy = new CachedDiskSerialisation();
properties = getPropertes();
this.logger = new ConsoleLogger();
workingDir = new File(properties.getProperty(WORKING_DIR_KEY));
if(!FileUtils.dirCheck(workingDir, true)){
final FileNotFoundException e = new FileNotFoundException("cannot access working dir " + workingDir);
logger.error(this, e, e);
throw e;
}
file = new File(workingDir, DATA_FILE_NAME);
printProperties();
}
private GFF3DataBean getData() throws DataBeanAccessException {
if(!FileUtils.fileCheck(file, false)){
logger.info(this, "file " + file + " not there, creating new data");
return strategy.getNewDataBean();
}
return strategy.readDataBean(file, GFF3DataBean.class);
}
private void setData(GFF3DataBean data) throws DataBeanAccessException {
strategy.writeDataBean(data, file);
}
public synchronized void modifiyData(DataModifier<GFF3DataBean> v)
throws DataBeanAccessException {
final GFF3DataBean data = getData();
v.modifiyData(data);
setData(data);
}
public GFF3DataBean viewData() throws DataBeanAccessException {
return getData();
}
@Override
public String toString() {
return this.getClass().getSimpleName();
}
private void printProperties() {
logger.debug(this, " created, properties:");
logger.debug(this, "\tdatafile=" + file);
}
private Properties getPropertes() {
final Properties defaultProperties = initDefaults();
final Properties pro = new Properties(defaultProperties);
try {
System.out.println(this + ": loading settings from "
+ PROPERTIES_FILE);
final FileInputStream fi = new FileInputStream(PROPERTIES_FILE);
pro.load(fi);
fi.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println(this + ": could not load settings from "
+ PROPERTIES_FILE.getAbsolutePath() + ", using defaults");
} catch (IOException e) {
e.printStackTrace();
System.out.println(this + ": could not load settings from "
+ PROPERTIES_FILE.getAbsolutePath() + ", using defaults");
}
return pro;
}
private Properties initDefaults() {
Properties pro = new Properties();
return pro;
}
}
| Java |
package de.mpg.mpiz.koeln.anna.server.dataproxy.impl;
import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher;
import de.mpg.mpiz.koeln.anna.server.data.DataBean;
import de.mpg.mpiz.koeln.anna.server.data.impl.GFF3DataBeanImpl;
public class GFF3DiskSerialisation extends AbstractDiskSerialisation {
protected volatile DataBean data = new GFF3DataBeanImpl();
GFF3DiskSerialisation() {
super();
}
GFF3DiskSerialisation(LogDispatcher logger) {
super(logger);
}
@SuppressWarnings("unchecked")
public <V extends DataBean> V getNewDataBean() {
// TODO: WHY CAST ?!?
return (V) new GFF3DataBeanImpl();
}
}
| Java |
package de.mpg.mpiz.koeln.anna.server.dataproxy.impl;
import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher;
public class SimpleDiskSerialisation extends GFF3DiskSerialisation {
public SimpleDiskSerialisation() {
super();
}
public SimpleDiskSerialisation(LogDispatcher logger) {
super(logger);
}
@Override
public String toString() {
return this.getClass().getSimpleName();
}
}
| Java |
package de.mpg.mpiz.koeln.anna.server.dataproxy.impl;
import java.util.Hashtable;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher;
import de.kerner.osgi.commons.logger.dispatcher.LogDispatcherImpl;
import de.mpg.mpiz.koeln.anna.server.dataproxy.GFF3DataProxy;
/**
*
* @author Alexander Kerner
* @lastVisit 2009-09-21
*
*/
public class GFF3DataProxyActivator implements BundleActivator {
private LogDispatcher logger = null;
public void start(BundleContext context) throws Exception {
logger = new LogDispatcherImpl(context);
GFF3DataProxy proxy = new GFF3DataProxyImpl(new CachedDiskSerialisation(logger));
context.registerService(GFF3DataProxy.class.getName(), proxy,
new Hashtable<Object, Object>());
}
public void stop(BundleContext context) throws Exception {
logger.debug(this, "service stopped!");
logger = null;
}
public String toString() {
return this.getClass().getSimpleName();
}
}
| Java |
package de.mpg.mpiz.koeln.anna.server.dataproxy.impl;
import java.io.File;
import de.mpg.mpiz.koeln.anna.server.data.DataBean;
import de.mpg.mpiz.koeln.anna.server.data.DataBeanAccessException;
/**
*
* @author Alexander Kerner
* @lastVisit 2009-09-21
*
*/
interface SerialisationStrategy {
<V extends DataBean> V readDataBean(File file, Class<V> v) throws DataBeanAccessException;
<V extends DataBean> void writeDataBean(V v, File file)
throws DataBeanAccessException;
<V extends DataBean> V getNewDataBean();
}
| Java |
package de.mpg.mpiz.koeln.anna.server.dataproxy.impl;
import java.io.File;
import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher;
import de.mpg.mpiz.koeln.anna.server.data.DataBean;
import de.mpg.mpiz.koeln.anna.server.data.DataBeanAccessException;
/**
*
* @author Alexander Kerner
* @lastVisit 2009-09-21
*
*/
class CachedDiskSerialisation extends GFF3DiskSerialisation {
CachedDiskSerialisation() {
super();
}
CachedDiskSerialisation(LogDispatcher logger) {
super(logger);
}
private volatile boolean dirty = false;
@SuppressWarnings("unchecked")
@Override
public synchronized <V extends DataBean> V readDataBean(File file,
Class<V> v) throws DataBeanAccessException {
if (dirty) {
logger.debug(this, "data dirty, reading from disk");
data = super.readDataBean(file, v);
dirty = false;
} else {
logger.debug(this, "reading data from cache");
}
return (V) data;
}
public synchronized <V extends DataBean> void writeDataBean(V v, File file)
throws DataBeanAccessException {
this.dirty = true;
logger.debug(this, "writing data");
super.writeDataBean(v, file);
}
@Override
public String toString() {
return this.getClass().getSimpleName();
}
}
| Java |
package de.mpg.mpiz.koeln.anna.server.dataproxy;
import de.mpg.mpiz.koeln.anna.server.data.GFF3DataBean;
public interface GFF3DataProxy extends DataProxy<GFF3DataBean>{
}
| Java |
package de.mpg.mpiz.koeln.anna.server.dataproxy;
public interface DataModifier<V> {
void modifiyData(V v);
}
| Java |
package de.mpg.mpiz.koeln.anna.server.dataproxy;
import de.mpg.mpiz.koeln.anna.server.data.DataBeanAccessException;
public interface DataProxy<V> {
/**
*
* <p>
* Atomar operation on data. Data will be synchronized bevor and after this
* operation.
* </p>
*
* @param v
* Type of Data, that is accessed.
* @throws DataBeanAccessException
*/
void modifiyData(DataModifier<V> v) throws DataBeanAccessException;
/**
*
* <p>
* Use this method for reading data only. If you make changes to the data
* you get from this method, these changes will not be synchronized! If you
* want to write data, use {@link modifiyData()} instead.
*
* @return the data object.
* @throws DataBeanAccessException
*/
V viewData() throws DataBeanAccessException;
}
| Java |
package de.mpg.mpiz.koeln.anna.server.dataproxy.impl;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.StreamCorruptedException;
import de.kerner.osgi.commons.logger.dispatcher.ConsoleLogger;
import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher;
import de.mpg.mpiz.koeln.anna.server.data.DataBean;
import de.mpg.mpiz.koeln.anna.server.data.DataBeanAccessException;
/**
*
* @author Alexander Kerner
* @lastVisit 2009-09-21
*
*/
abstract class AbstractDiskSerialisation implements SerialisationStrategy {
protected final LogDispatcher logger;
AbstractDiskSerialisation() {
this.logger = new ConsoleLogger();
}
AbstractDiskSerialisation(LogDispatcher logger) {
this.logger = logger;
}
protected void objectToFile(Serializable s, File file) throws IOException {
if (s == null || file == null)
throw new NullPointerException(s + " + " + file
+ " must not be null");
OutputStream fos = null;
ObjectOutputStream outStream = null;
try {
fos = new FileOutputStream(file);
outStream = new ObjectOutputStream(fos);
outStream.writeObject(s);
} finally {
if (outStream != null)
outStream.close();
if (fos != null)
fos.close();
}
}
protected <V> V fileToObject(Class<V> c, File file) throws IOException,
ClassNotFoundException {
if (c == null || file == null)
throw new NullPointerException(c + " + " + file
+ " must not be null");
InputStream fis = null;
ObjectInputStream inStream = null;
try {
fis = new FileInputStream(file);
inStream = new ObjectInputStream(fis);
V v = c.cast(inStream.readObject());
return v;
} finally {
if (inStream != null)
inStream.close();
if (fis != null)
fis.close();
}
}
protected <V extends DataBean> V handleCorruptData(File file, Throwable t) {
logger.warn(this, file.toString() + " corrupt, returning new one");
if (file.delete()) {
logger.info(this, "deleted corrupted data");
} else {
logger.warn(this, "could not delete corrupt data " + file);
}
return getNewDataBean();
}
public synchronized <V extends DataBean> V readDataBean(File file,
Class<V> v) throws DataBeanAccessException {
try {
final V data = fileToObject(v, file);
logger.debug(this, "reading data from file");
return data;
} catch (EOFException e) {
logger.warn(this, e.getLocalizedMessage(), e);
return handleCorruptData(file, e);
} catch (StreamCorruptedException e) {
logger.warn(this, e.getLocalizedMessage(), e);
return handleCorruptData(file, e);
} catch (Throwable t) {
logger.error(this, t.getLocalizedMessage(), t);
throw new DataBeanAccessException(t);
}
}
public synchronized <V extends DataBean> void writeDataBean(V v, File file)
throws DataBeanAccessException {
try {
logger.debug(this, "writing data to file");
objectToFile(v, file);
} catch (IOException e) {
logger.error(this, e.toString(), e);
throw new DataBeanAccessException(e);
}
}
}
| Java |
package de.mpg.mpiz.koeln.anna.server.dataproxy.impl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import de.kerner.commons.file.FileUtils;
import de.kerner.osgi.commons.logger.dispatcher.ConsoleLogger;
import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher;
import de.mpg.mpiz.koeln.anna.server.data.DataBeanAccessException;
import de.mpg.mpiz.koeln.anna.server.data.GFF3DataBean;
import de.mpg.mpiz.koeln.anna.server.dataproxy.DataModifier;
import de.mpg.mpiz.koeln.anna.server.dataproxy.GFF3DataProxy;
/**
*
* @author Alexander Kerner
* @lastVisit 2009-09-21
*
*/
public class GFF3DataProxyImpl implements GFF3DataProxy{
final static String WORKING_DIR_KEY = "anna.server.data.workingDir";
final static File PROPERTIES_FILE = new File(FileUtils.WORKING_DIR,
"configuration" + File.separatorChar + "data.properties");
final static String DATA_FILE_NAME = "data.ser";
private final SerialisationStrategy strategy;
private final Properties properties;
private final File workingDir;
private final File file;
private final LogDispatcher logger;
public GFF3DataProxyImpl(final SerialisationStrategy strategy) throws FileNotFoundException {
this.strategy = strategy;
this.logger = new ConsoleLogger();
properties = getPropertes();
workingDir = new File(properties.getProperty(WORKING_DIR_KEY));
if(!FileUtils.dirCheck(workingDir, true)){
final FileNotFoundException e = new FileNotFoundException("cannot access working dir " + workingDir);
logger.error(this, e, e);
throw e;
}
file = new File(workingDir, DATA_FILE_NAME);
printProperties();
}
public GFF3DataProxyImpl() throws FileNotFoundException {
this.strategy = new CachedDiskSerialisation();
properties = getPropertes();
this.logger = new ConsoleLogger();
workingDir = new File(properties.getProperty(WORKING_DIR_KEY));
if(!FileUtils.dirCheck(workingDir, true)){
final FileNotFoundException e = new FileNotFoundException("cannot access working dir " + workingDir);
logger.error(this, e, e);
throw e;
}
file = new File(workingDir, DATA_FILE_NAME);
printProperties();
}
private GFF3DataBean getData() throws DataBeanAccessException {
if(!FileUtils.fileCheck(file, false)){
logger.info(this, "file " + file + " not there, creating new data");
return strategy.getNewDataBean();
}
return strategy.readDataBean(file, GFF3DataBean.class);
}
private void setData(GFF3DataBean data) throws DataBeanAccessException {
strategy.writeDataBean(data, file);
}
public synchronized void modifiyData(DataModifier<GFF3DataBean> v)
throws DataBeanAccessException {
final GFF3DataBean data = getData();
v.modifiyData(data);
setData(data);
}
public GFF3DataBean viewData() throws DataBeanAccessException {
return getData();
}
@Override
public String toString() {
return this.getClass().getSimpleName();
}
private void printProperties() {
logger.debug(this, " created, properties:");
logger.debug(this, "\tdatafile=" + file);
}
private Properties getPropertes() {
final Properties defaultProperties = initDefaults();
final Properties pro = new Properties(defaultProperties);
try {
System.out.println(this + ": loading settings from "
+ PROPERTIES_FILE);
final FileInputStream fi = new FileInputStream(PROPERTIES_FILE);
pro.load(fi);
fi.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println(this + ": could not load settings from "
+ PROPERTIES_FILE.getAbsolutePath() + ", using defaults");
} catch (IOException e) {
e.printStackTrace();
System.out.println(this + ": could not load settings from "
+ PROPERTIES_FILE.getAbsolutePath() + ", using defaults");
}
return pro;
}
private Properties initDefaults() {
Properties pro = new Properties();
return pro;
}
}
| Java |
package de.mpg.mpiz.koeln.anna.server.dataproxy.impl;
import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher;
import de.mpg.mpiz.koeln.anna.server.data.DataBean;
import de.mpg.mpiz.koeln.anna.server.data.impl.GFF3DataBeanImpl;
public class GFF3DiskSerialisation extends AbstractDiskSerialisation {
protected volatile DataBean data = new GFF3DataBeanImpl();
GFF3DiskSerialisation() {
super();
}
GFF3DiskSerialisation(LogDispatcher logger) {
super(logger);
}
@SuppressWarnings("unchecked")
public <V extends DataBean> V getNewDataBean() {
// TODO: WHY CAST ?!?
return (V) new GFF3DataBeanImpl();
}
}
| Java |
package de.mpg.mpiz.koeln.anna.server.dataproxy.impl;
import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher;
public class SimpleDiskSerialisation extends GFF3DiskSerialisation {
public SimpleDiskSerialisation() {
super();
}
public SimpleDiskSerialisation(LogDispatcher logger) {
super(logger);
}
@Override
public String toString() {
return this.getClass().getSimpleName();
}
}
| Java |
package de.mpg.mpiz.koeln.anna.server.dataproxy.impl;
import java.util.Hashtable;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import de.kerner.osgi.commons.logger.dispatcher.LogDispatcher;
import de.kerner.osgi.commons.logger.dispatcher.LogDispatcherImpl;
import de.mpg.mpiz.koeln.anna.server.dataproxy.GFF3DataProxy;
/**
*
* @author Alexander Kerner
* @lastVisit 2009-09-21
*
*/
public class GFF3DataProxyActivator implements BundleActivator {
private LogDispatcher logger = null;
public void start(BundleContext context) throws Exception {
logger = new LogDispatcherImpl(context);
GFF3DataProxy proxy = new GFF3DataProxyImpl(new SimpleDiskSerialisation(logger));
context.registerService(GFF3DataProxy.class.getName(), proxy,
new Hashtable<Object, Object>());
}
public void stop(BundleContext context) throws Exception {
logger.debug(this, "service stopped!");
logger = null;
}
public String toString() {
return this.getClass().getSimpleName();
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.