code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.sh;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Mode;
import org.jdiameter.api.sh.ClientShSession;
import org.jdiameter.api.sh.ClientShSessionListener;
import org.jdiameter.api.sh.ServerShSession;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.impl.app.sh.ShSessionFactoryImpl;
import org.mobicents.diameter.stack.functional.TBase;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public abstract class AbstractClient extends TBase implements ClientShSessionListener {
// NOTE: implementing NetworkReqListener since its required for stack to
// know we support it... ech.
protected ClientShSession clientShSession;
public void init(InputStream configStream, String clientID) throws Exception {
try {
super.init(configStream, clientID, ApplicationId.createByAuthAppId(10415, 16777217));
ShSessionFactoryImpl shSessionFactory = new ShSessionFactoryImpl(this.sessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ServerShSession.class, shSessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ClientShSession.class, shSessionFactory);
shSessionFactory.setClientShSessionListener(this);
this.clientShSession = ((ISessionFactory) this.sessionFactory)
.getNewAppSession(this.sessionFactory.getSessionId("xxTESTxx"), getApplicationId(), ClientShSession.class, (Object) null);
}
finally {
try {
configStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
// ----------- delegate methods so
public void start() throws IllegalDiameterStateException, InternalException {
stack.start();
}
public void start(Mode mode, long timeOut, TimeUnit timeUnit) throws IllegalDiameterStateException, InternalException {
stack.start(mode, timeOut, timeUnit);
}
public void stop(long timeOut, TimeUnit timeUnit, int disconnectCause) throws IllegalDiameterStateException, InternalException {
stack.stop(timeOut, timeUnit, disconnectCause);
}
public void stop(int disconnectCause) {
stack.stop(disconnectCause);
}
// ----------- conf parts
public String getSessionId() {
return this.clientShSession.getSessionId();
}
public ClientShSession getSession() {
return this.clientShSession;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.sh;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Mode;
import org.jdiameter.api.sh.ClientShSession;
import org.jdiameter.api.sh.ServerShSession;
import org.jdiameter.api.sh.ServerShSessionListener;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.impl.app.sh.ShSessionFactoryImpl;
import org.mobicents.diameter.stack.functional.TBase;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public abstract class AbstractServer extends TBase implements ServerShSessionListener {
// NOTE: implementing NetworkReqListener since its required for stack to
// know we support it... ech.
protected ServerShSession serverShSession;
public void init(InputStream configStream, String clientID) throws Exception {
try {
super.init(configStream, clientID, ApplicationId.createByAuthAppId(10415, 16777217));
ShSessionFactoryImpl shSessionFactory = new ShSessionFactoryImpl(this.sessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ServerShSession.class, shSessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ClientShSession.class, shSessionFactory);
shSessionFactory.setServerShSessionListener(this);
}
finally {
try {
configStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
// ----------- delegate methods so
public void start() throws IllegalDiameterStateException, InternalException {
stack.start();
}
public void start(Mode mode, long timeOut, TimeUnit timeUnit) throws IllegalDiameterStateException, InternalException {
stack.start(mode, timeOut, timeUnit);
}
public void stop(long timeOut, TimeUnit timeUnit, int disconnectCause) throws IllegalDiameterStateException, InternalException {
stack.stop(timeOut, timeUnit, disconnectCause);
}
public void stop(int disconnectCause) {
stack.stop(disconnectCause);
}
public String getSessionId() {
return this.serverShSession.getSessionId();
}
public ServerShSession getSession() {
return this.serverShSession;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.cca.base;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.app.AppAnswerEvent;
import org.jdiameter.api.app.AppRequestEvent;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.auth.events.ReAuthRequest;
import org.jdiameter.api.cca.ClientCCASession;
import org.jdiameter.api.cca.events.JCreditControlAnswer;
import org.jdiameter.api.cca.events.JCreditControlRequest;
import org.mobicents.diameter.stack.functional.Utils;
import org.mobicents.diameter.stack.functional.cca.AbstractClient;
/**
* Base implementation of Client
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class Client extends AbstractClient {
protected boolean sentINITIAL;
protected boolean sentINTERIM;
protected boolean sentTERMINATE;
protected boolean sentEVENT;
protected boolean receiveINITIAL;
protected boolean receiveINTERIM;
protected boolean receiveTERMINATE;
protected boolean receiveEVENT;
/**
*
*/
public Client() {
// TODO Auto-generated constructor stub
}
public void sendInitial() throws Exception {
JCreditControlRequest initialRequest = super.createCCR(CC_REQUEST_TYPE_INITIAL, this.ccRequestNumber, super.clientCCASession);
this.ccRequestNumber++;
super.clientCCASession.sendCreditControlRequest(initialRequest);
Utils.printMessage(log, super.stack.getDictionary(), initialRequest.getMessage(), true);
this.sentINITIAL = true;
}
public void sendInterim() throws Exception {
if (!receiveINITIAL) {
throw new Exception();
}
JCreditControlRequest interimRequest = super.createCCR(CC_REQUEST_TYPE_INTERIM, this.ccRequestNumber, super.clientCCASession);
this.ccRequestNumber++;
super.clientCCASession.sendCreditControlRequest(interimRequest);
Utils.printMessage(log, super.stack.getDictionary(), interimRequest.getMessage(), true);
this.sentINTERIM = true;
}
public void sendTermination() throws Exception {
if (!receiveINTERIM) {
throw new Exception();
}
JCreditControlRequest terminateRequest = super.createCCR(CC_REQUEST_TYPE_TERMINATE, this.ccRequestNumber, super.clientCCASession);
this.ccRequestNumber++;
super.clientCCASession.sendCreditControlRequest(terminateRequest);
Utils.printMessage(log, super.stack.getDictionary(), terminateRequest.getMessage(), true);
this.sentTERMINATE = true;
}
public void sendEvent() throws Exception {
JCreditControlRequest eventRequest = super.createCCR(CC_REQUEST_TYPE_TERMINATE, this.ccRequestNumber, super.clientCCASession);
this.ccRequestNumber++;
super.clientCCASession.sendCreditControlRequest(eventRequest);
Utils.printMessage(log, super.stack.getDictionary(), eventRequest.getMessage(), true);
this.sentEVENT = true;
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ClientCCASessionListener#doCreditControlAnswer( org.jdiameter.api.cca.ClientCCASession,
* org.jdiameter.api.cca.events.JCreditControlRequest, org.jdiameter.api.cca.events.JCreditControlAnswer)
*/
public void doCreditControlAnswer(ClientCCASession session, JCreditControlRequest request, JCreditControlAnswer answer) throws InternalException, IllegalDiameterStateException,
RouteException, OverloadException {
try {
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), false);
switch (answer.getRequestTypeAVPValue()) {
case CC_REQUEST_TYPE_INITIAL:
if (receiveINITIAL) {
fail("Received INITIAL more than once!", null);
}
receiveINITIAL = true;
break;
case CC_REQUEST_TYPE_INTERIM:
if (receiveINTERIM) {
fail("Received INTERIM more than once!", null);
}
receiveINTERIM = true;
break;
case CC_REQUEST_TYPE_TERMINATE:
if (receiveTERMINATE) {
fail("Received TERMINATE more than once!", null);
}
receiveTERMINATE = true;
break;
case CC_REQUEST_TYPE_EVENT:
if (receiveEVENT) {
fail("Received EVENT more than once!", null);
}
receiveEVENT = true;
break;
default:
}
}
catch (Exception e) {
e.printStackTrace();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ClientCCASessionListener#doReAuthRequest(org.jdiameter .api.cca.ClientCCASession,
* org.jdiameter.api.auth.events.ReAuthRequest)
*/
public void doReAuthRequest(ClientCCASession session, ReAuthRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
fail("Received \"ReAuthRequest\" event, request[" + request + "], on session[" + session + "]", null);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ClientCCASessionListener#doOtherEvent(org.jdiameter .api.app.AppSession,
* org.jdiameter.api.app.AppRequestEvent, org.jdiameter.api.app.AppAnswerEvent)
*/
public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
fail("Received \"Other\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null);
}
// ------------ getters for some vars;
public boolean isSentINITIAL() {
return sentINITIAL;
}
public boolean isSentEVENT() {
return sentEVENT;
}
public boolean isReceiveEVENT() {
return receiveEVENT;
}
public boolean isSentINTERIM() {
return sentINTERIM;
}
public boolean isSentTERMINATE() {
return sentTERMINATE;
}
public boolean isReceiveINITIAL() {
return receiveINITIAL;
}
public boolean isReceiveINTERIM() {
return receiveINTERIM;
}
public boolean isReceiveTERMINATE() {
return receiveTERMINATE;
}
// ------------ getters for some vars;
@Override
protected int getChargingUnitsTime() {
// TODO Auto-generated method stub
return 10;
}
@Override
protected String getServiceContextId() {
// TODO Auto-generated method stub
return "tralalalal ID";
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.cca.base;
import org.jdiameter.api.Answer;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.app.AppAnswerEvent;
import org.jdiameter.api.app.AppRequestEvent;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.auth.events.ReAuthAnswer;
import org.jdiameter.api.auth.events.ReAuthRequest;
import org.jdiameter.api.cca.ServerCCASession;
import org.jdiameter.api.cca.events.JCreditControlAnswer;
import org.jdiameter.api.cca.events.JCreditControlRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.impl.app.cca.JCreditControlAnswerImpl;
import org.mobicents.diameter.stack.functional.Utils;
import org.mobicents.diameter.stack.functional.cca.AbstractServer;
/**
* Base implementation of Server
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class Server extends AbstractServer {
protected boolean sentINITIAL;
protected boolean sentINTERIM;
protected boolean sentTERMINATE;
protected boolean sentEVENT;
protected boolean receiveINITIAL;
protected boolean receiveINTERIM;
protected boolean receiveTERMINATE;
protected boolean receiveEVENT;
protected JCreditControlRequest request;
// ------- send methods to trigger answer
public void sendInitial() throws Exception {
if (!this.receiveINITIAL || this.request == null) {
fail("Did not receive INITIAL or answer already sent.", null);
throw new Exception("Request: " + this.request);
}
JCreditControlAnswer answer = new JCreditControlAnswerImpl((Request) request.getMessage(), 2001);
AvpSet reqSet = request.getMessage().getAvps();
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID));
super.serverCCASession.sendCreditControlAnswer(answer);
sentINITIAL = true;
request = null;
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
}
public void sendInterim() throws Exception {
if (!this.receiveINTERIM || this.request == null) {
fail("Did not receive INTERIM or answer already sent.", null);
throw new Exception("Request: " + this.request);
}
JCreditControlAnswerImpl answer = new JCreditControlAnswerImpl((Request) request.getMessage(), 2001);
AvpSet reqSet = request.getMessage().getAvps();
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID));
super.serverCCASession.sendCreditControlAnswer(answer);
sentINTERIM = true;
request = null;
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
}
public void sendTermination() throws Exception {
if (!this.receiveTERMINATE || this.request == null) {
fail("Did not receive TERMINATE or answer already sent.", null);
throw new Exception("Request: " + this.request);
}
JCreditControlAnswerImpl answer = new JCreditControlAnswerImpl((Request) request.getMessage(), 2001);
AvpSet reqSet = request.getMessage().getAvps();
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID));
super.serverCCASession.sendCreditControlAnswer(answer);
sentTERMINATE = true;
request = null;
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
}
public void sendEvent() throws Exception {
if (!this.receiveEVENT || this.request == null) {
fail("Did not receive EVENT or answer already sent.", null);
throw new Exception("Request: " + this.request);
}
JCreditControlAnswerImpl answer = new JCreditControlAnswerImpl((Request) request.getMessage(), 2001);
AvpSet reqSet = request.getMessage().getAvps();
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID));
super.serverCCASession.sendCreditControlAnswer(answer);
sentEVENT = true;
request = null;
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
}
// ------- initial, this will be triggered for first msg.
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.NetworkReqListener#processRequest(org.jdiameter.api.Request)
*/
@Override
public Answer processRequest(Request request) {
if (request.getCommandCode() != 272) {
fail("Received Request with code not equal 272!. Code[" + request.getCommandCode() + "]", null);
return null;
}
if (super.serverCCASession == null) {
try {
super.serverCCASession = ((ISessionFactory) this.sessionFactory).getNewAppSession(request.getSessionId(), getApplicationId(), ServerCCASession.class, (Object)null);
((NetworkReqListener) this.serverCCASession).processRequest(request);
}
catch (Exception e) {
fail(null, e);
}
}
else {
// do fail?
fail("Received Request in base listener, not in app specific!", null);
}
return null;
}
// ------------- specific, app session listener.
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ServerCCASessionListener#doCreditControlRequest(org.jdiameter.api.cca.ServerCCASession,
* org.jdiameter.api.cca.events.JCreditControlRequest)
*/
public void doCreditControlRequest(ServerCCASession session, JCreditControlRequest request) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
try {
Utils.printMessage(log, super.stack.getDictionary(), request.getMessage(), false);
// INITIAL_REQUEST 1,
// UPDATE_REQUEST 2,
// TERMINATION_REQUEST, 3
// EVENT_REQUEST 4
switch (request.getRequestTypeAVPValue()) {
case CC_REQUEST_TYPE_INITIAL:
if (receiveINITIAL) {
fail("Received INITIAL more than once!", null);
}
receiveINITIAL = true;
this.request = request;
break;
case CC_REQUEST_TYPE_INTERIM:
if (receiveINTERIM) {
fail("Received INTERIM more than once!", null);
}
receiveINTERIM = true;
this.request = request;
break;
case CC_REQUEST_TYPE_TERMINATE:
if (receiveTERMINATE) {
fail("Received TERMINATE more than once!", null);
}
receiveTERMINATE = true;
this.request = request;
break;
case CC_REQUEST_TYPE_EVENT:
if (receiveEVENT) {
fail("Received EVENT more than once!", null);
}
receiveEVENT = true;
this.request = request;
break;
default:
fail("No REQ type present?: " + request.getRequestTypeAVPValue(), null);
}
}
catch (Exception e) {
fail(null, e);
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ServerCCASessionListener#doReAuthAnswer(org.jdiameter.api.cca.ServerCCASession,
* org.jdiameter.api.auth.events.ReAuthRequest, org.jdiameter.api.auth.events.ReAuthAnswer)
*/
public void doReAuthAnswer(ServerCCASession session, ReAuthRequest request, ReAuthAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
fail("Received \"ReAuthAnswer\" event, request[" + request + "], on session[" + session + "]", null);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ServerCCASessionListener#doOtherEvent(org.jdiameter.api.app.AppSession,
* org.jdiameter.api.app.AppRequestEvent, org.jdiameter.api.app.AppAnswerEvent)
*/
public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
fail("Received \"Other\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null);
}
public boolean isSentINITIAL() {
return sentINITIAL;
}
public boolean isSentINTERIM() {
return sentINTERIM;
}
public boolean isSentTERMINATE() {
return sentTERMINATE;
}
public boolean isReceiveINITIAL() {
return receiveINITIAL;
}
public boolean isReceiveINTERIM() {
return receiveINTERIM;
}
public boolean isReceiveTERMINATE() {
return receiveTERMINATE;
}
public boolean isSentEVENT() {
return sentEVENT;
}
public boolean isReceiveEVENT() {
return receiveEVENT;
}
public JCreditControlRequest getRequest() {
return request;
}
}
| 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.diameter.stack.functional.cca;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.jdiameter.api.Answer;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Message;
import org.jdiameter.api.Mode;
import org.jdiameter.api.Request;
import org.jdiameter.api.cca.ClientCCASession;
import org.jdiameter.api.cca.ClientCCASessionListener;
import org.jdiameter.api.cca.ServerCCASession;
import org.jdiameter.api.cca.events.JCreditControlRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.api.app.cca.ClientCCASessionState;
import org.jdiameter.common.api.app.cca.IClientCCASessionContext;
import org.jdiameter.common.impl.app.cca.CCASessionFactoryImpl;
import org.jdiameter.common.impl.app.cca.JCreditControlRequestImpl;
import org.mobicents.diameter.stack.functional.StateChange;
import org.mobicents.diameter.stack.functional.TBase;
/**
* @author baranowb
*
*/
public abstract class AbstractClient extends TBase implements ClientCCASessionListener, IClientCCASessionContext {
// NOTE: implementing NetworkReqListener since its required for stack to
// know we support it... ech.
protected static final int CC_REQUEST_TYPE_INITIAL = 1;
protected static final int CC_REQUEST_TYPE_INTERIM = 2;
protected static final int CC_REQUEST_TYPE_TERMINATE = 3;
protected static final int CC_REQUEST_TYPE_EVENT = 4;
protected ClientCCASession clientCCASession;
protected int ccRequestNumber = 0;
protected List<StateChange<ClientCCASessionState>> stateChanges = new ArrayList<StateChange<ClientCCASessionState>>(); // state changes
public void init(InputStream configStream, String clientID) throws Exception {
try {
super.init(configStream, clientID, ApplicationId.createByAuthAppId(0, 4));
CCASessionFactoryImpl creditControlSessionFactory = new CCASessionFactoryImpl(this.sessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ServerCCASession.class, creditControlSessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ClientCCASession.class, creditControlSessionFactory);
creditControlSessionFactory.setStateListener(this);
creditControlSessionFactory.setClientSessionListener(this);
creditControlSessionFactory.setClientContextListener(this);
this.clientCCASession = ((ISessionFactory) this.sessionFactory).getNewAppSession(this.sessionFactory.getSessionId("xxTESTxx"), getApplicationId(), ClientCCASession.class, (Object) null);
}
finally {
try {
configStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
// ----------- delegate methods so
public void start() throws IllegalDiameterStateException, InternalException {
stack.start();
}
public void start(Mode mode, long timeOut, TimeUnit timeUnit) throws IllegalDiameterStateException, InternalException {
stack.start(mode, timeOut, timeUnit);
}
public void stop(long timeOut, TimeUnit timeUnit, int disconnectCause) throws IllegalDiameterStateException, InternalException {
stack.stop(timeOut, timeUnit, disconnectCause);
}
public void stop(int disconnectCause) {
stack.stop(disconnectCause);
}
// ----------- conf parts
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.cca.IClientCCASessionContext# getDefaultTxTimerValue()
*/
public long getDefaultTxTimerValue() {
return 10;
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ClientCCASessionListener#getDefaultDDFHValue()
*/
public int getDefaultDDFHValue() {
// DDFH_CONTINUE: 1
return 1;
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ClientCCASessionListener#getDefaultCCFHValue()
*/
public int getDefaultCCFHValue() {
// CCFH_CONTINUE: 1
return 1;
}
// ----------- should not be called..
public void receivedSuccessMessage(Request request, Answer answer) {
fail("Received \"SuccessMessage\" event, request[" + request + "], answer[" + answer + "]", null);
}
public void timeoutExpired(Request request) {
fail("Received \"Timoeout\" event, request[" + request + "]", null);
}
public Answer processRequest(Request request) {
fail("Received \"Request\" event, request[" + request + "]", null);
return null;
}
// ------------ leave those
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.cca.IClientCCASessionContext#txTimerExpired (org.jdiameter.api.cca.ClientCCASession)
*/
public void txTimerExpired(ClientCCASession session) {
// NOP
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.cca.IClientCCASessionContext# grantAccessOnDeliverFailure(org.jdiameter.api.cca.ClientCCASession,
* org.jdiameter.api.Message)
*/
public void grantAccessOnDeliverFailure(ClientCCASession clientCCASessionImpl, Message request) {
// NOP
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.cca.IClientCCASessionContext# denyAccessOnDeliverFailure(org.jdiameter.api.cca.ClientCCASession,
* org.jdiameter.api.Message)
*/
public void denyAccessOnDeliverFailure(ClientCCASession clientCCASessionImpl, Message request) {
// NOP
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.cca.IClientCCASessionContext# grantAccessOnTxExpire(org.jdiameter.api.cca.ClientCCASession)
*/
public void grantAccessOnTxExpire(ClientCCASession clientCCASessionImpl) {
// NOP
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.cca.IClientCCASessionContext# denyAccessOnTxExpire(org.jdiameter.api.cca.ClientCCASession)
*/
public void denyAccessOnTxExpire(ClientCCASession clientCCASessionImpl) {
// NOP
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.cca.IClientCCASessionContext# grantAccessOnFailureMessage(org.jdiameter.api.cca.ClientCCASession)
*/
public void grantAccessOnFailureMessage(ClientCCASession clientCCASessionImpl) {
// NOP
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.cca.IClientCCASessionContext# denyAccessOnFailureMessage(org.jdiameter.api.cca.ClientCCASession)
*/
public void denyAccessOnFailureMessage(ClientCCASession clientCCASessionImpl) {
// NOP
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.cca.IClientCCASessionContext# indicateServiceError(org.jdiameter.api.cca.ClientCCASession)
*/
public void indicateServiceError(ClientCCASession clientCCASessionImpl) {
// NOP
}
// ---------- some helper methods.
protected JCreditControlRequest createCCR(int ccRequestType, int requestNumber, ClientCCASession ccaSession) throws Exception {
// Create Credit-Control-Request
JCreditControlRequest ccr = new JCreditControlRequestImpl(ccaSession.getSessions().get(0).createRequest(JCreditControlRequest.code, getApplicationId(), getServerRealmName()));
// AVPs present by default: Origin-Host, Origin-Realm, Session-Id,
// Vendor-Specific-Application-Id, Destination-Realm
AvpSet ccrAvps = ccr.getMessage().getAvps();
// Add remaining AVPs ... from RFC 4006:
// <CCR> ::= < Diameter Header: 272, REQ, PXY >
// < Session-Id >
// ccrAvps.addAvp(Avp.SESSION_ID, s.getSessionId());
// { Origin-Host }
ccrAvps.removeAvp(Avp.ORIGIN_HOST);
ccrAvps.addAvp(Avp.ORIGIN_HOST, getClientURI(), true);
// { Origin-Realm }
// ccrAvps.addAvp(Avp.ORIGIN_REALM, realmName, true);
// { Destination-Realm }
// ccrAvps.addAvp(Avp.DESTINATION_REALM, realmName, true);
// { Auth-Application-Id }
ccrAvps.addAvp(Avp.AUTH_APPLICATION_ID, 4);
// { Service-Context-Id }
// 8.42. Service-Context-Id AVP
//
// The Service-Context-Id AVP is of type UTF8String (AVP Code 461) and
// contains a unique identifier of the Diameter credit-control service
// specific document that applies to the request (as defined in section
// 4.1.2). This is an identifier allocated by the service provider, by
// the service element manufacturer, or by a standardization body, and
// MUST uniquely identify a given Diameter credit-control service
// specific document. The format of the Service-Context-Id is:
//
// "service-context" "@" "domain"
//
// service-context = Token
//
// The Token is an arbitrary string of characters and digits.
//
// 'domain' represents the entity that allocated the Service-Context-Id.
// It can be ietf.org, 3gpp.org, etc., if the identifier is allocated by
// a standardization body, or it can be the FQDN of the service provider
// (e.g., provider.example.com) or of the vendor (e.g.,
// vendor.example.com) if the identifier is allocated by a private
// entity.
//
// This AVP SHOULD be placed as close to the Diameter header as
// possible.
//
// Service-specific documents that are for private use only (i.e., to
// one provider's own use, where no interoperability is deemed useful)
// may define private identifiers without need of coordination.
// However, when interoperability is wanted, coordination of the
// identifiers via, for example, publication of an informational RFC is
// RECOMMENDED in order to make Service-Context-Id globally available.
String serviceContextId = getServiceContextId();
if (serviceContextId == null) {
serviceContextId = UUID.randomUUID().toString().replaceAll("-", "") + "@mss.mobicents.org";
}
ccrAvps.addAvp(Avp.SERVICE_CONTEXT_ID, serviceContextId, false);
// { CC-Request-Type }
// 8.3. CC-Request-Type AVP
//
// The CC-Request-Type AVP (AVP Code 416) is of type Enumerated and
// contains the reason for sending the credit-control request message.
// It MUST be present in all Credit-Control-Request messages. The
// following values are defined for the CC-Request-Type AVP:
//
// INITIAL_REQUEST 1
// An Initial request is used to initiate a credit-control session,
// and contains credit control information that is relevant to the
// initiation.
//
// UPDATE_REQUEST 2
// An Update request contains credit-control information for an
// existing credit-control session. Update credit-control requests
// SHOULD be sent every time a credit-control re-authorization is
// needed at the expiry of the allocated quota or validity time.
// Further, additional service-specific events MAY trigger a
// spontaneous Update request.
//
// TERMINATION_REQUEST 3
// A Termination request is sent to terminate a credit-control
// session and contains credit-control information relevant to the
// existing session.
//
// EVENT_REQUEST 4
// An Event request is used when there is no need to maintain any
// credit-control session state in the credit-control server. This
// request contains all information relevant to the service, and is
// the only request of the service. The reason for the Event request
// is further detailed in the Requested-Action AVP. The Requested-
// Action AVP MUST be included in the Credit-Control-Request message
// when CC-Request-Type is set to EVENT_REQUEST.
ccrAvps.addAvp(Avp.CC_REQUEST_TYPE, ccRequestType);
// { CC-Request-Number }
// 8.2. CC-Request-Number AVP
//
// The CC-Request-Number AVP (AVP Code 415) is of type Unsigned32 and
// identifies this request within one session. As Session-Id AVPs are
// globally unique, the combination of Session-Id and CC-Request-Number
// AVPs is also globally unique and can be used in matching credit-
// control messages with confirmations. An easy way to produce unique
// numbers is to set the value to 0 for a credit-control request of type
// INITIAL_REQUEST and EVENT_REQUEST and to set the value to 1 for the
// first UPDATE_REQUEST, to 2 for the second, and so on until the value
// for TERMINATION_REQUEST is one more than for the last UPDATE_REQUEST.
ccrAvps.addAvp(Avp.CC_REQUEST_NUMBER, requestNumber);
// [ Destination-Host ]
ccrAvps.removeAvp(Avp.DESTINATION_HOST);
// ccrAvps.addAvp(Avp.DESTINATION_HOST, ccRequestType == 2 ?
// serverURINode1 : serverURINode1, false);
// [ User-Name ]
// [ CC-Sub-Session-Id ]
// [ Acct-Multi-Session-Id ]
// [ Origin-State-Id ]
// [ Event-Timestamp ]
// *[ Subscription-Id ]
// 8.46. Subscription-Id AVP
//
// The Subscription-Id AVP (AVP Code 443) is used to identify the end
// user's subscription and is of type Grouped. The Subscription-Id AVP
// includes a Subscription-Id-Data AVP that holds the identifier and a
// Subscription-Id-Type AVP that defines the identifier type.
//
// It is defined as follows (per the grouped-avp-def of RFC 3588
// [DIAMBASE]):
//
// Subscription-Id ::= < AVP Header: 443 >
// { Subscription-Id-Type }
// { Subscription-Id-Data }
AvpSet subscriptionId = ccrAvps.addGroupedAvp(Avp.SUBSCRIPTION_ID);
// 8.47. Subscription-Id-Type AVP
//
// The Subscription-Id-Type AVP (AVP Code 450) is of type Enumerated,
// and it is used to determine which type of identifier is carried by
// the Subscription-Id AVP.
//
// This specification defines the following subscription identifiers.
// However, new Subscription-Id-Type values can be assigned by an IANA
// designated expert, as defined in section 12. A server MUST implement
// all the Subscription-Id-Types required to perform credit
// authorization for the services it supports, including possible future
// values. Unknown or unsupported Subscription-Id-Types MUST be treated
// according to the 'M' flag rule, as defined in [DIAMBASE].
//
// END_USER_E164 0
// The identifier is in international E.164 format (e.g., MSISDN),
// according to the ITU-T E.164 numbering plan defined in [E164] and
// [CE164].
//
// END_USER_IMSI 1
// The identifier is in international IMSI format, according to the
// ITU-T E.212 numbering plan as defined in [E212] and [CE212].
//
// END_USER_SIP_URI 2
// The identifier is in the form of a SIP URI, as defined in [SIP].
//
// END_USER_NAI 3
// The identifier is in the form of a Network Access Identifier, as
// defined in [NAI].
//
// END_USER_PRIVATE 4
// The Identifier is a credit-control server private identifier.
subscriptionId.addAvp(Avp.SUBSCRIPTION_ID_TYPE, 2);
// 8.48. Subscription-Id-Data AVP
//
// The Subscription-Id-Data AVP (AVP Code 444) is used to identify the
// end user and is of type UTF8String. The Subscription-Id-Type AVP
// defines which type of identifier is used.
subscriptionId.addAvp(Avp.SUBSCRIPTION_ID_DATA, "sip:alexandre@mobicents.org", false);
// [ Service-Identifier ]
// [ Termination-Cause ]
// [ Requested-Service-Unit ]
// 8.18. Requested-Service-Unit AVP
//
// The Requested-Service-Unit AVP (AVP Code 437) is of type Grouped and
// contains the amount of requested units specified by the Diameter
// credit-control client. A server is not required to implement all the
// unit types, and it must treat unknown or unsupported unit types as
// invalid AVPs.
//
// The Requested-Service-Unit AVP is defined as follows (per the
// grouped-avp-def of RFC 3588 [DIAMBASE]):
//
// Requested-Service-Unit ::= < AVP Header: 437 >
// [ CC-Time ]
// [ CC-Money ]
// [ CC-Total-Octets ]
// [ CC-Input-Octets ]
// [ CC-Output-Octets ]
// [ CC-Service-Specific-Units ]
// *[ AVP ]
AvpSet rsuAvp = ccrAvps.addGroupedAvp(Avp.REQUESTED_SERVICE_UNIT);
// 8.21. CC-Time AVP
//
// The CC-Time AVP (AVP Code 420) is of type Unsigned32 and indicates
// the length of the requested, granted, or used time in seconds.
rsuAvp.addAvp(Avp.CC_TIME, getChargingUnitsTime());
// [ Requested-Action ]
// *[ Used-Service-Unit ]
// 8.19. Used-Service-Unit AVP
//
// The Used-Service-Unit AVP is of type Grouped (AVP Code 446) and
// contains the amount of used units measured from the point when the
// service became active or, if interim interrogations are used during
// the session, from the point when the previous measurement ended.
//
// The Used-Service-Unit AVP is defined as follows (per the grouped-
// avp-def of RFC 3588 [DIAMBASE]):
//
// Used-Service-Unit ::= < AVP Header: 446 >
// [ Tariff-Change-Usage ]
// [ CC-Time ]
// [ CC-Money ]
// [ CC-Total-Octets ]
// [ CC-Input-Octets ]
// [ CC-Output-Octets ]
// [ CC-Service-Specific-Units ]
// *[ AVP ]
// FIXME: alex :) ?
// if(ccRequestNumber >= 1) {
// AvpSet usedServiceUnit = ccrAvps.addGroupedAvp(Avp.USED_SERVICE_UNIT);
// usedServiceUnit.addAvp(Avp.CC_TIME, this.partialCallDurationCounter);
// System.out.println("USED SERVICE UNITS ==============================>"
// + partialCallDurationCounter);
// }
// [ AoC-Request-Type ]
// [ Multiple-Services-Indicator ]
// *[ Multiple-Services-Credit-Control ]
// *[ Service-Parameter-Info ]
// [ CC-Correlation-Id ]
// [ User-Equipment-Info ]
// *[ Proxy-Info ]
// *[ Route-Record ]
// [ Service-Information ]
// *[ AVP ]
return ccr;
}
public String getSessionId() {
return this.clientCCASession.getSessionId();
}
public void fetchSession(String sessionId) throws InternalException {
this.clientCCASession = stack.getSession(sessionId, ClientCCASession.class);
}
public ClientCCASession getSession() {
return this.clientCCASession;
}
public List<StateChange<ClientCCASessionState>> getStateChanges() {
return stateChanges;
}
protected abstract int getChargingUnitsTime();
protected abstract String getServiceContextId();
}
| 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.diameter.stack.functional.cca;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Mode;
import org.jdiameter.api.cca.ClientCCASession;
import org.jdiameter.api.cca.ServerCCASession;
import org.jdiameter.api.cca.ServerCCASessionListener;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.api.app.cca.IServerCCASessionContext;
import org.jdiameter.common.api.app.cca.ServerCCASessionState;
import org.jdiameter.common.impl.app.cca.CCASessionFactoryImpl;
import org.mobicents.diameter.stack.functional.StateChange;
import org.mobicents.diameter.stack.functional.TBase;
/**
* @author baranowb
*
*/
public abstract class AbstractServer extends TBase implements ServerCCASessionListener, IServerCCASessionContext {
// NOTE: implementing NetworkReqListener since its required for stack to
// know we support it... ech.
protected static final int CC_REQUEST_TYPE_INITIAL = 1;
protected static final int CC_REQUEST_TYPE_INTERIM = 2;
protected static final int CC_REQUEST_TYPE_TERMINATE = 3;
protected static final int CC_REQUEST_TYPE_EVENT = 4;
protected ServerCCASession serverCCASession;
protected int ccRequestNumber = 0;
protected List<StateChange<ServerCCASessionState>> stateChanges = new ArrayList<StateChange<ServerCCASessionState>>(); // state changes
public void init(InputStream configStream, String clientID) throws Exception {
try {
super.init(configStream, clientID, ApplicationId.createByAuthAppId(0, 4));
CCASessionFactoryImpl creditControlSessionFactory = new CCASessionFactoryImpl(this.sessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ServerCCASession.class, creditControlSessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ClientCCASession.class, creditControlSessionFactory);
creditControlSessionFactory.setStateListener(this);
creditControlSessionFactory.setServerSessionListener(this);
creditControlSessionFactory.setServerContextListener(this);
}
finally {
try {
configStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
// ----------- delegate methods so
public void start() throws IllegalDiameterStateException, InternalException {
stack.start();
}
public void start(Mode mode, long timeOut, TimeUnit timeUnit) throws IllegalDiameterStateException, InternalException {
stack.start(mode, timeOut, timeUnit);
}
public void stop(long timeOut, TimeUnit timeUnit, int disconnectCause) throws IllegalDiameterStateException, InternalException {
stack.stop(timeOut, timeUnit, disconnectCause);
}
public void stop(int disconnectCause) {
stack.stop(disconnectCause);
}
// ----------- conf parts
public void sessionSupervisionTimerExpired(ServerCCASession session) {
// NOP
}
public void sessionSupervisionTimerStarted(ServerCCASession session, ScheduledFuture future) {
// NOP
}
public void sessionSupervisionTimerReStarted(ServerCCASession session, ScheduledFuture future) {
// NOP
}
public void sessionSupervisionTimerStopped(ServerCCASession session, ScheduledFuture future) {
// NOP
}
public long getDefaultValidityTime() {
return 120;
}
public String getSessionId() {
return this.serverCCASession.getSessionId();
}
public void fetchSession(String sessionId) throws InternalException {
this.serverCCASession = stack.getSession(sessionId, ServerCCASession.class);
}
public ServerCCASession getSession() {
return this.serverCCASession;
}
public List<StateChange<ServerCCASessionState>> getStateChanges() {
return stateChanges;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.cxdx.base;
import java.io.InputStream;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.cxdx.ClientCxDxSession;
import org.jdiameter.api.cxdx.ServerCxDxSession;
import org.jdiameter.api.cxdx.events.JRegistrationTerminationAnswer;
import org.jdiameter.api.cxdx.events.JRegistrationTerminationRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.impl.app.cxdx.CxDxSessionFactoryImpl;
import org.jdiameter.common.impl.app.cxdx.JRegistrationTerminationRequestImpl;
import org.mobicents.diameter.stack.functional.Utils;
import org.mobicents.diameter.stack.functional.cxdx.AbstractServer;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class ServerRTR extends AbstractServer {
protected boolean receivedRegistrationTermination;
protected boolean sentRegistrationTermination;
/**
*
*/
public ServerRTR() {
}
@Override
public void init(InputStream configStream, String clientID) throws Exception {
try {
super.init(configStream, clientID, ApplicationId.createByAuthAppId(10415, 16777216));
CxDxSessionFactoryImpl cxDxSessionFactory = new CxDxSessionFactoryImpl(this.sessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ServerCxDxSession.class, cxDxSessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ClientCxDxSession.class, cxDxSessionFactory);
cxDxSessionFactory.setServerSessionListener(this);
this.serverCxDxSession = sessionFactory.getNewAppSession(getApplicationId(), ServerCxDxSession.class);
}
finally {
try {
configStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public void sendRegistrationTermination() throws Exception {
JRegistrationTerminationRequest request = new JRegistrationTerminationRequestImpl(super.createRequest(this.serverCxDxSession, JRegistrationTerminationRequest.code));
AvpSet reqSet = request.getMessage().getAvps();
// <Registration-Termination-Request> ::= < Diameter Header: 304, REQ, PXY, 16777216 >
// < Session-Id >
// { Vendor-Specific-Application-Id }
// { Auth-Session-State }
// { Origin-Host }
// { Origin-Realm }
// { Destination-Host }
// { Destination-Realm }
// { User-Name }
reqSet.addAvp(Avp.USER_NAME, "ala", false);
// [ Associated-Identities ]
// *[ Supported-Features ]
// *[ Public-Identity ]
// { Deregistration-Reason }
AvpSet deregeReason = reqSet.addGroupedAvp(Avp.DEREGISTRATION_REASON, getApplicationId().getVendorId(), true, false);
deregeReason.addAvp(Avp.REASON_CODE, 0, getApplicationId().getVendorId(), true, false, true);
// *[ AVP ]
// *[ Proxy-Info ]
// *[ Route-Record ]
this.serverCxDxSession.sendRegistrationTerminationRequest(request);
Utils.printMessage(log, super.stack.getDictionary(), request.getMessage(), true);
this.sentRegistrationTermination = true;
}
@Override
public void doRegistrationTerminationAnswer(ServerCxDxSession session, JRegistrationTerminationRequest request, JRegistrationTerminationAnswer answer) throws InternalException,
IllegalDiameterStateException, RouteException, OverloadException {
if (this.receivedRegistrationTermination) {
fail("Received RTA more than once", null);
return;
}
this.receivedRegistrationTermination = true;
}
public boolean isReceivedRegistrationTermination() {
return receivedRegistrationTermination;
}
public boolean isSentRegistrationTermination() {
return sentRegistrationTermination;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.cxdx.base;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.cxdx.ClientCxDxSession;
import org.jdiameter.api.cxdx.events.JUserAuthorizationAnswer;
import org.jdiameter.api.cxdx.events.JUserAuthorizationRequest;
import org.jdiameter.common.impl.app.cxdx.JUserAuthorizationRequestImpl;
import org.mobicents.diameter.stack.functional.Utils;
import org.mobicents.diameter.stack.functional.cxdx.AbstractClient;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class ClientUAR extends AbstractClient {
protected boolean receivedUserAuthorization;
protected boolean sentUserAuthorization;
/**
*
*/
public ClientUAR() {
}
public void sendUserAuthorization() throws Exception {
JUserAuthorizationRequest request = new JUserAuthorizationRequestImpl(super.createRequest(this.clientCxDxSession, JUserAuthorizationRequest.code));
AvpSet reqSet = request.getMessage().getAvps();
// < User-Authorization-Request> ::= < Diameter Header: 300, REQ, PXY, 16777216 >
// < Session-Id >
// { Vendor-Specific-Application-Id }
// { Auth-Session-State }
// { Origin-Host }
// { Origin-Realm }
// [ Destination-Host ]
// { Destination-Realm }
// { User-Name }
reqSet.addAvp(Avp.USER_NAME, "ala", false);
// *[ Supported-Features ]
// { Public-Identity }
AvpSet userIdentity = reqSet.addGroupedAvp(Avp.USER_IDENTITY, getApplicationId().getVendorId(), true, false);
// User-Identity ::= <AVP header: 700 10415>
// [Public-Identity]
userIdentity.addAvp(Avp.PUBLIC_IDENTITY, "tralalalal user", getApplicationId().getVendorId(), true, false, false);
// [MSISDN]
// *[AVP]
// { Visited-Network-Identifier }
reqSet.addAvp(Avp.VISITED_NETWORK_ID, "ala", getApplicationId().getVendorId(), true, false, false);
// [ User-Authorization-Type ]
// [ UAR-Flags ]
// *[ AVP ]
// *[ Proxy-Info ]
// *[ Route-Record ]
this.clientCxDxSession.sendUserAuthorizationRequest(request);
Utils.printMessage(log, super.stack.getDictionary(), request.getMessage(), true);
this.sentUserAuthorization = true;
}
@Override
public void doUserAuthorizationAnswer(ClientCxDxSession session, JUserAuthorizationRequest request, JUserAuthorizationAnswer answer) throws InternalException,
IllegalDiameterStateException, RouteException, OverloadException {
if (this.receivedUserAuthorization) {
fail("Received UAA more than once", null);
return;
}
this.receivedUserAuthorization = true;
}
public boolean isReceivedUserAuthorization() {
return receivedUserAuthorization;
}
public boolean isSentUserAuthorization() {
return sentUserAuthorization;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.cxdx.base;
import java.io.InputStream;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.cxdx.ClientCxDxSession;
import org.jdiameter.api.cxdx.ServerCxDxSession;
import org.jdiameter.api.cxdx.events.JPushProfileAnswer;
import org.jdiameter.api.cxdx.events.JPushProfileRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.impl.app.cxdx.CxDxSessionFactoryImpl;
import org.jdiameter.common.impl.app.cxdx.JPushProfileRequestImpl;
import org.mobicents.diameter.stack.functional.Utils;
import org.mobicents.diameter.stack.functional.cxdx.AbstractServer;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class ServerPPR extends AbstractServer {
protected boolean receivedPushProfile;
protected boolean sentPushProfile;
/**
*
*/
public ServerPPR() {
}
@Override
public void init(InputStream configStream, String clientID) throws Exception {
try {
super.init(configStream, clientID, ApplicationId.createByAuthAppId(10415, 16777216));
CxDxSessionFactoryImpl cxDxSessionFactory = new CxDxSessionFactoryImpl(this.sessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ServerCxDxSession.class, cxDxSessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ClientCxDxSession.class, cxDxSessionFactory);
cxDxSessionFactory.setServerSessionListener(this);
this.serverCxDxSession = sessionFactory.getNewAppSession(getApplicationId(), ServerCxDxSession.class);
}
finally {
try {
configStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public void sendPushProfile() throws Exception {
JPushProfileRequest request = new JPushProfileRequestImpl(super.createRequest(this.serverCxDxSession, JPushProfileRequest.code));
AvpSet reqSet = request.getMessage().getAvps();
// < Push-Profile-Request > ::= < Diameter Header: 305, REQ, PXY, 16777216 >
// < Session-Id >
// { Vendor-Specific-Application-Id }
// { Auth-Session-State }
// { Origin-Host }
// { Origin-Realm }
// { Destination-Host }
// { Destination-Realm }
// { User-Name }
reqSet.addAvp(Avp.USER_NAME, "ala", false);
// *[ Supported-Features ]
// [ User-Data ]
// [ Charging-Information ]
// [ SIP-Auth-Data-Item ]
// *[ AVP ]
// *[ Proxy-Info ]
// *[ Route-Record ]
this.serverCxDxSession.sendPushProfileRequest(request);
Utils.printMessage(log, super.stack.getDictionary(), request.getMessage(), true);
this.sentPushProfile = true;
}
@Override
public void doPushProfileAnswer(ServerCxDxSession session, JPushProfileRequest request, JPushProfileAnswer answer) throws InternalException, IllegalDiameterStateException,
RouteException, OverloadException {
if (this.receivedPushProfile) {
fail("Received PPA more than once", null);
return;
}
this.receivedPushProfile = true;
}
public boolean isReceivedPushProfile() {
return receivedPushProfile;
}
public boolean isSentPushProfile() {
return sentPushProfile;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.cxdx.base;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.cxdx.ClientCxDxSession;
import org.jdiameter.api.cxdx.events.JServerAssignmentAnswer;
import org.jdiameter.api.cxdx.events.JServerAssignmentRequest;
import org.jdiameter.common.impl.app.cxdx.JServerAssignmentRequestImpl;
import org.mobicents.diameter.stack.functional.Utils;
import org.mobicents.diameter.stack.functional.cxdx.AbstractClient;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class ClientSAR extends AbstractClient {
protected boolean receivedServerAssignment;
protected boolean sentServerAssignment;
/**
*
*/
public ClientSAR() {
}
public void sendServerAssignment() throws Exception {
JServerAssignmentRequest request = new JServerAssignmentRequestImpl(super.createRequest(this.clientCxDxSession, JServerAssignmentRequest.code));
AvpSet reqSet = request.getMessage().getAvps();
// <Server-Assignment-Request> ::= < Diameter Header: 301, REQ, PXY, 16777216 >
// < Session-Id >
// { Vendor-Specific-Application-Id }
// { Auth-Session-State }
// { Origin-Host }
// { Origin-Realm }
// [ Destination-Host ]
// { Destination-Realm }
// [ User-Name ]
// *[ Supported-Features ]
// *[ Public-Identity ]
// [ Wildcarded-PSI ]
// [ Wildcarded-IMPU ]
// { Server-Name }
reqSet.addAvp(Avp.SERVER_NAME, "ala", getApplicationId().getVendorId(), true, false, false);
this.clientCxDxSession.sendServerAssignmentRequest(request);
Utils.printMessage(log, super.stack.getDictionary(), request.getMessage(), true);
this.sentServerAssignment = true;
}
@Override
public void doServerAssignmentAnswer(ClientCxDxSession session, JServerAssignmentRequest request, JServerAssignmentAnswer answer) throws InternalException,
IllegalDiameterStateException, RouteException, OverloadException {
if (this.receivedServerAssignment) {
fail("Received SAA more than once", null);
return;
}
this.receivedServerAssignment = true;
}
public boolean isReceivedServerAssignment() {
return receivedServerAssignment;
}
public boolean isSentServerAssignment() {
return sentServerAssignment;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.cxdx.base;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.cxdx.ClientCxDxSession;
import org.jdiameter.api.cxdx.events.JMultimediaAuthAnswer;
import org.jdiameter.api.cxdx.events.JMultimediaAuthRequest;
import org.jdiameter.common.impl.app.cxdx.JMultimediaAuthRequestImpl;
import org.mobicents.diameter.stack.functional.Utils;
import org.mobicents.diameter.stack.functional.cxdx.AbstractClient;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class ClientMAR extends AbstractClient {
protected boolean receivedMultimediaAuth;
protected boolean sentMultimediaAuth;
/**
*
*/
public ClientMAR() {
}
public void sendMultimediaAuth() throws Exception {
JMultimediaAuthRequest request = new JMultimediaAuthRequestImpl(super.createRequest(this.clientCxDxSession, JMultimediaAuthRequest.code));
AvpSet reqSet = request.getMessage().getAvps();
reqSet.addAvp(Avp.SERVER_NAME, "ala", getApplicationId().getVendorId(), true, false, false);
// < Multimedia-Auth-Request > ::= < Diameter Header: 303, REQ, PXY, 16777216 >
// < Session-Id >
// { Vendor-Specific-Application-Id }
// { Auth-Session-State }
// { Origin-Host }
// { Origin-Realm }
// { Destination-Realm }
// [ Destination-Host ]
// { User-Name }
// *[ Supported-Features ]
// { Public-Identity }
AvpSet userIdentity = reqSet.addGroupedAvp(Avp.USER_IDENTITY, getApplicationId().getVendorId(), true, false);
// User-Identity ::= <AVP header: 700 10415>
// [Public-Identity]
userIdentity.addAvp(Avp.PUBLIC_IDENTITY, "tralalalal user", getApplicationId().getVendorId(), true, false, false);
// [MSISDN]
// *[AVP]
// { SIP-Auth-Data-Item }
// seriously ....
reqSet.addGroupedAvp(Avp.SIP_AUTH_DATA_ITEM, getApplicationId().getVendorId(), true, false);
// { SIP-Number-Auth-Items }
reqSet.addAvp(Avp.SIP_NUMBER_AUTH_ITEMS, getApplicationId().getVendorId(), 1, true, false, true);
// { Server-Name }
reqSet.addAvp(Avp.SERVER_NAME, "ala", getApplicationId().getVendorId(), true, false, false);
// *[ AVP ]
// *[ Proxy-Info ]
// *[ Route-Record ]
this.clientCxDxSession.sendMultimediaAuthRequest(request);
Utils.printMessage(log, super.stack.getDictionary(), request.getMessage(), true);
this.sentMultimediaAuth = true;
}
@Override
public void doMultimediaAuthAnswer(ClientCxDxSession session, JMultimediaAuthRequest request, JMultimediaAuthAnswer answer) throws InternalException,
IllegalDiameterStateException, RouteException, OverloadException {
if (this.receivedMultimediaAuth) {
fail("Received MAA more than once", null);
return;
}
this.receivedMultimediaAuth = true;
}
public boolean isReceivedMultimediaAuth() {
return receivedMultimediaAuth;
}
public boolean isSentMultimediaAuth() {
return sentMultimediaAuth;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.cxdx.base;
import java.io.InputStream;
import org.jdiameter.api.Answer;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.cxdx.ClientCxDxSession;
import org.jdiameter.api.cxdx.ServerCxDxSession;
import org.jdiameter.api.cxdx.events.JPushProfileAnswer;
import org.jdiameter.api.cxdx.events.JPushProfileRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.impl.app.cxdx.CxDxSessionFactoryImpl;
import org.jdiameter.common.impl.app.cxdx.JPushProfileAnswerImpl;
import org.mobicents.diameter.stack.functional.Utils;
import org.mobicents.diameter.stack.functional.cxdx.AbstractClient;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class ClientPPR extends AbstractClient {
protected boolean receivedPushProfile;
protected boolean sentPushProfile;
protected JPushProfileRequest request;
/**
*
*/
public ClientPPR() {
}
public void init(InputStream configStream, String clientID) throws Exception {
try {
super.init(configStream, clientID, ApplicationId.createByAuthAppId(10415, 16777216));
CxDxSessionFactoryImpl cxdxSessionFactory = new CxDxSessionFactoryImpl(this.sessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ServerCxDxSession.class, cxdxSessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ClientCxDxSession.class, cxdxSessionFactory);
cxdxSessionFactory.setClientSessionListener(this);
}
finally {
try {
configStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public void sendPushProfile() throws Exception {
if (!receivedPushProfile || request == null) {
fail("Did not receive PPR or answer already sent.", null);
throw new Exception("Did not receive PPR or answer already sent. Request: " + this.request);
}
JPushProfileAnswer answer = new JPushProfileAnswerImpl((Request) this.request.getMessage(), 2001);
AvpSet reqSet = request.getMessage().getAvps();
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID));
// < Push-Profile-Answer > ::= < Diameter Header: 305, PXY, 16777216 >
// < Session-Id >
// { Vendor-Specific-Application-Id }
if (set.getAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID) == null) {
AvpSet vendorSpecificApplicationId = set.addGroupedAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, 0, false, false);
// 1* [ Vendor-Id ]
vendorSpecificApplicationId.addAvp(Avp.VENDOR_ID, getApplicationId().getVendorId(), true);
// 0*1{ Auth-Application-Id }
vendorSpecificApplicationId.addAvp(Avp.AUTH_APPLICATION_ID, getApplicationId().getAuthAppId(), true);
}
// [Result-Code ]
// [ Experimental-Result ]
// { Auth-Session-State }
if (set.getAvp(Avp.AUTH_SESSION_STATE) == null) {
set.addAvp(Avp.AUTH_SESSION_STATE, 1);
}
// { Origin-Host }
// { Origin-Realm }
// *[ Supported-Features ]
// *[ AVP ]
// *[ Failed-AVP ]
// *[ Proxy-Info ]
// *[ Route-Record ]
this.clientCxDxSession.sendPushProfileAnswer(answer);
Utils.printMessage(log, super.stack.getDictionary(), request.getMessage(), true);
this.request = null;
this.sentPushProfile = true;
}
@Override
public void doPushProfileRequest(ClientCxDxSession session, JPushProfileRequest request) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
if (this.receivedPushProfile) {
fail("Received PPR more than once", null);
return;
}
this.receivedPushProfile = true;
this.request = request;
}
@Override
public Answer processRequest(Request request) {
int code = request.getCommandCode();
if (code != JPushProfileAnswer.code) {
fail("Received Request with code not used by CxDx!. Code[" + request.getCommandCode() + "]", null);
return null;
}
if (super.clientCxDxSession != null) {
// do fail?
fail("Received Request in base listener, not in app specific!" + code, null);
}
else {
try {
super.clientCxDxSession = ((ISessionFactory) this.sessionFactory).getNewAppSession(request.getSessionId(), getApplicationId(), ClientCxDxSession.class, (Object) null);
((NetworkReqListener) this.clientCxDxSession).processRequest(request);
}
catch (Exception e) {
e.printStackTrace();
fail(null, e);
}
}
return null;
}
public boolean isReceivedPushProfile() {
return receivedPushProfile;
}
public boolean isSentPushProfile() {
return sentPushProfile;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.cxdx.base;
import org.jdiameter.api.Answer;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.cxdx.ServerCxDxSession;
import org.jdiameter.api.cxdx.events.JLocationInfoAnswer;
import org.jdiameter.api.cxdx.events.JLocationInfoRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.impl.app.cxdx.JLocationInfoAnswerImpl;
import org.mobicents.diameter.stack.functional.Utils;
import org.mobicents.diameter.stack.functional.cxdx.AbstractServer;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class ServerLIR extends AbstractServer {
protected boolean receivedLocationInfo;
protected boolean sentLocationInfo;
protected JLocationInfoRequest request;
/**
*
*/
public ServerLIR() {
}
public void sendLocationInfo() throws Exception {
if (!receivedLocationInfo || request == null) {
fail("Did not receive LIR or answer already sent.", null);
throw new Exception("Did not receive LIR or answer already sent. Request: " + this.request);
}
JLocationInfoAnswer answer = new JLocationInfoAnswerImpl((Request) this.request.getMessage(), 2001);
AvpSet reqSet = request.getMessage().getAvps();
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID));
request = null;
// <Location-Info-Answer> ::= < Diameter Header: 302, PXY, 16777216 >
// < Session-Id >
// { Vendor-Specific-Application-Id }
if (set.getAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID) == null) {
AvpSet vendorSpecificApplicationId = set.addGroupedAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, 0, false, false);
// 1* [ Vendor-Id ]
vendorSpecificApplicationId.addAvp(Avp.VENDOR_ID, getApplicationId().getVendorId(), true);
// 0*1{ Auth-Application-Id }
vendorSpecificApplicationId.addAvp(Avp.AUTH_APPLICATION_ID, getApplicationId().getAuthAppId(), true);
}
// [ Result-Code ]
// [ Experimental-Result ]
// { Auth-Session-State }
if (set.getAvp(Avp.AUTH_SESSION_STATE) == null) {
set.addAvp(Avp.AUTH_SESSION_STATE, 1);
}
// { Origin-Host }
// { Origin-Realm }
// *[ Supported-Features ]
// [ Server-Name ]
// [ Server-Capabilities ]
// [ Wildcarded-PSI ]
// [ Wildcarded-IMPU ]
// *[ AVP ]
// *[ Failed-AVP ]
// *[ Proxy-Info ]
// *[ Route-Record ]
this.serverCxDxSession.sendLocationInformationAnswer(answer);
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
this.request = null;
this.sentLocationInfo = true;
}
@Override
public Answer processRequest(Request request) {
int code = request.getCommandCode();
if (code != JLocationInfoRequest.code) {
fail("Received Request with code not used by CxDx!. Code[" + request.getCommandCode() + "]", null);
return null;
}
if (super.serverCxDxSession != null) {
// do fail?
fail("Received Request in base listener, not in app specific!" + code, null);
}
else {
try {
super.serverCxDxSession = ((ISessionFactory) this.sessionFactory).getNewAppSession(request.getSessionId(), getApplicationId(), ServerCxDxSession.class, (Object) null);
((NetworkReqListener) this.serverCxDxSession).processRequest(request);
}
catch (Exception e) {
e.printStackTrace();
fail(null, e);
}
}
return null;
}
@Override
public void doLocationInformationRequest(ServerCxDxSession session, JLocationInfoRequest request) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
if (this.receivedLocationInfo) {
fail("Received LIR more than once", null);
return;
}
this.receivedLocationInfo = true;
this.request = request;
}
public boolean isReceivedLocationInfo() {
return receivedLocationInfo;
}
public boolean isSentLocationInfo() {
return sentLocationInfo;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.cxdx.base;
import java.io.InputStream;
import org.jdiameter.api.Answer;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.cxdx.ClientCxDxSession;
import org.jdiameter.api.cxdx.ServerCxDxSession;
import org.jdiameter.api.cxdx.events.JRegistrationTerminationAnswer;
import org.jdiameter.api.cxdx.events.JRegistrationTerminationRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.impl.app.cxdx.CxDxSessionFactoryImpl;
import org.jdiameter.common.impl.app.cxdx.JRegistrationTerminationAnswerImpl;
import org.mobicents.diameter.stack.functional.Utils;
import org.mobicents.diameter.stack.functional.cxdx.AbstractClient;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class ClientRTR extends AbstractClient {
protected boolean receivedRegistrationTermination;
protected boolean sentRegistrationTermination;
protected JRegistrationTerminationRequest request;
/**
*
*/
public ClientRTR() {
}
public void init(InputStream configStream, String clientID) throws Exception {
try {
super.init(configStream, clientID, ApplicationId.createByAuthAppId(10415, 16777216));
CxDxSessionFactoryImpl cxdxSessionFactory = new CxDxSessionFactoryImpl(this.sessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ServerCxDxSession.class, cxdxSessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ClientCxDxSession.class, cxdxSessionFactory);
cxdxSessionFactory.setClientSessionListener(this);
}
finally {
try {
configStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public void sendRegistrationTermination() throws Exception {
if (!receivedRegistrationTermination || request == null) {
fail("Did not receive RTR or answer already sent.", null);
throw new Exception("Did not receive RTR or answer already sent. Request: " + this.request);
}
JRegistrationTerminationAnswer answer = new JRegistrationTerminationAnswerImpl((Request) this.request.getMessage(), 2001);
AvpSet reqSet = request.getMessage().getAvps();
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID));
// <Registration-Termination-Answer> ::= < Diameter Header: 304, PXY, 16777216 >
// < Session-Id >
// { Vendor-Specific-Application-Id }
if (set.getAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID) == null) {
AvpSet vendorSpecificApplicationId = set.addGroupedAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, 0, false, false);
// 1* [ Vendor-Id ]
vendorSpecificApplicationId.addAvp(Avp.VENDOR_ID, getApplicationId().getVendorId(), true);
// 0*1{ Auth-Application-Id }
vendorSpecificApplicationId.addAvp(Avp.AUTH_APPLICATION_ID, getApplicationId().getAuthAppId(), true);
}
// [ Result-Code ]
// [ Experimental-Result ]
// { Auth-Session-State }
if (set.getAvp(Avp.AUTH_SESSION_STATE) == null) {
set.addAvp(Avp.AUTH_SESSION_STATE, 1);
}
// { Origin-Host }
// { Origin-Realm }
// [ Associated-Identities ]
// *[ Supported-Features ]
// *[ AVP ]
// *[ Failed-AVP ]
this.clientCxDxSession.sendRegistrationTerminationAnswer(answer);
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
this.request = null;
this.sentRegistrationTermination = true;
}
@Override
public void doRegistrationTerminationRequest(ClientCxDxSession session, JRegistrationTerminationRequest request) throws InternalException, IllegalDiameterStateException,
RouteException, OverloadException {
if (this.receivedRegistrationTermination) {
fail("Received RTR more than once", null);
return;
}
this.receivedRegistrationTermination = true;
this.request = request;
}
@Override
public Answer processRequest(Request request) {
int code = request.getCommandCode();
if (code != JRegistrationTerminationAnswer.code) {
fail("Received Request with code not used by CxDx!. Code[" + request.getCommandCode() + "]", null);
return null;
}
if (super.clientCxDxSession != null) {
// do fail?
fail("Received Request in base listener, not in app specific!" + code, null);
}
else {
try {
super.clientCxDxSession = ((ISessionFactory) this.sessionFactory).getNewAppSession(request.getSessionId(), getApplicationId(), ClientCxDxSession.class, (Object) null);
((NetworkReqListener) this.clientCxDxSession).processRequest(request);
}
catch (Exception e) {
e.printStackTrace();
fail(null, e);
}
}
return null;
}
public boolean isReceivedRegistrationTermination() {
return receivedRegistrationTermination;
}
public boolean isSentRegistrationTermination() {
return sentRegistrationTermination;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.cxdx.base;
import org.jdiameter.api.Answer;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.cxdx.ServerCxDxSession;
import org.jdiameter.api.cxdx.events.JMultimediaAuthAnswer;
import org.jdiameter.api.cxdx.events.JMultimediaAuthRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.impl.app.cxdx.JMultimediaAuthAnswerImpl;
import org.mobicents.diameter.stack.functional.Utils;
import org.mobicents.diameter.stack.functional.cxdx.AbstractServer;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class ServerMAR extends AbstractServer {
protected boolean receivedMultimediaAuth;
protected boolean sentMultimediaAuth;
protected JMultimediaAuthRequest request;
/**
*
*/
public ServerMAR() {
}
public void sendMultimediaAuth() throws Exception {
if (!receivedMultimediaAuth || request == null) {
fail("Did not receive MAR or answer already sent.", null);
throw new Exception("Did not receive MAR or answer already sent. Request: " + this.request);
}
JMultimediaAuthAnswer answer = new JMultimediaAuthAnswerImpl((Request) this.request.getMessage(), 2001);
AvpSet reqSet = request.getMessage().getAvps();
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID));
request = null;
// < Multimedia-Auth-Answer > ::= < Diameter Header: 303, PXY, 16777216 >
// < Session-Id >
// { Vendor-Specific-Application-Id }
if (set.getAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID) == null) {
AvpSet vendorSpecificApplicationId = set.addGroupedAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, 0, false, false);
// 1* [ Vendor-Id ]
vendorSpecificApplicationId.addAvp(Avp.VENDOR_ID, getApplicationId().getVendorId(), true);
// 0*1{ Auth-Application-Id }
vendorSpecificApplicationId.addAvp(Avp.AUTH_APPLICATION_ID, getApplicationId().getAuthAppId(), true);
}
// [ Result-Code ]
// [ Experimental-Result ]
// { Auth-Session-State }
if (set.getAvp(Avp.AUTH_SESSION_STATE) == null) {
set.addAvp(Avp.AUTH_SESSION_STATE, 1);
}
// { Origin-Host }
// { Origin-Realm }
// [ User-Name ]
// *[ Supported-Features ]
// [ Public-Identity ]
// [ SIP-Number-Auth-Items ]
// *[SIP-Auth-Data-Item ]
// [ Wildcarded-IMPU ]
// *[ AVP ]
// *[ Failed-AVP ]
// *[ Proxy-Info ]
// *[ Route-Record ]
this.serverCxDxSession.sendMultimediaAuthAnswer(answer);
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
this.request = null;
this.sentMultimediaAuth = true;
}
@Override
public Answer processRequest(Request request) {
int code = request.getCommandCode();
if (code != JMultimediaAuthRequest.code) {
fail("Received Request with code not used by CxDx!. Code[" + request.getCommandCode() + "]", null);
return null;
}
if (super.serverCxDxSession != null) {
// do fail?
fail("Received Request in base listener, not in app specific!" + code, null);
}
else {
try {
super.serverCxDxSession = ((ISessionFactory) this.sessionFactory).getNewAppSession(request.getSessionId(), getApplicationId(), ServerCxDxSession.class, (Object) null);
((NetworkReqListener) this.serverCxDxSession).processRequest(request);
}
catch (Exception e) {
e.printStackTrace();
fail(null, e);
}
}
return null;
}
@Override
public void doMultimediaAuthRequest(ServerCxDxSession session, JMultimediaAuthRequest request) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
if (this.receivedMultimediaAuth) {
fail("Received MAR more than once", null);
return;
}
this.receivedMultimediaAuth = true;
this.request = request;
}
public boolean isReceivedMultimediaAuth() {
return receivedMultimediaAuth;
}
public boolean isSentMultimediaAuth() {
return sentMultimediaAuth;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.cxdx.base;
import org.jdiameter.api.Answer;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.cxdx.ServerCxDxSession;
import org.jdiameter.api.cxdx.events.JUserAuthorizationAnswer;
import org.jdiameter.api.cxdx.events.JUserAuthorizationRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.impl.app.cxdx.JUserAuthorizationAnswerImpl;
import org.mobicents.diameter.stack.functional.Utils;
import org.mobicents.diameter.stack.functional.cxdx.AbstractServer;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class ServerUAR extends AbstractServer {
protected boolean receivedUserAuthorization;
protected boolean sentUserAuthorization;
protected JUserAuthorizationRequest request;
/**
*
*/
public ServerUAR() {
}
public void sendUserAuthorization() throws Exception {
if (!receivedUserAuthorization || request == null) {
fail("Did not receive UAR or answer already sent.", null);
throw new Exception("Did not receive UAR or answer already sent. Request: " + this.request);
}
JUserAuthorizationAnswer answer = new JUserAuthorizationAnswerImpl((Request) this.request.getMessage(), 2001);
AvpSet reqSet = request.getMessage().getAvps();
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID));
request = null;
//
// < User-Authorization-Answer> ::= < Diameter Header: 300, PXY, 16777216 >
// < Session-Id >
// { Vendor-Specific-Application-Id }
if (set.getAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID) == null) {
AvpSet vendorSpecificApplicationId = set.addGroupedAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, 0, false, false);
// 1* [ Vendor-Id ]
vendorSpecificApplicationId.addAvp(Avp.VENDOR_ID, getApplicationId().getVendorId(), true);
// 0*1{ Auth-Application-Id }
vendorSpecificApplicationId.addAvp(Avp.AUTH_APPLICATION_ID, getApplicationId().getAuthAppId(), true);
}
// [ Result-Code ]
// [ Experimental-Result ]
// { Auth-Session-State }
if (set.getAvp(Avp.AUTH_SESSION_STATE) == null) {
set.addAvp(Avp.AUTH_SESSION_STATE, 1);
}
// { Origin-Host }
// { Origin-Realm }
// *[ Supported-Features ]
// [ Server-Name ]
// [ Server-Capabilities ]
// [ Wildcarded-IMPU ]
// *[ AVP ]
// *[ Failed-AVP ]
// *[ Proxy-Info ]
// *[ Route-Record ]
this.serverCxDxSession.sendUserAuthorizationAnswer(answer);
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
this.request = null;
this.sentUserAuthorization = true;
}
@Override
public Answer processRequest(Request request) {
int code = request.getCommandCode();
if (code != JUserAuthorizationRequest.code) {
fail("Received Request with code not used by CxDx!. Code[" + request.getCommandCode() + "]", null);
return null;
}
if (super.serverCxDxSession != null) {
// do fail?
fail("Received Request in base listener, not in app specific!" + code, null);
}
else {
try {
super.serverCxDxSession = ((ISessionFactory) this.sessionFactory).getNewAppSession(request.getSessionId(), getApplicationId(), ServerCxDxSession.class, (Object) null);
((NetworkReqListener) this.serverCxDxSession).processRequest(request);
}
catch (Exception e) {
e.printStackTrace();
fail(null, e);
}
}
return null;
}
@Override
public void doUserAuthorizationRequest(ServerCxDxSession session, JUserAuthorizationRequest request) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
if (this.receivedUserAuthorization) {
fail("Received UAR more than once", null);
return;
}
this.receivedUserAuthorization = true;
this.request = request;
}
public boolean isReceivedUserAuthorization() {
return receivedUserAuthorization;
}
public boolean isSentUserAuthorization() {
return sentUserAuthorization;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.cxdx.base;
import org.jdiameter.api.Answer;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.cxdx.ServerCxDxSession;
import org.jdiameter.api.cxdx.events.JServerAssignmentAnswer;
import org.jdiameter.api.cxdx.events.JServerAssignmentRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.impl.app.cxdx.JServerAssignmentAnswerImpl;
import org.mobicents.diameter.stack.functional.Utils;
import org.mobicents.diameter.stack.functional.cxdx.AbstractServer;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class ServerSAR extends AbstractServer {
protected boolean receivedServerAssignment;
protected boolean sentServerAssignment;
protected JServerAssignmentRequest request;
/**
*
*/
public ServerSAR() {
}
public void sendServerAssignment() throws Exception {
if (!receivedServerAssignment || request == null) {
fail("Did not receive SAR or answer already sent.", null);
throw new Exception("Did not receive SAR or answer already sent. Request: " + this.request);
}
JServerAssignmentAnswer answer = new JServerAssignmentAnswerImpl((Request) this.request.getMessage(), 2001);
AvpSet reqSet = request.getMessage().getAvps();
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID));
request = null;
// <Server-Assignment-Answer> ::= < Diameter Header: 301, PXY, 16777216 >
// < Session-Id >
// { Vendor-Specific-Application-Id }
if (set.getAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID) == null) {
AvpSet vendorSpecificApplicationId = set.addGroupedAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, 0, false, false);
// 1* [ Vendor-Id ]
vendorSpecificApplicationId.addAvp(Avp.VENDOR_ID, getApplicationId().getVendorId(), true);
// 0*1{ Auth-Application-Id }
vendorSpecificApplicationId.addAvp(Avp.AUTH_APPLICATION_ID, getApplicationId().getAuthAppId(), true);
}
// [ Result-Code ]
// [ Experimental-Result ]
// { Auth-Session-State }
if (set.getAvp(Avp.AUTH_SESSION_STATE) == null) {
set.addAvp(Avp.AUTH_SESSION_STATE, 1);
}
// { Origin-Host }
// { Origin-Realm }
// [ User-Name ]
// *[ Supported-Features ]
// [ User-Data ]
// [ Charging-Information ]
// [ Associated-Identities ]
// [ Loose-Route-Indication ]
// *[ SCSCF-Restoration-Info ]
// [ Associated-Registered-Identities ]
// [ Server-Name ]
// *[ AVP ]
// *[ Failed-AVP ]
// *[ Proxy-Info ]
// *[ Route-Record ]
this.serverCxDxSession.sendServerAssignmentAnswer(answer);
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
this.request = null;
this.sentServerAssignment = true;
}
@Override
public Answer processRequest(Request request) {
int code = request.getCommandCode();
if (code != JServerAssignmentRequest.code) {
fail("Received Request with code not used by CxDx!. Code[" + request.getCommandCode() + "]", null);
return null;
}
if (super.serverCxDxSession != null) {
// do fail?
fail("Received Request in base listener, not in app specific!" + code, null);
}
else {
try {
super.serverCxDxSession = ((ISessionFactory) this.sessionFactory).getNewAppSession(request.getSessionId(), getApplicationId(), ServerCxDxSession.class, (Object) null);
((NetworkReqListener) this.serverCxDxSession).processRequest(request);
}
catch (Exception e) {
e.printStackTrace();
fail(null, e);
}
}
return null;
}
@Override
public void doServerAssignmentRequest(ServerCxDxSession session, JServerAssignmentRequest request) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
if (this.receivedServerAssignment) {
fail("Received SAR more than once", null);
return;
}
this.receivedServerAssignment = true;
this.request = request;
}
public boolean isReceivedServerAssignment() {
return receivedServerAssignment;
}
public boolean isSentServerAssignment() {
return sentServerAssignment;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.cxdx.base;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.cxdx.ClientCxDxSession;
import org.jdiameter.api.cxdx.events.JLocationInfoAnswer;
import org.jdiameter.api.cxdx.events.JLocationInfoRequest;
import org.jdiameter.common.impl.app.cxdx.JLocationInfoRequestImpl;
import org.mobicents.diameter.stack.functional.Utils;
import org.mobicents.diameter.stack.functional.cxdx.AbstractClient;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class ClientLIR extends AbstractClient {
protected boolean receivedLocationInfo;
protected boolean sentLocationInfo;
/**
*
*/
public ClientLIR() {
}
public void sendLocationInfo() throws Exception {
JLocationInfoRequest request = new JLocationInfoRequestImpl(super.createRequest(this.clientCxDxSession, JLocationInfoRequest.code));
AvpSet reqSet = request.getMessage().getAvps();
reqSet.addAvp(Avp.SERVER_NAME, "ala", getApplicationId().getVendorId(), true, false, false);
// <Location-Info-Request> ::= < Diameter Header: 302, REQ, PXY,
// 16777216 >
// < Session-Id >
// { Vendor-Specific-Application-Id }
// { Auth-Session-State }
// { Origin-Host }
// { Origin-Realm }
// [ Destination-Host ]
// { Destination-Realm }
// [ Originating-Request ]
// *[ Supported-Features ]
// { Public-Identity }
AvpSet userIdentity = reqSet.addGroupedAvp(Avp.USER_IDENTITY, getApplicationId().getVendorId(), true, false);
// User-Identity ::= <AVP header: 700 10415>
// [Public-Identity]
userIdentity.addAvp(Avp.PUBLIC_IDENTITY, "tralalalal user", getApplicationId().getVendorId(), true, false, false);
// [MSISDN]
// *[AVP]
// [ User-Authorization-Type ]
// *[ AVP ]
// *[ Proxy-Info ]
this.clientCxDxSession.sendLocationInformationRequest(request);
Utils.printMessage(log, super.stack.getDictionary(), request.getMessage(), true);
this.sentLocationInfo = true;
}
@Override
public void doLocationInformationAnswer(ClientCxDxSession session, JLocationInfoRequest request, JLocationInfoAnswer answer) throws InternalException,
IllegalDiameterStateException, RouteException, OverloadException {
if (this.receivedLocationInfo) {
fail("Received LIA more than once", null);
return;
}
this.receivedLocationInfo = true;
}
public boolean isReceivedLocationInfo() {
return receivedLocationInfo;
}
public boolean isSentLocationInfo() {
return sentLocationInfo;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.cxdx;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Mode;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.app.AppAnswerEvent;
import org.jdiameter.api.app.AppRequestEvent;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.cxdx.ClientCxDxSession;
import org.jdiameter.api.cxdx.ClientCxDxSessionListener;
import org.jdiameter.api.cxdx.ServerCxDxSession;
import org.jdiameter.api.cxdx.events.JLocationInfoAnswer;
import org.jdiameter.api.cxdx.events.JLocationInfoRequest;
import org.jdiameter.api.cxdx.events.JMultimediaAuthAnswer;
import org.jdiameter.api.cxdx.events.JMultimediaAuthRequest;
import org.jdiameter.api.cxdx.events.JPushProfileRequest;
import org.jdiameter.api.cxdx.events.JRegistrationTerminationRequest;
import org.jdiameter.api.cxdx.events.JServerAssignmentAnswer;
import org.jdiameter.api.cxdx.events.JServerAssignmentRequest;
import org.jdiameter.api.cxdx.events.JUserAuthorizationAnswer;
import org.jdiameter.api.cxdx.events.JUserAuthorizationRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.impl.app.cxdx.CxDxSessionFactoryImpl;
import org.mobicents.diameter.stack.functional.TBase;
/**
* @author baranowb
*
*/
public abstract class AbstractClient extends TBase implements ClientCxDxSessionListener {
// NOTE: implementing NetworkReqListener since its required for stack to
// know we support it... ech.
protected ClientCxDxSession clientCxDxSession;
public void init(InputStream configStream, String clientID) throws Exception {
try {
super.init(configStream, clientID, ApplicationId.createByAuthAppId(10415, 16777216));
CxDxSessionFactoryImpl shSessionFactory = new CxDxSessionFactoryImpl(this.sessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ServerCxDxSession.class, shSessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ClientCxDxSession.class, shSessionFactory);
shSessionFactory.setClientSessionListener(this);
this.clientCxDxSession = ((ISessionFactory) this.sessionFactory).getNewAppSession(this.sessionFactory.getSessionId("xxTESTxx"), getApplicationId(), ClientCxDxSession.class,
null); // true...
}
finally {
try {
configStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
// ----------- delegate methods so
public void start() throws IllegalDiameterStateException, InternalException {
stack.start();
}
public void start(Mode mode, long timeOut, TimeUnit timeUnit) throws IllegalDiameterStateException, InternalException {
stack.start(mode, timeOut, timeUnit);
}
public void stop(long timeOut, TimeUnit timeUnit, int disconnectCause) throws IllegalDiameterStateException, InternalException {
stack.stop(timeOut, timeUnit, disconnectCause);
}
public void stop(int disconnectCause) {
stack.stop(disconnectCause);
}
// ------- def methods, to fail :)
public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
fail("Received \"Other\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null);
}
public void doUserAuthorizationAnswer(ClientCxDxSession session, JUserAuthorizationRequest request, JUserAuthorizationAnswer answer) throws InternalException,
IllegalDiameterStateException, RouteException, OverloadException {
fail("Received \"UAA\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null);
}
public void doServerAssignmentAnswer(ClientCxDxSession session, JServerAssignmentRequest request, JServerAssignmentAnswer answer) throws InternalException,
IllegalDiameterStateException, RouteException, OverloadException {
fail("Received \"SAA\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null);
}
public void doRegistrationTerminationRequest(ClientCxDxSession session, JRegistrationTerminationRequest request) throws InternalException, IllegalDiameterStateException,
RouteException, OverloadException {
fail("Received \"RTR\" event, request[" + request + "], on session[" + session + "]", null);
}
public void doLocationInformationAnswer(ClientCxDxSession session, JLocationInfoRequest request, JLocationInfoAnswer answer) throws InternalException,
IllegalDiameterStateException, RouteException, OverloadException {
fail("Received \"LIA\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null);
}
public void doPushProfileRequest(ClientCxDxSession session, JPushProfileRequest request) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
fail("Received \"PPR\" event, request[" + request + "], on session[" + session + "]", null);
}
public void doMultimediaAuthAnswer(ClientCxDxSession session, JMultimediaAuthRequest request, JMultimediaAuthAnswer answer) throws InternalException,
IllegalDiameterStateException, RouteException, OverloadException {
fail("Received \"MAA\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null);
}
// ----------- conf parts
public String getSessionId() {
return this.clientCxDxSession.getSessionId();
}
public ClientCxDxSession getSession() {
return this.clientCxDxSession;
}
// ----------- helper
protected Request createRequest(AppSession session, int code) {
Request r = session.getSessions().get(0).createRequest(code, getApplicationId(), getServerRealmName());
AvpSet reqSet = r.getAvps();
AvpSet vendorSpecificApplicationId = reqSet.addGroupedAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, 0, false, false);
// 1* [ Vendor-Id ]
vendorSpecificApplicationId.addAvp(Avp.VENDOR_ID, getApplicationId().getVendorId(), true);
// 0*1{ Auth-Application-Id }
vendorSpecificApplicationId.addAvp(Avp.AUTH_APPLICATION_ID, getApplicationId().getAuthAppId(), true);
// 0*1{ Acct-Application-Id }
// { Auth-Session-State }
reqSet.addAvp(Avp.AUTH_SESSION_STATE, 1);
// { Origin-Host }
reqSet.removeAvp(Avp.ORIGIN_HOST);
reqSet.addAvp(Avp.ORIGIN_HOST, getClientURI(), true);
return r;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.cxdx;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Mode;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.app.AppAnswerEvent;
import org.jdiameter.api.app.AppRequestEvent;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.cxdx.ClientCxDxSession;
import org.jdiameter.api.cxdx.ServerCxDxSession;
import org.jdiameter.api.cxdx.ServerCxDxSessionListener;
import org.jdiameter.api.cxdx.events.JLocationInfoRequest;
import org.jdiameter.api.cxdx.events.JMultimediaAuthRequest;
import org.jdiameter.api.cxdx.events.JPushProfileAnswer;
import org.jdiameter.api.cxdx.events.JPushProfileRequest;
import org.jdiameter.api.cxdx.events.JRegistrationTerminationAnswer;
import org.jdiameter.api.cxdx.events.JRegistrationTerminationRequest;
import org.jdiameter.api.cxdx.events.JServerAssignmentRequest;
import org.jdiameter.api.cxdx.events.JUserAuthorizationRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.impl.app.cxdx.CxDxSessionFactoryImpl;
import org.mobicents.diameter.stack.functional.TBase;
/**
* @author baranowb
*
*/
public abstract class AbstractServer extends TBase implements ServerCxDxSessionListener {
// NOTE: implementing NetworkReqListener since its required for stack to
// know we support it... ech.
protected ServerCxDxSession serverCxDxSession;
public void init(InputStream configStream, String clientID) throws Exception {
try {
super.init(configStream, clientID, ApplicationId.createByAuthAppId(10415, 16777216));
CxDxSessionFactoryImpl cxDxSessionFactory = new CxDxSessionFactoryImpl(this.sessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ServerCxDxSession.class, cxDxSessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ClientCxDxSession.class, cxDxSessionFactory);
cxDxSessionFactory.setServerSessionListener(this);
}
finally {
try {
configStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
// ----------- delegate methods so
public void start() throws IllegalDiameterStateException, InternalException {
stack.start();
}
public void start(Mode mode, long timeOut, TimeUnit timeUnit) throws IllegalDiameterStateException, InternalException {
stack.start(mode, timeOut, timeUnit);
}
public void stop(long timeOut, TimeUnit timeUnit, int disconnectCause) throws IllegalDiameterStateException, InternalException {
stack.stop(timeOut, timeUnit, disconnectCause);
}
public void stop(int disconnectCause) {
stack.stop(disconnectCause);
}
public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
fail("Received \"Other\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null);
}
public void doUserAuthorizationRequest(ServerCxDxSession session, JUserAuthorizationRequest request) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
fail("Received \"UAR\" event, request[" + request + "], on session[" + session + "]", null);
}
public void doServerAssignmentRequest(ServerCxDxSession session, JServerAssignmentRequest request) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
fail("Received \"SAR\" event, request[" + request + "], on session[" + session + "]", null);
}
public void doRegistrationTerminationAnswer(ServerCxDxSession session, JRegistrationTerminationRequest request, JRegistrationTerminationAnswer answer) throws InternalException,
IllegalDiameterStateException, RouteException, OverloadException {
fail("Received \"RTA\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null);
}
public void doLocationInformationRequest(ServerCxDxSession session, JLocationInfoRequest request) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
fail("Received \"LIR\" event, request[" + request + "], on session[" + session + "]", null);
}
public void doPushProfileAnswer(ServerCxDxSession session, JPushProfileRequest request, JPushProfileAnswer answer) throws InternalException, IllegalDiameterStateException,
RouteException, OverloadException {
fail("Received \"PPA\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null);
}
public void doMultimediaAuthRequest(ServerCxDxSession session, JMultimediaAuthRequest request) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
fail("Received \"MAR\" event, request[" + request + "], on session[" + session + "]", null);
}
// -------- conf
public String getSessionId() {
return this.serverCxDxSession.getSessionId();
}
public ServerCxDxSession getSession() {
return this.serverCxDxSession;
}
// ----------- helper
protected Request createRequest(AppSession session, int code) {
Request r = session.getSessions().get(0).createRequest(code, getApplicationId(), getClientRealmName());
AvpSet reqSet = r.getAvps();
AvpSet vendorSpecificApplicationId = reqSet.addGroupedAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, 0, false, false);
// 1* [ Vendor-Id ]
vendorSpecificApplicationId.addAvp(Avp.VENDOR_ID, getApplicationId().getVendorId(), true);
// 0*1{ Auth-Application-Id }
vendorSpecificApplicationId.addAvp(Avp.AUTH_APPLICATION_ID, getApplicationId().getAuthAppId(), true);
// 0*1{ Acct-Application-Id }
// { Auth-Session-State }
reqSet.addAvp(Avp.AUTH_SESSION_STATE, 1);
// { Origin-Host }
reqSet.removeAvp(Avp.ORIGIN_HOST);
reqSet.addAvp(Avp.ORIGIN_HOST, getServerURI(), true);
return r;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.gx.base;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.app.AppAnswerEvent;
import org.jdiameter.api.app.AppRequestEvent;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.gx.ClientGxSession;
import org.jdiameter.api.gx.events.GxCreditControlAnswer;
import org.jdiameter.api.gx.events.GxCreditControlRequest;
import org.jdiameter.api.gx.events.GxReAuthRequest;
import org.jdiameter.common.impl.app.gx.GxReAuthAnswerImpl;
import org.mobicents.diameter.stack.functional.Utils;
import org.mobicents.diameter.stack.functional.gx.AbstractClient;
/**
* Base implementation of Client
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class Client extends AbstractClient {
protected boolean sentINITIAL;
protected boolean sentINTERIM;
protected boolean sentTERMINATE;
protected boolean sentEVENT;
protected boolean sentREAUTH;
protected boolean receiveINITIAL;
protected boolean receiveINTERIM;
protected boolean receiveTERMINATE;
protected boolean receiveEVENT;
protected boolean receiveREAUTH;
protected GxReAuthRequest reAuthRequest;
/**
*
*/
public Client() {
}
public void sendInitial() throws Exception {
GxCreditControlRequest initialRequest = super.createCCR(CC_REQUEST_TYPE_INITIAL, this.ccRequestNumber, super.clientGxSession);
this.ccRequestNumber++;
super.clientGxSession.sendCreditControlRequest(initialRequest);
Utils.printMessage(log, super.stack.getDictionary(), initialRequest.getMessage(), true);
this.sentINITIAL = true;
}
public void sendInterim() throws Exception {
if (!receiveINITIAL) {
throw new Exception();
}
GxCreditControlRequest interimRequest = super.createCCR(CC_REQUEST_TYPE_INTERIM, this.ccRequestNumber, super.clientGxSession);
this.ccRequestNumber++;
super.clientGxSession.sendCreditControlRequest(interimRequest);
Utils.printMessage(log, super.stack.getDictionary(), interimRequest.getMessage(), true);
this.sentINTERIM = true;
}
public void sendTermination() throws Exception {
if (!receiveINTERIM) {
throw new Exception();
}
GxCreditControlRequest terminateRequest = super.createCCR(CC_REQUEST_TYPE_TERMINATE, this.ccRequestNumber, super.clientGxSession);
this.ccRequestNumber++;
super.clientGxSession.sendCreditControlRequest(terminateRequest);
Utils.printMessage(log, super.stack.getDictionary(), terminateRequest.getMessage(), true);
this.sentTERMINATE = true;
}
public void sendEvent() throws Exception {
GxCreditControlRequest eventRequest = super.createCCR(CC_REQUEST_TYPE_TERMINATE, this.ccRequestNumber, super.clientGxSession);
this.ccRequestNumber++;
super.clientGxSession.sendCreditControlRequest(eventRequest);
Utils.printMessage(log, super.stack.getDictionary(), eventRequest.getMessage(), true);
this.sentEVENT = true;
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ClientCCASessionListener#doCreditControlAnswer( org.jdiameter.api.cca.ClientCCASession,
* org.jdiameter.api.cca.events.GxCreditControlRequest, org.jdiameter.api.cca.events.JCreditControlAnswer)
*/
public void doCreditControlAnswer(ClientGxSession session, GxCreditControlRequest request, GxCreditControlAnswer answer) throws InternalException, IllegalDiameterStateException,
RouteException, OverloadException {
try {
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), false);
switch (answer.getRequestTypeAVPValue()) {
case CC_REQUEST_TYPE_INITIAL:
if (receiveINITIAL) {
fail("Received INITIAL more than once!", null);
}
receiveINITIAL = true;
break;
case CC_REQUEST_TYPE_INTERIM:
if (receiveINTERIM) {
fail("Received INTERIM more than once!", null);
}
receiveINTERIM = true;
break;
case CC_REQUEST_TYPE_TERMINATE:
if (receiveTERMINATE) {
fail("Received TERMINATE more than once!", null);
}
receiveTERMINATE = true;
break;
case CC_REQUEST_TYPE_EVENT:
if (receiveEVENT) {
fail("Received EVENT more than once!", null);
}
receiveEVENT = true;
break;
default:
}
}
catch (Exception e) {
e.printStackTrace();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ClientCCASessionListener#doReAuthRequest(org.jdiameter .api.cca.ClientCCASession,
* org.jdiameter.api.auth.events.ReAuthRequest)
*/
public void doGxReAuthRequest(ClientGxSession session, GxReAuthRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
try {
Utils.printMessage(log, super.stack.getDictionary(), request.getMessage(), false);
if (sentREAUTH) {
fail("Received REAUTH more than once!", null);
}
receiveREAUTH = true;
reAuthRequest = request;
}
catch (Exception e) {
e.printStackTrace();
}
//fail("Received \"ReAuthRequest\" event, request[" + request + "], on session[" + session + "]", null);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ClientCCASessionListener#doOtherEvent(org.jdiameter .api.app.AppSession,
* org.jdiameter.api.app.AppRequestEvent, org.jdiameter.api.app.AppAnswerEvent)
*/
public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
fail("Received \"Other\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null);
}
// ------------ getters for some vars;
public boolean isSentINITIAL() {
return sentINITIAL;
}
public boolean isSentEVENT() {
return sentEVENT;
}
public boolean isReceiveEVENT() {
return receiveEVENT;
}
public boolean isSentINTERIM() {
return sentINTERIM;
}
public boolean isSentTERMINATE() {
return sentTERMINATE;
}
public boolean isReceiveINITIAL() {
return receiveINITIAL;
}
public boolean isReceiveINTERIM() {
return receiveINTERIM;
}
public boolean isReceiveTERMINATE() {
return receiveTERMINATE;
}
// ------------ getters for some vars;
@Override
protected int getChargingUnitsTime() {
return 10;
}
@Override
protected String getServiceContextId() {
return "tralalalal ID";
}
public void sendReAuth() throws Exception {
if (!this.receiveREAUTH || reAuthRequest == null) {
fail("Did not receive REAUTH or answer already sent.", null);
throw new Exception("Request: " + this.reAuthRequest);
}
GxReAuthAnswerImpl answer = new GxReAuthAnswerImpl((Request) reAuthRequest.getMessage(), 2001);
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
super.clientGxSession.sendGxReAuthAnswer(answer);
sentREAUTH = true;
reAuthRequest = null;
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.gx.base;
import org.jdiameter.api.Answer;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.app.AppAnswerEvent;
import org.jdiameter.api.app.AppRequestEvent;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.gx.ServerGxSession;
import org.jdiameter.api.gx.events.GxCreditControlAnswer;
import org.jdiameter.api.gx.events.GxCreditControlRequest;
import org.jdiameter.api.gx.events.GxReAuthAnswer;
import org.jdiameter.api.gx.events.GxReAuthRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.impl.app.gx.GxCreditControlAnswerImpl;
import org.mobicents.diameter.stack.functional.Utils;
import org.mobicents.diameter.stack.functional.gx.AbstractServer;
/**
* Base implementation of Server
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class Server extends AbstractServer {
protected boolean sentINITIAL;
protected boolean sentINTERIM;
protected boolean sentTERMINATE;
protected boolean sentEVENT;
protected boolean sentREAUTH;
protected boolean receiveINITIAL;
protected boolean receiveINTERIM;
protected boolean receiveTERMINATE;
protected boolean receiveEVENT;
protected boolean receiveREAUTH;
protected GxCreditControlRequest request;
// ------- send methods to trigger answer
public void sendInitial() throws Exception {
if (!this.receiveINITIAL || this.request == null) {
fail("Did not receive INITIAL or answer already sent.", null);
throw new Exception("Request: " + this.request);
}
GxCreditControlAnswer answer = new GxCreditControlAnswerImpl((Request) request.getMessage(), 2001);
AvpSet reqSet = request.getMessage().getAvps();
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID));
super.serverGxSession.sendCreditControlAnswer(answer);
sentINITIAL = true;
request = null;
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
}
public void sendInterim() throws Exception {
if (!this.receiveINTERIM || this.request == null) {
fail("Did not receive INTERIM or answer already sent.", null);
throw new Exception("Request: " + this.request);
}
GxCreditControlAnswerImpl answer = new GxCreditControlAnswerImpl((Request) request.getMessage(), 2001);
AvpSet reqSet = request.getMessage().getAvps();
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID));
super.serverGxSession.sendCreditControlAnswer(answer);
sentINTERIM = true;
request = null;
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
}
public void sendReAuth() throws Exception {
if (!(this.receiveINITIAL || this.receiveINTERIM) || this.request != null) {
fail("Did not receive INITIAL/INTERIM or pending request exists.", null);
throw new Exception("Request: " + this.request);
}
GxReAuthRequest reAuthRequest = super.createRAR(0 /*AUTHORIZE_ONLY*/, super.serverGxSession);
super.serverGxSession.sendGxReAuthRequest(reAuthRequest);
Utils.printMessage(log, super.stack.getDictionary(), reAuthRequest.getMessage(), true);
this.sentREAUTH = true;
}
public void send() throws Exception {
if (!this.receiveINTERIM || this.request == null) {
fail("Did not receive INTERIM or answer already sent.", null);
throw new Exception("Request: " + this.request);
}
GxCreditControlAnswerImpl answer = new GxCreditControlAnswerImpl((Request) request.getMessage(), 2001);
AvpSet reqSet = request.getMessage().getAvps();
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID));
super.serverGxSession.sendCreditControlAnswer(answer);
sentINTERIM = true;
request = null;
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
}
public void sendTermination() throws Exception {
if (!this.receiveTERMINATE || this.request == null) {
fail("Did not receive TERMINATE or answer already sent.", null);
throw new Exception("Request: " + this.request);
}
GxCreditControlAnswerImpl answer = new GxCreditControlAnswerImpl((Request) request.getMessage(), 2001);
AvpSet reqSet = request.getMessage().getAvps();
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID));
super.serverGxSession.sendCreditControlAnswer(answer);
sentTERMINATE = true;
request = null;
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
}
public void sendEvent() throws Exception {
if (!this.receiveEVENT || this.request == null) {
fail("Did not receive EVENT or answer already sent.", null);
throw new Exception("Request: " + this.request);
}
GxCreditControlAnswerImpl answer = new GxCreditControlAnswerImpl((Request) request.getMessage(), 2001);
AvpSet reqSet = request.getMessage().getAvps();
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID));
super.serverGxSession.sendCreditControlAnswer(answer);
sentEVENT = true;
request = null;
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
}
// ------- initial, this will be triggered for first msg.
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.NetworkReqListener#processRequest(org.jdiameter.api.Request)
*/
@Override
public Answer processRequest(Request request) {
if (request.getCommandCode() != 272) {
fail("Received Request with code not equal 272!. Code[" + request.getCommandCode() + "]", null);
return null;
}
if (super.serverGxSession == null) {
try {
super.serverGxSession = ((ISessionFactory) this.sessionFactory).getNewAppSession(request.getSessionId(), getApplicationId(), ServerGxSession.class, (Object) null);
((NetworkReqListener) this.serverGxSession).processRequest(request);
}
catch (Exception e) {
fail(null, e);
}
}
else {
// do fail?
fail("Received Request in base listener, not in app specific!", null);
}
return null;
}
// ------------- specific, app session listener.
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ServerGxSessionListener#doCreditControlRequest(org.jdiameter.api.cca.ServerGxSession,
* org.jdiameter.api.cca.events.GxCreditControlRequest)
*/
public void doCreditControlRequest(ServerGxSession session, GxCreditControlRequest request) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
try {
Utils.printMessage(log, super.stack.getDictionary(), request.getMessage(), false);
// INITIAL_REQUEST 1,
// UPDATE_REQUEST 2,
// TERMINATION_REQUEST 3,
// EVENT_REQUEST 4
switch (request.getRequestTypeAVPValue()) {
case CC_REQUEST_TYPE_INITIAL:
if (receiveINITIAL) {
fail("Received INITIAL more than once!", null);
}
receiveINITIAL = true;
this.request = request;
break;
case CC_REQUEST_TYPE_INTERIM:
if (receiveINTERIM) {
fail("Received INTERIM more than once!", null);
}
receiveINTERIM = true;
this.request = request;
break;
case CC_REQUEST_TYPE_TERMINATE:
if (receiveTERMINATE) {
fail("Received TERMINATE more than once!", null);
}
receiveTERMINATE = true;
this.request = request;
break;
case CC_REQUEST_TYPE_EVENT:
if (receiveEVENT) {
fail("Received EVENT more than once!", null);
}
receiveEVENT = true;
this.request = request;
break;
default:
fail("No REQ type present?: " + request.getRequestTypeAVPValue(), null);
}
}
catch (Exception e) {
fail(null, e);
}
}
/*
* (non-Javadoc)
* @see org.jdiameter.api.gx.ServerGxSessionListener#doGxReAuthAnswer(org.jdiameter.api.gx.ServerGxSession, org.jdiameter.api.gx.events.GxReAuthRequest, org.jdiameter.api.gx.events.GxReAuthAnswer)
*/
public void doGxReAuthAnswer(ServerGxSession session, GxReAuthRequest request, GxReAuthAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), false);
if (receiveREAUTH) {
fail("Received REAUTH more than once!", null);
}
receiveREAUTH = true;
//fail("Received \"ReAuthAnswer\" event, request[" + request + "], on session[" + session + "]", null);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ServerGxSessionListener#doOtherEvent(org.jdiameter.api.app.AppSession,
* org.jdiameter.api.app.AppRequestEvent, org.jdiameter.api.app.AppAnswerEvent)
*/
public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
fail("Received \"Other\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null);
}
public boolean isSentINITIAL() {
return sentINITIAL;
}
public boolean isSentINTERIM() {
return sentINTERIM;
}
public boolean isSentTERMINATE() {
return sentTERMINATE;
}
public boolean isSentREAUTH() {
return sentREAUTH;
}
public boolean isReceiveINITIAL() {
return receiveINITIAL;
}
public boolean isReceiveINTERIM() {
return receiveINTERIM;
}
public boolean isReceiveTERMINATE() {
return receiveTERMINATE;
}
public boolean isReceiveREAUTH() {
return receiveREAUTH;
}
public boolean isSentEVENT() {
return sentEVENT;
}
public boolean isReceiveEVENT() {
return receiveEVENT;
}
public GxCreditControlRequest getRequest() {
return request;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.gx;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Message;
import org.jdiameter.api.Mode;
import org.jdiameter.api.gx.ClientGxSession;
import org.jdiameter.api.gx.ClientGxSessionListener;
import org.jdiameter.api.gx.ServerGxSession;
import org.jdiameter.api.gx.events.GxCreditControlRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.api.app.gx.ClientGxSessionState;
import org.jdiameter.common.api.app.gx.IClientGxSessionContext;
import org.jdiameter.common.impl.app.gx.GxCreditControlRequestImpl;
import org.jdiameter.common.impl.app.gx.GxSessionFactoryImpl;
import org.mobicents.diameter.stack.functional.StateChange;
import org.mobicents.diameter.stack.functional.TBase;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public abstract class AbstractClient extends TBase implements ClientGxSessionListener, IClientGxSessionContext {
// NOTE: implementing NetworkReqListener since its required for stack to
// know we support it... ech.
protected static final int CC_REQUEST_TYPE_INITIAL = 1;
protected static final int CC_REQUEST_TYPE_INTERIM = 2;
protected static final int CC_REQUEST_TYPE_TERMINATE = 3;
protected static final int CC_REQUEST_TYPE_EVENT = 4;
protected ClientGxSession clientGxSession;
protected int ccRequestNumber = 0;
protected List<StateChange<ClientGxSessionState>> stateChanges = new ArrayList<StateChange<ClientGxSessionState>>(); // state changes
public void init(InputStream configStream, String clientID) throws Exception {
try {
super.init(configStream, clientID, ApplicationId.createByAuthAppId(10415, 16777224));
GxSessionFactoryImpl creditControlSessionFactory = new GxSessionFactoryImpl(this.sessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ServerGxSession.class, creditControlSessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ClientGxSession.class, creditControlSessionFactory);
creditControlSessionFactory.setStateListener(this);
creditControlSessionFactory.setClientSessionListener(this);
creditControlSessionFactory.setClientContextListener(this);
this.clientGxSession = ((ISessionFactory) this.sessionFactory)
.getNewAppSession(this.sessionFactory.getSessionId("xxTESTxx"), getApplicationId(), ClientGxSession.class, (Object) null);
}
finally {
try {
configStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
// ----------- delegate methods so
public void start() throws IllegalDiameterStateException, InternalException {
stack.start();
}
public void start(Mode mode, long timeOut, TimeUnit timeUnit) throws IllegalDiameterStateException, InternalException {
stack.start(mode, timeOut, timeUnit);
}
public void stop(long timeOut, TimeUnit timeUnit, int disconnectCause) throws IllegalDiameterStateException, InternalException {
stack.stop(timeOut, timeUnit, disconnectCause);
}
public void stop(int disconnectCause) {
stack.stop(disconnectCause);
}
// ----------- conf parts
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.cca.IClientCCASessionContext# getDefaultTxTimerValue()
*/
public long getDefaultTxTimerValue() {
return 10;
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ClientCCASessionListener#getDefaultDDFHValue()
*/
public int getDefaultDDFHValue() {
// DDFH_CONTINUE: 1
return 1;
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ClientCCASessionListener#getDefaultCCFHValue()
*/
public int getDefaultCCFHValue() {
// CCFH_CONTINUE: 1
return 1;
}
// ------------ leave those
public void txTimerExpired(ClientGxSession session) {
// NOP
}
public void grantAccessOnDeliverFailure(ClientGxSession clientCCASessionImpl, Message request) {
// NOP
}
public void denyAccessOnDeliverFailure(ClientGxSession clientCCASessionImpl, Message request) {
// NOP
}
public void grantAccessOnTxExpire(ClientGxSession clientCCASessionImpl) {
// NOP
}
public void denyAccessOnTxExpire(ClientGxSession clientCCASessionImpl) {
// NOP
}
public void grantAccessOnFailureMessage(ClientGxSession clientCCASessionImpl) {
// NOP
}
public void denyAccessOnFailureMessage(ClientGxSession clientCCASessionImpl) {
// NOP
}
public void indicateServiceError(ClientGxSession clientCCASessionImpl) {
// NOP
}
// ---------- some helper methods.
protected GxCreditControlRequest createCCR(int ccRequestType, int requestNumber, ClientGxSession ccaSession) throws Exception {
// Create Credit-Control-Request
GxCreditControlRequest ccr = new GxCreditControlRequestImpl(ccaSession.getSessions().get(0)
.createRequest(GxCreditControlRequest.code, getApplicationId(), getServerRealmName()));
// AVPs present by default: Origin-Host, Origin-Realm, Session-Id,
// Vendor-Specific-Application-Id, Destination-Realm
AvpSet ccrAvps = ccr.getMessage().getAvps();
// Add remaining AVPs ... from RFC 4006:
// <CCR> ::= < Diameter Header: 272, REQ, PXY >
// < Session-Id >
// ccrAvps.addAvp(Avp.SESSION_ID, s.getSessionId());
// { Origin-Host }
ccrAvps.removeAvp(Avp.ORIGIN_HOST);
ccrAvps.addAvp(Avp.ORIGIN_HOST, getClientURI(), true);
// { Origin-Realm }
// ccrAvps.addAvp(Avp.ORIGIN_REALM, realmName, true);
// { Destination-Realm }
// ccrAvps.addAvp(Avp.DESTINATION_REALM, realmName, true);
// { Auth-Application-Id }
ccrAvps.addAvp(Avp.AUTH_APPLICATION_ID, 4);
// { Service-Context-Id }
// 8.42. Service-Context-Id AVP
//
// The Service-Context-Id AVP is of type UTF8String (AVP Code 461) and
// contains a unique identifier of the Diameter credit-control service
// specific document that applies to the request (as defined in section
// 4.1.2). This is an identifier allocated by the service provider, by
// the service element manufacturer, or by a standardization body, and
// MUST uniquely identify a given Diameter credit-control service
// specific document. The format of the Service-Context-Id is:
//
// "service-context" "@" "domain"
//
// service-context = Token
//
// The Token is an arbitrary string of characters and digits.
//
// 'domain' represents the entity that allocated the Service-Context-Id.
// It can be ietf.org, 3gpp.org, etc., if the identifier is allocated by
// a standardization body, or it can be the FQDN of the service provider
// (e.g., provider.example.com) or of the vendor (e.g.,
// vendor.example.com) if the identifier is allocated by a private
// entity.
//
// This AVP SHOULD be placed as close to the Diameter header as
// possible.
//
// Service-specific documents that are for private use only (i.e., to
// one provider's own use, where no interoperability is deemed useful)
// may define private identifiers without need of coordination.
// However, when interoperability is wanted, coordination of the
// identifiers via, for example, publication of an informational RFC is
// RECOMMENDED in order to make Service-Context-Id globally available.
String serviceContextId = getServiceContextId();
if (serviceContextId == null) {
serviceContextId = UUID.randomUUID().toString().replaceAll("-", "") + "@mss.mobicents.org";
}
ccrAvps.addAvp(Avp.SERVICE_CONTEXT_ID, serviceContextId, false);
// { CC-Request-Type }
// 8.3. CC-Request-Type AVP
//
// The CC-Request-Type AVP (AVP Code 416) is of type Enumerated and
// contains the reason for sending the credit-control request message.
// It MUST be present in all Credit-Control-Request messages. The
// following values are defined for the CC-Request-Type AVP:
//
// INITIAL_REQUEST 1
// An Initial request is used to initiate a credit-control session,
// and contains credit control information that is relevant to the
// initiation.
//
// UPDATE_REQUEST 2
// An Update request contains credit-control information for an
// existing credit-control session. Update credit-control requests
// SHOULD be sent every time a credit-control re-authorization is
// needed at the expiry of the allocated quota or validity time.
// Further, additional service-specific events MAY trigger a
// spontaneous Update request.
//
// TERMINATION_REQUEST 3
// A Termination request is sent to terminate a credit-control
// session and contains credit-control information relevant to the
// existing session.
//
// EVENT_REQUEST 4
// An Event request is used when there is no need to maintain any
// credit-control session state in the credit-control server. This
// request contains all information relevant to the service, and is
// the only request of the service. The reason for the Event request
// is further detailed in the Requested-Action AVP. The Requested-
// Action AVP MUST be included in the Credit-Control-Request message
// when CC-Request-Type is set to EVENT_REQUEST.
ccrAvps.addAvp(Avp.CC_REQUEST_TYPE, ccRequestType);
// { CC-Request-Number }
// 8.2. CC-Request-Number AVP
//
// The CC-Request-Number AVP (AVP Code 415) is of type Unsigned32 and
// identifies this request within one session. As Session-Id AVPs are
// globally unique, the combination of Session-Id and CC-Request-Number
// AVPs is also globally unique and can be used in matching credit-
// control messages with confirmations. An easy way to produce unique
// numbers is to set the value to 0 for a credit-control request of type
// INITIAL_REQUEST and EVENT_REQUEST and to set the value to 1 for the
// first UPDATE_REQUEST, to 2 for the second, and so on until the value
// for TERMINATION_REQUEST is one more than for the last UPDATE_REQUEST.
ccrAvps.addAvp(Avp.CC_REQUEST_NUMBER, requestNumber);
// [ Destination-Host ]
ccrAvps.removeAvp(Avp.DESTINATION_HOST);
// ccrAvps.addAvp(Avp.DESTINATION_HOST, ccRequestType == 2 ?
// serverURINode1 : serverURINode1, false);
// [ User-Name ]
// [ CC-Sub-Session-Id ]
// [ Acct-Multi-Session-Id ]
// [ Origin-State-Id ]
// [ Event-Timestamp ]
// *[ Subscription-Id ]
// 8.46. Subscription-Id AVP
//
// The Subscription-Id AVP (AVP Code 443) is used to identify the end
// user's subscription and is of type Grouped. The Subscription-Id AVP
// includes a Subscription-Id-Data AVP that holds the identifier and a
// Subscription-Id-Type AVP that defines the identifier type.
//
// It is defined as follows (per the grouped-avp-def of RFC 3588
// [DIAMBASE]):
//
// Subscription-Id ::= < AVP Header: 443 >
// { Subscription-Id-Type }
// { Subscription-Id-Data }
AvpSet subscriptionId = ccrAvps.addGroupedAvp(Avp.SUBSCRIPTION_ID);
// 8.47. Subscription-Id-Type AVP
//
// The Subscription-Id-Type AVP (AVP Code 450) is of type Enumerated,
// and it is used to determine which type of identifier is carried by
// the Subscription-Id AVP.
//
// This specification defines the following subscription identifiers.
// However, new Subscription-Id-Type values can be assigned by an IANA
// designated expert, as defined in section 12. A server MUST implement
// all the Subscription-Id-Types required to perform credit
// authorization for the services it supports, including possible future
// values. Unknown or unsupported Subscription-Id-Types MUST be treated
// according to the 'M' flag rule, as defined in [DIAMBASE].
//
// END_USER_E164 0
// The identifier is in international E.164 format (e.g., MSISDN),
// according to the ITU-T E.164 numbering plan defined in [E164] and
// [CE164].
//
// END_USER_IMSI 1
// The identifier is in international IMSI format, according to the
// ITU-T E.212 numbering plan as defined in [E212] and [CE212].
//
// END_USER_SIP_URI 2
// The identifier is in the form of a SIP URI, as defined in [SIP].
//
// END_USER_NAI 3
// The identifier is in the form of a Network Access Identifier, as
// defined in [NAI].
//
// END_USER_PRIVATE 4
// The Identifier is a credit-control server private identifier.
subscriptionId.addAvp(Avp.SUBSCRIPTION_ID_TYPE, 2);
// 8.48. Subscription-Id-Data AVP
//
// The Subscription-Id-Data AVP (AVP Code 444) is used to identify the
// end user and is of type UTF8String. The Subscription-Id-Type AVP
// defines which type of identifier is used.
subscriptionId.addAvp(Avp.SUBSCRIPTION_ID_DATA, "sip:alexandre@mobicents.org", false);
// [ Service-Identifier ]
// [ Termination-Cause ]
// [ Requested-Service-Unit ]
// 8.18. Requested-Service-Unit AVP
//
// The Requested-Service-Unit AVP (AVP Code 437) is of type Grouped and
// contains the amount of requested units specified by the Diameter
// credit-control client. A server is not required to implement all the
// unit types, and it must treat unknown or unsupported unit types as
// invalid AVPs.
//
// The Requested-Service-Unit AVP is defined as follows (per the
// grouped-avp-def of RFC 3588 [DIAMBASE]):
//
// Requested-Service-Unit ::= < AVP Header: 437 >
// [ CC-Time ]
// [ CC-Money ]
// [ CC-Total-Octets ]
// [ CC-Input-Octets ]
// [ CC-Output-Octets ]
// [ CC-Service-Specific-Units ]
// *[ AVP ]
AvpSet rsuAvp = ccrAvps.addGroupedAvp(Avp.REQUESTED_SERVICE_UNIT);
// 8.21. CC-Time AVP
//
// The CC-Time AVP (AVP Code 420) is of type Unsigned32 and indicates
// the length of the requested, granted, or used time in seconds.
rsuAvp.addAvp(Avp.CC_TIME, getChargingUnitsTime());
// [ Requested-Action ]
// *[ Used-Service-Unit ]
// 8.19. Used-Service-Unit AVP
//
// The Used-Service-Unit AVP is of type Grouped (AVP Code 446) and
// contains the amount of used units measured from the point when the
// service became active or, if interim interrogations are used during
// the session, from the point when the previous measurement ended.
//
// The Used-Service-Unit AVP is defined as follows (per the grouped-
// avp-def of RFC 3588 [DIAMBASE]):
//
// Used-Service-Unit ::= < AVP Header: 446 >
// [ Tariff-Change-Usage ]
// [ CC-Time ]
// [ CC-Money ]
// [ CC-Total-Octets ]
// [ CC-Input-Octets ]
// [ CC-Output-Octets ]
// [ CC-Service-Specific-Units ]
// *[ AVP ]
// FIXME: alex :) ?
// if(ccRequestNumber >= 1) {
// AvpSet usedServiceUnit = ccrAvps.addGroupedAvp(Avp.USED_SERVICE_UNIT);
// usedServiceUnit.addAvp(Avp.CC_TIME, this.partialCallDurationCounter);
// System.out.println("USED SERVICE UNITS ==============================>"
// + partialCallDurationCounter);
// }
// [ AoC-Request-Type ]
// [ Multiple-Services-Indicator ]
// *[ Multiple-Services-Credit-Control ]
// *[ Service-Parameter-Info ]
// [ CC-Correlation-Id ]
// [ User-Equipment-Info ]
// *[ Proxy-Info ]
// *[ Gxute-Record ]
// [ Service-Information ]
// *[ AVP ]
return ccr;
}
public String getSessionId() {
return this.clientGxSession.getSessionId();
}
public void fetchSession(String sessionId) throws InternalException {
this.clientGxSession = stack.getSession(sessionId, ClientGxSession.class);
}
public ClientGxSession getSession() {
return this.clientGxSession;
}
public List<StateChange<ClientGxSessionState>> getStateChanges() {
return stateChanges;
}
protected abstract int getChargingUnitsTime();
protected abstract String getServiceContextId();
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.gx;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Mode;
import org.jdiameter.api.auth.events.ReAuthRequest;
import org.jdiameter.api.gx.ClientGxSession;
import org.jdiameter.api.gx.ServerGxSession;
import org.jdiameter.api.gx.ServerGxSessionListener;
import org.jdiameter.api.gx.events.GxReAuthRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.api.app.gx.IServerGxSessionContext;
import org.jdiameter.common.api.app.gx.ServerGxSessionState;
import org.jdiameter.common.impl.app.gx.GxReAuthRequestImpl;
import org.jdiameter.common.impl.app.gx.GxSessionFactoryImpl;
import org.mobicents.diameter.stack.functional.StateChange;
import org.mobicents.diameter.stack.functional.TBase;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public abstract class AbstractServer extends TBase implements ServerGxSessionListener, IServerGxSessionContext {
// NOTE: implementing NetworkReqListener since its required for stack to
// know we support it... ech.
protected static final int CC_REQUEST_TYPE_INITIAL = 1;
protected static final int CC_REQUEST_TYPE_INTERIM = 2;
protected static final int CC_REQUEST_TYPE_TERMINATE = 3;
protected static final int CC_REQUEST_TYPE_EVENT = 4;
protected ServerGxSession serverGxSession;
protected int ccRequestNumber = 0;
protected List<StateChange<ServerGxSessionState>> stateChanges = new ArrayList<StateChange<ServerGxSessionState>>(); // state changes
public void init(InputStream configStream, String clientID) throws Exception {
try {
super.init(configStream, clientID, ApplicationId.createByAuthAppId(10415, 16777224));
GxSessionFactoryImpl creditControlSessionFactory = new GxSessionFactoryImpl(this.sessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ServerGxSession.class, creditControlSessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ClientGxSession.class, creditControlSessionFactory);
creditControlSessionFactory.setStateListener(this);
creditControlSessionFactory.setServerSessionListener(this);
creditControlSessionFactory.setServerContextListener(this);
}
finally {
try {
configStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
// ----------- delegate methods so
public void start() throws IllegalDiameterStateException, InternalException {
stack.start();
}
public void start(Mode mode, long timeOut, TimeUnit timeUnit) throws IllegalDiameterStateException, InternalException {
stack.start(mode, timeOut, timeUnit);
}
public void stop(long timeOut, TimeUnit timeUnit, int disconnectCause) throws IllegalDiameterStateException, InternalException {
stack.stop(timeOut, timeUnit, disconnectCause);
}
public void stop(int disconnectCause) {
stack.stop(disconnectCause);
}
// ----------- conf parts
public void sessionSupervisionTimerExpired(ServerGxSession session) {
// NOP
}
public void sessionSupervisionTimerStarted(ServerGxSession session, ScheduledFuture future) {
// NOP
}
public void sessionSupervisionTimerReStarted(ServerGxSession session, ScheduledFuture future) {
// NOP
}
public void sessionSupervisionTimerStopped(ServerGxSession session, ScheduledFuture future) {
// NOP
}
public long getDefaultValidityTime() {
return 120;
}
protected GxReAuthRequest createRAR(int reAuthRequestType, ServerGxSession gxSession) throws Exception {
// <RA-Request> ::= < Diameter Header: 258, REQ, PXY >
GxReAuthRequest rar = new GxReAuthRequestImpl(gxSession.getSessions().get(0)
.createRequest(ReAuthRequest.code, getApplicationId(), getClientRealmName()));
// AVPs present by default: Origin-Host, Origin-Realm, Session-Id,
// Vendor-Specific-Application-Id, Destination-Realm
AvpSet rarAvps = rar.getMessage().getAvps();
// < Session-Id >
// { Auth-Application-Id }
// { Origin-Host }
rarAvps.removeAvp(Avp.ORIGIN_HOST);
rarAvps.addAvp(Avp.ORIGIN_HOST, getServerURI(), true);
// { Origin-Realm }
// { Destination-Realm }
// { Destination-Host }
// { Re-Auth-Request-Type }
rarAvps.addAvp(Avp.RE_AUTH_REQUEST_TYPE, reAuthRequestType);
// [ Session-Release-Cause ]
// [ Origin-State-Id ]
// *[ Event-Trigger ]
// [ Event-Report-Indication ]
// *[ Charging-Rule-Remove ]
// *[ Charging-Rule-Install ]
// [ Default-EPS-Bearer-QoS ]
// *[ QoS-Information ]
// [ Revalidation-Time ]
// *[ Usage-Monitoring-Information ]
// *[ Proxy-Info ]
// *[ Route-Record ]
// *[ AVP]
return rar;
}
public String getSessionId() {
return this.serverGxSession.getSessionId();
}
public void fetchSession(String sessionId) throws InternalException {
this.serverGxSession = stack.getSession(sessionId, ServerGxSession.class);
}
public ServerGxSession getSession() {
return this.serverGxSession;
}
public List<StateChange<ServerGxSessionState>> getStateChanges() {
return stateChanges;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional;
import org.apache.log4j.Logger;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.Message;
import org.jdiameter.api.validation.AvpRepresentation;
import org.jdiameter.api.validation.Dictionary;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class Utils {
public static void printMessage(Logger log, Dictionary avpDictionary, Message message, boolean sending) {
log.info((sending ? "Sending " : "Received ") + (message.isRequest() ? "Request: " : "Answer: ") + message.getCommandCode() + " [E2E:" + message.getEndToEndIdentifier()
+ " -- HBH:" + message.getHopByHopIdentifier() + " -- AppID:" + message.getApplicationId() + "]");
log.info("Request AVPs:");
try {
printAvps(log, avpDictionary, message.getAvps());
}
catch (AvpDataException e) {
e.printStackTrace();
}
log.info("\n");
}
public static void printAvps(Logger log, Dictionary avpDictionary, AvpSet avpSet) throws AvpDataException {
printAvpsAux(log, avpDictionary, avpSet, 0);
}
/**
* Prints the AVPs present in an AvpSet with a specified 'tab' level
*
* @param avpSet
* the AvpSet containing the AVPs to be printed
* @param level
* an int representing the number of 'tabs' to make a pretty print
* @throws AvpDataException
*/
private static void printAvpsAux(Logger log, Dictionary avpDictionary, AvpSet avpSet, int level) throws AvpDataException {
String prefix = " ".substring(0, level * 2);
for (Avp avp : avpSet) {
AvpRepresentation avpRep = avpDictionary.getAvp(avp.getCode(), avp.getVendorId());
if (avpRep != null && avpRep.getType().equals("Grouped")) {
log.info(prefix + "<avp name=\"" + avpRep.getName() + "\" code=\"" + avp.getCode() + "\" vendor=\"" + avp.getVendorId() + "\">");
printAvpsAux(log, avpDictionary, avp.getGrouped(), level + 1);
log.info(prefix + "</avp>");
}
else if (avpRep != null) {
String value = "";
if (avpRep.getType().equals("Integer32"))
value = String.valueOf(avp.getInteger32());
else if (avpRep.getType().equals("Integer64") || avpRep.getType().equals("Unsigned64"))
value = String.valueOf(avp.getInteger64());
else if (avpRep.getType().equals("Unsigned32"))
value = String.valueOf(avp.getUnsigned32());
else if (avpRep.getType().equals("Float32"))
value = String.valueOf(avp.getFloat32());
else
value = avp.getUTF8String();
log.info(prefix + "<avp name=\"" + avpRep.getName() + "\" code=\"" + avp.getCode() + "\" vendor=\"" + avp.getVendorId() + "\" value=\"" + value + "\" />");
}
}
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class ErrorHolder {
private String errorMessage;
private Throwable error;
/**
* @param error
*/
public ErrorHolder(Throwable error) {
super();
this.error = error;
}
/**
* @param errorMessage
*/
public ErrorHolder(String errorMessage) {
super();
this.errorMessage = errorMessage;
}
/**
* @param errorMessage
* @param error
*/
public ErrorHolder(String errorMessage, Throwable error) {
super();
this.errorMessage = errorMessage;
this.error = error;
}
public String getErrorMessage() {
return errorMessage;
}
public Throwable getError() {
return error;
}
@Override
public String toString() {
// for now. add StackTrace gen
StringBuilder sb = new StringBuilder(" Msg: ");
if (errorMessage != null) {
sb.append(errorMessage).append(", stack trace: \n");
}
else {
sb.append("EMPTY, stack trace: \n");
}
if (error != null) {
error.fillInStackTrace();
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
error.printStackTrace(pw);
sb.append(sw.getBuffer().toString());
}
return sb.toString();
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional;
import static org.jdiameter.client.impl.helpers.Parameters.AcctApplId;
import static org.jdiameter.client.impl.helpers.Parameters.ApplicationId;
import static org.jdiameter.client.impl.helpers.Parameters.Assembler;
import static org.jdiameter.client.impl.helpers.Parameters.AuthApplId;
import static org.jdiameter.client.impl.helpers.Parameters.OwnDiameterURI;
import static org.jdiameter.client.impl.helpers.Parameters.OwnIPAddress;
import static org.jdiameter.client.impl.helpers.Parameters.OwnRealm;
import static org.jdiameter.client.impl.helpers.Parameters.OwnVendorID;
import static org.jdiameter.client.impl.helpers.Parameters.PeerName;
import static org.jdiameter.client.impl.helpers.Parameters.PeerRating;
import static org.jdiameter.client.impl.helpers.Parameters.PeerTable;
import static org.jdiameter.client.impl.helpers.Parameters.RealmEntry;
import static org.jdiameter.client.impl.helpers.Parameters.RealmTable;
import static org.jdiameter.client.impl.helpers.Parameters.VendorId;
import org.jdiameter.client.impl.helpers.EmptyConfiguration;
/**
* Class representing the Diameter Test Framework Configuration
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class StackConfig extends EmptyConfiguration {
private static String clientHost = "127.0.0.1";
private static String clientPort = "13868";
private static String clientURI = "aaa://" + clientHost + ":" + clientPort;
private static String serverHost = "127.0.0.1";
private static String serverPort = "3868";
private static String serverURI = "aaa://" + serverHost + ":" + serverPort;
private static String realmName = "mobicents.org";
public StackConfig() {
super();
add(Assembler, Assembler.defValue());
add(OwnDiameterURI, clientURI);
add(OwnIPAddress, "127.0.0.1");
add(OwnRealm, realmName);
add(OwnVendorID, 193L);
// Set Ericsson SDK feature
//add(UseUriAsFqdn, true);
// Set Common Applications
add(ApplicationId,
// AppId 1
getInstance().
add(VendorId, 193L).
add(AuthApplId, 0L).
add(AcctApplId, 19302L)
);
// Set peer table
add(PeerTable,
// Peer 1
getInstance().
add(PeerRating, 1).
add(PeerName, serverURI));
// Set realm table
// add(RealmTable,
// // Realm 1
// getInstance().
// add(RealmEntry, realmName + ":" + clientHost + "," + serverHost)
// );
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.acc.base;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.acc.ClientAccSession;
import org.jdiameter.api.acc.events.AccountAnswer;
import org.jdiameter.api.acc.events.AccountRequest;
import org.jdiameter.api.app.AppAnswerEvent;
import org.jdiameter.api.app.AppRequestEvent;
import org.jdiameter.api.app.AppSession;
import org.mobicents.diameter.stack.functional.Utils;
import org.mobicents.diameter.stack.functional.acc.AbstractClient;
/**
* Base implementation of Client
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class Client extends AbstractClient {
protected boolean sentINITIAL;
protected boolean sentINTERIM;
protected boolean sentTERMINATE;
protected boolean sentEVENT;
protected boolean receiveINITIAL;
protected boolean receiveINTERIM;
protected boolean receiveTERMINATE;
protected boolean receiveEVENT;
/**
*
*/
public Client() {
// TODO Auto-generated constructor stub
}
public void sendInitial() throws Exception {
AccountRequest initialRequest = super.createAcc(ACC_REQUEST_TYPE_INITIAL, this.ccRequestNumber, super.clientAccSession);
this.ccRequestNumber++;
super.clientAccSession.sendAccountRequest(initialRequest);
Utils.printMessage(log, super.stack.getDictionary(), initialRequest.getMessage(), true);
this.sentINITIAL = true;
}
public void sendInterim() throws Exception {
if (!receiveINITIAL) {
throw new Exception();
}
AccountRequest interimRequest = super.createAcc(ACC_REQUEST_TYPE_INTERIM, this.ccRequestNumber, super.clientAccSession);
this.ccRequestNumber++;
super.clientAccSession.sendAccountRequest(interimRequest);
Utils.printMessage(log, super.stack.getDictionary(), interimRequest.getMessage(), true);
this.sentINTERIM = true;
}
public void sendTermination() throws Exception {
if (!receiveINTERIM) {
throw new Exception();
}
AccountRequest terminateRequest = super.createAcc(ACC_REQUEST_TYPE_TERMINATE, this.ccRequestNumber, super.clientAccSession);
this.ccRequestNumber++;
super.clientAccSession.sendAccountRequest(terminateRequest);
Utils.printMessage(log, super.stack.getDictionary(), terminateRequest.getMessage(), true);
this.sentTERMINATE = true;
}
public void sendEvent() throws Exception {
AccountRequest eventRequest = super.createAcc(ACC_REQUEST_TYPE_TERMINATE, this.ccRequestNumber, super.clientAccSession);
this.ccRequestNumber++;
super.clientAccSession.sendAccountRequest(eventRequest);
Utils.printMessage(log, super.stack.getDictionary(), eventRequest.getMessage(), true);
this.sentEVENT = true;
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.acc.ClientAccSessionListener#doCreditControlAnswer( org.jdiameter.api.acc.ClientAccSession,
* org.jdiameter.api.acc.events.JCreditControlRequest, org.jdiameter.api.acc.events.JCreditControlAnswer)
*/
public void doAccAnswerEvent(ClientAccSession session, AccountRequest request, AccountAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
try {
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), false);
switch (answer.getAccountingRecordType()) {
case ACC_REQUEST_TYPE_INITIAL:
if (receiveINITIAL) {
fail("Received INITIAL more than once!", null);
}
receiveINITIAL = true;
break;
case ACC_REQUEST_TYPE_INTERIM:
if (receiveINTERIM) {
fail("Received INTERIM more than once!", null);
}
receiveINTERIM = true;
break;
case ACC_REQUEST_TYPE_TERMINATE:
if (receiveTERMINATE) {
fail("Received TERMINATE more than once!", null);
}
receiveTERMINATE = true;
break;
case ACC_REQUEST_TYPE_EVENT:
if (receiveEVENT) {
fail("Received EVENT more than once!", null);
}
receiveEVENT = true;
break;
default:
}
}
catch (Exception e) {
e.printStackTrace();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.acc.ClientAccSessionListener#doOtherEvent(org.jdiameter .api.app.AppSession,
* org.jdiameter.api.app.AppRequestEvent, org.jdiameter.api.app.AppAnswerEvent)
*/
public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
fail("Received \"Other\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null);
}
// ------------ getters for some vars;
public boolean isSentINITIAL() {
return sentINITIAL;
}
public boolean isSentEVENT() {
return sentEVENT;
}
public boolean isReceiveEVENT() {
return receiveEVENT;
}
public boolean isSentINTERIM() {
return sentINTERIM;
}
public boolean isSentTERMINATE() {
return sentTERMINATE;
}
public boolean isReceiveINITIAL() {
return receiveINITIAL;
}
public boolean isReceiveINTERIM() {
return receiveINTERIM;
}
public boolean isReceiveTERMINATE() {
return receiveTERMINATE;
}
// ------------ getters for some vars;
@Override
protected int getChargingUnitsTime() {
return 10;
}
@Override
protected String getServiceContextId() {
return "tralalalal ID";
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.acc.base;
import org.jdiameter.api.Answer;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.acc.ServerAccSession;
import org.jdiameter.api.acc.events.AccountAnswer;
import org.jdiameter.api.acc.events.AccountRequest;
import org.jdiameter.api.app.AppAnswerEvent;
import org.jdiameter.api.app.AppRequestEvent;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.impl.app.acc.AccountAnswerImpl;
import org.mobicents.diameter.stack.functional.Utils;
import org.mobicents.diameter.stack.functional.acc.AbstractServer;
/**
* Base implementation of Server
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class Server extends AbstractServer {
protected boolean sentINITIAL;
protected boolean sentINTERIM;
protected boolean sentTERMINATE;
protected boolean sentEVENT;
protected boolean receiveINITIAL;
protected boolean receiveINTERIM;
protected boolean receiveTERMINATE;
protected boolean receiveEVENT;
protected AccountRequest request;
protected boolean stateless = true;
public void sendInitial() throws Exception {
if (!this.receiveINITIAL || this.request == null) {
fail("Did not receive INITIAL or answer already sent.", null);
throw new Exception("Request: " + this.request);
}
AccountAnswer answer = new AccountAnswerImpl((Request) request.getMessage(), request.getAccountingRecordType(), (int) request.getAccountingRecordNumber(), 2001);
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
super.serverAccSession.sendAccountAnswer(answer);
sentINITIAL = true;
request = null;
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
}
public void sendInterim() throws Exception {
if (!this.receiveINTERIM || this.request == null) {
fail("Did not receive INTERIM or answer already sent.", null);
throw new Exception("Request: " + this.request);
}
AccountAnswer answer = new AccountAnswerImpl((Request) request.getMessage(), request.getAccountingRecordType(), (int) request.getAccountingRecordNumber(), 2001);
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
super.serverAccSession.sendAccountAnswer(answer);
sentINTERIM = true;
request = null;
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
}
public void sendTermination() throws Exception {
if (!this.receiveTERMINATE || this.request == null) {
fail("Did not receive TERMINATE or answer already sent.", null);
throw new Exception("Request: " + this.request);
}
AccountAnswer answer = new AccountAnswerImpl((Request) request.getMessage(), request.getAccountingRecordType(), (int) request.getAccountingRecordNumber(), 2001);
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
super.serverAccSession.sendAccountAnswer(answer);
sentTERMINATE = true;
request = null;
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
}
public void sendEvent() throws Exception {
if (!this.receiveEVENT || this.request == null) {
fail("Did not receive EVENT or answer already sent.", null);
throw new Exception("Request: " + this.request);
}
AccountAnswer answer = new AccountAnswerImpl((Request) request.getMessage(), request.getAccountingRecordType(), (int) request.getAccountingRecordNumber(), 2001);
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
super.serverAccSession.sendAccountAnswer(answer);
sentEVENT = true;
request = null;
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.NetworkReqListener#processRequest(org.jdiameter.api.Request)
*/
@Override
public Answer processRequest(Request request) {
if (request.getCommandCode() != AccountRequest.code) {
fail("Received Request with code not equal " + AccountRequest.code + "!. Code[" + request.getCommandCode() + "]", null);
return null;
}
if (super.serverAccSession == null) {
try {
super.serverAccSession = ((ISessionFactory) this.sessionFactory).getNewAppSession(request.getSessionId(), getApplicationId(), ServerAccSession.class,
new Object[] { new Boolean(stateless) }); // pass false to be stateful
((NetworkReqListener) this.serverAccSession).processRequest(request);
}
catch (Exception e) {
fail(null, e);
}
}
else {
// do fail?
fail("Received Request in base listener, not in app specific!", null);
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.acc.ServerAccSessionListener#doAccRequestEvent(org.jdiameter.api.acc.ServerAccSession,
* org.jdiameter.api.acc.events.AccountRequest)
*/
public void doAccRequestEvent(ServerAccSession appSession, AccountRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
try {
Utils.printMessage(log, super.stack.getDictionary(), request.getMessage(), false);
// INITIAL_REQUEST 1,
// UPDATE_REQUEST 2,
// TERMINATION_REQUEST 3,
// EVENT_REQUEST 4
switch (request.getAccountingRecordType()) {
case ACC_REQUEST_TYPE_INITIAL:
if (receiveINITIAL) {
fail("Received INITIAL more than once!", null);
}
receiveINITIAL = true;
this.request = request;
break;
case ACC_REQUEST_TYPE_INTERIM:
if (receiveINTERIM) {
fail("Received INTERIM more than once!", null);
}
receiveINTERIM = true;
this.request = request;
break;
case ACC_REQUEST_TYPE_TERMINATE:
if (receiveTERMINATE) {
fail("Received TERMINATE more than once!", null);
}
receiveTERMINATE = true;
this.request = request;
break;
case ACC_REQUEST_TYPE_EVENT:
if (receiveEVENT) {
fail("Received EVENT more than once!", null);
}
receiveEVENT = true;
this.request = request;
break;
default:
fail("No REQ type present?: " + request.getAccountingRecordType(), null);
}
}
catch (Exception e) {
fail(null, e);
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.acc.ServerAccSessionListener#doOtherEvent(org.jdiameter.api.app.AppSession,
* org.jdiameter.api.app.AppRequestEvent, org.jdiameter.api.app.AppAnswerEvent)
*/
public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
fail("Received \"Other\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null);
}
public boolean isSentINITIAL() {
return sentINITIAL;
}
public boolean isSentINTERIM() {
return sentINTERIM;
}
public boolean isSentTERMINATE() {
return sentTERMINATE;
}
public boolean isReceiveINITIAL() {
return receiveINITIAL;
}
public boolean isReceiveINTERIM() {
return receiveINTERIM;
}
public boolean isReceiveTERMINATE() {
return receiveTERMINATE;
}
public boolean isSentEVENT() {
return sentEVENT;
}
public boolean isReceiveEVENT() {
return receiveEVENT;
}
public boolean isStateless() {
return stateless;
}
public void setStateless(boolean stateless) {
this.stateless = stateless;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.acc;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.jdiameter.api.Answer;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Mode;
import org.jdiameter.api.Request;
import org.jdiameter.api.acc.ClientAccSession;
import org.jdiameter.api.acc.ClientAccSessionListener;
import org.jdiameter.api.acc.ServerAccSession;
import org.jdiameter.api.acc.events.AccountRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.api.app.acc.ClientAccSessionState;
import org.jdiameter.common.api.app.acc.IClientAccActionContext;
import org.jdiameter.common.impl.app.acc.AccSessionFactoryImpl;
import org.jdiameter.common.impl.app.acc.AccountRequestImpl;
import org.mobicents.diameter.stack.functional.StateChange;
import org.mobicents.diameter.stack.functional.TBase;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public abstract class AbstractClient extends TBase implements ClientAccSessionListener, IClientAccActionContext {
// NOTE: implementing NetworkReqListener since its required for stack to
// know we support it... ech.
protected static final int ACC_REQUEST_TYPE_INITIAL = 2;
protected static final int ACC_REQUEST_TYPE_INTERIM = 3;
protected static final int ACC_REQUEST_TYPE_TERMINATE = 4;
protected static final int ACC_REQUEST_TYPE_EVENT = 1;
// this is custom id.
protected ClientAccSession clientAccSession;
protected int ccRequestNumber = 0;
protected List<StateChange<ClientAccSessionState>> stateChanges = new ArrayList<StateChange<ClientAccSessionState>>(); // state changes
public void init(InputStream configStream, String clientID) throws Exception {
try {
super.init(configStream, clientID, ApplicationId.createByAccAppId(0, 300));
AccSessionFactoryImpl creditControlSessionFactory = new AccSessionFactoryImpl(this.sessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ServerAccSession.class, creditControlSessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ClientAccSession.class, creditControlSessionFactory);
creditControlSessionFactory.setStateListener(this);
creditControlSessionFactory.setClientSessionListener(this);
creditControlSessionFactory.setClientContextListener(this);
this.clientAccSession = ((ISessionFactory) this.sessionFactory).getNewAppSession(
this.sessionFactory.getSessionId("xxTESTxx"), getApplicationId(), ClientAccSession.class, (Object)null);
}
finally {
try {
configStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
// ----------- delegate methods so
public void start() throws IllegalDiameterStateException, InternalException {
stack.start();
}
public void start(Mode mode, long timeOut, TimeUnit timeUnit) throws IllegalDiameterStateException, InternalException {
stack.start(mode, timeOut, timeUnit);
}
public void stop(long timeOut, TimeUnit timeUnit, int disconnectCause) throws IllegalDiameterStateException, InternalException {
stack.stop(timeOut, timeUnit, disconnectCause);
}
public void stop(int disconnectCause) {
stack.stop(disconnectCause);
}
// ----------- conf parts
// ----------- should not be called..
@Override
public void receivedSuccessMessage(Request request, Answer answer) {
fail("Received \"SuccessMessage\" event, request[" + request + "], answer[" + answer + "]", null);
}
@Override
public void timeoutExpired(Request request) {
fail("Received \"Timoeout\" event, request[" + request + "]", null);
}
@Override
public Answer processRequest(Request request) {
fail("Received \"Request\" event, request[" + request + "]", null);
return null;
}
// ------------ leave those
public void interimIntervalElapses(ClientAccSession appSession, Request interimRequest) throws InternalException {
// NOP
}
public boolean failedSendRecord(ClientAccSession appSession, Request accRequest) throws InternalException {
// NOP
return false;
}
public void disconnectUserOrDev(ClientAccSession appSession, Request sessionTermRequest) throws InternalException {
// NOP
}
// ---------- some helper methods.
protected AccountRequest createAcc(int ccRequestType, int requestNumber, ClientAccSession ccaSession) throws Exception {
// Create Credit-Control-Request
AccountRequest ccr = new AccountRequestImpl(ccaSession.getSessions().get(0).createRequest(AccountRequest.code, getApplicationId(), getServerRealmName()));
// AVPs present by default: Origin-Host, Origin-Realm, Session-Id,
// Vendor-Specific-Application-Id, Destination-Realm
AvpSet ccrAvps = ccr.getMessage().getAvps();
// <ACR> ::= < Diameter Header: 271, REQ, PXY >
// < Session-Id >
// { Origin-Host }
ccrAvps.removeAvp(Avp.ORIGIN_HOST);
ccrAvps.addAvp(Avp.ORIGIN_HOST, getClientURI(), true);
// { Origin-Realm }
// { Destination-Realm } - set in constructor.
// { Accounting-Record-Type }
ccr.setAccountingRecordType(ccRequestType);
// EVENT_RECORD 1
// An Accounting Event Record is used to indicate that a one-time
// event has occurred (meaning that the start and end of the event
// are simultaneous). This record contains all information relevant
// to the service, and is the only record of the service.
//
// START_RECORD 2
// An Accounting Start, Interim, and Stop Records are used to
// indicate that a service of a measurable length has been given. An
// Accounting Start Record is used to initiate an accounting session,
// and contains accounting information that is relevant to the
// initiation of the session.
//
// INTERIM_RECORD 3
// An Interim Accounting Record contains cumulative accounting
// information for an existing accounting session. Interim
// Accounting Records SHOULD be sent every time a re-authentication
// or re-authorization occurs. Further, additional interim record
// triggers MAY be defined by application-specific Diameter
// applications. The selection of whether to use INTERIM_RECORD
// records is done by the Acct-Interim-Interval AVP.
//
// STOP_RECORD 4
// An Accounting Stop Record is sent to terminate an accounting
// session and contains cumulative accounting information relevant to
// the existing session.
// { Accounting-Record-Number }
ccr.setAccountingRecordNumber(requestNumber);
// [ Acct-Application-Id ]
if (ccrAvps.getAvp(Avp.ACCT_APPLICATION_ID) == null) {
ccrAvps.addAvp(Avp.ACCT_APPLICATION_ID, getApplicationId().getAcctAppId());
}
// [ Vendor-Specific-Application-Id ]
// [ User-Name ] - just to have it, its almost always mandatory
ccrAvps.addAvp(Avp.USER_NAME, "ala@kota.ma.bez.siersci", false);
// [ Accounting-Sub-Session-Id ]
// [ Acct-Session-Id ]
// [ Acct-Multi-Session-Id ]
// [ Acct-Interim-Interval ]
// [ Accounting-Realtime-Required ]
// [ Origin-State-Id ]
// [ Event-Timestamp ]
// * [ Proxy-Info ]
// * [ Route-Record ]
// * [ AVP ]
return ccr;
}
public String getSessionId() {
return this.clientAccSession.getSessionId();
}
public void fetchSession(String sessionId) throws InternalException {
this.clientAccSession = stack.getSession(sessionId, ClientAccSession.class);
}
public ClientAccSession getSession() {
return this.clientAccSession;
}
public List<StateChange<ClientAccSessionState>> getStateChanges() {
return stateChanges;
}
protected abstract int getChargingUnitsTime();
protected abstract String getServiceContextId();
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.acc;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Mode;
import org.jdiameter.api.acc.ClientAccSession;
import org.jdiameter.api.acc.ServerAccSession;
import org.jdiameter.api.acc.ServerAccSessionListener;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.api.app.acc.IServerAccActionContext;
import org.jdiameter.common.api.app.acc.ServerAccSessionState;
import org.jdiameter.common.impl.app.acc.AccSessionFactoryImpl;
import org.mobicents.diameter.stack.functional.StateChange;
import org.mobicents.diameter.stack.functional.TBase;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public abstract class AbstractServer extends TBase implements ServerAccSessionListener, IServerAccActionContext {
// NOTE: implementing NetworkReqListener since its required for stack to
// know we support it... ech.
protected static final int ACC_REQUEST_TYPE_INITIAL = 2;
protected static final int ACC_REQUEST_TYPE_INTERIM = 3;
protected static final int ACC_REQUEST_TYPE_TERMINATE = 4;
protected static final int ACC_REQUEST_TYPE_EVENT = 1;
protected ServerAccSession serverAccSession;
protected int ccRequestNumber = 0;
protected List<StateChange<ServerAccSessionState>> stateChanges = new ArrayList<StateChange<ServerAccSessionState>>(); // state changes
public void init(InputStream configStream, String clientID) throws Exception {
try {
super.init(configStream, clientID, ApplicationId.createByAccAppId(0, 300));
AccSessionFactoryImpl creditControlSessionFactory = new AccSessionFactoryImpl(this.sessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ServerAccSession.class, creditControlSessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ClientAccSession.class, creditControlSessionFactory);
creditControlSessionFactory.setStateListener(this);
creditControlSessionFactory.setServerSessionListener(this);
creditControlSessionFactory.setServerContextListener(this);
}
finally {
try {
configStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
// ----------- delegate methods so
public void start() throws IllegalDiameterStateException, InternalException {
stack.start();
}
public void start(Mode mode, long timeOut, TimeUnit timeUnit) throws IllegalDiameterStateException, InternalException {
stack.start(mode, timeOut, timeUnit);
}
public void stop(long timeOut, TimeUnit timeUnit, int disconnectCause) throws IllegalDiameterStateException, InternalException {
stack.stop(timeOut, timeUnit, disconnectCause);
}
public void stop(int disconnectCause) {
stack.stop(disconnectCause);
}
// ----------- ctx
public void sessionTimerStarted(ServerAccSession appSession, ScheduledFuture timer) throws InternalException {
// NOP
}
public void sessionTimeoutElapses(ServerAccSession appSession) throws InternalException {
// NOP
}
public void sessionTimerCanceled(ServerAccSession appSession, ScheduledFuture timer) throws InternalException {
// NOP
}
public String getSessionId() {
return this.serverAccSession.getSessionId();
}
public void fetchSession(String sessionId) throws InternalException {
this.serverAccSession = stack.getSession(sessionId, ServerAccSession.class);
}
public ServerAccSession getSession() {
return this.serverAccSession;
}
public List<StateChange<ServerAccSessionState>> getStateChanges() {
return stateChanges;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class StateChange<T> {
private T oldState;
private T newState;
/**
* @param oldState
* @param newState
*/
public StateChange(T oldState, T newState) {
super();
this.oldState = oldState;
this.newState = newState;
}
public T getOldState() {
return oldState;
}
public T getNewState() {
return newState;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((newState == null) ? 0 : newState.hashCode());
result = prime * result + ((oldState == null) ? 0 : oldState.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;
StateChange other = (StateChange) obj;
if (newState == null) {
if (other.newState != null)
return false;
}
else if (!newState.equals(other.newState))
return false;
if (oldState == null) {
if (other.oldState != null)
return false;
}
else if (!oldState.equals(other.oldState))
return false;
return true;
}
@Override
public String toString() {
return "StateChange [oldState=" + oldState + ", newState=" + newState + "]";
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.jdiameter.api.Answer;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.EventListener;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.Request;
import org.jdiameter.api.Stack;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.app.StateChangeListener;
import org.jdiameter.client.api.ISessionFactory;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public abstract class TBase implements EventListener<Request, Answer>, NetworkReqListener, StateChangeListener<AppSession> {
protected final Logger log = Logger.getLogger(getClass());
protected boolean passed = true;
protected List<ErrorHolder> errors = new ArrayList<ErrorHolder>();
// ------- those actually should come from conf... but..
protected static final String clientHost = "127.0.0.1";
protected static final String clientPort = "13868";
protected static final String clientURI = "aaa://" + clientHost + ":" + clientPort;
protected static final String serverHost = "127.0.0.1";
protected static final String serverHost2 = "127.0.0.2";
protected static final String serverPortNode1 = "4868";
protected static final String serverPortNode2 = "4968";
protected static final String serverURINode1 = "aaa://" + serverHost + ":" + serverPortNode1;
protected static final String serverURINode2 = "aaa://" + serverHost2 + ":" + serverPortNode2;
protected static final String serverRealm = "server.mobicents.org";
protected static final String clientRealm = "client.mobicents.org";
protected StackCreator stack;
protected ISessionFactory sessionFactory;
protected ApplicationId applicationId;
public void init(InputStream configStream, String clientID, ApplicationId appId) throws Exception {
try {
this.applicationId = appId;
stack = new StackCreator();
stack.init(configStream, this, this, clientID, true, appId); // lets always pass
this.sessionFactory = (ISessionFactory) this.stack.getSessionFactory();
}
finally {
}
}
protected void fail(String msg, Throwable e) {
this.passed = false;
ErrorHolder eh = new ErrorHolder(msg, e);
this.errors.add(eh);
}
public boolean isPassed() {
return passed;
}
public List<ErrorHolder> getErrors() {
return errors;
}
public String createErrorReport(List<ErrorHolder> errors) {
if (errors.size() > 0) {
StringBuilder sb = new StringBuilder();
for (int index = 0; index < errors.size(); index++) {
sb.append(errors.get(index));
if (index + 1 < errors.size()) {
sb.append("\n");
}
}
return sb.toString();
}
else {
return "";
}
}
public ApplicationId getApplicationId() {
return applicationId;
}
protected String getClientURI() {
return clientURI;
}
protected String getServerRealmName() {
return serverRealm;
}
protected String getClientRealmName() {
return clientRealm;
}
public Stack getStack() {
return this.stack;
}
/**
* @return
*/
protected String getServerURI() {
return serverURINode1;
}
// --------- Default Implementation
// --------- Depending on class it is overridden or by default makes test fail.
public void receivedSuccessMessage(Request request, Answer answer) {
fail("Received \"SuccessMessage\" event, request[" + request + "], answer[" + answer + "]", null);
}
public void timeoutExpired(Request request) {
fail("Received \"Timoeout\" event, request[" + request + "]", null);
}
public Answer processRequest(Request request) {
fail("Received \"Request\" event, request[" + request + "]", null);
return null;
}
// --- State Changes --------------------------------------------------------
public void stateChanged(Enum oldState, Enum newState) {
// NOP
}
public void stateChanged(AppSession source, Enum oldState, Enum newState) {
// NOP
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.ro.base;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.app.AppAnswerEvent;
import org.jdiameter.api.app.AppRequestEvent;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.auth.events.ReAuthRequest;
import org.jdiameter.api.ro.ClientRoSession;
import org.jdiameter.api.ro.events.RoCreditControlAnswer;
import org.jdiameter.api.ro.events.RoCreditControlRequest;
import org.mobicents.diameter.stack.functional.Utils;
import org.mobicents.diameter.stack.functional.ro.AbstractClient;
/**
* Base implementation of Client
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class Client extends AbstractClient {
protected boolean sentINITIAL;
protected boolean sentINTERIM;
protected boolean sentTERMINATE;
protected boolean sentEVENT;
protected boolean receiveINITIAL;
protected boolean receiveINTERIM;
protected boolean receiveTERMINATE;
protected boolean receiveEVENT;
/**
*
*/
public Client() {
}
public void sendInitial() throws Exception {
RoCreditControlRequest initialRequest = super.createCCR(CC_REQUEST_TYPE_INITIAL, this.ccRequestNumber, super.clientRoSession);
this.ccRequestNumber++;
super.clientRoSession.sendCreditControlRequest(initialRequest);
Utils.printMessage(log, super.stack.getDictionary(), initialRequest.getMessage(), true);
this.sentINITIAL = true;
}
public void sendInterim() throws Exception {
if (!receiveINITIAL) {
throw new Exception();
}
RoCreditControlRequest interimRequest = super.createCCR(CC_REQUEST_TYPE_INTERIM, this.ccRequestNumber, super.clientRoSession);
this.ccRequestNumber++;
super.clientRoSession.sendCreditControlRequest(interimRequest);
Utils.printMessage(log, super.stack.getDictionary(), interimRequest.getMessage(), true);
this.sentINTERIM = true;
}
public void sendTermination() throws Exception {
if (!receiveINTERIM) {
throw new Exception();
}
RoCreditControlRequest terminateRequest = super.createCCR(CC_REQUEST_TYPE_TERMINATE, this.ccRequestNumber, super.clientRoSession);
this.ccRequestNumber++;
super.clientRoSession.sendCreditControlRequest(terminateRequest);
Utils.printMessage(log, super.stack.getDictionary(), terminateRequest.getMessage(), true);
this.sentTERMINATE = true;
}
public void sendEvent() throws Exception {
RoCreditControlRequest eventRequest = super.createCCR(CC_REQUEST_TYPE_TERMINATE, this.ccRequestNumber, super.clientRoSession);
this.ccRequestNumber++;
super.clientRoSession.sendCreditControlRequest(eventRequest);
Utils.printMessage(log, super.stack.getDictionary(), eventRequest.getMessage(), true);
this.sentEVENT = true;
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ClientCCASessionListener#doCreditControlAnswer( org.jdiameter.api.cca.ClientCCASession,
* org.jdiameter.api.cca.events.RoCreditControlRequest, org.jdiameter.api.cca.events.JCreditControlAnswer)
*/
public void doCreditControlAnswer(ClientRoSession session, RoCreditControlRequest request, RoCreditControlAnswer answer) throws InternalException, IllegalDiameterStateException,
RouteException, OverloadException {
try {
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), false);
switch (answer.getRequestTypeAVPValue()) {
case CC_REQUEST_TYPE_INITIAL:
if (receiveINITIAL) {
fail("Received INITIAL more than once!", null);
}
receiveINITIAL = true;
break;
case CC_REQUEST_TYPE_INTERIM:
if (receiveINTERIM) {
fail("Received INTERIM more than once!", null);
}
receiveINTERIM = true;
break;
case CC_REQUEST_TYPE_TERMINATE:
if (receiveTERMINATE) {
fail("Received TERMINATE more than once!", null);
}
receiveTERMINATE = true;
break;
case CC_REQUEST_TYPE_EVENT:
if (receiveEVENT) {
fail("Received EVENT more than once!", null);
}
receiveEVENT = true;
break;
default:
}
}
catch (Exception e) {
e.printStackTrace();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ClientCCASessionListener#doReAuthRequest(org.jdiameter .api.cca.ClientCCASession,
* org.jdiameter.api.auth.events.ReAuthRequest)
*/
public void doReAuthRequest(ClientRoSession session, ReAuthRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
fail("Received \"ReAuthRequest\" event, request[" + request + "], on session[" + session + "]", null);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ClientCCASessionListener#doOtherEvent(org.jdiameter .api.app.AppSession,
* org.jdiameter.api.app.AppRequestEvent, org.jdiameter.api.app.AppAnswerEvent)
*/
public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
fail("Received \"Other\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null);
}
// ------------ getters for some vars;
public boolean isSentINITIAL() {
return sentINITIAL;
}
public boolean isSentEVENT() {
return sentEVENT;
}
public boolean isReceiveEVENT() {
return receiveEVENT;
}
public boolean isSentINTERIM() {
return sentINTERIM;
}
public boolean isSentTERMINATE() {
return sentTERMINATE;
}
public boolean isReceiveINITIAL() {
return receiveINITIAL;
}
public boolean isReceiveINTERIM() {
return receiveINTERIM;
}
public boolean isReceiveTERMINATE() {
return receiveTERMINATE;
}
// ------------ getters for some vars;
@Override
protected int getChargingUnitsTime() {
return 10;
}
@Override
protected String getServiceContextId() {
return "tralalalal ID";
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.ro.base;
import org.jdiameter.api.Answer;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.app.AppAnswerEvent;
import org.jdiameter.api.app.AppRequestEvent;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.auth.events.ReAuthAnswer;
import org.jdiameter.api.auth.events.ReAuthRequest;
import org.jdiameter.api.ro.ServerRoSession;
import org.jdiameter.api.ro.events.RoCreditControlAnswer;
import org.jdiameter.api.ro.events.RoCreditControlRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.impl.app.ro.RoCreditControlAnswerImpl;
import org.mobicents.diameter.stack.functional.Utils;
import org.mobicents.diameter.stack.functional.ro.AbstractServer;
/**
* Base implementation of Server
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class Server extends AbstractServer {
protected boolean sentINITIAL;
protected boolean sentINTERIM;
protected boolean sentTERMINATE;
protected boolean sentEVENT;
protected boolean receiveINITIAL;
protected boolean receiveINTERIM;
protected boolean receiveTERMINATE;
protected boolean receiveEVENT;
protected RoCreditControlRequest request;
// ------- send methods to trigger answer
public void sendInitial() throws Exception {
if (!this.receiveINITIAL || this.request == null) {
fail("Did not receive INITIAL or answer already sent.", null);
throw new Exception("Request: " + this.request);
}
RoCreditControlAnswer answer = new RoCreditControlAnswerImpl((Request) request.getMessage(), 2001);
AvpSet reqSet = request.getMessage().getAvps();
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID));
super.serverRoSession.sendCreditControlAnswer(answer);
sentINITIAL = true;
request = null;
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
}
public void sendInterim() throws Exception {
if (!this.receiveINTERIM || this.request == null) {
fail("Did not receive INTERIM or answer already sent.", null);
throw new Exception("Request: " + this.request);
}
RoCreditControlAnswerImpl answer = new RoCreditControlAnswerImpl((Request) request.getMessage(), 2001);
AvpSet reqSet = request.getMessage().getAvps();
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID));
super.serverRoSession.sendCreditControlAnswer(answer);
sentINTERIM = true;
request = null;
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
}
public void sendTermination() throws Exception {
if (!this.receiveTERMINATE || this.request == null) {
fail("Did not receive TERMINATE or answer already sent.", null);
throw new Exception("Request: " + this.request);
}
RoCreditControlAnswerImpl answer = new RoCreditControlAnswerImpl((Request) request.getMessage(), 2001);
AvpSet reqSet = request.getMessage().getAvps();
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID));
super.serverRoSession.sendCreditControlAnswer(answer);
sentTERMINATE = true;
request = null;
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
}
public void sendEvent() throws Exception {
if (!this.receiveEVENT || this.request == null) {
fail("Did not receive EVENT or answer already sent.", null);
throw new Exception("Request: " + this.request);
}
RoCreditControlAnswerImpl answer = new RoCreditControlAnswerImpl((Request) request.getMessage(), 2001);
AvpSet reqSet = request.getMessage().getAvps();
AvpSet set = answer.getMessage().getAvps();
set.removeAvp(Avp.DESTINATION_HOST);
set.removeAvp(Avp.DESTINATION_REALM);
set.addAvp(reqSet.getAvp(Avp.CC_REQUEST_TYPE), reqSet.getAvp(Avp.CC_REQUEST_NUMBER), reqSet.getAvp(Avp.AUTH_APPLICATION_ID));
super.serverRoSession.sendCreditControlAnswer(answer);
sentEVENT = true;
request = null;
Utils.printMessage(log, super.stack.getDictionary(), answer.getMessage(), true);
}
// ------- initial, this will be triggered for first msg.
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.NetworkReqListener#processRequest(org.jdiameter.api.Request)
*/
@Override
public Answer processRequest(Request request) {
if (request.getCommandCode() != 272) {
fail("Received Request with code not equal 272!. Code[" + request.getCommandCode() + "]", null);
return null;
}
if (super.serverRoSession == null) {
try {
super.serverRoSession = ((ISessionFactory) this.sessionFactory).getNewAppSession(request.getSessionId(), getApplicationId(), ServerRoSession.class, (Object) null);
((NetworkReqListener) this.serverRoSession).processRequest(request);
}
catch (Exception e) {
fail(null, e);
}
}
else {
// do fail?
fail("Received Request in base listener, not in app specific!", null);
}
return null;
}
// ------------- specific, app session listener.
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ServerRoSessionListener#doCreditControlRequest(org.jdiameter.api.cca.ServerRoSession,
* org.jdiameter.api.cca.events.RoCreditControlRequest)
*/
public void doCreditControlRequest(ServerRoSession session, RoCreditControlRequest request) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
try {
Utils.printMessage(log, super.stack.getDictionary(), request.getMessage(), false);
// INITIAL_REQUEST 1,
// UPDATE_REQUEST 2,
// TERMINATION_REQUEST 3,
// EVENT_REQUEST 4
switch (request.getRequestTypeAVPValue()) {
case CC_REQUEST_TYPE_INITIAL:
if (receiveINITIAL) {
fail("Received INITIAL more than once!", null);
}
receiveINITIAL = true;
this.request = request;
break;
case CC_REQUEST_TYPE_INTERIM:
if (receiveINTERIM) {
fail("Received INTERIM more than once!", null);
}
receiveINTERIM = true;
this.request = request;
break;
case CC_REQUEST_TYPE_TERMINATE:
if (receiveTERMINATE) {
fail("Received TERMINATE more than once!", null);
}
receiveTERMINATE = true;
this.request = request;
break;
case CC_REQUEST_TYPE_EVENT:
if (receiveEVENT) {
fail("Received EVENT more than once!", null);
}
receiveEVENT = true;
this.request = request;
break;
default:
fail("No REQ type present?: " + request.getRequestTypeAVPValue(), null);
}
}
catch (Exception e) {
fail(null, e);
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ServerRoSessionListener#doReAuthAnswer(org.jdiameter.api.cca.ServerRoSession,
* org.jdiameter.api.auth.events.ReAuthRequest, org.jdiameter.api.auth.events.ReAuthAnswer)
*/
public void doReAuthAnswer(ServerRoSession session, ReAuthRequest request, ReAuthAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
fail("Received \"ReAuthAnswer\" event, request[" + request + "], on session[" + session + "]", null);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ServerRoSessionListener#doOtherEvent(org.jdiameter.api.app.AppSession,
* org.jdiameter.api.app.AppRequestEvent, org.jdiameter.api.app.AppAnswerEvent)
*/
public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException,
OverloadException {
fail("Received \"Other\" event, request[" + request + "], answer[" + answer + "], on session[" + session + "]", null);
}
public boolean isSentINITIAL() {
return sentINITIAL;
}
public boolean isSentINTERIM() {
return sentINTERIM;
}
public boolean isSentTERMINATE() {
return sentTERMINATE;
}
public boolean isReceiveINITIAL() {
return receiveINITIAL;
}
public boolean isReceiveINTERIM() {
return receiveINTERIM;
}
public boolean isReceiveTERMINATE() {
return receiveTERMINATE;
}
public boolean isSentEVENT() {
return sentEVENT;
}
public boolean isReceiveEVENT() {
return receiveEVENT;
}
public RoCreditControlRequest getRequest() {
return request;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.ro;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Message;
import org.jdiameter.api.Mode;
import org.jdiameter.api.ro.ClientRoSession;
import org.jdiameter.api.ro.ClientRoSessionListener;
import org.jdiameter.api.ro.ServerRoSession;
import org.jdiameter.api.ro.events.RoCreditControlRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.api.app.ro.ClientRoSessionState;
import org.jdiameter.common.api.app.ro.IClientRoSessionContext;
import org.jdiameter.common.impl.app.ro.RoCreditControlRequestImpl;
import org.jdiameter.common.impl.app.ro.RoSessionFactoryImpl;
import org.mobicents.diameter.stack.functional.StateChange;
import org.mobicents.diameter.stack.functional.TBase;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public abstract class AbstractClient extends TBase implements ClientRoSessionListener, IClientRoSessionContext {
// NOTE: implementing NetworkReqListener since its required for stack to
// know we support it... ech.
protected static final int CC_REQUEST_TYPE_INITIAL = 1;
protected static final int CC_REQUEST_TYPE_INTERIM = 2;
protected static final int CC_REQUEST_TYPE_TERMINATE = 3;
protected static final int CC_REQUEST_TYPE_EVENT = 4;
protected ClientRoSession clientRoSession;
protected int ccRequestNumber = 0;
protected List<StateChange<ClientRoSessionState>> stateChanges = new ArrayList<StateChange<ClientRoSessionState>>(); // state changes
public void init(InputStream configStream, String clientID) throws Exception {
try {
super.init(configStream, clientID, ApplicationId.createByAuthAppId(0, 4));
RoSessionFactoryImpl creditControlSessionFactory = new RoSessionFactoryImpl(this.sessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ServerRoSession.class, creditControlSessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ClientRoSession.class, creditControlSessionFactory);
creditControlSessionFactory.setStateListener(this);
creditControlSessionFactory.setClientSessionListener(this);
creditControlSessionFactory.setClientContextListener(this);
this.clientRoSession = ((ISessionFactory) this.sessionFactory)
.getNewAppSession(this.sessionFactory.getSessionId("xxTESTxx"), getApplicationId(), ClientRoSession.class, (Object) null);
}
finally {
try {
configStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
// ----------- delegate methods so
public void start() throws IllegalDiameterStateException, InternalException {
stack.start();
}
public void start(Mode mode, long timeOut, TimeUnit timeUnit) throws IllegalDiameterStateException, InternalException {
stack.start(mode, timeOut, timeUnit);
}
public void stop(long timeOut, TimeUnit timeUnit, int disconnectCause) throws IllegalDiameterStateException, InternalException {
stack.stop(timeOut, timeUnit, disconnectCause);
}
public void stop(int disconnectCause) {
stack.stop(disconnectCause);
}
// ----------- conf parts
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.cca.IClientCCASessionContext# getDefaultTxTimerValue()
*/
public long getDefaultTxTimerValue() {
return 10;
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ClientCCASessionListener#getDefaultDDFHValue()
*/
public int getDefaultDDFHValue() {
// DDFH_CONTINUE: 1
return 1;
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.cca.ClientCCASessionListener#getDefaultCCFHValue()
*/
public int getDefaultCCFHValue() {
// CCFH_CONTINUE: 1
return 1;
}
// ------------ leave those
public void txTimerExpired(ClientRoSession session) {
// NOP
}
public void grantAccessOnDeliverFailure(ClientRoSession clientCCASessionImpl, Message request) {
// NOP
}
public void denyAccessOnDeliverFailure(ClientRoSession clientCCASessionImpl, Message request) {
// NOP
}
public void grantAccessOnTxExpire(ClientRoSession clientCCASessionImpl) {
// NOP
}
public void denyAccessOnTxExpire(ClientRoSession clientCCASessionImpl) {
// NOP
}
public void grantAccessOnFailureMessage(ClientRoSession clientCCASessionImpl) {
// NOP
}
public void denyAccessOnFailureMessage(ClientRoSession clientCCASessionImpl) {
// NOP
}
public void indicateServiceError(ClientRoSession clientCCASessionImpl) {
// NOP
}
// ---------- some helper methods.
protected RoCreditControlRequest createCCR(int ccRequestType, int requestNumber, ClientRoSession ccaSession) throws Exception {
// Create Credit-Control-Request
RoCreditControlRequest ccr = new RoCreditControlRequestImpl(ccaSession.getSessions().get(0)
.createRequest(RoCreditControlRequest.code, getApplicationId(), getServerRealmName()));
// AVPs present by default: Origin-Host, Origin-Realm, Session-Id,
// Vendor-Specific-Application-Id, Destination-Realm
AvpSet ccrAvps = ccr.getMessage().getAvps();
// Add remaining AVPs ... from RFC 4006:
// <CCR> ::= < Diameter Header: 272, REQ, PXY >
// < Session-Id >
// ccrAvps.addAvp(Avp.SESSION_ID, s.getSessionId());
// { Origin-Host }
ccrAvps.removeAvp(Avp.ORIGIN_HOST);
ccrAvps.addAvp(Avp.ORIGIN_HOST, getClientURI(), true);
// { Origin-Realm }
// ccrAvps.addAvp(Avp.ORIGIN_REALM, realmName, true);
// { Destination-Realm }
// ccrAvps.addAvp(Avp.DESTINATION_REALM, realmName, true);
// { Auth-Application-Id }
ccrAvps.addAvp(Avp.AUTH_APPLICATION_ID, 4);
// { Service-Context-Id }
// 8.42. Service-Context-Id AVP
//
// The Service-Context-Id AVP is of type UTF8String (AVP Code 461) and
// contains a unique identifier of the Diameter credit-control service
// specific document that applies to the request (as defined in section
// 4.1.2). This is an identifier allocated by the service provider, by
// the service element manufacturer, or by a standardization body, and
// MUST uniquely identify a given Diameter credit-control service
// specific document. The format of the Service-Context-Id is:
//
// "service-context" "@" "domain"
//
// service-context = Token
//
// The Token is an arbitrary string of characters and digits.
//
// 'domain' represents the entity that allocated the Service-Context-Id.
// It can be ietf.org, 3gpp.org, etc., if the identifier is allocated by
// a standardization body, or it can be the FQDN of the service provider
// (e.g., provider.example.com) or of the vendor (e.g.,
// vendor.example.com) if the identifier is allocated by a private
// entity.
//
// This AVP SHOULD be placed as close to the Diameter header as
// possible.
//
// Service-specific documents that are for private use only (i.e., to
// one provider's own use, where no interoperability is deemed useful)
// may define private identifiers without need of coordination.
// However, when interoperability is wanted, coordination of the
// identifiers via, for example, publication of an informational RFC is
// RECOMMENDED in order to make Service-Context-Id globally available.
String serviceContextId = getServiceContextId();
if (serviceContextId == null) {
serviceContextId = UUID.randomUUID().toString().replaceAll("-", "") + "@mss.mobicents.org";
}
ccrAvps.addAvp(Avp.SERVICE_CONTEXT_ID, serviceContextId, false);
// { CC-Request-Type }
// 8.3. CC-Request-Type AVP
//
// The CC-Request-Type AVP (AVP Code 416) is of type Enumerated and
// contains the reason for sending the credit-control request message.
// It MUST be present in all Credit-Control-Request messages. The
// following values are defined for the CC-Request-Type AVP:
//
// INITIAL_REQUEST 1
// An Initial request is used to initiate a credit-control session,
// and contains credit control information that is relevant to the
// initiation.
//
// UPDATE_REQUEST 2
// An Update request contains credit-control information for an
// existing credit-control session. Update credit-control requests
// SHOULD be sent every time a credit-control re-authorization is
// needed at the expiry of the allocated quota or validity time.
// Further, additional service-specific events MAY trigger a
// spontaneous Update request.
//
// TERMINATION_REQUEST 3
// A Termination request is sent to terminate a credit-control
// session and contains credit-control information relevant to the
// existing session.
//
// EVENT_REQUEST 4
// An Event request is used when there is no need to maintain any
// credit-control session state in the credit-control server. This
// request contains all information relevant to the service, and is
// the only request of the service. The reason for the Event request
// is further detailed in the Requested-Action AVP. The Requested-
// Action AVP MUST be included in the Credit-Control-Request message
// when CC-Request-Type is set to EVENT_REQUEST.
ccrAvps.addAvp(Avp.CC_REQUEST_TYPE, ccRequestType);
// { CC-Request-Number }
// 8.2. CC-Request-Number AVP
//
// The CC-Request-Number AVP (AVP Code 415) is of type Unsigned32 and
// identifies this request within one session. As Session-Id AVPs are
// globally unique, the combination of Session-Id and CC-Request-Number
// AVPs is also globally unique and can be used in matching credit-
// control messages with confirmations. An easy way to produce unique
// numbers is to set the value to 0 for a credit-control request of type
// INITIAL_REQUEST and EVENT_REQUEST and to set the value to 1 for the
// first UPDATE_REQUEST, to 2 for the second, and so on until the value
// for TERMINATION_REQUEST is one more than for the last UPDATE_REQUEST.
ccrAvps.addAvp(Avp.CC_REQUEST_NUMBER, requestNumber);
// [ Destination-Host ]
ccrAvps.removeAvp(Avp.DESTINATION_HOST);
// ccrAvps.addAvp(Avp.DESTINATION_HOST, ccRequestType == 2 ?
// serverURINode1 : serverURINode1, false);
// [ User-Name ]
// [ CC-Sub-Session-Id ]
// [ Acct-Multi-Session-Id ]
// [ Origin-State-Id ]
// [ Event-Timestamp ]
// *[ Subscription-Id ]
// 8.46. Subscription-Id AVP
//
// The Subscription-Id AVP (AVP Code 443) is used to identify the end
// user's subscription and is of type Grouped. The Subscription-Id AVP
// includes a Subscription-Id-Data AVP that holds the identifier and a
// Subscription-Id-Type AVP that defines the identifier type.
//
// It is defined as follows (per the grouped-avp-def of RFC 3588
// [DIAMBASE]):
//
// Subscription-Id ::= < AVP Header: 443 >
// { Subscription-Id-Type }
// { Subscription-Id-Data }
AvpSet subscriptionId = ccrAvps.addGroupedAvp(Avp.SUBSCRIPTION_ID);
// 8.47. Subscription-Id-Type AVP
//
// The Subscription-Id-Type AVP (AVP Code 450) is of type Enumerated,
// and it is used to determine which type of identifier is carried by
// the Subscription-Id AVP.
//
// This specification defines the following subscription identifiers.
// However, new Subscription-Id-Type values can be assigned by an IANA
// designated expert, as defined in section 12. A server MUST implement
// all the Subscription-Id-Types required to perform credit
// authorization for the services it supports, including possible future
// values. Unknown or unsupported Subscription-Id-Types MUST be treated
// according to the 'M' flag rule, as defined in [DIAMBASE].
//
// END_USER_E164 0
// The identifier is in international E.164 format (e.g., MSISDN),
// according to the ITU-T E.164 numbering plan defined in [E164] and
// [CE164].
//
// END_USER_IMSI 1
// The identifier is in international IMSI format, according to the
// ITU-T E.212 numbering plan as defined in [E212] and [CE212].
//
// END_USER_SIP_URI 2
// The identifier is in the form of a SIP URI, as defined in [SIP].
//
// END_USER_NAI 3
// The identifier is in the form of a Network Access Identifier, as
// defined in [NAI].
//
// END_USER_PRIVATE 4
// The Identifier is a credit-control server private identifier.
subscriptionId.addAvp(Avp.SUBSCRIPTION_ID_TYPE, 2);
// 8.48. Subscription-Id-Data AVP
//
// The Subscription-Id-Data AVP (AVP Code 444) is used to identify the
// end user and is of type UTF8String. The Subscription-Id-Type AVP
// defines which type of identifier is used.
subscriptionId.addAvp(Avp.SUBSCRIPTION_ID_DATA, "sip:alexandre@mobicents.org", false);
// [ Service-Identifier ]
// [ Termination-Cause ]
// [ Requested-Service-Unit ]
// 8.18. Requested-Service-Unit AVP
//
// The Requested-Service-Unit AVP (AVP Code 437) is of type Grouped and
// contains the amount of requested units specified by the Diameter
// credit-control client. A server is not required to implement all the
// unit types, and it must treat unknown or unsupported unit types as
// invalid AVPs.
//
// The Requested-Service-Unit AVP is defined as follows (per the
// grouped-avp-def of RFC 3588 [DIAMBASE]):
//
// Requested-Service-Unit ::= < AVP Header: 437 >
// [ CC-Time ]
// [ CC-Money ]
// [ CC-Total-Octets ]
// [ CC-Input-Octets ]
// [ CC-Output-Octets ]
// [ CC-Service-Specific-Units ]
// *[ AVP ]
AvpSet rsuAvp = ccrAvps.addGroupedAvp(Avp.REQUESTED_SERVICE_UNIT);
// 8.21. CC-Time AVP
//
// The CC-Time AVP (AVP Code 420) is of type Unsigned32 and indicates
// the length of the requested, granted, or used time in seconds.
rsuAvp.addAvp(Avp.CC_TIME, getChargingUnitsTime());
// [ Requested-Action ]
// *[ Used-Service-Unit ]
// 8.19. Used-Service-Unit AVP
//
// The Used-Service-Unit AVP is of type Grouped (AVP Code 446) and
// contains the amount of used units measured from the point when the
// service became active or, if interim interrogations are used during
// the session, from the point when the previous measurement ended.
//
// The Used-Service-Unit AVP is defined as follows (per the grouped-
// avp-def of RFC 3588 [DIAMBASE]):
//
// Used-Service-Unit ::= < AVP Header: 446 >
// [ Tariff-Change-Usage ]
// [ CC-Time ]
// [ CC-Money ]
// [ CC-Total-Octets ]
// [ CC-Input-Octets ]
// [ CC-Output-Octets ]
// [ CC-Service-Specific-Units ]
// *[ AVP ]
// FIXME: alex :) ?
// if(ccRequestNumber >= 1) {
// AvpSet usedServiceUnit = ccrAvps.addGroupedAvp(Avp.USED_SERVICE_UNIT);
// usedServiceUnit.addAvp(Avp.CC_TIME, this.partialCallDurationCounter);
// System.out.println("USED SERVICE UNITS ==============================>"
// + partialCallDurationCounter);
// }
// [ AoC-Request-Type ]
// [ Multiple-Services-Indicator ]
// *[ Multiple-Services-Credit-Control ]
// *[ Service-Parameter-Info ]
// [ CC-Correlation-Id ]
// [ User-Equipment-Info ]
// *[ Proxy-Info ]
// *[ Route-Record ]
// [ Service-Information ]
// *[ AVP ]
return ccr;
}
public String getSessionId() {
return this.clientRoSession.getSessionId();
}
public void fetchSession(String sessionId) throws InternalException {
this.clientRoSession = stack.getSession(sessionId, ClientRoSession.class);
}
public ClientRoSession getSession() {
return this.clientRoSession;
}
public List<StateChange<ClientRoSessionState>> getStateChanges() {
return stateChanges;
}
protected abstract int getChargingUnitsTime();
protected abstract String getServiceContextId();
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional.ro;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Mode;
import org.jdiameter.api.ro.ClientRoSession;
import org.jdiameter.api.ro.ServerRoSession;
import org.jdiameter.api.ro.ServerRoSessionListener;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.api.app.ro.IServerRoSessionContext;
import org.jdiameter.common.api.app.ro.ServerRoSessionState;
import org.jdiameter.common.impl.app.ro.RoSessionFactoryImpl;
import org.mobicents.diameter.stack.functional.StateChange;
import org.mobicents.diameter.stack.functional.TBase;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public abstract class AbstractServer extends TBase implements ServerRoSessionListener, IServerRoSessionContext {
// NOTE: implementing NetworkReqListener since its required for stack to
// know we support it... ech.
protected static final int CC_REQUEST_TYPE_INITIAL = 1;
protected static final int CC_REQUEST_TYPE_INTERIM = 2;
protected static final int CC_REQUEST_TYPE_TERMINATE = 3;
protected static final int CC_REQUEST_TYPE_EVENT = 4;
protected ServerRoSession serverRoSession;
protected int ccRequestNumber = 0;
protected List<StateChange<ServerRoSessionState>> stateChanges = new ArrayList<StateChange<ServerRoSessionState>>(); // state changes
public void init(InputStream configStream, String clientID) throws Exception {
try {
super.init(configStream, clientID, ApplicationId.createByAuthAppId(0, 4));
RoSessionFactoryImpl creditControlSessionFactory = new RoSessionFactoryImpl(this.sessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ServerRoSession.class, creditControlSessionFactory);
((ISessionFactory) sessionFactory).registerAppFacory(ClientRoSession.class, creditControlSessionFactory);
creditControlSessionFactory.setStateListener(this);
creditControlSessionFactory.setServerSessionListener(this);
creditControlSessionFactory.setServerContextListener(this);
}
finally {
try {
configStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
// ----------- delegate methods so
public void start() throws IllegalDiameterStateException, InternalException {
stack.start();
}
public void start(Mode mode, long timeOut, TimeUnit timeUnit) throws IllegalDiameterStateException, InternalException {
stack.start(mode, timeOut, timeUnit);
}
public void stop(long timeOut, TimeUnit timeUnit, int disconnectCause) throws IllegalDiameterStateException, InternalException {
stack.stop(timeOut, timeUnit, disconnectCause);
}
public void stop(int disconnectCause) {
stack.stop(disconnectCause);
}
// ----------- conf parts
public void sessionSupervisionTimerExpired(ServerRoSession session) {
// NOP
}
public void sessionSupervisionTimerStarted(ServerRoSession session, ScheduledFuture future) {
// NOP
}
public void sessionSupervisionTimerReStarted(ServerRoSession session, ScheduledFuture future) {
// NOP
}
public void sessionSupervisionTimerStopped(ServerRoSession session, ScheduledFuture future) {
// NOP
}
public long getDefaultValidityTime() {
return 120;
}
public String getSessionId() {
return this.serverRoSession.getSessionId();
}
public void fetchSession(String sessionId) throws InternalException {
this.serverRoSession = stack.getSession(sessionId, ServerRoSession.class);
}
public ServerRoSession getSession() {
return this.serverRoSession;
}
public List<StateChange<ServerRoSessionState>> getStateChanges() {
return stateChanges;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.mobicents.diameter.stack.functional;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Set;
import org.apache.log4j.Logger;
import org.jdiameter.api.Answer;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Configuration;
import org.jdiameter.api.EventListener;
import org.jdiameter.api.Network;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.Request;
import org.jdiameter.server.impl.StackImpl;
import org.jdiameter.server.impl.helpers.XMLConfiguration;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class StackCreator extends StackImpl {
private static Logger logger = Logger.getLogger(StackCreator.class);
public StackCreator() {
super();
}
public StackCreator(InputStream streamConfig, NetworkReqListener networkReqListener, EventListener<Request, Answer> eventListener, String dooer, Boolean isServer,
ApplicationId... appIds) throws Exception {
init(isServer ? new XMLConfiguration(streamConfig) : new org.jdiameter.client.impl.helpers.XMLConfiguration(streamConfig), networkReqListener, eventListener, dooer, isServer,
appIds);
}
public StackCreator(String stringConfig, NetworkReqListener networkReqListener, EventListener<Request, Answer> eventListener, String dooer, Boolean isServer,
ApplicationId... appIds) throws Exception {
init(isServer ? new XMLConfiguration(new ByteArrayInputStream(stringConfig.getBytes())) : new org.jdiameter.client.impl.helpers.XMLConfiguration(new ByteArrayInputStream(
stringConfig.getBytes())), networkReqListener, eventListener, dooer, isServer, appIds);
}
public void init(String stringConfig, NetworkReqListener networkReqListener, EventListener<Request, Answer> eventListener, String dooer, Boolean isServer,
ApplicationId... appIds) throws Exception {
this.init(isServer ? new XMLConfiguration(new ByteArrayInputStream(stringConfig.getBytes())) : new org.jdiameter.client.impl.helpers.XMLConfiguration(new ByteArrayInputStream(
stringConfig.getBytes())), networkReqListener, eventListener, dooer, isServer, appIds);
}
public void init(InputStream streamConfig, NetworkReqListener networkReqListener, EventListener<Request, Answer> eventListener, String dooer, Boolean isServer,
ApplicationId... appIds) throws Exception {
this.init(isServer ? new XMLConfiguration(streamConfig) : new org.jdiameter.client.impl.helpers.XMLConfiguration(streamConfig), networkReqListener, eventListener, dooer,
isServer, appIds);
}
public void init(Configuration config, NetworkReqListener networkReqListener, EventListener<Request, Answer> eventListener, String identifier, Boolean isServer,
ApplicationId... appIds) throws Exception {
// local one
try {
this.init(config);
// Let it stabilize...
Thread.sleep(500);
Network network = unwrap(Network.class);
if (appIds != null) {
for (ApplicationId appId : appIds) {
if (logger.isInfoEnabled()) {
logger.info("Diameter " + identifier + " :: Adding Listener for [" + appId + "].");
}
network.addNetworkReqListener(networkReqListener, appId);
}
if (logger.isInfoEnabled()) {
logger.info("Diameter " + identifier + " :: Supporting " + appIds.length + " applications.");
}
}
else {
Set<ApplicationId> stackAppIds = getMetaData().getLocalPeer().getCommonApplications();
for (ApplicationId appId : stackAppIds) {
if (logger.isInfoEnabled()) {
logger.info("Diameter " + identifier + " :: Adding Listener for [" + appId + "].");
}
network.addNetworkReqListener(networkReqListener, appId);
}
if (logger.isInfoEnabled()) {
logger.info("Diameter " + identifier + " :: Supporting " + stackAppIds.size() + " applications.");
}
}
}
catch (Exception e) {
logger.error("Failure creating stack '" + identifier + "'", e);
}
}
}
| 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.diameter.impl.ha.client.sh;
import org.jboss.cache.Fqn;
import org.jdiameter.api.sh.ClientShSession;
import org.jdiameter.client.impl.app.sh.IShClientSessionData;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.common.AppSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ShClientSessionDataReplicatedImpl extends AppSessionDataReplicatedImpl implements IShClientSessionData {
/**
* @param nodeFqn
* @param mobicentsCluster
* @param iface
*/
public ShClientSessionDataReplicatedImpl(Fqn<?> nodeFqn, MobicentsCluster mobicentsCluster) {
super(nodeFqn, mobicentsCluster);
if (super.create()) {
setAppSessionIface(this, ClientShSession.class);
}
}
/**
* @param sessionId
* @param mobicentsCluster
* @param iface
*/
public ShClientSessionDataReplicatedImpl(String sessionId, MobicentsCluster mobicentsCluster) {
this(Fqn.fromRelativeElements(ReplicatedSessionDatasource.SESSIONS_FQN, sessionId), mobicentsCluster);
}
}
| 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.diameter.impl.ha.client.cca;
import java.io.Serializable;
import java.nio.ByteBuffer;
import org.jboss.cache.Fqn;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.Request;
import org.jdiameter.api.cca.ClientCCASession;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.parser.IMessageParser;
import org.jdiameter.client.api.parser.ParseException;
import org.jdiameter.client.impl.app.cca.IClientCCASessionData;
import org.jdiameter.common.api.app.cca.ClientCCASessionState;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.common.AppSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ClientCCASessionDataReplicatedImpl extends AppSessionDataReplicatedImpl implements IClientCCASessionData {
private static final Logger logger = LoggerFactory.getLogger(ClientCCASessionDataReplicatedImpl.class);
private static final String EVENT_BASED = "EVENT_BASED";
private static final String REQUEST_TYPE = "REQUEST_TYPE";
private static final String STATE = "STATE";
private static final String TXTIMER_ID = "TXTIMER_ID";
private static final String TXTIMER_REQUEST = "TXTIMER_REQUEST";
private static final String BUFFER = "BUFFER";
private static final String GRA = "GRA";
private static final String GDDFH = "GDDFH";
private static final String GCCFH = "GCCFH";
private IMessageParser messageParser;
/**
* @param nodeFqn
* @param mobicentsCluster
* @param iface
*/
public ClientCCASessionDataReplicatedImpl(Fqn<?> nodeFqn, MobicentsCluster mobicentsCluster, IContainer container) {
super(nodeFqn, mobicentsCluster);
if (super.create()) {
setAppSessionIface(this, ClientCCASession.class);
setClientCCASessionState(ClientCCASessionState.IDLE);
}
this.messageParser = container.getAssemblerFacility().getComponentInstance(IMessageParser.class);
}
/**
* @param sessionId
* @param mobicentsCluster
* @param iface
*/
public ClientCCASessionDataReplicatedImpl(String sessionId, MobicentsCluster mobicentsCluster, IContainer container) {
this(Fqn.fromRelativeElements(ReplicatedSessionDatasource.SESSIONS_FQN, sessionId), mobicentsCluster, container);
}
public boolean isEventBased() {
if (exists()) {
return toPrimitive((Boolean) getNode().get(EVENT_BASED), true);
}
else {
throw new IllegalStateException();
}
}
public void setEventBased(boolean isEventBased) {
if (exists()) {
getNode().put(EVENT_BASED, isEventBased);
}
else {
throw new IllegalStateException();
}
}
public boolean isRequestTypeSet() {
if (exists()) {
return toPrimitive((Boolean) getNode().get(REQUEST_TYPE), false);
}
else {
throw new IllegalStateException();
}
}
public void setRequestTypeSet(boolean requestTypeSet) {
if (exists()) {
getNode().put(REQUEST_TYPE, requestTypeSet);
}
else {
throw new IllegalStateException();
}
}
public ClientCCASessionState getClientCCASessionState() {
if (exists()) {
return (ClientCCASessionState) getNode().get(STATE);
}
else {
throw new IllegalStateException();
}
}
public void setClientCCASessionState(ClientCCASessionState state) {
if (exists()) {
getNode().put(STATE, state);
}
else {
throw new IllegalStateException();
}
}
public Serializable getTxTimerId() {
if (exists()) {
return (Serializable) getNode().get(TXTIMER_ID);
}
else {
throw new IllegalStateException();
}
}
public void setTxTimerId(Serializable txTimerId) {
if (exists()) {
getNode().put(TXTIMER_ID, txTimerId);
}
else {
throw new IllegalStateException();
}
}
public Request getTxTimerRequest() {
if (exists()) {
byte[] data = (byte[]) getNode().get(TXTIMER_REQUEST);
if (data != null) {
try {
return (Request) this.messageParser.createMessage(ByteBuffer.wrap(data));
}
catch (AvpDataException e) {
logger.error("Unable to recreate Tx Timer Request from buffer.");
return null;
}
}
else {
return null;
}
}
else {
throw new IllegalStateException();
}
}
public void setTxTimerRequest(Request txTimerRequest) {
if (exists()) {
if (txTimerRequest != null) {
try {
byte[] data = this.messageParser.encodeMessage((IMessage) txTimerRequest).array();
getNode().put(TXTIMER_REQUEST, data);
}
catch (ParseException e) {
logger.error("Unable to encode Tx Timer Request to buffer.");
}
}
else {
getNode().remove(TXTIMER_REQUEST);
}
}
else {
throw new IllegalStateException();
}
}
public Request getBuffer() {
byte[] data = (byte[]) getNode().get(BUFFER);
if (data != null) {
try {
return (Request) this.messageParser.createMessage(ByteBuffer.wrap(data));
}
catch (AvpDataException e) {
logger.error("Unable to recreate message from buffer.");
return null;
}
}
else {
return null;
}
}
public void setBuffer(Request buffer) {
if (buffer != null) {
try {
byte[] data = this.messageParser.encodeMessage((IMessage) buffer).array();
getNode().put(BUFFER, data);
}
catch (ParseException e) {
logger.error("Unable to encode message to buffer.");
}
}
else {
getNode().remove(BUFFER);
}
}
public int getGatheredRequestedAction() {
if (exists()) {
return toPrimitive((Integer) getNode().get(GRA));
}
else {
throw new IllegalStateException();
}
}
public void setGatheredRequestedAction(int gatheredRequestedAction) {
if (exists()) {
getNode().put(GRA, gatheredRequestedAction);
}
else {
throw new IllegalStateException();
}
}
public int getGatheredCCFH() {
if (exists()) {
return toPrimitive((Integer) getNode().get(GCCFH));
}
else {
throw new IllegalStateException();
}
}
public void setGatheredCCFH(int gatheredCCFH) {
if (exists()) {
getNode().put(GCCFH, gatheredCCFH);
}
else {
throw new IllegalStateException();
}
}
public int getGatheredDDFH() {
if (exists()) {
return toPrimitive((Integer) getNode().get(GDDFH));
}
else {
throw new IllegalStateException();
}
}
public void setGatheredDDFH(int gatheredDDFH) {
if (exists()) {
getNode().put(GDDFH, gatheredDDFH);
}
else {
throw new IllegalStateException();
}
}
}
| 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.diameter.impl.ha.client.cxdx;
import org.jboss.cache.Fqn;
import org.jdiameter.api.cxdx.ClientCxDxSession;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.client.impl.app.cxdx.IClientCxDxSessionData;
import org.jdiameter.common.api.app.cxdx.CxDxSessionState;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.common.cxdx.CxDxSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ClientCxDxSessionDataReplicatedImpl extends CxDxSessionDataReplicatedImpl implements IClientCxDxSessionData {
/**
* @param nodeFqn
* @param mobicentsCluster
* @param iface
*/
public ClientCxDxSessionDataReplicatedImpl(Fqn<?> nodeFqn, MobicentsCluster mobicentsCluster, IContainer container) {
super(nodeFqn, mobicentsCluster, container);
if (super.create()) {
setAppSessionIface(this, ClientCxDxSession.class);
setCxDxSessionState(CxDxSessionState.IDLE);
}
}
/**
* @param sessionId
* @param mobicentsCluster
* @param iface
*/
public ClientCxDxSessionDataReplicatedImpl(String sessionId, MobicentsCluster mobicentsCluster, IContainer container) {
this(Fqn.fromRelativeElements(ReplicatedSessionDatasource.SESSIONS_FQN, sessionId), mobicentsCluster, container);
}
}
| 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.diameter.impl.ha.client.gx;
import java.io.Serializable;
import java.nio.ByteBuffer;
import org.jboss.cache.Fqn;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.Request;
import org.jdiameter.api.gx.ClientGxSession;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.parser.IMessageParser;
import org.jdiameter.client.api.parser.ParseException;
import org.jdiameter.client.impl.app.gx.IClientGxSessionData;
import org.jdiameter.common.api.app.gx.ClientGxSessionState;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.common.AppSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ClientGxSessionDataReplicatedImpl extends AppSessionDataReplicatedImpl implements IClientGxSessionData {
private static final Logger logger = LoggerFactory.getLogger(ClientGxSessionDataReplicatedImpl.class);
private static final String EVENT_BASED = "EVENT_BASED";
private static final String REQUEST_TYPE = "REQUEST_TYPE";
private static final String STATE = "STATE";
private static final String TXTIMER_ID = "TXTIMER_ID";
private static final String TXTIMER_REQUEST = "TXTIMER_REQUEST";
private static final String BUFFER = "BUFFER";
private static final String GRA = "GRA";
private static final String GDDFH = "GDDFH";
private static final String GCCFH = "GCCFH";
private IMessageParser messageParser;
/**
* @param nodeFqn
* @param mobicentsCluster
* @param iface
*/
public ClientGxSessionDataReplicatedImpl(Fqn<?> nodeFqn, MobicentsCluster mobicentsCluster, IContainer container) {
super(nodeFqn, mobicentsCluster);
if (super.create()) {
setAppSessionIface(this, ClientGxSession.class);
setClientGxSessionState(ClientGxSessionState.IDLE);
}
this.messageParser = container.getAssemblerFacility().getComponentInstance(IMessageParser.class);
}
/**
* @param sessionId
* @param mobicentsCluster
* @param iface
*/
public ClientGxSessionDataReplicatedImpl(String sessionId, MobicentsCluster mobicentsCluster, IContainer container) {
this(Fqn.fromRelativeElements(ReplicatedSessionDatasource.SESSIONS_FQN, sessionId), mobicentsCluster, container);
}
public boolean isEventBased() {
if (exists()) {
return toPrimitive((Boolean) getNode().get(EVENT_BASED), true);
}
else {
throw new IllegalStateException();
}
}
public void setEventBased(boolean isEventBased) {
if (exists()) {
getNode().put(EVENT_BASED, isEventBased);
}
else {
throw new IllegalStateException();
}
}
public boolean isRequestTypeSet() {
if (exists()) {
return toPrimitive((Boolean) getNode().get(REQUEST_TYPE), false);
}
else {
throw new IllegalStateException();
}
}
public void setRequestTypeSet(boolean requestTypeSet) {
if (exists()) {
getNode().put(REQUEST_TYPE, requestTypeSet);
}
else {
throw new IllegalStateException();
}
}
public ClientGxSessionState getClientGxSessionState() {
if (exists()) {
return (ClientGxSessionState) getNode().get(STATE);
}
else {
throw new IllegalStateException();
}
}
public void setClientGxSessionState(ClientGxSessionState state) {
if (exists()) {
getNode().put(STATE, state);
}
else {
throw new IllegalStateException();
}
}
public Serializable getTxTimerId() {
if (exists()) {
return (Serializable) getNode().get(TXTIMER_ID);
}
else {
throw new IllegalStateException();
}
}
public void setTxTimerId(Serializable txTimerId) {
if (exists()) {
getNode().put(TXTIMER_ID, txTimerId);
}
else {
throw new IllegalStateException();
}
}
public Request getTxTimerRequest() {
if (exists()) {
byte[] data = (byte[]) getNode().get(TXTIMER_REQUEST);
if (data != null) {
try {
return (Request) this.messageParser.createMessage(ByteBuffer.wrap(data));
}
catch (AvpDataException e) {
logger.error("Unable to recreate Tx Timer Request from buffer.");
return null;
}
}
else {
return null;
}
}
else {
throw new IllegalStateException();
}
}
public void setTxTimerRequest(Request txTimerRequest) {
if (exists()) {
if (txTimerRequest != null) {
try {
byte[] data = this.messageParser.encodeMessage((IMessage) txTimerRequest).array();
getNode().put(TXTIMER_REQUEST, data);
}
catch (ParseException e) {
logger.error("Unable to encode Tx Timer Request to buffer.");
}
}
else {
getNode().remove(TXTIMER_REQUEST);
}
}
else {
throw new IllegalStateException();
}
}
public Request getBuffer() {
byte[] data = (byte[]) getNode().get(BUFFER);
if (data != null) {
try {
return (Request) this.messageParser.createMessage(ByteBuffer.wrap(data));
}
catch (AvpDataException e) {
logger.error("Unable to recreate message from buffer.");
return null;
}
}
else {
return null;
}
}
public void setBuffer(Request buffer) {
if (buffer != null) {
try {
byte[] data = this.messageParser.encodeMessage((IMessage) buffer).array();
getNode().put(BUFFER, data);
}
catch (ParseException e) {
logger.error("Unable to encode message to buffer.");
}
}
else {
getNode().remove(BUFFER);
}
}
public int getGatheredRequestedAction() {
if (exists()) {
return toPrimitive((Integer) getNode().get(GRA));
}
else {
throw new IllegalStateException();
}
}
public void setGatheredRequestedAction(int gatheredRequestedAction) {
if (exists()) {
getNode().put(GRA, gatheredRequestedAction);
}
else {
throw new IllegalStateException();
}
}
public int getGatheredCCFH() {
if (exists()) {
return toPrimitive((Integer) getNode().get(GCCFH));
}
else {
throw new IllegalStateException();
}
}
public void setGatheredCCFH(int gatheredCCFH) {
if (exists()) {
getNode().put(GCCFH, gatheredCCFH);
}
else {
throw new IllegalStateException();
}
}
public int getGatheredDDFH() {
if (exists()) {
return toPrimitive((Integer) getNode().get(GDDFH));
}
else {
throw new IllegalStateException();
}
}
public void setGatheredDDFH(int gatheredDDFH) {
if (exists()) {
getNode().put(GDDFH, gatheredDDFH);
}
else {
throw new IllegalStateException();
}
}
}
| 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.diameter.impl.ha.client.rx;
import org.jboss.cache.Fqn;
import org.jdiameter.api.rx.ClientRxSession;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.client.impl.app.rx.IClientRxSessionData;
import org.jdiameter.common.api.app.rx.ClientRxSessionState;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.common.AppSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ClientRxSessionDataReplicatedImpl extends AppSessionDataReplicatedImpl implements IClientRxSessionData {
private static final String EVENT_BASED = "EVENT_BASED";
private static final String REQUEST_TYPE = "REQUEST_TYPE";
private static final String STATE = "STATE";
/**
* @param nodeFqn
* @param mobicentsCluster
* @param iface
*/
public ClientRxSessionDataReplicatedImpl(Fqn<?> nodeFqn, MobicentsCluster mobicentsCluster, IContainer container) {
super(nodeFqn, mobicentsCluster);
if (super.create()) {
setAppSessionIface(this, ClientRxSession.class);
setClientRxSessionState(ClientRxSessionState.IDLE);
}
}
/**
* @param sessionId
* @param mobicentsCluster
* @param iface
*/
public ClientRxSessionDataReplicatedImpl(String sessionId, MobicentsCluster mobicentsCluster, IContainer container) {
this(Fqn.fromRelativeElements(ReplicatedSessionDatasource.SESSIONS_FQN, sessionId), mobicentsCluster, container);
}
@Override
public boolean isEventBased() {
if (exists()) {
return toPrimitive((Boolean) getNode().get(EVENT_BASED), true);
} else {
throw new IllegalStateException();
}
}
@Override
public void setEventBased(boolean isEventBased) {
if (exists()) {
getNode().put(EVENT_BASED, isEventBased);
} else {
throw new IllegalStateException();
}
}
@Override
public boolean isRequestTypeSet() {
if (exists()) {
return toPrimitive((Boolean) getNode().get(REQUEST_TYPE), false);
} else {
throw new IllegalStateException();
}
}
@Override
public void setRequestTypeSet(boolean requestTypeSet) {
if (exists()) {
getNode().put(REQUEST_TYPE, requestTypeSet);
} else {
throw new IllegalStateException();
}
}
@Override
public ClientRxSessionState getClientRxSessionState() {
if (exists()) {
return (ClientRxSessionState) getNode().get(STATE);
} else {
throw new IllegalStateException();
}
}
@Override
public void setClientRxSessionState(ClientRxSessionState state) {
if (exists()) {
getNode().put(STATE, state);
} else {
throw new IllegalStateException();
}
}
}
| 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.diameter.impl.ha.client.auth;
import java.io.Serializable;
import org.jboss.cache.Fqn;
import org.jdiameter.api.auth.ClientAuthSession;
import org.jdiameter.client.impl.app.auth.IClientAuthSessionData;
import org.jdiameter.common.api.app.auth.ClientAuthSessionState;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.common.AppSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ClientAuthSessionDataReplicatedImpl extends AppSessionDataReplicatedImpl implements IClientAuthSessionData {
private static final String STATE = "STATE";
private static final String DESTINATION_HOST = "DESTINATION_HOST";
private static final String DESTINATION_REALM = "DESTINATION_REALM";
private static final String STATELESS = "STATELESS";
private static final String TS_TIMERID = "TS_TIMERID";
/**
* @param nodeFqn
* @param mobicentsCluster
* @param iface
*/
public ClientAuthSessionDataReplicatedImpl(Fqn<?> nodeFqn, MobicentsCluster mobicentsCluster) {
super(nodeFqn, mobicentsCluster);
if (super.create()) {
setAppSessionIface(this, ClientAuthSession.class);
setClientAuthSessionState(ClientAuthSessionState.IDLE);
}
}
/**
* @param sessionId
* @param mobicentsCluster
* @param iface
*/
public ClientAuthSessionDataReplicatedImpl(String sessionId, MobicentsCluster mobicentsCluster) {
this(Fqn.fromRelativeElements(ReplicatedSessionDatasource.SESSIONS_FQN, sessionId), mobicentsCluster);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.auth.IClientAuthSessionData#setClientAuthSessionState(org.jdiameter.common.api.app.auth.
* ClientAuthSessionState)
*/
@Override
public void setClientAuthSessionState(ClientAuthSessionState state) {
if (exists()) {
getNode().put(STATE, state);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.auth.IClientAuthSessionData#getClientAuthSessionState()
*/
@Override
public ClientAuthSessionState getClientAuthSessionState() {
if (exists()) {
return (ClientAuthSessionState) getNode().get(STATE);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.auth.IClientAuthSessionData#isStateless()
*/
@Override
public boolean isStateless() {
if (exists()) {
return toPrimitive((Boolean) getNode().get(STATELESS), true);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.auth.IClientAuthSessionData#setStateless(boolean)
*/
@Override
public void setStateless(boolean b) {
if (exists()) {
getNode().put(STATELESS, b);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.auth.IClientAuthSessionData#getDestinationHost()
*/
@Override
public String getDestinationHost() {
if (exists()) {
return (String) getNode().get(DESTINATION_HOST);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.auth.IClientAuthSessionData#setDestinationHost(java.lang.String)
*/
@Override
public void setDestinationHost(String host) {
if (exists()) {
getNode().put(DESTINATION_HOST, host);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.auth.IClientAuthSessionData#getDestinationRealm()
*/
@Override
public String getDestinationRealm() {
if (exists()) {
return (String) getNode().get(DESTINATION_REALM);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.auth.IClientAuthSessionData#setDestinationRealm(java.lang.String)
*/
@Override
public void setDestinationRealm(String realm) {
if (exists()) {
getNode().put(DESTINATION_REALM, realm);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.auth.IClientAuthSessionData#getTsTimerId()
*/
@Override
public Serializable getTsTimerId() {
if (exists()) {
return (Serializable) getNode().get(TS_TIMERID);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.auth.IClientAuthSessionData#setTsTimerId(java.io.Serializable)
*/
@Override
public void setTsTimerId(Serializable tid) {
if (exists()) {
getNode().put(TS_TIMERID, tid);
}
else {
throw new IllegalStateException();
}
}
}
| 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.diameter.impl.ha.client.acc;
import java.io.Serializable;
import java.nio.ByteBuffer;
import org.jboss.cache.Fqn;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.Request;
import org.jdiameter.api.acc.ClientAccSession;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.parser.IMessageParser;
import org.jdiameter.client.api.parser.ParseException;
import org.jdiameter.client.impl.app.acc.IClientAccSessionData;
import org.jdiameter.common.api.app.acc.ClientAccSessionState;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.common.AppSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ClientAccSessionDataReplicatedImpl extends AppSessionDataReplicatedImpl implements IClientAccSessionData {
private static final Logger logger = LoggerFactory.getLogger(ClientAccSessionDataReplicatedImpl.class);
private static final String STATE = "STATE";
private static final String INTERIM_TIMERID = "INTERIM_TIMERID";
private static final String DEST_HOST = "DEST_HOST";
private static final String DEST_REALM = "DEST_REALM";
private static final String BUFFER = "BUFFER";
private IMessageParser messageParser;
/**
* @param nodeFqn
* @param mobicentsCluster
* @param iface
*/
public ClientAccSessionDataReplicatedImpl(Fqn<?> nodeFqn, MobicentsCluster mobicentsCluster, IContainer container) {
super(nodeFqn, mobicentsCluster);
if (super.create()) {
setAppSessionIface(this, ClientAccSession.class);
setClientAccSessionState(ClientAccSessionState.IDLE);
}
this.messageParser = container.getAssemblerFacility().getComponentInstance(IMessageParser.class);
}
/**
* @param sessionId
* @param mobicentsCluster
* @param iface
*/
public ClientAccSessionDataReplicatedImpl(String sessionId, MobicentsCluster mobicentsCluster, IContainer container) {
this(Fqn.fromRelativeElements(ReplicatedSessionDatasource.SESSIONS_FQN, sessionId), mobicentsCluster, container);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.acc.IClientAccSessionData#setClientAccSessionState
* (org.jdiameter.common.api.app.acc.ClientAccSessionState)
*/
@Override
public void setClientAccSessionState(ClientAccSessionState state) {
if (exists()) {
getNode().put(STATE, state);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.acc.IClientAccSessionData#getClientAccSessionState()
*/
@Override
public ClientAccSessionState getClientAccSessionState() {
if (exists()) {
return (ClientAccSessionState) getNode().get(STATE);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.acc.IClientAccSessionData#setInterimTimerId(java.io.Serializable)
*/
@Override
public void setInterimTimerId(Serializable tid) {
if (exists()) {
getNode().put(INTERIM_TIMERID, tid);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.acc.IClientAccSessionData#getInterimTimerId()
*/
@Override
public Serializable getInterimTimerId() {
if (exists()) {
return (Serializable) getNode().get(INTERIM_TIMERID);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.acc.IClientAccSessionData#setDestinationHost(java.lang.String)
*/
@Override
public void setDestinationHost(String destHost) {
if (exists()) {
getNode().put(DEST_HOST, destHost);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.acc.IClientAccSessionData#getDestinationHost()
*/
@Override
public String getDestinationHost() {
if (exists()) {
return (String) getNode().get(DEST_HOST);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.acc.IClientAccSessionData#setDestinationRealm(java.lang.String)
*/
@Override
public void setDestinationRealm(String destRealm) {
if (exists()) {
getNode().put(DEST_REALM, destRealm);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.acc.IClientAccSessionData#getDestinationRealm()
*/
@Override
public String getDestinationRealm() {
if (exists()) {
return (String) getNode().get(DEST_REALM);
}
else {
throw new IllegalStateException();
}
}
@Override
public Request getBuffer() {
byte[] data = (byte[]) getNode().get(BUFFER);
if (data != null) {
try {
return (Request) this.messageParser.createMessage(ByteBuffer.wrap(data));
}
catch (AvpDataException e) {
logger.error("Unable to recreate message from buffer.");
return null;
}
}
else {
return null;
}
}
@Override
public void setBuffer(Request buffer) {
if (buffer != null) {
try {
byte[] data = this.messageParser.encodeMessage((IMessage) buffer).array();
getNode().put(BUFFER, data);
}
catch (ParseException e) {
logger.error("Unable to encode message to buffer.");
}
}
else {
getNode().remove(BUFFER);
}
}
}
| 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.diameter.impl.ha.client.ro;
import java.io.Serializable;
import java.nio.ByteBuffer;
import org.jboss.cache.Fqn;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.Request;
import org.jdiameter.api.ro.ClientRoSession;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.parser.IMessageParser;
import org.jdiameter.client.api.parser.ParseException;
import org.jdiameter.client.impl.app.ro.IClientRoSessionData;
import org.jdiameter.common.api.app.ro.ClientRoSessionState;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.common.AppSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ClientRoSessionDataReplicatedImpl extends AppSessionDataReplicatedImpl implements IClientRoSessionData {
private static final Logger logger = LoggerFactory.getLogger(ClientRoSessionDataReplicatedImpl.class);
private static final String EVENT_BASED = "EVENT_BASED";
private static final String REQUEST_TYPE = "REQUEST_TYPE";
private static final String STATE = "STATE";
private static final String TXTIMER_ID = "TXTIMER_ID";
private static final String TXTIMER_REQUEST = "TXTIMER_REQUEST";
private static final String BUFFER = "BUFFER";
private static final String GRA = "GRA";
private static final String GDDFH = "GDDFH";
private static final String GCCFH = "GCCFH";
private IMessageParser messageParser;
/**
* @param nodeFqn
* @param mobicentsCluster
* @param iface
*/
public ClientRoSessionDataReplicatedImpl(Fqn<?> nodeFqn, MobicentsCluster mobicentsCluster, IContainer container) {
super(nodeFqn, mobicentsCluster);
if (super.create()) {
setAppSessionIface(this, ClientRoSession.class);
setClientRoSessionState(ClientRoSessionState.IDLE);
}
this.messageParser = container.getAssemblerFacility().getComponentInstance(IMessageParser.class);
}
/**
* @param sessionId
* @param mobicentsCluster
* @param iface
*/
public ClientRoSessionDataReplicatedImpl(String sessionId, MobicentsCluster mobicentsCluster, IContainer container) {
this(Fqn.fromRelativeElements(ReplicatedSessionDatasource.SESSIONS_FQN, sessionId), mobicentsCluster, container);
}
public boolean isEventBased() {
if (exists()) {
return toPrimitive((Boolean) getNode().get(EVENT_BASED), true);
}
else {
throw new IllegalStateException();
}
}
public void setEventBased(boolean isEventBased) {
if (exists()) {
getNode().put(EVENT_BASED, isEventBased);
}
else {
throw new IllegalStateException();
}
}
public boolean isRequestTypeSet() {
if (exists()) {
return toPrimitive((Boolean) getNode().get(REQUEST_TYPE), false);
}
else {
throw new IllegalStateException();
}
}
public void setRequestTypeSet(boolean requestTypeSet) {
if (exists()) {
getNode().put(REQUEST_TYPE, requestTypeSet);
}
else {
throw new IllegalStateException();
}
}
public ClientRoSessionState getClientRoSessionState() {
if (exists()) {
return (ClientRoSessionState) getNode().get(STATE);
}
else {
throw new IllegalStateException();
}
}
public void setClientRoSessionState(ClientRoSessionState state) {
if (exists()) {
getNode().put(STATE, state);
}
else {
throw new IllegalStateException();
}
}
public Serializable getTxTimerId() {
if (exists()) {
return (Serializable) getNode().get(TXTIMER_ID);
}
else {
throw new IllegalStateException();
}
}
public void setTxTimerId(Serializable txTimerId) {
if (exists()) {
getNode().put(TXTIMER_ID, txTimerId);
}
else {
throw new IllegalStateException();
}
}
public Request getTxTimerRequest() {
if (exists()) {
byte[] data = (byte[]) getNode().get(TXTIMER_REQUEST);
if (data != null) {
try {
return (Request) this.messageParser.createMessage(ByteBuffer.wrap(data));
}
catch (AvpDataException e) {
logger.error("Unable to recreate Tx Timer Request from buffer.");
return null;
}
}
else {
return null;
}
}
else {
throw new IllegalStateException();
}
}
public void setTxTimerRequest(Request txTimerRequest) {
if (exists()) {
if (txTimerRequest != null) {
try {
byte[] data = this.messageParser.encodeMessage((IMessage) txTimerRequest).array();
getNode().put(TXTIMER_REQUEST, data);
}
catch (ParseException e) {
logger.error("Unable to encode Tx Timer Request to buffer.");
}
}
else {
getNode().remove(TXTIMER_REQUEST);
}
}
else {
throw new IllegalStateException();
}
}
public Request getBuffer() {
byte[] data = (byte[]) getNode().get(BUFFER);
if (data != null) {
try {
return (Request) this.messageParser.createMessage(ByteBuffer.wrap(data));
}
catch (AvpDataException e) {
logger.error("Unable to recreate message from buffer.");
return null;
}
}
else {
return null;
}
}
public void setBuffer(Request buffer) {
if (buffer != null) {
try {
byte[] data = this.messageParser.encodeMessage((IMessage) buffer).array();
getNode().put(BUFFER, data);
}
catch (ParseException e) {
logger.error("Unable to encode message to buffer.");
}
}
else {
getNode().remove(BUFFER);
}
}
public int getGatheredRequestedAction() {
if (exists()) {
return toPrimitive((Integer) getNode().get(GRA));
}
else {
throw new IllegalStateException();
}
}
public void setGatheredRequestedAction(int gatheredRequestedAction) {
if (exists()) {
getNode().put(GRA, gatheredRequestedAction);
}
else {
throw new IllegalStateException();
}
}
public int getGatheredCCFH() {
if (exists()) {
return toPrimitive((Integer) getNode().get(GCCFH));
}
else {
throw new IllegalStateException();
}
}
public void setGatheredCCFH(int gatheredCCFH) {
if (exists()) {
getNode().put(GCCFH, gatheredCCFH);
}
else {
throw new IllegalStateException();
}
}
public int getGatheredDDFH() {
if (exists()) {
return toPrimitive((Integer) getNode().get(GDDFH));
}
else {
throw new IllegalStateException();
}
}
public void setGatheredDDFH(int gatheredDDFH) {
if (exists()) {
getNode().put(GDDFH, gatheredDDFH);
}
else {
throw new IllegalStateException();
}
}
}
| 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.diameter.impl.ha.client.rf;
import java.io.Serializable;
import java.nio.ByteBuffer;
import org.jboss.cache.Fqn;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.Request;
import org.jdiameter.api.rf.ClientRfSession;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.parser.IMessageParser;
import org.jdiameter.client.api.parser.ParseException;
import org.jdiameter.client.impl.app.rf.IClientRfSessionData;
import org.jdiameter.common.api.app.rf.ClientRfSessionState;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.common.AppSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ClientRfSessionDataReplicatedImpl extends AppSessionDataReplicatedImpl implements IClientRfSessionData {
private static final Logger logger = LoggerFactory.getLogger(ClientRfSessionDataReplicatedImpl.class);
private static final String STATE = "STATE";
private static final String BUFFER = "BUFFER";
private static final String TS_TIMERID = "TS_TIMERID";
private static final String DESTINATION_HOST = "DESTINATION_HOST";
private static final String DESTINATION_REALM = "DESTINATION_REALM";
private IMessageParser messageParser;
/**
* @param nodeFqn
* @param mobicentsCluster
* @param iface
*/
public ClientRfSessionDataReplicatedImpl(Fqn<?> nodeFqn, MobicentsCluster mobicentsCluster, IContainer container) {
super(nodeFqn, mobicentsCluster);
if (super.create()) {
setAppSessionIface(this, ClientRfSession.class);
setClientRfSessionState(ClientRfSessionState.IDLE);
}
this.messageParser = container.getAssemblerFacility().getComponentInstance(IMessageParser.class);
}
/**
* @param sessionId
* @param mobicentsCluster
* @param iface
*/
public ClientRfSessionDataReplicatedImpl(String sessionId, MobicentsCluster mobicentsCluster, IContainer container) {
this(Fqn.fromRelativeElements(ReplicatedSessionDatasource.SESSIONS_FQN, sessionId), mobicentsCluster, container);
}
public ClientRfSessionState getClientRfSessionState() {
if (exists()) {
return (ClientRfSessionState) getNode().get(STATE);
}
else {
throw new IllegalStateException();
}
}
public void setClientRfSessionState(ClientRfSessionState state) {
if (exists()) {
getNode().put(STATE, state);
}
else {
throw new IllegalStateException();
}
}
public Request getBuffer() {
byte[] data = (byte[]) getNode().get(BUFFER);
if (data != null) {
try {
return (Request) this.messageParser.createMessage(ByteBuffer.wrap(data));
}
catch (AvpDataException e) {
logger.error("Unable to recreate message from buffer.");
return null;
}
}
else {
return null;
}
}
public void setBuffer(Request buffer) {
if (buffer != null) {
try {
byte[] data = this.messageParser.encodeMessage((IMessage) buffer).array();
getNode().put(BUFFER, data);
}
catch (ParseException e) {
logger.error("Unable to encode message to buffer.");
}
}
else {
getNode().remove(BUFFER);
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.rf.IClientRfSessionData#getTsTimerId()
*/
@Override
public Serializable getTsTimerId() {
if (exists()) {
return (Serializable) getNode().get(TS_TIMERID);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.rf.IClientRfSessionData#setTsTimerId(java.io.Serializable)
*/
@Override
public void setTsTimerId(Serializable tid) {
if (exists()) {
getNode().put(TS_TIMERID, tid);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.rf.IClientRfSessionData#getDestinationHost()
*/
@Override
public String getDestinationHost() {
if (exists()) {
return (String) getNode().get(DESTINATION_HOST);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.rf.IClientRfSessionData#setDestinationHost(java.lang.String)
*/
@Override
public void setDestinationHost(String destinationHost) {
if (exists()) {
getNode().put(DESTINATION_HOST, destinationHost);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.rf.IClientRfSessionData#getDestinationRealm()
*/
@Override
public String getDestinationRealm() {
if (exists()) {
return (String) getNode().get(DESTINATION_REALM);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.client.impl.app.rf.IClientRfSessionData#setDestinationRealm(java.lang.String)
*/
@Override
public void setDestinationRealm(String destinationRealm) {
if (exists()) {
getNode().put(DESTINATION_REALM, destinationRealm);
}
else {
throw new IllegalStateException();
}
}
}
| 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.diameter.impl.ha.timer;
import java.io.Serializable;
import org.jdiameter.api.BaseSession;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.common.api.data.ISessionDatasource;
import org.jdiameter.common.api.timer.ITimerFacility;
import org.jdiameter.common.impl.app.AppSessionImpl;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
import org.mobicents.timers.FaultTolerantScheduler;
import org.mobicents.timers.TimerTask;
import org.mobicents.timers.TimerTaskData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Replicated implementation of {@link ITimerFacility}
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ReplicatedTimerFacilityImpl implements ITimerFacility {
private static final Logger logger = LoggerFactory.getLogger(ReplicatedTimerFacilityImpl.class);
private ISessionDatasource sessionDataSource;
private TimerTaskFactory taskFactory;
private FaultTolerantScheduler ftScheduler;
public ReplicatedTimerFacilityImpl(IContainer container) {
super();
this.sessionDataSource = container.getAssemblerFacility().getComponentInstance(ISessionDatasource.class);
this.taskFactory = new TimerTaskFactory();
MobicentsCluster cluster = ((ReplicatedSessionDatasource) this.sessionDataSource).getMobicentsCluster();
this.ftScheduler = new FaultTolerantScheduler("DiameterTimer", 5, cluster, (byte) 12, null, this.taskFactory);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.timer.ITimerFacility#cancel(java.io.Serializable)
*/
public void cancel(Serializable id) {
logger.debug("Cancelling timer with id {}", id);
this.ftScheduler.cancel(id);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.timer.ITimerFacility#schedule(java.lang.String, java.lang.String, long)
*/
public Serializable schedule(String sessionId, String timerName, long miliseconds) throws IllegalArgumentException {
String id = sessionId + "/" + timerName;
logger.debug("Scheduling timer with id {}", id);
if (this.ftScheduler.getTimerTaskData(id) != null) {
throw new IllegalArgumentException("Timer already running: " + id);
}
DiameterTimerTaskData data = new DiameterTimerTaskData(id, miliseconds, sessionId, timerName);
TimerTask tt = this.taskFactory.newTimerTask(data);
ftScheduler.schedule(tt);
return id;
}
private final class TimerTaskFactory implements org.mobicents.timers.TimerTaskFactory {
public TimerTask newTimerTask(TimerTaskData data) {
return new DiameterTimerTask(data);
}
}
private final class DiameterTimerTask extends TimerTask {
public DiameterTimerTask(TimerTaskData data) {
super(data);
}
public void runTask() {
try {
DiameterTimerTaskData data = (DiameterTimerTaskData) getData();
BaseSession bSession = sessionDataSource.getSession(data.getSessionId());
if (bSession == null || !bSession.isAppSession()) {
// FIXME: error ?
return;
}
else {
AppSessionImpl impl = (AppSessionImpl) bSession;
impl.onTimer(data.getTimerName());
}
}
catch (Exception e) {
logger.error("Failure executing timer task", e);
}
}
}
}
| 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.diameter.impl.ha.timer;
import java.io.Serializable;
import org.mobicents.timers.PeriodicScheduleStrategy;
import org.mobicents.timers.TimerTaskData;
/**
* Diameter timer task data holder.
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
final class DiameterTimerTaskData extends TimerTaskData {
private static final long serialVersionUID = 8774218122384404225L;
// data we need to recreate timer task
private String sessionId;
private String timerName;
public DiameterTimerTaskData(Serializable id, long delay, String sessionId, String timerName) {
super(id, System.currentTimeMillis() + delay, -1, PeriodicScheduleStrategy.withFixedDelay);
this.sessionId = sessionId;
this.timerName = timerName;
}
public String getSessionId() {
return sessionId;
}
public String getTimerName() {
return timerName;
}
}
| 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.diameter.impl.ha.data;
import java.util.HashMap;
import javax.transaction.TransactionManager;
import org.jboss.cache.Fqn;
import org.jdiameter.api.BaseSession;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.api.app.IAppSessionData;
import org.jdiameter.common.api.app.IAppSessionDataFactory;
import org.jdiameter.common.api.app.IAppSessionFactory;
import org.jdiameter.common.api.app.acc.IAccSessionData;
import org.jdiameter.common.api.app.auth.IAuthSessionData;
import org.jdiameter.common.api.app.cca.ICCASessionData;
import org.jdiameter.common.api.app.cxdx.ICxDxSessionData;
import org.jdiameter.common.api.app.gx.IGxSessionData;
import org.jdiameter.common.api.app.rx.IRxSessionData;
import org.jdiameter.common.api.app.rf.IRfSessionData;
import org.jdiameter.common.api.app.ro.IRoSessionData;
import org.jdiameter.common.api.app.sh.IShSessionData;
import org.jdiameter.common.api.data.ISessionDatasource;
import org.jdiameter.common.impl.data.LocalDataSource;
import org.mobicents.cache.MobicentsCache;
import org.mobicents.cluster.DataRemovalListener;
import org.mobicents.cluster.DefaultMobicentsCluster;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.cluster.election.DefaultClusterElector;
import org.mobicents.diameter.impl.ha.common.AppSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.common.acc.AccReplicatedSessionDataFactory;
import org.mobicents.diameter.impl.ha.common.auth.AuthReplicatedSessionDataFactory;
import org.mobicents.diameter.impl.ha.common.cca.CCAReplicatedSessionDataFactory;
import org.mobicents.diameter.impl.ha.common.cxdx.CxDxReplicatedSessionDataFactory;
import org.mobicents.diameter.impl.ha.common.gx.GxReplicatedSessionDataFactory;
import org.mobicents.diameter.impl.ha.common.rx.RxReplicatedSessionDataFactory;
import org.mobicents.diameter.impl.ha.common.rf.RfReplicatedSessionDataFactory;
import org.mobicents.diameter.impl.ha.common.ro.RoReplicatedSessionDataFactory;
import org.mobicents.diameter.impl.ha.common.sh.ShReplicatedSessionDataFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Replicated datasource implementation for {@link ISessionDatasource}
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class ReplicatedSessionDatasource implements ISessionDatasource, DataRemovalListener {
private static final Logger logger = LoggerFactory.getLogger(ReplicatedSessionDatasource.class);
public static final String CLUSTER_DS_DEFAULT_FILE = "jdiameter-jbc.xml";
private IContainer container;
private ISessionDatasource localDataSource;
private DefaultMobicentsCluster mobicentsCluster;
private boolean localMode;
// provided by impl, no way to change that, no conf! :)
protected HashMap<Class<? extends IAppSessionData>, IAppSessionDataFactory<? extends IAppSessionData>> appSessionDataFactories = new HashMap<Class<? extends IAppSessionData>, IAppSessionDataFactory<? extends IAppSessionData>>();
// Constants
// ----------------------------------------------------------------
public final static String SESSIONS = "/diameter/appsessions";
public final static Fqn SESSIONS_FQN = Fqn.fromString(SESSIONS);
public ReplicatedSessionDatasource(IContainer container) {
this(container, new LocalDataSource(), ReplicatedSessionDatasource.class.getClassLoader().getResource(CLUSTER_DS_DEFAULT_FILE) == null ? "config/" + CLUSTER_DS_DEFAULT_FILE : CLUSTER_DS_DEFAULT_FILE);
}
public ReplicatedSessionDatasource(IContainer container, ISessionDatasource localDataSource, String cacheConfigFilename) {
super();
this.localDataSource = localDataSource;
MobicentsCache mcCache = new MobicentsCache(cacheConfigFilename);
TransactionManager txMgr = null;
try {
Class<?> txMgrClass = Class.forName(mcCache.getJBossCache().getConfiguration().getTransactionManagerLookupClass());
Object txMgrLookup = txMgrClass.getConstructor(new Class[]{}).newInstance(new Object[]{});
txMgr = (TransactionManager) txMgrClass.getMethod("getTransactionManager", new Class[]{}).invoke(txMgrLookup, new Object[]{});
}
catch (Exception e) {
logger.debug("Could not fetch TxMgr. Not using one.", e);
// let's not have Tx Manager than...
}
this.mobicentsCluster = new DefaultMobicentsCluster(mcCache, txMgr, new DefaultClusterElector());
this.mobicentsCluster.addDataRemovalListener(this); // register, so we know WHEN some other node removes session.
this.mobicentsCluster.startCluster();
this.container = container;
// this is coded, its tied to specific impl of SessionDatasource
appSessionDataFactories.put(IAuthSessionData.class, new AuthReplicatedSessionDataFactory(this));
appSessionDataFactories.put(IAccSessionData.class, new AccReplicatedSessionDataFactory(this));
appSessionDataFactories.put(ICCASessionData.class, new CCAReplicatedSessionDataFactory(this));
appSessionDataFactories.put(IRoSessionData.class, new RoReplicatedSessionDataFactory(this));
appSessionDataFactories.put(IRfSessionData.class, new RfReplicatedSessionDataFactory(this));
appSessionDataFactories.put(IShSessionData.class, new ShReplicatedSessionDataFactory(this));
appSessionDataFactories.put(ICxDxSessionData.class, new CxDxReplicatedSessionDataFactory(this));
appSessionDataFactories.put(IGxSessionData.class, new GxReplicatedSessionDataFactory(this));
appSessionDataFactories.put(IRxSessionData.class, new RxReplicatedSessionDataFactory(this));
}
@Override
public boolean exists(String sessionId) {
return this.localDataSource.exists(sessionId) ? true : this.existReplicated(sessionId);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.ha.ISessionDatasource#addSession(org.jdiameter .api.BaseSession)
*/
public void addSession(BaseSession session) {
// Simple as is, if its replicated, it will be already there :)
this.localDataSource.addSession(session);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.ha.ISessionDatasource#getSession(java.lang.String )
*/
public BaseSession getSession(String sessionId) {
if (this.localDataSource.exists(sessionId)) {
return this.localDataSource.getSession(sessionId);
}
else if (!this.localMode && this.existReplicated(sessionId)) {
this.makeLocal(sessionId);
return this.localDataSource.getSession(sessionId);
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.ha.ISessionDatasource#getSessionListener(java .lang.String)
*/
public NetworkReqListener getSessionListener(String sessionId) {
if (this.localDataSource.exists(sessionId)) {
return this.localDataSource.getSessionListener(sessionId);
}
else if (!this.localMode && this.existReplicated(sessionId)) {
this.makeLocal(sessionId);
return this.localDataSource.getSessionListener(sessionId);
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.ha.ISessionDatasource#removeSession(java.lang .String)
*/
public void removeSession(String sessionId) {
logger.debug("removeSession({}) in Local DataSource", sessionId);
if (this.localDataSource.exists(sessionId)) {
this.localDataSource.removeSession(sessionId);
}
else if (!this.localMode && this.existReplicated(sessionId)) {
// FIXME: remove node.
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.ha.ISessionDatasource#removeSessionListener( java.lang.String)
*/
public NetworkReqListener removeSessionListener(String sessionId) {
if (this.localDataSource.exists(sessionId)) {
return this.localDataSource.removeSessionListener(sessionId);
}
else if (!this.localMode && this.existReplicated(sessionId)) {
// does not make much sense ;[
this.makeLocal(sessionId);
return this.localDataSource.removeSessionListener(sessionId);
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.ha.ISessionDatasource#setSessionListener(java .lang.String, org.jdiameter.api.NetworkReqListener)
*/
public void setSessionListener(String sessionId, NetworkReqListener data) {
if (this.localDataSource.exists(sessionId)) {
this.localDataSource.setSessionListener(sessionId, data);
}
else if (!this.localMode && this.existReplicated(sessionId)) {
// does not make much sense ;[
this.makeLocal(sessionId);
this.localDataSource.setSessionListener(sessionId, data);
}
}
public void start() {
mobicentsCluster.getMobicentsCache().startCache();
localMode = mobicentsCluster.getMobicentsCache().isLocalMode();
}
public void stop() {
mobicentsCluster.getMobicentsCache().stopCache();
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.data.ISessionDatasource#isClustered()
*/
public boolean isClustered() {
return !localMode;
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.data.ISessionDatasource#getDataFactory(java. lang.Class)
*/
@Override
public IAppSessionDataFactory<? extends IAppSessionData> getDataFactory(Class<? extends IAppSessionData> x) {
return this.appSessionDataFactories.get(x);
}
// remove lst;
public MobicentsCluster getMobicentsCluster() {
return this.mobicentsCluster;
}
public void dataRemoved(Fqn sessionFqn) {
String sessionId = (String) sessionFqn.getLastElement();
this.localDataSource.removeSession(sessionId);
}
public Fqn getBaseFqn() {
return SESSIONS_FQN;
}
/**
* @param sessionId
* @return
*/
private boolean existReplicated(String sessionId) {
if (!this.localMode && this.mobicentsCluster.getMobicentsCache().getJBossCache().getNode(Fqn.fromRelativeElements(SESSIONS_FQN, sessionId)) != null) {
return true;
}
return false;
}
/**
* @param sessionId
*/
private void makeLocal(String sessionId) {
try {
// this is APP session, always
Class<? extends AppSession> appSessionInterfaceClass = AppSessionDataReplicatedImpl.getAppSessionIface(this.mobicentsCluster.getMobicentsCache(), sessionId);
// get factory;
// FIXME: make it a field?
IAppSessionFactory fct = ((ISessionFactory) this.container.getSessionFactory()).getAppSessionFactory(appSessionInterfaceClass);
if (fct == null) {
logger.warn("Session with id:{}, is in replicated data source, but no Application Session Factory for:{}.", sessionId, appSessionInterfaceClass);
return;
}
else {
BaseSession session = fct.getSession(sessionId, appSessionInterfaceClass);
this.localDataSource.addSession(session);
// hmmm
this.localDataSource.setSessionListener(sessionId, (NetworkReqListener) session);
return;
}
}
catch (IllegalDiameterStateException e) {
if (logger.isErrorEnabled()) {
logger.error("Failed to obtain factory from stack...");
}
}
}
// ------- local getter
public IContainer getContainer() {
return this.container;
}
}
| 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.diameter.impl.ha.server.sh;
import org.jboss.cache.Fqn;
import org.jdiameter.api.sh.ServerShSession;
import org.jdiameter.server.impl.app.sh.IShServerSessionData;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.common.AppSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ShServerSessionDataReplicatedImpl extends AppSessionDataReplicatedImpl implements IShServerSessionData {
/**
* @param nodeFqn
* @param mobicentsCluster
* @param iface
*/
public ShServerSessionDataReplicatedImpl(Fqn<?> nodeFqn, MobicentsCluster mobicentsCluster) {
super(nodeFqn, mobicentsCluster);
if (super.create()) {
setAppSessionIface(this, ServerShSession.class);
}
}
/**
* @param sessionId
* @param mobicentsCluster
* @param iface
*/
public ShServerSessionDataReplicatedImpl(String sessionId, MobicentsCluster mobicentsCluster) {
this(Fqn.fromRelativeElements(ReplicatedSessionDatasource.SESSIONS_FQN, sessionId), mobicentsCluster);
}
}
| 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.diameter.impl.ha.server.cca;
import java.io.Serializable;
import org.jboss.cache.Fqn;
import org.jdiameter.api.cca.ServerCCASession;
import org.jdiameter.common.api.app.cca.ServerCCASessionState;
import org.jdiameter.server.impl.app.cca.IServerCCASessionData;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.common.AppSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ServerCCASessionDataReplicatedImpl extends AppSessionDataReplicatedImpl implements IServerCCASessionData {
private static final String TCCID = "TCCID";
private static final String STATELESS = "STATELESS";
private static final String STATE = "STATE";
/**
* @param nodeFqn
* @param mobicentsCluster
* @param iface
*/
public ServerCCASessionDataReplicatedImpl(Fqn<?> nodeFqn, MobicentsCluster mobicentsCluster) {
super(nodeFqn, mobicentsCluster);
if (super.create()) {
setAppSessionIface(this, ServerCCASession.class);
setServerCCASessionState(ServerCCASessionState.IDLE);
}
}
/**
* @param sessionId
* @param mobicentsCluster
* @param iface
*/
public ServerCCASessionDataReplicatedImpl(String sessionId, MobicentsCluster mobicentsCluster) {
this(Fqn.fromRelativeElements(ReplicatedSessionDatasource.SESSIONS_FQN, sessionId), mobicentsCluster);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#isStateless()
*/
@Override
public boolean isStateless() {
if (exists()) {
return toPrimitive((Boolean) getNode().get(STATELESS), true);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#setStateless( boolean)
*/
@Override
public void setStateless(boolean stateless) {
if (exists()) {
getNode().put(STATELESS, stateless);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData# getServerCCASessionState()
*/
@Override
public ServerCCASessionState getServerCCASessionState() {
if (exists()) {
return (ServerCCASessionState) getNode().get(STATE);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData# setServerCCASessionState
* (org.jdiameter.common.api.app.cca.ServerCCASessionState)
*/
@Override
public void setServerCCASessionState(ServerCCASessionState state) {
if (exists()) {
getNode().put(STATE, state);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#setTccTimerId (java.io.Serializable)
*/
@Override
public void setTccTimerId(Serializable tccTimerId) {
if (exists()) {
getNode().put(TCCID, tccTimerId);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#getTccTimerId()
*/
@Override
public Serializable getTccTimerId() {
if (exists()) {
return (Serializable) getNode().get(TCCID);
}
else {
throw new IllegalStateException();
}
}
}
| 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.diameter.impl.ha.server.cxdx;
import org.jboss.cache.Fqn;
import org.jdiameter.api.cxdx.ServerCxDxSession;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.common.api.app.cxdx.CxDxSessionState;
import org.jdiameter.server.impl.app.cxdx.IServerCxDxSessionData;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.common.cxdx.CxDxSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ServerCxDxSessionDataReplicatedImpl extends CxDxSessionDataReplicatedImpl implements IServerCxDxSessionData {
/**
* @param nodeFqn
* @param mobicentsCluster
* @param iface
*/
public ServerCxDxSessionDataReplicatedImpl(Fqn<?> nodeFqn, MobicentsCluster mobicentsCluster, IContainer container) {
super(nodeFqn, mobicentsCluster, container);
if (super.create()) {
setAppSessionIface(this, ServerCxDxSession.class);
setCxDxSessionState(CxDxSessionState.IDLE);
}
}
/**
* @param sessionId
* @param mobicentsCluster
* @param iface
*/
public ServerCxDxSessionDataReplicatedImpl(String sessionId, MobicentsCluster mobicentsCluster, IContainer container) {
this(Fqn.fromRelativeElements(ReplicatedSessionDatasource.SESSIONS_FQN, sessionId), mobicentsCluster, container);
}
}
| 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.diameter.impl.ha.server.gx;
import java.io.Serializable;
import org.jboss.cache.Fqn;
import org.jdiameter.api.gx.ServerGxSession;
import org.jdiameter.common.api.app.gx.ServerGxSessionState;
import org.jdiameter.server.impl.app.gx.IServerGxSessionData;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.common.AppSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ServerGxSessionDataReplicatedImpl extends AppSessionDataReplicatedImpl implements IServerGxSessionData {
private static final String TCCID = "TCCID";
private static final String STATELESS = "STATELESS";
private static final String STATE = "STATE";
/**
* @param nodeFqn
* @param mobicentsCluster
* @param iface
*/
public ServerGxSessionDataReplicatedImpl(Fqn<?> nodeFqn, MobicentsCluster mobicentsCluster) {
super(nodeFqn, mobicentsCluster);
if (super.create()) {
setAppSessionIface(this, ServerGxSession.class);
setServerGxSessionState(ServerGxSessionState.IDLE);
}
}
/**
* @param sessionId
* @param mobicentsCluster
* @param iface
*/
public ServerGxSessionDataReplicatedImpl(String sessionId, MobicentsCluster mobicentsCluster) {
this(Fqn.fromRelativeElements(ReplicatedSessionDatasource.SESSIONS_FQN, sessionId), mobicentsCluster);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#isStateless()
*/
@Override
public boolean isStateless() {
if (exists()) {
return toPrimitive((Boolean) getNode().get(STATELESS), true);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#setStateless( boolean)
*/
@Override
public void setStateless(boolean stateless) {
if (exists()) {
getNode().put(STATELESS, stateless);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData# getServerCCASessionState()
*/
@Override
public ServerGxSessionState getServerGxSessionState() {
if (exists()) {
return (ServerGxSessionState) getNode().get(STATE);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData# setServerCCASessionState
* (org.jdiameter.common.api.app.cca.ServerCCASessionState)
*/
@Override
public void setServerGxSessionState(ServerGxSessionState state) {
if (exists()) {
getNode().put(STATE, state);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#setTccTimerId (java.io.Serializable)
*/
@Override
public void setTccTimerId(Serializable tccTimerId) {
if (exists()) {
getNode().put(TCCID, tccTimerId);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#getTccTimerId()
*/
@Override
public Serializable getTccTimerId() {
if (exists()) {
return (Serializable) getNode().get(TCCID);
}
else {
throw new IllegalStateException();
}
}
}
| 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.diameter.impl.ha.server.rx;
import org.jboss.cache.Fqn;
import org.jdiameter.api.rx.ServerRxSession;
import org.jdiameter.common.api.app.rx.ServerRxSessionState;
import org.jdiameter.server.impl.app.rx.IServerRxSessionData;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.common.AppSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ServerRxSessionDataReplicatedImpl extends AppSessionDataReplicatedImpl implements IServerRxSessionData {
private static final String STATELESS = "STATELESS";
private static final String STATE = "STATE";
/**
* @param nodeFqn
* @param mobicentsCluster
* @param iface
*/
public ServerRxSessionDataReplicatedImpl(Fqn<?> nodeFqn, MobicentsCluster mobicentsCluster) {
super(nodeFqn, mobicentsCluster);
if (super.create()) {
setAppSessionIface(this, ServerRxSession.class);
setServerRxSessionState(ServerRxSessionState.IDLE);
}
}
/**
* @param sessionId
* @param mobicentsCluster
* @param iface
*/
public ServerRxSessionDataReplicatedImpl(String sessionId, MobicentsCluster mobicentsCluster) {
this(Fqn.fromRelativeElements(ReplicatedSessionDatasource.SESSIONS_FQN, sessionId), mobicentsCluster);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#isStateless()
*/
@Override
public boolean isStateless() {
if (exists()) {
return toPrimitive((Boolean) getNode().get(STATELESS), true);
} else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#setStateless( boolean)
*/
@Override
public void setStateless(boolean stateless) {
if (exists()) {
getNode().put(STATELESS, stateless);
} else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData# getServerCCASessionState()
*/
@Override
public ServerRxSessionState getServerRxSessionState() {
if (exists()) {
return (ServerRxSessionState) getNode().get(STATE);
} else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData# setServerCCASessionState
* (org.jdiameter.common.api.app.cca.ServerCCASessionState)
*/
@Override
public void setServerRxSessionState(ServerRxSessionState state) {
if (exists()) {
getNode().put(STATE, state);
} else {
throw new IllegalStateException();
}
}
}
| 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.diameter.impl.ha.server.auth;
import java.io.Serializable;
import org.jboss.cache.Fqn;
import org.jdiameter.api.auth.ServerAuthSession;
import org.jdiameter.common.api.app.auth.ServerAuthSessionState;
import org.jdiameter.server.impl.app.auth.IServerAuthSessionData;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.common.AppSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ServerAuthSessionDataReplicatedImpl extends AppSessionDataReplicatedImpl implements IServerAuthSessionData {
private static final String STATELESS = "STATELESS";
private static final String STATE = "STATE";
private static final String TS_TIMEOUT = "TS_TIMEOUT";
private static final String TS_TIMERID = "TS_TIMERID";
/**
* @param nodeFqn
* @param mobicentsCluster
* @param iface
*/
public ServerAuthSessionDataReplicatedImpl(Fqn<?> nodeFqn, MobicentsCluster mobicentsCluster) {
super(nodeFqn, mobicentsCluster);
if (super.create()) {
setAppSessionIface(this, ServerAuthSession.class);
setServerAuthSessionState(ServerAuthSessionState.IDLE);
}
}
/**
* @param sessionId
* @param mobicentsCluster
* @param iface
*/
public ServerAuthSessionDataReplicatedImpl(String sessionId, MobicentsCluster mobicentsCluster) {
this(Fqn.fromRelativeElements(ReplicatedSessionDatasource.SESSIONS_FQN, sessionId), mobicentsCluster);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#isStateless()
*/
@Override
public boolean isStateless() {
if (exists()) {
return toPrimitive((Boolean) getNode().get(STATELESS), true);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#setStateless( boolean)
*/
@Override
public void setStateless(boolean stateless) {
if (exists()) {
getNode().put(STATELESS, stateless);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData# getServerCCASessionState()
*/
@Override
public ServerAuthSessionState getServerAuthSessionState() {
if (exists()) {
return (ServerAuthSessionState) getNode().get(STATE);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData# setServerCCASessionState
* (org.jdiameter.common.api.app.cca.ServerCCASessionState)
*/
@Override
public void setServerAuthSessionState(ServerAuthSessionState state) {
if (exists()) {
getNode().put(STATE, state);
}
else {
throw new IllegalStateException();
}
}
@Override
public void setTsTimeout(long value) {
if (exists()) {
getNode().put(TS_TIMEOUT, value);
}
else {
throw new IllegalStateException();
}
}
@Override
public long getTsTimeout() {
if (exists()) {
return toPrimitive((Long) getNode().get(TS_TIMEOUT));
}
else {
throw new IllegalStateException();
}
}
@Override
public void setTsTimerId(Serializable value) {
if (exists()) {
getNode().put(TS_TIMERID, value);
}
else {
throw new IllegalStateException();
}
}
@Override
public Serializable getTsTimerId() {
if (exists()) {
return (Serializable) getNode().get(TS_TIMERID);
}
else {
throw new IllegalStateException();
}
}
}
| 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.diameter.impl.ha.server.acc;
import java.io.Serializable;
import org.jboss.cache.Fqn;
import org.jdiameter.api.acc.ServerAccSession;
import org.jdiameter.common.api.app.acc.ServerAccSessionState;
import org.jdiameter.server.impl.app.acc.IServerAccSessionData;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.common.AppSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ServerAccSessionDataReplicatedImpl extends AppSessionDataReplicatedImpl implements IServerAccSessionData {
private static final String STATELESS = "STATELESS";
private static final String STATE = "STATE";
private static final String TS_TIMEOUT = "TS_TIMEOUT";
private static final String TS_TIMERID = "TS_TIMERID";
/**
* @param nodeFqn
* @param mobicentsCluster
* @param iface
*/
public ServerAccSessionDataReplicatedImpl(Fqn<?> nodeFqn, MobicentsCluster mobicentsCluster) {
super(nodeFqn, mobicentsCluster);
if (super.create()) {
setAppSessionIface(this, ServerAccSession.class);
setServerAccSessionState(ServerAccSessionState.IDLE);
}
}
/**
* @param sessionId
* @param mobicentsCluster
* @param iface
*/
public ServerAccSessionDataReplicatedImpl(String sessionId, MobicentsCluster mobicentsCluster) {
this(Fqn.fromRelativeElements(ReplicatedSessionDatasource.SESSIONS_FQN, sessionId), mobicentsCluster);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#isStateless()
*/
@Override
public boolean isStateless() {
if (exists()) {
return toPrimitive((Boolean) getNode().get(STATELESS), true);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#setStateless( boolean)
*/
@Override
public void setStateless(boolean stateless) {
if (exists()) {
getNode().put(STATELESS, stateless);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData# getServerCCASessionState()
*/
@Override
public ServerAccSessionState getServerAccSessionState() {
if (exists()) {
return (ServerAccSessionState) getNode().get(STATE);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData# setServerCCASessionState
* (org.jdiameter.common.api.app.cca.ServerCCASessionState)
*/
@Override
public void setServerAccSessionState(ServerAccSessionState state) {
if (exists()) {
getNode().put(STATE, state);
}
else {
throw new IllegalStateException();
}
}
@Override
public void setTsTimeout(long value) {
if (exists()) {
getNode().put(TS_TIMEOUT, value);
}
else {
throw new IllegalStateException();
}
}
@Override
public long getTsTimeout() {
if (exists()) {
return toPrimitive((Long) getNode().get(TS_TIMEOUT));
}
else {
throw new IllegalStateException();
}
}
@Override
public void setTsTimerId(Serializable value) {
if (exists()) {
getNode().put(TS_TIMERID, value);
}
else {
throw new IllegalStateException();
}
}
@Override
public Serializable getTsTimerId() {
if (exists()) {
return (Serializable) getNode().get(TS_TIMERID);
}
else {
throw new IllegalStateException();
}
}
}
| 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.diameter.impl.ha.server.ro;
import java.io.Serializable;
import org.jboss.cache.Fqn;
import org.jdiameter.api.ro.ServerRoSession;
import org.jdiameter.common.api.app.ro.ServerRoSessionState;
import org.jdiameter.server.impl.app.ro.IServerRoSessionData;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.common.AppSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ServerRoSessionDataReplicatedImpl extends AppSessionDataReplicatedImpl implements IServerRoSessionData {
private static final String TCCID = "TCCID";
private static final String STATELESS = "STATELESS";
private static final String STATE = "STATE";
/**
* @param nodeFqn
* @param mobicentsCluster
* @param iface
*/
public ServerRoSessionDataReplicatedImpl(Fqn<?> nodeFqn, MobicentsCluster mobicentsCluster) {
super(nodeFqn, mobicentsCluster);
if (super.create()) {
setAppSessionIface(this, ServerRoSession.class);
setServerRoSessionState(ServerRoSessionState.IDLE);
}
}
/**
* @param sessionId
* @param mobicentsCluster
* @param iface
*/
public ServerRoSessionDataReplicatedImpl(String sessionId, MobicentsCluster mobicentsCluster) {
this(Fqn.fromRelativeElements(ReplicatedSessionDatasource.SESSIONS_FQN, sessionId), mobicentsCluster);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#isStateless()
*/
@Override
public boolean isStateless() {
if (exists()) {
return toPrimitive((Boolean) getNode().get(STATELESS), true);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#setStateless( boolean)
*/
@Override
public void setStateless(boolean stateless) {
if (exists()) {
getNode().put(STATELESS, stateless);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData# getServerCCASessionState()
*/
@Override
public ServerRoSessionState getServerRoSessionState() {
if (exists()) {
return (ServerRoSessionState) getNode().get(STATE);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData# setServerCCASessionState
* (org.jdiameter.common.api.app.cca.ServerCCASessionState)
*/
@Override
public void setServerRoSessionState(ServerRoSessionState state) {
if (exists()) {
getNode().put(STATE, state);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#setTccTimerId (java.io.Serializable)
*/
@Override
public void setTccTimerId(Serializable tccTimerId) {
if (exists()) {
getNode().put(TCCID, tccTimerId);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#getTccTimerId()
*/
@Override
public Serializable getTccTimerId() {
if (exists()) {
return (Serializable) getNode().get(TCCID);
}
else {
throw new IllegalStateException();
}
}
}
| 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.diameter.impl.ha.server.rf;
import java.io.Serializable;
import org.jboss.cache.Fqn;
import org.jdiameter.api.rf.ServerRfSession;
import org.jdiameter.common.api.app.rf.ServerRfSessionState;
import org.jdiameter.server.impl.app.rf.IServerRfSessionData;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.common.AppSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ServerRfSessionDataReplicatedImpl extends AppSessionDataReplicatedImpl implements IServerRfSessionData {
private static final String TS_TIMERID = "TCCID";
private static final String STATELESS = "STATELESS";
private static final String STATE = "STATE";
private static final String TS_TIMEOUT = "TS_TIMEOUT";
/**
* @param nodeFqn
* @param mobicentsCluster
* @param iface
*/
public ServerRfSessionDataReplicatedImpl(Fqn<?> nodeFqn, MobicentsCluster mobicentsCluster) {
super(nodeFqn, mobicentsCluster);
if (super.create()) {
setAppSessionIface(this, ServerRfSession.class);
setServerRfSessionState(ServerRfSessionState.IDLE);
}
}
/**
* @param sessionId
* @param mobicentsCluster
* @param iface
*/
public ServerRfSessionDataReplicatedImpl(String sessionId, MobicentsCluster mobicentsCluster) {
this(Fqn.fromRelativeElements(ReplicatedSessionDatasource.SESSIONS_FQN, sessionId), mobicentsCluster);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#isStateless()
*/
@Override
public boolean isStateless() {
if (exists()) {
return toPrimitive((Boolean) getNode().get(STATELESS), true);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#setStateless( boolean)
*/
@Override
public void setStateless(boolean stateless) {
if (exists()) {
getNode().put(STATELESS, stateless);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData# getServerCCASessionState()
*/
@Override
public ServerRfSessionState getServerRfSessionState() {
if (exists()) {
return (ServerRfSessionState) getNode().get(STATE);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData# setServerCCASessionState
* (org.jdiameter.common.api.app.cca.ServerCCASessionState)
*/
@Override
public void setServerRfSessionState(ServerRfSessionState state) {
if (exists()) {
getNode().put(STATE, state);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#setTccTimerId (java.io.Serializable)
*/
@Override
public void setTsTimerId(Serializable tccTimerId) {
if (exists()) {
getNode().put(TS_TIMERID, tccTimerId);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.cca.IServerCCASessionData#getTccTimerId()
*/
@Override
public Serializable getTsTimerId() {
if (exists()) {
return (Serializable) getNode().get(TS_TIMERID);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.rf.IServerRfSessionData#getTsTimeout()
*/
@Override
public long getTsTimeout() {
if (exists()) {
return toPrimitive((Long) getNode().get(TS_TIMEOUT));
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.server.impl.app.rf.IServerRfSessionData#setTsTimeout(long)
*/
@Override
public void setTsTimeout(long l) {
if (exists()) {
getNode().put(TS_TIMEOUT, l);
}
else {
throw new IllegalStateException();
}
}
}
| 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.diameter.impl.ha.common.sh;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.sh.ClientShSession;
import org.jdiameter.api.sh.ServerShSession;
import org.jdiameter.common.api.app.IAppSessionDataFactory;
import org.jdiameter.common.api.app.sh.IShSessionData;
import org.jdiameter.common.api.data.ISessionDatasource;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.client.sh.ShClientSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
import org.mobicents.diameter.impl.ha.server.sh.ShServerSessionDataReplicatedImpl;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ShReplicatedSessionDataFactory implements IAppSessionDataFactory<IShSessionData> {
private ReplicatedSessionDatasource replicatedSessionDataSource;
private MobicentsCluster mobicentsCluster;
/**
* @param replicatedSessionDataSource
*/
public ShReplicatedSessionDataFactory(ISessionDatasource replicatedSessionDataSource) { // Is this ok?
super();
this.replicatedSessionDataSource = (ReplicatedSessionDatasource) replicatedSessionDataSource;
this.mobicentsCluster = this.replicatedSessionDataSource.getMobicentsCluster();
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.IAppSessionDataFactory#getAppSessionData (java.lang.Class, java.lang.String)
*/
@Override
public IShSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
if (clazz.equals(ClientShSession.class)) {
ShClientSessionDataReplicatedImpl data = new ShClientSessionDataReplicatedImpl(sessionId, this.mobicentsCluster);
return data;
}
else if (clazz.equals(ServerShSession.class)) {
ShServerSessionDataReplicatedImpl data = new ShServerSessionDataReplicatedImpl(sessionId, this.mobicentsCluster);
return data;
}
throw new IllegalArgumentException();
}
}
| 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.diameter.impl.ha.common.cca;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.cca.ClientCCASession;
import org.jdiameter.api.cca.ServerCCASession;
import org.jdiameter.common.api.app.IAppSessionDataFactory;
import org.jdiameter.common.api.app.cca.ICCASessionData;
import org.jdiameter.common.api.data.ISessionDatasource;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.client.cca.ClientCCASessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
import org.mobicents.diameter.impl.ha.server.cca.ServerCCASessionDataReplicatedImpl;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class CCAReplicatedSessionDataFactory implements IAppSessionDataFactory<ICCASessionData> {
private ReplicatedSessionDatasource replicatedSessionDataSource;
private MobicentsCluster mobicentsCluster;
/**
* @param replicatedSessionDataSource
*/
public CCAReplicatedSessionDataFactory(ISessionDatasource replicatedSessionDataSource) { // Is this ok?
super();
this.replicatedSessionDataSource = (ReplicatedSessionDatasource) replicatedSessionDataSource;
this.mobicentsCluster = this.replicatedSessionDataSource.getMobicentsCluster();
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.IAppSessionDataFactory#getAppSessionData(java.lang.Class, java.lang.String)
*/
@Override
public ICCASessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
if (clazz.equals(ClientCCASession.class)) {
ClientCCASessionDataReplicatedImpl data = new ClientCCASessionDataReplicatedImpl(sessionId, this.mobicentsCluster, this.replicatedSessionDataSource.getContainer());
return data;
}
else if (clazz.equals(ServerCCASession.class)) {
ServerCCASessionDataReplicatedImpl data = new ServerCCASessionDataReplicatedImpl(sessionId, this.mobicentsCluster);
return data;
}
throw new IllegalArgumentException();
}
}
| 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.diameter.impl.ha.common.cxdx;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.cxdx.ClientCxDxSession;
import org.jdiameter.api.cxdx.ServerCxDxSession;
import org.jdiameter.common.api.app.IAppSessionDataFactory;
import org.jdiameter.common.api.app.cxdx.ICxDxSessionData;
import org.jdiameter.common.api.data.ISessionDatasource;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.client.cxdx.ClientCxDxSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
import org.mobicents.diameter.impl.ha.server.cxdx.ServerCxDxSessionDataReplicatedImpl;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class CxDxReplicatedSessionDataFactory implements IAppSessionDataFactory<ICxDxSessionData> {
private ReplicatedSessionDatasource replicatedSessionDataSource;
private MobicentsCluster mobicentsCluster;
/**
* @param replicatedSessionDataSource
*/
public CxDxReplicatedSessionDataFactory(ISessionDatasource replicatedSessionDataSource) { // Is this ok?
super();
this.replicatedSessionDataSource = (ReplicatedSessionDatasource) replicatedSessionDataSource;
this.mobicentsCluster = this.replicatedSessionDataSource.getMobicentsCluster();
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.IAppSessionDataFactory#getAppSessionData(java.lang.Class, java.lang.String)
*/
@Override
public ICxDxSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
if (clazz.equals(ClientCxDxSession.class)) {
ClientCxDxSessionDataReplicatedImpl data = new ClientCxDxSessionDataReplicatedImpl(sessionId, this.mobicentsCluster, this.replicatedSessionDataSource.getContainer());
return data;
}
else if (clazz.equals(ServerCxDxSession.class)) {
ServerCxDxSessionDataReplicatedImpl data = new ServerCxDxSessionDataReplicatedImpl(sessionId, this.mobicentsCluster, this.replicatedSessionDataSource.getContainer());
return data;
}
throw new IllegalArgumentException();
}
}
| 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.diameter.impl.ha.common.cxdx;
import java.io.Serializable;
import java.nio.ByteBuffer;
import org.jboss.cache.Fqn;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.Request;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.parser.IMessageParser;
import org.jdiameter.client.api.parser.ParseException;
import org.jdiameter.common.api.app.cxdx.CxDxSessionState;
import org.jdiameter.common.api.app.cxdx.ICxDxSessionData;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.common.AppSessionDataReplicatedImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public abstract class CxDxSessionDataReplicatedImpl extends AppSessionDataReplicatedImpl implements ICxDxSessionData {
private static final Logger logger = LoggerFactory.getLogger(CxDxSessionDataReplicatedImpl.class);
private static final String STATE = "STATE";
private static final String BUFFER = "BUFFER";
private static final String TS_TIMERID = "TS_TIMERID";
private IMessageParser messageParser;
/**
* @param nodeFqn
* @param mobicentsCluster
* @param iface
*/
public CxDxSessionDataReplicatedImpl(Fqn<?> nodeFqn, MobicentsCluster mobicentsCluster, IContainer container) {
super(nodeFqn, mobicentsCluster);
this.messageParser = container.getAssemblerFacility().getComponentInstance(IMessageParser.class);
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.cxdx.ICxDxSessionData#setCxDxSessionState(org.jdiameter.common.api.app.cxdx.CxDxSessionState)
*/
@Override
public void setCxDxSessionState(CxDxSessionState state) {
if (exists()) {
getNode().put(STATE, state);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.cxdx.ICxDxSessionData#getCxDxSessionState()
*/
@Override
public CxDxSessionState getCxDxSessionState() {
if (exists()) {
return (CxDxSessionState) getNode().get(STATE);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.cxdx.ICxDxSessionData#getTsTimerId()
*/
@Override
public Serializable getTsTimerId() {
if (exists()) {
return (Serializable) getNode().get(TS_TIMERID);
}
else {
throw new IllegalStateException();
}
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.cxdx.ICxDxSessionData#setTsTimerId(java.io.Serializable)
*/
@Override
public void setTsTimerId(Serializable tid) {
if (exists()) {
getNode().put(TS_TIMERID, tid);
}
else {
throw new IllegalStateException();
}
}
public Request getBuffer() {
byte[] data = (byte[]) getNode().get(BUFFER);
if (data != null) {
try {
return (Request) this.messageParser.createMessage(ByteBuffer.wrap(data));
}
catch (AvpDataException e) {
logger.error("Unable to recreate message from buffer.");
return null;
}
}
else {
return null;
}
}
public void setBuffer(Request buffer) {
if (buffer != null) {
try {
byte[] data = this.messageParser.encodeMessage((IMessage) buffer).array();
getNode().put(BUFFER, data);
}
catch (ParseException e) {
logger.error("Unable to encode message to buffer.");
}
}
else {
getNode().remove(BUFFER);
}
}
}
| 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.diameter.impl.ha.common.gx;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.gx.ClientGxSession;
import org.jdiameter.api.gx.ServerGxSession;
import org.jdiameter.common.api.app.IAppSessionDataFactory;
import org.jdiameter.common.api.app.gx.IGxSessionData;
import org.jdiameter.common.api.data.ISessionDatasource;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.client.gx.ClientGxSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
import org.mobicents.diameter.impl.ha.server.gx.ServerGxSessionDataReplicatedImpl;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class GxReplicatedSessionDataFactory implements IAppSessionDataFactory<IGxSessionData> {
private ReplicatedSessionDatasource replicatedSessionDataSource;
private MobicentsCluster mobicentsCluster;
/**
* @param replicatedSessionDataSource
*/
public GxReplicatedSessionDataFactory(ISessionDatasource replicatedSessionDataSource) { // Is this ok?
super();
this.replicatedSessionDataSource = (ReplicatedSessionDatasource) replicatedSessionDataSource;
this.mobicentsCluster = this.replicatedSessionDataSource.getMobicentsCluster();
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.IAppSessionDataFactory#getAppSessionData(java.lang.Class, java.lang.String)
*/
@Override
public IGxSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
if (clazz.equals(ClientGxSession.class)) {
ClientGxSessionDataReplicatedImpl data = new ClientGxSessionDataReplicatedImpl(sessionId, this.mobicentsCluster, this.replicatedSessionDataSource.getContainer());
return data;
}
else if (clazz.equals(ServerGxSession.class)) {
ServerGxSessionDataReplicatedImpl data = new ServerGxSessionDataReplicatedImpl(sessionId, this.mobicentsCluster);
return data;
}
throw new IllegalArgumentException();
}
}
| 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.diameter.impl.ha.common.rx;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.rx.ClientRxSession;
import org.jdiameter.api.rx.ServerRxSession;
import org.jdiameter.common.api.app.IAppSessionDataFactory;
import org.jdiameter.common.api.app.rx.IRxSessionData;
import org.jdiameter.common.api.data.ISessionDatasource;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.client.rx.ClientRxSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
import org.mobicents.diameter.impl.ha.server.rx.ServerRxSessionDataReplicatedImpl;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class RxReplicatedSessionDataFactory implements IAppSessionDataFactory<IRxSessionData> {
private ReplicatedSessionDatasource replicatedSessionDataSource;
private MobicentsCluster mobicentsCluster;
/**
* @param replicatedSessionDataSource
*/
public RxReplicatedSessionDataFactory(ISessionDatasource replicatedSessionDataSource) { // Is this ok?
super();
this.replicatedSessionDataSource = (ReplicatedSessionDatasource) replicatedSessionDataSource;
this.mobicentsCluster = this.replicatedSessionDataSource.getMobicentsCluster();
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.IAppSessionDataFactory#getAppSessionData(java.lang.Class, java.lang.String)
*/
@Override
public IRxSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
if (clazz.equals(ClientRxSession.class)) {
ClientRxSessionDataReplicatedImpl data = new ClientRxSessionDataReplicatedImpl(sessionId, this.mobicentsCluster, this.replicatedSessionDataSource.getContainer());
return data;
}
else if (clazz.equals(ServerRxSession.class)) {
ServerRxSessionDataReplicatedImpl data = new ServerRxSessionDataReplicatedImpl(sessionId, this.mobicentsCluster);
return data;
}
throw new IllegalArgumentException();
}
}
| 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.diameter.impl.ha.common.auth;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.auth.ClientAuthSession;
import org.jdiameter.api.auth.ServerAuthSession;
import org.jdiameter.common.api.app.IAppSessionDataFactory;
import org.jdiameter.common.api.app.auth.IAuthSessionData;
import org.jdiameter.common.api.data.ISessionDatasource;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.client.auth.ClientAuthSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
import org.mobicents.diameter.impl.ha.server.auth.ServerAuthSessionDataReplicatedImpl;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class AuthReplicatedSessionDataFactory implements IAppSessionDataFactory<IAuthSessionData> {
private ReplicatedSessionDatasource replicatedSessionDataSource;
private MobicentsCluster mobicentsCluster;
/**
* @param replicatedSessionDataSource
*/
public AuthReplicatedSessionDataFactory(ISessionDatasource replicatedSessionDataSource) { // Is this ok?
super();
this.replicatedSessionDataSource = (ReplicatedSessionDatasource) replicatedSessionDataSource;
this.mobicentsCluster = this.replicatedSessionDataSource.getMobicentsCluster();
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.IAppSessionDataFactory#getAppSessionData(java.lang.Class, java.lang.String)
*/
@Override
public IAuthSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
if (clazz.equals(ClientAuthSession.class)) {
ClientAuthSessionDataReplicatedImpl data = new ClientAuthSessionDataReplicatedImpl(sessionId, this.mobicentsCluster);
return data;
}
else if (clazz.equals(ServerAuthSession.class)) {
ServerAuthSessionDataReplicatedImpl data = new ServerAuthSessionDataReplicatedImpl(sessionId, this.mobicentsCluster);
return data;
}
throw new IllegalArgumentException();
}
}
| 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.diameter.impl.ha.common.acc;
import org.jdiameter.api.acc.ClientAccSession;
import org.jdiameter.api.acc.ServerAccSession;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.common.api.app.IAppSessionDataFactory;
import org.jdiameter.common.api.app.acc.IAccSessionData;
import org.jdiameter.common.api.data.ISessionDatasource;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.client.acc.ClientAccSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
import org.mobicents.diameter.impl.ha.server.acc.ServerAccSessionDataReplicatedImpl;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class AccReplicatedSessionDataFactory implements IAppSessionDataFactory<IAccSessionData> {
private ReplicatedSessionDatasource replicatedSessionDataSource;
private MobicentsCluster mobicentsCluster;
/**
* @param replicatedSessionDataSource
*/
public AccReplicatedSessionDataFactory(ISessionDatasource replicatedSessionDataSource) { // Is this ok?
super();
this.replicatedSessionDataSource = (ReplicatedSessionDatasource) replicatedSessionDataSource;
this.mobicentsCluster = this.replicatedSessionDataSource.getMobicentsCluster();
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.IAppSessionDataFactory#getAppSessionData(java.lang.Class, java.lang.String)
*/
@Override
public IAccSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
if (clazz.equals(ClientAccSession.class)) {
ClientAccSessionDataReplicatedImpl data = new ClientAccSessionDataReplicatedImpl(sessionId, this.mobicentsCluster, this.replicatedSessionDataSource.getContainer());
return data;
}
else if (clazz.equals(ServerAccSession.class)) {
ServerAccSessionDataReplicatedImpl data = new ServerAccSessionDataReplicatedImpl(sessionId, this.mobicentsCluster);
return data;
}
throw new IllegalArgumentException();
}
}
| 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.diameter.impl.ha.common;
import org.jboss.cache.Fqn;
import org.jboss.cache.Node;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.common.api.app.IAppSessionData;
import org.mobicents.cache.MobicentsCache;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.cluster.cache.ClusteredCacheData;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class AppSessionDataReplicatedImpl extends ClusteredCacheData implements IAppSessionData {
protected static final String SID = "SID";
protected static final String APID = "APID";
protected static final String SIFACE = "SIFACE";
/**
* @param nodeFqn
* @param mobicentsCluster
*/
public AppSessionDataReplicatedImpl(Fqn<?> nodeFqn, MobicentsCluster mobicentsCluster) {
super(nodeFqn, mobicentsCluster);
}
public AppSessionDataReplicatedImpl(String sessionId, MobicentsCluster mobicentsCluster) {
this(Fqn.fromRelativeElements(ReplicatedSessionDatasource.SESSIONS_FQN, sessionId), mobicentsCluster);
}
public static void setAppSessionIface(ClusteredCacheData ccd, Class<? extends AppSession> iface) {
Node n = ccd.getMobicentsCache().getJBossCache().getNode(ccd.getNodeFqn());
n.put(SIFACE, iface);
}
public static Class<? extends AppSession> getAppSessionIface(MobicentsCache mcCache, String sessionId) {
Node n = mcCache.getJBossCache().getNode(Fqn.fromRelativeElements(ReplicatedSessionDatasource.SESSIONS_FQN, sessionId));
return (Class<AppSession>) n.get(SIFACE);
}
@Override
public String getSessionId() {
return (String) super.getNodeFqn().getLastElement();
}
@Override
public void setApplicationId(ApplicationId applicationId) {
if (exists()) {
getNode().put(APID, applicationId);
}
else {
throw new IllegalStateException();
}
}
@Override
public ApplicationId getApplicationId() {
if (exists()) {
return (ApplicationId) getNode().get(APID);
}
else {
throw new IllegalStateException();
}
}
// Some util methods for handling primitives
protected boolean toPrimitive(Boolean b, boolean _default) {
return b == null ? _default : b;
}
protected int toPrimitive(Integer i) {
return i == null ? NON_INITIALIZED : i;
}
protected long toPrimitive(Long l) {
return l == null ? NON_INITIALIZED : l;
}
}
| 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.diameter.impl.ha.common.ro;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.ro.ClientRoSession;
import org.jdiameter.api.ro.ServerRoSession;
import org.jdiameter.common.api.app.IAppSessionDataFactory;
import org.jdiameter.common.api.app.ro.IRoSessionData;
import org.jdiameter.common.api.data.ISessionDatasource;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.client.ro.ClientRoSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
import org.mobicents.diameter.impl.ha.server.ro.ServerRoSessionDataReplicatedImpl;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class RoReplicatedSessionDataFactory implements IAppSessionDataFactory<IRoSessionData> {
private ReplicatedSessionDatasource replicatedSessionDataSource;
private MobicentsCluster mobicentsCluster;
/**
* @param replicatedSessionDataSource
*/
public RoReplicatedSessionDataFactory(ISessionDatasource replicatedSessionDataSource) { // Is this ok?
super();
this.replicatedSessionDataSource = (ReplicatedSessionDatasource) replicatedSessionDataSource;
this.mobicentsCluster = this.replicatedSessionDataSource.getMobicentsCluster();
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.IAppSessionDataFactory#getAppSessionData(java.lang.Class, java.lang.String)
*/
@Override
public IRoSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
if (clazz.equals(ClientRoSession.class)) {
ClientRoSessionDataReplicatedImpl data = new ClientRoSessionDataReplicatedImpl(sessionId, this.mobicentsCluster, this.replicatedSessionDataSource.getContainer());
return data;
}
else if (clazz.equals(ServerRoSession.class)) {
ServerRoSessionDataReplicatedImpl data = new ServerRoSessionDataReplicatedImpl(sessionId, this.mobicentsCluster);
return data;
}
throw new IllegalArgumentException();
}
}
| 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.diameter.impl.ha.common.rf;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.rf.ClientRfSession;
import org.jdiameter.api.rf.ServerRfSession;
import org.jdiameter.common.api.app.IAppSessionDataFactory;
import org.jdiameter.common.api.app.rf.IRfSessionData;
import org.jdiameter.common.api.data.ISessionDatasource;
import org.mobicents.cluster.MobicentsCluster;
import org.mobicents.diameter.impl.ha.client.rf.ClientRfSessionDataReplicatedImpl;
import org.mobicents.diameter.impl.ha.data.ReplicatedSessionDatasource;
import org.mobicents.diameter.impl.ha.server.rf.ServerRfSessionDataReplicatedImpl;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class RfReplicatedSessionDataFactory implements IAppSessionDataFactory<IRfSessionData> {
private ReplicatedSessionDatasource replicatedSessionDataSource;
private MobicentsCluster mobicentsCluster;
/**
* @param replicatedSessionDataSource
*/
public RfReplicatedSessionDataFactory(ISessionDatasource replicatedSessionDataSource) { // Is this ok?
super();
this.replicatedSessionDataSource = (ReplicatedSessionDatasource) replicatedSessionDataSource;
this.mobicentsCluster = this.replicatedSessionDataSource.getMobicentsCluster();
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.common.api.app.IAppSessionDataFactory#getAppSessionData(java.lang.Class, java.lang.String)
*/
@Override
public IRfSessionData getAppSessionData(Class<? extends AppSession> clazz, String sessionId) {
if (clazz.equals(ClientRfSession.class)) {
ClientRfSessionDataReplicatedImpl data = new ClientRfSessionDataReplicatedImpl(sessionId, this.mobicentsCluster, this.replicatedSessionDataSource.getContainer());
return data;
}
else if (clazz.equals(ServerRfSession.class)) {
ServerRfSessionDataReplicatedImpl data = new ServerRfSessionDataReplicatedImpl(sessionId, this.mobicentsCluster);
return data;
}
throw new IllegalArgumentException();
}
}
| 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.diameter.api.ha.data;
import org.jdiameter.api.BaseSession;
import org.jdiameter.api.NetworkReqListener;
/**
* Interface for Session Clustered Data.
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public interface ISessionClusteredData {
public void setSession(BaseSession s);
public BaseSession getSession();
public NetworkReqListener getSessionListener();
public void setSessionListener(NetworkReqListener lst);
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.jdiameter.client.impl.annotation;
import org.jdiameter.api.annotation.Getter;
import org.jdiameter.api.annotation.Setter;
/**
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public abstract class Value<T> {
protected T value;
@Setter
public Value(T value) {
this.value = value;
}
@Getter
public T get() {
return value;
}
@Override
public String toString() {
return "Value{" + "value=" + value + "}";
}
} | Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.jdiameter.client.impl.annotation.internal;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class ConstructorInfo {
private Storage storage;
private Constructor constr;
private ClassInfo classInfo;
private Collection<Annotation> annotationsCache;
private Map<Class<?>, Annotation> annotationStorage;
public ConstructorInfo(Storage storage, ClassInfo classInfo, Constructor constr) {
this.storage = storage;
this.classInfo = classInfo;
this.constr = constr;
}
public Constructor getConstructor() {
return constr;
}
public ClassInfo getClassInfo() {
return classInfo;
}
public Collection<Annotation> getAnnotations() {
return annotationsCache == null ? (annotationsCache = getAnnotationStorage().values()) : annotationsCache;
}
private Map<Class<?>, Annotation> getAnnotationStorage(){
if (annotationStorage == null) {
annotationStorage = new ConcurrentHashMap<Class<?>, Annotation>();
Class<?> parent = getClassInfo().getAttachedClass().getSuperclass();
if (parent != null) {
addAnnotations(storage.getClassInfo(parent).getConstructorInfo(getConstructor().getParameterTypes()));
}
for (Class<?> i : getClassInfo().getAttachedClass().getInterfaces()) {
addAnnotations(storage.getClassInfo(i).getConstructorInfo(getConstructor().getParameterTypes()));
}
for (Annotation a : getConstructor().getDeclaredAnnotations()) {
annotationStorage.put(a.getClass().getInterfaces()[0], a);
}
}
return annotationStorage;
}
private void addAnnotations(ConstructorInfo constr) {
if (constr != null) {
for (Annotation annotation : constr.getAnnotations()) {
if (annotation != null) {
for (Class<?> _interface : annotation.getClass().getInterfaces()) {
annotationStorage.put( _interface, annotation ); // [0]
}
}
}
}
}
public <T> T getAnnotation(Class<?> annotation) {
for (Annotation a : getAnnotations()) {
if (a.annotationType() == annotation) {
return (T) a;
}
}
return null;
}
} | Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.jdiameter.client.impl.annotation.internal;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class MethodInfo {
private Storage storage;
private Method method;
private ClassInfo classInfo;
private Collection<Annotation> annotationsCache;
private Map<Class<?>, Annotation> annotationStorage;
public MethodInfo(Storage storage, ClassInfo classInfo, Method method) {
this.storage = storage;
this.classInfo = classInfo;
this.method = method;
}
public Method getMethod() {
return method;
}
public ClassInfo getClassInfo() {
return classInfo;
}
public Collection<Annotation> getAnnotations() {
return annotationsCache == null ? (annotationsCache = getAnnotationStorage().values()) : annotationsCache;
}
public <T> T getAnnotation(Class<?> annotation) {
for (Annotation a : getAnnotations()) {
if (a.annotationType() == annotation) {
return (T) a;
}
}
return null;
}
private Map<Class<?>, Annotation> getAnnotationStorage(){
if (annotationStorage == null) {
annotationStorage = new ConcurrentHashMap<Class<?>, Annotation>();
Class<?> parent = getClassInfo().getAttachedClass().getSuperclass();
if (parent != null) {
addAnnotations(storage.getClassInfo(parent).getMethodInfo(getMethod().getName(), getMethod().getParameterTypes()));
}
for (Class<?> i : getClassInfo().getAttachedClass().getInterfaces()) {
addAnnotations(storage.getClassInfo(i).getMethodInfo(getMethod().getName(),getMethod().getParameterTypes()));
}
for (Annotation a : getMethod().getDeclaredAnnotations()) {
annotationStorage.put(a.getClass().getInterfaces()[0], a);
}
}
return annotationStorage;
}
private void addAnnotations(MethodInfo method) {
if (method != null) {
for (Annotation annotation : method.getAnnotations()) {
if (annotation != null) {
for (Class<?> _interface : annotation.getClass().getInterfaces()) {
annotationStorage.put( _interface, annotation ); // [0]
}
}
}
}
}
} | Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.jdiameter.client.impl.annotation.internal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class Storage {
private Map<Class<?>, ClassInfo> annotations = new ConcurrentHashMap<Class<?>, ClassInfo>();
public synchronized final ClassInfo getClassInfo(Class<?> _class){
ClassInfo info = annotations.get(_class);
if (info == null) {
info = new ClassInfo(this, _class);
annotations.put(_class, info);
}
return info;
}
public synchronized final void clear() {
annotations.clear();
}
} | Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.jdiameter.client.impl.annotation.internal;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class ClassInfo {
private Storage storage;
private Class<?> _class;
private Map<Class<?>, Annotation> annotations;
private Map<Method, MethodInfo> methods;
private Map<Constructor, ConstructorInfo> constructors;
private Collection<Annotation> classCache;
private Collection<MethodInfo> methodCache;
private Collection<ConstructorInfo> constructorCache;
public ClassInfo (Storage storage, Class<?> _class){
this.storage = storage;
this._class = _class;
}
public Class<?> getAttachedClass() {
return _class;
}
public Collection<Annotation> getAnnotations() {
if (classCache == null) {
if (annotations == null) {
annotations = new ConcurrentHashMap<Class<?>, Annotation>();
final Class<?> parent = getAttachedClass().getSuperclass();
if (parent != null) {
addAnnotations(parent);
}
for (Class<?> i : getAttachedClass().getInterfaces()) {
addAnnotations(i);
}
for (Annotation a : getAttachedClass().getDeclaredAnnotations()) {
annotations.put(a.getClass().getInterfaces()[0], a);
}
}
classCache = annotations.values();
}
return classCache;
}
public <T> T getAnnotation(Class<?> annotation) {
for (Annotation a : getAnnotations()) {
if (a.annotationType() == annotation) {
return (T) a;
}
}
return null;
}
private void addAnnotations(Class<?> _class) {
for (Annotation annotation : storage.getClassInfo(_class).getAnnotations()) {
if (annotation != null) {
for (Class<?> _interface : annotation.getClass().getInterfaces()) {
annotations.put(_interface, annotation);
}
}
}
}
public MethodInfo getMethodInfo(String methodName, Class<?>... args) {
try {
return getMethodInfo( getAttachedClass().getMethod(methodName, args) );
}
catch (Exception e) {
return null;
}
}
public ConstructorInfo getConstructorInfo(Class<?>... args) {
try {
return getConstructorInfo( getAttachedClass().getConstructor(args) );
}
catch (Exception e1) {
// may be generic
try {
return getConstructorInfo( getAttachedClass().getConstructor(Object.class) );
}
catch (Exception e2) {}
return null;
}
}
public MethodInfo getMethodInfo(Method method) {
return getMethodMap().get(method);
}
public ConstructorInfo getConstructorInfo(Constructor constr) {
return getConstructorMap().get(constr);
}
public Collection<MethodInfo> getMethodsInfo() {
return methodCache == null ? (methodCache = getMethodMap().values()) : methodCache;
}
public Collection<ConstructorInfo> getConstructorsInfo() {
return constructorCache == null ? (constructorCache = getConstructorMap().values()) : constructorCache;
}
private Map<Method, MethodInfo> getMethodMap(){
if (methods == null) {
methods = new ConcurrentHashMap<Method, MethodInfo>();
for (Method method : getAttachedClass().getMethods()) {
methods.put(method, new MethodInfo(storage, this, method));
}
}
return methods;
}
private Map<Constructor, ConstructorInfo> getConstructorMap(){
if (constructors == null) {
constructors = new ConcurrentHashMap<Constructor, ConstructorInfo>();
for (Constructor constr : getAttachedClass().getConstructors()) {
constructors.put(constr, new ConstructorInfo(storage, this, constr));
}
}
return constructors;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.jdiameter.client.impl.annotation;
/**
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class UnknownAvp extends Value<byte[]> {
private int code;
boolean m,v,p;
private long vendorId;
public UnknownAvp(int code, boolean m, boolean v, boolean p, long vendorId, byte[] value) {
super(value);
this.code = code;
this.m = m;
this.v = v;
this.p = p;
this.vendorId = vendorId;
}
public int getCode() {
return code;
}
public boolean isMandatory() {
return m;
}
public boolean isVendorSpecific() {
return v;
}
public long getVendorId() {
return vendorId;
}
public boolean isProxiable() {
return p;
}
} | Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.jdiameter.client.impl.annotation;
import org.jdiameter.api.*;
import org.jdiameter.api.annotation.*;
import org.jdiameter.client.impl.annotation.internal.ClassInfo;
import org.jdiameter.client.impl.annotation.internal.ConstructorInfo;
import org.jdiameter.client.impl.annotation.internal.MethodInfo;
import org.jdiameter.client.impl.annotation.internal.Storage;
import org.jdiameter.client.impl.RawSessionImpl;
import org.jdiameter.client.api.annotation.IRecoder;
import org.jdiameter.client.api.annotation.RecoderException;
import org.jdiameter.client.api.IMessage;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
/**
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class Recoder implements IRecoder {
// TODO full min/max/position constrains and optimization (caching)
private static final Logger log = LoggerFactory.getLogger(Recoder.class);
private Storage storage = new Storage();
private final RawSessionImpl rawSession;
private final MetaData metaData;
public Recoder(SessionFactory factory, MetaData metaData) {
this.metaData = metaData;
try {
this.rawSession = (RawSessionImpl) factory.getNewRawSession();
} catch (InternalException e) {
throw new IllegalArgumentException(e);
}
}
// =======================================================================================
//@Override
public Message encodeToRequest(Object yourDomainMessageObject, Avp... additionalAvp) throws RecoderException {
return encode(yourDomainMessageObject, null, 0, additionalAvp);
}
//@Override
public Message encodeToAnswer(Object yourDomainMessageObject, Request request, long resultCode) throws RecoderException {
return encode(yourDomainMessageObject, request, resultCode);
}
public Message encode(Object yourDomainMessageObject, Request request, long resultCode, Avp... addAvp) throws RecoderException {
IMessage message = null;
ClassInfo classInfo = storage.getClassInfo(yourDomainMessageObject.getClass());
CommandDscr commandDscr = classInfo.getAnnotation(CommandDscr.class);
if (commandDscr != null) {
// Get command parameters
if (request == null) {
message = (IMessage) rawSession.createMessage(commandDscr.code(), ApplicationId.createByAccAppId(0));
message.setRequest(true);
message.getAvps().addAvp(addAvp);
try {
if (message.getAvps().getAvp(Avp.AUTH_APPLICATION_ID) != null) {
message.setHeaderApplicationId(message.getAvps().getAvp(Avp.AUTH_APPLICATION_ID).getUnsigned32());
}
else if (message.getAvps().getAvp(Avp.ACCT_APPLICATION_ID) != null) {
message.setHeaderApplicationId(message.getAvps().getAvp(Avp.ACCT_APPLICATION_ID).getUnsigned32());
}
else if (message.getAvps().getAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID) != null) {
message.setHeaderApplicationId(message.getAvps().getAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID).
getGrouped().getAvp(Avp.VENDOR_ID).getUnsigned32());
}
} catch (Exception exc) {
throw new RecoderException(exc);
}
if (message.getAvps().getAvp(Avp.ORIGIN_HOST) == null) {
message.getAvps().addAvp(Avp.ORIGIN_HOST, metaData.getLocalPeer().getUri().getFQDN(), true, false, true);
}
if (message.getAvps().getAvp(Avp.ORIGIN_REALM) == null) {
message.getAvps().addAvp(Avp.ORIGIN_REALM, metaData.getLocalPeer().getRealmName(), true, false, true);
}
} else {
message = (IMessage) request.createAnswer(resultCode);
}
for (CommandFlag f : commandDscr.flags()) {
switch (f) {
case E:
message.setError(true);
break;
case P:
message.setProxiable(true);
break;
case R:
message.setRequest(true);
break;
case T:
message.setReTransmitted(true);
break;
}
}
// Find top level avp in getter-annotation methods
Map<String, Object> chMap = getChildInstance(yourDomainMessageObject, classInfo, null);
// Fill
for (Child ch : commandDscr.childs()) {
fillChild(message.getAvps(), ch, chMap);
}
} else {
log.debug("Can not found annotation for object {}", yourDomainMessageObject);
}
return message;
}
private Map<String, Object> getChildInstance(Object yourDomainMessageObject, ClassInfo c, Map<String, Object> chMap)
throws RecoderException {
if (chMap == null)
chMap = new HashMap<String, Object>();
for (MethodInfo mi : c.getMethodsInfo()) {
if (mi.getAnnotation(Getter.class) != null) {
try {
Object value = mi.getMethod().invoke(yourDomainMessageObject);
if (value != null) {
Class mc = value.getClass().isArray() ? value.getClass().getComponentType() : value.getClass();
chMap.put(mc.getName(), value);
for (Class<?> i : mc.getInterfaces())
chMap.put(i.getName(), value);
}
} catch (IllegalAccessException e) {
throw new RecoderException(e);
} catch (InvocationTargetException e) {
throw new RecoderException(e);
}
}
}
return chMap;
}
private void fillChild(AvpSet as, Child ci, Map<String, Object> childs) throws RecoderException {
Object c = childs.get(ci.ref().getName());
if (c != null) {
ClassInfo cc = storage.getClassInfo(ci.ref());
AvpDscr ad = cc.getAnnotation(AvpDscr.class);
if (ad != null) {
boolean m = false, p = false;
// cast <=> getter for primitive
switch (ad.type()) {
case Integer32:
case Enumerated: {
for (AvpFlag f : ad.must())
if (AvpFlag.M.equals(f)) {
m = true;
}
else if (AvpFlag.P.equals(f)) {
p = true;
}
// find in getter
Collection<Integer> cv = getValue(c, Integer.class);
for (Integer v : cv)
as.addAvp(ad.code(), v, ad.vendorId(), m, p);
}
break;
case Unsigned32: {
for (AvpFlag f : ad.must())
if (AvpFlag.M.equals(f)) {
m = true;
}
else if (AvpFlag.P.equals(f)) {
p = true;
}
Collection<Long> cv = getValue(c, Long.class);
for (Long v : cv)
as.addAvp(ad.code(), v, ad.vendorId(), m, p, true);
}
break;
case Unsigned64:
case Integer64: {
for (AvpFlag f : ad.must())
if (AvpFlag.M.equals(f)) {
m = true;
}
else if (AvpFlag.P.equals(f)) {
p = true;
}
Collection<Long> cv = getValue(c, Long.class);
for (Long v : cv)
as.addAvp(ad.code(), v, ad.vendorId(), m, p);
}
break;
case Float32: {
for (AvpFlag f : ad.must())
if (AvpFlag.M.equals(f)) {
m = true;
}
else if (AvpFlag.P.equals(f)) {
p = true;
}
Collection<Float> cv = getValue(c, Float.class);
for (Float v : cv)
as.addAvp(ad.code(), v, ad.vendorId(), m, p);
}
break;
case Float64: {
for (AvpFlag f : ad.must())
if (AvpFlag.M.equals(f)) {
m = true;
}
else if (AvpFlag.P.equals(f)) {
p = true;
}
Collection<Double> cv = getValue(c, Double.class);
for (Double v : cv)
as.addAvp(ad.code(), v, ad.vendorId(), m, p);
}
break;
case OctetString:
case Address:
case Time:
case DiameterIdentity:
case DiameterURI:
case IPFilterRule:
case QoSFilterRule: {
for (AvpFlag f : ad.must())
if (AvpFlag.M.equals(f)) {
m = true;
}
else if (AvpFlag.P.equals(f)) {
p = true;
}
Collection<String> cv = getValue(c, String.class);
for (String v : cv)
as.addAvp(ad.code(), v, ad.vendorId(), m, p, true);
}
break;
case UTF8String: {
for (AvpFlag f : ad.must())
if (AvpFlag.M.equals(f)) {
m = true;
}
else if (AvpFlag.P.equals(f)) {
p = true;
}
Collection<String> cv = getValue(c, String.class);
for (String v : cv)
as.addAvp(ad.code(), v, ad.vendorId(), m, p, false);
}
break;
case Grouped: {
for (AvpFlag f : ad.must()) {
if (AvpFlag.M.equals(f)) {
m = true;
}
else if (AvpFlag.P.equals(f)) {
p = true;
}
}
Collection<Object> cv = new ArrayList<Object>();
if (c.getClass().isArray()) {
cv = Arrays.asList((Object[])c);
}
else {
cv.add(c);
}
for (Object cj : cv) {
AvpSet las = as.addGroupedAvp(ad.code(),ad.vendorId(), m, p);
Map<String, Object> lchilds = getChildInstance(cj, storage.getClassInfo(cj.getClass()), null);
for (Child lci : ad.childs()) {
fillChild(las, lci, lchilds);
}
}
}
break;
}
}
}
}
private <T> Collection<T> getValue(Object ic, Class<T> type) throws RecoderException {
Collection<T> rc = new ArrayList<T>();
Object[] xc = null;
if (ic.getClass().isArray())
xc = (Object[]) ic;
else
xc = new Object[] {ic};
for (Object c : xc) {
for (MethodInfo lm : storage.getClassInfo(c.getClass()).getMethodsInfo()) {
if (lm.getAnnotation(Getter.class) != null) {
try {
rc.add((T) lm.getMethod().invoke(c));
} catch (IllegalAccessException e) {
throw new RecoderException(e);
} catch (InvocationTargetException e) {
throw new RecoderException(e);
}
}
}
}
return rc;
}
// =======================================================================================
public <T> T decode(Message message, java.lang.Class<T> yourDomainMessageObject) throws RecoderException {
Object rc = null;
ClassInfo c = storage.getClassInfo(yourDomainMessageObject);
CommandDscr cd = c.getAnnotation(CommandDscr.class);
if (cd != null) {
try {
if (message.getCommandCode() != cd.code())
throw new IllegalArgumentException("Invalid message code " + message.getCommandCode());
if (message.getApplicationId() != 0 && message.getApplicationId() != cd.appId())
throw new IllegalArgumentException("Invalid Application-Id " + message.getApplicationId());
for (CommandFlag f : cd.flags()) {
switch (f) {
case E:
if (!message.isError())
throw new IllegalArgumentException("Flag e is not set");
break;
case P:
if (!message.isProxiable())
throw new IllegalArgumentException("Flag p is not set");
break;
case R:
if (!message.isRequest())
throw new IllegalArgumentException("Flag m is not set");
break;
case T:
if (!message.isReTransmitted())
throw new IllegalArgumentException("Flag t is not set");
break;
}
}
// Find max constructor + lost avp set by setters
int cacount = 0;
Constructor<?> cm = null;
Map<String, Class<?>> cmargs = new HashMap<String, Class<?>>();
for (ConstructorInfo ci : c.getConstructorsInfo()) {
if (ci.getAnnotation(Setter.class) != null) {
// check params - all params must have avp annotation
Class<?>[] params = ci.getConstructor().getParameterTypes();
boolean correct = true;
for (Class<?> j : params) {
if (j.isArray())
j = j.getComponentType();
if (storage.getClassInfo(j).getAnnotation(AvpDscr.class) == null) {
correct = false;
break;
}
}
if (!correct)
continue;
// find max args constructor
if (cacount < params.length) {
cacount = params.length;
cm = ci.getConstructor();
}
}
}
// fill cm args
List<Object> initargs = new ArrayList<Object>();
if (cm != null) {
for (Class<?> ac : cm.getParameterTypes()) {
Class<?> lac = ac.isArray() ? ac.getComponentType() : ac;
cmargs.put(lac.getName(), ac);
// Create params
initargs.add(createChildByAvp(findChildDscr(cd.childs(), ac), ac, message.getAvps()));
}
// Create instance class
rc = cm.newInstance(initargs.toArray());
} else {
rc = yourDomainMessageObject.newInstance();
}
//
for (MethodInfo mi : c.getMethodsInfo()) {
if (mi.getAnnotation(Setter.class) != null) {
Class<?>[] pt = mi.getMethod().getParameterTypes();
if (pt.length == 1 && storage.getClassInfo(pt[0]).getAnnotation(AvpDscr.class) != null) {
Class<?> ptc = pt[0].isArray() ? pt[0].getComponentType() : pt[0];
if (!cmargs.containsKey(ptc.getName())) {
cmargs.put(ptc.getName(), ptc);
mi.getMethod().invoke(rc, createChildByAvp(findChildDscr(cd.childs(), pt[0]), pt[0], message.getAvps()));
}
}
}
}
// Fill undefined avp
setUndefinedAvp(message.getAvps(), rc, c, cmargs);
} catch (InstantiationException e) {
throw new RecoderException(e);
} catch (InvocationTargetException e) {
throw new RecoderException(e);
} catch (IllegalAccessException e) {
throw new RecoderException(e);
}
}
return (T) rc;
}
private void setUndefinedAvp(AvpSet set, Object rc, ClassInfo c, Map<String, Class<?>> cmargs) throws RecoderException {
try {
for (MethodInfo mi : c.getMethodsInfo()) {
Setter s = mi.getAnnotation(Setter.class);
if (s != null && Setter.Type.UNDEFINED.equals(s.value())) {
Map<Integer, Integer> known = new HashMap<Integer, Integer>();
for (Class<?> argc : cmargs.values()) {
AvpDscr argd = storage.getClassInfo((argc.isArray() ? argc.getComponentType() : argc)).getAnnotation(AvpDscr.class);
known.put(argd.code(), argd.code());
}
for (Avp a : set) {
if (!known.containsKey(a.getCode()))
mi.getMethod().invoke(rc, new UnknownAvp(a.getCode(), a.isMandatory(), a.isVendorId(), a.isEncrypted(), a.getVendorId(), a.getRaw()));
}
break;
}
}
} catch (IllegalAccessException e) {
throw new RecoderException(e);
} catch (InvocationTargetException e) {
throw new RecoderException(e);
} catch (AvpDataException e) {
throw new RecoderException(e);
}
}
private Child findChildDscr(Child[] childs, Class<?> m) {
for (Child c : childs) {
Class<?> t = c.ref();
m = m.isArray() ? m.getComponentType() : m;
if (m == t)
return c;
if (m.getSuperclass() == t)
return c;
for (Class<?> i : m.getInterfaces())
if (i == t)
return c;
}
return null;
}
private Object createChildByAvp(Child mInfo, Class<?> m, AvpSet parentSet) throws RecoderException {
Object rc;
AvpDscr ad = storage.getClassInfo((m.isArray() ? m.getComponentType() : m)).getAnnotation(AvpDscr.class);
Avp av = parentSet.getAvp(ad.code());
if (av != null) {
for (AvpFlag i : ad.must())
switch (i) {
case M:
if (!av.isMandatory()) throw new IllegalArgumentException("not set flag M");
break;
case V:
if (!av.isVendorId()) throw new IllegalArgumentException("not set flag V");
break;
case P:
if (!av.isEncrypted()) throw new IllegalArgumentException("not set flag P");
break;
}
} else {
if (mInfo.min() > 0)
throw new IllegalArgumentException("Avp " + ad.code() + " is mandatory");
}
if (AvpType.Grouped.equals(ad.type())) {
if (m.isArray()) {
Class<?> arrayClass = m.getComponentType();
AvpSet as = parentSet.getAvps(ad.code());
Object[] array = (Object[]) java.lang.reflect.Array.newInstance(arrayClass, as.size());
for (int ii = 0; ii < array.length; ii++) {
array[ii] = newInstanceGroupedAvp(arrayClass, ad, as.getAvpByIndex(ii));
}
rc = array;
} else {
rc = newInstanceGroupedAvp(m, ad, parentSet.getAvp(ad.code()));
}
} else {
if (m.isArray()) {
Class<?> arrayClass = m.getComponentType();
AvpSet as = parentSet.getAvps(ad.code());
Object[] array = (Object[]) java.lang.reflect.Array.newInstance(arrayClass, as.size());
for (int ii = 0; ii < array.length; ii++) {
array[ii] = newInstanceSimpleAvp(arrayClass, ad, as.getAvpByIndex(ii));
}
rc = array;
} else {
rc = newInstanceSimpleAvp(m, ad, parentSet.getAvp(ad.code()));
}
}
// =========
return rc;
}
private Object newInstanceGroupedAvp(Class<?> m, AvpDscr ad, Avp avp) throws RecoderException {
Object rc;
int cacount = 0;
ClassInfo c = storage.getClassInfo(m);
Constructor<?> cm = null;
Map<String, Class<?>> cmargs = new HashMap<String, Class<?>>();
for (ConstructorInfo ci : c.getConstructorsInfo()) {
if (ci.getAnnotation(Setter.class) != null) {
// check params - all params must have avp annotation
Class<?>[] params = ci.getConstructor().getParameterTypes();
boolean correct = true;
for (Class<?> j : params) {
if (j.isArray())
j = j.getComponentType();
if (storage.getClassInfo(j).getAnnotation(AvpDscr.class) == null) {
correct = false;
break;
}
}
if (!correct)
continue;
// find max args constructor
if (cacount < params.length) {
cacount = params.length;
cm = ci.getConstructor();
}
}
}
// fill cm args
try {
List<Object> initargs = new ArrayList<Object>();
if (cm != null) {
for (Class<?> ac : cm.getParameterTypes()) {
Class<?> lac = ac.isArray() ? ac.getComponentType() : ac;
cmargs.put(lac.getName(), ac);
// Create params
initargs.add(createChildByAvp(findChildDscr(ad.childs(), ac), ac, avp.getGrouped()));
}
// Create instance class
rc = cm.newInstance(initargs.toArray());
} else {
rc = m.newInstance();
}
//
for (MethodInfo mi : c.getMethodsInfo()) {
if (mi.getAnnotation(Setter.class) != null) {
Class<?>[] pt = mi.getMethod().getParameterTypes();
if (pt.length == 1 && storage.getClassInfo(pt[0]).getAnnotation(AvpDscr.class) != null) {
Class<?> ptc = pt[0].isArray() ? pt[0].getComponentType() : pt[0];
if (!cmargs.containsKey(ptc.getName())) {
cmargs.put(ptc.getName(), ptc);
mi.getMethod().invoke(rc, createChildByAvp(findChildDscr(ad.childs(), pt[0]), pt[0], avp.getGrouped()));
}
}
}
}
// Fill undefined child
setUndefinedAvp(avp.getGrouped(), rc, c, cmargs);
} catch (InstantiationException e) {
throw new RecoderException(e);
} catch (InvocationTargetException e) {
throw new RecoderException(e);
} catch (AvpDataException e) {
throw new RecoderException(e);
} catch (IllegalAccessException e) {
throw new RecoderException(e);
}
return rc;
}
private Object newInstanceSimpleAvp(Class<?> m, AvpDscr ad, Avp avp) {
Object rc = null;
if (avp == null) return null;
ClassInfo c = storage.getClassInfo(m);
try {
for (ConstructorInfo ci : c.getConstructorsInfo()) {
if (ci.getConstructor().getParameterTypes().length == 1 && ci.getAnnotation(Setter.class) != null) {
List<Object> args = new ArrayList<Object>();
if (ci.getConstructor().getParameterTypes()[0].isArray()) {
args.add(getValue(ad.type(), avp));
} else {
args.add(getValue(ad.type(), avp));
}
rc = ci.getConstructor().newInstance(args.toArray());
}
}
if (rc == null) {
rc = m.newInstance();
for (MethodInfo mi : c.getMethodsInfo()) {
if (mi.getAnnotation(Setter.class) != null) {
List<Object> args = new ArrayList<Object>();
if (mi.getMethod().getParameterTypes()[0].isArray()) {
args.add(getValue(ad.type(), avp));
} else {
args.add(getValue(ad.type(), avp));
}
mi.getMethod().invoke(rc, args);
}
}
}
} catch (InstantiationException e) {
throw new RecoderException(e);
} catch (InvocationTargetException e) {
throw new RecoderException(e);
} catch (AvpDataException e) {
throw new RecoderException(e);
} catch (IllegalAccessException e) {
throw new RecoderException(e);
}
return rc;
}
private Object getValue(AvpType type, Avp avp) throws AvpDataException {
switch (type) {
case Integer32:
case Enumerated:
return avp.getInteger32();
case Unsigned32:
return avp.getUnsigned32();
case Unsigned64:
case Integer64:
return avp.getInteger64();
case Float32:
return avp.getFloat32();
case Float64:
return avp.getFloat64();
case OctetString:
case Address:
case Time:
case DiameterIdentity:
case DiameterURI:
case IPFilterRule:
case QoSFilterRule:
return avp.getOctetString();
case UTF8String:
return avp.getUTF8String();
}
return null;
}
// =======================================================================================
} | Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.jdiameter.client.impl;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.RawSession;
import org.jdiameter.api.Session;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.client.api.StackState;
import org.jdiameter.client.impl.helpers.UIDGenerator;
import org.jdiameter.common.api.app.IAppSessionFactory;
import org.jdiameter.common.api.data.ISessionDatasource;
/**
* Implementation for {@link ISessionFactory}
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class SessionFactoryImpl implements ISessionFactory {
private IContainer stack;
@SuppressWarnings("rawtypes")
private Map<Class, IAppSessionFactory> appFactories = new ConcurrentHashMap<Class, IAppSessionFactory>();
private ISessionDatasource dataSource;
protected static UIDGenerator uid = new UIDGenerator();
public SessionFactoryImpl(IContainer stack) {
this.stack = stack;
this.dataSource = this.stack.getAssemblerFacility().getComponentInstance(ISessionDatasource.class);
}
public String getSessionId(String custom) {
long id = uid.nextLong();
long high32 = (id & 0xffffffff00000000L) >> 32;
long low32 = (id & 0xffffffffL);
StringBuilder sb = new StringBuilder();
sb.append(stack.getMetaData().getLocalPeer().getUri().getFQDN()).
append(";").append(high32).append(";").append(low32);
if(custom!=null)
{
//FIXME: add checks for not allowed chars?
sb.append(";").append(custom);
}
return sb.toString();
}
public String getSessionId() {
return this.getSessionId(null);
}
public RawSession getNewRawSession() throws InternalException {
if (stack.getState() == StackState.IDLE) {
throw new InternalException("Illegal state of stack");
}
return new RawSessionImpl(stack);
}
public Session getNewSession() throws InternalException {
if (stack.getState() == StackState.IDLE) {
throw new InternalException("Illegal state of stack");
}
// FIXME: store this! Properly handle in ISessiondata
SessionImpl session = new SessionImpl(stack);
this.dataSource.addSession(session);
return session;
}
public Session getNewSession(String sessionId) throws InternalException {
if (stack.getState() == StackState.IDLE) {
throw new InternalException("Illegal state of stack");
}
SessionImpl session = new SessionImpl(stack);
if (sessionId != null && sessionId.length() > 0) {
session.sessionId = sessionId;
}
// FIXME: store this! Properly handle in ISessiondata
this.dataSource.addSession(session);
return session;
}
@SuppressWarnings("unchecked")
public <T extends AppSession> T getNewAppSession(ApplicationId applicationId, Class<? extends AppSession> aClass) throws InternalException {
return (T) getNewAppSession(null, applicationId, aClass, new Object[0]);
}
@SuppressWarnings("unchecked")
public <T extends AppSession> T getNewAppSession(String sessionId, ApplicationId applicationId, Class<? extends AppSession> aClass) throws InternalException {
return (T) getNewAppSession(sessionId, applicationId,aClass, new Object[0]);
}
@SuppressWarnings("unchecked")
public <T extends AppSession> T getNewAppSession(String sessionId, ApplicationId applicationId, Class<? extends AppSession> aClass, Object... args) throws InternalException {
T session = null;
if (stack.getState() == StackState.IDLE)
throw new InternalException("Illegal state of stack");
if (appFactories.containsKey(aClass)) {
session = (T) ((IAppSessionFactory) appFactories.get(aClass)).getNewSession(sessionId, aClass, applicationId, args);
// FIXME: add check if it exists already!
//dataSource.addSession(session);
}
return session;
}
public void registerAppFacory(Class<? extends AppSession> sessionClass, IAppSessionFactory factory) {
appFactories.put(sessionClass, factory);
}
public void unRegisterAppFacory(Class<? extends AppSession> sessionClass) {
appFactories.remove(sessionClass);
}
/* (non-Javadoc)
* @see org.jdiameter.client.api.ISessionFactory#getAppSessionFactory(java.lang.Class)
*/
public IAppSessionFactory getAppSessionFactory(Class<? extends AppSession> sessionClass) {
return appFactories.get(sessionClass);
}
public IContainer getContainer() {
return stack;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.jdiameter.client.impl;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.validation.Dictionary;
import org.jdiameter.api.validation.ValidatorLevel;
import org.jdiameter.common.impl.validation.DictionaryImpl;
/**
* Util class. Makes it easier to access Dictionary instance as singleton.
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @since 1.5.4.0-build404
*/
public class DictionarySingleton {
private static Dictionary SINGLETON = DictionaryImpl.INSTANCE; // default
private DictionarySingleton() {
// defeat instantiation
}
public static Dictionary getDictionary() {
return SINGLETON;
}
static void init(String clazz, boolean validatorEnabled, ValidatorLevel validatorSendLevel, ValidatorLevel validatorReceiveLevel) throws InternalException {
try {
SINGLETON = (Dictionary) Class.forName(clazz).getField("INSTANCE").get(null);
SINGLETON.setEnabled(validatorEnabled);
SINGLETON.setSendLevel(validatorSendLevel);
SINGLETON.setReceiveLevel(validatorReceiveLevel);
}
catch (Exception e) {
throw new InternalException(e);
}
}
}
| 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.jdiameter.client.impl.app.sh;
import org.jdiameter.common.api.app.sh.IShSessionData;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public interface IShClientSessionData extends IShSessionData {
// Stateless
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.jdiameter.client.impl.app.sh;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.jdiameter.api.Answer;
import org.jdiameter.api.EventListener;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Message;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.app.AppEvent;
import org.jdiameter.api.app.StateEvent;
import org.jdiameter.api.sh.ClientShSession;
import org.jdiameter.api.sh.ClientShSessionListener;
import org.jdiameter.api.sh.events.ProfileUpdateRequest;
import org.jdiameter.api.sh.events.PushNotificationAnswer;
import org.jdiameter.api.sh.events.PushNotificationRequest;
import org.jdiameter.api.sh.events.SubscribeNotificationsRequest;
import org.jdiameter.api.sh.events.UserDataRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.common.api.app.sh.IShMessageFactory;
import org.jdiameter.common.impl.app.AppAnswerEventImpl;
import org.jdiameter.common.impl.app.AppRequestEventImpl;
import org.jdiameter.common.impl.app.sh.ProfileUpdateAnswerImpl;
import org.jdiameter.common.impl.app.sh.PushNotificationRequestImpl;
import org.jdiameter.common.impl.app.sh.ShSession;
import org.jdiameter.common.impl.app.sh.SubscribeNotificationsAnswerImpl;
import org.jdiameter.common.impl.app.sh.UserDataAnswerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Basic implementation of ShClientSession - can be one time - for UDR,PUR and
* constant for SNR-PNR pair, in case when SNA contains response code from range
* different than 2001-2004(success codes) user is responsible for maintaing
* state - releasing etc, same goes if result code is contained
* Experimental-Result AVP <br>
* If ShSession moves to ShSessionState.TERMINATED - it means that no further
* messages can be received via it and it should be discarded. <br>
* <br>
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ShClientSessionImpl extends ShSession implements ClientShSession, EventListener<Request, Answer>, NetworkReqListener {
private Logger logger = LoggerFactory.getLogger(ShClientSessionImpl.class);
// Session State Handling ---------------------------------------------------
protected Lock sendAndStateLock = new ReentrantLock();
// Factories and Listeners --------------------------------------------------
protected transient IShMessageFactory factory = null;
protected transient ClientShSessionListener listener;
protected IShClientSessionData sessionData;
public ShClientSessionImpl(IShClientSessionData sessionData, IShMessageFactory fct, ISessionFactory sf, ClientShSessionListener lst) {
super(sf,sessionData);
if (lst == null) {
throw new IllegalArgumentException("Listener can not be null");
}
if (fct.getApplicationId() < 0) {
throw new IllegalArgumentException("ApplicationId can not be less than zero");
}
this.listener = lst;
this.factory = fct;
this.sessionData = sessionData;
}
public Answer processRequest(Request request) {
RequestDelivery rd = new RequestDelivery();
rd.session = this;
rd.request = request;
super.scheduler.execute(rd);
return null;
}
@SuppressWarnings("unchecked")
public <E> E getState(Class<E> stateType) {
return null;
}
public boolean handleEvent(StateEvent event) throws InternalException, OverloadException {
try {
sendAndStateLock.lock();
Event localEvent = (Event) event;
// Do the delivery
switch ((Event.Type) localEvent.getType()) {
case RECEIVE_PUSH_NOTIFICATION_REQUEST:
listener.doPushNotificationRequestEvent(this, new PushNotificationRequestImpl( (Request) localEvent.getRequest().getMessage() ));
break;
case RECEIVE_PROFILE_UPDATE_ANSWER:
listener.doProfileUpdateAnswerEvent(this, null, new ProfileUpdateAnswerImpl( (Answer) localEvent.getAnswer().getMessage()));
break;
case RECEIVE_USER_DATA_ANSWER:
listener.doUserDataAnswerEvent(this, null, new UserDataAnswerImpl((Answer) localEvent.getAnswer().getMessage()));
break;
case RECEIVE_SUBSCRIBE_NOTIFICATIONS_ANSWER:
listener.doSubscribeNotificationsAnswerEvent(this, null, new SubscribeNotificationsAnswerImpl( (Answer) localEvent.getAnswer().getMessage()));
break;
case SEND_PROFILE_UPDATE_REQUEST:
case SEND_PUSH_NOTIFICATION_ANSWER:
case SEND_SUBSCRIBE_NOTIFICATIONS_REQUEST:
case SEND_USER_DATA_REQUEST:
Message m = null;
Object data = event.getData();
m = data instanceof AppEvent ? ((AppEvent)data).getMessage() : (Message) event.getData();
session.send(m, this);
break;
case TIMEOUT_EXPIRES:
// TODO Anything here?
break;
default:
logger.error("Wrong message type={} req={} ans={}", new Object[]{localEvent.getType(), localEvent.getRequest(), localEvent.getAnswer()});
}
}
catch (IllegalDiameterStateException idse) {
throw new InternalException(idse);
}
catch (RouteException re) {
throw new InternalException(re);
}
finally {
sendAndStateLock.unlock();
}
return true;
}
public void sendProfileUpdateRequest(ProfileUpdateRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_PROFILE_UPDATE_REQUEST, request, null);
}
public void sendPushNotificationAnswer(PushNotificationAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_PUSH_NOTIFICATION_ANSWER, null, answer);
}
public void sendSubscribeNotificationsRequest(SubscribeNotificationsRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_SUBSCRIBE_NOTIFICATIONS_REQUEST, request, null);
}
public void sendUserDataRequest(UserDataRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_USER_DATA_REQUEST, request, null);
}
protected void send(Event.Type type, AppEvent request, AppEvent answer) throws InternalException {
try {
sendAndStateLock.lock();
if (type != null) {
handleEvent(new Event(type, request, answer));
}
}
catch (Exception e) {
throw new InternalException(e);
}
finally {
sendAndStateLock.unlock();
}
}
public void receivedSuccessMessage(Request request, Answer answer) {
AnswerDelivery rd = new AnswerDelivery();
rd.session = this;
rd.request = request;
rd.answer = answer;
super.scheduler.execute(rd);
}
public void timeoutExpired(Request request) {
try {
if (request.getApplicationId() == factory.getApplicationId()) {
if (request.getCommandCode() == ProfileUpdateRequest.code) {
handleEvent(new Event(Event.Type.TIMEOUT_EXPIRES, factory.createProfileUpdateRequest(request), null));
return;
}
else if (request.getCommandCode() == UserDataRequest.code) {
handleEvent(new Event(Event.Type.TIMEOUT_EXPIRES, factory.createUserDataRequest(request), null));
return;
}
else if (request.getCommandCode() == SubscribeNotificationsRequest.code) {
handleEvent(new Event(Event.Type.TIMEOUT_EXPIRES, factory.createSubscribeNotificationsRequest(request), null));
return;
}
}
}
catch (Exception e) {
logger.debug("Failed to process timeout message", e);
}
}
public void release() {
if (isValid()) {
try {
sendAndStateLock.lock();
super.release();
}
catch (Exception e) {
logger.debug("Failed to release session", e);
}
finally {
sendAndStateLock.unlock();
}
}
else {
logger.debug("Trying to release an already invalid session, with Session ID '{}'", getSessionId());
}
}
public boolean isStateless() {
return true;
}
/* (non-Javadoc)
* @see org.jdiameter.common.impl.app.AppSessionImpl#isReplicable()
*/
@Override
public boolean isReplicable() {
return true;
}
@Override
public void onTimer(String timerName) {
// TODO ...
}
private class RequestDelivery implements Runnable {
ClientShSession session;
Request request;
public void run() {
try {
if (request.getApplicationId() == factory.getApplicationId()) {
if (request.getCommandCode() == PushNotificationRequest.code) {
handleEvent(new Event(Event.Type.RECEIVE_PUSH_NOTIFICATION_REQUEST, factory.createPushNotificationRequest(request), null));
return;
}
}
listener.doOtherEvent(session, new AppRequestEventImpl(request), null);
}
catch (Exception e) {
logger.debug("Failed to process request {}", request, e);
}
}
}
private class AnswerDelivery implements Runnable {
ClientShSession session;
Answer answer;
Request request;
public void run() {
try {
sendAndStateLock.lock();
if (request.getApplicationId() == factory.getApplicationId()) {
if (request.getCommandCode() == ProfileUpdateRequest.code) {
handleEvent(new Event(Event.Type.RECEIVE_PROFILE_UPDATE_ANSWER, factory.createProfileUpdateRequest(request), factory.createProfileUpdateAnswer(answer)));
return;
}
else if (request.getCommandCode() == UserDataRequest.code) {
handleEvent(new Event(Event.Type.RECEIVE_USER_DATA_ANSWER, factory.createUserDataRequest(request), factory.createUserDataAnswer(answer)));
return;
}
else if (request.getCommandCode() == SubscribeNotificationsRequest.code) {
handleEvent(new Event(Event.Type.RECEIVE_SUBSCRIBE_NOTIFICATIONS_ANSWER, factory.createSubscribeNotificationsRequest(request), factory
.createSubscribeNotificationsAnswer(answer)));
return;
}
}
listener.doOtherEvent(session, new AppRequestEventImpl(request), new AppAnswerEventImpl(answer));
}
catch (Exception e) {
logger.debug("Failed to process success message", e);
}
finally {
sendAndStateLock.unlock();
}
}
}
}
| 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.jdiameter.client.impl.app.sh;
import org.jdiameter.common.api.app.AppSessionDataLocalImpl;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ShClientSessionDataLocalImpl extends AppSessionDataLocalImpl implements IShClientSessionData {
/**
*
*/
public ShClientSessionDataLocalImpl() {
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2008, 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.jdiameter.client.impl.app.sh;
import org.jdiameter.api.app.AppEvent;
import org.jdiameter.api.app.StateEvent;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class Event implements StateEvent {
enum Type {
SEND_USER_DATA_REQUEST,
SEND_PROFILE_UPDATE_REQUEST,
SEND_SUBSCRIBE_NOTIFICATIONS_REQUEST,
SEND_PUSH_NOTIFICATION_ANSWER,
RECEIVE_PUSH_NOTIFICATION_REQUEST,
RECEIVE_USER_DATA_ANSWER,
RECEIVE_PROFILE_UPDATE_ANSWER,
RECEIVE_SUBSCRIBE_NOTIFICATIONS_ANSWER,
TIMEOUT_EXPIRES
}
Type type;
AppEvent request;
AppEvent answer;
Event(Type type, AppEvent request, AppEvent answer) {
this.type = type;
this.answer = answer;
this.request = request;
}
public <E> E encodeType(Class<E> eClass) {
return eClass == Type.class ? (E) type : null;
}
public Enum getType() {
return type;
}
public AppEvent getRequest() {
return request;
}
public AppEvent getAnswer() {
return answer;
}
public int compareTo(Object o) {
return 0;
}
public Object getData() {
return request != null ? request : answer;
}
public void setData(Object data) {
// FIXME: What should we do here?! Is it request or answer?
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.jdiameter.client.impl.app.cca;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.jdiameter.api.Answer;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.EventListener;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Message;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.app.AppAnswerEvent;
import org.jdiameter.api.app.AppEvent;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.app.StateChangeListener;
import org.jdiameter.api.app.StateEvent;
import org.jdiameter.api.auth.events.ReAuthAnswer;
import org.jdiameter.api.auth.events.ReAuthRequest;
import org.jdiameter.api.cca.ClientCCASession;
import org.jdiameter.api.cca.ClientCCASessionListener;
import org.jdiameter.api.cca.events.JCreditControlAnswer;
import org.jdiameter.api.cca.events.JCreditControlRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.client.impl.app.cca.Event.Type;
import org.jdiameter.common.api.app.IAppSessionState;
import org.jdiameter.common.api.app.cca.ClientCCASessionState;
import org.jdiameter.common.api.app.cca.ICCAMessageFactory;
import org.jdiameter.common.api.app.cca.IClientCCASessionContext;
import org.jdiameter.common.impl.app.AppAnswerEventImpl;
import org.jdiameter.common.impl.app.AppEventImpl;
import org.jdiameter.common.impl.app.AppRequestEventImpl;
import org.jdiameter.common.impl.app.auth.ReAuthAnswerImpl;
import org.jdiameter.common.impl.app.cca.AppCCASessionImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Client Credit-Control Application session implementation
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class ClientCCASessionImpl extends AppCCASessionImpl implements ClientCCASession, NetworkReqListener, EventListener<Request, Answer> {
private static final Logger logger = LoggerFactory.getLogger(ClientCCASessionImpl.class);
// session data pojo, local reference so we dont have to cast super.data to IClientCCASessionData
protected IClientCCASessionData sessionData;
// Session State Handling ---------------------------------------------------
protected Lock sendAndStateLock = new ReentrantLock();
// Session Based Queue
protected ArrayList<Event> eventQueue = new ArrayList<Event>(); //FIXME: this is not replicable?
// Factories and Listeners --------------------------------------------------
protected ICCAMessageFactory factory;
protected ClientCCASessionListener listener;
protected IClientCCASessionContext context;
protected final static String TX_TIMER_NAME = "CCA_CLIENT_TX_TIMER";
protected static final long TX_TIMER_DEFAULT_VALUE = 30 * 60 * 1000; // miliseconds
protected long[] authAppIds = new long[] { 4 };
protected static final int CCFH_TERMINATE = 0;
protected static final int CCFH_CONTINUE = 1;
protected static final int CCFH_RETRY_AND_TERMINATE = 2;
private static final int DDFH_TERMINATE_OR_BUFFER = 0;
private static final int DDFH_CONTINUE = 1;
// CC-Request-Type Values ---------------------------------------------------
private static final int DIRECT_DEBITING = 0;
private static final int REFUND_ACCOUNT = 1;
private static final int CHECK_BALANCE = 2;
private static final int PRICE_ENQUIRY = 3;
private static final int EVENT_REQUEST = 4;
// Error Codes --------------------------------------------------------------
private static final long END_USER_SERVICE_DENIED = 4010;
private static final long CREDIT_CONTROL_NOT_APPLICABLE = 4011;
private static final long USER_UNKNOWN = 5030;
private static final long DIAMETER_UNABLE_TO_DELIVER = 3002L;
private static final long DIAMETER_TOO_BUSY = 3004L;
private static final long DIAMETER_LOOP_DETECTED = 3005L;
protected static final Set<Long> temporaryErrorCodes;
static {
HashSet<Long> tmp = new HashSet<Long>();
tmp.add(DIAMETER_UNABLE_TO_DELIVER);
tmp.add(DIAMETER_TOO_BUSY);
tmp.add(DIAMETER_LOOP_DETECTED);
temporaryErrorCodes = Collections.unmodifiableSet(tmp);
}
public ClientCCASessionImpl(IClientCCASessionData data, ICCAMessageFactory fct, ISessionFactory sf, ClientCCASessionListener lst,IClientCCASessionContext ctx, StateChangeListener<AppSession> stLst) {
super(sf,data);
if (lst == null) {
throw new IllegalArgumentException("Listener can not be null");
}
if (data == null) {
throw new IllegalArgumentException("SessionData can not be null");
}
if (fct.getApplicationIds() == null) {
throw new IllegalArgumentException("ApplicationId can not be less than zero");
}
this.sessionData = data;
this.context = (IClientCCASessionContext)ctx;
this.authAppIds = fct.getApplicationIds();
this.listener = lst;
this.factory = fct;
super.addStateChangeNotification(stLst);
}
protected int getLocalCCFH() {
return sessionData.getGatheredCCFH() >= 0 ? sessionData.getGatheredCCFH() : context.getDefaultCCFHValue();
}
protected int getLocalDDFH() {
return sessionData.getGatheredDDFH() >= 0 ? sessionData.getGatheredDDFH() : context.getDefaultDDFHValue();
}
public void sendCreditControlRequest(JCreditControlRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
extractFHAVPs(request, null);
this.handleEvent(new Event(true, request, null));
}
public void sendReAuthAnswer(ReAuthAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
this.handleEvent(new Event(Event.Type.SEND_RAA, null, answer));
}
public boolean isStateless() {
return false;
}
public boolean isEventBased() {
return this.sessionData.isEventBased();
}
@SuppressWarnings("unchecked")
public <E> E getState(Class<E> stateType) {
return stateType == ClientCCASessionState.class ? (E) this.sessionData.getClientCCASessionState() : null;
}
public boolean handleEvent(StateEvent event) throws InternalException, OverloadException {
return this.isEventBased() ? handleEventForEventBased(event) : handleEventForSessionBased(event);
}
protected boolean handleEventForEventBased(StateEvent event) throws InternalException, OverloadException {
try {
sendAndStateLock.lock();
final Event localEvent = (Event) event;
final Event.Type eventType = (Type) localEvent.getType();
final ClientCCASessionState state = this.sessionData.getClientCCASessionState();
switch (state) {
case IDLE:
switch (eventType) {
case SEND_EVENT_REQUEST:
// Current State: IDLE
// Event: Client or device requests a one-time service
// Action: Send CC event request, start Tx
// New State: PENDING_E
startTx((JCreditControlRequest) localEvent.getRequest());
setState(ClientCCASessionState.PENDING_EVENT);
try {
dispatchEvent(localEvent.getRequest());
}
catch (Exception e) {
// This handles failure to send in PendingI state in FSM table
logger.debug("Failure handling send event request", e);
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
case PENDING_EVENT:
switch (eventType) {
case RECEIVE_EVENT_ANSWER:
AppAnswerEvent answer = (AppAnswerEvent) localEvent.getAnswer();
try {
long resultCode = answer.getResultCodeAvp().getUnsigned32();
if (isSuccess(resultCode)) {
// Current State: PENDING_E
// Event: Successful CC event answer received
// Action: Grant service to end user
// New State: IDLE
setState(ClientCCASessionState.IDLE, false);
}
if (isProvisional(resultCode) || isFailure(resultCode)) {
handleFailureMessage((JCreditControlAnswer) answer, (JCreditControlRequest) localEvent.getRequest(), eventType);
}
deliverCCAnswer((JCreditControlRequest) localEvent.getRequest(), (JCreditControlAnswer) localEvent.getAnswer());
}
catch (AvpDataException e) {
logger.debug("Failure handling received answer event", e);
setState(ClientCCASessionState.IDLE, false);
}
break;
case Tx_TIMER_FIRED:
handleTxExpires(localEvent.getRequest().getMessage());
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
case PENDING_BUFFERED:
switch (eventType) {
case RECEIVE_EVENT_ANSWER:
// Current State: PENDING_B
// Event: Successful CC answer received
// Action: Delete request
// New State: IDLE
setState(ClientCCASessionState.IDLE, false);
sessionData.setBuffer(null);
deliverCCAnswer((JCreditControlRequest) localEvent.getRequest(), (JCreditControlAnswer) localEvent.getAnswer());
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
dispatch();
return true;
}
catch (Exception e) {
throw new InternalException(e);
}
finally {
sendAndStateLock.unlock();
}
}
protected boolean handleEventForSessionBased(StateEvent event) throws InternalException, OverloadException {
try {
sendAndStateLock.lock();
Event localEvent = (Event) event;
Event.Type eventType = (Type) localEvent.getType();
ClientCCASessionState state = this.sessionData.getClientCCASessionState();
switch (state) {
case IDLE:
switch (eventType) {
case SEND_INITIAL_REQUEST:
// Current State: IDLE
// Event: Client or device requests access/service
// Action: Send CC initial request, start Tx
// New State: PENDING_I
startTx((JCreditControlRequest) localEvent.getRequest());
setState(ClientCCASessionState.PENDING_INITIAL);
try {
dispatchEvent(localEvent.getRequest());
}
catch (Exception e) {
// This handles failure to send in PendingI state in FSM table
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
case PENDING_INITIAL:
AppAnswerEvent answer = (AppAnswerEvent) localEvent.getAnswer();
switch (eventType) {
case RECEIVED_INITIAL_ANSWER:
long resultCode = answer.getResultCodeAvp().getUnsigned32();
if (isSuccess(resultCode)) {
// Current State: PENDING_I
// Event: Successful CC initial answer received
// Action: Stop Tx
// New State: OPEN
stopTx();
setState(ClientCCASessionState.OPEN);
}
else if (isProvisional(resultCode) || isFailure(resultCode)) {
handleFailureMessage((JCreditControlAnswer) answer, (JCreditControlRequest) localEvent.getRequest(), eventType);
}
deliverCCAnswer((JCreditControlRequest) localEvent.getRequest(), (JCreditControlAnswer) localEvent.getAnswer());
break;
case Tx_TIMER_FIRED:
handleTxExpires(localEvent.getRequest().getMessage());
break;
case SEND_UPDATE_REQUEST:
case SEND_TERMINATE_REQUEST:
// Current State: PENDING_I
// Event: User service terminated
// Action: Queue termination event
// New State: PENDING_I
// Current State: PENDING_I
// Event: Change in rating condition
// Action: Queue changed rating condition event
// New State: PENDING_I
eventQueue.add(localEvent);
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
case OPEN:
switch (eventType) {
case SEND_UPDATE_REQUEST:
// Current State: OPEN
// Event: Granted unit elapses and no final unit indication received
// Action: Send CC update request, start Tx
// New State: PENDING_U
// Current State: OPEN
// Event: Change in rating condition in queue
// Action: Send CC update request, start Tx
// New State: PENDING_U
// Current State: OPEN
// Event: Change in rating condition or Validity-Time elapses
// Action: Send CC update request, start Tx
// New State: PENDING_U
// Current State: OPEN
// Event: RAR received
// Action: Send RAA followed by CC update request, start Tx
// New State: PENDING_U
startTx((JCreditControlRequest) localEvent.getRequest());
setState(ClientCCASessionState.PENDING_UPDATE);
try {
dispatchEvent(localEvent.getRequest());
}
catch (Exception e) {
// This handles failure to send in PendingI state in FSM table
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
case SEND_TERMINATE_REQUEST:
// Current State: OPEN
// Event: Granted unit elapses and final unit action equal to TERMINATE received
// Action: Terminate end user�s service, send CC termination request
// New State: PENDING_T
// Current State: OPEN
// Event: Service terminated in queue
// Action: Send CC termination request
// New State: PENDING_T
// Current State: OPEN
// Event: User service terminated
// Action: Send CC termination request
// New State: PENDING_T
setState(ClientCCASessionState.PENDING_TERMINATION);
try {
dispatchEvent(localEvent.getRequest());
}
catch (Exception e) {
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
case RECEIVED_RAR:
deliverRAR((ReAuthRequest) localEvent.getRequest());
break;
case SEND_RAA:
try {
dispatchEvent(localEvent.getAnswer());
}
catch (Exception e) {
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
case PENDING_UPDATE:
answer = (AppAnswerEvent) localEvent.getAnswer();
switch (eventType) {
case RECEIVED_UPDATE_ANSWER:
long resultCode = answer.getResultCodeAvp().getUnsigned32();
if (isSuccess(resultCode)) {
// Current State: PENDING_U
// Event: Successful CC update answer received
// Action: Stop Tx
// New State: OPEN
stopTx();
setState(ClientCCASessionState.OPEN);
}
else if (isProvisional(resultCode) || isFailure(resultCode)) {
handleFailureMessage((JCreditControlAnswer) answer, (JCreditControlRequest) localEvent.getRequest(), eventType);
}
deliverCCAnswer((JCreditControlRequest) localEvent.getRequest(), (JCreditControlAnswer) localEvent.getAnswer());
break;
case Tx_TIMER_FIRED:
handleTxExpires(localEvent.getRequest().getMessage());
break;
case SEND_UPDATE_REQUEST:
case SEND_TERMINATE_REQUEST:
// Current State: PENDING_U
// Event: User service terminated
// Action: Queue termination event
// New State: PENDING_U
// Current State: PENDING_U
// Event: Change in rating condition
// Action: Queue changed rating condition event
// New State: PENDING_U
eventQueue.add(localEvent);
break;
case RECEIVED_RAR:
deliverRAR((ReAuthRequest) localEvent.getRequest());
break;
case SEND_RAA:
// Current State: PENDING_U
// Event: RAR received
// Action: Send RAA
// New State: PENDING_U
try {
dispatchEvent(localEvent.getAnswer());
}
catch (Exception e) {
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
}
break;
case PENDING_TERMINATION:
switch (eventType) {
case SEND_UPDATE_REQUEST:
try {
// Current State: PENDING_T
// Event: Change in rating condition
// Action: -
// New State: PENDING_T
dispatchEvent(localEvent.getRequest());
// No transition
}
catch (Exception e) {
// This handles failure to send in PendingI state in FSM table
// handleSendFailure(e, eventType);
}
break;
case RECEIVED_TERMINATED_ANSWER:
// Current State: PENDING_T
// Event: Successful CC termination answer received
// Action: -
// New State: IDLE
// Current State: PENDING_T
// Event: Failure to send, temporary error, or failed answer
// Action: -
// New State: IDLE
//FIXME: Alex broke this, setting back "true" ?
//setState(ClientCCASessionState.IDLE, false);
deliverCCAnswer((JCreditControlRequest) localEvent.getRequest(), (JCreditControlAnswer) localEvent.getAnswer());
setState(ClientCCASessionState.IDLE, true);
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
default:
// any other state is bad
setState(ClientCCASessionState.IDLE, true);
}
dispatch();
return true;
}
catch (Exception e) {
throw new InternalException(e);
}
finally {
sendAndStateLock.unlock();
}
}
public Answer processRequest(Request request) {
RequestDelivery rd = new RequestDelivery();
rd.session = this;
rd.request = request;
super.scheduler.execute(rd);
return null;
}
public void receivedSuccessMessage(Request request, Answer answer) {
AnswerDelivery ad = new AnswerDelivery();
ad.session = this;
ad.request = request;
ad.answer = answer;
super.scheduler.execute(ad);
}
public void timeoutExpired(Request request) {
if(request.getCommandCode()== JCreditControlAnswer.code) {
try {
handleSendFailure(null, null, request);
}
catch (Exception e) {
logger.debug("Failure processing timeout message for request", e);
}
}
}
protected void startTx(JCreditControlRequest request) {
long txTimerValue = context.getDefaultTxTimerValue();
if (txTimerValue < 0) {
txTimerValue = TX_TIMER_DEFAULT_VALUE;
}
stopTx();
logger.debug("Scheduling TX Timer {}", txTimerValue);
//this.txFuture = scheduler.schedule(new TxTimerTask(this, request), txTimerValue, TimeUnit.SECONDS);
try {
this.sessionData.setTxTimerRequest((Request) ((AppEventImpl)request).getMessage());
}
catch (Exception e) {
throw new IllegalArgumentException("Failed to store request.", e);
}
this.sessionData.setTxTimerId(this.timerFacility.schedule(this.getSessionId(), TX_TIMER_NAME, TX_TIMER_DEFAULT_VALUE));
}
protected void stopTx() {
Serializable txTimerId = this.sessionData.getTxTimerId();
if(txTimerId!= null) {
this.sessionData.setTxTimerRequest(null);
this.timerFacility.cancel(txTimerId);
this.sessionData.setTxTimerId(null);
}
}
/* (non-Javadoc)
* @see org.jdiameter.common.impl.app.AppSessionImpl#onTimer(java.lang.String)
*/
@Override
public void onTimer(String timerName) {
if(timerName.equals(TX_TIMER_NAME)) {
new TxTimerTask(this, this.sessionData.getTxTimerRequest()).run();
}
}
protected void setState(ClientCCASessionState newState) {
setState(newState, true);
}
@SuppressWarnings("unchecked")
protected void setState(ClientCCASessionState newState, boolean release) {
try {
IAppSessionState oldState = this.sessionData.getClientCCASessionState();
this.sessionData.setClientCCASessionState(newState);
for (StateChangeListener i : stateListeners) {
i.stateChanged(this,(Enum) oldState, (Enum) newState);
}
if (newState == ClientCCASessionState.IDLE) {
if (release) {
this.release();
}
stopTx();
}
}
catch (Exception e) {
if(logger.isDebugEnabled()) {
logger.debug("Failure switching to state " + this.sessionData.getClientCCASessionState() + " (release=" + release + ")", e);
}
}
}
@Override
public void release() {
if (isValid()) {
try {
this.sendAndStateLock.lock();
super.release();
}
catch (Exception e) {
logger.debug("Failed to release session", e);
}
finally {
sendAndStateLock.unlock();
}
}
else {
logger.debug("Trying to release an already invalid session, with Session ID '{}'", getSessionId());
}
}
protected void handleSendFailure(Exception e, Event.Type eventType, Message request) throws Exception {
logger.debug("Failed to send message, type: {} message: {}, failure: {}", new Object[]{eventType, request, e != null ? e.getLocalizedMessage() : ""});
try {
this.sendAndStateLock.lock();
ClientCCASessionState state = this.sessionData.getClientCCASessionState();
// Event Based ----------------------------------------------------------
if (isEventBased()) {
int gatheredRequestedAction = this.sessionData.getGatheredRequestedAction();
switch (state) {
case PENDING_EVENT:
if (gatheredRequestedAction == CHECK_BALANCE || gatheredRequestedAction == PRICE_ENQUIRY) {
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action CHECK_BALANCE or PRICE_ENQUIRY
// Action: Indicate service error
// New State: IDLE
setState(ClientCCASessionState.IDLE);
context.indicateServiceError(this);
}
else if (gatheredRequestedAction == DIRECT_DEBITING) {
switch(getLocalDDFH()) {
case DDFH_TERMINATE_OR_BUFFER:
// Current State: PENDING_E
// Event: Failure to send; request action DIRECT_DEBITING; DDFH equal to TERMINATE_OR_BUFFER
// Action: Store request with T-flag
// New State: IDLE
request.setReTransmitted(true);
this.sessionData.setBuffer((Request) request);
setState(ClientCCASessionState.IDLE, false);
break;
case DDFH_CONTINUE:
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action DIRECT_DEBITING; DDFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnDeliverFailure(this, request);
break;
default:
logger.warn("Invalid Direct-Debiting-Failure-Handling AVP value {}", getLocalDDFH());
}
}
else if (gatheredRequestedAction == REFUND_ACCOUNT) {
// Current State: PENDING_E
// Event: Failure to send or Tx expired; requested action REFUND_ACCOUNT
// Action: Store request with T-flag
// New State: IDLE
setState(ClientCCASessionState.IDLE, false);
request.setReTransmitted(true);
this.sessionData.setBuffer((Request) request);
}
else {
logger.warn("Invalid Requested-Action AVP value {}", gatheredRequestedAction);
}
break;
case PENDING_BUFFERED:
// Current State: PENDING_B
// Event: Failure to send or temporary error
// Action: -
// New State: IDLE
setState(ClientCCASessionState.IDLE, false);
this.sessionData.setBuffer(null); // FIXME: Action does not mention, but ...
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
}
// Session Based --------------------------------------------------------
else {
switch (getLocalCCFH()) {
case CCFH_CONTINUE:
// Current State: PENDING_I
// Event: Failure to send, or temporary error and CCFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
// Current State: PENDING_U
// Event: Failure to send, or temporary error and CCFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
setState(ClientCCASessionState.IDLE, false);
this.context.grantAccessOnDeliverFailure(this, request);
break;
default:
// Current State: PENDING_I
// Event: Failure to send, or temporary error and CCFH equal to TERMINATE or to RETRY_AND_TERMINATE
// Action: Terminate end user�s service
// New State: IDLE
// Current State: PENDING_U
// Event: Failure to send, or temporary error and CCFH equal to TERMINATE or to RETRY_AND_TERMINATE
// Action: Terminate end user�s service
// New State: IDLE
this.context.denyAccessOnDeliverFailure(this, request);
setState(ClientCCASessionState.IDLE, true);
break;
}
}
dispatch();
}
finally {
this.sendAndStateLock.unlock();
}
}
protected void handleFailureMessage(JCreditControlAnswer answer, JCreditControlRequest request, Event.Type eventType) {
try {
// Event Based ----------------------------------------------------------
long resultCode = answer.getResultCodeAvp().getUnsigned32();
ClientCCASessionState state = this.sessionData.getClientCCASessionState();
Serializable txTimerId = this.sessionData.getTxTimerId();
if (isEventBased()) {
int gatheredRequestedAction = this.sessionData.getGatheredRequestedAction();
switch (state) {
case PENDING_EVENT:
if (resultCode == END_USER_SERVICE_DENIED || resultCode == USER_UNKNOWN) {
if(txTimerId != null) {
// Current State: PENDING_E
// Event: CC event answer received with result code END_USER_SERVICE_DENIED or USER_UNKNOWN and Tx running
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
deliverCCAnswer(request, answer);
setState(ClientCCASessionState.IDLE);
}
else if(gatheredRequestedAction == DIRECT_DEBITING && txTimerId == null) {
// Current State: PENDING_E
// Event: Failed answer or answer received with result code END_USER_SERVICE DENIED or USER_UNKNOWN; requested action DIRECT_DEBITING; Tx expired
// Action: -
// New State: IDLE
setState(ClientCCASessionState.IDLE);
}
}
else if (resultCode == CREDIT_CONTROL_NOT_APPLICABLE && gatheredRequestedAction == DIRECT_DEBITING) {
// Current State: PENDING_E
// Event: CC event answer received with result code CREDIT_CONTROL_NOT_APPLICABLE; requested action DIRECT_DEBITING
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
deliverCCAnswer(request, answer);
setState(ClientCCASessionState.IDLE);
}
else if (temporaryErrorCodes.contains(resultCode)) {
if (gatheredRequestedAction == CHECK_BALANCE || gatheredRequestedAction == PRICE_ENQUIRY) {
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action CHECK_BALANCE or PRICE_ENQUIRY
// Action: Indicate service error
// New State: IDLE
context.indicateServiceError(this);
deliverCCAnswer(request, answer);
setState(ClientCCASessionState.IDLE);
}
else if (gatheredRequestedAction == DIRECT_DEBITING) {
if(getLocalDDFH() == DDFH_CONTINUE) {
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action DIRECT_DEBITING; DDFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
deliverCCAnswer(request, answer);
setState(ClientCCASessionState.IDLE);
}
else if (getLocalDDFH() == DDFH_TERMINATE_OR_BUFFER && txTimerId != null) {
// Current State: PENDING_E
// Event: Failed CC event answer received or temporary error; requested action DIRECT_DEBITING; DDFH equal to TERMINATE_OR_BUFFER and Tx running
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
deliverCCAnswer(request, answer);
setState(ClientCCASessionState.IDLE);
}
}
else if (gatheredRequestedAction == REFUND_ACCOUNT) {
// Current State: PENDING_E
// Event: Temporary error, and requested action REFUND_ACCOUNT
// Action: Store request
// New State: IDLE
this.sessionData.setBuffer((Request) request.getMessage());
setState(ClientCCASessionState.IDLE, false);
}
else {
logger.warn("Invalid combination for CCA Client FSM: State {}, Result-Code {}, Requested-Action {}, DDFH {}, Tx {}", new Object[]{state, resultCode, gatheredRequestedAction, getLocalDDFH(), txTimerId});
}
}
else { // Failure
if (gatheredRequestedAction == CHECK_BALANCE || gatheredRequestedAction == PRICE_ENQUIRY) {
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action CHECK_BALANCE or PRICE_ENQUIRY
// Action: Indicate service error
// New State: IDLE
context.indicateServiceError(this);
deliverCCAnswer(request, answer);
setState(ClientCCASessionState.IDLE);
}
else if (gatheredRequestedAction == DIRECT_DEBITING) {
if(getLocalDDFH() == DDFH_CONTINUE) {
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action DIRECT_DEBITING; DDFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
deliverCCAnswer(request, answer);
setState(ClientCCASessionState.IDLE);
}
else if (getLocalDDFH() == DDFH_TERMINATE_OR_BUFFER && txTimerId != null) {
// Current State: PENDING_E
// Event: Failed CC event answer received or temporary error; requested action DIRECT_DEBITING; DDFH equal to TERMINATE_OR_BUFFER and Tx running
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
deliverCCAnswer(request, answer);
setState(ClientCCASessionState.IDLE);
}
}
else if (gatheredRequestedAction == REFUND_ACCOUNT) {
// Current State: PENDING_E
// Event: Failed CC event answer received; requested action REFUND_ACCOUNT
// Action: Indicate service error and delete request
// New State: IDLE
this.sessionData.setBuffer(null);
context.indicateServiceError(this);
deliverCCAnswer(request, answer);
setState(ClientCCASessionState.IDLE);
}
else {
logger.warn("Invalid combination for CCA Client FSM: State {}, Result-Code {}, Requested-Action {}, DDFH {}, Tx {}", new Object[]{state, resultCode, gatheredRequestedAction, getLocalDDFH(), txTimerId});
}
}
break;
case PENDING_BUFFERED:
// Current State: PENDING_B
// Event: Failed CC answer received
// Action: Delete request
// New State: IDLE
this.sessionData.setBuffer(null);
setState(ClientCCASessionState.IDLE, false);
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
}
}
// Session Based --------------------------------------------------------
else {
switch (state) {
case PENDING_INITIAL:
if (resultCode == CREDIT_CONTROL_NOT_APPLICABLE) {
// Current State: PENDING_I
// Event: CC initial answer received with result code equal to CREDIT_CONTROL_NOT_APPLICABLE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
setState(ClientCCASessionState.IDLE, false);
}
else if ((resultCode == END_USER_SERVICE_DENIED) || (resultCode == USER_UNKNOWN)) {
// Current State: PENDING_I
// Event: CC initial answer received with result code END_USER_SERVICE_DENIED or USER_UNKNOWN
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
setState(ClientCCASessionState.IDLE, false);
}
else {
// Temporary errors and others
switch (getLocalCCFH()) {
case CCFH_CONTINUE:
// Current State: PENDING_I
// Event: Failed CC initial answer received and CCFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
setState(ClientCCASessionState.IDLE, false);
break;
case CCFH_TERMINATE:
case CCFH_RETRY_AND_TERMINATE:
// Current State: PENDING_I
// Event: Failed CC initial answer received and CCFH equal to TERMINATE or to RETRY_AND_TERMINATE
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
setState(ClientCCASessionState.IDLE, false);
break;
default:
logger.warn("Invalid value for CCFH: {}", getLocalCCFH());
break;
}
}
break;
case PENDING_UPDATE:
if (resultCode == CREDIT_CONTROL_NOT_APPLICABLE) {
// Current State: PENDING_U
// Event: CC update answer received with result code equal to CREDIT_CONTROL_NOT_APPLICABLE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
setState(ClientCCASessionState.IDLE, false);
}
else if (resultCode == END_USER_SERVICE_DENIED) {
// Current State: PENDING_U
// Event: CC update answer received with result code END_USER_SERVICE_DENIED
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
setState(ClientCCASessionState.IDLE, false);
}
else {
// Temporary errors and others
switch (getLocalCCFH()) {
case CCFH_CONTINUE:
// Current State: PENDING_U
// Event: Failed CC update answer received and CCFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
setState(ClientCCASessionState.IDLE, false);
break;
case CCFH_TERMINATE:
case CCFH_RETRY_AND_TERMINATE:
// Current State: PENDING_U
// Event: Failed CC update answer received and CCFH equal to CONTINUE or to RETRY_AND_CONTINUE
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
setState(ClientCCASessionState.IDLE, false);
break;
default:
logger.warn("Invalid value for CCFH: " + getLocalCCFH());
break;
}
}
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
}
}
}
catch (Exception e) {
if(logger.isDebugEnabled()) {
logger.debug("Failure handling failure message for Event " + answer + " (" + eventType + ") and Request " + request, e);
}
}
}
protected void handleTxExpires(Message message) {
// Event Based ----------------------------------------------------------
ClientCCASessionState state = this.sessionData.getClientCCASessionState();
Serializable txTimerId = this.sessionData.getTxTimerId();
if (isEventBased()) {
int gatheredRequestedAction = this.sessionData.getGatheredRequestedAction();
if (gatheredRequestedAction == CHECK_BALANCE || gatheredRequestedAction == PRICE_ENQUIRY) {
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action CHECK_BALANCE or PRICE_ENQUIRY
// Action: Indicate service error
// New State: IDLE
context.indicateServiceError(this);
setState(ClientCCASessionState.IDLE);
}
else if (gatheredRequestedAction == DIRECT_DEBITING) {
int gatheredDDFH = this.sessionData.getGatheredDDFH();
if(gatheredDDFH == DDFH_TERMINATE_OR_BUFFER) {
// Current State: PENDING_E
// Event: Temporary error; requested action DIRECT_DEBITING; DDFH equal to TERMINATE_OR_BUFFER; Tx expired
// Action: Store request
// New State: IDLE
this.sessionData.setBuffer((Request) message);
setState(ClientCCASessionState.IDLE, false);
}
else {
// Current State: PENDING_E
// Event: Tx expired; requested action DIRECT_DEBITING
// Action: Grant service to end user
// New State: PENDING_E
context.grantAccessOnTxExpire(this);
setState(ClientCCASessionState.PENDING_EVENT);
}
}
else if (gatheredRequestedAction == REFUND_ACCOUNT) {
// Current State: PENDING_E
// Event: Failure to send or Tx expired; requested action REFUND_ACCOUNT
// Action: Store request with T-flag
// New State: IDLE
message.setReTransmitted(true);
this.sessionData.setBuffer((Request) message);
setState(ClientCCASessionState.IDLE, false);
}
}
// Session Based --------------------------------------------------------
else {
switch (state) {
case PENDING_INITIAL:
switch (getLocalCCFH()) {
case CCFH_CONTINUE:
case CCFH_RETRY_AND_TERMINATE:
// Current State: PENDING_I
// Event: Tx expired and CCFH equal to CONTINUE or to RETRY_AND_TERMINATE
// Action: Grant service to end user
// New State: PENDING_I
context.grantAccessOnTxExpire(this);
break;
case CCFH_TERMINATE:
// Current State: PENDING_I
// Event: Tx expired and CCFH equal to TERMINATE
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnTxExpire(this);
setState(ClientCCASessionState.IDLE, true);
break;
default:
logger.warn("Invalid value for CCFH: " + getLocalCCFH());
break;
}
break;
case PENDING_UPDATE:
switch (getLocalCCFH()) {
case CCFH_CONTINUE:
case CCFH_RETRY_AND_TERMINATE:
// Current State: PENDING_U
// Event: Tx expired and CCFH equal to CONTINUE or to RETRY_AND_TERMINATE
// Action: Grant service to end user
// New State: PENDING_U
context.grantAccessOnTxExpire(this);
break;
case CCFH_TERMINATE:
// Current State: PENDING_U
// Event: Tx expired and CCFH equal to TERMINATE
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnTxExpire(this);
setState(ClientCCASessionState.IDLE, true);
break;
default:
logger.error("Bad value of CCFH: " + getLocalCCFH());
break;
}
break;
default:
logger.error("Unknown state (" + state + ") on txExpire");
break;
}
}
}
/**
* This makes checks on queue, moves it to proper state if event there is
* present on Open state ;]
*/
protected void dispatch() {
// Event Based ----------------------------------------------------------
if (isEventBased()) {
// Current State: IDLE
// Event: Request in storage
// Action: Send stored request
// New State: PENDING_B
Request buffer = this.sessionData.getBuffer();
if (buffer != null) {
setState(ClientCCASessionState.PENDING_BUFFERED);
try {
dispatchEvent(new AppRequestEventImpl(buffer));
}
catch (Exception e) {
try {
handleSendFailure(e, Event.Type.SEND_EVENT_REQUEST, buffer);
}
catch (Exception e1) {
logger.error("Failure handling buffer send failure", e1);
}
}
}
}
// Session Based --------------------------------------------------------
else {
if (this.sessionData.getClientCCASessionState() == ClientCCASessionState.OPEN && eventQueue.size() > 0) {
try {
this.handleEvent(eventQueue.remove(0));
}
catch (Exception e) {
logger.error("Failure handling queued event", e);
}
}
}
}
protected void deliverCCAnswer(JCreditControlRequest request, JCreditControlAnswer answer) {
try {
listener.doCreditControlAnswer(this, request, answer);
}
catch (Exception e) {
logger.warn("Failure delivering CCA Answer", e);
}
}
protected void extractFHAVPs(JCreditControlRequest request, JCreditControlAnswer answer) {
if (answer != null) {
try {
if (answer.isCreditControlFailureHandlingAVPPresent()) {
this.sessionData.setGatheredCCFH(answer.getCredidControlFailureHandlingAVPValue());
}
}
catch (Exception e) {
logger.debug("Failure trying to obtain Credit-Control-Failure-Handling AVP value", e);
}
try {
if (answer.isDirectDebitingFailureHandlingAVPPresent()) {
this.sessionData.setGatheredDDFH(answer.getDirectDebitingFailureHandlingAVPValue());
}
}
catch (Exception e) {
logger.debug("Failure trying to obtain Direct-Debit-Failure-Handling AVP value", e);
}
if(!this.sessionData.isRequestTypeSet()) {
this.sessionData.setRequestTypeSet(true);
// No need to check if it exists.. it must, if not fail with exception
this.sessionData.setEventBased(answer.getRequestTypeAVPValue() == EVENT_REQUEST);
}
}
else if (request != null) {
try {
if (request.isRequestedActionAVPPresent()) {
this.sessionData.setGatheredRequestedAction(request.getRequestedActionAVPValue());
}
}
catch (Exception e) {
logger.debug("Failure trying to obtain Request-Action AVP value", e);
}
if(!this.sessionData.isRequestTypeSet()) {
this.sessionData.setRequestTypeSet(true);
// No need to check if it exists.. it must, if not fail with exception
this.sessionData.setEventBased(request.getRequestTypeAVPValue() == EVENT_REQUEST);
}
}
}
protected void deliverRAR(ReAuthRequest request) {
try {
listener.doReAuthRequest(this, request);
}
catch (Exception e) {
logger.debug("Failure delivering RAR", e);
}
}
protected void dispatchEvent(AppEvent event) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
session.send(event.getMessage(), this);
}
protected boolean isProvisional(long resultCode) {
return resultCode >= 1000 && resultCode < 2000;
}
protected boolean isSuccess(long resultCode) {
return resultCode >= 2000 && resultCode < 3000;
}
protected boolean isFailure(long code) {
return (!isProvisional(code) && !isSuccess(code) && ((code >= 3000 && /*code < 4000) || (code >= 5000 &&*/ code < 6000)) && !temporaryErrorCodes.contains(code));
}
/* (non-Javadoc)
* @see org.jdiameter.common.impl.app.AppSessionImpl#isReplicable()
*/
@Override
public boolean isReplicable() {
return true;
}
private class TxTimerTask implements Runnable {
private ClientCCASession session = null;
private Request request = null;
private TxTimerTask(ClientCCASession session, Request request) {
super();
this.session = session;
this.request = request;
}
public void run() {
try {
sendAndStateLock.lock();
logger.debug("Fired TX Timer");
sessionData.setTxTimerId(null);
try {
context.txTimerExpired(session);
}
catch (Exception e) {
logger.debug("Failure handling TX Timer Expired", e);
}
JCreditControlRequest req = factory.createCreditControlRequest(request);
handleEvent(new Event(Event.Type.Tx_TIMER_FIRED, req, null));
}
catch (InternalException e) {
logger.error("Internal Exception", e);
}
catch (OverloadException e) {
logger.error("Overload Exception", e);
}
catch (Exception e) {
logger.error("Exception", e);
}
finally {
sendAndStateLock.unlock();
}
}
}
private class RequestDelivery implements Runnable {
ClientCCASession session;
Request request;
public void run() {
try {
switch (request.getCommandCode()) {
case ReAuthAnswerImpl.code:
handleEvent(new Event(Event.Type.RECEIVED_RAR, factory.createReAuthRequest(request), null));
break;
default:
listener.doOtherEvent(session, new AppRequestEventImpl(request), null);
break;
}
}
catch (Exception e) {
logger.debug("Failure processing request", e);
}
}
}
private class AnswerDelivery implements Runnable {
ClientCCASession session;
Answer answer;
Request request;
public void run() {
try{
switch(request.getCommandCode())
{
case JCreditControlAnswer.code:
JCreditControlRequest _request = factory.createCreditControlRequest(request);
JCreditControlAnswer _answer = factory.createCreditControlAnswer(answer);
extractFHAVPs(null, _answer );
handleEvent(new Event(false, _request, _answer));
break;
default:
listener.doOtherEvent(session, new AppRequestEventImpl(request), new AppAnswerEventImpl(answer));
break;
}
}
catch(Exception e) {
logger.debug("Failure processing success message", e);
}
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((sessionData == null) ? 0 : sessionData.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;
ClientCCASessionImpl other = (ClientCCASessionImpl) obj;
if (sessionData == null) {
if (other.sessionData != null)
return false;
}
else if (!sessionData.equals(other.sessionData))
return false;
return true;
}
}
| 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.jdiameter.client.impl.app.cca;
import java.io.Serializable;
import org.jdiameter.api.Request;
import org.jdiameter.common.api.app.AppSessionDataLocalImpl;
import org.jdiameter.common.api.app.cca.ClientCCASessionState;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ClientCCASessionDataLocalImpl extends AppSessionDataLocalImpl implements IClientCCASessionData {
protected boolean isEventBased = true;
protected boolean requestTypeSet = false;
protected ClientCCASessionState state = ClientCCASessionState.IDLE;
protected Serializable txTimerId;
//protected JCreditControlRequest txTimerRequest;
protected Request txTimerRequest;
// Event Based Buffer
//protected Message buffer = null;
protected Request buffer;
protected int gatheredRequestedAction = NON_INITIALIZED;
protected int gatheredCCFH = NON_INITIALIZED;
protected int gatheredDDFH = NON_INITIALIZED;
/**
*
*/
public ClientCCASessionDataLocalImpl() {
}
public boolean isEventBased() {
return isEventBased;
}
public void setEventBased(boolean isEventBased) {
this.isEventBased = isEventBased;
}
public boolean isRequestTypeSet() {
return requestTypeSet;
}
public void setRequestTypeSet(boolean requestTypeSet) {
this.requestTypeSet = requestTypeSet;
}
public ClientCCASessionState getClientCCASessionState() {
return state;
}
public void setClientCCASessionState(ClientCCASessionState state) {
this.state = state;
}
public Serializable getTxTimerId() {
return txTimerId;
}
public void setTxTimerId(Serializable txTimerId) {
this.txTimerId = txTimerId;
}
public Request getTxTimerRequest() {
return txTimerRequest;
}
public void setTxTimerRequest(Request txTimerRequest) {
this.txTimerRequest = txTimerRequest;
}
public Request getBuffer() {
return buffer;
}
public void setBuffer(Request buffer) {
this.buffer = buffer;
}
public int getGatheredRequestedAction() {
return gatheredRequestedAction;
}
public void setGatheredRequestedAction(int gatheredRequestedAction) {
this.gatheredRequestedAction = gatheredRequestedAction;
}
public int getGatheredCCFH() {
return gatheredCCFH;
}
public void setGatheredCCFH(int gatheredCCFH) {
this.gatheredCCFH = gatheredCCFH;
}
public int getGatheredDDFH() {
return gatheredDDFH;
}
public void setGatheredDDFH(int gatheredDDFH) {
this.gatheredDDFH = gatheredDDFH;
}
}
| 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.jdiameter.client.impl.app.cca;
import org.jdiameter.api.app.AppAnswerEvent;
import org.jdiameter.api.app.AppEvent;
import org.jdiameter.api.app.AppRequestEvent;
import org.jdiameter.api.app.StateEvent;
import org.jdiameter.api.cca.events.JCreditControlAnswer;
import org.jdiameter.api.cca.events.JCreditControlRequest;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class Event implements StateEvent {
public enum Type {
SEND_INITIAL_REQUEST, RECEIVED_INITIAL_ANSWER,
SEND_UPDATE_REQUEST, RECEIVED_UPDATE_ANSWER,
SEND_TERMINATE_REQUEST,RECEIVED_TERMINATED_ANSWER,
RECEIVED_RAR,SEND_RAA,Tx_TIMER_FIRED,
SEND_EVENT_REQUEST, RECEIVE_EVENT_ANSWER;
}
Type type;
AppRequestEvent request;
AppAnswerEvent answer;
Event(Type type) {
this.type = type;
}
Event(Type type, AppRequestEvent request, AppAnswerEvent answer) {
this.type = type;
this.answer = answer;
this.request = request;
}
Event(boolean isRequest, JCreditControlRequest request, JCreditControlAnswer answer) {
this.answer = answer;
this.request = request;
if(isRequest) {
switch(request.getRequestTypeAVPValue())
{
case 1:
type = Type.SEND_INITIAL_REQUEST;
break;
case 2:
type = Type.SEND_UPDATE_REQUEST;
break;
case 3:
type = Type.SEND_TERMINATE_REQUEST;
break;
case 4:
type = Type.SEND_EVENT_REQUEST;
break;
default:
throw new RuntimeException("Wrong CC-Request-Type value: " + request.getRequestTypeAVPValue());
}
}
else {
switch(answer.getRequestTypeAVPValue())
{
case 1:
type = Type.RECEIVED_INITIAL_ANSWER;
break;
case 2:
type = Type.RECEIVED_UPDATE_ANSWER;
break;
case 3:
type = Type.RECEIVED_TERMINATED_ANSWER;
break;
case 4:
type = Type.RECEIVE_EVENT_ANSWER;
break;
default:
throw new RuntimeException("Wrong CC-Request-Type value: " + answer.getRequestTypeAVPValue());
}
}
}
public Enum getType() {
return type;
}
public int compareTo(Object o) {
return 0;
}
public Object getData() {
return request != null ? request : answer;
}
public void setData(Object data) {
// FIXME: What should we do here?! Is it request or answer?
}
public AppEvent getRequest() {
return request;
}
public AppEvent getAnswer() {
return answer;
}
public <E> E encodeType(Class<E> eClass) {
return eClass == Event.Type.class ? (E) type : null;
}
}
| 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.jdiameter.client.impl.app.cca;
import java.io.Serializable;
import org.jdiameter.api.Request;
import org.jdiameter.common.api.app.cca.ClientCCASessionState;
import org.jdiameter.common.api.app.cca.ICCASessionData;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public interface IClientCCASessionData extends ICCASessionData {
public boolean isEventBased();
public void setEventBased(boolean b);
public boolean isRequestTypeSet();
public void setRequestTypeSet(boolean b);
public ClientCCASessionState getClientCCASessionState();
public void setClientCCASessionState(ClientCCASessionState state);
public Serializable getTxTimerId();
public void setTxTimerId(Serializable txTimerId);
public Request getTxTimerRequest();
public void setTxTimerRequest(Request txTimerRequest);
public Request getBuffer();
public void setBuffer(Request buffer);
public int getGatheredRequestedAction();
public void setGatheredRequestedAction(int gatheredRequestedAction);
public int getGatheredCCFH();
public void setGatheredCCFH(int gatheredCCFH);
public int getGatheredDDFH();
public void setGatheredDDFH(int gatheredDDFH);
}
| 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.jdiameter.client.impl.app.cxdx;
import org.jdiameter.common.api.app.cxdx.ICxDxSessionData;
/**
*
* @author <a href="mailto:baranowb@gmail.com">Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public interface IClientCxDxSessionData extends ICxDxSessionData{
}
| 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.jdiameter.client.impl.app.cxdx;
import org.jdiameter.common.impl.app.cxdx.CxDxLocalSessionDataImpl;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ClientCxDxSessionDataLocalImpl extends CxDxLocalSessionDataImpl implements IClientCxDxSessionData {
/**
*
*/
public ClientCxDxSessionDataLocalImpl() {
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2009, 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.jdiameter.client.impl.app.cxdx;
import org.jdiameter.api.app.AppEvent;
import org.jdiameter.api.app.StateEvent;
/**
*
* @author <a href="mailto:baranowb@gmail.com">Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class Event implements StateEvent {
enum Type {
SEND_MESSAGE,
RECEIVE_RTR,
RECEIVE_PPR,
TIMEOUT_EXPIRES,
RECEIVE_UAA,
RECEIVE_SAA,
RECEIVE_LIA,
RECEIVE_MAA;
}
AppEvent request;
AppEvent answer;
Type type;
Event(Type type, AppEvent request, AppEvent answer) {
this.type = type;
this.answer = answer;
this.request = request;
}
public <E> E encodeType(Class<E> eClass) {
return eClass == Type.class ? (E) type : null;
}
public Enum getType() {
return type;
}
public AppEvent getRequest() {
return request;
}
public AppEvent getAnswer() {
return answer;
}
public int compareTo(Object o) {
return 0;
}
public Object getData() {
return request != null ? request : answer;
}
public void setData(Object data) {
// TODO: Replace Request/Answer with this
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.jdiameter.client.impl.app.cxdx;
import org.jdiameter.api.Answer;
import org.jdiameter.api.EventListener;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.app.AppEvent;
import org.jdiameter.api.app.StateChangeListener;
import org.jdiameter.api.app.StateEvent;
import org.jdiameter.api.cxdx.ClientCxDxSession;
import org.jdiameter.api.cxdx.ClientCxDxSessionListener;
import org.jdiameter.api.cxdx.events.JLocationInfoAnswer;
import org.jdiameter.api.cxdx.events.JLocationInfoRequest;
import org.jdiameter.api.cxdx.events.JMultimediaAuthAnswer;
import org.jdiameter.api.cxdx.events.JMultimediaAuthRequest;
import org.jdiameter.api.cxdx.events.JPushProfileAnswer;
import org.jdiameter.api.cxdx.events.JPushProfileRequest;
import org.jdiameter.api.cxdx.events.JRegistrationTerminationAnswer;
import org.jdiameter.api.cxdx.events.JRegistrationTerminationRequest;
import org.jdiameter.api.cxdx.events.JServerAssignmentAnswer;
import org.jdiameter.api.cxdx.events.JServerAssignmentRequest;
import org.jdiameter.api.cxdx.events.JUserAuthorizationAnswer;
import org.jdiameter.api.cxdx.events.JUserAuthorizationRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.client.impl.app.cxdx.Event.Type;
import org.jdiameter.common.api.app.cxdx.CxDxSessionState;
import org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory;
import org.jdiameter.common.impl.app.AppAnswerEventImpl;
import org.jdiameter.common.impl.app.AppRequestEventImpl;
import org.jdiameter.common.impl.app.cxdx.CxDxSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Diameter Cx/Dx Client Session implementation
*
* @author <a href="mailto:baranowb@gmail.com">Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class CxDxClientSessionImpl extends CxDxSession implements ClientCxDxSession, EventListener<Request, Answer>, NetworkReqListener {
private static final Logger logger = LoggerFactory.getLogger(CxDxClientSessionImpl.class);
// Factories and Listeners --------------------------------------------------
private transient ClientCxDxSessionListener listener;
protected long appId = -1;
protected IClientCxDxSessionData sessionData;
public CxDxClientSessionImpl(IClientCxDxSessionData sessionData, ICxDxMessageFactory fct, ISessionFactory sf, ClientCxDxSessionListener lst) {
super(sf,sessionData);
if (lst == null) {
throw new IllegalArgumentException("Listener can not be null");
}
if (fct.getApplicationId() < 0) {
throw new IllegalArgumentException("ApplicationId can not be less than zero");
}
this.appId = fct.getApplicationId();
this.listener = lst;
super.messageFactory = fct;
this.sessionData = sessionData;
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.app.StateMachine#getState(java.lang.Class)
*/
@SuppressWarnings("unchecked")
public <E> E getState(Class<E> stateType) {
return stateType == CxDxSessionState.class ? (E) this.sessionData.getCxDxSessionState() : null;
}
/*
* (non-Javadoc)
* @see org.jdiameter.api.NetworkReqListener#processRequest(org.jdiameter.api.Request)
*/
public Answer processRequest(Request request) {
RequestDelivery rd = new RequestDelivery();
rd.session = this;
rd.request = request;
super.scheduler.execute(rd);
return null;
}
/*
* (non-Javadoc)
* @see org.jdiameter.api.cxdx.ClientCxDxSession#sendLocationInformationRequest(org.jdiameter.api.cxdx.events.JLocationInfoRequest)
*/
public void sendLocationInformationRequest(JLocationInfoRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_MESSAGE, request, null);
}
/*
* (non-Javadoc)
* @see org.jdiameter.api.cxdx.ClientCxDxSession#sendMultimediaAuthRequest(org.jdiameter.api.cxdx.events.JMultimediaAuthRequest)
*/
public void sendMultimediaAuthRequest(JMultimediaAuthRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_MESSAGE, request, null);
}
/*
* (non-Javadoc)
* @see org.jdiameter.api.cxdx.ClientCxDxSession#sendServerAssignmentRequest(org.jdiameter.api.cxdx.events.JServerAssignmentRequest)
*/
public void sendServerAssignmentRequest(JServerAssignmentRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_MESSAGE, request, null);
}
/*
* (non-Javadoc)
* @see org.jdiameter.api.cxdx.ClientCxDxSession#sendUserAuthorizationRequest(org.jdiameter.api.cxdx.events.JUserAuthorizationRequest)
*/
public void sendUserAuthorizationRequest(JUserAuthorizationRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_MESSAGE, request, null);
}
/*
* (non-Javadoc)
* @see org.jdiameter.api.cxdx.ClientCxDxSession#sendPushProfileAnswer(org.jdiameter.api.cxdx.events.JPushProfileAnswer)
*/
public void sendPushProfileAnswer(JPushProfileAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_MESSAGE, null, answer);
}
/*
* (non-Javadoc)
* @see org.jdiameter.api.cxdx.ClientCxDxSession#sendRegistrationTerminationAnswer(org.jdiameter.api.cxdx.events.JRegistrationTerminationAnswer)
*/
public void sendRegistrationTerminationAnswer(JRegistrationTerminationAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_MESSAGE, null, answer);
}
/*
* (non-Javadoc)
* @see org.jdiameter.api.EventListener#receivedSuccessMessage(org.jdiameter.api.Message, org.jdiameter.api.Message)
*/
public void receivedSuccessMessage(Request request, Answer answer) {
AnswerDelivery rd = new AnswerDelivery();
rd.session = this;
rd.request = request;
rd.answer = answer;
super.scheduler.execute(rd);
}
/*
* (non-Javadoc)
*
* @see
* org.jdiameter.api.EventListener#timeoutExpired(org.jdiameter.api.Message)
*/
public void timeoutExpired(Request request) {
try {
handleEvent(new Event(Event.Type.TIMEOUT_EXPIRES, new AppRequestEventImpl(request), null));
}
catch (Exception e) {
logger.debug("Failed to process timeout message", e);
}
}
protected void send(Event.Type type, AppEvent request, AppEvent answer) throws InternalException {
try {
if (type != null) {
handleEvent(new Event(type, request, answer));
}
}
catch (Exception e) {
throw new InternalException(e);
}
}
public boolean handleEvent(StateEvent event) throws InternalException, OverloadException {
try {
sendAndStateLock.lock();
if (!super.session.isValid()) {
// FIXME: throw new InternalException("Generic session is not valid.");
return false;
}
final CxDxSessionState state = this.sessionData.getCxDxSessionState();
CxDxSessionState newState = null;
Event.Type eventType = (Type) event.getType();
switch (state) {
case IDLE:
switch (eventType) {
case RECEIVE_PPR:
//super.scheduler.schedule(new TimeoutTimerTask((Request) ((AppEvent) event.getData()).getMessage()), CxDxSession._TX_TIMEOUT, TimeUnit.MILLISECONDS);
this.sessionData.setBuffer( (Request) ((AppEvent) event.getData()).getMessage());
super.startMsgTimer();
newState = CxDxSessionState.MESSAGE_SENT_RECEIVED;
setState(newState);
listener.doPushProfileRequest(this, (JPushProfileRequest) event.getData());
break;
case RECEIVE_RTR:
//super.scheduler.schedule(new TimeoutTimerTask((Request) ((AppEvent) event.getData()).getMessage()), CxDxSession._TX_TIMEOUT, TimeUnit.MILLISECONDS);
newState = CxDxSessionState.MESSAGE_SENT_RECEIVED;
setState(newState);
this.sessionData.setBuffer( (Request) ((AppEvent) event.getData()).getMessage());
super.startMsgTimer();
listener.doRegistrationTerminationRequest(this, (JRegistrationTerminationRequest) event.getData());
break;
case SEND_MESSAGE:
newState = CxDxSessionState.MESSAGE_SENT_RECEIVED;
super.session.send(((AppEvent) event.getData()).getMessage(),this);
setState(newState); //FIXME: is this ok to be here?
break;
default:
logger.error("Invalid Event Type {} for Cx/Dx Client Session at state {}.", eventType, sessionData.getCxDxSessionState());
break;
}
break;
case MESSAGE_SENT_RECEIVED:
switch (eventType) {
case TIMEOUT_EXPIRES:
newState = CxDxSessionState.TIMEDOUT;
setState(newState);
break;
case SEND_MESSAGE:
// if (super.timeoutTaskFuture != null) {
// super.timeoutTaskFuture.cancel(false);
// super.timeoutTaskFuture = null;
// }
super.session.send(((AppEvent) event.getData()).getMessage(), this);
newState = CxDxSessionState.TERMINATED;
setState(newState);
break;
case RECEIVE_LIA:
newState = CxDxSessionState.TERMINATED;
setState(newState);
super.cancelMsgTimer();
listener.doLocationInformationAnswer(this, null, (JLocationInfoAnswer) event.getData());
break;
case RECEIVE_MAA:
newState = CxDxSessionState.TERMINATED;
setState(newState);
super.cancelMsgTimer();
listener.doMultimediaAuthAnswer(this, null, (JMultimediaAuthAnswer) event.getData());
break;
case RECEIVE_SAA:
newState = CxDxSessionState.TERMINATED;
setState(newState);
super.cancelMsgTimer();
listener.doServerAssignmentAnswer(this, null, (JServerAssignmentAnswer) event.getData());
break;
case RECEIVE_UAA:
newState = CxDxSessionState.TERMINATED;
setState(newState);
super.cancelMsgTimer();
listener.doUserAuthorizationAnswer(this, null, (JUserAuthorizationAnswer) event.getData());
break;
default:
throw new InternalException("Should not receive more messages after initial. Command: " + event.getData());
}
break;
case TERMINATED:
throw new InternalException("Cant receive message in state TERMINATED. Command: " + event.getData());
case TIMEDOUT:
throw new InternalException("Cant receive message in state TIMEDOUT. Command: " + event.getData());
default:
logger.error("Cx/Dx Client FSM in wrong state: {}", state);
break;
}
}
catch (Exception e) {
throw new InternalException(e);
}
finally {
sendAndStateLock.unlock();
}
return true;
}
@SuppressWarnings("unchecked")
protected void setState(CxDxSessionState newState) {
CxDxSessionState oldState = this.sessionData.getCxDxSessionState();
this.sessionData.setCxDxSessionState(newState);
for (StateChangeListener i : stateListeners) {
i.stateChanged(this,(Enum) oldState, (Enum) newState);
}
if (newState == CxDxSessionState.TERMINATED || newState == CxDxSessionState.TIMEDOUT) {
super.cancelMsgTimer();
this.release();
// if (super.timeoutTaskFuture != null) {
// timeoutTaskFuture.cancel(true);
// timeoutTaskFuture = null;
// }
}
}
/* (non-Javadoc)
* @see org.jdiameter.common.impl.app.AppSessionImpl#onTimer(java.lang.String)
*/
@Override
public void onTimer(String timerName) {
if(timerName.equals(CxDxSession.TIMER_NAME_MSG_TIMEOUT)) {
try{
sendAndStateLock.lock();
try {
handleEvent(new Event(Event.Type.TIMEOUT_EXPIRES, new AppRequestEventImpl(this.sessionData.getBuffer()), null));
}
catch (Exception e) {
logger.debug("Failure handling Timeout event.");
}
this.sessionData.setBuffer(null);
this.sessionData.setTsTimerId(null);
}
finally {
sendAndStateLock.unlock();
}
}
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + (int) (appId ^ (appId >>> 32));
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
CxDxClientSessionImpl other = (CxDxClientSessionImpl) obj;
if (appId != other.appId) {
return false;
}
return true;
}
@Override
public void release() {
if (isValid()) {
try {
sendAndStateLock.lock();
super.release();
}
catch (Exception e) {
logger.debug("Failed to release session", e);
}
finally {
sendAndStateLock.unlock();
}
}
else {
logger.debug("Trying to release an already invalid session, with Session ID '{}'", getSessionId());
}
}
private class RequestDelivery implements Runnable {
ClientCxDxSession session;
Request request;
public void run() {
try {
if (request.getCommandCode() == JRegistrationTerminationRequest.code) {
handleEvent(new Event(Event.Type.RECEIVE_RTR, messageFactory.createRegistrationTerminationRequest(request), null));
}
else if (request.getCommandCode() == JPushProfileRequest.code) {
handleEvent(new Event(Event.Type.RECEIVE_PPR, messageFactory.createPushProfileRequest(request), null));
}
else {
listener.doOtherEvent(session, new AppRequestEventImpl(request), null);
}
}
catch (Exception e) {
logger.debug("Failed to process request message", e);
}
}
}
private class AnswerDelivery implements Runnable {
ClientCxDxSession session;
Answer answer;
Request request;
public void run() {
try {
switch (answer.getCommandCode()) {
case JUserAuthorizationAnswer.code:
handleEvent(new Event(Event.Type.RECEIVE_UAA, null, messageFactory.createUserAuthorizationAnswer(answer)));
break;
case JServerAssignmentAnswer.code:
handleEvent(new Event(Event.Type.RECEIVE_SAA, null, messageFactory.createServerAssignmentAnswer(answer)));
break;
case JMultimediaAuthAnswer.code:
handleEvent(new Event(Event.Type.RECEIVE_MAA, null, messageFactory.createMultimediaAuthAnswer(answer)));
break;
case JLocationInfoAnswer.code:
handleEvent(new Event(Event.Type.RECEIVE_LIA,null, messageFactory.createLocationInfoAnswer(answer)));
break;
default:
listener.doOtherEvent(session, new AppRequestEventImpl(request), new AppAnswerEventImpl(answer));
break;
}
}
catch (Exception e) {
logger.debug("Failed to process success message", e);
}
}
}
}
| 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.jdiameter.client.impl.app.s6a;
import org.jdiameter.common.impl.app.s6a.S6aLocalSessionDataImpl;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ClientS6aSessionDataLocalImpl extends S6aLocalSessionDataImpl implements IClientS6aSessionData {
public ClientS6aSessionDataLocalImpl() {
}
}
| 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.jdiameter.client.impl.app.s6a;
import org.jdiameter.common.api.app.s6a.IS6aSessionData;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public interface IClientS6aSessionData extends IS6aSessionData {
}
| 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.jdiameter.client.impl.app.s6a;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.app.AppEvent;
import org.jdiameter.api.app.StateEvent;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class Event implements StateEvent {
enum Type {
SEND_MESSAGE,
TIMEOUT_EXPIRES,
RECEIVE_AIA,
RECEIVE_PUA,
RECEIVE_ULA,
RECEIVE_NOA,
RECEIVE_CLR,
RECEIVE_IDR,
RECEIVE_DSR,
RECEIVE_RSR;
}
AppEvent request;
AppEvent answer;
Type type;
Event(Type type, AppEvent request, AppEvent answer) {
this.type = type;
this.answer = answer;
this.request = request;
}
public <E> E encodeType(Class<E> eClass) {
return eClass == Type.class ? (E) type : null;
}
public Enum getType() {
return type;
}
public AppEvent getRequest() {
return request;
}
public AppEvent getAnswer() {
return answer;
}
public int compareTo(Object o) {
return 0;
}
public Object getData() {
return request != null ? request : answer;
}
public void setData(Object data) {
try {
if(((AppEvent) data).getMessage().isRequest()) {
request = (AppEvent) data;
}
else {
answer = (AppEvent) data;
}
}
catch (InternalException e) {
throw new IllegalArgumentException(e);
}
}
}
| 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.jdiameter.client.impl.app.s6a;
import org.jdiameter.api.Answer;
import org.jdiameter.api.EventListener;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.app.AppEvent;
import org.jdiameter.api.app.StateChangeListener;
import org.jdiameter.api.app.StateEvent;
import org.jdiameter.api.s6a.ClientS6aSession;
import org.jdiameter.api.s6a.ClientS6aSessionListener;
import org.jdiameter.api.s6a.events.JAuthenticationInformationAnswer;
import org.jdiameter.api.s6a.events.JAuthenticationInformationRequest;
import org.jdiameter.api.s6a.events.JCancelLocationAnswer;
import org.jdiameter.api.s6a.events.JCancelLocationRequest;
import org.jdiameter.api.s6a.events.JDeleteSubscriberDataAnswer;
import org.jdiameter.api.s6a.events.JDeleteSubscriberDataRequest;
import org.jdiameter.api.s6a.events.JInsertSubscriberDataAnswer;
import org.jdiameter.api.s6a.events.JInsertSubscriberDataRequest;
import org.jdiameter.api.s6a.events.JNotifyAnswer;
import org.jdiameter.api.s6a.events.JNotifyRequest;
import org.jdiameter.api.s6a.events.JPurgeUEAnswer;
import org.jdiameter.api.s6a.events.JPurgeUERequest;
import org.jdiameter.api.s6a.events.JResetAnswer;
import org.jdiameter.api.s6a.events.JResetRequest;
import org.jdiameter.api.s6a.events.JUpdateLocationAnswer;
import org.jdiameter.api.s6a.events.JUpdateLocationRequest;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.client.impl.app.s6a.S6aClientSessionImpl;
import org.jdiameter.client.impl.app.s6a.Event;
import org.jdiameter.client.impl.app.s6a.IClientS6aSessionData;
import org.jdiameter.client.impl.app.s6a.Event.Type;
import org.jdiameter.common.api.app.s6a.S6aSessionState;
import org.jdiameter.common.api.app.s6a.IS6aMessageFactory;
import org.jdiameter.common.impl.app.AppAnswerEventImpl;
import org.jdiameter.common.impl.app.AppRequestEventImpl;
import org.jdiameter.common.impl.app.s6a.S6aSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Diameter S6a Client Session implementation
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class S6aClientSessionImpl extends S6aSession implements ClientS6aSession, EventListener<Request, Answer>, NetworkReqListener {
private static final Logger logger = LoggerFactory.getLogger(S6aClientSessionImpl.class);
// Factories and Listeners --------------------------------------------------
private transient ClientS6aSessionListener listener;
protected long appId = -1;
protected IClientS6aSessionData sessionData;
public S6aClientSessionImpl(IClientS6aSessionData sessionData, IS6aMessageFactory fct, ISessionFactory sf, ClientS6aSessionListener lst) {
super(sf,sessionData);
if (lst == null) {
throw new IllegalArgumentException("Listener can not be null");
}
if (fct.getApplicationId() < 0) {
throw new IllegalArgumentException("ApplicationId can not be less than zero");
}
this.appId = fct.getApplicationId();
this.listener = lst;
super.messageFactory = fct;
this.sessionData = sessionData;
}
/*
* (non-Javadoc)
*
* @see org.jdiameter.api.app.StateMachine#getState(java.lang.Class)
*/
@SuppressWarnings("unchecked")
public <E> E getState(Class<E> stateType) {
return stateType == S6aSessionState.class ? (E) this.sessionData.getS6aSessionState() : null;
}
/*
* (non-Javadoc)
* @see org.jdiameter.api.NetworkReqListener#processRequest(org.jdiameter.api.Request)
*/
public Answer processRequest(Request request) {
RequestDelivery rd = new RequestDelivery();
rd.session = this;
rd.request = request;
super.scheduler.execute(rd);
return null;
}
public void sendAuthenticationInformationRequest(JAuthenticationInformationRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_MESSAGE, request, null);
}
public void sendPurgeUERequest(JPurgeUERequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_MESSAGE, request, null);
}
public void sendNotifyRequest(JNotifyRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_MESSAGE, request, null);
}
public void sendUpdateLocationRequest(JUpdateLocationRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_MESSAGE, request, null);
}
public void sendCancelLocationAnswer(JCancelLocationAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_MESSAGE, null, answer);
}
public void sendInsertSubscriberDataAnswer(JInsertSubscriberDataAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_MESSAGE, null, answer);
}
public void sendDeleteSubscriberDataAnswer(JDeleteSubscriberDataAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_MESSAGE, null, answer);
}
public void sendResetAnswer(JResetAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_MESSAGE, null, answer);
}
/*
* (non-Javadoc)
* @see org.jdiameter.api.EventListener#receivedSuccessMessage(org.jdiameter.api.Message, org.jdiameter.api.Message)
*/
public void receivedSuccessMessage(Request request, Answer answer) {
AnswerDelivery rd = new AnswerDelivery();
rd.session = this;
rd.request = request;
rd.answer = answer;
super.scheduler.execute(rd);
}
/*
* (non-Javadoc)
*
* @see
* org.jdiameter.api.EventListener#timeoutExpired(org.jdiameter.api.Message)
*/
public void timeoutExpired(Request request) {
try {
handleEvent(new Event(Event.Type.TIMEOUT_EXPIRES, new AppRequestEventImpl(request), null));
}
catch (Exception e) {
logger.debug("Failed to process timeout message", e);
}
}
protected void send(Event.Type type, AppEvent request, AppEvent answer) throws InternalException {
try {
if (type != null) {
handleEvent(new Event(type, request, answer));
}
}
catch (Exception e) {
throw new InternalException(e);
}
}
public boolean handleEvent(StateEvent event) throws InternalException, OverloadException {
try {
sendAndStateLock.lock();
if (!super.session.isValid()) {
// FIXME: throw new InternalException("Generic session is not valid.");
return false;
}
final S6aSessionState state = this.sessionData.getS6aSessionState();
S6aSessionState newState = null;
Event localEvent = (Event) event;
Event.Type eventType = (Type) event.getType();
switch (state) {
case IDLE:
switch (eventType) {
case RECEIVE_CLR:
this.sessionData.setBuffer( (Request) ((AppEvent) event.getData()).getMessage());
super.startMsgTimer();
newState = S6aSessionState.MESSAGE_SENT_RECEIVED;
setState(newState);
listener.doCancelLocationRequestEvent(this, (JCancelLocationRequest) event.getData());
break;
case RECEIVE_IDR:
newState = S6aSessionState.MESSAGE_SENT_RECEIVED;
setState(newState);
this.sessionData.setBuffer( (Request) ((AppEvent) event.getData()).getMessage());
super.startMsgTimer();
listener.doInsertSubscriberDataRequestEvent(this, (JInsertSubscriberDataRequest) event.getData());
break;
case RECEIVE_DSR:
newState = S6aSessionState.MESSAGE_SENT_RECEIVED;
setState(newState);
this.sessionData.setBuffer( (Request) ((AppEvent) event.getData()).getMessage());
super.startMsgTimer();
listener.doDeleteSubscriberDataRequestEvent(this, (JDeleteSubscriberDataRequest) event.getData());
break;
case RECEIVE_RSR:
newState = S6aSessionState.MESSAGE_SENT_RECEIVED;
setState(newState);
this.sessionData.setBuffer( (Request) ((AppEvent) event.getData()).getMessage());
super.startMsgTimer();
listener.doResetRequestEvent(this, (JResetRequest) event.getData());
break;
case SEND_MESSAGE:
newState = S6aSessionState.MESSAGE_SENT_RECEIVED;
super.session.send(((AppEvent) event.getData()).getMessage(),this);
setState(newState); //FIXME: is this ok to be here?
break;
default:
logger.error("Invalid Event Type {} for S6a Client Session at state {}.", eventType, sessionData.getS6aSessionState());
break;
}
break;
case MESSAGE_SENT_RECEIVED:
switch (eventType) {
case TIMEOUT_EXPIRES:
newState = S6aSessionState.TIMEDOUT;
setState(newState);
break;
case SEND_MESSAGE:
try {
super.session.send(((AppEvent) event.getData()).getMessage(), this);
}
finally {
newState = S6aSessionState.TERMINATED;
setState(newState);
}
break;
case RECEIVE_ULA:
newState = S6aSessionState.TERMINATED;
setState(newState);
super.cancelMsgTimer();
listener.doUpdateLocationAnswerEvent(this, (JUpdateLocationRequest) localEvent.getRequest(), (JUpdateLocationAnswer) localEvent.getAnswer());
break;
case RECEIVE_AIA:
newState = S6aSessionState.TERMINATED;
setState(newState);
super.cancelMsgTimer();
listener.doAuthenticationInformationAnswerEvent(this, (JAuthenticationInformationRequest) localEvent.getRequest(), (JAuthenticationInformationAnswer) localEvent.getAnswer());
break;
case RECEIVE_PUA:
newState = S6aSessionState.TERMINATED;
setState(newState);
super.cancelMsgTimer();
listener.doPurgeUEAnswerEvent(this, (JPurgeUERequest) localEvent.getRequest(), (JPurgeUEAnswer) localEvent.getAnswer());
break;
case RECEIVE_NOA:
newState = S6aSessionState.TERMINATED;
setState(newState);
super.cancelMsgTimer();
listener.doNotifyAnswerEvent(this, (JNotifyRequest) localEvent.getRequest(), (JNotifyAnswer) localEvent.getAnswer());
break;
default:
throw new InternalException("Unexpected/Unknown message received: " + event.getData());
}
break;
case TERMINATED:
throw new InternalException("Cant receive message in state TERMINATED. Command: " + event.getData());
case TIMEDOUT:
throw new InternalException("Cant receive message in state TIMEDOUT. Command: " + event.getData());
default:
logger.error("S6a Client FSM in wrong state: {}", state);
break;
}
}
catch (Exception e) {
throw new InternalException(e);
}
finally {
sendAndStateLock.unlock();
}
return true;
}
@SuppressWarnings("unchecked")
protected void setState(S6aSessionState newState) {
S6aSessionState oldState = this.sessionData.getS6aSessionState();
this.sessionData.setS6aSessionState(newState);
for (StateChangeListener i : stateListeners) {
i.stateChanged(this,(Enum) oldState, (Enum) newState);
}
if (newState == S6aSessionState.TERMINATED || newState == S6aSessionState.TIMEDOUT) {
super.cancelMsgTimer();
this.release();
}
}
/*
* (non-Javadoc)
* @see org.jdiameter.common.impl.app.AppSessionImpl#onTimer(java.lang.String)
*/
public void onTimer(String timerName) {
if(timerName.equals(S6aSession.TIMER_NAME_MSG_TIMEOUT)) {
try{
sendAndStateLock.lock();
try {
handleEvent(new Event(Event.Type.TIMEOUT_EXPIRES, new AppRequestEventImpl(this.sessionData.getBuffer()), null));
}
catch (Exception e) {
logger.debug("Failure handling Timeout event.");
}
this.sessionData.setBuffer(null);
this.sessionData.setTsTimerId(null);
}
finally {
sendAndStateLock.unlock();
}
}
}
/*
* (non-Javadoc)
* @see org.jdiameter.common.impl.app.s6a.S6aSession#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + (int) (appId ^ (appId >>> 32));
return result;
}
/*
* (non-Javadoc)
* @see org.jdiameter.common.impl.app.s6a.S6aSession#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
S6aClientSessionImpl other = (S6aClientSessionImpl) obj;
if (appId != other.appId) {
return false;
}
return true;
}
@Override
public void release() {
if (isValid()) {
try {
sendAndStateLock.lock();
super.release();
}
catch (Exception e) {
logger.debug("Failed to release session", e);
}
finally {
sendAndStateLock.unlock();
}
}
else {
logger.debug("Trying to release an already invalid session, with Session ID '{}'", getSessionId());
}
}
private class RequestDelivery implements Runnable {
ClientS6aSession session;
Request request;
public void run() {
try {
switch (request.getCommandCode()) {
case JCancelLocationRequest.code:
handleEvent(new Event(Event.Type.RECEIVE_CLR, messageFactory.createCancelLocationRequest(request), null));
break;
case JInsertSubscriberDataRequest.code:
handleEvent(new Event(Event.Type.RECEIVE_IDR, messageFactory.createInsertSubscriberDataRequest(request), null));
break;
case JDeleteSubscriberDataRequest.code:
handleEvent(new Event(Event.Type.RECEIVE_DSR, messageFactory.createDeleteSubscriberDataRequest(request), null));
break;
case JResetRequest.code:
handleEvent(new Event(Event.Type.RECEIVE_RSR, messageFactory.createResetRequest(request), null));
break;
default:
listener.doOtherEvent(session, new AppRequestEventImpl(request), null);
break;
}
}
catch (Exception e) {
logger.debug("Failed to process request message", e);
}
}
}
private class AnswerDelivery implements Runnable {
ClientS6aSession session;
Answer answer;
Request request;
public void run() {
try {
switch (answer.getCommandCode()) {
case JUpdateLocationAnswer.code:
handleEvent(new Event(Event.Type.RECEIVE_ULA, messageFactory.createUpdateLocationRequest(request), messageFactory.createUpdateLocationAnswer(answer)));
break;
case JAuthenticationInformationAnswer.code:
handleEvent(new Event(Event.Type.RECEIVE_AIA, messageFactory.createAuthenticationInformationRequest(request), messageFactory.createAuthenticationInformationAnswer(answer)));
break;
case JPurgeUEAnswer.code:
handleEvent(new Event(Event.Type.RECEIVE_PUA, messageFactory.createPurgeUERequest(request), messageFactory.createPurgeUEAnswer(answer)));
break;
case JNotifyAnswer.code:
handleEvent(new Event(Event.Type.RECEIVE_NOA, messageFactory.createNotifyRequest(request), messageFactory.createNotifyAnswer(answer)));
break;
default:
listener.doOtherEvent(session, new AppRequestEventImpl(request), new AppAnswerEventImpl(answer));
break;
}
}
catch (Exception e) {
logger.debug("Failed to process success message", e);
}
}
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.jdiameter.client.impl.app.gx;
import java.io.Serializable;
import org.jdiameter.api.Request;
import org.jdiameter.common.api.app.gx.ClientGxSessionState;
import org.jdiameter.common.api.app.gx.IGxSessionData;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public interface IClientGxSessionData extends IGxSessionData {
public boolean isEventBased();
public void setEventBased(boolean b);
public boolean isRequestTypeSet();
public void setRequestTypeSet(boolean b);
public ClientGxSessionState getClientGxSessionState();
public void setClientGxSessionState(ClientGxSessionState state);
public Serializable getTxTimerId();
public void setTxTimerId(Serializable txTimerId);
public Request getTxTimerRequest();
public void setTxTimerRequest(Request txTimerRequest);
public Request getBuffer();
public void setBuffer(Request buffer);
public int getGatheredRequestedAction();
public void setGatheredRequestedAction(int gatheredRequestedAction);
public int getGatheredCCFH();
public void setGatheredCCFH(int gatheredCCFH);
public int getGatheredDDFH();
public void setGatheredDDFH(int gatheredDDFH);
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.jdiameter.client.impl.app.gx;
import java.io.Serializable;
import org.jdiameter.api.Request;
import org.jdiameter.common.api.app.AppSessionDataLocalImpl;
import org.jdiameter.common.api.app.gx.ClientGxSessionState;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ClientGxSessionDataLocalImpl extends AppSessionDataLocalImpl implements IClientGxSessionData {
protected boolean isEventBased = true;
protected boolean requestTypeSet = false;
protected ClientGxSessionState state = ClientGxSessionState.IDLE;
protected Serializable txTimerId;
//protected JCreditControlRequest txTimerRequest;
protected Request txTimerRequest;
// Event Based Buffer
//protected Message buffer = null;
protected Request buffer;
protected int gatheredRequestedAction = NON_INITIALIZED;
protected int gatheredCCFH = NON_INITIALIZED;
protected int gatheredDDFH = NON_INITIALIZED;
/**
*
*/
public ClientGxSessionDataLocalImpl() {
}
public boolean isEventBased() {
return isEventBased;
}
public void setEventBased(boolean isEventBased) {
this.isEventBased = isEventBased;
}
public boolean isRequestTypeSet() {
return requestTypeSet;
}
public void setRequestTypeSet(boolean requestTypeSet) {
this.requestTypeSet = requestTypeSet;
}
public ClientGxSessionState getClientGxSessionState() {
return state;
}
public void setClientGxSessionState(ClientGxSessionState state) {
this.state = state;
}
public Serializable getTxTimerId() {
return txTimerId;
}
public void setTxTimerId(Serializable txTimerId) {
this.txTimerId = txTimerId;
}
public Request getTxTimerRequest() {
return txTimerRequest;
}
public void setTxTimerRequest(Request txTimerRequest) {
this.txTimerRequest = txTimerRequest;
}
public Request getBuffer() {
return buffer;
}
public void setBuffer(Request buffer) {
this.buffer = buffer;
}
public int getGatheredRequestedAction() {
return gatheredRequestedAction;
}
public void setGatheredRequestedAction(int gatheredRequestedAction) {
this.gatheredRequestedAction = gatheredRequestedAction;
}
public int getGatheredCCFH() {
return gatheredCCFH;
}
public void setGatheredCCFH(int gatheredCCFH) {
this.gatheredCCFH = gatheredCCFH;
}
public int getGatheredDDFH() {
return gatheredDDFH;
}
public void setGatheredDDFH(int gatheredDDFH) {
this.gatheredDDFH = gatheredDDFH;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.jdiameter.client.impl.app.gx;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.app.AppAnswerEvent;
import org.jdiameter.api.app.AppEvent;
import org.jdiameter.api.app.AppRequestEvent;
import org.jdiameter.api.app.StateEvent;
import org.jdiameter.api.gx.events.GxCreditControlAnswer;
import org.jdiameter.api.gx.events.GxCreditControlRequest;
/**
* @author <a href="mailto:carl-magnus.bjorkell@emblacom.com"> Carl-Magnus Björkell </a>
*/
public class Event implements StateEvent {
public enum Type {
SEND_INITIAL_REQUEST, RECEIVED_INITIAL_ANSWER,
SEND_UPDATE_REQUEST, RECEIVED_UPDATE_ANSWER,
SEND_TERMINATE_REQUEST, RECEIVED_TERMINATED_ANSWER,
RECEIVED_RAR, SEND_RAA, Tx_TIMER_FIRED,
SEND_EVENT_REQUEST, RECEIVE_EVENT_ANSWER;
}
Type type;
AppRequestEvent request;
AppAnswerEvent answer;
Event(Type type) {
this.type = type;
}
Event(Type type, AppRequestEvent request, AppAnswerEvent answer) {
this.type = type;
this.answer = answer;
this.request = request;
}
Event(boolean isRequest, GxCreditControlRequest request, GxCreditControlAnswer answer) throws AvpDataException {
this.answer = answer;
this.request = request;
if (isRequest) {
switch (request.getRequestTypeAVPValue()) {
case 1:
type = Type.SEND_INITIAL_REQUEST;
break;
case 2:
type = Type.SEND_UPDATE_REQUEST;
break;
case 3:
type = Type.SEND_TERMINATE_REQUEST;
break;
case 4:
type = Type.SEND_EVENT_REQUEST;
break;
default:
throw new RuntimeException("Wrong CC-Request-Type value: " + request.getRequestTypeAVPValue());
}
} else {
switch (answer.getRequestTypeAVPValue()) {
case 1:
type = Type.RECEIVED_INITIAL_ANSWER;
break;
case 2:
type = Type.RECEIVED_UPDATE_ANSWER;
break;
case 3:
type = Type.RECEIVED_TERMINATED_ANSWER;
break;
case 4:
type = Type.RECEIVE_EVENT_ANSWER;
break;
default:
throw new RuntimeException("Wrong CC-Request-Type value: " + answer.getRequestTypeAVPValue());
}
}
}
public Enum getType() {
return type;
}
public int compareTo(Object o) {
return 0;
}
public Object getData() {
return request != null ? request : answer;
}
public void setData(Object data) {
// FIXME: What should we do here?! Is it request or answer?
}
public AppEvent getRequest() {
return request;
}
public AppEvent getAnswer() {
return answer;
}
public <E> E encodeType(Class<E> eClass) {
return eClass == Event.Type.class ? (E) type : null;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.jdiameter.client.impl.app.gx;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.jdiameter.api.Answer;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.EventListener;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Message;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.app.AppAnswerEvent;
import org.jdiameter.api.app.AppEvent;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.app.StateChangeListener;
import org.jdiameter.api.app.StateEvent;
import org.jdiameter.api.gx.events.GxReAuthAnswer;
import org.jdiameter.api.gx.events.GxReAuthRequest;
import org.jdiameter.api.gx.ClientGxSession;
import org.jdiameter.api.gx.ClientGxSessionListener;
import org.jdiameter.api.gx.events.GxCreditControlAnswer;
import org.jdiameter.api.gx.events.GxCreditControlRequest;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.client.api.parser.IMessageParser;
import org.jdiameter.client.impl.app.gx.Event.Type;
import org.jdiameter.common.api.app.IAppSessionState;
import org.jdiameter.common.api.app.gx.ClientGxSessionState;
import org.jdiameter.common.api.app.gx.IClientGxSessionContext;
import org.jdiameter.common.api.app.gx.IGxMessageFactory;
import org.jdiameter.common.impl.app.AppAnswerEventImpl;
import org.jdiameter.common.impl.app.AppRequestEventImpl;
import org.jdiameter.common.impl.app.gx.GxReAuthAnswerImpl;
import org.jdiameter.common.impl.app.gx.AppGxSessionImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Client Credit-Control Application session implementation
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:carl-magnus.bjorkell@emblacom.com"> Carl-Magnus Björkell </a>
*/
public class ClientGxSessionImpl extends AppGxSessionImpl implements ClientGxSession, NetworkReqListener, EventListener<Request, Answer> {
private static final Logger logger = LoggerFactory.getLogger(ClientGxSessionImpl.class);
protected IClientGxSessionData sessionData;
// Session State Handling ---------------------------------------------------
protected Lock sendAndStateLock = new ReentrantLock();
// Factories and Listeners --------------------------------------------------
protected IGxMessageFactory factory;
protected ClientGxSessionListener listener;
protected IClientGxSessionContext context;
protected IMessageParser parser;
// Tx Timer -----------------------------------------------------------------
protected final static String TX_TIMER_NAME = "Gx_CLIENT_TX_TIMER";
protected static final long TX_TIMER_DEFAULT_VALUE = 30 * 60 * 1000; // miliseconds
protected long[] authAppIds = new long[]{4};
protected static final int CCFH_TERMINATE = 0;
protected static final int CCFH_CONTINUE = 1;
protected static final int CCFH_RETRY_AND_TERMINATE = 2;
private static final int DDFH_TERMINATE_OR_BUFFER = 0;
private static final int DDFH_CONTINUE = 1;
// CC-Request-Type Values ---------------------------------------------------
private static final int DIRECT_DEBITING = 0;
private static final int REFUND_ACCOUNT = 1;
private static final int CHECK_BALANCE = 2;
private static final int PRICE_ENQUIRY = 3;
private static final int EVENT_REQUEST = 4;
// Error Codes --------------------------------------------------------------
private static final long END_USER_SERVICE_DENIED = 4010;
private static final long CREDIT_CONTROL_NOT_APPLICABLE = 4011;
private static final long USER_UNKNOWN = 5030;
private static final long DIAMETER_UNABLE_TO_DELIVER = 3002L;
private static final long DIAMETER_TOO_BUSY = 3004L;
private static final long DIAMETER_LOOP_DETECTED = 3005L;
protected static final Set<Long> temporaryErrorCodes;
static {
HashSet<Long> tmp = new HashSet<Long>();
tmp.add(DIAMETER_UNABLE_TO_DELIVER);
tmp.add(DIAMETER_TOO_BUSY);
tmp.add(DIAMETER_LOOP_DETECTED);
temporaryErrorCodes = Collections.unmodifiableSet(tmp);
}
// Session Based Queue
protected ArrayList<Event> eventQueue = new ArrayList<Event>();
public ClientGxSessionImpl(IClientGxSessionData sessionData, IGxMessageFactory fct, ISessionFactory sf, ClientGxSessionListener lst, IClientGxSessionContext ctx,
StateChangeListener<AppSession> stLst) {
super(sf, sessionData);
if (lst == null) {
throw new IllegalArgumentException("Listener can not be null");
}
if (fct.getApplicationIds() == null) {
throw new IllegalArgumentException("ApplicationId can not be less than zero");
}
this.context = (IClientGxSessionContext) ctx;
this.authAppIds = fct.getApplicationIds();
this.listener = lst;
this.factory = fct;
IContainer icontainer = sf.getContainer();
this.parser = icontainer.getAssemblerFacility().getComponentInstance(IMessageParser.class);
this.sessionData = sessionData;
super.addStateChangeNotification(stLst);
}
protected int getLocalCCFH() {
return this.sessionData.getGatheredCCFH() >= 0 ? this.sessionData.getGatheredCCFH() : context.getDefaultCCFHValue();
}
protected int getLocalDDFH() {
return this.sessionData.getGatheredDDFH() >= 0 ? this.sessionData.getGatheredDDFH() : context.getDefaultDDFHValue();
}
public void sendCreditControlRequest(GxCreditControlRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
try {
extractFHAVPs(request, null);
this.handleEvent(new Event(true, request, null));
} catch (AvpDataException e) {
throw new InternalException(e);
}
}
public void sendGxReAuthAnswer(GxReAuthAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
this.handleEvent(new Event(Event.Type.SEND_RAA, null, answer));
}
public boolean isStateless() {
return false;
}
public boolean isEventBased() {
return this.sessionData.isEventBased();
}
@SuppressWarnings("unchecked")
public <E> E getState(Class<E> stateType) {
return stateType == ClientGxSessionState.class ? (E) this.sessionData.getClientGxSessionState() : null;
}
public boolean handleEvent(StateEvent event) throws InternalException, OverloadException {
return this.isEventBased() ? handleEventForEventBased(event) : handleEventForSessionBased(event);
}
protected boolean handleEventForEventBased(StateEvent event) throws InternalException, OverloadException {
try {
sendAndStateLock.lock();
final ClientGxSessionState state = this.sessionData.getClientGxSessionState();
Event localEvent = (Event) event;
Event.Type eventType = (Type) localEvent.getType();
switch (state) {
case IDLE:
switch (eventType) {
case SEND_EVENT_REQUEST:
// Current State: IDLE
// Event: Client or device requests a one-time service
// Action: Send CC event request, start Tx
// New State: PENDING_E
startTx((GxCreditControlRequest) localEvent.getRequest());
setState(ClientGxSessionState.PENDING_EVENT);
try {
dispatchEvent(localEvent.getRequest());
} catch (Exception e) {
// This handles failure to send in PendingI state in FSM table
logger.debug("Failure handling send event request", e);
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
case PENDING_EVENT:
switch (eventType) {
case RECEIVE_EVENT_ANSWER:
AppAnswerEvent answer = (AppAnswerEvent) localEvent.getAnswer();
try {
long resultCode = answer.getResultCodeAvp().getUnsigned32();
if (isSuccess(resultCode)) {
// Current State: PENDING_E
// Event: Successful CC event answer received
// Action: Grant service to end user
// New State: IDLE
setState(ClientGxSessionState.IDLE, false);
}
if (isProvisional(resultCode) || isFailure(resultCode)) {
handleFailureMessage((GxCreditControlAnswer) answer, (GxCreditControlRequest) localEvent.getRequest(), eventType);
}
deliverGxAnswer((GxCreditControlRequest) localEvent.getRequest(), (GxCreditControlAnswer) localEvent.getAnswer());
} catch (AvpDataException e) {
logger.debug("Failure handling received answer event", e);
setState(ClientGxSessionState.IDLE, false);
}
break;
case Tx_TIMER_FIRED:
handleTxExpires(localEvent.getRequest().getMessage());
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
case PENDING_BUFFERED:
switch (eventType) {
case RECEIVE_EVENT_ANSWER:
// Current State: PENDING_B
// Event: Successful CC answer received
// Action: Delete request
// New State: IDLE
setState(ClientGxSessionState.IDLE, false);
this.sessionData.setBuffer(null);
deliverGxAnswer((GxCreditControlRequest) localEvent.getRequest(), (GxCreditControlAnswer) localEvent.getAnswer());
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
dispatch();
return true;
} catch (Exception e) {
throw new InternalException(e);
} finally {
sendAndStateLock.unlock();
}
}
protected boolean handleEventForSessionBased(StateEvent event) throws InternalException, OverloadException {
try {
sendAndStateLock.lock();
final ClientGxSessionState state = this.sessionData.getClientGxSessionState();
final Event localEvent = (Event) event;
final Event.Type eventType = (Type) localEvent.getType();
switch (state) {
case IDLE:
switch (eventType) {
case SEND_INITIAL_REQUEST:
// Current State: IDLE
// Event: Client or device requests access/service
// Action: Send CC initial request, start Tx
// New State: PENDING_I
startTx((GxCreditControlRequest) localEvent.getRequest());
setState(ClientGxSessionState.PENDING_INITIAL);
try {
dispatchEvent(localEvent.getRequest());
} catch (Exception e) {
// This handles failure to send in PendingI state in FSM table
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
case PENDING_INITIAL:
AppAnswerEvent answer = (AppAnswerEvent) localEvent.getAnswer();
switch (eventType) {
case RECEIVED_INITIAL_ANSWER:
long resultCode = answer.getResultCodeAvp().getUnsigned32();
if (isSuccess(resultCode)) {
// Current State: PENDING_I
// Event: Successful CC initial answer received
// Action: Stop Tx
// New State: OPEN
stopTx();
setState(ClientGxSessionState.OPEN);
} else if (isProvisional(resultCode) || isFailure(resultCode)) {
handleFailureMessage((GxCreditControlAnswer) answer, (GxCreditControlRequest) localEvent.getRequest(), eventType);
}
deliverGxAnswer((GxCreditControlRequest) localEvent.getRequest(), (GxCreditControlAnswer) localEvent.getAnswer());
break;
case Tx_TIMER_FIRED:
handleTxExpires(localEvent.getRequest().getMessage());
break;
case SEND_UPDATE_REQUEST:
case SEND_TERMINATE_REQUEST:
// Current State: PENDING_I
// Event: User service terminated
// Action: Queue termination event
// New State: PENDING_I
// Current State: PENDING_I
// Event: Change in rating condition
// Action: Queue changed rating condition event
// New State: PENDING_I
eventQueue.add(localEvent);
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
case OPEN:
switch (eventType) {
case SEND_UPDATE_REQUEST:
// Current State: OPEN
// Event: Granted unit elapses and no final unit indication received
// Action: Send CC update request, start Tx
// New State: PENDING_U
// Current State: OPEN
// Event: Change in rating condition in queue
// Action: Send CC update request, start Tx
// New State: PENDING_U
// Current State: OPEN
// Event: Change in rating condition or Validity-Time elapses
// Action: Send CC update request, start Tx
// New State: PENDING_U
// Current State: OPEN
// Event: RAR received
// Action: Send RAA followed by CC update request, start Tx
// New State: PENDING_U
startTx((GxCreditControlRequest) localEvent.getRequest());
setState(ClientGxSessionState.PENDING_UPDATE);
try {
dispatchEvent(localEvent.getRequest());
} catch (Exception e) {
// This handles failure to send in PendingI state in FSM table
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
case SEND_TERMINATE_REQUEST:
// Current State: OPEN
// Event: Granted unit elapses and final unit action equal to TERMINATE received
// Action: Terminate end user�s service, send CC termination request
// New State: PENDING_T
// Current State: OPEN
// Event: Service terminated in queue
// Action: Send CC termination request
// New State: PENDING_T
// Current State: OPEN
// Event: User service terminated
// Action: Send CC termination request
// New State: PENDING_T
setState(ClientGxSessionState.PENDING_TERMINATION);
try {
dispatchEvent(localEvent.getRequest());
} catch (Exception e) {
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
case RECEIVED_RAR:
deliverRAR((GxReAuthRequest) localEvent.getRequest());
break;
case SEND_RAA:
try {
dispatchEvent(localEvent.getAnswer());
} catch (Exception e) {
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
case PENDING_UPDATE:
answer = (AppAnswerEvent) localEvent.getAnswer();
switch (eventType) {
case RECEIVED_UPDATE_ANSWER:
long resultCode = answer.getResultCodeAvp().getUnsigned32();
if (isSuccess(resultCode)) {
// Current State: PENDING_U
// Event: Successful CC update answer received
// Action: Stop Tx
// New State: OPEN
stopTx();
setState(ClientGxSessionState.OPEN);
} else if (isProvisional(resultCode) || isFailure(resultCode)) {
handleFailureMessage((GxCreditControlAnswer) answer, (GxCreditControlRequest) localEvent.getRequest(), eventType);
}
deliverGxAnswer((GxCreditControlRequest) localEvent.getRequest(), (GxCreditControlAnswer) localEvent.getAnswer());
break;
case Tx_TIMER_FIRED:
handleTxExpires(localEvent.getRequest().getMessage());
break;
case SEND_UPDATE_REQUEST:
case SEND_TERMINATE_REQUEST:
// Current State: PENDING_U
// Event: User service terminated
// Action: Queue termination event
// New State: PENDING_U
// Current State: PENDING_U
// Event: Change in rating condition
// Action: Queue changed rating condition event
// New State: PENDING_U
eventQueue.add(localEvent);
break;
case RECEIVED_RAR:
deliverRAR((GxReAuthRequest) localEvent.getRequest());
break;
case SEND_RAA:
// Current State: PENDING_U
// Event: RAR received
// Action: Send RAA
// New State: PENDING_U
try {
dispatchEvent(localEvent.getAnswer());
} catch (Exception e) {
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
}
break;
case PENDING_TERMINATION:
switch (eventType) {
case SEND_UPDATE_REQUEST:
try {
// Current State: PENDING_T
// Event: Change in rating condition
// Action: -
// New State: PENDING_T
dispatchEvent(localEvent.getRequest());
// No transition
} catch (Exception e) {
// This handles failure to send in PendingI state in FSM table
// handleSendFailure(e, eventType);
}
break;
case RECEIVED_TERMINATED_ANSWER:
// Current State: PENDING_T
// Event: Successful CC termination answer received
// Action: -
// New State: IDLE
// Current State: PENDING_T
// Event: Failure to send, temporary error, or failed answer
// Action: -
// New State: IDLE
//FIXME: Alex broke this, setting back "true" ?
//setState(ClientGxSessionState.IDLE, false);
deliverGxAnswer((GxCreditControlRequest) localEvent.getRequest(), (GxCreditControlAnswer) localEvent.getAnswer());
setState(ClientGxSessionState.IDLE, true);
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
default:
// any other state is bad
setState(ClientGxSessionState.IDLE, true);
}
dispatch();
return true;
} catch (Exception e) {
throw new InternalException(e);
} finally {
sendAndStateLock.unlock();
}
}
public Answer processRequest(Request request) {
RequestDelivery rd = new RequestDelivery();
rd.session = this;
rd.request = request;
super.scheduler.execute(rd);
return null;
}
public void receivedSuccessMessage(Request request, Answer answer) {
AnswerDelivery ad = new AnswerDelivery();
ad.session = this;
ad.request = request;
ad.answer = answer;
super.scheduler.execute(ad);
}
public void timeoutExpired(Request request) {
if (request.getCommandCode() == GxCreditControlAnswer.code) {
try {
sendAndStateLock.lock();
handleSendFailure(null, null, request);
}
catch (Exception e) {
logger.debug("Failure processing timeout message for request", e);
}
finally {
sendAndStateLock.unlock();
}
}
}
protected void startTx(GxCreditControlRequest request) {
long txTimerValue = context.getDefaultTxTimerValue();
if (txTimerValue < 0) {
txTimerValue = TX_TIMER_DEFAULT_VALUE;
}
stopTx();
logger.debug("Scheduling TX Timer {}", txTimerValue);
//this.txFuture = scheduler.schedule(new TxTimerTask(this, request), txTimerValue, TimeUnit.SECONDS);
try {
this.sessionData.setTxTimerRequest((Request) request.getMessage());
} catch (Exception e) {
throw new IllegalArgumentException("Failed to store request.", e);
}
this.sessionData.setTxTimerId(this.timerFacility.schedule(this.getSessionId(), TX_TIMER_NAME, TX_TIMER_DEFAULT_VALUE));
}
protected void stopTx() {
Serializable txTimerId = this.sessionData.getTxTimerId();
if (txTimerId != null) {
this.timerFacility.cancel(txTimerId);
this.sessionData.setTxTimerRequest(null);
this.sessionData.setTxTimerId(null);
}
}
/* (non-Javadoc)
* @see org.jdiameter.common.impl.app.AppSessionImpl#onTimer(java.lang.String)
*/
@Override
public void onTimer(String timerName) {
if (timerName.equals(TX_TIMER_NAME)) {
new TxTimerTask(this, this.sessionData.getTxTimerRequest()).run();
}
}
protected void setState(ClientGxSessionState newState) {
setState(newState, true);
}
@SuppressWarnings("unchecked")
protected void setState(ClientGxSessionState newState, boolean release) {
try {
IAppSessionState oldState = this.sessionData.getClientGxSessionState();
this.sessionData.setClientGxSessionState(newState);
for (StateChangeListener i : stateListeners) {
i.stateChanged(this, (Enum) oldState, (Enum) newState);
}
if (newState == ClientGxSessionState.IDLE) {
if (release) {
this.release();
}
stopTx();
}
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("Failure switching to state " + this.sessionData.getClientGxSessionState() + " (release=" + release + ")", e);
}
}
}
@Override
public void release() {
if (isValid()) {
try {
this.sendAndStateLock.lock();
this.stopTx();
super.release();
}
catch (Exception e) {
logger.debug("Failed to release session", e);
}
finally {
sendAndStateLock.unlock();
}
}
else {
logger.debug("Trying to release an already invalid session, with Session ID '{}'", getSessionId());
}
}
protected void handleSendFailure(Exception e, Event.Type eventType, Message request) throws Exception {
logger.debug("Failed to send message, type: {} message: {}, failure: {}", new Object[]{eventType, request, e != null ? e.getLocalizedMessage() : ""});
try {
// Event Based ----------------------------------------------------------
final ClientGxSessionState state = this.sessionData.getClientGxSessionState();
if (isEventBased()) {
final int gatheredRequestedAction = sessionData.getGatheredRequestedAction();
switch (state) {
case PENDING_EVENT:
if (gatheredRequestedAction == CHECK_BALANCE || gatheredRequestedAction == PRICE_ENQUIRY) {
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action CHECK_BALANCE or PRICE_ENQUIRY
// Action: Indicate service error
// New State: IDLE
setState(ClientGxSessionState.IDLE);
context.indicateServiceError(this);
} else if (gatheredRequestedAction == DIRECT_DEBITING) {
switch (getLocalDDFH()) {
case DDFH_TERMINATE_OR_BUFFER:
// Current State: PENDING_E
// Event: Failure to send; request action DIRECT_DEBITING; DDFH equal to TERMINATE_OR_BUFFER
// Action: Store request with T-flag
// New State: IDLE
request.setReTransmitted(true);
this.sessionData.setBuffer((Request) request);
setState(ClientGxSessionState.IDLE, false);
break;
case DDFH_CONTINUE:
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action DIRECT_DEBITING; DDFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnDeliverFailure(this, request);
break;
default:
logger.warn("Invalid Direct-Debiting-Failure-Handling AVP value {}", getLocalDDFH());
}
} else if (gatheredRequestedAction == REFUND_ACCOUNT) {
// Current State: PENDING_E
// Event: Failure to send or Tx expired; requested action REFUND_ACCOUNT
// Action: Store request with T-flag
// New State: IDLE
setState(ClientGxSessionState.IDLE, false);
request.setReTransmitted(true);
this.sessionData.setBuffer((Request) request);
} else {
logger.warn("Invalid Requested-Action AVP value {}", gatheredRequestedAction);
}
break;
case PENDING_BUFFERED:
// Current State: PENDING_B
// Event: Failure to send or temporary error
// Action: -
// New State: IDLE
setState(ClientGxSessionState.IDLE, false);
this.sessionData.setBuffer(null); // FIXME: Action does not mention, but ...
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
} // Session Based --------------------------------------------------------
else {
switch (getLocalCCFH()) {
case CCFH_CONTINUE:
// Current State: PENDING_I
// Event: Failure to send, or temporary error and CCFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
// Current State: PENDING_U
// Event: Failure to send, or temporary error and CCFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
setState(ClientGxSessionState.IDLE, false);
this.context.grantAccessOnDeliverFailure(this, request);
break;
default:
// Current State: PENDING_I
// Event: Failure to send, or temporary error and CCFH equal to TERMINATE or to RETRY_AND_TERMINATE
// Action: Terminate end user�s service
// New State: IDLE
// Current State: PENDING_U
// Event: Failure to send, or temporary error and CCFH equal to TERMINATE or to RETRY_AND_TERMINATE
// Action: Terminate end user�s service
// New State: IDLE
this.context.denyAccessOnDeliverFailure(this, request);
setState(ClientGxSessionState.IDLE, true);
break;
}
}
} finally {
dispatch();
}
}
protected void handleFailureMessage(final GxCreditControlAnswer event, final GxCreditControlRequest request, final Event.Type eventType) {
try {
// Event Based ----------------------------------------------------------
final ClientGxSessionState state = this.sessionData.getClientGxSessionState();
final Serializable txTimerId = sessionData.getTxTimerId();
final long resultCode = event.getResultCodeAvp().getUnsigned32();
if (isEventBased()) {
final int gatheredRequestedAction = sessionData.getGatheredRequestedAction();
switch (state) {
case PENDING_EVENT:
if (resultCode == END_USER_SERVICE_DENIED || resultCode == USER_UNKNOWN) {
if (sessionData.getTxTimerId() != null) {
// Current State: PENDING_E
// Event: CC event answer received with result code END_USER_SERVICE_DENIED or USER_UNKNOWN and Tx running
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
deliverGxAnswer(request, event);
setState(ClientGxSessionState.IDLE);
} else if (gatheredRequestedAction == DIRECT_DEBITING && txTimerId == null) {
// Current State: PENDING_E
// Event: Failed answer or answer received with result code END_USER_SERVICE DENIED or USER_UNKNOWN; requested action DIRECT_DEBITING; Tx expired
// Action: -
// New State: IDLE
setState(ClientGxSessionState.IDLE);
}
} else if (resultCode == CREDIT_CONTROL_NOT_APPLICABLE && gatheredRequestedAction == DIRECT_DEBITING) {
// Current State: PENDING_E
// Event: CC event answer received with result code CREDIT_CONTROL_NOT_APPLICABLE; requested action DIRECT_DEBITING
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
deliverGxAnswer(request, event);
setState(ClientGxSessionState.IDLE);
} else if (temporaryErrorCodes.contains(resultCode)) {
if (gatheredRequestedAction == CHECK_BALANCE || gatheredRequestedAction == PRICE_ENQUIRY) {
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action CHECK_BALANCE or PRICE_ENQUIRY
// Action: Indicate service error
// New State: IDLE
context.indicateServiceError(this);
deliverGxAnswer(request, event);
setState(ClientGxSessionState.IDLE);
} else if (gatheredRequestedAction == DIRECT_DEBITING) {
if (getLocalDDFH() == DDFH_CONTINUE) {
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action DIRECT_DEBITING; DDFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
deliverGxAnswer(request, event);
setState(ClientGxSessionState.IDLE);
} else if (getLocalDDFH() == DDFH_TERMINATE_OR_BUFFER && txTimerId != null) {
// Current State: PENDING_E
// Event: Failed CC event answer received or temporary error; requested action DIRECT_DEBITING; DDFH equal to TERMINATE_OR_BUFFER and Tx running
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
deliverGxAnswer(request, event);
setState(ClientGxSessionState.IDLE);
}
} else if (gatheredRequestedAction == REFUND_ACCOUNT) {
// Current State: PENDING_E
// Event: Temporary error, and requested action REFUND_ACCOUNT
// Action: Store request
// New State: IDLE
this.sessionData.setBuffer((Request) request.getMessage());
setState(ClientGxSessionState.IDLE, false);
} else {
logger.warn("Invalid combination for Ro Client FSM: State {}, Result-Code {}, Requested-Action {}, DDFH {}, Tx {}", new Object[]{state, resultCode, gatheredRequestedAction, getLocalDDFH(), txTimerId});
}
} else { // Failure
if (gatheredRequestedAction == CHECK_BALANCE || gatheredRequestedAction == PRICE_ENQUIRY) {
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action CHECK_BALANCE or PRICE_ENQUIRY
// Action: Indicate service error
// New State: IDLE
context.indicateServiceError(this);
deliverGxAnswer(request, event);
setState(ClientGxSessionState.IDLE);
} else if (gatheredRequestedAction == DIRECT_DEBITING) {
if (getLocalDDFH() == DDFH_CONTINUE) {
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action DIRECT_DEBITING; DDFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
deliverGxAnswer(request, event);
setState(ClientGxSessionState.IDLE);
} else if (getLocalDDFH() == DDFH_TERMINATE_OR_BUFFER && txTimerId != null) {
// Current State: PENDING_E
// Event: Failed CC event answer received or temporary error; requested action DIRECT_DEBITING; DDFH equal to TERMINATE_OR_BUFFER and Tx running
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
deliverGxAnswer(request, event);
setState(ClientGxSessionState.IDLE);
}
} else if (gatheredRequestedAction == REFUND_ACCOUNT) {
// Current State: PENDING_E
// Event: Failed CC event answer received; requested action REFUND_ACCOUNT
// Action: Indicate service error and delete request
// New State: IDLE
this.sessionData.setBuffer(null);
context.indicateServiceError(this);
deliverGxAnswer(request, event);
setState(ClientGxSessionState.IDLE);
} else {
logger.warn("Invalid combination for Ro Client FSM: State {}, Result-Code {}, Requested-Action {}, DDFH {}, Tx {}", new Object[]{state, resultCode, gatheredRequestedAction, getLocalDDFH(), txTimerId});
}
}
break;
case PENDING_BUFFERED:
// Current State: PENDING_B
// Event: Failed CC answer received
// Action: Delete request
// New State: IDLE
this.sessionData.setBuffer(null);
setState(ClientGxSessionState.IDLE, false);
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
}
} // Session Based --------------------------------------------------------
else {
switch (state) {
case PENDING_INITIAL:
if (resultCode == CREDIT_CONTROL_NOT_APPLICABLE) {
// Current State: PENDING_I
// Event: CC initial answer received with result code equal to CREDIT_CONTROL_NOT_APPLICABLE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
setState(ClientGxSessionState.IDLE, false);
} else if ((resultCode == END_USER_SERVICE_DENIED) || (resultCode == USER_UNKNOWN)) {
// Current State: PENDING_I
// Event: CC initial answer received with result code END_USER_SERVICE_DENIED or USER_UNKNOWN
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
setState(ClientGxSessionState.IDLE, false);
} else {
// Temporary errors and others
switch (getLocalCCFH()) {
case CCFH_CONTINUE:
// Current State: PENDING_I
// Event: Failed CC initial answer received and CCFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
setState(ClientGxSessionState.IDLE, false);
break;
case CCFH_TERMINATE:
case CCFH_RETRY_AND_TERMINATE:
// Current State: PENDING_I
// Event: Failed CC initial answer received and CCFH equal to TERMINATE or to RETRY_AND_TERMINATE
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
setState(ClientGxSessionState.IDLE, false);
break;
default:
logger.warn("Invalid value for CCFH: {}", getLocalCCFH());
break;
}
}
break;
case PENDING_UPDATE:
if (resultCode == CREDIT_CONTROL_NOT_APPLICABLE) {
// Current State: PENDING_U
// Event: CC update answer received with result code equal to CREDIT_CONTROL_NOT_APPLICABLE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
setState(ClientGxSessionState.IDLE, false);
} else if (resultCode == END_USER_SERVICE_DENIED) {
// Current State: PENDING_U
// Event: CC update answer received with result code END_USER_SERVICE_DENIED
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
setState(ClientGxSessionState.IDLE, false);
} else {
// Temporary errors and others
switch (getLocalCCFH()) {
case CCFH_CONTINUE:
// Current State: PENDING_U
// Event: Failed CC update answer received and CCFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
setState(ClientGxSessionState.IDLE, false);
break;
case CCFH_TERMINATE:
case CCFH_RETRY_AND_TERMINATE:
// Current State: PENDING_U
// Event: Failed CC update answer received and CCFH equal to CONTINUE or to RETRY_AND_CONTINUE
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
setState(ClientGxSessionState.IDLE, false);
break;
default:
logger.warn("Invalid value for CCFH: " + getLocalCCFH());
break;
}
}
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
}
}
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("Failure handling failure message for Event " + event + " (" + eventType + ") and Request " + request, e);
}
}
}
protected void handleTxExpires(Message message) {
// Event Based ----------------------------------------------------------
final ClientGxSessionState state = this.sessionData.getClientGxSessionState();
if (isEventBased()) {
final int gatheredRequestedAction = this.sessionData.getGatheredRequestedAction();
if (gatheredRequestedAction == CHECK_BALANCE || gatheredRequestedAction == PRICE_ENQUIRY) {
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action CHECK_BALANCE or PRICE_ENQUIRY
// Action: Indicate service error
// New State: IDLE
context.indicateServiceError(this);
setState(ClientGxSessionState.IDLE);
} else if (gatheredRequestedAction == DIRECT_DEBITING) {
final int gatheredDDFH = this.sessionData.getGatheredDDFH();
if (gatheredDDFH == DDFH_TERMINATE_OR_BUFFER) {
// Current State: PENDING_E
// Event: Temporary error; requested action DIRECT_DEBITING; DDFH equal to TERMINATE_OR_BUFFER; Tx expired
// Action: Store request
// New State: IDLE
this.sessionData.setBuffer((Request) message);
setState(ClientGxSessionState.IDLE, false);
} else {
// Current State: PENDING_E
// Event: Tx expired; requested action DIRECT_DEBITING
// Action: Grant service to end user
// New State: PENDING_E
context.grantAccessOnTxExpire(this);
setState(ClientGxSessionState.PENDING_EVENT);
}
} else if (gatheredRequestedAction == REFUND_ACCOUNT) {
// Current State: PENDING_E
// Event: Failure to send or Tx expired; requested action REFUND_ACCOUNT
// Action: Store request with T-flag
// New State: IDLE
message.setReTransmitted(true);
this.sessionData.setBuffer((Request) message);
setState(ClientGxSessionState.IDLE, false);
}
} // Session Based --------------------------------------------------------
else {
switch (state) {
case PENDING_INITIAL:
switch (getLocalCCFH()) {
case CCFH_CONTINUE:
case CCFH_RETRY_AND_TERMINATE:
// Current State: PENDING_I
// Event: Tx expired and CCFH equal to CONTINUE or to RETRY_AND_TERMINATE
// Action: Grant service to end user
// New State: PENDING_I
context.grantAccessOnTxExpire(this);
break;
case CCFH_TERMINATE:
// Current State: PENDING_I
// Event: Tx expired and CCFH equal to TERMINATE
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnTxExpire(this);
setState(ClientGxSessionState.IDLE, true);
break;
default:
logger.warn("Invalid value for CCFH: " + getLocalCCFH());
break;
}
break;
case PENDING_UPDATE:
switch (getLocalCCFH()) {
case CCFH_CONTINUE:
case CCFH_RETRY_AND_TERMINATE:
// Current State: PENDING_U
// Event: Tx expired and CCFH equal to CONTINUE or to RETRY_AND_TERMINATE
// Action: Grant service to end user
// New State: PENDING_U
context.grantAccessOnTxExpire(this);
break;
case CCFH_TERMINATE:
// Current State: PENDING_U
// Event: Tx expired and CCFH equal to TERMINATE
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnTxExpire(this);
setState(ClientGxSessionState.IDLE, true);
break;
default:
logger.error("Bad value of CCFH: " + getLocalCCFH());
break;
}
break;
default:
logger.error("Unknown state (" + state + ") on txExpire");
break;
}
}
}
/**
* This makes checks on queue, moves it to proper state if event there is
* present on Open state ;]
*/
protected void dispatch() {
// Event Based ----------------------------------------------------------
if (isEventBased()) {
// Current State: IDLE
// Event: Request in storage
// Action: Send stored request
// New State: PENDING_B
final Request buffer = this.sessionData.getBuffer();
if (buffer != null) {
setState(ClientGxSessionState.PENDING_BUFFERED);
try {
dispatchEvent(new AppRequestEventImpl(buffer));
} catch (Exception e) {
try {
handleSendFailure(e, Event.Type.SEND_EVENT_REQUEST, buffer);
} catch (Exception e1) {
logger.error("Failure handling buffer send failure", e1);
}
}
}
} // Session Based --------------------------------------------------------
else {
if (this.sessionData.getClientGxSessionState() == ClientGxSessionState.OPEN && eventQueue.size() > 0) {
try {
this.handleEvent(eventQueue.remove(0));
} catch (Exception e) {
logger.error("Failure handling queued event", e);
}
}
}
}
protected void deliverGxAnswer(GxCreditControlRequest request, GxCreditControlAnswer answer) {
try {
listener.doCreditControlAnswer(this, request, answer);
} catch (Exception e) {
logger.warn("Failure delivering Ro Answer", e);
}
}
protected void extractFHAVPs(GxCreditControlRequest request, GxCreditControlAnswer answer) throws AvpDataException {
if (answer != null) {
try {
if (answer.isCreditControlFailureHandlingAVPPresent()) {
this.sessionData.setGatheredCCFH(answer.getCredidControlFailureHandlingAVPValue());
}
} catch (Exception e) {
logger.debug("Failure trying to obtain Credit-Control-Failure-Handling AVP value", e);
}
try {
if (answer.isDirectDebitingFailureHandlingAVPPresent()) {
this.sessionData.setGatheredDDFH(answer.getDirectDebitingFailureHandlingAVPValue());
}
} catch (Exception e) {
logger.debug("Failure trying to obtain Direct-Debit-Failure-Handling AVP value", e);
}
if (!sessionData.isRequestTypeSet()) {
this.sessionData.setRequestTypeSet(true);
// No need to check if it exists.. it must, if not fail with exception
this.sessionData.setEventBased(answer.getRequestTypeAVPValue() == EVENT_REQUEST);
}
} else if (request != null) {
try {
if (request.isRequestedActionAVPPresent()) {
this.sessionData.setGatheredRequestedAction(request.getRequestedActionAVPValue());
}
} catch (Exception e) {
logger.debug("Failure trying to obtain Request-Action AVP value", e);
}
if (!sessionData.isRequestTypeSet()) {
this.sessionData.setRequestTypeSet(true);
// No need to check if it exists.. it must, if not fail with exception
this.sessionData.setEventBased(request.getRequestTypeAVPValue() == EVENT_REQUEST);
}
}
}
protected void deliverRAR(GxReAuthRequest request) {
try {
listener.doGxReAuthRequest(this, request);
} catch (Exception e) {
logger.debug("Failure delivering RAR", e);
}
}
protected void dispatchEvent(AppEvent event) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
session.send(event.getMessage(), this);
}
protected boolean isProvisional(long resultCode) {
return resultCode >= 1000 && resultCode < 2000;
}
protected boolean isSuccess(long resultCode) {
return resultCode >= 2000 && resultCode < 3000;
}
protected boolean isFailure(long code) {
return (!isProvisional(code) && !isSuccess(code) && ((code >= 3000 && /*code < 4000) || (code >= 5000 &&*/ code < 6000)) && !temporaryErrorCodes.contains(code));
}
/* (non-Javadoc)
* @see org.jdiameter.common.impl.app.AppSessionImpl#isReplicable()
*/
@Override
public boolean isReplicable() {
return true;
}
private class TxTimerTask implements Runnable {
private ClientGxSession session = null;
private Request request = null;
private TxTimerTask(ClientGxSession session, Request request) {
super();
this.session = session;
this.request = request;
}
public void run() {
try {
sendAndStateLock.lock();
logger.debug("Fired TX Timer");
sessionData.setTxTimerId(null);
sessionData.setTxTimerRequest(null); //??
try {
context.txTimerExpired(session);
} catch (Exception e) {
logger.debug("Failure handling TX Timer Expired", e);
}
GxCreditControlRequest req = factory.createCreditControlRequest(request);
handleEvent(new Event(Event.Type.Tx_TIMER_FIRED, req, null));
} catch (InternalException e) {
logger.error("Internal Exception", e);
} catch (OverloadException e) {
logger.error("Overload Exception", e);
} catch (Exception e) {
logger.error("Exception", e);
} finally {
sendAndStateLock.unlock();
}
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((sessionData == null) ? 0 : sessionData.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
ClientGxSessionImpl other = (ClientGxSessionImpl) obj;
if (sessionData == null) {
if (other.sessionData != null)
return false;
}
else if (!sessionData.equals(other.sessionData))
return false;
return true;
}
private class RequestDelivery implements Runnable {
ClientGxSession session;
Request request;
public void run() {
try {
switch (request.getCommandCode()) {
case GxReAuthAnswerImpl.code:
handleEvent(new Event(Event.Type.RECEIVED_RAR, factory.createGxReAuthRequest(request), null));
break;
default:
listener.doOtherEvent(session, new AppRequestEventImpl(request), null);
break;
}
} catch (Exception e) {
logger.debug("Failure processing request", e);
}
}
}
private class AnswerDelivery implements Runnable {
ClientGxSession session;
Answer answer;
Request request;
public void run() {
try {
switch (request.getCommandCode()) {
case GxCreditControlAnswer.code:
final GxCreditControlRequest myRequest = factory.createCreditControlRequest(request);
final GxCreditControlAnswer myAnswer = factory.createCreditControlAnswer(answer);
extractFHAVPs(null, myAnswer);
handleEvent(new Event(false, myRequest, myAnswer));
break;
default:
listener.doOtherEvent(session, new AppRequestEventImpl(request), new AppAnswerEventImpl(answer));
break;
}
} catch (Exception e) {
logger.debug("Failure processing success message", e);
}
}
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.