code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * 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.server.impl.app.cca; import java.io.Serializable; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.jdiameter.api.Answer; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpDataException; 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.ResultCode; import org.jdiameter.api.RouteException; import org.jdiameter.api.app.AppAnswerEvent; import org.jdiameter.api.app.AppEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.app.StateChangeListener; import org.jdiameter.api.app.StateEvent; import org.jdiameter.api.auth.events.ReAuthRequest; import org.jdiameter.api.cca.ServerCCASession; import org.jdiameter.api.cca.ServerCCASessionListener; import org.jdiameter.api.cca.events.JCreditControlAnswer; import org.jdiameter.api.cca.events.JCreditControlRequest; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.common.api.app.IAppSessionState; import org.jdiameter.common.api.app.cca.ICCAMessageFactory; import org.jdiameter.common.api.app.cca.IServerCCASessionContext; import org.jdiameter.common.api.app.cca.ServerCCASessionState; import org.jdiameter.common.impl.app.AppAnswerEventImpl; import org.jdiameter.common.impl.app.AppRequestEventImpl; import org.jdiameter.common.impl.app.auth.ReAuthAnswerImpl; import org.jdiameter.common.impl.app.auth.ReAuthRequestImpl; import org.jdiameter.common.impl.app.cca.AppCCASessionImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Credit Control Application Server session implementation * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class ServerCCASessionImpl extends AppCCASessionImpl implements ServerCCASession, NetworkReqListener, EventListener<Request, Answer> { private static final Logger logger = LoggerFactory.getLogger(ServerCCASessionImpl.class); protected IServerCCASessionData sessionData; // Session State Handling --------------------------------------------------- protected Lock sendAndStateLock = new ReentrantLock(); // Factories and Listeners -------------------------------------------------- protected transient ICCAMessageFactory factory = null; protected transient IServerCCASessionContext context = null; protected transient ServerCCASessionListener listener = null; protected static final String TCC_TIMER_NAME = "TCC_CCASERVER_TIMER"; protected long[] authAppIds = new long[]{4}; //protected String originHost, originRealm; public ServerCCASessionImpl(IServerCCASessionData data, ICCAMessageFactory fct, ISessionFactory sf, ServerCCASessionListener lst, IServerCCASessionContext ctx, StateChangeListener<AppSession> stLst) { super(sf,data); if (lst == null) { throw new IllegalArgumentException("Listener can not be null"); } if (data == null) { throw new IllegalArgumentException("IServerCCASessionData can not be null"); } if (fct.getApplicationIds() == null) { throw new IllegalArgumentException("ApplicationId can not be less than zero"); } sessionData = data; context = ctx; authAppIds = fct.getApplicationIds(); listener = lst; factory = fct; super.addStateChangeNotification(stLst); } public void sendCreditControlAnswer(JCreditControlAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { handleEvent(new Event(false, null, answer)); } public void sendReAuthRequest(ReAuthRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SENT_RAR, request, null); } public boolean isStateless() { return sessionData.isStateless(); } @SuppressWarnings("unchecked") public <E> E getState(Class<E> stateType) { return stateType == ServerCCASessionState.class ? (E) sessionData.getServerCCASessionState() : null; } public boolean handleEvent(StateEvent event) throws InternalException, OverloadException { ServerCCASessionState newState = null; try { sendAndStateLock.lock(); ServerCCASessionState state = this.sessionData.getServerCCASessionState(); // Can be null if there is no state transition, transition to IDLE state should terminate this app session Event localEvent = (Event) event; //Its kind of awkward, but with two state on server side its easier to go through event types? //but for sake of FSM readability Event.Type eventType = (Event.Type) localEvent.getType(); switch(state) { case IDLE: switch(eventType) { case RECEIVED_INITIAL: listener.doCreditControlRequest(this, (JCreditControlRequest)localEvent.getRequest()); break; case RECEIVED_EVENT: // Current State: IDLE // Event: CC event request received and successfully processed // Action: Send CC event answer // New State: IDLE listener.doCreditControlRequest(this, (JCreditControlRequest)localEvent.getRequest()); break; case SENT_EVENT_RESPONSE: // Current State: IDLE // Event: CC event request received and successfully processed // Action: Send CC event answer // New State: IDLE // Current State: IDLE // Event: CC event request received but not successfully processed // Action: Send CC event answer with Result-Code != SUCCESS // New State: IDLE newState = ServerCCASessionState.IDLE; dispatchEvent(localEvent.getAnswer()); setState(newState); break; case SENT_INITIAL_RESPONSE: JCreditControlAnswer answer = (JCreditControlAnswer) localEvent.getAnswer(); try { long resultCode = answer.getResultCodeAvp().getUnsigned32(); // Current State: IDLE // Event: CC initial request received and successfully processed // Action: Send CC initial answer, reserve units, start Tcc // New State: OPEN if(isSuccess(resultCode)) { startTcc(answer.getValidityTimeAvp()); newState = ServerCCASessionState.OPEN; } // Current State: IDLE // Event: CC initial request received but not successfully processed // Action: Send CC initial answer with Result-Code != SUCCESS // New State: IDLE else { newState = ServerCCASessionState.IDLE; } dispatchEvent(localEvent.getAnswer()); setState(newState); } catch (AvpDataException e) { throw new InternalException(e); } break; case RECEIVED_UPDATE: case RECEIVED_TERMINATE: Answer errorAnswer = ((Request) localEvent.getRequest().getMessage()).createAnswer(ResultCode.UNKNOWN_SESSION_ID); session.send(errorAnswer); logger.debug("Received an UPDATE or TERMINATE for a new session. Answering with 5002 (UNKNOWN_SESSION_ID) and terminating session."); // and let it throw exception anyway ... default: throw new InternalException("Wrong state: " + ServerCCASessionState.IDLE + " on event: " + eventType + " " + localEvent.getRequest() + " " + localEvent.getAnswer()); } case OPEN: switch(eventType) { /* This should not happen, it should be silently discarded, right? case RECEIVED_INITIAL: // only for rtr if(((JCreditControlRequest)localEvent.getRequest()).getMessage().isReTransmitted()) { listener.doCreditControlRequest(this, (JCreditControlRequest)localEvent.getRequest()); } else { //do nothing? } break; */ case RECEIVED_UPDATE: listener.doCreditControlRequest(this, (JCreditControlRequest)localEvent.getRequest()); break; case SENT_UPDATE_RESPONSE: JCreditControlAnswer answer = (JCreditControlAnswer) localEvent.getAnswer(); try { if(isSuccess(answer.getResultCodeAvp().getUnsigned32())) { // Current State: OPEN // Event: CC update request received and successfully processed // Action: Send CC update answer, debit used units, reserve new units, restart Tcc // New State: OPEN startTcc(answer.getValidityTimeAvp()); } else { // Current State: OPEN // Event: CC update request received but not successfully processed // Action: Send CC update answer with Result-Code != SUCCESS, debit used units // New State: IDLE // It's a failure, we wait for Tcc to fire -- FIXME: Alexandre: Should we? } } catch (AvpDataException e) { throw new InternalException(e); } dispatchEvent(localEvent.getAnswer()); break; case RECEIVED_TERMINATE: listener.doCreditControlRequest(this, (JCreditControlRequest)localEvent.getRequest()); break; case SENT_TERMINATE_RESPONSE: answer = (JCreditControlAnswer) localEvent.getAnswer(); try { // Current State: OPEN // Event: CC termination request received and successfully processed // Action: Send CC termination answer, Stop Tcc, debit used units // New State: IDLE if(isSuccess(answer.getResultCodeAvp().getUnsigned32())) { stopTcc(false); } else { // Current State: OPEN // Event: CC termination request received but not successfully processed // Action: Send CC termination answer with Result-Code != SUCCESS, debit used units // New State: IDLE // It's a failure, we wait for Tcc to fire -- FIXME: Alexandre: Should we? } } catch (AvpDataException e) { throw new InternalException(e); } newState = ServerCCASessionState.IDLE; dispatchEvent(localEvent.getAnswer()); setState(newState); break; case RECEIVED_RAA: listener.doReAuthAnswer(this, new ReAuthRequestImpl(localEvent.getRequest().getMessage()), new ReAuthAnswerImpl((Answer)localEvent.getAnswer().getMessage())); break; case SENT_RAR: dispatchEvent(localEvent.getRequest()); break; } } return true; } catch (Exception e) { throw new InternalException(e); } finally { sendAndStateLock.unlock(); } } /* * (non-Javadoc) * * @see org.jdiameter.common.impl.app.AppSessionImpl#isReplicable() */ @Override public boolean isReplicable() { return true; } private class TccScheduledTask implements Runnable { ServerCCASession session = null; private TccScheduledTask(ServerCCASession session) { super(); this.session = session; } public void run() { // Current State: OPEN // Event: Session supervision timer Tcc expired // Action: Release reserved units // New State: IDLE context.sessionSupervisionTimerExpired(session); try { sendAndStateLock.lock(); // tccFuture = null; sessionData.setTccTimerId(null); setState(ServerCCASessionState.IDLE); } finally { sendAndStateLock.unlock(); } } } public Answer processRequest(Request request) { RequestDelivery rd = new RequestDelivery(); //rd.session = (ServerCCASession) LocalDataSource.INSTANCE.getSession(request.getSessionId()); rd.session = this; rd.request = request; super.scheduler.execute(rd); return null; } 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) { context.timeoutExpired(request); //FIXME: Should we release ? } private void startTcc(Avp validityAvp) { long tccTimeout; if(validityAvp != null) { try { tccTimeout = 2 * validityAvp.getUnsigned32(); } catch (AvpDataException e) { logger.debug("Unable to retrieve Validity-Time AVP value, using default.", e); tccTimeout = 2 * context.getDefaultValidityTime(); } } else { tccTimeout = 2 * context.getDefaultValidityTime(); } if(sessionData.getTccTimerId() != null) { stopTcc(true); //tccFuture = super.scheduler.schedule(new TccScheduledTask(this), defaultValue, TimeUnit.SECONDS); this.sessionData.setTccTimerId(super.timerFacility.schedule(this.getSessionId(), TCC_TIMER_NAME, tccTimeout * 1000)); // FIXME: this accepts Future! context.sessionSupervisionTimerReStarted(this, null); } else { //tccFuture = super.scheduler.schedule(new TccScheduledTask(this), defaultValue, TimeUnit.SECONDS); this.sessionData.setTccTimerId(super.timerFacility.schedule(this.getSessionId(), TCC_TIMER_NAME, tccTimeout * 1000)); //FIXME: this accepts Future! context.sessionSupervisionTimerStarted(this, null); } } /* * (non-Javadoc) * * @see org.jdiameter.common.impl.app.AppSessionImpl#onTimer(java.lang.String) */ @Override public void onTimer(String timerName) { if (timerName.equals(TCC_TIMER_NAME)) { new TccScheduledTask(this).run(); } } private void stopTcc(boolean willRestart) { Serializable tccTimerId = this.sessionData.getTccTimerId(); if (tccTimerId != null) { // tccFuture.cancel(false); super.timerFacility.cancel(tccTimerId); // ScheduledFuture f = tccFuture; this.sessionData.setTccTimerId(null); if (!willRestart) { context.sessionSupervisionTimerStopped(this, null); } } } protected boolean isProvisional(long resultCode) { return resultCode >= 1000 && resultCode < 2000; } protected boolean isSuccess(long resultCode) { return resultCode >= 2000 && resultCode < 3000; } protected void setState(ServerCCASessionState newState) { setState(newState, true); } @SuppressWarnings("unchecked") protected void setState(ServerCCASessionState newState, boolean release) { IAppSessionState oldState = this.sessionData.getServerCCASessionState(); this.sessionData.setServerCCASessionState(newState); for (StateChangeListener i : stateListeners) { i.stateChanged(this, (Enum) oldState, (Enum) newState); } if (newState == ServerCCASessionState.IDLE) { // do EVERYTHING before this! stopTcc(false); if (release) { this.release(); } } } @Override public void release() { if (isValid()) { try { sendAndStateLock.lock(); this.stopTcc(false); super.release(); } finally { sendAndStateLock.unlock(); } } else { logger.debug("Trying to release an already invalid session, with Session ID '{}'", getSessionId()); } } protected void send(Event.Type type, AppRequestEvent request, AppAnswerEvent answer) throws InternalException { try { if (type != null) { handleEvent(new Event(type, request, answer)); } } catch (Exception e) { throw new InternalException(e); } } protected void dispatchEvent(AppEvent event) throws InternalException { try { session.send(event.getMessage(), this); // Store last destination information // FIXME: add differentiation on server/client request //originRealm = event.getMessage().getAvps().getAvp(Avp.ORIGIN_REALM).getOctetString(); //originHost = event.getMessage().getAvps().getAvp(Avp.ORIGIN_HOST).getOctetString(); } catch(Exception e) { //throw new InternalException(e); logger.debug("Failure trying to dispatch event", e); } } private class RequestDelivery implements Runnable { ServerCCASession session; Request request; public void run() { try { switch (request.getCommandCode()) { case JCreditControlAnswer.code: handleEvent(new Event(true, factory.createCreditControlRequest(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 { ServerCCASession session; Answer answer; Request request; public void run() { try { // FIXME: baranowb: add message validation here!!! // We handle CCR, STR, ACR, ASR other go into extension switch (request.getCommandCode()) { case ReAuthRequest.code: handleEvent(new Event(Event.Type.RECEIVED_RAA, factory.createReAuthRequest(request), factory.createReAuthAnswer(answer))); break; default: listener.doOtherEvent(session, new AppRequestEventImpl(request), new AppAnswerEventImpl(answer)); break; } } catch (Exception e) { logger.debug("Failed to process 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; ServerCCASessionImpl other = (ServerCCASessionImpl) obj; if (sessionData == null) { if (other.sessionData != null) return false; } else if (!sessionData.equals(other.sessionData)) return false; return true; } @Override public String toString() { return "ServerCCASessionImpl [sessionData=" + sessionData + "]"; } }
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.server.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:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class Event implements StateEvent { public enum Type { RECEIVED_EVENT, SENT_EVENT_RESPONSE, RECEIVED_INITIAL, SENT_INITIAL_RESPONSE, RECEIVED_UPDATE, SENT_UPDATE_RESPONSE, RECEIVED_TERMINATE, SENT_TERMINATE_RESPONSE, // These have no transition, no state resources, timers SENT_RAR, RECEIVED_RAA; } 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; /** * <pre> * 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 * UPDATE_REQUEST 2 * TERMINATION_REQUEST 3 * EVENT_REQUEST 4 * </pre> */ if (isRequest) { switch (request.getRequestTypeAVPValue()) { case 1: type = Type.RECEIVED_INITIAL; break; case 2: type = Type.RECEIVED_UPDATE; break; case 3: type = Type.RECEIVED_TERMINATE; break; case 4: type = Type.RECEIVED_EVENT; break; default: throw new IllegalArgumentException("Invalid value or Request-Type AVP not present in CC Request."); } } else { switch (answer.getRequestTypeAVPValue()) { case 1: type = Type.SENT_INITIAL_RESPONSE; break; case 2: type = Type.SENT_UPDATE_RESPONSE; break; case 3: type = Type.SENT_TERMINATE_RESPONSE; break; case 4: type = Type.SENT_EVENT_RESPONSE; break; default: throw new IllegalArgumentException("Invalid value or Request-Type AVP not present in CC Answer."); } } } public <E> E encodeType(Class<E> eClass) { return eClass == Event.Type.class ? (E) type : null; } public Enum getType() { return type; } public int compareTo(Object o) { return 0; } public Object getData() { return this.request != null ? this.request : this.answer; } public void setData(Object data) { // data = (AppEvent) o; // FIXME: What should we do here?! Is it request or answer? } public AppEvent getRequest() { return request; } public AppEvent getAnswer() { return answer; } }
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.server.impl.app.cca; import java.io.Serializable; import org.jdiameter.common.api.app.AppSessionDataLocalImpl; import org.jdiameter.common.api.app.cca.ServerCCASessionState; /** * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public class ServerCCASessionDataLocalImpl extends AppSessionDataLocalImpl implements IServerCCASessionData { protected boolean stateless = true; protected ServerCCASessionState state = ServerCCASessionState.IDLE; protected Serializable tccTimerId; /** * */ public ServerCCASessionDataLocalImpl() { } public boolean isStateless() { return stateless; } public void setStateless(boolean stateless) { this.stateless = stateless; } public ServerCCASessionState getServerCCASessionState() { return state; } public void setServerCCASessionState(ServerCCASessionState state) { this.state = state; } public Serializable getTccTimerId() { return tccTimerId; } public void setTccTimerId(Serializable tccTimerId) { this.tccTimerId = tccTimerId; } }
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.server.impl.app.cca; import java.io.Serializable; import org.jdiameter.common.api.app.cca.ICCASessionData; import org.jdiameter.common.api.app.cca.ServerCCASessionState; /** * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public interface IServerCCASessionData extends ICCASessionData{ public boolean isStateless(); public void setStateless(boolean stateless); public ServerCCASessionState getServerCCASessionState(); public void setServerCCASessionState(ServerCCASessionState state); public void setTccTimerId(Serializable tccTimerId); public Serializable getTccTimerId(); }
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.server.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.ServerCxDxSession; import org.jdiameter.api.cxdx.ServerCxDxSessionListener; import org.jdiameter.api.cxdx.events.JLocationInfoAnswer; import org.jdiameter.api.cxdx.events.JLocationInfoRequest; import org.jdiameter.api.cxdx.events.JMultimediaAuthAnswer; import org.jdiameter.api.cxdx.events.JMultimediaAuthRequest; import org.jdiameter.api.cxdx.events.JPushProfileAnswer; import org.jdiameter.api.cxdx.events.JPushProfileRequest; import org.jdiameter.api.cxdx.events.JRegistrationTerminationAnswer; import org.jdiameter.api.cxdx.events.JRegistrationTerminationRequest; import org.jdiameter.api.cxdx.events.JServerAssignmentAnswer; import org.jdiameter.api.cxdx.events.JServerAssignmentRequest; import org.jdiameter.api.cxdx.events.JUserAuthorizationAnswer; import org.jdiameter.api.cxdx.events.JUserAuthorizationRequest; import org.jdiameter.client.api.ISessionFactory; 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.jdiameter.server.impl.app.cxdx.Event.Type; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Cx/Dx Server session implementation * * @author <a href="mailto:baranowb@gmail.com">Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public class CxDxServerSessionImpl extends CxDxSession implements ServerCxDxSession, EventListener<Request, Answer>, NetworkReqListener { private static final Logger logger = LoggerFactory.getLogger(CxDxServerSessionImpl.class); // Factories and Listeners -------------------------------------------------- private transient ServerCxDxSessionListener listener; protected long appId = -1; protected IServerCxDxSessionData sessionData; public CxDxServerSessionImpl(IServerCxDxSessionData sessionData, ICxDxMessageFactory fct, ISessionFactory sf, ServerCxDxSessionListener lst) { super(sf,sessionData); if (lst == null) { throw new IllegalArgumentException("Listener can not be null"); } if ((this.appId = fct.getApplicationId()) < 0) { throw new IllegalArgumentException("ApplicationId can not be less than zero"); } this.listener = lst; super.messageFactory = fct; this.sessionData = sessionData; } /* (non-Javadoc) * @see org.jdiameter.api.cxdx.ServerCxDxSession#sendLocationInformationAnswer(org.jdiameter.api.cxdx.events.JLocationInfoAnswer) */ public void sendLocationInformationAnswer(JLocationInfoAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SEND_MESSAGE, null, answer); } /* (non-Javadoc) * @see org.jdiameter.api.cxdx.ServerCxDxSession#sendMultimediaAuthAnswer(org.jdiameter.api.cxdx.events.JMultimediaAuthAnswer) */ public void sendMultimediaAuthAnswer(JMultimediaAuthAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SEND_MESSAGE, null, answer); } /* (non-Javadoc) * @see org.jdiameter.api.cxdx.ServerCxDxSession#sendServerAssignmentAnswer(org.jdiameter.api.cxdx.events.JServerAssignmentAnswer) */ public void sendServerAssignmentAnswer(JServerAssignmentAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SEND_MESSAGE, null, answer); } /* (non-Javadoc) * @see org.jdiameter.api.cxdx.ServerCxDxSession#sendUserAuthorizationAnswer(org.jdiameter.api.cxdx.events.JUserAuthorizationAnswer) */ public void sendUserAuthorizationAnswer(JUserAuthorizationAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SEND_MESSAGE, null, answer); } /* * (non-Javadoc) * @see org.jdiameter.api.cxdx.ServerCxDxSession#sendPushProfileRequest(org.jdiameter.api.cxdx.events.JPushProfileRequest) */ public void sendPushProfileRequest(JPushProfileRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SEND_MESSAGE, request, null); } /* * (non-Javadoc) * @see org.jdiameter.api.cxdx.ServerCxDxSession#sendRegistrationTerminationRequest(org.jdiameter.api.cxdx.events.JRegistrationTerminationRequest) */ public void sendRegistrationTerminationRequest(JRegistrationTerminationRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SEND_MESSAGE, request, null); } /* * (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.app.StateMachine#handleEvent(org.jdiameter.api.app.StateEvent) */ 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 localEvent = (Event) event; Event.Type eventType = (Type) event.getType(); switch (state) { case IDLE: switch (eventType) { case RECEIVE_LIR: this.sessionData.setBuffer((Request)((AppEvent) event.getData()).getMessage()); super.cancelMsgTimer(); super.startMsgTimer(); newState = CxDxSessionState.MESSAGE_SENT_RECEIVED; setState(newState); listener.doLocationInformationRequest(this, (JLocationInfoRequest) event.getData()); break; case RECEIVE_MAR: this.sessionData.setBuffer((Request)((AppEvent) event.getData()).getMessage()); super.cancelMsgTimer(); super.startMsgTimer(); newState = CxDxSessionState.MESSAGE_SENT_RECEIVED; setState(newState); listener.doMultimediaAuthRequest(this, (JMultimediaAuthRequest) event.getData()); break; case RECEIVE_SAR: this.sessionData.setBuffer((Request)((AppEvent) event.getData()).getMessage()); super.cancelMsgTimer(); super.startMsgTimer(); newState = CxDxSessionState.MESSAGE_SENT_RECEIVED; setState(newState); listener.doServerAssignmentRequest(this, (JServerAssignmentRequest) event.getData()); break; case RECEIVE_UAR: this.sessionData.setBuffer((Request)((AppEvent) event.getData()).getMessage()); super.cancelMsgTimer(); super.startMsgTimer(); newState = CxDxSessionState.MESSAGE_SENT_RECEIVED; setState(newState); listener.doUserAuthorizationRequest(this, (JUserAuthorizationRequest) event.getData()); break; case SEND_MESSAGE: super.session.send(((AppEvent) event.getData()).getMessage(),this); newState = CxDxSessionState.MESSAGE_SENT_RECEIVED; setState(newState); break; default: logger.error("Wrong action in Cx/Dx Server FSM. State: IDLE, Event Type: {}", eventType); break; } break; case MESSAGE_SENT_RECEIVED: switch (eventType) { case TIMEOUT_EXPIRES: newState = CxDxSessionState.TIMEDOUT; break; case SEND_MESSAGE: try { super.session.send(((AppEvent) event.getData()).getMessage(), this); } finally { newState = CxDxSessionState.TERMINATED; setState(newState); } break; case RECEIVE_PPA: try { super.cancelMsgTimer(); listener.doPushProfileAnswer(this, (JPushProfileRequest) localEvent.getRequest(), (JPushProfileAnswer) localEvent.getAnswer()); } finally { newState = CxDxSessionState.TERMINATED; setState(newState); } break; case RECEIVE_RTA: try { super.cancelMsgTimer(); listener.doRegistrationTerminationAnswer(this, (JRegistrationTerminationRequest) localEvent.getRequest(), (JRegistrationTerminationAnswer) localEvent.getAnswer()); } finally { newState = CxDxSessionState.TERMINATED; setState(newState); } 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 Server FSM in wrong state: {}", state); break; } } catch (Exception e) { throw new InternalException(e); } finally { sendAndStateLock.unlock(); } 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()); } } /* * (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); } } /* * (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; } 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); } } @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(); } } @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(); } } } private class RequestDelivery implements Runnable { ServerCxDxSession session; Request request; public void run() { try { switch (request.getCommandCode()) { case JUserAuthorizationRequest.code: handleEvent(new Event(Event.Type.RECEIVE_UAR, messageFactory.createUserAuthorizationRequest(request), null)); break; case JServerAssignmentRequest.code: handleEvent(new Event(Event.Type.RECEIVE_SAR, messageFactory.createServerAssignmentRequest(request), null)); break; case JMultimediaAuthRequest.code: handleEvent(new Event(Event.Type.RECEIVE_MAR, messageFactory.createMultimediaAuthRequest(request), null)); break; case JLocationInfoRequest.code: handleEvent(new Event(Event.Type.RECEIVE_LIR, messageFactory.createLocationInfoRequest(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 { ServerCxDxSession session; Answer answer; Request request; public void run() { try{ switch (answer.getCommandCode()) { case JPushProfileAnswer.code: handleEvent(new Event(Event.Type.RECEIVE_PPA, messageFactory.createPushProfileRequest(request), messageFactory.createPushProfileAnswer(answer))); break; case JRegistrationTerminationAnswer.code: handleEvent(new Event(Event.Type.RECEIVE_RTA, messageFactory.createRegistrationTerminationRequest(request), messageFactory.createRegistrationTerminationAnswer(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 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.server.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 ServerCxDxSessionDataLocalImpl extends CxDxLocalSessionDataImpl implements IServerCxDxSessionData { /** * */ public ServerCxDxSessionDataLocalImpl() { } }
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.server.impl.app.cxdx; import org.jdiameter.api.InternalException; import org.jdiameter.api.app.AppEvent; import org.jdiameter.api.app.StateEvent; /** * Start time:19:52:21 2009-08-17<br> * Project: diameter-parent<br> * * @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, TIMEOUT_EXPIRES, RECEIVE_UAR, RECEIVE_SAR, RECEIVE_LIR, RECEIVE_MAR, RECEIVE_PPA,RECEIVE_RTA; } 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; } /* (non-Javadoc) * @see org.jdiameter.api.app.StateEvent#setData(java.lang.Object) */ 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 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.server.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 IServerCxDxSessionData 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.server.impl.app.s6a; import org.jdiameter.common.impl.app.s6a.S6aLocalSessionDataImpl; /** * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:richard.good@smilecoms.com"> Richard Good </a> * @author <a href="mailto:paul.carter-brown@smilecoms.com"> Paul Carter-Brown </a> */ public class ServerS6aSessionDataLocalImpl extends S6aLocalSessionDataImpl implements IServerS6aSessionData { public ServerS6aSessionDataLocalImpl() { } }
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.server.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.ServerS6aSession; import org.jdiameter.api.s6a.ServerS6aSessionListener; 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.common.api.app.s6a.IS6aMessageFactory; import org.jdiameter.common.api.app.s6a.S6aSessionState; import org.jdiameter.common.impl.app.AppAnswerEventImpl; import org.jdiameter.common.impl.app.AppRequestEventImpl; import org.jdiameter.common.impl.app.s6a.S6aSession; import org.jdiameter.server.impl.app.s6a.Event; import org.jdiameter.server.impl.app.s6a.Event.Type; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * S6a Server session implementation * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:richard.good@smilecoms.com"> Richard Good </a> * @author <a href="mailto:paul.carter-brown@smilecoms.com"> Paul Carter-Brown </a> */ public class S6aServerSessionImpl extends S6aSession implements ServerS6aSession, EventListener<Request, Answer>, NetworkReqListener { private static final Logger logger = LoggerFactory.getLogger(S6aServerSessionImpl.class); // Factories and Listeners -------------------------------------------------- private transient ServerS6aSessionListener listener; protected long appId = -1; protected IServerS6aSessionData sessionData; public S6aServerSessionImpl(IServerS6aSessionData sessionData, IS6aMessageFactory fct, ISessionFactory sf, ServerS6aSessionListener lst) { super(sf, sessionData); if (lst == null) { throw new IllegalArgumentException("Listener can not be null"); } if ((this.appId = fct.getApplicationId()) < 0) { throw new IllegalArgumentException("ApplicationId can not be less than zero"); } this.listener = lst; super.messageFactory = fct; this.sessionData = sessionData; } public void sendAuthenticationInformationAnswer(JAuthenticationInformationAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SEND_MESSAGE, null, answer); } public void sendPurgeUEAnswer(JPurgeUEAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SEND_MESSAGE, null, answer); } public void sendUpdateLocationAnswer(JUpdateLocationAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SEND_MESSAGE, null, answer); } public void sendNotifyAnswer(JNotifyAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SEND_MESSAGE, null, answer); } public void sendCancelLocationRequest(JCancelLocationRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SEND_MESSAGE, request, null); } public void sendInsertSubscriberDataRequest(JInsertSubscriberDataRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SEND_MESSAGE, request, null); } public void sendDeleteSubscriberDataRequest(JDeleteSubscriberDataRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SEND_MESSAGE, request, null); } public void sendResetRequest(JResetRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SEND_MESSAGE, request, null); } /* * (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.app.StateMachine#handleEvent(org.jdiameter.api.app.StateEvent) */ 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_AIR: this.sessionData.setBuffer((Request) ((AppEvent) event.getData()).getMessage()); super.cancelMsgTimer(); super.startMsgTimer(); newState = S6aSessionState.MESSAGE_SENT_RECEIVED; setState(newState); listener.doAuthenticationInformationRequestEvent(this, (JAuthenticationInformationRequest) event.getData()); break; case RECEIVE_PUR: this.sessionData.setBuffer((Request) ((AppEvent) event.getData()).getMessage()); super.cancelMsgTimer(); super.startMsgTimer(); newState = S6aSessionState.MESSAGE_SENT_RECEIVED; setState(newState); listener.doPurgeUERequestEvent(this, (JPurgeUERequest) event.getData()); break; case RECEIVE_ULR: this.sessionData.setBuffer((Request) ((AppEvent) event.getData()).getMessage()); super.cancelMsgTimer(); super.startMsgTimer(); newState = S6aSessionState.MESSAGE_SENT_RECEIVED; setState(newState); listener.doUpdateLocationRequestEvent(this, (JUpdateLocationRequest) event.getData()); break; case RECEIVE_NOR: this.sessionData.setBuffer((Request) ((AppEvent) event.getData()).getMessage()); super.cancelMsgTimer(); super.startMsgTimer(); newState = S6aSessionState.MESSAGE_SENT_RECEIVED; setState(newState); listener.doNotifyRequestEvent(this, (JNotifyRequest) event.getData()); break; case SEND_MESSAGE: super.session.send(((AppEvent) event.getData()).getMessage(), this); newState = S6aSessionState.MESSAGE_SENT_RECEIVED; setState(newState); break; default: logger.error("Wrong action in S6a Server FSM. State: IDLE, Event Type: {}", eventType); 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_CLA: try { super.cancelMsgTimer(); listener.doCancelLocationAnswerEvent(this, (JCancelLocationRequest) localEvent.getRequest(), (JCancelLocationAnswer) localEvent.getAnswer()); } finally { newState = S6aSessionState.TERMINATED; setState(newState); } break; case RECEIVE_IDA: try { super.cancelMsgTimer(); listener.doInsertSubscriberDataAnswerEvent(this, (JInsertSubscriberDataRequest) localEvent.getRequest(), (JInsertSubscriberDataAnswer) localEvent.getAnswer()); } finally { newState = S6aSessionState.TERMINATED; setState(newState); } break; case RECEIVE_DSA: try { super.cancelMsgTimer(); listener.doDeleteSubscriberDataAnswerEvent(this, (JDeleteSubscriberDataRequest) localEvent.getRequest(), (JDeleteSubscriberDataAnswer) localEvent.getAnswer()); } finally { newState = S6aSessionState.TERMINATED; setState(newState); } break; case RECEIVE_RSA: try { super.cancelMsgTimer(); listener.doResetAnswerEvent(this, (JResetRequest) localEvent.getRequest(), (JResetAnswer) localEvent.getAnswer()); } finally { newState = S6aSessionState.TERMINATED; setState(newState); } 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("S6a Server FSM in wrong state: {}", state); break; } } catch (Exception e) { throw new InternalException(e); } finally { sendAndStateLock.unlock(); } return true; } /* * (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); } } /* * (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; } 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); } } @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(); } } @Override 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(); } } } 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 { ServerS6aSession session; Request request; public void run() { try { switch (request.getCommandCode()) { case JAuthenticationInformationRequest.code: handleEvent(new Event(Event.Type.RECEIVE_AIR, messageFactory.createAuthenticationInformationRequest(request), null)); break; case JPurgeUERequest.code: handleEvent(new Event(Event.Type.RECEIVE_PUR, messageFactory.createPurgeUERequest(request), null)); break; case JUpdateLocationRequest.code: handleEvent(new Event(Event.Type.RECEIVE_ULR, messageFactory.createUpdateLocationRequest(request), null)); break; case JNotifyRequest.code: handleEvent(new Event(Event.Type.RECEIVE_NOR, messageFactory.createNotifyRequest(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 { ServerS6aSession session; Answer answer; Request request; public void run() { try { switch (answer.getCommandCode()) { case JCancelLocationAnswer.code: handleEvent(new Event(Event.Type.RECEIVE_CLA, messageFactory.createCancelLocationRequest(request), messageFactory.createCancelLocationAnswer(answer))); break; case JInsertSubscriberDataAnswer.code: handleEvent(new Event(Event.Type.RECEIVE_IDA, messageFactory.createInsertSubscriberDataRequest(request), messageFactory.createInsertSubscriberDataAnswer(answer))); break; case JDeleteSubscriberDataAnswer.code: handleEvent(new Event(Event.Type.RECEIVE_DSA, messageFactory.createDeleteSubscriberDataRequest(request), messageFactory.createDeleteSubscriberDataAnswer(answer))); break; case JResetAnswer.code: handleEvent(new Event(Event.Type.RECEIVE_RSA, messageFactory.createResetRequest(request), messageFactory.createResetAnswer(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.server.impl.app.s6a; import org.jdiameter.common.api.app.s6a.IS6aSessionData; /** * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:richard.good@smilecoms.com"> Richard Good </a> * @author <a href="mailto:paul.carter-brown@smilecoms.com"> Paul Carter-Brown </a> */ public interface IServerS6aSessionData 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.server.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> * @author <a href="mailto:richard.good@smilecoms.com"> Richard Good </a> * @author <a href="mailto:paul.carter-brown@smilecoms.com"> Paul Carter-Brown </a> */ public class Event implements StateEvent { enum Type { SEND_MESSAGE, TIMEOUT_EXPIRES, RECEIVE_AIR, RECEIVE_PUR, RECEIVE_ULR, RECEIVE_NOR, RECEIVE_CLA, RECEIVE_IDA, RECEIVE_DSA, RECEIVE_RSA; } 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 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.server.impl.app.gx; 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 { RECEIVED_EVENT, SENT_EVENT_RESPONSE, RECEIVED_INITIAL, SENT_INITIAL_RESPONSE, RECEIVED_UPDATE, SENT_UPDATE_RESPONSE, RECEIVED_TERMINATE, SENT_TERMINATE_RESPONSE, // These have no transition, no state resources, timers SENT_RAR, RECEIVED_RAA; } 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) { this.answer = answer; this.request = request; /** * <pre> * 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 * UPDATE_REQUEST 2 * TERMINATION_REQUEST 3 * EVENT_REQUEST 4 * </pre> */ if (isRequest) { switch (request.getRequestTypeAVPValue()) { case 1: type = Type.RECEIVED_INITIAL; break; case 2: type = Type.RECEIVED_UPDATE; break; case 3: type = Type.RECEIVED_TERMINATE; break; case 4: type = Type.RECEIVED_EVENT; break; default: throw new IllegalArgumentException("Invalid value or Request-Type AVP not present in CC Request."); } } else { switch (answer.getRequestTypeAVPValue()) { case 1: type = Type.SENT_INITIAL_RESPONSE; break; case 2: type = Type.SENT_UPDATE_RESPONSE; break; case 3: type = Type.SENT_TERMINATE_RESPONSE; break; case 4: type = Type.SENT_EVENT_RESPONSE; break; default: throw new IllegalArgumentException("Invalid value or Request-Type AVP not present in CC Answer."); } } } public <E> E encodeType(Class<E> eClass) { return eClass == Event.Type.class ? (E) type : null; } public Enum getType() { return type; } public int compareTo(Object o) { return 0; } public Object getData() { return this.request != null ? this.request : this.answer; } public void setData(Object data) { // data = (AppEvent) o; // FIXME: What should we do here?! Is it request or answer? } public AppEvent getRequest() { return request; } public AppEvent getAnswer() { return 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.server.impl.app.gx; import java.io.Serializable; import org.jdiameter.common.api.app.gx.IGxSessionData; import org.jdiameter.common.api.app.gx.ServerGxSessionState; /** * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public interface IServerGxSessionData extends IGxSessionData{ public boolean isStateless(); public void setStateless(boolean stateless); public ServerGxSessionState getServerGxSessionState(); public void setServerGxSessionState(ServerGxSessionState state); public void setTccTimerId(Serializable tccTimerId); public Serializable getTccTimerId(); }
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.server.impl.app.gx; import java.io.Serializable; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.jdiameter.api.Answer; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpDataException; 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.AppAnswerEvent; import org.jdiameter.api.app.AppEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.app.StateChangeListener; import org.jdiameter.api.app.StateEvent; import org.jdiameter.api.gx.events.GxReAuthRequest; import org.jdiameter.api.gx.events.GxReAuthAnswer; import org.jdiameter.api.gx.ServerGxSession; import org.jdiameter.api.gx.ServerGxSessionListener; import org.jdiameter.api.gx.events.GxCreditControlAnswer; import org.jdiameter.api.gx.events.GxCreditControlRequest; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.common.api.app.IAppSessionState; import org.jdiameter.common.api.app.gx.IGxMessageFactory; import org.jdiameter.common.api.app.gx.IServerGxSessionContext; import org.jdiameter.common.api.app.gx.ServerGxSessionState; import org.jdiameter.common.impl.app.AppAnswerEventImpl; import org.jdiameter.common.impl.app.AppRequestEventImpl; import org.jdiameter.common.impl.app.gx.AppGxSessionImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Credit Control Application Server 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 ServerGxSessionImpl extends AppGxSessionImpl implements ServerGxSession, NetworkReqListener, EventListener<Request, Answer> { private static final Logger logger = LoggerFactory.getLogger(ServerGxSessionImpl.class); // Session State Handling --------------------------------------------------- protected Lock sendAndStateLock = new ReentrantLock(); // Factories and Listeners -------------------------------------------------- protected transient IGxMessageFactory factory = null; protected transient IServerGxSessionContext context = null; protected transient ServerGxSessionListener listener = null; protected static final String TCC_TIMER_NAME = "TCC_GxSERVER_TIMER"; protected long[] authAppIds = new long[]{4}; //protected String originHost, originRealm; protected IServerGxSessionData sessionData; public ServerGxSessionImpl(IServerGxSessionData sessionData, IGxMessageFactory fct, ISessionFactory sf, ServerGxSessionListener lst, IServerGxSessionContext 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"); } context = ctx; authAppIds = fct.getApplicationIds(); listener = lst; factory = fct; this.sessionData = sessionData; super.addStateChangeNotification(stLst); } public void sendCreditControlAnswer(GxCreditControlAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { handleEvent(new Event(false, null, answer)); } public void sendGxReAuthRequest(GxReAuthRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SENT_RAR, request, null); } public boolean isStateless() { return this.sessionData.isStateless(); } @SuppressWarnings("unchecked") public <E> E getState(Class<E> stateType) { return stateType == ServerGxSessionState.class ? (E) this.sessionData.getServerGxSessionState() : null; } public boolean handleEvent(StateEvent event) throws InternalException, OverloadException { ServerGxSessionState newState = null; try { sendAndStateLock.lock(); // Can be null if there is no state transition, transition to IDLE state should terminate this app session final Event localEvent = (Event) event; final ServerGxSessionState state = this.sessionData.getServerGxSessionState(); //Its kind of awkward, but with two state on server side its easier to go through event types? //but for sake of FSM readability final Event.Type eventType = (Event.Type) localEvent.getType(); switch(state) { case IDLE: switch(eventType) { case RECEIVED_INITIAL: listener.doCreditControlRequest(this, (GxCreditControlRequest)localEvent.getRequest()); break; case RECEIVED_EVENT: // Current State: IDLE // Event: CC event request received and successfully processed // Action: Send CC event answer // New State: IDLE listener.doCreditControlRequest(this, (GxCreditControlRequest)localEvent.getRequest()); break; case SENT_EVENT_RESPONSE: // Current State: IDLE // Event: CC event request received and successfully processed // Action: Send CC event answer // New State: IDLE // Current State: IDLE // Event: CC event request received but not successfully processed // Action: Send CC event answer with Result-Code != SUCCESS // New State: IDLE newState = ServerGxSessionState.IDLE; dispatchEvent(localEvent.getAnswer()); setState(newState); break; case SENT_INITIAL_RESPONSE: GxCreditControlAnswer answer = (GxCreditControlAnswer) localEvent.getAnswer(); try { long resultCode = answer.getResultCodeAvp().getUnsigned32(); // Current State: IDLE // Event: CC initial request received and successfully processed // Action: Send CC initial answer, reserve units, start Tcc // New State: OPEN if(isSuccess(resultCode)) { startTcc(answer.getValidityTimeAvp()); newState = ServerGxSessionState.OPEN; } // Current State: IDLE // Event: CC initial request received but not successfully processed // Action: Send CC initial answer with Result-Code != SUCCESS // New State: IDLE else { newState = ServerGxSessionState.IDLE; } dispatchEvent(localEvent.getAnswer()); setState(newState); } catch (AvpDataException e) { throw new InternalException(e); } break; default: throw new InternalException("Wrong state: " + ServerGxSessionState.IDLE + " one event: " + eventType + " " + localEvent.getRequest() + " " + localEvent.getAnswer()); } case OPEN: switch(eventType) { /* This should not happen, it should be silently discarded, right? case RECEIVED_INITIAL: // only for rtr if(((RoRequest)localEvent.getRequest()).getMessage().isReTransmitted()) { listener.doCreditControlRequest(this, (RoRequest)localEvent.getRequest()); } else { //do nothing? } break; */ case RECEIVED_UPDATE: listener.doCreditControlRequest(this, (GxCreditControlRequest)localEvent.getRequest()); break; case SENT_UPDATE_RESPONSE: GxCreditControlAnswer answer = (GxCreditControlAnswer) localEvent.getAnswer(); try { if(isSuccess(answer.getResultCodeAvp().getUnsigned32())) { // Current State: OPEN // Event: CC update request received and successfully processed // Action: Send CC update answer, debit used units, reserve new units, restart Tcc // New State: OPEN startTcc(answer.getValidityTimeAvp()); } else { // Current State: OPEN // Event: CC update request received but not successfully processed // Action: Send CC update answer with Result-Code != SUCCESS, debit used units // New State: IDLE // It's a failure, we wait for Tcc to fire -- FIXME: Alexandre: Should we? } } catch (AvpDataException e) { throw new InternalException(e); } dispatchEvent(localEvent.getAnswer()); break; case RECEIVED_TERMINATE: listener.doCreditControlRequest(this, (GxCreditControlRequest)localEvent.getRequest()); break; case SENT_TERMINATE_RESPONSE: answer = (GxCreditControlAnswer) localEvent.getAnswer(); try { // Current State: OPEN // Event: CC termination request received and successfully processed // Action: Send CC termination answer, Stop Tcc, debit used units // New State: IDLE if(isSuccess(answer.getResultCodeAvp().getUnsigned32())) { stopTcc(false); } else { // Current State: OPEN // Event: CC termination request received but not successfully processed // Action: Send CC termination answer with Result-Code != SUCCESS, debit used units // New State: IDLE // It's a failure, we wait for Tcc to fire -- FIXME: Alexandre: Should we? } } catch (AvpDataException e) { throw new InternalException(e); } newState = ServerGxSessionState.IDLE; dispatchEvent(localEvent.getAnswer()); setState(newState); break; case RECEIVED_RAA: listener.doGxReAuthAnswer(this, (GxReAuthRequest)localEvent.getRequest(), (GxReAuthAnswer)localEvent.getAnswer()); break; case SENT_RAR: dispatchEvent(localEvent.getRequest()); break; } } return true; } catch (Exception e) { throw new InternalException(e); } finally { sendAndStateLock.unlock(); } } /* * (non-Javadoc) * * @see org.jdiameter.common.impl.app.AppSessionImpl#isReplicable() */ @Override public boolean isReplicable() { return true; } private class TccScheduledTask implements Runnable { ServerGxSession session = null; private TccScheduledTask(ServerGxSession session) { super(); this.session = session; } public void run() { // Current State: OPEN // Event: Session supervision timer Tcc expired // Action: Release reserved units // New State: IDLE context.sessionSupervisionTimerExpired(session); try { sendAndStateLock.lock(); // tccFuture = null; sessionData.setTccTimerId(null); setState(ServerGxSessionState.IDLE); } finally { sendAndStateLock.unlock(); } } } public Answer processRequest(Request request) { RequestDelivery rd = new RequestDelivery(); //rd.session = (ServerGxSession) LocalDataSource.INSTANCE.getSession(request.getSessionId()); rd.session = this; rd.request = request; super.scheduler.execute(rd); return null; } 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) { context.timeoutExpired(request); //FIXME: Should we release ? } private void startTcc(Avp validityAvp) { // There is no Validity-Time //long tccTimeout; // //if(validityAvp != null) { // try { // tccTimeout = 2 * validityAvp.getUnsigned32(); // } // catch (AvpDataException e) { // logger.debug("Unable to retrieve Validity-Time AVP value, using default.", e); // tccTimeout = 2 * context.getDefaultValidityTime(); // } //} //else { // tccTimeout = 2 * context.getDefaultValidityTime(); //} // //if(tccTimerId != null) { // stopTcc(true); // //tccFuture = super.scheduler.schedule(new TccScheduledTask(this), defaultValue, TimeUnit.SECONDS); // tccTimerId = super.timerFacility.schedule(this.sessionId, TCC_TIMER_NAME, tccTimeout * 1000); // // FIXME: this accepts Future! // context.sessionSupervisionTimerReStarted(this, null); //} //else { // //tccFuture = super.scheduler.schedule(new TccScheduledTask(this), defaultValue, TimeUnit.SECONDS); // tccTimerId = super.timerFacility.schedule(this.sessionId, TCC_TIMER_NAME, tccTimeout * 1000); // //FIXME: this accepts Future! // context.sessionSupervisionTimerStarted(this, null); //} //super.sessionDataSource.updateSession(this); } /* * (non-Javadoc) * * @see org.jdiameter.common.impl.app.AppSessionImpl#onTimer(java.lang.String) */ @Override public void onTimer(String timerName) { if (timerName.equals(TCC_TIMER_NAME)) { new TccScheduledTask(this).run(); } } private void stopTcc(boolean willRestart) { final Serializable tccTimerId = this.sessionData.getTccTimerId(); if (tccTimerId != null) { super.timerFacility.cancel(tccTimerId); this.sessionData.setTccTimerId(null); if (!willRestart && context!=null) { context.sessionSupervisionTimerStopped(this, null); } } } protected boolean isProvisional(long resultCode) { return resultCode >= 1000 && resultCode < 2000; } protected boolean isSuccess(long resultCode) { return resultCode >= 2000 && resultCode < 3000; } protected void setState(ServerGxSessionState newState) { setState(newState, true); } @SuppressWarnings("unchecked") protected void setState(ServerGxSessionState newState, boolean release) { IAppSessionState oldState = this.sessionData.getServerGxSessionState(); this.sessionData.setServerGxSessionState(newState); for (StateChangeListener i : stateListeners) { i.stateChanged(this, (Enum) oldState, (Enum) newState); } if (newState == ServerGxSessionState.IDLE) { stopTcc(false); if (release) { // NOTE: do EVERYTHING before release. this.release(); } } } @Override public void release() { if (isValid()) { try { this.sendAndStateLock.lock(); this.stopTcc(false); 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 send(Event.Type type, AppRequestEvent request, AppAnswerEvent 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(); } } protected void dispatchEvent(AppEvent event) throws InternalException { try { session.send(event.getMessage(), this); // Store last destination information } catch(Exception e) { throw new InternalException(e); // logger.debug("Failure trying to dispatch event", e); } } @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; ServerGxSessionImpl other = (ServerGxSessionImpl) 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 { ServerGxSession session; Request request; public void run() { try { switch (request.getCommandCode()) { case GxCreditControlAnswer.code: handleEvent(new Event(true, factory.createCreditControlRequest(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 { ServerGxSession session; Answer answer; Request request; public void run() { try { // FIXME: baranowb: add message validation here!!! // We handle CCR, STR, ACR, ASR other go into extension switch (request.getCommandCode()) { case GxReAuthRequest.code: handleEvent(new Event(Event.Type.RECEIVED_RAA, factory.createGxReAuthRequest(request), factory.createGxReAuthAnswer(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.server.impl.app.gx; import java.io.Serializable; import org.jdiameter.common.api.app.AppSessionDataLocalImpl; import org.jdiameter.common.api.app.gx.ServerGxSessionState; /** * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public class ServerGxSessionDataLocalImpl extends AppSessionDataLocalImpl implements IServerGxSessionData { protected boolean stateless = true; protected ServerGxSessionState state = ServerGxSessionState.IDLE; protected Serializable tccTimerId; /** * */ public ServerGxSessionDataLocalImpl() { } public boolean isStateless() { return stateless; } public void setStateless(boolean stateless) { this.stateless = stateless; } public ServerGxSessionState getServerGxSessionState() { return state; } public void setServerGxSessionState(ServerGxSessionState state) { this.state = state; } public Serializable getTccTimerId() { return tccTimerId; } public void setTccTimerId(Serializable tccTimerId) { this.tccTimerId = tccTimerId; } }
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.server.impl.app.rx; import org.jdiameter.common.api.app.AppSessionDataLocalImpl; import org.jdiameter.common.api.app.rx.ServerRxSessionState; /** * * @author <a href="mailto:richard.good@smilecoms.com"> Richard Good </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class ServerRxSessionDataLocalImpl extends AppSessionDataLocalImpl implements IServerRxSessionData { protected boolean stateless = true; protected ServerRxSessionState state = ServerRxSessionState.IDLE; /** * */ public ServerRxSessionDataLocalImpl() { } public boolean isStateless() { return stateless; } public void setStateless(boolean stateless) { this.stateless = stateless; } public ServerRxSessionState getServerRxSessionState() { return state; } public void setServerRxSessionState(ServerRxSessionState state) { this.state = state; } }
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.server.impl.app.rx; import org.jdiameter.common.api.app.rx.IRxSessionData; import org.jdiameter.common.api.app.rx.ServerRxSessionState; /** * * @author <a href="mailto:richard.good@smilecoms.com"> Richard Good </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public interface IServerRxSessionData extends IRxSessionData{ public boolean isStateless(); public void setStateless(boolean stateless); public ServerRxSessionState getServerRxSessionState(); public void setServerRxSessionState(ServerRxSessionState state); }
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.server.impl.app.rx; 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.rx.events.RxAAAnswer; import org.jdiameter.api.rx.events.RxAARequest; import org.jdiameter.api.rx.events.RxAbortSessionAnswer; import org.jdiameter.api.rx.events.RxAbortSessionRequest; import org.jdiameter.api.rx.events.RxReAuthAnswer; import org.jdiameter.api.rx.events.RxReAuthRequest; import org.jdiameter.api.rx.events.RxSessionTermAnswer; import org.jdiameter.api.rx.events.RxSessionTermRequest; /** * * @author <a href="mailto:richard.good@smilecoms.com"> Richard Good </a> * @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 { public enum Type { SEND_AAA, RECEIVE_AAR, SEND_STA, RECEIVE_STR, SEND_RAR, RECEIVE_RAA, SEND_ASR, RECEIVE_ASA, SEND_EVENT_ANSWER, RECEIVE_EVENT_REQUEST; } 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, AppRequestEvent request, AppAnswerEvent answer) { this.answer = answer; this.request = request; if (isRequest) { switch (request.getCommandCode()) { case RxReAuthRequest.code: type = Type.SEND_RAR; break; case RxAbortSessionRequest.code: type = Type.SEND_ASR; break; case RxAARequest.code: type = Type.RECEIVE_AAR; break; case RxSessionTermRequest.code: type = Type.RECEIVE_STR; break; case 5: //BUG FIX How do we know this is an event and not a session? Do we need to fix this? Does Rx do event? type = Type.RECEIVE_EVENT_REQUEST; break; default: throw new RuntimeException("Wrong command code value: " + request.getCommandCode()); } } else { switch (answer.getCommandCode()) { case RxAbortSessionAnswer.code: type = Type.RECEIVE_ASA; break; case RxReAuthAnswer.code: type = Type.RECEIVE_RAA; break; case RxAAAnswer.code: type = Type.SEND_AAA; break; case RxSessionTermAnswer.code: type = Type.SEND_STA; break; case 6: //BUG FIX How do we know this is an event and not a session? Do we need to fix this? Does Rx do event? type = Type.SEND_EVENT_ANSWER; break; default: throw new RuntimeException("Wrong CC-Request-Type value: " + answer.getCommandCode()); } } } public <E> E encodeType(Class<E> eClass) { return eClass == Event.Type.class ? (E) type : null; } public Enum getType() { return type; } public int compareTo(Object o) { return 0; } public Object getData() { return this.request != null ? this.request : this.answer; } public void setData(Object data) { // data = (AppEvent) o; // FIXME: What should we do here?! Is it request or answer? } public AppEvent getRequest() { return request; } public AppEvent getAnswer() { return answer; } }
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.server.impl.app.rx; 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.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.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.app.StateChangeListener; import org.jdiameter.api.app.StateEvent; import org.jdiameter.api.rx.ServerRxSession; import org.jdiameter.api.rx.ServerRxSessionListener; import org.jdiameter.api.rx.events.RxAAAnswer; import org.jdiameter.api.rx.events.RxAARequest; import org.jdiameter.api.rx.events.RxAbortSessionAnswer; import org.jdiameter.api.rx.events.RxAbortSessionRequest; import org.jdiameter.api.rx.events.RxReAuthAnswer; import org.jdiameter.api.rx.events.RxReAuthRequest; import org.jdiameter.api.rx.events.RxSessionTermAnswer; import org.jdiameter.api.rx.events.RxSessionTermRequest; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.common.api.app.IAppSessionState; import org.jdiameter.common.api.app.rx.IRxMessageFactory; import org.jdiameter.common.api.app.rx.IServerRxSessionContext; import org.jdiameter.common.api.app.rx.ServerRxSessionState; import org.jdiameter.common.impl.app.AppAnswerEventImpl; import org.jdiameter.common.impl.app.AppRequestEventImpl; import org.jdiameter.common.impl.app.rx.AppRxSessionImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 3GPP IMS Rx Reference Point Server session implementation * * @author <a href="mailto:richard.good@smilecoms.com"> Richard Good </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class ServerRxSessionImpl extends AppRxSessionImpl implements ServerRxSession, NetworkReqListener, EventListener<Request, Answer> { private static final Logger logger = LoggerFactory.getLogger(ServerRxSessionImpl.class); // Session State Handling --------------------------------------------------- //protected boolean stateless = true; //protected ServerGxSessionState state = ServerGxSessionState.IDLE; protected Lock sendAndStateLock = new ReentrantLock(); // Factories and Listeners -------------------------------------------------- protected transient IRxMessageFactory factory = null; protected transient IServerRxSessionContext context = null; protected transient ServerRxSessionListener listener = null; protected long[] authAppIds = new long[]{4}; //protected String originHost, originRealm; protected IServerRxSessionData sessionData; public ServerRxSessionImpl(IServerRxSessionData sessionData, IRxMessageFactory fct, ISessionFactory sf, ServerRxSessionListener lst, IServerRxSessionContext 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"); } context = ctx; authAppIds = fct.getApplicationIds(); listener = lst; factory = fct; this.sessionData = sessionData; super.addStateChangeNotification(stLst); } public void sendAAAnswer(RxAAAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { handleEvent(new Event(false, null, answer)); } public void sendSessionTermAnswer(RxSessionTermAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { handleEvent(new Event(false, null, answer)); } public void sendReAuthRequest(RxReAuthRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SEND_RAR, request, null); } public void sendAbortSessionRequest(RxAbortSessionRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SEND_ASR, request, null); } public boolean isStateless() { return this.sessionData.isStateless(); } @SuppressWarnings("unchecked") public <E> E getState(Class<E> stateType) { return stateType == ServerRxSessionState.class ? (E) this.sessionData.getServerRxSessionState() : null; } public boolean handleEvent(StateEvent event) throws InternalException, OverloadException { ServerRxSessionState newState = null; try { sendAndStateLock.lock(); // Can be null if there is no state transition, transition to IDLE state should terminate this app session final Event localEvent = (Event) event; final ServerRxSessionState state = this.sessionData.getServerRxSessionState(); //Its kind of awkward, but with two state on server side its easier to go through event types? //but for sake of FSM readability final Event.Type eventType = (Event.Type) localEvent.getType(); switch (state) { case IDLE: switch (eventType) { case RECEIVE_AAR: listener.doAARequest(this, (RxAARequest) localEvent.getRequest()); break; case RECEIVE_EVENT_REQUEST: // Current State: IDLE // Event: AA event request received and successfully processed // Action: Send AA event answer // New State: IDLE listener.doAARequest(this, (RxAARequest) localEvent.getRequest()); break; // case SEND_EVENT_ANSWER: // // Current State: IDLE // // Event: AAR event request received and successfully processed // // Action: Send AA event answer // // New State: IDLE // // newState = ServerRxSessionState.IDLE; // dispatchEvent(localEvent.getAnswer()); // break; case SEND_AAA: RxAAAnswer answer = (RxAAAnswer) localEvent.getAnswer(); try { long resultCode = answer.getResultCodeAvp().getUnsigned32(); // Current State: IDLE // Event: AA initial request received and successfully processed // Action: Send AAinitial answer // New State: OPEN if (isSuccess(resultCode)) { newState = ServerRxSessionState.OPEN; } // Current State: IDLE // Event: AA initial request received but not successfully processed // Action: Send AA initial answer with Result-Code != SUCCESS // New State: IDLE else { newState = ServerRxSessionState.IDLE; } dispatchEvent(localEvent.getAnswer()); } catch (AvpDataException e) { throw new InternalException(e); } break; default: throw new InternalException("Wrong state: " + ServerRxSessionState.IDLE + " one event: " + eventType + " " + localEvent.getRequest() + " " + localEvent.getAnswer()); }//end switch eventType break; case OPEN: switch (eventType) { case RECEIVE_AAR: listener.doAARequest(this, (RxAARequest) localEvent.getRequest()); break; case SEND_AAA: RxAAAnswer answer = (RxAAAnswer) localEvent.getAnswer(); try { if (isSuccess(answer.getResultCodeAvp().getUnsigned32())) { // Current State: OPEN // Event: AA update request received and successfully processed // Action: Send AA update answer // New State: OPEN } else { // Current State: OPEN // Event: AA update request received but not successfully processed // Action: Send AA update answer with Result-Code != SUCCESS // New State: IDLE // It's a failure, we wait for Tcc to fire -- FIXME: Alexandre: Should we? } } catch (AvpDataException e) { throw new InternalException(e); } dispatchEvent(localEvent.getAnswer()); break; case RECEIVE_STR: listener.doSessionTermRequest(this, (RxSessionTermRequest) localEvent.getRequest()); break; case SEND_STA: RxSessionTermAnswer STA = (RxSessionTermAnswer) localEvent.getAnswer(); try { if (isSuccess(STA.getResultCodeAvp().getUnsigned32())) { // Current State: OPEN // Event: AA update request received and successfully processed // Action: Send AA update answer // New State: OPEN } else { // Current State: OPEN // Event: AA update request received but not successfully processed // Action: Send AA update answer with Result-Code != SUCCESS // New State: IDLE // It's a failure, we wait for Tcc to fire -- FIXME: Alexandre: Should we? } } catch (AvpDataException e) { throw new InternalException(e); } finally { newState = ServerRxSessionState.IDLE; } dispatchEvent(localEvent.getAnswer()); break; case RECEIVE_RAA: listener.doReAuthAnswer(this, (RxReAuthRequest) localEvent.getRequest(), (RxReAuthAnswer) localEvent.getAnswer()); break; case SEND_RAR: dispatchEvent(localEvent.getRequest()); break; case RECEIVE_ASA: listener.doAbortSessionAnswer(this, (RxAbortSessionRequest) localEvent.getRequest(), (RxAbortSessionAnswer) localEvent.getAnswer()); break; case SEND_ASR: dispatchEvent(localEvent.getRequest()); break; }//end switch eventtype break; } return true; } catch (Exception e) { throw new InternalException(e); } finally { if (newState != null) { setState(newState); } sendAndStateLock.unlock(); } } /* * (non-Javadoc) * * @see org.jdiameter.common.impl.app.AppSessionImpl#isReplicable() */ @Override public boolean isReplicable() { return true; } public Answer processRequest(Request request) { RequestDelivery rd = new RequestDelivery(); //rd.session = (ServerRxSession) LocalDataSource.INSTANCE.getSession(request.getSessionId()); rd.session = this; rd.request = request; super.scheduler.execute(rd); return null; } 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.common.impl.app.AppSessionImpl#onTimer(java.lang.String) */ @Override public void onTimer(String timerName) { } public void timeoutExpired(Request request) { // context.timeoutExpired(request); //FIXME: Should we release ? } protected boolean isProvisional(long resultCode) { return resultCode >= 1000 && resultCode < 2000; } protected boolean isSuccess(long resultCode) { return resultCode >= 2000 && resultCode < 3000; } protected void setState(ServerRxSessionState newState) { setState(newState, true); } @SuppressWarnings("unchecked") protected void setState(ServerRxSessionState newState, boolean release) { IAppSessionState oldState = this.sessionData.getServerRxSessionState(); this.sessionData.setServerRxSessionState(newState); for (StateChangeListener i : stateListeners) { i.stateChanged(this, (Enum) oldState, (Enum) newState); } if (newState == ServerRxSessionState.IDLE) { if (release) { // NOTE: do EVERYTHING before release. this.release(); } } } @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 send(Event.Type type, AppRequestEvent request, AppAnswerEvent 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(); } } protected void dispatchEvent(AppEvent event) throws InternalException { try { session.send(event.getMessage(), this); // Store last destination information } catch (Exception e) { //throw new InternalException(e); logger.debug("Failure trying to dispatch event", e); } } private class RequestDelivery implements Runnable { ServerRxSession session; Request request; public void run() { try { switch (request.getCommandCode()) { case RxAARequest.code: handleEvent(new Event(true, factory.createAARequest(request), null)); break; case RxSessionTermRequest.code: handleEvent(new Event(true, factory.createSessionTermRequest(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 { ServerRxSession session; Answer answer; Request request; public void run() { try { // FIXME: baranowb: add message validation here!!! // We handle CCR, STR, ACR, ASR other go into extension switch (request.getCommandCode()) { case RxReAuthRequest.code: handleEvent(new Event(Event.Type.RECEIVE_RAA, factory.createReAuthRequest(request), factory.createReAuthAnswer(answer))); break; case RxAbortSessionRequest.code: handleEvent(new Event(Event.Type.RECEIVE_ASA, factory.createAbortSessionRequest(request), factory.createAbortSessionAnswer(answer))); break; default: listener.doOtherEvent(session, new AppRequestEventImpl(request), new AppAnswerEventImpl(answer)); break; } } catch (Exception e) { logger.debug("Failed to process success message", e); } } } @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; } ServerRxSessionImpl other = (ServerRxSessionImpl) 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 2006, 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.server.impl.app.auth; import java.io.Serializable; import org.jdiameter.common.api.app.AppSessionDataLocalImpl; import org.jdiameter.common.api.app.auth.ServerAuthSessionState; /** * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public class ServerAuthSessionDataLocalImpl extends AppSessionDataLocalImpl implements IServerAuthSessionData { protected ServerAuthSessionState state = ServerAuthSessionState.IDLE; protected Serializable tsTimerId; protected long tsTimeout = NON_INITIALIZED; protected boolean stateless = true; /** * */ public ServerAuthSessionDataLocalImpl() { } /* (non-Javadoc) * @see org.jdiameter.server.impl.app.auth.IServerAuthSessionData#getServerAuthSessionState() */ @Override public ServerAuthSessionState getServerAuthSessionState() { return this.state; } /* (non-Javadoc) * @see org.jdiameter.server.impl.app.auth.IServerAuthSessionData#setServerAuthSessionState(org.jdiameter.common.api.app.auth.ServerAuthSessionState) */ @Override public void setServerAuthSessionState(ServerAuthSessionState state) { this.state = state; } /* (non-Javadoc) * @see org.jdiameter.server.impl.app.auth.IServerAuthSessionData#isStateless() */ @Override public boolean isStateless() { return this.stateless; } /* (non-Javadoc) * @see org.jdiameter.server.impl.app.auth.IServerAuthSessionData#setStateless(boolean) */ @Override public void setStateless(boolean stateless) { this.stateless = stateless; } /* (non-Javadoc) * @see org.jdiameter.server.impl.app.auth.IServerAuthSessionData#setTsTimeout(long) */ @Override public void setTsTimeout(long tsTimeout) { this.tsTimeout = tsTimeout; } /* (non-Javadoc) * @see org.jdiameter.server.impl.app.auth.IServerAuthSessionData#getTsTimeout() */ @Override public long getTsTimeout() { return this.tsTimeout; } /* (non-Javadoc) * @see org.jdiameter.server.impl.app.auth.IServerAuthSessionData#setTsTimerId(java.io.Serializable) */ @Override public void setTsTimerId(Serializable tsTimerId) { this.tsTimerId = tsTimerId; } /* (non-Javadoc) * @see org.jdiameter.server.impl.app.auth.IServerAuthSessionData#getTsTimerId() */ @Override public Serializable getTsTimerId() { return this.tsTimerId; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl.app.auth; import java.io.Serializable; import org.jdiameter.common.api.app.auth.IAuthSessionData; import org.jdiameter.common.api.app.auth.ServerAuthSessionState; /** * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public interface IServerAuthSessionData extends IAuthSessionData{ public ServerAuthSessionState getServerAuthSessionState(); public void setServerAuthSessionState(ServerAuthSessionState state); public boolean isStateless(); public void setStateless(boolean b); public void setTsTimeout(long l); public long getTsTimeout(); public void setTsTimerId(Serializable tid); public Serializable getTsTimerId(); }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl.app.auth; import org.jdiameter.api.app.AppEvent; import org.jdiameter.api.app.StateEvent; /** * * @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> */ class Event implements StateEvent { enum Type{ RECEIVE_AUTH_REQUEST, RECEIVE_STR_REQUEST, SEND_ASR_REQUEST, SEND_ASR_FAILURE, RECEIVE_ASR_ANSWER, TIMEOUT_EXPIRES } Type type; AppEvent data; Event(Type type, AppEvent data) { this.type = type; this.data = data; } public <E> E encodeType(Class<E> eClass) { return eClass == Type.class ? (E) type : null; } public Enum getType() { return type; } public void setData(Object o) { data = (AppEvent) o; } public Object getData() { return data; } public int compareTo(Object o) { return 0; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl.app.auth; import static org.jdiameter.common.api.app.auth.ServerAuthSessionState.DISCONNECTED; import static org.jdiameter.common.api.app.auth.ServerAuthSessionState.IDLE; import static org.jdiameter.common.api.app.auth.ServerAuthSessionState.OPEN; import static org.jdiameter.server.impl.app.auth.Event.Type.RECEIVE_ASR_ANSWER; import static org.jdiameter.server.impl.app.auth.Event.Type.RECEIVE_AUTH_REQUEST; import static org.jdiameter.server.impl.app.auth.Event.Type.TIMEOUT_EXPIRES; import java.io.Serializable; 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.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.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.app.StateChangeListener; import org.jdiameter.api.app.StateEvent; import org.jdiameter.api.auth.ServerAuthSession; import org.jdiameter.api.auth.ServerAuthSessionListener; import org.jdiameter.api.auth.events.AbortSessionAnswer; import org.jdiameter.api.auth.events.AbortSessionRequest; import org.jdiameter.api.auth.events.ReAuthRequest; import org.jdiameter.api.auth.events.SessionTermAnswer; import org.jdiameter.api.auth.events.SessionTermRequest; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.common.api.app.IAppSessionState; import org.jdiameter.common.api.app.auth.IAuthMessageFactory; import org.jdiameter.common.api.app.auth.IServerAuthActionContext; import org.jdiameter.common.api.app.auth.ServerAuthSessionState; import org.jdiameter.common.impl.app.AppAnswerEventImpl; import org.jdiameter.common.impl.app.auth.AbortSessionAnswerImpl; import org.jdiameter.common.impl.app.auth.AbortSessionRequestImpl; import org.jdiameter.common.impl.app.auth.AppAuthSessionImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Server Authorization session implementation * * @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 ServerAuthSessionImpl extends AppAuthSessionImpl implements ServerAuthSession, EventListener<Request, Answer>, NetworkReqListener { private static final long serialVersionUID = 1L; protected static final Logger logger = LoggerFactory.getLogger(ServerAuthSessionImpl.class); protected IServerAuthSessionData sessionData; // Session State Handling --------------------------------------------------- private Lock sendAndStateLock = new ReentrantLock(); // Factories and Listeners -------------------------------------------------- protected transient IAuthMessageFactory factory; protected transient IServerAuthActionContext context; protected transient ServerAuthSessionListener listener; // Ts Timer ----------------------------------------------------------------- protected final static String TIMER_NAME_TS="AUTH_TS"; // Constructors ------------------------------------------------------------- public ServerAuthSessionImpl(IServerAuthSessionData sessionData,ISessionFactory sf, ServerAuthSessionListener lst, IAuthMessageFactory fct, StateChangeListener<AppSession> scListener,IServerAuthActionContext context, long tsTimeout, boolean stateless) { super(sf,sessionData); super.appId = fct.getApplicationId(); this.listener = lst; this.factory = fct; this.context = context; this.sessionData = sessionData; this.sessionData.setStateless(stateless); this.sessionData.setTsTimeout(tsTimeout); super.addStateChangeNotification(scListener); } // ServerAuthSession Implementation methods --------------------------------- public void sendAuthAnswer(AppAnswerEvent appAnswerEvent) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(null, appAnswerEvent); } public void sendReAuthRequest(ReAuthRequest reAuthRequest) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(null, reAuthRequest); } public void sendAbortSessionRequest(AbortSessionRequest abortSessionRequest) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SEND_ASR_REQUEST, abortSessionRequest); } public void sendSessionTerminationAnswer(SessionTermAnswer sessionTermAnswer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(null, sessionTermAnswer); } protected void send(Event.Type type, AppEvent event) throws InternalException { try { sendAndStateLock.lock(); if (type != null) { handleEvent(new Event(type, event)); } session.send(event.getMessage(), this); } catch (Exception e) { throw new InternalException(e); } finally { sendAndStateLock.unlock(); } } public boolean isStateless() { return sessionData.isStateless(); } @SuppressWarnings("unchecked") protected void setState(ServerAuthSessionState newState) { IAppSessionState oldState = sessionData.getServerAuthSessionState(); sessionData.setServerAuthSessionState(newState); for (StateChangeListener i : stateListeners) { i.stateChanged(this,(Enum) oldState, (Enum) newState); } } @SuppressWarnings("unchecked") public <E> E getState(Class<E> eClass) { return eClass == ServerAuthSessionState.class ? (E) sessionData.getServerAuthSessionState() : null; } public boolean handleEvent(StateEvent event) throws InternalException, OverloadException { return isStateless() ? handleEventForStatelessSession(event) : handleEventForStatefullSession(event); } public boolean handleEventForStatelessSession(StateEvent event) throws InternalException, OverloadException { try { switch (sessionData.getServerAuthSessionState()) { case IDLE: switch ((Event.Type) event.getType()) { case RECEIVE_AUTH_REQUEST: // Current State: IDLE // Event: Service-specific authorization request received, and successfully processed // Action: Send service specific answer // New State: IDLE setState(IDLE); listener.doAuthRequestEvent(this, (AppRequestEvent) event.getData()); break; default: logger.debug("Unknown event {}", event.getType()); break; } break; } } catch (Throwable t) { throw new InternalException(t); } return true; } public boolean handleEventForStatefullSession(StateEvent event) throws InternalException, OverloadException { ServerAuthSessionState state = sessionData.getServerAuthSessionState(); ServerAuthSessionState oldState = state; try { switch (state) { case IDLE: { switch ((Event.Type) event.getType()) { case RECEIVE_AUTH_REQUEST: try { // Current State: IDLE // Event: Service-specific authorization request received, and user is authorized // Action: Send successful service specific answer // New State: OPEN setState(OPEN); listener.doAuthRequestEvent(this, (AppRequestEvent) event.getData()); } catch (Exception e) { setState(IDLE); } break; case RECEIVE_STR_REQUEST: try { // Current State: ANY // Event: STR Received // Action: Send STA, Cleanup // New State: IDLE setState(IDLE); listener.doSessionTerminationRequestEvent(this, (SessionTermRequest) event.getData()); } catch (Exception e) { logger.debug("Can not handle event", e); } break; case SEND_ASR_REQUEST: setState(DISCONNECTED); break; case TIMEOUT_EXPIRES: if (context != null) { context.accessTimeoutElapses(this); } setState(IDLE); break; default: logger.debug("Unknown event {}", event.getType()); break; } break; } case OPEN: { switch ((Event.Type) event.getType()) { case RECEIVE_AUTH_REQUEST: try { // Current State: OPEN // Event: Service-specific authorization request received, and user is authorized // Action: Send successful service specific answer // New State: OPEN listener.doAuthRequestEvent(this, (AppRequestEvent) event.getData()); } catch (Exception e) { // Current State: OPEN // Event: Service-specific authorization request received, and user is not authorized // Action: Send failed service specific answer, Cleanup // New State: IDLE setState(IDLE); } break; case RECEIVE_STR_REQUEST: try { setState(IDLE); listener.doSessionTerminationRequestEvent(this, (SessionTermRequest) event.getData()); } catch (Exception e) { logger.debug("Can not handle event", e); } break; case SEND_ASR_REQUEST: // Current State: OPEN // Event: Home server wants to terminate the service // Action: Send ASR // New State: DISCON setState(DISCONNECTED); break; case TIMEOUT_EXPIRES: // Current State: OPEN // Event: Authorization-Lifetime (and Auth-Grace-Period) expires on home server. // Action: Cleanup // New State: IDLE // Current State: OPEN // Event: Session-Timeout expires on home server // Action: Cleanup // New State: IDLE if (context != null) { context.accessTimeoutElapses(this); } setState(IDLE); break; default: logger.debug("Unknown event {}", event.getType()); break; } break; } case DISCONNECTED: { switch ((Event.Type) event.getType()) { case SEND_ASR_FAILURE: // Current State: DISCON // Event: Failure to send ASR // Action: Wait, Re-send ASR // New State: DISCON setState(DISCONNECTED); break; case RECEIVE_ASR_ANSWER: // Current State: DISCON // Event: ASR successfully sent and ASA Received with Result-Code // Action: Cleanup // New State: IDLE setState(IDLE); listener.doAbortSessionAnswerEvent(this, (AbortSessionAnswer) event.getData()); break; default: logger.debug("Unknown event {}", event.getType()); break; } break; } default: { logger.debug("Unknown state {}", state); break; } } // post processing if (oldState != state) { if (OPEN.equals(state) && context != null) { if(context != null) { cancelTsTimer(); startTsTimer(); } // scheduler.schedule(new Runnable() { // public void run() { // if (context != null) { // try { // handleEvent(new Event(TIMEOUT_EXPIRES, null)); // } // catch (Exception e) { // logger.debug("Can not handle event", e); // } // } // } // }, context.createAccessTimer(), TimeUnit.MILLISECONDS); } } } catch (Throwable t) { throw new InternalException(t); } return true; } 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.getCommandCode() == AbortSessionRequestImpl.code) { handleEvent(new Event(Event.Type.SEND_ASR_FAILURE, new AbortSessionRequestImpl(request))); } else { logger.debug("Timeout for unknown request {}", request); } } catch (Exception e) { logger.debug("Can not handle event", e); } } 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.common.impl.app.AppSessionImpl#isReplicable() */ @Override public boolean isReplicable() { return true; } protected void startTsTimer() { try { sendAndStateLock.lock(); if (sessionData.getTsTimeout() > 0) { sessionData.setTsTimerId(super.timerFacility.schedule(sessionData.getSessionId(), TIMER_NAME_TS, sessionData.getTsTimeout())); } } finally { sendAndStateLock.unlock(); } } protected void cancelTsTimer() { try { sendAndStateLock.lock(); Serializable tsTimerId = sessionData.getTsTimerId(); if(tsTimerId != null) { super.timerFacility.cancel(tsTimerId); sessionData.setTsTimerId(null); } } finally { sendAndStateLock.unlock(); } } /* (non-Javadoc) * @see org.jdiameter.common.impl.app.AppSessionImpl#onTimer(java.lang.String) */ @Override public void onTimer(String timerName) { if(timerName.equals(TIMER_NAME_TS)) { try { sendAndStateLock.lock(); sessionData.setTsTimerId(null); handleEvent(new Event(TIMEOUT_EXPIRES, null)); } catch (Exception e) { logger.debug("Can not handle event", 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; ServerAuthSessionImpl other = (ServerAuthSessionImpl) obj; if (sessionData == null) { if (other.sessionData != null) return false; } else if (!sessionData.equals(other.sessionData)) return false; return true; } @Override public void release() { if (isValid()) { try { sendAndStateLock.lock(); super.release(); this.context = null; this.listener = null; } 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 { ServerAuthSession session; Request request; public void run() { if (request != null) { if (request.getCommandCode() == factory.getAuthMessageCommandCode()) { try { sendAndStateLock.lock(); handleEvent(new Event(RECEIVE_AUTH_REQUEST, factory.createAuthRequest(request))); } catch (Exception e) { logger.debug("Can not handle event", e); } finally { sendAndStateLock.unlock(); } } else { try { listener.doOtherEvent(session, factory.createAuthRequest(request), null); } catch (Exception e) { logger.debug("Can not handle event", e); } } } } } private class AnswerDelivery implements Runnable { ServerAuthSession session; Answer answer; Request request; public void run() { try { sendAndStateLock.lock(); if (request.getCommandCode() == factory.getAuthMessageCommandCode()) { handleEvent(new Event(RECEIVE_AUTH_REQUEST, factory.createAuthRequest(request))); } else if (request.getCommandCode() == AbortSessionRequestImpl.code) { handleEvent(new Event(RECEIVE_ASR_ANSWER, new AbortSessionAnswerImpl(answer))); } else { listener.doOtherEvent(session, factory.createAuthRequest(request), new AppAnswerEventImpl(answer)); } } catch (Exception e) { logger.debug("Can not handle event", e); } finally { sendAndStateLock.unlock(); } } } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl.app.acc; import java.io.Serializable; import org.jdiameter.common.api.app.AppSessionDataLocalImpl; import org.jdiameter.common.api.app.acc.ServerAccSessionState; /** * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public class ServerAccSessionDataLocalImpl extends AppSessionDataLocalImpl implements IServerAccSessionData { protected ServerAccSessionState state = ServerAccSessionState.IDLE; protected boolean stateles = true; protected long tsTimeout = NON_INITIALIZED; protected Serializable tsTimerId; /** * */ public ServerAccSessionDataLocalImpl() { } /* * (non-Javadoc) * * @see org.jdiameter.server.impl.app.acc.IServerAccSessionData# * setServerAccSessionState * (org.jdiameter.common.api.app.acc.ServerAccSessionState) */ @Override public void setServerAccSessionState(ServerAccSessionState value) { this.state = value; } /* * (non-Javadoc) * * @see org.jdiameter.server.impl.app.acc.IServerAccSessionData# * getServerAccSessionState() */ @Override public ServerAccSessionState getServerAccSessionState() { return this.state; } /* * (non-Javadoc) * * @see * org.jdiameter.server.impl.app.acc.IServerAccSessionData#setStateles(boolean * ) */ @Override public void setStateless(boolean value) { this.stateles = value; } /* * (non-Javadoc) * * @see org.jdiameter.server.impl.app.acc.IServerAccSessionData#isStateles() */ @Override public boolean isStateless() { return this.stateles; } /* * (non-Javadoc) * * @see * org.jdiameter.server.impl.app.acc.IServerAccSessionData#setTsTimeout( * long) */ @Override public void setTsTimeout(long value) { this.tsTimeout = value; } /* * (non-Javadoc) * * @see * org.jdiameter.server.impl.app.acc.IServerAccSessionData#getTsTimeout() */ @Override public long getTsTimeout() { return this.tsTimeout; } /* * (non-Javadoc) * * @see * org.jdiameter.server.impl.app.acc.IServerAccSessionData#setTsTimerId( * java.io.Serializable) */ @Override public void setTsTimerId(Serializable value) { this.tsTimerId = value; } /* * (non-Javadoc) * * @see * org.jdiameter.server.impl.app.acc.IServerAccSessionData#getTsTimerId() */ @Override public Serializable getTsTimerId() { return this.tsTimerId; } }
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.server.impl.app.acc; import org.jdiameter.api.acc.events.AccountRequest; import org.jdiameter.api.app.AppEvent; import org.jdiameter.api.app.StateEvent; /** * * @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> */ class Event implements StateEvent { enum Type{ RECEIVED_EVENT_RECORD, RECEIVED_START_RECORD, RECEIVED_INTERIM_RECORD, RECEIVED_STOP_RECORD } Type type; AppEvent data; Event(Type type) { this.type = type; } Event(AccountRequest accountRequest) throws Exception { data = accountRequest; int type = accountRequest.getAccountingRecordType(); switch (type) { case 1: this.type = Type.RECEIVED_EVENT_RECORD; break; case 2: this.type = Type.RECEIVED_START_RECORD; break; case 3: this.type = Type.RECEIVED_INTERIM_RECORD; break; case 4: this.type = Type.RECEIVED_STOP_RECORD; break; default: throw new Exception("Unknown type " + type); } } public <E> E encodeType(Class<E> eClass) { return eClass == Type.class ? (E) type : null; } public Enum getType() { return type; } public void setData(Object o) { data = (AppEvent) o; } public Object getData() { return data; } public int compareTo(Object other) { return equals(other) ? 0 : -1; } public boolean equals(Object other) { return this == other; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl.app.acc; import java.io.Serializable; import org.jdiameter.common.api.app.acc.IAccSessionData; import org.jdiameter.common.api.app.acc.ServerAccSessionState; /** * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public interface IServerAccSessionData extends IAccSessionData { public void setServerAccSessionState(ServerAccSessionState value); public ServerAccSessionState getServerAccSessionState(); public void setStateless(boolean value); public boolean isStateless(); /** * Seconds value, its taken from either request or answer. Contained in Acct-Interim-Interval AVP * @param value */ public void setTsTimeout(long value); public long getTsTimeout(); public void setTsTimerId(Serializable value); public Serializable getTsTimerId(); }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl.app.acc; import static org.jdiameter.common.api.app.acc.ServerAccSessionState.IDLE; import static org.jdiameter.common.api.app.acc.ServerAccSessionState.OPEN; import java.io.Serializable; import org.jdiameter.api.Answer; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpDataException; import org.jdiameter.api.AvpSet; import org.jdiameter.api.EventListener; import org.jdiameter.api.IllegalDiameterStateException; import org.jdiameter.api.InternalException; import org.jdiameter.api.NetworkReqListener; import org.jdiameter.api.OverloadException; import org.jdiameter.api.Request; import org.jdiameter.api.ResultCode; import org.jdiameter.api.RouteException; import org.jdiameter.api.acc.ServerAccSession; import org.jdiameter.api.acc.ServerAccSessionListener; import org.jdiameter.api.acc.events.AccountAnswer; import org.jdiameter.api.acc.events.AccountRequest; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.app.StateChangeListener; import org.jdiameter.api.app.StateEvent; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.common.api.app.IAppSessionState; import org.jdiameter.common.api.app.acc.IServerAccActionContext; import org.jdiameter.common.api.app.acc.ServerAccSessionState; import org.jdiameter.common.impl.app.acc.AccountRequestImpl; import org.jdiameter.common.impl.app.acc.AppAccSessionImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Server Accounting session implementation * * @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 ServerAccSessionImpl extends AppAccSessionImpl implements EventListener<Request, Answer>, ServerAccSession, NetworkReqListener { private static final Logger logger = LoggerFactory.getLogger(ServerAccSessionImpl.class); // Factories and Listeners -------------------------------------------------- protected transient IServerAccActionContext context; protected transient ServerAccSessionListener listener; // Ts Timer ----------------------------------------------------------------- protected static final String TIMER_NAME_TS = "TS"; protected IServerAccSessionData sessionData; // Constructors ------------------------------------------------------------- public ServerAccSessionImpl(IServerAccSessionData sessionData, ISessionFactory sessionFactory, ServerAccSessionListener serverSessionListener, IServerAccActionContext serverContextListener,StateChangeListener<AppSession> stLst,boolean stateless) { // TODO Auto-generated constructor stub this(sessionData,sessionFactory,serverSessionListener,serverContextListener,stLst); this.sessionData.setTsTimeout(0); // 0 == turn off this.sessionData.setStateless(stateless); } public ServerAccSessionImpl(IServerAccSessionData sessionData, ISessionFactory sessionFactory, ServerAccSessionListener serverSessionListener, IServerAccActionContext serverContextListener,StateChangeListener<AppSession> stLst) { // TODO Auto-generated constructor stub super(sessionFactory,sessionData); this.sessionData = sessionData; this.listener = serverSessionListener; this.context = serverContextListener; super.addStateChangeNotification(stLst); } public void sendAccountAnswer(AccountAnswer accountAnswer) throws InternalException, IllegalStateException, RouteException, OverloadException { try { AvpSet avpSet = accountAnswer.getMessage().getAvps(); Avp acctInterimIntervalAvp = avpSet.getAvp(Avp.ACCT_INTERIM_INTERVAL); //Unsigned32 if(acctInterimIntervalAvp != null) { try { this.sessionData.setTsTimeout(acctInterimIntervalAvp.getUnsigned32()); } catch (AvpDataException e) { throw new InternalException(e); } } cancelTsTimer(); startTsTimer(); session.send(accountAnswer.getMessage()); /* TODO: Do we need to notify state change ? */ if(isStateless() && isValid()) { session.release(); } } catch (IllegalDiameterStateException e) { throw new IllegalStateException(e); } } public boolean isStateless() { return sessionData.isStateless(); } @SuppressWarnings("unchecked") protected void setState(IAppSessionState newState) { IAppSessionState oldState = sessionData.getServerAccSessionState(); sessionData.setServerAccSessionState((ServerAccSessionState) newState); for (StateChangeListener i : stateListeners) { i.stateChanged(this,(Enum) oldState, (Enum) newState); } } public boolean handleEvent(StateEvent event) throws InternalException, OverloadException { return sessionData.isStateless() ? handleEventForStatelessMode(event) : handleEventForStatefulMode(event); } public boolean handleEventForStatelessMode(StateEvent event) throws InternalException, OverloadException { try { //NOTE: NO Ts Timer here //this will handle RTRs as well, no need to alter. ServerAccSessionState state = sessionData.getServerAccSessionState(); switch (state) { case IDLE: { switch ((Event.Type) event.getType()) { case RECEIVED_START_RECORD: // Current State: IDLE // Event: Accounting start request received, and successfully processed. // Action: Send accounting start answer // New State: IDLE if (listener != null) { try { listener.doAccRequestEvent(this, (AccountRequest) event.getData()); } catch (Exception e) { logger.debug("Can not handle event", e); } } // TODO: This is unnecessary state change: setState(IDLE); break; case RECEIVED_EVENT_RECORD: // Current State: IDLE // Event: Accounting event request received, and successfully processed. // Action: Send accounting event answer // New State: IDLE if (listener != null) { try { listener.doAccRequestEvent(this, (AccountRequest) event.getData()); } catch (Exception e) { logger.debug("Can not handle event", e); } } // FIXME: it is required, so we know it ends up again in IDLE! setState(IDLE); break; case RECEIVED_INTERIM_RECORD: // Current State: IDLE // Event: Interim record received, and successfully processed. // Action: Send accounting interim answer // New State: IDLE if (listener != null) { try { listener.doAccRequestEvent(this, (AccountRequest) event.getData()); } catch (Exception e) { logger.debug("Can not handle event", e); } } // TODO: This is unnecessary state change: setState(IDLE); break; case RECEIVED_STOP_RECORD: // Current State: IDLE // Event: Accounting stop request received, and successfully processed // Action: Send accounting stop answer // New State: IDLE if (listener != null) { try { listener.doAccRequestEvent(this, (AccountRequest) event.getData()); } catch (Exception e) { logger.debug("Can not handle event", e); } } // TODO: This is unnecessary state change: setState(IDLE); break; default: throw new IllegalStateException("Current state " + state + " action " + event.getType()); } } } } catch (Exception e) { logger.debug("Can not process event", e); return false; } finally { // TODO: Since setState was removed, we are now using this to terminate. Correct? // We can't release here, answer needs to be sent through. done at send. // release(); } return true; } public boolean handleEventForStatefulMode(StateEvent event) throws InternalException, OverloadException { try { if (((AccountRequest) event.getData()).getMessage().isReTransmitted()) { try { cancelTsTimer(); startTsTimer(); setState(OPEN); listener.doAccRequestEvent(this, (AccountRequest) event.getData()); if (context != null) { context.sessionTimerStarted(this, null); } } catch (Exception e) { logger.debug("Can not handle event", e); setState(IDLE); } return true; } else { ServerAccSessionState state = sessionData.getServerAccSessionState(); AccountRequest request = (AccountRequest) event.getData(); AvpSet avpSet = request.getMessage().getAvps(); Avp acctInterimIntervalAvp = avpSet.getAvp(85);//Unsigned32 if(acctInterimIntervalAvp!=null) { this.sessionData.setTsTimeout(acctInterimIntervalAvp.getUnsigned32()); } switch (state) { case IDLE: { switch ((Event.Type) event.getType()) { case RECEIVED_START_RECORD: // Current State: IDLE // Event: Accounting start request received, and successfully processed. // Action: Send accounting start answer, Start Ts // New State: OPEN setState(OPEN); if (listener != null) { try { listener.doAccRequestEvent(this, (AccountRequest) event.getData()); cancelTsTimer(); startTsTimer(); if (context != null) { context.sessionTimerStarted(this, null); } } catch (Exception e) { logger.debug("Can not handle event", e); setState(IDLE); } } break; case RECEIVED_EVENT_RECORD: // Current State: IDLE // Event: Accounting event request received, and // successfully processed. // Action: Send accounting event answer // New State: IDLE if (listener != null) { try { listener.doAccRequestEvent(this, (AccountRequest) event.getData()); } catch (Exception e) { logger.debug("Can not handle event", e); } } break; } break; } case OPEN: { switch ((Event.Type) event.getType()) { case RECEIVED_INTERIM_RECORD: // Current State: OPEN // Event: Interim record received, and successfully // processed. // Action: Send accounting interim answer, Restart Ts // New State: OPEN try { listener.doAccRequestEvent(this, (AccountRequest) event.getData()); cancelTsTimer(); startTsTimer(); if (context != null) { context.sessionTimerStarted(this, null); } } catch (Exception e) { logger.debug("Can not handle event", e); setState(IDLE); } break; case RECEIVED_STOP_RECORD: // Current State: OPEN // Event: Accounting stop request received, and // successfully // processed // Action: Send accounting stop answer, Stop Ts // New State: IDLE try { setState(IDLE); cancelTsTimer(); listener.doAccRequestEvent(this, (AccountRequest) event.getData()); if (context != null) { context.sessionTimerCanceled(this, null); } } catch (Exception e) { logger.debug("Can not handle event", e); setState(IDLE); } break; } break; } } } } catch (Exception e) { logger.debug("Can not process event", e); return false; } return true; } private void startTsTimer() { try{ sendAndStateLock.lock(); if(sessionData.getTsTimeout() > 0) { Serializable tsTid = super.timerFacility.schedule(sessionData.getSessionId(), TIMER_NAME_TS, sessionData.getTsTimeout()); sessionData.setTsTimerId(tsTid); } return; } finally { sendAndStateLock.unlock(); } } private void cancelTsTimer() { try{ sendAndStateLock.lock(); Serializable tsTid = sessionData.getTsTimerId(); if(tsTid != null) { super.timerFacility.cancel(tsTid); sessionData.setTsTimerId(null); } } finally { sendAndStateLock.unlock(); } } /* (non-Javadoc) * @see org.jdiameter.common.impl.app.AppSessionImpl#onTimer(java.lang.String) */ @Override public void onTimer(String timerName) { if(timerName.equals(TIMER_NAME_TS)) { if (context != null) { try { context.sessionTimeoutElapses(ServerAccSessionImpl.this); } catch (InternalException e) { logger.debug("Failure on processing expired Ts", e); } } setState(IDLE); } else { // FIXME: ??? } } protected Answer createStopAnswer(Request request) { Answer answer = request.createAnswer(ResultCode.SUCCESS); answer.getAvps().addAvp(Avp.ACC_RECORD_TYPE, 4); answer.getAvps().addAvp(request.getAvps().getAvp(Avp.ACC_RECORD_NUMBER)); return answer; } protected Answer createInterimAnswer(Request request) { Answer answer = request.createAnswer(ResultCode.SUCCESS); answer.getAvps().addAvp(Avp.ACC_RECORD_TYPE, 3); answer.getAvps().addAvp(request.getAvps().getAvp(Avp.ACC_RECORD_NUMBER)); return answer; } protected Answer createEventAnswer(Request request) { Answer answer = request.createAnswer(ResultCode.SUCCESS); answer.getAvps().addAvp(Avp.ACC_RECORD_TYPE, 2); answer.getAvps().addAvp(request.getAvps().getAvp(Avp.ACC_RECORD_NUMBER)); return answer; } protected Answer createStartAnswer(Request request) { Answer answer = request.createAnswer(ResultCode.SUCCESS); answer.getAvps().addAvp(Avp.ACC_RECORD_TYPE, 1); answer.getAvps().addAvp(request.getAvps().getAvp(Avp.ACC_RECORD_NUMBER)); return answer; } @SuppressWarnings("unchecked") public <E> E getState(Class<E> eClass) { return eClass == ServerAccSessionState.class ? (E) sessionData.getServerAccSessionState() : null; } public Answer processRequest(Request request) { if (request.getCommandCode() == AccountRequestImpl.code) { try { sendAndStateLock.lock(); handleEvent(new Event(createAccountRequest(request))); } catch (Exception e) { logger.debug("Can not handle event", e); } finally { sendAndStateLock.unlock(); } } else { try { listener.doOtherEvent(this, createAccountRequest(request), null); } catch (Exception e) { logger.debug("Can not handle event", e); } } return null; } public void receivedSuccessMessage(Request request, Answer answer) { if(request.getCommandCode() == AccountRequestImpl.code) { try { sendAndStateLock.lock(); handleEvent(new Event(createAccountRequest(request))); } catch (Exception e) { logger.debug("Can not handle event", e); } finally { sendAndStateLock.unlock(); } try { listener.doAccRequestEvent(this, createAccountRequest(request)); } catch (Exception e) { logger.debug("Can not handle event", e); } } else { try { listener.doOtherEvent(this, createAccountRequest(request), createAccountAnswer(answer)); } catch (Exception e) { logger.debug("Can not handle event", e); } } } public void timeoutExpired(Request request) { // FIXME: alexandre: We don't do anything here... are we even getting this on server? } /* (non-Javadoc) * @see org.jdiameter.common.impl.app.AppSessionImpl#isReplicable() */ @Override public boolean isReplicable() { 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()); } } }
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.server.impl.app.gq; import org.jdiameter.api.app.AppEvent; import org.jdiameter.api.app.StateEvent; /** * * @author <a href="mailto:webdev@web-ukraine.info"> Yulian Oifa </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ class Event implements StateEvent { enum Type{ RECEIVE_AUTH_REQUEST, SEND_AUTH_ANSWER, RECEIVE_STR_REQUEST, SEND_STR_ANSWER, SEND_ASR_REQUEST, SEND_ASR_FAILURE, RECEIVE_ASR_ANSWER, SEND_RAR_REQUEST, SEND_RAR_FAILURE, RECEIVE_RAR_ANSWER, TIMEOUT_EXPIRES } Type type; AppEvent data; Event(Type type, AppEvent data) { this.type = type; this.data = data; } public <E> E encodeType(Class<E> eClass) { return eClass == Type.class ? (E) type : null; } public Enum getType() { return type; } public void setData(Object o) { data = (AppEvent) o; } public Object getData() { return data; } public int compareTo(Object o) { return 0; } }
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.server.impl.app.gq; import static org.jdiameter.common.api.app.auth.ServerAuthSessionState.DISCONNECTED; import static org.jdiameter.common.api.app.auth.ServerAuthSessionState.IDLE; import static org.jdiameter.common.api.app.auth.ServerAuthSessionState.OPEN; import static org.jdiameter.server.impl.app.gq.Event.Type.RECEIVE_ASR_ANSWER; import static org.jdiameter.server.impl.app.gq.Event.Type.RECEIVE_AUTH_REQUEST; import static org.jdiameter.server.impl.app.gq.Event.Type.RECEIVE_STR_REQUEST; import static org.jdiameter.server.impl.app.gq.Event.Type.TIMEOUT_EXPIRES; import java.io.Serializable; 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.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.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.app.StateChangeListener; import org.jdiameter.api.app.StateEvent; import org.jdiameter.api.auth.ServerAuthSessionListener; import org.jdiameter.api.auth.events.AbortSessionAnswer; import org.jdiameter.api.auth.events.AbortSessionRequest; import org.jdiameter.api.auth.events.ReAuthAnswer; import org.jdiameter.api.auth.events.ReAuthRequest; import org.jdiameter.api.auth.events.SessionTermAnswer; import org.jdiameter.api.auth.events.SessionTermRequest; import org.jdiameter.api.gq.GqServerSession; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.common.api.app.IAppSessionState; import org.jdiameter.common.api.app.auth.IAuthMessageFactory; import org.jdiameter.common.api.app.auth.IServerAuthActionContext; import org.jdiameter.common.api.app.auth.ServerAuthSessionState; import org.jdiameter.common.impl.app.AppAnswerEventImpl; import org.jdiameter.common.impl.app.auth.AbortSessionAnswerImpl; import org.jdiameter.common.impl.app.auth.AbortSessionRequestImpl; import org.jdiameter.common.impl.app.auth.AppAuthSessionImpl; import org.jdiameter.common.impl.app.auth.ReAuthAnswerImpl; import org.jdiameter.common.impl.app.auth.ReAuthRequestImpl; import org.jdiameter.common.impl.app.auth.SessionTermRequestImpl; import org.jdiameter.server.impl.app.auth.IServerAuthSessionData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Server Gq Application session implementation * * @author <a href="mailto:webdev@web-ukraine.info"> Yulian Oifa </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class GqServerSessionImpl extends AppAuthSessionImpl implements GqServerSession, EventListener<Request, Answer>, NetworkReqListener { protected static final Logger logger = LoggerFactory.getLogger(GqServerSessionImpl.class); protected IServerAuthSessionData sessionData; // Session State Handling --------------------------------------------------- private Lock sendAndStateLock = new ReentrantLock(); // Factories and Listeners -------------------------------------------------- protected transient IAuthMessageFactory factory; protected transient IServerAuthActionContext context; protected transient ServerAuthSessionListener listener; // Ts Timer ----------------------------------------------------------------- protected final static String TIMER_NAME_TS = "GQ_TS"; // Constructors ------------------------------------------------------------- public GqServerSessionImpl(IServerAuthSessionData sessionData,ISessionFactory sf, ServerAuthSessionListener lst, IAuthMessageFactory fct, StateChangeListener<AppSession> scListener,IServerAuthActionContext context, long tsTimeout, boolean stateless) { super(sf,sessionData); super.appId = fct.getApplicationId(); this.listener = lst; this.factory = fct; this.context = context; this.sessionData = sessionData; this.sessionData.setStateless(stateless); this.sessionData.setTsTimeout(tsTimeout); super.addStateChangeNotification(scListener); } // ServerAuthSession Implementation methods --------------------------------- public void sendAuthAnswer(AppAnswerEvent appAnswerEvent) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(null, appAnswerEvent); } public void sendReAuthRequest(ReAuthRequest reAuthRequest) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(null, reAuthRequest); } public void sendAbortSessionRequest(AbortSessionRequest abortSessionRequest) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SEND_ASR_REQUEST, abortSessionRequest); } public void sendSessionTerminationAnswer(SessionTermAnswer sessionTermAnswer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { sendPost(Event.Type.SEND_STR_ANSWER, sessionTermAnswer); } protected void sendPost(Event.Type type, AppEvent event) throws InternalException { try { sendAndStateLock.lock(); session.send(event.getMessage(), this); if (type != null) { handleEvent(new Event(type, event)); } } catch (Exception e) { throw new InternalException(e); } finally { sendAndStateLock.unlock(); } } protected void send(Event.Type type, AppEvent event) throws InternalException { try { sendAndStateLock.lock(); if (type != null) { handleEvent(new Event(type, event)); } session.send(event.getMessage(), this); } catch (Exception e) { throw new InternalException(e); } finally { sendAndStateLock.unlock(); } } public boolean isStateless() { return sessionData.isStateless(); } @SuppressWarnings("unchecked") protected void setState(ServerAuthSessionState newState) { IAppSessionState oldState = sessionData.getServerAuthSessionState(); sessionData.setServerAuthSessionState(newState); for (StateChangeListener i : stateListeners) { i.stateChanged(this,(Enum) oldState, (Enum) newState); } } @SuppressWarnings("unchecked") public <E> E getState(Class<E> eClass) { return eClass == ServerAuthSessionState.class ? (E) sessionData.getServerAuthSessionState() : null; } public boolean handleEvent(StateEvent event) throws InternalException, OverloadException { return isStateless() ? handleEventForStatelessSession(event) : handleEventForStatefullSession(event); } public boolean handleEventForStatelessSession(StateEvent event) throws InternalException, OverloadException { try { switch (sessionData.getServerAuthSessionState()) { case IDLE: switch ((Event.Type) event.getType()) { case RECEIVE_AUTH_REQUEST: // Current State: IDLE // Event: Service-specific authorization request received, and successfully processed // Action: Send service specific answer // New State: IDLE listener.doAuthRequestEvent(this, (AppRequestEvent) event.getData()); setState(IDLE); break; default: logger.debug("Unknown event {}", event.getType()); break; } break; } } catch (Throwable t) { throw new InternalException(t); } return true; } public boolean handleEventForStatefullSession(StateEvent event) throws InternalException, OverloadException { ServerAuthSessionState state = sessionData.getServerAuthSessionState(); ServerAuthSessionState oldState = state; try { switch (state) { case IDLE: { switch ((Event.Type) event.getType()) { case RECEIVE_AUTH_REQUEST: try { // Current State: IDLE // Event: Service-specific authorization request received, and user is authorized // Action: Send successful service specific answer // New State: OPEN listener.doAuthRequestEvent(this, (AppRequestEvent) event.getData()); setState(OPEN); } catch (Exception e) { setState(IDLE); } break; case RECEIVE_STR_REQUEST: try { // Current State: ANY // Event: STR Received // Action: Send STA, Cleanup // New State: IDLE listener.doSessionTerminationRequestEvent(this, (SessionTermRequest) event.getData()); } catch (Exception e) { logger.debug("Can not handle event", e); } break; case SEND_ASR_REQUEST: setState(DISCONNECTED); break; case SEND_STR_ANSWER: setState(IDLE); break; case TIMEOUT_EXPIRES: if (context != null) { context.accessTimeoutElapses(this); } setState(IDLE); break; default: logger.debug("Unknown event {}", event.getType()); break; } break; } case OPEN: { switch ((Event.Type) event.getType()) { case RECEIVE_AUTH_REQUEST: try { // Current State: OPEN // Event: Service-specific authorization request received, and user is authorized // Action: Send successful service specific answer // New State: OPEN listener.doAuthRequestEvent(this, (AppRequestEvent) event.getData()); } catch (Exception e) { // Current State: OPEN // Event: Service-specific authorization request received, and user is not authorized // Action: Send failed service specific answer, Cleanup // New State: IDLE setState(IDLE); } break; case RECEIVE_STR_REQUEST: try { listener.doSessionTerminationRequestEvent(this, (SessionTermRequest) event.getData()); } catch (Exception e) { logger.debug("Can not handle event", e); } break; case SEND_ASR_REQUEST: // Current State: OPEN // Event: Home server wants to terminate the service // Action: Send ASR // New State: DISCON setState(DISCONNECTED); break; case SEND_STR_ANSWER: setState(IDLE); break; case TIMEOUT_EXPIRES: // Current State: OPEN // Event: Authorization-Lifetime (and Auth-Grace-Period) expires on home server. // Action: Cleanup // New State: IDLE // Current State: OPEN // Event: Session-Timeout expires on home server // Action: Cleanup // New State: IDLE if (context != null) { context.accessTimeoutElapses(this); } setState(IDLE); break; default: logger.debug("Unknown event {}", event.getType()); break; } break; } case DISCONNECTED: { switch ((Event.Type) event.getType()) { case SEND_ASR_FAILURE: // Current State: DISCON // Event: Failure to send ASR // Action: Wait, Re-send ASR // New State: DISCON setState(DISCONNECTED); break; case RECEIVE_ASR_ANSWER: // Current State: DISCON // Event: ASR successfully sent and ASA Received with Result-Code // Action: Cleanup // New State: DISCON listener.doAbortSessionAnswerEvent(this, (AbortSessionAnswer) event.getData()); //setState(IDLE); break; case RECEIVE_STR_REQUEST: try { listener.doSessionTerminationRequestEvent(this, (SessionTermRequest) event.getData()); } catch (Exception e) { logger.debug("Can not handle event", e); } break; case SEND_STR_ANSWER: setState(IDLE); break; default: logger.debug("Unknown event {}", event.getType()); break; } break; } default: { logger.debug("Unknown state {}", state); break; } } // post processing if (oldState != state) { if (OPEN.equals(state) && context != null) { if(context != null) { cancelTsTimer(); startTsTimer(); } } } } catch (Throwable t) { throw new InternalException(t); } return true; } 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.getCommandCode() == AbortSessionRequestImpl.code) { handleEvent(new Event(Event.Type.SEND_ASR_FAILURE, new AbortSessionRequestImpl(request))); } else { logger.debug("Timeout for unknown request {}", request); } } catch (Exception e) { logger.debug("Can not handle event", e); } } 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.common.impl.app.AppSessionImpl#isReplicable() */ @Override public boolean isReplicable() { return true; } protected void startTsTimer() { try { sendAndStateLock.lock(); if (sessionData.getTsTimeout() > 0) { sessionData.setTsTimerId(super.timerFacility.schedule(sessionData.getSessionId(), TIMER_NAME_TS, sessionData.getTsTimeout())); } } finally { sendAndStateLock.unlock(); } } protected void cancelTsTimer() { try { sendAndStateLock.lock(); Serializable tsTimerId = sessionData.getTsTimerId(); if(tsTimerId != null) { super.timerFacility.cancel(tsTimerId); sessionData.setTsTimerId(null); } } finally { sendAndStateLock.unlock(); } } /* * (non-Javadoc) * @see org.jdiameter.common.impl.app.AppSessionImpl#onTimer(java.lang.String) */ @Override public void onTimer(String timerName) { if(timerName.equals(TIMER_NAME_TS)) { try { sendAndStateLock.lock(); sessionData.setTsTimerId(null); handleEvent(new Event(TIMEOUT_EXPIRES, null)); } catch (Exception e) { logger.debug("Can not handle event", e); } finally { sendAndStateLock.unlock(); } } } protected ReAuthAnswer createReAuthAnswer(Answer answer) { return new ReAuthAnswerImpl(answer); } protected ReAuthRequest createReAuthRequest(Request request) { return new ReAuthRequestImpl(request); } @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; GqServerSessionImpl other = (GqServerSessionImpl) 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 { GqServerSession session; Request request; public void run() { if (request != null) { try { sendAndStateLock.lock(); if (request.getCommandCode() == factory.getAuthMessageCommandCode()) { handleEvent(new Event(RECEIVE_AUTH_REQUEST, factory.createAuthRequest(request))); } else if (request.getCommandCode() == SessionTermRequestImpl.code) { handleEvent(new Event(RECEIVE_STR_REQUEST, new SessionTermRequestImpl(request))); } else { listener.doOtherEvent(session, factory.createAuthRequest(request), null); } } catch (Exception e) { logger.debug("Can not handle event", e); } finally { sendAndStateLock.unlock(); } } } } private class AnswerDelivery implements Runnable { GqServerSession session; Answer answer; Request request; public void run() { try { sendAndStateLock.lock(); if (request.getCommandCode() == ReAuthRequestImpl.code) { listener.doReAuthAnswerEvent(session,createReAuthRequest(request), createReAuthAnswer(answer)); } else if (request.getCommandCode() == AbortSessionRequestImpl.code) { handleEvent(new Event(RECEIVE_ASR_ANSWER, new AbortSessionAnswerImpl(answer))); } else { listener.doOtherEvent(session, factory.createAuthRequest(request), new AppAnswerEventImpl(answer)); } } catch (Exception e) { logger.debug("Can not handle event", e); } finally { sendAndStateLock.unlock(); } } } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl.app.ro; import java.io.Serializable; import org.jdiameter.common.api.app.AppSessionDataLocalImpl; import org.jdiameter.common.api.app.ro.ServerRoSessionState; /** * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public class ServerRoSessionDataLocalImpl extends AppSessionDataLocalImpl implements IServerRoSessionData { protected boolean stateless = true; protected ServerRoSessionState state = ServerRoSessionState.IDLE; protected Serializable tccTimerId; /** * */ public ServerRoSessionDataLocalImpl() { } public boolean isStateless() { return stateless; } public void setStateless(boolean stateless) { this.stateless = stateless; } public ServerRoSessionState getServerRoSessionState() { return state; } public void setServerRoSessionState(ServerRoSessionState state) { this.state = state; } public Serializable getTccTimerId() { return tccTimerId; } public void setTccTimerId(Serializable tccTimerId) { this.tccTimerId = tccTimerId; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl.app.ro; import java.io.Serializable; import org.jdiameter.common.api.app.ro.IRoSessionData; import org.jdiameter.common.api.app.ro.ServerRoSessionState; /** * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public interface IServerRoSessionData extends IRoSessionData{ public boolean isStateless(); public void setStateless(boolean stateless); public ServerRoSessionState getServerRoSessionState(); public void setServerRoSessionState(ServerRoSessionState state); public void setTccTimerId(Serializable tccTimerId); public Serializable getTccTimerId(); }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl.app.ro; 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.ro.events.RoCreditControlAnswer; import org.jdiameter.api.ro.events.RoCreditControlRequest; /** * * @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 Event implements StateEvent { public enum Type { RECEIVED_EVENT, SENT_EVENT_RESPONSE, RECEIVED_INITIAL, SENT_INITIAL_RESPONSE, RECEIVED_UPDATE, SENT_UPDATE_RESPONSE, RECEIVED_TERMINATE, SENT_TERMINATE_RESPONSE, // These have no transition, no state resources, timers SENT_RAR, RECEIVED_RAA; } 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, RoCreditControlRequest request, RoCreditControlAnswer answer) { this.answer = answer; this.request = request; /** * <pre> * 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 * UPDATE_REQUEST 2 * TERMINATION_REQUEST 3 * EVENT_REQUEST 4 * </pre> */ if (isRequest) { switch (request.getRequestTypeAVPValue()) { case 1: type = Type.RECEIVED_INITIAL; break; case 2: type = Type.RECEIVED_UPDATE; break; case 3: type = Type.RECEIVED_TERMINATE; break; case 4: type = Type.RECEIVED_EVENT; break; default: throw new IllegalArgumentException("Invalid value or Request-Type AVP not present in CC Request."); } } else { switch (answer.getRequestTypeAVPValue()) { case 1: type = Type.SENT_INITIAL_RESPONSE; break; case 2: type = Type.SENT_UPDATE_RESPONSE; break; case 3: type = Type.SENT_TERMINATE_RESPONSE; break; case 4: type = Type.SENT_EVENT_RESPONSE; break; default: throw new IllegalArgumentException("Invalid value or Request-Type AVP not present in CC Answer."); } } } public <E> E encodeType(Class<E> eClass) { return eClass == Event.Type.class ? (E) type : null; } public Enum getType() { return type; } public int compareTo(Object o) { return 0; } public Object getData() { return this.request != null ? this.request : this.answer; } public void setData(Object data) { // data = (AppEvent) o; // FIXME: What should we do here?! Is it request or answer? } public AppEvent getRequest() { return request; } public AppEvent getAnswer() { return answer; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl.app.ro; import java.io.Serializable; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.jdiameter.api.Answer; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpDataException; 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.ResultCode; import org.jdiameter.api.RouteException; import org.jdiameter.api.app.AppAnswerEvent; import org.jdiameter.api.app.AppEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.app.StateChangeListener; import org.jdiameter.api.app.StateEvent; import org.jdiameter.api.auth.events.ReAuthRequest; import org.jdiameter.api.ro.ServerRoSession; import org.jdiameter.api.ro.ServerRoSessionListener; import org.jdiameter.api.ro.events.RoCreditControlAnswer; import org.jdiameter.api.ro.events.RoCreditControlRequest; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.common.api.app.IAppSessionState; import org.jdiameter.common.api.app.ro.IRoMessageFactory; import org.jdiameter.common.api.app.ro.IServerRoSessionContext; import org.jdiameter.common.api.app.ro.ServerRoSessionState; import org.jdiameter.common.impl.app.AppAnswerEventImpl; import org.jdiameter.common.impl.app.AppRequestEventImpl; import org.jdiameter.common.impl.app.auth.ReAuthAnswerImpl; import org.jdiameter.common.impl.app.auth.ReAuthRequestImpl; import org.jdiameter.common.impl.app.ro.AppRoSessionImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Ro Application Server session implementation * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class ServerRoSessionImpl extends AppRoSessionImpl implements ServerRoSession, NetworkReqListener, EventListener<Request, Answer> { private static final Logger logger = LoggerFactory.getLogger(ServerRoSessionImpl.class); // Session State Handling --------------------------------------------------- protected Lock sendAndStateLock = new ReentrantLock(); // Factories and Listeners -------------------------------------------------- protected transient IRoMessageFactory factory = null; protected transient IServerRoSessionContext context = null; protected transient ServerRoSessionListener listener = null; protected static final String TCC_TIMER_NAME = "TCC_RoSERVER_TIMER"; protected long[] authAppIds = new long[]{4}; //protected String originHost, originRealm; protected IServerRoSessionData sessionData; public ServerRoSessionImpl(IServerRoSessionData sessionData, IRoMessageFactory fct, ISessionFactory sf, ServerRoSessionListener lst, IServerRoSessionContext ctx, StateChangeListener<AppSession> stLst) { super(sf,sessionData); if(sessionData == null) { throw new IllegalArgumentException("SessionData can not be null"); } 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.sessionData = sessionData; this.context = ctx; this.authAppIds = fct.getApplicationIds(); this.listener = lst; this.factory = fct; super.addStateChangeNotification(stLst); } public void sendCreditControlAnswer(RoCreditControlAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { handleEvent(new Event(false, null, answer)); } public void sendReAuthRequest(ReAuthRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { send(Event.Type.SENT_RAR, request, null); } public boolean isStateless() { return this.sessionData.isStateless(); } @SuppressWarnings("unchecked") public <E> E getState(Class<E> stateType) { return stateType == ServerRoSessionState.class ? (E) this.sessionData.getServerRoSessionState() : null; } public boolean handleEvent(StateEvent event) throws InternalException, OverloadException { ServerRoSessionState newState = null; ServerRoSessionState state = sessionData.getServerRoSessionState(); try { sendAndStateLock.lock(); // Can be null if there is no state transition, transition to IDLE state should terminate this app session Event localEvent = (Event) event; //Its kind of awkward, but with two state on server side its easier to go through event types? //but for sake of FSM readability Event.Type eventType = (Event.Type) localEvent.getType(); switch(state) { case IDLE: switch(eventType) { case RECEIVED_INITIAL: listener.doCreditControlRequest(this, (RoCreditControlRequest)localEvent.getRequest()); break; case RECEIVED_EVENT: // Current State: IDLE // Event: CC event request received and successfully processed // Action: Send CC event answer // New State: IDLE listener.doCreditControlRequest(this, (RoCreditControlRequest)localEvent.getRequest()); break; case SENT_EVENT_RESPONSE: // Current State: IDLE // Event: CC event request received and successfully processed // Action: Send CC event answer // New State: IDLE // Current State: IDLE // Event: CC event request received but not successfully processed // Action: Send CC event answer with Result-Code != SUCCESS // New State: IDLE newState = ServerRoSessionState.IDLE; dispatchEvent(localEvent.getAnswer()); setState(newState); break; case SENT_INITIAL_RESPONSE: RoCreditControlAnswer answer = (RoCreditControlAnswer) localEvent.getAnswer(); try { long resultCode = answer.getResultCodeAvp().getUnsigned32(); // Current State: IDLE // Event: CC initial request received and successfully processed // Action: Send CC initial answer, reserve units, start Tcc // New State: OPEN if(isSuccess(resultCode)) { startTcc(answer.getValidityTimeAvp()); newState = ServerRoSessionState.OPEN; } // Current State: IDLE // Event: CC initial request received but not successfully processed // Action: Send CC initial answer with Result-Code != SUCCESS // New State: IDLE else { newState = ServerRoSessionState.IDLE; } dispatchEvent(localEvent.getAnswer()); setState(newState); } catch (AvpDataException e) { throw new InternalException(e); } break; case RECEIVED_UPDATE: case RECEIVED_TERMINATE: Answer errorAnswer = ((Request) localEvent.getRequest().getMessage()).createAnswer(ResultCode.UNKNOWN_SESSION_ID); session.send(errorAnswer); logger.debug("Received an UPDATE or TERMINATE for a new session. Answering with 5002 (UNKNOWN_SESSION_ID) and terminating session."); // and let it throw exception anyway ... default: throw new InternalException("Wrong state: " + ServerRoSessionState.IDLE + " one event: " + eventType + " " + localEvent.getRequest() + " " + localEvent.getAnswer()); } case OPEN: switch(eventType) { /* This should not happen, it should be silently discarded, right? case RECEIVED_INITIAL: // only for rtr if(((RoRequest)localEvent.getRequest()).getMessage().isReTransmitted()) { listener.doCreditControlRequest(this, (RoRequest)localEvent.getRequest()); } else { //do nothing? } break; */ case RECEIVED_UPDATE: listener.doCreditControlRequest(this, (RoCreditControlRequest)localEvent.getRequest()); break; case SENT_UPDATE_RESPONSE: RoCreditControlAnswer answer = (RoCreditControlAnswer) localEvent.getAnswer(); try { if(isSuccess(answer.getResultCodeAvp().getUnsigned32())) { // Current State: OPEN // Event: CC update request received and successfully processed // Action: Send CC update answer, debit used units, reserve new units, restart Tcc // New State: OPEN startTcc(answer.getValidityTimeAvp()); } else { // Current State: OPEN // Event: CC update request received but not successfully processed // Action: Send CC update answer with Result-Code != SUCCESS, debit used units // New State: IDLE // It's a failure, we wait for Tcc to fire -- FIXME: Alexandre: Should we? } } catch (AvpDataException e) { throw new InternalException(e); } dispatchEvent(localEvent.getAnswer()); break; case RECEIVED_TERMINATE: listener.doCreditControlRequest(this, (RoCreditControlRequest)localEvent.getRequest()); break; case SENT_TERMINATE_RESPONSE: answer = (RoCreditControlAnswer) localEvent.getAnswer(); try { // Current State: OPEN // Event: CC termination request received and successfully processed // Action: Send CC termination answer, Stop Tcc, debit used units // New State: IDLE if(isSuccess(answer.getResultCodeAvp().getUnsigned32())) { stopTcc(false); } else { // Current State: OPEN // Event: CC termination request received but not successfully processed // Action: Send CC termination answer with Result-Code != SUCCESS, debit used units // New State: IDLE // It's a failure, we wait for Tcc to fire -- FIXME: Alexandre: Should we? } } catch (AvpDataException e) { throw new InternalException(e); } newState = ServerRoSessionState.IDLE; dispatchEvent(localEvent.getAnswer()); setState(newState); break; case RECEIVED_RAA: listener.doReAuthAnswer(this, new ReAuthRequestImpl(localEvent.getRequest().getMessage()), new ReAuthAnswerImpl((Answer)localEvent.getAnswer().getMessage())); break; case SENT_RAR: dispatchEvent(localEvent.getRequest()); break; } } return true; } catch (Exception e) { throw new InternalException(e); } finally { sendAndStateLock.unlock(); } } /* * (non-Javadoc) * * @see org.jdiameter.common.impl.app.AppSessionImpl#isReplicable() */ @Override public boolean isReplicable() { return true; } private class TccScheduledTask implements Runnable { ServerRoSession session = null; private TccScheduledTask(ServerRoSession session) { super(); this.session = session; } public void run() { // Current State: OPEN // Event: Session supervision timer Tcc expired // Action: Release reserved units // New State: IDLE try { sendAndStateLock.lock(); if(context != null) { context.sessionSupervisionTimerExpired(session); } } finally { try{ sessionData.setTccTimerId(null); setState(ServerRoSessionState.IDLE); } catch (Exception e) { logger.error("",e); } sendAndStateLock.unlock(); } } } public Answer processRequest(Request request) { RequestDelivery rd = new RequestDelivery(); //rd.session = (ServerRoSession) LocalDataSource.INSTANCE.getSession(request.getSessionId()); rd.session = this; rd.request = request; super.scheduler.execute(rd); return null; } 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) { context.timeoutExpired(request); //FIXME: Should we release ? } private void startTcc(Avp validityAvp) { // There is no Validity-Time //long tccTimeout; // //if(validityAvp != null) { // try { // tccTimeout = 2 * validityAvp.getUnsigned32(); // } // catch (AvpDataException e) { // logger.debug("Unable to retrieve Validity-Time AVP value, using default.", e); // tccTimeout = 2 * context.getDefaultValidityTime(); // } //} //else { // tccTimeout = 2 * context.getDefaultValidityTime(); //} // //if(tccTimerId != null) { // stopTcc(true); // //tccFuture = super.scheduler.schedule(new TccScheduledTask(this), defaultValue, TimeUnit.SECONDS); // tccTimerId = super.timerFacility.schedule(this.sessionId, TCC_TIMER_NAME, tccTimeout * 1000); // // FIXME: this accepts Future! // context.sessionSupervisionTimerReStarted(this, null); //} //else { // //tccFuture = super.scheduler.schedule(new TccScheduledTask(this), defaultValue, TimeUnit.SECONDS); // tccTimerId = super.timerFacility.schedule(this.sessionId, TCC_TIMER_NAME, tccTimeout * 1000); // //FIXME: this accepts Future! // context.sessionSupervisionTimerStarted(this, null); //} //super.sessionDataSource.updateSession(this); } /* * (non-Javadoc) * * @see org.jdiameter.common.impl.app.AppSessionImpl#onTimer(java.lang.String) */ @Override public void onTimer(String timerName) { if (timerName.equals(TCC_TIMER_NAME)) { new TccScheduledTask(this).run(); } } private void stopTcc(boolean willRestart) { Serializable tccTimerId = sessionData.getTccTimerId(); if (tccTimerId != null) { // tccFuture.cancel(false); super.timerFacility.cancel(tccTimerId); // ScheduledFuture f = tccFuture; sessionData.setTccTimerId(null); if (!willRestart) { context.sessionSupervisionTimerStopped(this, null); } } } protected boolean isProvisional(long resultCode) { return resultCode >= 1000 && resultCode < 2000; } protected boolean isSuccess(long resultCode) { return resultCode >= 2000 && resultCode < 3000; } protected void setState(ServerRoSessionState newState) { setState(newState, true); } @SuppressWarnings("unchecked") protected void setState(ServerRoSessionState newState, boolean release) { IAppSessionState oldState = sessionData.getServerRoSessionState(); sessionData.setServerRoSessionState(newState); for (StateChangeListener i : stateListeners) { i.stateChanged(this, (Enum) oldState, (Enum) newState); } if (newState == ServerRoSessionState.IDLE) { stopTcc(false); if (release) { this.release(); } } } @Override public void release() { if (isValid()) { try { this.sendAndStateLock.lock(); this.stopTcc(false); 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 send(Event.Type type, AppRequestEvent request, AppAnswerEvent 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(); } } protected void dispatchEvent(AppEvent event) throws InternalException { try { session.send(event.getMessage(), this); } catch(Exception e) { //throw new InternalException(e); logger.debug("Failure trying to dispatch event", e); } } private class RequestDelivery implements Runnable { ServerRoSession session; Request request; public void run() { try { switch (request.getCommandCode()) { case RoCreditControlAnswer.code: handleEvent(new Event(true, factory.createCreditControlRequest(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 { ServerRoSession session; Answer answer; Request request; public void run() { try { // FIXME: baranowb: add message validation here!!! // We handle CCR, STR, ACR, ASR other go into extension switch (request.getCommandCode()) { case ReAuthRequest.code: handleEvent(new Event(Event.Type.RECEIVED_RAA, factory.createReAuthRequest(request), factory.createReAuthAnswer(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 2006, 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.server.impl.app.rf; import java.io.Serializable; import org.jdiameter.common.api.app.AppSessionDataLocalImpl; import org.jdiameter.common.api.app.rf.ServerRfSessionState; /** * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public class ServerRfSessionDataLocalImpl extends AppSessionDataLocalImpl implements IServerRfSessionData { protected boolean stateless = true; protected ServerRfSessionState state = ServerRfSessionState.IDLE; protected Serializable tsTimerId; protected long tsTimeout = NON_INITIALIZED; /** * */ public ServerRfSessionDataLocalImpl() { } public boolean isStateless() { return stateless; } public void setStateless(boolean stateless) { this.stateless = stateless; } public ServerRfSessionState getServerRfSessionState() { return state; } public void setServerRfSessionState(ServerRfSessionState state) { this.state = state; } public Serializable getTsTimerId() { return tsTimerId; } public void setTsTimerId(Serializable tsTimerId) { this.tsTimerId = tsTimerId; } /* (non-Javadoc) * @see org.jdiameter.server.impl.app.rf.IServerRfSessionData#getTsTimeout() */ @Override public long getTsTimeout() { return this.tsTimeout; } /* (non-Javadoc) * @see org.jdiameter.server.impl.app.rf.IServerRfSessionData#setTsTimeout(long) */ @Override public void setTsTimeout(long tsTimeout) { this.tsTimeout = tsTimeout; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl.app.rf; import org.jdiameter.api.app.AppEvent; import org.jdiameter.api.app.StateEvent; import org.jdiameter.api.rf.events.RfAccountingRequest; /** * * @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> */ class Event implements StateEvent { enum Type{ RECEIVED_EVENT_RECORD, RECEIVED_START_RECORD, RECEIVED_INTERIM_RECORD, RECEIVED_STOP_RECORD } Type type; AppEvent data; Event(Type type) { this.type = type; } Event(RfAccountingRequest accountRequest) throws Exception { data = accountRequest; int type = accountRequest.getAccountingRecordType(); switch (type) { case 1: this.type = Type.RECEIVED_EVENT_RECORD; break; case 2: this.type = Type.RECEIVED_START_RECORD; break; case 3: this.type = Type.RECEIVED_INTERIM_RECORD; break; case 4: this.type = Type.RECEIVED_STOP_RECORD; break; default: throw new Exception("Unknown type " + type); } } public <E> E encodeType(Class<E> eClass) { return eClass == Type.class ? (E) type : null; } public Enum getType() { return type; } public void setData(Object o) { data = (AppEvent) o; } public Object getData() { return data; } public int compareTo(Object other) { return equals(other) ? 0 : -1; } public boolean equals(Object other) { return this == other; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl.app.rf; import java.io.Serializable; import org.jdiameter.common.api.app.rf.IRfSessionData; import org.jdiameter.common.api.app.rf.ServerRfSessionState; /** * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public interface IServerRfSessionData extends IRfSessionData{ public ServerRfSessionState getServerRfSessionState(); public void setServerRfSessionState(ServerRfSessionState state); public void setTsTimerId(Serializable tsTimerId); public Serializable getTsTimerId(); public long getTsTimeout(); public void setTsTimeout(long tsTimeout); public boolean isStateless(); public void setStateless(boolean stateless); }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl.app.rf; import static org.jdiameter.common.api.app.rf.ServerRfSessionState.IDLE; import static org.jdiameter.common.api.app.rf.ServerRfSessionState.OPEN; import java.io.Serializable; import org.jdiameter.api.Answer; import org.jdiameter.api.Avp; 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.ResultCode; import org.jdiameter.api.RouteException; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.app.StateChangeListener; import org.jdiameter.api.app.StateEvent; import org.jdiameter.api.rf.ServerRfSession; import org.jdiameter.api.rf.ServerRfSessionListener; import org.jdiameter.api.rf.events.RfAccountingAnswer; import org.jdiameter.api.rf.events.RfAccountingRequest; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.common.api.app.IAppSessionState; import org.jdiameter.common.api.app.rf.IServerRfActionContext; import org.jdiameter.common.api.app.rf.ServerRfSessionState; import org.jdiameter.common.impl.app.rf.AppRfSessionImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Server Accounting session implementation * * @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 ServerRfSessionImpl extends AppRfSessionImpl implements EventListener<Request, Answer>, ServerRfSession, NetworkReqListener { //FIXME: verify this FSM private static final long serialVersionUID = 1L; private static final Logger logger = LoggerFactory.getLogger(ServerRfSessionImpl.class); // Session State Handling --------------------------------------------------- // Factories and Listeners -------------------------------------------------- protected transient IServerRfActionContext context; protected transient ServerRfSessionListener listener; // Ts Timer ----------------------------------------------------------------- protected static final String TIMER_NAME_TS = "TS"; protected IServerRfSessionData sessionData; // Constructors ------------------------------------------------------------- public ServerRfSessionImpl(IServerRfSessionData sessionData, ISessionFactory sessionFactory, ServerRfSessionListener serverSessionListener, IServerRfActionContext serverContextListener,StateChangeListener<AppSession> stLst, long tsTimeout, boolean stateless) { // TODO Auto-generated constructor stub super(sessionFactory,sessionData); this.listener = serverSessionListener; this.context = serverContextListener; this.sessionData = sessionData; this.sessionData.setTsTimeout(tsTimeout); this.sessionData.setStateless(stateless); super.addStateChangeNotification(stLst); } public void sendAccountAnswer(RfAccountingAnswer accountAnswer) throws InternalException, IllegalStateException, RouteException, OverloadException { try { session.send(accountAnswer.getMessage()); /* TODO: Need to notify state change... if(isStateless() && isValid()) { session.release(); } */ } catch (IllegalDiameterStateException e) { throw new IllegalStateException(e); } } public boolean isStateless() { return this.sessionData.isStateless(); } @SuppressWarnings("unchecked") protected void setState(IAppSessionState newState) { IAppSessionState oldState = this.sessionData.getServerRfSessionState(); this.sessionData.setServerRfSessionState((ServerRfSessionState) newState); for (StateChangeListener i : stateListeners) { i.stateChanged(this,(Enum) oldState, (Enum) newState); } } public boolean handleEvent(StateEvent event) throws InternalException, OverloadException { return isStateless() ? handleEventForStatelessMode(event) : handleEventForStatefulMode(event); } public boolean handleEventForStatelessMode(StateEvent event) throws InternalException, OverloadException { try { //this will handle RTRs as well, no need to alter. final ServerRfSessionState state = this.sessionData.getServerRfSessionState(); switch (state) { case IDLE: { switch ((Event.Type) event.getType()) { case RECEIVED_START_RECORD: // Current State: IDLE // Event: Accounting start request received, and successfully processed. // Action: Send accounting start answer // New State: IDLE if (listener != null) { try { listener.doRfAccountingRequestEvent(this, (RfAccountingRequest) event.getData()); } catch (Exception e) { logger.debug("Can not handle event", e); } } // TODO: This is unnecessary state change: setState(IDLE); break; case RECEIVED_EVENT_RECORD: // Current State: IDLE // Event: Accounting event request received, and successfully processed. // Action: Send accounting event answer // New State: IDLE if (listener != null) { try { listener.doRfAccountingRequestEvent(this, (RfAccountingRequest) event.getData()); } catch (Exception e) { logger.debug("Can not handle event", e); } } // FIXME: it is required, so we know it ends up again in IDLE! setState(IDLE); break; case RECEIVED_INTERIM_RECORD: // Current State: IDLE // Event: Interim record received, and successfully processed. // Action: Send accounting interim answer // New State: IDLE if (listener != null) { try { listener.doRfAccountingRequestEvent(this, (RfAccountingRequest) event.getData()); } catch (Exception e) { logger.debug("Can not handle event", e); } } // TODO: This is unnecessary state change: setState(IDLE); break; case RECEIVED_STOP_RECORD: // Current State: IDLE // Event: Accounting stop request received, and successfully processed // Action: Send accounting stop answer // New State: IDLE if (listener != null) { try { listener.doRfAccountingRequestEvent(this, (RfAccountingRequest) event.getData()); } catch (Exception e) { logger.debug("Can not handle event", e); } } // TODO: This is unnecessary state change: setState(IDLE); break; default: throw new IllegalStateException("Current state " + state + " action " + event.getType()); } } } } catch (Exception e) { logger.debug("Can not process event", e); return false; } finally { // TODO: Since setState was removed, we are now using this to terminate. Correct? // We can't release here, answer needs to be sent through. done at send. // release(); } return true; } public boolean handleEventForStatefulMode(StateEvent event) throws InternalException, OverloadException { try { if (((RfAccountingRequest) event.getData()).getMessage().isReTransmitted()) { try { setState(OPEN); listener.doRfAccountingRequestEvent(this, (RfAccountingRequest) event.getData()); // FIXME: should we do this before passing to lst? cancelTsTimer(); startTsTimer(); if (context != null) { context.sessionTimerStarted(this, null); } } catch (Exception e) { logger.debug("Can not handle event", e); setState(IDLE); } return true; } else { final ServerRfSessionState state = this.sessionData.getServerRfSessionState(); switch (state) { case IDLE: { switch ((Event.Type) event.getType()) { case RECEIVED_START_RECORD: // Current State: IDLE // Event: Accounting start request received, and successfully processed. // Action: Send accounting start answer, Start Ts // New State: OPEN setState(OPEN); if (listener != null) { try { listener.doRfAccountingRequestEvent(this, (RfAccountingRequest) event.getData()); cancelTsTimer(); startTsTimer(); if (context != null) { context.sessionTimerStarted(this, null); } } catch (Exception e) { logger.debug("Can not handle event", e); setState(IDLE); } } break; case RECEIVED_EVENT_RECORD: // Current State: IDLE // Event: Accounting event request received, and // successfully processed. // Action: Send accounting event answer // New State: IDLE if (listener != null) { try { listener.doRfAccountingRequestEvent(this, (RfAccountingRequest) event.getData()); } catch (Exception e) { logger.debug("Can not handle event", e); } } break; } break; } case OPEN: { switch ((Event.Type) event.getType()) { case RECEIVED_INTERIM_RECORD: // Current State: OPEN // Event: Interim record received, and successfully // processed. // Action: Send accounting interim answer, Restart Ts // New State: OPEN try { listener.doRfAccountingRequestEvent(this, (RfAccountingRequest) event.getData()); cancelTsTimer(); startTsTimer(); if (context != null) { context.sessionTimerStarted(this, null); } } catch (Exception e) { logger.debug("Can not handle event", e); setState(IDLE); } break; case RECEIVED_STOP_RECORD: // Current State: OPEN // Event: Accounting stop request received, and // successfully // processed // Action: Send accounting stop answer, Stop Ts // New State: IDLE setState(IDLE); try { listener.doRfAccountingRequestEvent(this, (RfAccountingRequest) event.getData()); cancelTsTimer(); if (context != null) { context.sessionTimerCanceled(this, null); } } catch (Exception e) { logger.debug("Can not handle event", e); setState(IDLE); } break; } break; } } } } catch (Exception e) { logger.debug("Can not process event", e); return false; } return true; } private void startTsTimer() { // return scheduler.schedule(new Runnable() { // public void run() { // logger.debug("Ts timer expired"); // if (context != null) { // try { // context.sessionTimeoutElapses(ServerRfSessionImpl.this); // } // catch (InternalException e) { // logger.debug("Failure on processing expired Ts", e); // } // } // setState(IDLE); // } // }, tsTimeout, TimeUnit.MILLISECONDS); try { sendAndStateLock.lock(); if(sessionData.getTsTimeout() > 0) { this.sessionData.setTsTimerId(super.timerFacility.schedule(getSessionId(), TIMER_NAME_TS, this.sessionData.getTsTimeout())); } } finally { sendAndStateLock.unlock(); } } private void cancelTsTimer() { try{ sendAndStateLock.lock(); final Serializable tsTimerId = this.sessionData.getTsTimerId(); if(tsTimerId != null) { super.timerFacility.cancel(tsTimerId); this.sessionData.setTsTimerId(null); } } finally { sendAndStateLock.unlock(); } } /* (non-Javadoc) * @see org.jdiameter.common.impl.app.AppSessionImpl#onTimer(java.lang.String) */ @Override public void onTimer(String timerName) { if(timerName.equals(TIMER_NAME_TS)) { if (context != null) { try { context.sessionTimeoutElapses(ServerRfSessionImpl.this); } catch (InternalException e) { logger.debug("Failure on processing expired Ts", e); } } setState(IDLE); } } protected Answer createStopAnswer(Request request) { Answer answer = request.createAnswer(ResultCode.SUCCESS); answer.getAvps().addAvp(Avp.ACC_RECORD_TYPE, 4); answer.getAvps().addAvp(request.getAvps().getAvp(Avp.ACC_RECORD_NUMBER)); return answer; } protected Answer createInterimAnswer(Request request) { Answer answer = request.createAnswer(ResultCode.SUCCESS); answer.getAvps().addAvp(Avp.ACC_RECORD_TYPE, 3); answer.getAvps().addAvp(request.getAvps().getAvp(Avp.ACC_RECORD_NUMBER)); return answer; } protected Answer createEventAnswer(Request request) { Answer answer = request.createAnswer(ResultCode.SUCCESS); answer.getAvps().addAvp(Avp.ACC_RECORD_TYPE, 2); answer.getAvps().addAvp(request.getAvps().getAvp(Avp.ACC_RECORD_NUMBER)); return answer; } protected Answer createStartAnswer(Request request) { Answer answer = request.createAnswer(ResultCode.SUCCESS); answer.getAvps().addAvp(Avp.ACC_RECORD_TYPE, 1); answer.getAvps().addAvp(request.getAvps().getAvp(Avp.ACC_RECORD_NUMBER)); return answer; } @SuppressWarnings("unchecked") public <E> E getState(Class<E> eClass) { return eClass == ServerRfSessionState.class ? (E) this.sessionData.getServerRfSessionState() : null; } public Answer processRequest(Request request) { if (request.getCommandCode() == RfAccountingRequest.code) { try { sendAndStateLock.lock(); handleEvent(new Event(createAccountRequest(request))); } catch (Exception e) { logger.debug("Can not handle event", e); } finally { sendAndStateLock.unlock(); } } else { try { listener.doOtherEvent(this, createAccountRequest(request), null); } catch (Exception e) { logger.debug("Can not handle event", e); } } return null; } public void receivedSuccessMessage(Request request, Answer answer) { if(request.getCommandCode() == RfAccountingRequest.code) { try { sendAndStateLock.lock(); handleEvent(new Event(createAccountRequest(request))); } catch (Exception e) { logger.debug("Can not handle event", e); } finally { sendAndStateLock.unlock(); } try { listener.doRfAccountingRequestEvent(this, createAccountRequest(request)); } catch (Exception e) { logger.debug("Can not handle event", e); } } else { try { listener.doOtherEvent(this, createAccountRequest(request), createAccountAnswer(answer)); } catch (Exception e) { logger.debug("Can not handle event", e); } } } public void timeoutExpired(Request request) { // FIXME: alexandre: We don't do anything here... are we even getting this on server? } /* (non-Javadoc) * @see org.jdiameter.common.impl.app.AppSessionImpl#isReplicable() */ @Override public boolean isReplicable() { return true; } @Override public void release() { if (isValid()) { try { sendAndStateLock.lock(); //TODO: cancel timer? 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()); } } }
Java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, TeleStax Inc. and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * * This file incorporates work covered by the following copyright and * permission notice: * * JBoss, Home of Professional Open Source * Copyright 2007-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.server.impl.helpers; /** * * @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 Parameters extends org.jdiameter.client.impl.helpers.Parameters { private static final long serialVersionUID = 1L; /** * Array of local host ip addresses property */ public static final Parameters OwnIPAddresses = new Parameters("OwnIPAddresses", Object.class); /** * On/Off duplication protection property */ public static final Parameters DuplicateProtection = new Parameters("DuplicateProtection", Boolean.class, false); /** * Duplication clear task time period property */ public static final Parameters DuplicateTimer = new Parameters("DuplicateTimer", Long.class, 4 * 60 * 1000L); /** * Maximum number of Answers to keep for duplicate detection */ public static final Parameters DuplicateSize = new Parameters("DuplicateSize", Integer.class, 5000); /** * On/Off */ public static final Parameters AcceptUndefinedPeer = new Parameters("PeerAcceptUndefinedPeer", Boolean.class, false); /** * Realm name property */ public static final Parameters RealmName = new Parameters("RealmName", String.class, ""); /** * Realm hosts property */ public static final Parameters RealmHosts = new Parameters("RealmHosts", String.class, "localhost"); /** * Realm action property */ public static final Parameters RealmLocalAction = new Parameters("RealmLocalAction", String.class, "LOCAL"); /** * Realm EntryIsDynamic */ public static final Parameters RealmEntryIsDynamic = new Parameters("RealmEntryIsDynamic", Boolean.class, false); /** * Realm EntryExpTime */ public static final Parameters RealmEntryExpTime = new Parameters("RealmEntryExpTime", Long.class, 0); /** * Overload monitor property */ public static final Parameters OverloadMonitor = new Parameters("OverloadMonitor", Object.class, ""); /** * Overload monitor entry property */ public static final Parameters OverloadMonitorEntry = new Parameters("OverloadMonitorEntry", Object.class, ""); /** * Overload monitor data property */ public static final Parameters OverloadMonitorData = new Parameters("OverloadMonitorData", Object.class, ""); /** * Overload entry Index property */ public static final Parameters OverloadEntryIndex = new Parameters("OverloadEntryIndex", Integer.class, ""); /** * Overload high threshold property */ public static final Parameters OverloadEntryhighThreshold = new Parameters("OverloadEntryhighThreshold", Double.class, ""); /** * Overload low threshold property */ public static final Parameters OverloadEntrylowThreshold = new Parameters("OverloadEntrylowThreshold", Double.class, ""); /** * Peer reconnection property property */ public static final Parameters PeerAttemptConnection = new Parameters("PeerAttemptConnection", Boolean.class, false); /** * Peer reconnection property property */ public static final Parameters NeedClientAuth = new Parameters("NeedClientAuth", Boolean.class); /** * Socket bind delay property */ public static final Parameters BindDelay = new Parameters("BindDelay", Long.class, 0L); /** * RequestTable - specifies parameters of request table. */ public static final Parameters RequestTable = new Parameters("RequestTable", Object.class, ""); public static final Parameters RequestTableSize = new Parameters("RequestTableSize", Integer.class, new Integer(10240)); public static final Parameters RequestTableClearSize = new Parameters("RequestTableClearSize", Integer.class, new Integer(2048)); protected Parameters(String name, Class type) { super(name, type); } protected Parameters(String name, Class type, Object defValue) { super(name, type, defValue); } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl.helpers; import org.jdiameter.api.ApplicationId; import org.jdiameter.api.Message; import org.jdiameter.api.Selector; import org.jdiameter.client.api.IMessage; /** * * @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 ApplicationIdSelector implements Selector<Message, ApplicationId> { private ApplicationId applicationId; public ApplicationIdSelector(ApplicationId applicationId) { if (applicationId == null){ throw new IllegalArgumentException("Please set application id"); } this.applicationId = applicationId; } public boolean checkRule(Message message) { return message != null && ((IMessage) message).getSingleApplicationId().equals(applicationId); } public ApplicationId getMetaData() { return applicationId; } }
Java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, TeleStax Inc. and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * * This file incorporates work covered by the following copyright and * permission notice: * * JBoss, Home of Professional Open Source * Copyright 2007-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.server.impl.helpers; import org.jdiameter.api.Configuration; import org.jdiameter.client.impl.helpers.AppConfiguration; import org.jdiameter.client.impl.helpers.Ordinal; import static org.jdiameter.server.impl.helpers.ExtensionPoint.*; import static org.jdiameter.client.impl.helpers.Parameters.Agent; import static org.jdiameter.client.impl.helpers.Parameters.CipherSuites; import static org.jdiameter.client.impl.helpers.Parameters.DictionaryClass; import static org.jdiameter.client.impl.helpers.Parameters.DictionaryEnabled; import static org.jdiameter.client.impl.helpers.Parameters.DictionaryReceiveLevel; import static org.jdiameter.client.impl.helpers.Parameters.DictionarySendLevel; import static org.jdiameter.client.impl.helpers.Parameters.KDFile; import static org.jdiameter.client.impl.helpers.Parameters.KDManager; import static org.jdiameter.client.impl.helpers.Parameters.KDPwd; import static org.jdiameter.client.impl.helpers.Parameters.KDStore; import static org.jdiameter.client.impl.helpers.Parameters.KeyData; import static org.jdiameter.client.impl.helpers.Parameters.PeerFSMThreadCount; import static org.jdiameter.client.impl.helpers.Parameters.Properties; import static org.jdiameter.client.impl.helpers.Parameters.PropertyName; import static org.jdiameter.client.impl.helpers.Parameters.PropertyValue; import static org.jdiameter.client.impl.helpers.Parameters.RealmEntry; import static org.jdiameter.client.impl.helpers.Parameters.SDEnableSessionCreation; import static org.jdiameter.client.impl.helpers.Parameters.SDName; import static org.jdiameter.client.impl.helpers.Parameters.SDProtocol; import static org.jdiameter.client.impl.helpers.Parameters.SDUseClientMode; import static org.jdiameter.client.impl.helpers.Parameters.Security; import static org.jdiameter.client.impl.helpers.Parameters.SecurityRef; import static org.jdiameter.client.impl.helpers.Parameters.StatisticsActiveList; import static org.jdiameter.client.impl.helpers.Parameters.StatisticsEnabled; import static org.jdiameter.client.impl.helpers.Parameters.StatisticsLoggerDelay; import static org.jdiameter.client.impl.helpers.Parameters.StatisticsLoggerPause; import static org.jdiameter.client.impl.helpers.Parameters.TDFile; import static org.jdiameter.client.impl.helpers.Parameters.TDManager; import static org.jdiameter.client.impl.helpers.Parameters.TDPwd; import static org.jdiameter.client.impl.helpers.Parameters.TDStore; import static org.jdiameter.client.impl.helpers.Parameters.TrustData; import static org.jdiameter.server.impl.helpers.Parameters.*; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Source; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; /** * This class provide loading and verification configuration for server from XML file * * @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 XMLConfiguration extends EmptyConfiguration { /** * Create instance of class and load file from defined input stream * * @param in input stream * @throws Exception */ public XMLConfiguration(InputStream in) throws Exception { this(in, null, null, false); } /** * Create instance of class and load file from defined input stream * * @param in input stream * @param attributes attributes for DocumentBuilderFactory * @param features features for DocumentBuilderFactory * @throws Exception */ public XMLConfiguration(InputStream in, Hashtable<String, Object> attributes, Hashtable<String, Boolean> features) throws Exception { this(in, attributes, features, false); } /** * Create instance of class and load file from defined file name * * @param filename configuration file name * @throws Exception */ public XMLConfiguration(String filename) throws Exception { this(filename, null, null, false); } /** * Create instance of class and load file from defined input stream * * @param filename configuration file name * @param attributes attributes for DocumentBuilderFactory * @param features features for DocumentBuilderFactory * @throws Exception */ public XMLConfiguration(String filename, Hashtable<String, Object> attributes, Hashtable<String, Boolean> features) throws Exception { this(filename, attributes, features, false); } protected XMLConfiguration(Object in, Hashtable<String, Object> attributes, Hashtable<String, Boolean> features, boolean nop) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); if (attributes != null) { for (String key : attributes.keySet()) { factory.setAttribute(key, attributes.get(key)); } } if (features != null) { for (String key : features.keySet()) { factory.setFeature(key, features.get(key)); } } DocumentBuilder builder = factory.newDocumentBuilder(); Document document; if (in instanceof InputStream) { document = builder.parse((InputStream) in); } else if (in instanceof String) { document = builder.parse(new File((String) in)); } else { throw new Exception("Unknown type of input data"); } validate(document); processing(document); } protected void validate(Document document) throws Exception { SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Source schemaFile = new StreamSource(getClass().getResourceAsStream("/META-INF/jdiameter-server.xsd")); Schema schema = factory.newSchema(schemaFile); Validator validator = schema.newValidator(); validator.validate(new DOMSource(document)); } protected void processing(Document document) { Element element = document.getDocumentElement(); NodeList c = element.getChildNodes(); for (int i = 0; i < c.getLength(); i++) { String nodeName = c.item(i).getNodeName(); if (nodeName.equals("LocalPeer")) { addLocalPeer(c.item(i)); } else if (nodeName.equals("Parameters")) { addParameters(c.item(i)); } else if (nodeName.equals("Security")) { addSecurity(c.item(i)); } else if (nodeName.equals("Network")) { addNetwork(c.item(i)); } else if (nodeName.equals("Extensions")) { addExtensions(c.item(i)); } } } protected void addApplications(Node node) { NodeList c = node.getChildNodes(); ArrayList<Configuration> items = new ArrayList<Configuration>(); for (int i = 0; i < c.getLength(); i++) { String nodeName = c.item(i).getNodeName(); if (nodeName.equals("ApplicationID")) { Configuration m = addApplicationID(c.item(i)); if (m != null) { items.add(m); } } } add(ApplicationId, items.toArray(EMPTY_ARRAY)); } protected Configuration addApplicationID(NodeList node) { for (int i = 0; i < node.getLength(); i++) { String nodeName = node.item(i).getNodeName(); if (nodeName.equals("ApplicationID")) { return addApplicationID(node.item(i)); } } return null; } protected Configuration addApplicationID(Node node) { NodeList c = node.getChildNodes(); AppConfiguration e = getInstance(); for (int i = 0; i < c.getLength(); i++) { String nodeName = c.item(i).getNodeName(); if (nodeName.equals("VendorId")) e.add(VendorId, getLongValue(c.item(i))); else if (nodeName.equals("AuthApplId")) e.add(AuthApplId, getLongValue(c.item(i))); else if (nodeName.equals("AcctApplId")) e.add(AcctApplId, getLongValue(c.item(i))); } return e; } protected void addParameters(Node node) { NodeList c = node.getChildNodes(); for (int i = 0; i < c.getLength(); i++) { String nodeName = c.item(i).getNodeName(); if (nodeName.equals("UseUriAsFqdn")) { add(UseUriAsFqdn, Boolean.valueOf(getValue(c.item(i)))); } else if (nodeName.equals("QueueSize")) { add(QueueSize, getIntValue(c.item(i))); } else if (nodeName.equals("MessageTimeOut")) { add(MessageTimeOut, getLongValue(c.item(i))); } else if (nodeName.equals("StopTimeOut")) { add(StopTimeOut, getLongValue(c.item(i))); } else if (nodeName.equals("CeaTimeOut")) { add(CeaTimeOut, getLongValue(c.item(i))); } else if (nodeName.equals("IacTimeOut")) { add(IacTimeOut, getLongValue(c.item(i))); } else if (nodeName.equals("DwaTimeOut")) { add(DwaTimeOut, getLongValue(c.item(i))); } else if (nodeName.equals("DpaTimeOut")) { add(DpaTimeOut, getLongValue(c.item(i))); } else if (nodeName.equals("RecTimeOut")) { add(RecTimeOut, getLongValue(c.item(i))); } else if (nodeName.equals("BindDelay")) { add(BindDelay, getLongValue(c.item(i))); } else if (nodeName.equals("ThreadPool")) { addThreadPool(c.item(i)); } else if (nodeName.equals("PeerFSMThreadCount")) { add(PeerFSMThreadCount, getIntValue(c.item(i)));} else if (nodeName.equals("Statistics")) { addStatisticLogger(Statistics, c.item(i)); } else if (nodeName.equals("Concurrent")) { addConcurrent(Concurrent, c.item(i)); } else if (nodeName.equals("Dictionary")) { addDictionary(Dictionary, c.item(i)); } else if (nodeName.equals("RequestTable")) { addRequestTable(RequestTable, c.item(i)); } else { appendOtherParameter(c.item(i)); } } } protected void addThreadPool(Node item) { AppConfiguration threadPoolConfiguration = EmptyConfiguration.getInstance(); NamedNodeMap attributes = item.getAttributes(); for (int index = 0; index < attributes.getLength(); index++) { Node n = attributes.item(index); int v = Integer.parseInt(n.getNodeValue()); if (n.getNodeName().equals("size")) { threadPoolConfiguration.add(ThreadPoolSize, v); } else if (n.getNodeName().equals("priority")) { threadPoolConfiguration.add(ThreadPoolPriority, v); } else { //log.error("Unkonwn attribute on " + item.getNodeName() + ", attribute name: " + n.getNodeName()); } } if (!threadPoolConfiguration.isAttributeExist(ThreadPoolSize.ordinal())) { threadPoolConfiguration.add(ThreadPoolSize, ThreadPoolSize.defValue()); } if (!threadPoolConfiguration.isAttributeExist(ThreadPoolPriority.ordinal())) { threadPoolConfiguration.add(ThreadPoolPriority, ThreadPoolPriority.defValue()); } this.add(ThreadPool, threadPoolConfiguration); } protected void addConcurrent(org.jdiameter.client.impl.helpers.Parameters name, Node node) { NodeList c = node.getChildNodes(); List<Configuration> items = new ArrayList<Configuration>(); for (int i = 0; i < c.getLength(); i++) { String nodeName = c.item(i).getNodeName(); if (nodeName.equals("Entity")) addConcurrentEntity(items, c.item(i)); } add(name, items.toArray(new Configuration[items.size()])); } protected void addConcurrentEntity(List<Configuration> items, Node node) { AppConfiguration cfg = getInstance(); String name = node.getAttributes().getNamedItem("name").getNodeValue(); cfg.add(ConcurrentEntityName, name); if (node.getAttributes().getNamedItem("description") != null) { String descr = node.getAttributes().getNamedItem("description").getNodeValue(); cfg.add(ConcurrentEntityDescription, descr); } if (node.getAttributes().getNamedItem("size") != null) { String size = node.getAttributes().getNamedItem("size").getNodeValue(); cfg.add(ConcurrentEntityPoolSize, Integer.parseInt(size)); } items.add(cfg); } protected void addStatisticLogger(org.jdiameter.client.impl.helpers.Parameters name, Node node) { String pause = node.getAttributes().getNamedItem("pause").getNodeValue(); String delay = node.getAttributes().getNamedItem("delay").getNodeValue(); String enabled = node.getAttributes().getNamedItem("enabled").getNodeValue(); String active_records; if (node.getAttributes().getNamedItem("active_records") != null) { active_records = node.getAttributes().getNamedItem("active_records").getNodeValue(); } else { active_records = (String) StatisticsActiveList.defValue(); } add(name, getInstance(). add(StatisticsLoggerPause, Long.parseLong(pause)). add(StatisticsLoggerDelay, Long.parseLong(delay)). add(StatisticsEnabled, Boolean.parseBoolean(enabled)). add(StatisticsActiveList, active_records)); } protected void addDictionary(org.jdiameter.client.impl.helpers.Parameters name, Node node) { AppConfiguration dicConfiguration = getInstance(); Node param = node.getAttributes().getNamedItem("class"); if(param != null) { String clazz = param.getNodeValue(); dicConfiguration.add(DictionaryClass, clazz); } param = node.getAttributes().getNamedItem("enabled"); if(param != null) { String enabled = param.getNodeValue(); dicConfiguration.add(DictionaryEnabled, Boolean.valueOf(enabled)); } param = node.getAttributes().getNamedItem("sendLevel"); if(param != null) { String sendLevel = param.getNodeValue(); dicConfiguration.add(DictionarySendLevel, sendLevel); } param = node.getAttributes().getNamedItem("receiveLevel"); if(param != null) { String receiveLevel = param.getNodeValue(); dicConfiguration.add(DictionaryReceiveLevel, receiveLevel); } add(name, dicConfiguration); } protected void addRequestTable(org.jdiameter.client.impl.helpers.Parameters name, Node node) { AppConfiguration tableConfiguration = getInstance(); Node param = node.getAttributes().getNamedItem("size"); if(param != null) { String size = param.getNodeValue(); tableConfiguration.add(Parameters.RequestTableSize, Integer.parseInt(size)); } param = node.getAttributes().getNamedItem("clear_size"); if(param != null) { String size = param.getNodeValue(); tableConfiguration.add(Parameters.RequestTableClearSize, Integer.parseInt(size)); } add(name, tableConfiguration); } protected void addSecurity(Node node) { NodeList c = node.getChildNodes(); List<Configuration> items = new ArrayList<Configuration>(); for (int i = 0; i < c.getLength(); i++) { String nodeName = c.item(i).getNodeName(); if (nodeName.equals("SecurityData")) items.add(addSecurityData(c.item(i))); } add(Security, items.toArray(EMPTY_ARRAY)); } protected Configuration addSecurityData(Node node) { AppConfiguration sd = getInstance().add(SDName, node.getAttributes().getNamedItem("name").getNodeValue()) .add(SDProtocol, node.getAttributes().getNamedItem("protocol").getNodeValue()) .add(SDEnableSessionCreation, Boolean.valueOf(node.getAttributes().getNamedItem("enable_session_creation").getNodeValue())) .add(SDUseClientMode, Boolean.valueOf(node.getAttributes().getNamedItem("use_client_mode").getNodeValue())); NodeList c = node.getChildNodes(); for (int i = 0; i < c.getLength(); i++) { Node cnode = c.item(i); String nodeName = cnode.getNodeName(); if (nodeName.equals("CipherSuites")) { sd.add(CipherSuites, cnode.getTextContent().trim()); } if (nodeName.equals("KeyData")) { sd.add(KeyData, getInstance().add(KDManager, cnode.getAttributes().getNamedItem("manager").getNodeValue()) .add(KDStore, cnode.getAttributes().getNamedItem("store").getNodeValue()) .add(KDFile, cnode.getAttributes().getNamedItem("file").getNodeValue()) .add(KDPwd, cnode.getAttributes().getNamedItem("pwd").getNodeValue())); } if (nodeName.equals("TrustData")) { sd.add(TrustData, getInstance().add(TDManager, cnode.getAttributes().getNamedItem("manager").getNodeValue()) .add(TDStore, cnode.getAttributes().getNamedItem("store").getNodeValue()) .add(TDFile, cnode.getAttributes().getNamedItem("file").getNodeValue()) .add(TDPwd, cnode.getAttributes().getNamedItem("pwd").getNodeValue())); } } return sd; } protected void addNetwork(Node node) { NodeList c = node.getChildNodes(); for (int i = 0; i < c.getLength(); i++) { String nodeName = c.item(i).getNodeName(); if (nodeName.equals("Peers")) addPeers(c.item(i)); else if (nodeName.equals("Realms")) addRealms(c.item(i)); } } protected void addPeers(Node node) { NodeList c = node.getChildNodes(); ArrayList<Configuration> items = new ArrayList<Configuration>(); for (int i = 0; i < c.getLength(); i++) { String nodeName = c.item(i).getNodeName(); if (nodeName.equals("Peer")) items.add(addPeer(c.item(i))); } add(PeerTable, items.toArray(EMPTY_ARRAY)); } protected void addRealms(Node node) { NodeList c = node.getChildNodes(); ArrayList<Configuration> items = new ArrayList<Configuration>(); for (int i = 0; i < c.getLength(); i++) { String nodeName = c.item(i).getNodeName(); if (nodeName.equals("Realm")) items.add(addRealm(c.item(i))); } add(RealmTable, items.toArray(EMPTY_ARRAY)); } protected Configuration addPeer(Node node) { String rating = node.getAttributes().getNamedItem("rating").getNodeValue(); String connecting = node.getAttributes().getNamedItem("attempt_connect").getNodeValue(); String name = node.getAttributes().getNamedItem("name").getNodeValue(); AppConfiguration c = getInstance(); c.add(PeerRating, Integer.parseInt(rating)); c.add(PeerAttemptConnection, Boolean.valueOf(connecting)); c.add(PeerName, name); if (node.getAttributes().getNamedItem("ip") != null) { c.add(PeerIp, node.getAttributes().getNamedItem("ip").getNodeValue()); } if (node.getAttributes().getNamedItem("portRange") != null) { c.add(PeerLocalPortRange, node.getAttributes().getNamedItem("portRange").getNodeValue()); } if (node.getAttributes().getNamedItem("security_ref") != null) { c.add(SecurityRef, node.getAttributes().getNamedItem("security_ref").getNodeValue()); } return c; } protected void addLocalPeer(Node node) { NodeList c = node.getChildNodes(); if (node.getAttributes().getNamedItem("security_ref") != null) { add(SecurityRef, node.getAttributes().getNamedItem("security_ref").getNodeValue()); } for (int i = 0; i < c.getLength(); i++) { String nodeName = c.item(i).getNodeName(); if (nodeName.equals("URI")) add(OwnDiameterURI, getValue(c.item(i))); addIPAddress(c.item(i)); if (nodeName.equals("Realm")) add(OwnRealm, getValue(c.item(i))); if (nodeName.equals("VendorID")) add(OwnVendorID, getLongValue(c.item(i))); if (nodeName.equals("ProductName")) add(OwnProductName, getValue(c.item(i))); if (nodeName.equals("FirmwareRevision")) add(OwnFirmwareRevision, getLongValue(c.item(i))); if (nodeName.equals("Applications")) addApplications(c.item(i)); if (nodeName.equals("OverloadMonitor")) addOverloadMonitor(c.item(i)); } } private void addOverloadMonitor(Node node) { NodeList c = node.getChildNodes(); ArrayList<Configuration> items = new ArrayList<Configuration>(); for (int i = 0; i < c.getLength(); i++) { String nodeName = c.item(i).getNodeName(); if (nodeName.equals("Entry")) items.add(addOverloadMonitorItem(c.item(i))); } add(OverloadMonitor, items.toArray(EMPTY_ARRAY)); } private Configuration addOverloadMonitorItem(Node node) { return getInstance(). add(OverloadEntryIndex, Integer.valueOf(getAttrValue(node, "index"))). add(OverloadEntrylowThreshold, Double.valueOf(getAttrValue(node, "lowThreshold"))). add(OverloadEntryhighThreshold, Double.valueOf(getAttrValue(node, "highThreshold"))). add(ApplicationId, addApplicationID(node.getChildNodes())); } protected void addIPAddress(Node node) { String nodeName = node.getNodeName(); if (nodeName.equals("IPAddresses")) addIPAddresses(node); } private void addIPAddresses(Node node) { NodeList c = node.getChildNodes(); ArrayList<Configuration> items = new ArrayList<Configuration>(); for (int i = 0; i < c.getLength(); i++) { String nodeName = c.item(i).getNodeName(); if (nodeName.equals("IPAddress")) items.add(addIPAddressItem(c.item(i))); } add(OwnIPAddresses, items.toArray(EMPTY_ARRAY)); } protected Configuration addIPAddressItem(Node node) { return getInstance(). add(OwnIPAddress, getValue(node)); } protected Configuration addRealm(Node node) { AppConfiguration realmEntry = getInstance(); realmEntry. add(ApplicationId, new Configuration[] {addApplicationID(node.getChildNodes())}). add(RealmName, getAttrValue(node, "name")). add(RealmHosts, getAttrValue(node, "peers")). add(RealmLocalAction, getAttrValue(node, "local_action")). add(RealmEntryIsDynamic, Boolean.valueOf(getAttrValue(node, "dynamic"))). add(RealmEntryExpTime, Long.valueOf(getAttrValue(node, "exp_time"))); NodeList childNodes = node.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { String nodeName = childNodes.item(i).getNodeName(); if (nodeName.equals("Agent")) { realmEntry.add(Agent, addAgent(childNodes.item(i))); } } return getInstance().add(RealmEntry, realmEntry); } protected Configuration addAgent(Node node) { AppConfiguration agentConf = getInstance(); NodeList agentChildren = node.getChildNodes(); for(int index = 0; index < agentChildren.getLength(); index++) { Node n = agentChildren.item(index); if(n.getNodeName().equals("Properties")) { agentConf.add(Properties, getProperties(n).toArray(EMPTY_ARRAY)); } } return agentConf; } protected List<Configuration> getProperties(Node node) { List<Configuration> props = new ArrayList<Configuration>(); NodeList propertiesChildren = node.getChildNodes(); for(int index = 0; index < propertiesChildren.getLength(); index++) { Node n = propertiesChildren.item(index); if(n.getNodeName().equals("Property")) { AppConfiguration property = getInstance(); property.add(PropertyName, n.getAttributes().getNamedItem(PropertyName.name()).getNodeValue()); property.add(PropertyValue, n.getAttributes().getNamedItem(PropertyValue.name()).getNodeValue()); props.add(property); } } return props; } protected void appendOtherParameter(Node node) { String nodeName = node.getNodeName(); if (nodeName.equals("DuplicateProtection")) add(DuplicateProtection, Boolean.valueOf(getValue(node))); if (nodeName.equals("DuplicateTimer")) add(DuplicateTimer, getLongValue(node)); if (nodeName.equals("DuplicateSize")) add(DuplicateSize, getIntValue(node)); if (nodeName.equals("AcceptUndefinedPeer")) add(AcceptUndefinedPeer, Boolean.valueOf(getValue(node))); } protected void addExtensions(Node node) { NodeList c = node.getChildNodes(); for (int i = 0; i < c.getLength(); i++) { String nodeName = c.item(i).getNodeName(); if (nodeName.equals("MetaData")) { addInternalExtension(InternalMetaData, getValue(c.item(i))); } else if (nodeName.equals("MessageParser")) { addInternalExtension(InternalMessageParser, getValue(c.item(i))); } else if (nodeName.equals("ElementParser")) { addInternalExtension(InternalElementParser, getValue(c.item(i))); } else if (nodeName.equals("RouterEngine")) { addInternalExtension(InternalRouterEngine, getValue(c.item(i))); } else if (nodeName.equals("PeerController")) { addInternalExtension(InternalPeerController, getValue(c.item(i))); } else if (nodeName.equals("RealmController")) { addInternalExtension(InternalRealmController, getValue(c.item(i))); } else if (nodeName.equals("SessionFactory")) { addInternalExtension(InternalSessionFactory, getValue(c.item(i))); } else if (nodeName.equals("TransportFactory")) { addInternalExtension(InternalTransportFactory, getValue(c.item(i))); } else if (nodeName.equals("Connection")) { addInternalExtension(InternalConnectionClass, getValue(c.item(i))); } else if (nodeName.equals("NetworkGuard")) { addInternalExtension(InternalNetworkGuard, getValue(c.item(i))); } else if (nodeName.equals("PeerFsmFactory")) { addInternalExtension(InternalPeerFsmFactory, getValue(c.item(i))); } else if (nodeName.equals("StatisticFactory")) { addInternalExtension(InternalStatisticFactory, getValue(c.item(i))); } else if (nodeName.equals("ConcurrentFactory")) { addInternalExtension(InternalConcurrentFactory, getValue(c.item(i))); } else if (nodeName.equals("ConcurrentEntityFactory")) { addInternalExtension(InternalConcurrentEntityFactory, getValue(c.item(i))); } else if (nodeName.equals("StatisticProcessor")) { addInternalExtension(InternalStatisticProcessor, getValue(c.item(i))); } else if (nodeName.equals("NetWork")) { addInternalExtension(InternalNetWork, getValue(c.item(i))); } else if (nodeName.equals("SessionDatasource")) { addInternalExtension(InternalSessionDatasource, getValue(c.item(i))); } else if (nodeName.equals("TimerFacility")) { addInternalExtension(InternalTimerFacility, getValue(c.item(i))); } else if (nodeName.equals("AgentRedirect")) { addInternalExtension(InternalAgentRedirect, getValue(c.item(i))); } else if (nodeName.equals("AgentConfiguration")) { add(ExtensionPoint.InternalAgentConfiguration,getValue(c.item(i))); } else if (nodeName.equals("AgentProxy")) { addInternalExtension(InternalAgentProxy, getValue(c.item(i))); } else if (nodeName.equals("OverloadManager")) { addInternalExtension(InternalOverloadManager,getValue(c.item(i))); } else appendOtherExtension(c.item(i)); } } protected void addInternalExtension(Ordinal ep, String value) { Configuration[] extensionConfs = this.getChildren(Parameters.Extensions.ordinal()); AppConfiguration internalExtensions = (AppConfiguration) extensionConfs[ExtensionPoint.Internal.id()]; internalExtensions.add(ep,value); } private void appendOtherExtension(Node item) { // Nothing to do here, so far } protected Long getLongValue(Node node) { return new Long(getValue(node)); } protected Integer getIntValue(Node node) { return new Integer(getValue(node)); } protected String getValue(Node node) { return node.getAttributes().getNamedItem("value").getNodeValue(); } protected String getAttrValue(Node node, String name) { return node.getAttributes().getNamedItem(name).getNodeValue(); } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl.helpers; /** * This class provide pluggable features * * @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 ExtensionPoint extends org.jdiameter.client.impl.helpers.ExtensionPoint { private static final long serialVersionUID = -8220684081025349561L; /** * Network implementation class name */ public static final ExtensionPoint InternalNetWork = new ExtensionPoint("InternalNetWork", "org.jdiameter.server.impl.NetworkImpl", true); //false - so its not added to extension point so Assembler does not try to create instance! /** * Class name of network guard */ public static final ExtensionPoint InternalNetworkGuard = new ExtensionPoint("InternalNetworkGuard", "org.jdiameter.server.impl.io.tcp.NetworkGuard", false); /** * Overload manager implementation class name */ public static final ExtensionPoint InternalOverloadManager = new ExtensionPoint("InternalOverloadManager", "org.jdiameter.server.impl.OverloadManagerImpl", true); protected ExtensionPoint(String name, String defaultValue, boolean appendToInternal) { super(name, defaultValue); if (appendToInternal) { Internal.appendElements(this); } } protected ExtensionPoint(String name, org.jdiameter.client.impl.helpers.ExtensionPoint... parameters) { super(name, parameters); } protected ExtensionPoint(String name, int id, org.jdiameter.client.impl.helpers.ExtensionPoint... parameters) { super(name, id, parameters); } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl.helpers; import org.jdiameter.api.ConfigurationListener; import org.jdiameter.api.MutableConfiguration; import org.jdiameter.client.impl.helpers.ExtensionPoint; import static org.jdiameter.client.impl.helpers.ExtensionPoint.InternalAgentConfiguration; import static org.jdiameter.client.impl.helpers.ExtensionPoint.InternalConnectionClass; import static org.jdiameter.client.impl.helpers.ExtensionPoint.InternalTransportFactory; import static org.jdiameter.client.impl.helpers.Parameters.ExtensionName; import static org.jdiameter.server.impl.helpers.ExtensionPoint.*; import static org.jdiameter.server.impl.helpers.Parameters.Extensions; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; /** * This class allow create configuration class for stack * * @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 EmptyConfiguration extends org.jdiameter.client.impl.helpers.EmptyConfiguration implements MutableConfiguration { private final ConcurrentHashMap<Integer, List<ConfigurationListener>> listeners = new ConcurrentHashMap<Integer, List<ConfigurationListener>>(); protected EmptyConfiguration() { this(true); } /** * Create instance of class * * @param callInit true if need append default parameters */ public EmptyConfiguration(boolean callInit) { if (callInit) { add(Extensions, getInstance(). // Internal extension point add(ExtensionName, ExtensionPoint.Internal.name()). add(InternalMetaData, "org.jdiameter.server.impl.MetaDataImpl"). add(InternalMessageParser, InternalMessageParser.defValue()). add(InternalElementParser, InternalElementParser.defValue()). add(InternalTransportFactory, "org.jdiameter.server.impl.io.TransportLayerFactory"). add(InternalConnectionClass, InternalConnectionClass.defValue()). add(InternalNetworkGuard, InternalNetworkGuard.defValue()). add(InternalPeerFsmFactory, "org.jdiameter.server.impl.fsm.FsmFactoryImpl"). add(InternalSessionFactory, InternalSessionFactory.defValue()). add(InternalRouterEngine, "org.jdiameter.server.impl.RouterImpl"). add(InternalNetWork, "org.jdiameter.server.impl.NetworkImpl"). add(InternalStatisticFactory, InternalStatisticFactory.defValue()). add(InternalOverloadManager, "org.jdiameter.server.impl.OverloadManagerImpl"). add(InternalRealmController, InternalRealmController.defValue()). add(InternalAgentRedirect, InternalAgentRedirect.defValue()). add(InternalAgentConfiguration, InternalAgentConfiguration.defValue()). add(InternalAgentProxy, InternalAgentProxy.defValue()). add(InternalSessionDatasource, InternalSessionDatasource.defValue()). add(InternalTimerFacility, InternalTimerFacility.defValue()). add(InternalPeerController, "org.jdiameter.server.impl.MutablePeerTableImpl"), getInstance(). // StackLayer extension point add(ExtensionName, ExtensionPoint.StackLayer.name()), getInstance(). // ControllerLayer extension point add(ExtensionName, ExtensionPoint.ControllerLayer.name()), getInstance(). // TransportLayer extension point add(ExtensionName, ExtensionPoint.TransportLayer.name()) ); } } // public void setByteValue(int key, byte value) { List<ConfigurationListener> list = listeners.get(key); if (list != null) { boolean commit = true; for (ConfigurationListener l : list) { commit &= l.elementChanged(key, value); } if (commit) { putValue(key, value); } } else { putValue(key, value); } } public void setIntValue(int key, int value) { List<ConfigurationListener> list = listeners.get(key); if (list != null) { boolean commit = true; for (ConfigurationListener l : list) { commit &= l.elementChanged(key, value); } if (commit) { putValue(key, value); } } else { putValue(key, value); } } public void setLongValue(int key, long value) { List<ConfigurationListener> list = listeners.get(key); if (list != null) { boolean commit = true; for (ConfigurationListener l : list) { commit &= l.elementChanged(key, value); } if (commit) { putValue(key, value); } } else { putValue(key, value); } } public void setDoubleValue(int key, double value) { List<ConfigurationListener> list = listeners.get(key); if (list != null) { boolean commit = true; for (ConfigurationListener l : list) { commit &= l.elementChanged(key, value); } if (commit) { putValue(key, value); } } else { putValue(key, value); } } public void setByteArrayValue(int key, byte[] value) { List<ConfigurationListener> list = listeners.get(key); if (list != null) { boolean commit = true; for (ConfigurationListener l : list) { commit &= l.elementChanged(key, value); } if (commit) { putValue(key, value); } } else { putValue(key, value); } } public void setBooleanValue(int key, boolean value) { List<ConfigurationListener> list = listeners.get(key); if (list != null) { boolean commit = true; for (ConfigurationListener l : list) { commit &= l.elementChanged(key, value); } if (commit) { putValue(key, value); } } else { putValue(key, value); } } public void setStringValue(int key, java.lang.String value) { List<ConfigurationListener> list = listeners.get(key); if (list != null) { boolean commit = true; for (ConfigurationListener l : list) { commit &= l.elementChanged(key, value); } if (commit) { putValue(key, value); } } else { putValue(key, value); } } public void setChildren(int key, org.jdiameter.api.Configuration... values) { List<ConfigurationListener> list = listeners.get(key); if (list != null) { boolean commit = true; for (ConfigurationListener l : list) { commit &= l.elementChanged(key, values); } if (commit) { putValue(key, values); } // Removed due to issue #1009 (http://code.google.com/p/mobicents/issues/detail?id=1009) // putValue(key, new EmptyConfiguration(false).add(key, values)); } else { putValue(key, values); // Removed due to issue #1009 (http://code.google.com/p/mobicents/issues/detail?id=1009) // putValue(key, new EmptyConfiguration(false).add(key, values)); } } public void removeValue(int... keys) { for (int i:keys) { List<ConfigurationListener> list = listeners.get(i); if (list != null) { boolean rem = true; for (ConfigurationListener l : list) { rem &= l.elementChanged(i, null); } if (rem) { removeValue(i); } } } } /** * @see org.jdiameter.api.MutableConfiguration class */ public void addChangeListener(ConfigurationListener listener, int... ints) { for (int i:ints) { List<ConfigurationListener> list = listeners.get(i); if (list == null) { list = new CopyOnWriteArrayList<ConfigurationListener>(); list.add(listener); } listeners.put(i, list); } } /** * @see org.jdiameter.api.MutableConfiguration class */ public void removeChangeListener(ConfigurationListener listener,int... ints) { for (int i:ints) { List<ConfigurationListener> list = listeners.get(i); if (list != null) { list.remove(listener); if (list.size() == 0) { listeners.remove(i); } } } } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl.helpers; /** * * @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 Loggers extends org.jdiameter.client.impl.helpers.Loggers{ private static final long serialVersionUID = 1L; /** * Logs for network operations */ public static final Loggers NetWork = new Loggers("NetWork", "netWork", "Logs the NetWork watcher"); public Loggers(String name, String fullName, String desc) { super(name, fullName, desc); } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl; import org.jdiameter.api.*; import org.jdiameter.client.api.StackState; /** * * @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 StackImpl extends org.jdiameter.client.impl.StackImpl implements StackImplMBean{ public MetaData getMetaData() { if (state == StackState.IDLE) throw new IllegalStateException("Meta data not defined"); return (MetaData) assembler.getComponentInstance(MetaDataImpl.class); } public boolean isWrapperFor(Class<?> aClass) throws InternalException { if (aClass == MutablePeerTable.class) return true; else if (aClass == Network.class) return true; else if (aClass == OverloadManager.class) return true; else return super.isWrapperFor(aClass); } public <T> T unwrap(Class<T> aClass) throws InternalException { if (aClass == MutablePeerTable.class) return (T) assembler.getComponentInstance(aClass); if (aClass == Network.class) return (T) assembler.getComponentInstance(aClass); if (aClass == OverloadManager.class) return (T) assembler.getComponentInstance(aClass); else return (T) super.unwrap(aClass); } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl; import static org.jdiameter.client.impl.helpers.Parameters.OwnIPAddress; import static org.jdiameter.server.impl.helpers.Parameters.OwnIPAddresses; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.jdiameter.api.ApplicationId; import org.jdiameter.api.Avp; import org.jdiameter.api.Configuration; import org.jdiameter.api.Network; import org.jdiameter.api.NetworkReqListener; import org.jdiameter.api.OverloadException; import org.jdiameter.api.PeerTable; import org.jdiameter.api.StackType; import org.jdiameter.client.api.IContainer; import org.jdiameter.client.api.IMessage; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.client.api.controller.IPeer; import org.jdiameter.client.api.io.TransportException; import org.jdiameter.client.impl.helpers.IPConverter; import org.jdiameter.common.api.statistic.IStatisticManager; import org.jdiameter.server.api.IMetaData; import org.jdiameter.server.api.IMutablePeerTable; import org.jdiameter.server.api.INetwork; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @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 MetaDataImpl extends org.jdiameter.client.impl.MetaDataImpl implements IMetaData { private static final Logger logger = LoggerFactory.getLogger(MetaDataImpl.class); private final Object lock = new Object(); public MetaDataImpl(IContainer s) { super(s); } public MetaDataImpl(IContainer s, IStatisticManager factory) { super(s, factory); } public StackType getStackType() { return StackType.TYPE_SERVER; } protected IPeer newLocalPeer(IStatisticManager statisticFactory) { return new ServerLocalPeer(statisticFactory); } public void addApplicationId(ApplicationId applicationId) { synchronized (lock) { if (appIds.contains(applicationId)) { return; } appIds.add(applicationId); } if(logger.isDebugEnabled()) { logger.debug("Adding application id of auth [{}] acct [{}] vendor [{}]", new Object[]{applicationId.getAuthAppId(), applicationId.getAcctAppId(), applicationId.getVendorId()}); } } public void remApplicationId(ApplicationId applicationId) { synchronized (lock) { appIds.remove(applicationId); } if(logger.isDebugEnabled()) { logger.debug("Removing application id of auth [{}] acct [{}] vendor [{}]", new Object[]{applicationId.getAuthAppId(), applicationId.getAcctAppId(), applicationId.getVendorId()}); } } public void reload() { // Reload common application ids from configuration synchronized (lock) { appIds.clear(); logger.debug("Clearing out application ids"); getLocalPeer().getCommonApplications(); // Reload ip addresses from configuration ((ServerLocalPeer) peer).resetAddresses(); peer.getIPAddresses(); } } protected class ServerLocalPeer extends ClientLocalPeer { protected INetwork net = null; protected IMutablePeerTable manager = null; protected ISessionFactory factory = null; // XXX: FT/HA // protected Map<String, NetworkReqListener> slc = null; Map<Long, IMessage> peerRequests = new ConcurrentHashMap<Long, IMessage>(); public ServerLocalPeer(IStatisticManager statisticFactory) { super(statisticFactory); } public Set<ApplicationId> getCommonApplications() { Set<ApplicationId> set; synchronized (lock) { set = super.getCommonApplications(); } return set; } @Override public InetAddress[] getIPAddresses() { if (addresses.length == 0) { Configuration[] ipAddresses = stack.getConfiguration().getChildren(OwnIPAddresses.ordinal()); List<InetAddress> list = new ArrayList<InetAddress>(); if (ipAddresses != null) { for (Configuration address : ipAddresses) { if (address != null) { InetAddress iaddress = getAddress(address); if (iaddress != null) { list.add(iaddress); } } } } else { InetAddress address = getDefaultIpAddress(); if (address != null) { list.add(address); } } addresses = list.toArray(new InetAddress[list.size()]); } return addresses; } private InetAddress getAddress(Configuration configuration) { InetAddress rc; String address = configuration.getStringValue(OwnIPAddress.ordinal(), null); if (address == null || address.length() == 0) { rc = getDefaultIpAddress(); } else { try { rc = InetAddress.getByName(address); } catch (UnknownHostException e) { logger.debug("Unable to retrieve IP by Address [{}]", address, e); rc = IPConverter.InetAddressByIPv4(address); if (rc == null) { rc = IPConverter.InetAddressByIPv6(address); } if (rc == null) { rc = getDefaultIpAddress(); } } } return rc; } private InetAddress getDefaultIpAddress() { try { return InetAddress.getByName(getLocalPeer().getUri().getFQDN()); } catch (Exception e1) { logger.debug("Unable to retrieve IP by URI [{}]", getLocalPeer().getUri().getFQDN(), e1); try { return InetAddress.getLocalHost(); } catch (Exception e2) { logger.debug("Unable to retrieve IP for localhost", e2); } } return null; } // Local processing message @SuppressWarnings("unchecked") public boolean sendMessage(IMessage message) throws TransportException, OverloadException { logger.debug("Sending Message in Server Local Peer"); try { if (net == null || manager == null) { try { logger.debug("Unwrapping network and manager"); net = (INetwork) stack.unwrap(Network.class); manager = (IMutablePeerTable) stack.unwrap(PeerTable.class); factory = manager.getSessionFactory(); // XXX: FT/HA // slc = manager.getSessionReqListeners(); } catch (Exception e) { logger.warn("Error initialising for message send", e); } } IMessage answer = null; if (message.isRequest()) { logger.debug("Message is a request"); message.setHopByHopIdentifier(peer.getHopByHopIdentifier()); peerRequests.put(message.getHopByHopIdentifier(), message); NetworkReqListener listener = net.getListener(message); if (listener != null) { // This is duplicate code from PeerImpl answer = manager.isDuplicate(message); if (answer != null) { logger.debug("Found message in duplicates. No need to invoke listener, will send previous answer."); answer.setProxiable(message.isProxiable()); answer.getAvps().removeAvp(Avp.PROXY_INFO); for (Avp avp : message.getAvps().getAvps(Avp.PROXY_INFO)) { answer.getAvps().addAvp(avp); } answer.setHopByHopIdentifier(message.getHopByHopIdentifier()); } else { String avpSessionId = message.getSessionId(); if (avpSessionId != null) { // XXX: FT/HA // NetworkReqListener sessionListener = slc.get(avpSessionId); NetworkReqListener sessionListener = (NetworkReqListener) sessionDataSource.getSessionListener(avpSessionId); if (sessionListener != null) { logger.debug("Giving message to sessionListener to process as Session-Id AVP existed in message and was used to get a session from Session DataSource"); answer = (IMessage) sessionListener.processRequest(message); } else { try { logger.debug("Giving message to listener to process. Listener was retrieved from net"); answer = (IMessage) listener.processRequest(message); if (answer != null) { manager.saveToDuplicate(message.getDuplicationKey(), answer); } } catch (Exception e) { logger.debug("Error during processing message by listener", e); } } } } } else { if(logger.isDebugEnabled()) { logger.debug("Unable to find handler {} for message {}", message.getSingleApplicationId(), message); } } if (answer != null) { if(logger.isDebugEnabled()) { logger.debug("Removing message with HbH Identifier [{}] from Peer Requests Map", message.getHopByHopIdentifier()); } peerRequests.remove(message.getHopByHopIdentifier()); } } else { if(logger.isDebugEnabled()) { logger.debug("Message is an answer. Setting answer to the message and fetching message from Peer Requests Map using HbH Identifier [{}]", message.getHopByHopIdentifier()); } answer = message; message = peerRequests.get(answer.getHopByHopIdentifier()); } // Process answer if (message != null && !message.isTimeOut() && answer != null) { logger.debug("Clearing timer on message and notifying event listeners of receiving success message"); message.clearTimer(); message.setState(IMessage.STATE_ANSWERED); message.getEventListener().receivedSuccessMessage(message, answer); } return true; } catch (Exception e) { logger.warn("Unable to process message {}", message, e); } return false; } } }
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.server.impl.agent; import java.util.Properties; import org.jdiameter.api.Configuration; import org.jdiameter.api.InternalException; import org.jdiameter.server.api.agent.IAgentConfiguration; import static org.jdiameter.client.impl.helpers.Parameters.Properties; import static org.jdiameter.client.impl.helpers.Parameters.PropertyName; import static org.jdiameter.client.impl.helpers.Parameters.PropertyValue; /** * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class AgentConfigurationImpl implements IAgentConfiguration { private static final long serialVersionUID = 1L; protected Properties properties; /* * (non-Javadoc) * @see org.jdiameter.server.api.agent.IAgentConfiguration#getProperties() */ public Properties getProperties() { return this.properties; } /* * (non-Javadoc) * * @see org.jdiameter.server.api.agent.IAgentConfiguration#parse(java.lang.String ) */ public IAgentConfiguration parse(String agentConfiguration) throws InternalException { if (agentConfiguration == null) { return null; } AgentConfigurationImpl conf = new AgentConfigurationImpl(); try { conf.properties = new Properties(); String[] split = agentConfiguration.split(";"); for (String s : split) { String[] data = s.split("="); conf.properties.put(data[0], data[1]); } } catch (Exception e) { throw new InternalException(e); } return conf; } /* * (non-Javadoc) * * @see org.jdiameter.server.api.agent.IAgentConfiguration#parse(org.jdiameter .api.Configuration) */ public IAgentConfiguration parse(Configuration agentConfiguration) throws InternalException { if (agentConfiguration == null) { return null; } AgentConfigurationImpl conf = new AgentConfigurationImpl(); try { conf.properties = new Properties(); Configuration[] propConfs = agentConfiguration.getChildren(Properties.ordinal()); for (Configuration c : propConfs) { conf.properties.put(c.getStringValue(PropertyName.ordinal(), ""), c.getStringValue(PropertyValue.ordinal(), "")); } } catch (Exception e) { throw new InternalException(e); } return conf; } }
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.server.impl.agent; import org.apache.log4j.Logger; import org.jdiameter.api.Answer; import org.jdiameter.api.Request; import org.jdiameter.client.api.IContainer; import org.jdiameter.client.api.IRequest; import org.jdiameter.client.api.controller.IRealm; import org.jdiameter.client.api.controller.IRealmTable; import org.jdiameter.server.api.agent.IProxy; /** * * * @author babass */ public class ProxyAgentImpl extends AgentImpl implements IProxy { private static Logger logger = Logger.getLogger(ProxyAgentImpl.class); /** * @param container * @param realmTable */ public ProxyAgentImpl(IContainer container, IRealmTable realmTable) { super(container, realmTable); logger.info("proxy agent: created"); } /* * (non-Javadoc) * * @see * org.jdiameter.server.api.agent.IAgent#processRequest(org.jdiameter.client * .api.IRequest, org.jdiameter.client.api.controller.IRealm) */ @Override public Answer processRequest(IRequest request, IRealm matchedRealm) { logger.info("proxy agent: processRequest executed"); return null; } /* * (non-Javadoc) * * @see * org.jdiameter.api.EventListener#receivedSuccessMessage(org.jdiameter. * api.Message, org.jdiameter.api.Message) */ @Override public void receivedSuccessMessage(Request request, Answer answer) { logger.info("proxy agent: receivedSuccessMessage"); } /* * (non-Javadoc) * * @see * org.jdiameter.api.EventListener#timeoutExpired(org.jdiameter.api.Message) */ @Override public void timeoutExpired(Request request) { logger.info("proxy agent: timeoutExpired"); } }
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.server.impl.agent; import java.io.IOException; import java.util.Properties; import org.jdiameter.api.Answer; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpDataException; import org.jdiameter.api.AvpSet; import org.jdiameter.api.IllegalDiameterStateException; import org.jdiameter.api.Request; import org.jdiameter.api.ResultCode; import org.jdiameter.api.RouteException; import org.jdiameter.client.api.IContainer; import org.jdiameter.client.api.IMessage; import org.jdiameter.client.api.IRequest; import org.jdiameter.client.api.controller.IRealm; import org.jdiameter.client.api.controller.IRealmTable; import org.jdiameter.server.api.agent.IAgentConfiguration; import org.jdiameter.server.api.agent.IRedirect; 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 RedirectAgentImpl extends AgentImpl implements IRedirect { private static final Logger logger = LoggerFactory.getLogger(RedirectAgentImpl.class); /** * @param container * @param peerTable * @param realmTable */ public RedirectAgentImpl(IContainer container, IRealmTable realmTable) { super(container, realmTable); } public static final int RESULT_REDIRECT_INDICATION = ResultCode.REDIRECT_INDICATION; public static final int RESULT_INVALID_AVP_VALUE = ResultCode.INVALID_AVP_VALUE; /* * (non-Javadoc) * @see org.jdiameter.server.api.agent.IAgent#processRequest(org.jdiameter.client.api.IRequest, org.jdiameter.client.api.controller.IRealm) */ public Answer processRequest(IRequest request,IRealm matchedRealm) { try { Answer ans = request.createAnswer(RESULT_REDIRECT_INDICATION); AvpSet set = ans.getAvps(); String[] destHosts = matchedRealm.getPeerNames(); for(String host:destHosts) { set.addAvp(Avp.REDIRECT_HOST,host,false); } IAgentConfiguration agentConfiguration = matchedRealm.getAgentConfiguration(); //default int rhuValue = RHU_REALM_AND_APPLICATION; if(agentConfiguration != null) { Properties p = agentConfiguration.getProperties(); try { rhuValue = Integer.parseInt(p.getProperty(RHU_PROPERTY, ""+rhuValue)); } catch(Exception e) { if(logger.isWarnEnabled()) { logger.warn("Failed to parse configuration value. ", e); } } } set.addAvp(Avp.REDIRECT_HOST_USAGE, rhuValue); ans.setError(true); super.container.sendMessage((IMessage) ans); } catch (Exception e) { if(logger.isDebugEnabled()) { logger.debug("Failure when trying to send Answer", e); } Answer ans = request.createAnswer(RESULT_INVALID_AVP_VALUE); // now lets do the magic. if (e instanceof AvpDataException && ((AvpDataException)e).getAvp() != null) { // lets add failed if its present AvpSet failedAvp = ans.getAvps().addGroupedAvp(Avp.FAILED_AVP); failedAvp.addAvp(((AvpDataException)e).getAvp()); } try { container.sendMessage((IMessage) ans); } catch (RouteException re) { if(logger.isDebugEnabled()) { logger.debug("Failure when trying to send failure answer", re); } } catch (AvpDataException ade) { if(logger.isDebugEnabled()) { logger.debug("Failure when trying to send failure answer", ade); } } catch (IllegalDiameterStateException idse) { if(logger.isDebugEnabled()) { logger.debug("Failure when trying to send failure answer", idse); } } catch (IOException ioe) { if(logger.isDebugEnabled()) { logger.debug("Failure when trying to send failure answer", ioe); } } } return null; } /* * (non-Javadoc) * @see org.jdiameter.api.EventListener#receivedSuccessMessage(org.jdiameter.api.Message, org.jdiameter.api.Message) */ public void receivedSuccessMessage(Request request, Answer answer) { // TODO Auto-generated method stub } /* * (non-Javadoc) * @see org.jdiameter.api.EventListener#timeoutExpired(org.jdiameter.api.Message) */ public void timeoutExpired(Request request) { // TODO Auto-generated method stub } }
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.server.impl.agent; import org.jdiameter.client.api.IContainer; import org.jdiameter.client.api.controller.IRealmTable; import org.jdiameter.server.api.agent.IAgent; /** * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public abstract class AgentImpl implements IAgent { protected IContainer container; protected IRealmTable realmTable; /** * @param container * @param peerTable * @param realmTable */ public AgentImpl(IContainer container, IRealmTable realmTable) { super(); this.container = container; this.realmTable = realmTable; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import org.jdiameter.api.ApplicationAlreadyUseException; import org.jdiameter.api.ApplicationId; import org.jdiameter.api.InternalException; import org.jdiameter.api.LocalAction; import org.jdiameter.api.Message; import org.jdiameter.api.NetworkReqListener; import org.jdiameter.api.Peer; import org.jdiameter.api.Realm; import org.jdiameter.api.Selector; import org.jdiameter.api.Statistic; import org.jdiameter.api.URI; import org.jdiameter.client.api.IMessage; import org.jdiameter.common.api.statistic.IStatistic; import org.jdiameter.common.api.statistic.IStatisticManager; import org.jdiameter.common.api.statistic.IStatisticRecord; import org.jdiameter.server.api.IMetaData; import org.jdiameter.server.api.IMutablePeerTable; import org.jdiameter.server.api.INetwork; import org.jdiameter.server.api.IRouter; import org.jdiameter.server.api.agent.IAgentConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @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 NetworkImpl implements INetwork { private static final Logger logger = LoggerFactory.getLogger(NetworkImpl.class); protected IMutablePeerTable manager; protected IRouter router; protected IMetaData metaData; private final ApplicationId commonAuthAppId = ApplicationId.createByAuthAppId(0, 0xffffffff); private final ApplicationId commonAccAppId = ApplicationId.createByAccAppId(0, 0xffffffff); private final ConcurrentHashMap<ApplicationId, NetworkReqListener> appIdToNetListener = new ConcurrentHashMap<ApplicationId, NetworkReqListener>(); private final ConcurrentHashMap<Selector, NetworkReqListener> selectorToNetListener = new ConcurrentHashMap<Selector, NetworkReqListener>(); protected IStatistic statistic; public NetworkImpl(IStatisticManager statisticFactory, IMetaData metaData, IRouter router) { this.router = router; this.metaData = metaData; IStatisticRecord nrlStat = statisticFactory.newCounterRecord(IStatisticRecord.Counters.RequestListenerCount, new IStatisticRecord.IntegerValueHolder() { public int getValueAsInt() { return appIdToNetListener.size(); } public String getValueAsString() { return String.valueOf(getValueAsInt()); } }); IStatisticRecord nslStat = statisticFactory.newCounterRecord(IStatisticRecord.Counters.SelectorCount, new IStatisticRecord.IntegerValueHolder() { public int getValueAsInt() { return selectorToNetListener.size(); } public String getValueAsString() { return String.valueOf(getValueAsInt()); } }); //no need to remove, this class lives with whole stack, until its destroyed. statistic = statisticFactory.newStatistic("network",IStatistic.Groups.Network, nrlStat, nslStat); } public void addNetworkReqListener(NetworkReqListener networkReqListener, ApplicationId... applicationId) throws ApplicationAlreadyUseException { for (ApplicationId a : applicationId) { if (appIdToNetListener.containsKey(commonAuthAppId) || appIdToNetListener.containsKey(commonAccAppId)) throw new ApplicationAlreadyUseException(a + " already use by common application id"); if (appIdToNetListener.containsKey(applicationId)) throw new ApplicationAlreadyUseException(a + " already use"); appIdToNetListener.put(a, networkReqListener); metaData.addApplicationId(a); // this has ALL config declared, we need currently deployed router.getRealmTable().addLocalApplicationId(a); } } public void addNetworkReqListener(NetworkReqListener listener, Selector<Message, ApplicationId>... selectors) { for (Selector<Message, ApplicationId> s : selectors) { selectorToNetListener.put(s, listener); ApplicationId ap = s.getMetaData(); metaData.addApplicationId(ap); router.getRealmTable().addLocalApplicationId(ap); } } public void removeNetworkReqListener(ApplicationId... applicationId) { for (ApplicationId a : applicationId) { appIdToNetListener.remove(a); for (Selector<Message, ApplicationId> s : selectorToNetListener.keySet()) { if (s.getMetaData().equals(a)) return; } metaData.remApplicationId(a); router.getRealmTable().removeLocalApplicationId(a); } } public void removeNetworkReqListener(Selector<Message, ApplicationId>... selectors) { for (Selector<Message, ApplicationId> s : selectors) { selectorToNetListener.remove(s); if (appIdToNetListener.containsKey(s.getMetaData())) { return; } for (Selector<Message, ApplicationId> i : selectorToNetListener.keySet()) { if (i.getMetaData().equals(s.getMetaData())) { return; } } metaData.remApplicationId(s.getMetaData()); router.getRealmTable().removeLocalApplicationId(s.getMetaData()); } } public Peer addPeer(String name, String realm, boolean connecting) { if (manager != null) { try { return manager.addPeer(new URI(name), realm, connecting); } catch (Exception e) { logger.error("Failed to add peer with name[" + name + "] and realm[" + realm + "] (connecting=" + connecting + ")", e); return null; } } else { logger.debug("Failed to add peer with name[{}] and realm[{}] (connecting={}) as peer manager is null.", new Object[]{name, realm, connecting}); return null; } } public boolean isWrapperFor(Class<?> aClass) throws InternalException { return false; } public <T> T unwrap(Class<T> aClass) throws InternalException { return null; } public Realm addRealm(String name, ApplicationId applicationId, LocalAction localAction, String agentConfiguration, boolean dynamic, long expirationTime) { try { //TODO: why oh why this method exists? return router.getRealmTable().addRealm(name, applicationId, localAction, agentConfiguration, dynamic, expirationTime, new String[0]); } catch (InternalException e) { logger.error("Failure on add realm operation.",e); return null; } } public Realm addRealm(String name, ApplicationId applicationId, LocalAction localAction, IAgentConfiguration agentConfiguration, boolean dynamic, long expirationTime) { try { //TODO: why oh why this method exists? return router.getRealmTable().addRealm(name, applicationId, localAction,agentConfiguration, dynamic, expirationTime, new String[0]); } catch (InternalException e) { logger.error("Failure on add realm operation.",e); return null; } } public Collection<Realm> remRealm(String name) { return router.getRealmTable().removeRealm(name); } public Statistic getStatistic() { return this.statistic; } public NetworkReqListener getListener(IMessage message) { if (message == null) return null; for (Selector<Message, ApplicationId> s : selectorToNetListener.keySet()) { boolean r = s.checkRule(message); if (r) return selectorToNetListener.get(s); } ApplicationId appId = message.getSingleApplicationId(); if (appId == null) return null; if (appIdToNetListener.containsKey(commonAuthAppId)) return appIdToNetListener.get(commonAuthAppId); else if (appIdToNetListener.containsKey(commonAccAppId)) return appIdToNetListener.get(commonAccAppId); else return appIdToNetListener.get(appId); } public void setPeerManager(IMutablePeerTable manager) { this.manager = manager; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl; /** * * @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 interface StackImplMBean extends org.jdiameter.client.impl.StackImplMBean { }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl.fsm; import org.jdiameter.api.Configuration; import org.jdiameter.api.InternalException; import org.jdiameter.client.api.fsm.IContext; import org.jdiameter.common.api.concurrent.IConcurrentFactory; import org.jdiameter.common.api.statistic.IStatisticManager; import org.jdiameter.server.api.IFsmFactory; import org.jdiameter.server.api.IStateMachine; /** * * @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 FsmFactoryImpl extends org.jdiameter.client.impl.fsm.FsmFactoryImpl implements IFsmFactory { public FsmFactoryImpl(IStatisticManager statisticFactory) { super(statisticFactory); } public IStateMachine createInstanceFsm(IContext context, IConcurrentFactory concurrentFactory, Configuration config) throws InternalException { return new org.jdiameter.server.impl.fsm.PeerFSMImpl(context, concurrentFactory, config, statisticFactory); } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl.fsm; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpDataException; import org.jdiameter.api.Configuration; import org.jdiameter.api.ConfigurationListener; import org.jdiameter.api.DisconnectCause; import org.jdiameter.api.MutableConfiguration; import org.jdiameter.api.ResultCode; import org.jdiameter.api.app.State; import org.jdiameter.api.app.StateEvent; import org.jdiameter.client.api.IMessage; import org.jdiameter.client.api.fsm.IContext; import static org.jdiameter.client.impl.fsm.FsmState.*; import org.jdiameter.common.api.concurrent.IConcurrentFactory; import org.jdiameter.common.api.statistic.IStatisticManager; import org.jdiameter.server.api.IStateMachine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class PeerFSMImpl extends org.jdiameter.client.impl.fsm.PeerFSMImpl implements IStateMachine, ConfigurationListener { private static final Logger logger = LoggerFactory.getLogger(org.jdiameter.server.impl.fsm.PeerFSMImpl.class); public PeerFSMImpl(IContext context, IConcurrentFactory concurrentFactory, Configuration config, IStatisticManager statisticFactory) { super(context, concurrentFactory, config, statisticFactory); } protected void loadTimeOuts(Configuration config) { super.loadTimeOuts(config); if (config instanceof MutableConfiguration) { ((MutableConfiguration) config).addChangeListener(this, 0); } } public boolean elementChanged(int i, Object data) { Configuration newConfig = (Configuration) data; super.loadTimeOuts(newConfig); return true; } protected State[] getStates() { if (states == null) { states = new State[] { new MyState() // OKEY { public void entryAction() { // todo send buffered messages setInActiveTimer(); watchdogSent = false; } public boolean processEvent(StateEvent event) { switch (type(event)) { case DISCONNECT_EVENT: doEndConnection(); break; case TIMEOUT_EVENT: try { context.sendDwrMessage(); setTimer(DWA_TIMEOUT); if (watchdogSent) { switchToNextState(SUSPECT); } else { watchdogSent = true; } } catch (Throwable e) { logger.debug("Can not send DWR", e); doDisconnect(); doEndConnection(); } break; case STOP_EVENT: try { if(event.getData() == null) { context.sendDprMessage(DisconnectCause.BUSY); } else { Integer disconnectCause = (Integer) event.getData(); context.sendDprMessage(disconnectCause); } setTimer(DPA_TIMEOUT); switchToNextState(STOPPING); } catch (Throwable e) { logger.debug("Can not send DPR", e); doDisconnect(); switchToNextState(DOWN); } break; case RECEIVE_MSG_EVENT: setInActiveTimer(); context.receiveMessage(message(event)); break; case CEA_EVENT: setInActiveTimer(); if (context.processCeaMessage(key(event), message(event))) { doDisconnect(); // ! doEndConnection(); } break; case CER_EVENT: // setInActiveTimer(); logger.debug("Rejecting CER in OKAY state. Answering with UNABLE_TO_COMPLY (5012)"); try { context.sendCeaMessage(ResultCode.UNABLE_TO_COMPLY, message(event), "Unable to receive CER in OPEN state."); } catch (Exception e) { logger.debug("Failed to send CEA.", e); doDisconnect(); // ! doEndConnection(); } break; case DPR_EVENT: try { int code = context.processDprMessage((IMessage) event.getData()); context.sendDpaMessage(message(event), code, null); } catch (Throwable e) { logger.debug("Can not send DPA", e); } IMessage message = (IMessage) event.getData(); try { Avp discCause = message.getAvps().getAvp(Avp.DISCONNECT_CAUSE); boolean willReconnect = (discCause != null) ? (discCause.getInteger32() == DisconnectCause.REBOOTING) : false; if(willReconnect) { doDisconnect(); doEndConnection(); } else { doDisconnect(); switchToNextState(DOWN); } } catch (AvpDataException ade) { logger.warn("Disconnect cause is bad.", ade); doDisconnect(); switchToNextState(DOWN); } break; case DWR_EVENT: setInActiveTimer(); try { context.sendDwaMessage(message(event), ResultCode.SUCCESS, null); } catch (Throwable e) { logger.debug("Can not send DWA, reconnecting", e); doDisconnect(); doEndConnection(); } break; case DWA_EVENT: setInActiveTimer(); watchdogSent = false; break; case SEND_MSG_EVENT: try { context.sendMessage(message(event)); } catch (Throwable e) { logger.debug("Can not send message", e); doDisconnect(); doEndConnection(); } break; default: logger.debug("Unknown event type {} in state {}", type(event), state); return false; } return true; } }, new MyState() // SUSPECT { public boolean processEvent(StateEvent event) { switch (type(event)) { case DISCONNECT_EVENT: doEndConnection(); break; case TIMEOUT_EVENT: doDisconnect(); doEndConnection(); break; case STOP_EVENT: try { if(event.getData() == null) { context.sendDprMessage(DisconnectCause.REBOOTING); } else { Integer disconnectCause = (Integer) event.getData(); context.sendDprMessage(disconnectCause); } setInActiveTimer(); switchToNextState(STOPPING); } catch (Throwable e) { logger.debug("Can not send DPR", e); doDisconnect(); switchToNextState(DOWN); } break; case CER_EVENT: case CEA_EVENT: case DWA_EVENT: clearTimer(); switchToNextState(OKAY); break; case DPR_EVENT: try { int code = context.processDprMessage((IMessage) event.getData()); context.sendDpaMessage(message(event), code, null); } catch (Throwable e) { logger.debug("Can not send DPA", e); } IMessage message = (IMessage) event.getData(); try { if(message.getAvps().getAvp(Avp.DISCONNECT_CAUSE)!=null && message.getAvps().getAvp(Avp.DISCONNECT_CAUSE).getInteger32()==DisconnectCause.REBOOTING) { doDisconnect(); doEndConnection(); } else { doDisconnect(); switchToNextState(DOWN); } } catch (AvpDataException e1) { logger.warn("Disconnect cause is bad.",e1); doDisconnect(); switchToNextState(DOWN); } break; case DWR_EVENT: try { int code = context.processDwrMessage((IMessage) event.getData()); context.sendDwaMessage(message(event),code, null); switchToNextState(OKAY); } catch (Throwable e) { logger.debug("Can not send DWA", e); doDisconnect(); switchToNextState(DOWN); } break; case RECEIVE_MSG_EVENT: clearTimer(); context.receiveMessage(message(event)); switchToNextState(OKAY); break; case SEND_MSG_EVENT: // todo buffering throw new IllegalStateException("Connection is down"); default: logger.debug("Unknown event type {} in state {}", type(event), state); return false; } return true; } }, new MyState() // DOWN { public void entryAction() { setTimer(0); //FIXME: baranowb: removed this, cause this breaks peers as // it seems, if peer is not removed, it will linger // without any way to process messages // if(context.isRestoreConnection()) { //PCB added FSM multithread mustRun = false; // } context.removeStatistics(); } public boolean processEvent(StateEvent event) { switch (type(event)) { case START_EVENT: try { context.createStatistics(); if (!context.isConnected()) { context.connect(); } context.sendCerMessage(); setTimer(CEA_TIMEOUT); switchToNextState(INITIAL); } catch (Throwable e) { logger.debug("Connect error", e); doEndConnection(); } break; case CER_EVENT: context.createStatistics(); int resultCode = context.processCerMessage(key(event), message(event)); if (resultCode == ResultCode.SUCCESS) { try { context.sendCeaMessage(resultCode, message(event), null); switchToNextState(OKAY); } catch (Exception e) { logger.debug("Failed to send CEA.", e); doDisconnect(); // ! doEndConnection(); } } else { try { context.sendCeaMessage(resultCode, message(event), null); } catch (Exception e) { logger.debug("Failed to send CEA.", e); } doDisconnect(); // ! doEndConnection(); } break; case SEND_MSG_EVENT: // todo buffering throw new IllegalStateException("Connection is down"); case STOP_EVENT: case TIMEOUT_EVENT: case DISCONNECT_EVENT: // those are ~legal, ie. DISCONNECT_EVENT is sent back from connection break; default: logger.debug("Unknown event type {} in state {}", type(event), state); return false; } return true; } }, new MyState() // REOPEN { public boolean processEvent(StateEvent event) { switch (type(event)) { case CONNECT_EVENT: try { context.sendCerMessage(); setTimer(CEA_TIMEOUT); switchToNextState(INITIAL); } catch (Throwable e) { logger.debug("Can not send CER", e); setTimer(REC_TIMEOUT); } break; case TIMEOUT_EVENT: try { context.connect(); } catch (Exception e) { logger.debug("Can not connect to remote peer", e); setTimer(REC_TIMEOUT); } break; case STOP_EVENT: setTimer(0); doDisconnect(); switchToNextState(DOWN); break; case DISCONNECT_EVENT: break; case SEND_MSG_EVENT: // todo buffering throw new IllegalStateException("Connection is down"); default: logger.debug("Unknown event type {} in state {}", type(event), state); return false; } return true; } }, new MyState() // INITIAL { public void entryAction() { setTimer(CEA_TIMEOUT); } public boolean processEvent(StateEvent event) { switch (type(event)) { case DISCONNECT_EVENT: setTimer(0); doEndConnection(); break; case TIMEOUT_EVENT: doDisconnect(); doEndConnection(); break; case STOP_EVENT: setTimer(0); doDisconnect(); switchToNextState(DOWN); break; case CEA_EVENT: setTimer(0); if (context.processCeaMessage(key(event), message(event))) { switchToNextState(OKAY); } else { doDisconnect(); // ! doEndConnection(); } break; case CER_EVENT: int resultCode = context.processCerMessage(key(event), message(event)); if (resultCode == ResultCode.SUCCESS) { try { context.sendCeaMessage(resultCode, message(event), null); switchToNextState(OKAY); // if other connection is win } catch (Exception e) { logger.debug("Can not send CEA", e); doDisconnect(); doEndConnection(); } } else if (resultCode == -1 || resultCode == ResultCode.NO_COMMON_APPLICATION) { doDisconnect(); doEndConnection(); } break; case SEND_MSG_EVENT: // todo buffering throw new IllegalStateException("Connection is down"); default: logger.debug("Unknown event type {} in state {}", type(event), state); return false; } return true; } }, new MyState() // STOPPING { public boolean processEvent(StateEvent event) { switch (type(event)) { case TIMEOUT_EVENT: case DPA_EVENT: switchToNextState(DOWN); break; case RECEIVE_MSG_EVENT: context.receiveMessage(message(event)); break; case SEND_MSG_EVENT: throw new IllegalStateException("Stack now is stopping"); case STOP_EVENT: case DISCONNECT_EVENT: break; default: logger.debug("Unknown event type {} in state {}", type(event), state); return false; } return true; } } }; } return states; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl; import org.jdiameter.api.Configuration; import org.jdiameter.api.MetaData; import org.jdiameter.client.api.IContainer; import org.jdiameter.client.api.controller.IRealmTable; import org.jdiameter.common.api.concurrent.IConcurrentFactory; import org.jdiameter.server.api.IRouter; /** * * @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 RouterImpl extends org.jdiameter.client.impl.router.RouterImpl implements IRouter { public RouterImpl(IContainer container,IConcurrentFactory concurrentFactory, IRealmTable realmTable, Configuration config, MetaData metaData) { super(container,concurrentFactory, realmTable, config, metaData); } }
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.server.impl; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpSet; import org.jdiameter.api.ResultCode; import org.jdiameter.client.api.IMessage; /** * This class provides check incoming/outgoing diameter messages. * Check's rules consist into xml file. * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class MessageValidator { public static final Result SUCCESS = new Result(null, ResultCode.SUCCESS); private boolean enable = true; public MessageValidator() { // todo load validator rules } /** * Enable validation functions */ public void enable() { enable = true; } /** * Disable validation functions */ public void disable() { enable = false; } /** * Return true if validation function is on * @return true if validation function is on */ public boolean isEnable() { return enable; } /** * Validate message * @param message message instance * @return result of validation procedure */ public Result check(IMessage message) { if (message == null) throw new IllegalArgumentException("Message is null"); if (!enable) return SUCCESS; // todo return null; } public static class Result { private IMessage errorMessage; private long code = ResultCode.SUCCESS; Result(IMessage errorMessage, long code) { this.errorMessage = errorMessage; this.code = code; } /** * Return true if message is correct * @return true if message is correct */ public boolean isOK() { return code == ResultCode.SUCCESS || code == ResultCode.LIMITED_SUCCESS; } /** * Return long value of result code * @return long value of result code */ public long toLong() { return code; } /** * Create error answer message with Result-Code Avp * @return error answer message */ public IMessage toMessage() { if ( errorMessage != null && errorMessage.getAvps().getAvp(Avp.RESULT_CODE) == null ) errorMessage.getAvps().addAvp(Avp.RESULT_CODE, code); return errorMessage; } /** * Create error answer message with Experemental-Result-Code Avp * @param vendorId vendor id * @return error answer message with Experemental-Result-Code Avp */ public IMessage toMessage(int vendorId) { if ( errorMessage != null && errorMessage.getAvps().getAvp(297) == null ) { // EXPERIMENTAL_RESULT = 297 AvpSet er = errorMessage.getAvps().addGroupedAvp(297); er.addAvp(Avp.VENDOR_ID, vendorId); er.addAvp(Avp.EXPERIMENTAL_RESULT_CODE, code); } return errorMessage; } } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.impl; import static org.jdiameter.api.PeerState.DOWN; import static org.jdiameter.api.PeerState.INITIAL; import java.io.IOException; import java.net.InetAddress; import java.util.Map; import java.util.Set; import org.jdiameter.api.ApplicationId; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpDataException; import org.jdiameter.api.Configuration; import org.jdiameter.api.InternalException; import org.jdiameter.api.LocalAction; import org.jdiameter.api.Message; import org.jdiameter.api.NetworkReqListener; import org.jdiameter.api.OverloadException; import org.jdiameter.api.PeerState; import org.jdiameter.api.ResultCode; import org.jdiameter.api.StatisticRecord; import org.jdiameter.api.URI; import org.jdiameter.client.api.IMessage; import org.jdiameter.client.api.IMetaData; import org.jdiameter.client.api.IRequest; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.client.api.controller.IRealm; import org.jdiameter.client.api.controller.IRealmTable; import org.jdiameter.client.api.fsm.IContext; import org.jdiameter.client.api.io.IConnection; import org.jdiameter.client.api.io.ITransportLayerFactory; import org.jdiameter.client.api.io.TransportException; import org.jdiameter.client.api.parser.IMessageParser; import org.jdiameter.common.api.concurrent.IConcurrentFactory; import org.jdiameter.common.api.data.ISessionDatasource; import org.jdiameter.common.api.statistic.IStatisticManager; import org.jdiameter.common.api.statistic.IStatisticRecord; import org.jdiameter.server.api.IFsmFactory; import org.jdiameter.server.api.INetwork; import org.jdiameter.server.api.IOverloadManager; import org.jdiameter.server.api.IPeer; import org.jdiameter.server.api.IStateMachine; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @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 PeerImpl extends org.jdiameter.client.impl.controller.PeerImpl implements IPeer { private static final Logger logger = LoggerFactory.getLogger(org.jdiameter.server.impl.PeerImpl.class); // External references private MutablePeerTableImpl peerTable; protected Set<String> predefinedPeerTable; protected INetwork network; protected IOverloadManager ovrManager; protected ISessionFactory sessionFactory; // Internal parameters and members protected boolean isDuplicateProtection; protected boolean isAttemptConnection; protected boolean isElection = true; protected Map<String, IConnection> incConnections; /** * Create instance of class */ public PeerImpl(int rating, URI remotePeer, String ip, String portRange, boolean attCnn, IConnection connection, MutablePeerTableImpl peerTable, IMetaData metaData, Configuration config, Configuration peerConfig, ISessionFactory sessionFactory, IFsmFactory fsmFactory, ITransportLayerFactory trFactory, IStatisticManager statisticFactory, IConcurrentFactory concurrentFactory, IMessageParser parser, INetwork nWork, IOverloadManager oManager, final ISessionDatasource sessionDataSource) throws InternalException, TransportException { super(peerTable, rating, remotePeer, ip, portRange, metaData, config, peerConfig, fsmFactory, trFactory, parser, statisticFactory, concurrentFactory, connection, sessionDataSource); // Create specific action context this.peerTable = peerTable; this.isDuplicateProtection = this.peerTable.isDuplicateProtection(); this.sessionFactory = sessionFactory; this.isAttemptConnection = attCnn; this.incConnections = this.peerTable.getIncConnections(); this.predefinedPeerTable = this.peerTable.getPredefinedPeerTable(); this.network = nWork; this.ovrManager = oManager; } protected void createPeerStatistics() { super.createPeerStatistics(); // Append fsm statistic if (this.fsm instanceof IStateMachine) { StatisticRecord[] records = ((IStateMachine) fsm).getStatistic().getRecords(); IStatisticRecord[] recordsArray = new IStatisticRecord[records.length]; int count = 0; for(StatisticRecord st: records) { recordsArray[count++] = (IStatisticRecord) st; } this.statistic.appendCounter(recordsArray); } } protected void preProcessRequest(IMessage message) { // ammendonca: this is non-sense, we don't want to save requests //if (isDuplicateProtection && message.isRequest()) { // peerTable.saveToDuplicate(message.getDuplicationKey(), message); //} } public boolean isAttemptConnection() { return isAttemptConnection; } public IContext getContext() { return new LocalActionConext(); } public IConnection getConnection() { return connection; } public void addIncomingConnection(IConnection conn) { PeerState state = fsm.getState(PeerState.class); if (DOWN == state || INITIAL == state) { conn.addConnectionListener(connListener); // ammendonca: if we are receiving a new connection in such state, we may want to make it primary, right? this.connection = conn; logger.debug("Append external connection [{}]", conn.getKey()); } else { logger.debug("Releasing connection [{}]", conn.getKey()); incConnections.remove(conn.getKey()); try { conn.release(); } catch (IOException e) { logger.debug("Can not close external connection", e); } finally { logger.debug("Close external connection"); } } } public void setElection(boolean isElection) { this.isElection = isElection; } public void notifyOvrManager(IOverloadManager ovrManager) { ovrManager.changeNotification(0, getUri(), fsm.getQueueInfo()); } public String toString() { if (fsm != null) { return "SPeer{" + "Uri=" + uri + "; State=" + fsm.getState(PeerState.class) + "; con="+ connection +"; incCon"+incConnections+" }"; } return "SPeer{" + "Uri=" + uri + "; State=" + fsm + "; con="+ connection +"; incCon"+incConnections+" }"; } protected class LocalActionConext extends ActionContext { public void sendCeaMessage(int resultCode, Message cer, String errMessage) throws TransportException, OverloadException { logger.debug("Send CEA message"); IMessage message = parser.createEmptyMessage(Message.CAPABILITIES_EXCHANGE_ANSWER, 0); message.setRequest(false); message.setHopByHopIdentifier(cer.getHopByHopIdentifier()); message.setEndToEndIdentifier(cer.getEndToEndIdentifier()); message.getAvps().addAvp(Avp.ORIGIN_HOST, metaData.getLocalPeer().getUri().getFQDN(), true, false, true); message.getAvps().addAvp(Avp.ORIGIN_REALM, metaData.getLocalPeer().getRealmName(), true, false, true); for (InetAddress ia : metaData.getLocalPeer().getIPAddresses()) { message.getAvps().addAvp(Avp.HOST_IP_ADDRESS, ia, true, false); } message.getAvps().addAvp(Avp.VENDOR_ID, metaData.getLocalPeer().getVendorId(), true, false, true); for (ApplicationId appId: metaData.getLocalPeer().getCommonApplications()) { addAppId(appId, message); } message.getAvps().addAvp(Avp.PRODUCT_NAME, metaData.getLocalPeer().getProductName(), false); message.getAvps().addAvp(Avp.RESULT_CODE, resultCode, true, false, true); message.getAvps().addAvp(Avp.FIRMWARE_REVISION, metaData.getLocalPeer().getFirmware(), true); if (errMessage != null) { message.getAvps().addAvp(Avp.ERROR_MESSAGE, errMessage, false); } sendMessage(message); } public int processCerMessage(String key, IMessage message) { logger.debug("Processing CER"); int resultCode = ResultCode.SUCCESS; try { if (connection == null || !connection.isConnected()) { if (logger.isDebugEnabled()) { logger.debug("Connection is null or not connected. Looking for one in incConnections with key [{}]. Here are the incConnections :", key); for (String c : incConnections.keySet()) { logger.debug(c); } } connection = incConnections.get(key); } // Process cer Set<ApplicationId> newAppId = getCommonApplicationIds(message); if (newAppId.isEmpty()) { if(logger.isDebugEnabled()) { logger.debug("Processing CER failed, no common application. Message AppIds [{}]", message.getApplicationIdAvps()); } return ResultCode.NO_COMMON_APPLICATION; } // Handshake if (!connection.getKey().equals(key)) { // received cer by other connection logger.debug("CER received by other connection [{}]", key); switch(fsm.getState(PeerState.class)) { case DOWN: resultCode = ResultCode.SUCCESS; break; case INITIAL: boolean isLocalWin = false; if (isElection) { try { // ammendonca: can't understand why it checks for <= 0 ... using equals //isLocalWin = metaData.getLocalPeer().getUri().getFQDN().compareTo( // message.getAvps().getAvp(Avp.ORIGIN_HOST).getOctetString()) <= 0; isLocalWin = metaData.getLocalPeer().getUri().getFQDN().equals( message.getAvps().getAvp(Avp.ORIGIN_HOST).getOctetString()); } catch (Exception exc) { isLocalWin = true; } } logger.debug("local peer is win - [{}]", isLocalWin); resultCode = 0; if (isLocalWin) { IConnection c = incConnections.get(key); c.remConnectionListener(connListener); c.disconnect(); incConnections.remove(key); } else { connection.disconnect(); // close current connection and work with other connection connection.remConnectionListener(connListener); connection = incConnections.remove(key); resultCode = ResultCode.SUCCESS; } break; } } else { if (logger.isDebugEnabled()) { logger.debug("CER received by current connection, key: [{}] PeerState: [{}] ", key, fsm.getState(PeerState.class)); } if (fsm.getState(PeerState.class).equals(INITIAL)) { // received cer by current connection resultCode = 0; // NOP } incConnections.remove(key); } if (resultCode == ResultCode.SUCCESS) { commonApplications.clear(); commonApplications.addAll(newAppId); fillIPAddressTable(message); } } catch (Exception exc) { logger.debug("Can not process CER", exc); } logger.debug("CER result [{}]", resultCode); return resultCode; } public boolean isRestoreConnection() { return isAttemptConnection; } public String getPeerDescription() { return PeerImpl.this.toString(); } public boolean receiveMessage(IMessage message) { logger.debug("Receiving message in server."); boolean isProcessed = false; if (message.isRequest()) { IRequest req = message; Avp destRealmAvp = req.getAvps().getAvp(Avp.DESTINATION_REALM); String destRealm = null; if (destRealmAvp == null) { // TODO: add that missing avp in "Failed-AVP" avp... sendErrorAnswer(message, "Missing Destination-Realm AVP", ResultCode.MISSING_AVP); return true; } else { try{ destRealm = destRealmAvp.getDiameterIdentity(); } catch (AvpDataException ade) { sendErrorAnswer(message, "Failed to parse Destination-Realm AVP", ResultCode.INVALID_AVP_VALUE, destRealmAvp); return true; } } IRealmTable realmTable = router.getRealmTable(); if (!realmTable.realmExists(destRealm)) { // send no such realm answer. logger.warn("Received a request for an unrecognized realm: [{}]. Answering with 3003 (DIAMETER_REALM_NOT_SERVED) Result-Code.", destRealm); sendErrorAnswer(message, null, ResultCode.REALM_NOT_SERVED); return true; } ApplicationId appId = message.getSingleApplicationId(); if (appId == null) { logger.warn("Receive a message with no Application Id. Answering with 5005 (MISSING_AVP) Result-Code."); sendErrorAnswer(message, "Missing Application-Id", ResultCode.MISSING_AVP); // TODO: add Auth-Application-Id, Acc-Application-Id and Vendor-Specific-Application-Id, can be empty return true; } // check condition for local processing. Avp destHostAvp = req.getAvps().getAvp(Avp.DESTINATION_HOST); //messages for local stack: // - The Destination-Host AVP contains the local host's identity, // - The Destination-Host AVP is not present, the Destination-Realm AVP // contains a realm the server is configured to process locally, and // the Diameter application is locally supported, or //check conditions for immediate consumption. //this includes if (destHostAvp != null) { try{ String destHost = destHostAvp.getDiameterIdentity(); //FIXME: add check with DNS/names to check 127 vs localhost if (destHost.equals(metaData.getLocalPeer().getUri().getFQDN())) { // this is for handling possible REDIRECT, destRealm != local.realm LocalAction action = null; IRealm matched = null; matched = (IRealm) realmTable.matchRealm(req); if(matched != null) { action = matched.getLocalAction(); } else { // We don't support it locally, its not defined as remote, so send no such realm answer. sendErrorAnswer(message, null, ResultCode.APPLICATION_UNSUPPORTED); // or REALM_NOT_SERVED ? return true; } switch (action) { case LOCAL: // always call listener - this covers realms // configured as localy processed and // LocalPeer.realm isProcessed = consumeMessage(message); break; case PROXY: //TODO: change this its almost the same as above, make it sync, so no router code involved if(handleByAgent(message, isProcessed, req, matched)) { isProcessed = true; } break; case RELAY: // might be complicated, lets make it listener // now isProcessed = consumeMessage(message); //if its not redirected its break; case REDIRECT: //TODO: change this its almost the same as above, make it sync, so no router code involved if(handleByAgent(message, isProcessed, req, matched)) { isProcessed = true; } break; } } else { //NOTE: this check should be improved, it checks if there is connection to peer, otherwise we cant serve it. //possibly also match realm. IPeer p = (IPeer) peerTable.getPeer(destHost); if(p != null && p.hasValidConnection()) { isProcessed = consumeMessage(message); } else { // RFC 3588 // 6.1 // 4. If none of the above is successful, an answer is returned with the // Result-Code set to DIAMETER_UNABLE_TO_DELIVER, with the E-bit set. logger.warn("Received message for unknown peer [{}]. Answering with 3002 (UNABLE_TO_DELIVER) Result-Code.", destHost); sendErrorAnswer(req, "No connection to peer", ResultCode.UNABLE_TO_DELIVER); isProcessed = true; } } } catch (AvpDataException ade) { logger.warn("Received message with present but unparsable Destination-Host. Answering with 5004 (INVALID_AVP_VALUE) Result-Code."); sendErrorAnswer(message, "Failed to parse Destination-Host AVP", ResultCode.INVALID_AVP_VALUE, destHostAvp); return true; } } else { // we have to match realms :) this MUST include local realm LocalAction action = null; IRealm matched = null; matched = (IRealm) realmTable.matchRealm(req); if(matched != null) { action = matched.getLocalAction(); } else { // We don't support it locally, its not defined as remote, so send no such realm answer. sendErrorAnswer(message, null, ResultCode.APPLICATION_UNSUPPORTED); // or REALM_NOT_SERVED ? return true; } switch (action) { case LOCAL: // always call listener - this covers realms // configured as locally processed and LocalPeer.realm isProcessed = consumeMessage(message); break; case PROXY: //TODO: change this its almost the same as above, make it sync, so no router code involved if( handleByAgent(message, isProcessed, req, matched)) { isProcessed = true; } break; case RELAY: // might be complicated, lets make it listener // now isProcessed = consumeMessage(message); break; case REDIRECT: //TODO: change this its almost the same as above, make it sync, so no router code involved if(handleByAgent(message, isProcessed, req, matched)) { isProcessed = true; } break; } } } else { // answer, let client do its work isProcessed = super.receiveMessage(message); } return isProcessed; } /** * @param message * @param isProcessed * @param req * @param matched * @return */ private boolean handleByAgent(IMessage message, boolean isProcessed, IRequest req, IRealm matched) { if (ovrManager != null && ovrManager.isParenAppOverload(message.getSingleApplicationId())) { logger.debug("Request [{}] skipped, because server application is overloaded", message); sendErrorAnswer(message, "Overloaded", ResultCode.TOO_BUSY); return true; } else { try { router.registerRequestRouteInfo(message); IMessage answer = (IMessage)matched.getAgent().processRequest(req,matched); if (isDuplicateProtection && answer != null) { peerTable.saveToDuplicate(message.getDuplicationKey(), answer); } isProcessed = true; if(answer != null) { sendMessage(answer); } if (statistic.isEnabled()) { statistic.getRecordByName(IStatisticRecord.Counters.SysGenResponse.name()).inc(); } } catch (Exception exc) { // TODO: check this!! logger.warn("Error during processing message by " + matched.getAgent().getClass(), exc); sendErrorAnswer(message, "Unable to process", ResultCode.UNABLE_TO_COMPLY); return true; } } if (isProcessed) { // NOTE: done to inc stat which informs on net work request consumption :) if (statistic.isEnabled()) { statistic.getRecordByName(IStatisticRecord.Counters.NetGenRequest.name()).inc(); } } return isProcessed; } /** * @param message * @return */ private boolean consumeMessage(IMessage message) { // now its safe to call stupid client code.... logger.debug("In Server consumeMessage. Going to call parents class receiveMessage"); boolean isProcessed = super.receiveMessage(message); logger.debug("Did client PeerImpl process the message? [{}]", isProcessed); IMessage answer = null; // this will process if session exists. if (!isProcessed) { if (statistic.isEnabled()) { // Decrement what we have incremented in super.receiveMessage(message) since it wasn't processed statistic.getRecordByName(IStatisticRecord.Counters.NetGenRejectedRequest.name()).dec(); } NetworkReqListener listener = network.getListener(message); if (listener != null) { if (logger.isDebugEnabled()) { logger.debug("We have found an application that is a listener for this message. It is [{}]", listener.getClass().getName()); } if (isDuplicateProtection) { logger.debug("Checking if it's a duplicate, since duplicate protection is ENABLED."); answer = peerTable.isDuplicate(message); } if (answer != null) { logger.debug("This message was detected as being a duplicate"); answer.setProxiable(message.isProxiable()); answer.getAvps().removeAvp(Avp.PROXY_INFO); for (Avp avp : message.getAvps().getAvps(Avp.PROXY_INFO)) { answer.getAvps().addAvp(avp); } answer.setHopByHopIdentifier(message.getHopByHopIdentifier()); isProcessed = true; try{ sendMessage(answer); if (statistic.isEnabled()) { statistic.getRecordByName(IStatisticRecord.Counters.SysGenResponse.name()).inc(); } } catch (Exception e) { // TODO: check this!! logger.warn("Error during processing message by duplicate protection", e); sendErrorAnswer(message, "Unable to process", ResultCode.UNABLE_TO_COMPLY); return true; } } else { if (ovrManager != null && ovrManager.isParenAppOverload(message.getSingleApplicationId())) { logger.debug("Request [{}] skipped, because server application is overloaded", message); sendErrorAnswer(message, "Overloaded", ResultCode.TOO_BUSY); return true; } else { try { router.registerRequestRouteInfo(message); answer = (IMessage) listener.processRequest(message); if (isDuplicateProtection && answer != null) { peerTable.saveToDuplicate(message.getDuplicationKey(), answer); } isProcessed = true; if(isProcessed && answer != null) { sendMessage(answer); } if (statistic.isEnabled()) { statistic.getRecordByName(IStatisticRecord.Counters.AppGenResponse.name()).inc(); } } catch (Exception exc) { // TODO: check this!! logger.warn("Error during processing message by listener", exc); sendErrorAnswer(message, "Unable to process", ResultCode.UNABLE_TO_COMPLY); return true; } } } } else { // NOTE: no listener defined for messages apps, response with "bad peer" stuff. logger.warn("Received message for unsupported Application-Id [{}]", message.getSingleApplicationId()); sendErrorAnswer(message, "Unsupported Application-Id", ResultCode.APPLICATION_UNSUPPORTED); return true; } } if (isProcessed) { // NOTE: done to inc stat which informs on net work request consumption :)... if (statistic.isEnabled()) { statistic.getRecordByName(IStatisticRecord.Counters.NetGenRequest.name()).inc(); } } return isProcessed; } public String toString() { return new StringBuffer("LocalActionConext [isRestoreConnection()=").append(isRestoreConnection()).append(", getPeerDescription()=").append(getPeerDescription()).append(", isConnected()=").append(isConnected()).append(", LocalPeer=").append(metaData.getLocalPeer().getUri()).append(" ]").toString(); } } }
Java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, TeleStax Inc. and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package org.jdiameter.server.impl.io.sctp; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.jdiameter.api.AvpDataException; import org.jdiameter.api.Configuration; import org.jdiameter.api.InternalException; import org.jdiameter.api.OverloadException; import org.jdiameter.client.api.IMessage; import org.jdiameter.client.api.io.IConnection; import org.jdiameter.client.api.io.IConnectionListener; import org.jdiameter.client.api.io.TransportError; import org.jdiameter.client.api.io.TransportException; import org.jdiameter.client.api.parser.IMessageParser; import org.mobicents.protocols.api.Association; import org.mobicents.protocols.api.Management; import org.mobicents.protocols.api.Server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class SCTPServerConnection implements IConnection { private static Logger logger = LoggerFactory.getLogger(SCTPServerConnection.class); private final long createdTime; private SCTPTransportServer server; // FIXME : requires JDK6 : protected LinkedBlockingDeque<Event> buffer = new LinkedBlockingDeque<Event>(64); private LinkedBlockingQueue<Event> buffer = new LinkedBlockingQueue<Event>(64); private IMessageParser parser; private Lock lock = new ReentrantLock(); private ConcurrentLinkedQueue<IConnectionListener> listeners = new ConcurrentLinkedQueue<IConnectionListener>(); // Cached value for connection key private String cachedKey = null; private NetworkGuard parentGuard; protected SCTPServerConnection(IMessageParser parser, NetworkGuard guard) { this.createdTime = System.currentTimeMillis(); this.parser = parser; this.parentGuard = guard; server = new SCTPTransportServer(this); } // this creates the listening server - no dest address is passed it is automatically 0.0.0.0:0 public SCTPServerConnection(Configuration config, InetAddress localAddress, int localPort, IMessageParser parser, String ref, NetworkGuard guard) throws Exception { this(parser, guard); logger.debug("SCTP Server constructor for listening server @ {}:{}", localAddress, localPort); server.setOrigAddress(new InetSocketAddress(localAddress, localPort)); server.startServer(); } // this creates the remote client connection public SCTPServerConnection(Configuration config, InetAddress remoteAddress, int remotePort, InetAddress localAddress, int localPort, IMessageParser parser, String ref, NetworkGuard guard, Server globalServer, Association association, Management management) throws Exception { this(parser, guard); logger.debug("SCTP Server constructor for remote client connections @ {}:{} <=> {}:{}", new Object[]{localAddress, localPort, remoteAddress, remotePort}); server.setOrigAddress(new InetSocketAddress(localAddress, localPort)); server.setDestAddress(new InetSocketAddress(remoteAddress, remotePort)); server.setManagement(management); server.startNewRemoteConnection(globalServer, association, remoteAddress.getHostAddress(), remotePort); } public long getCreatedTime() { return createdTime; } public void connect() throws TransportException { // NOP. Only for client. TODO: Consider remove from connection interface } public void disconnect() throws InternalError { logger.debug("Disconnecting SCTP Server Connection {}", this.getKey()); try { if (getServer() != null) { getServer().stop(); } } catch (Exception e) { throw new InternalError("Error while stopping transport: " + e.getMessage()); } } public Management getManagement() { return this.getServer().getManagement(); } public void destroy() throws InternalError { logger.debug("Destroying SCTP Server Connection {}", this.getKey()); try { if (getServer() != null) { getServer().destroy(); } } catch (Exception e) { throw new InternalError("Error while stopping transport: " + e.getMessage()); } } public void release() throws IOException { logger.debug("Releasing SCTP Server Connection {}", this.getKey()); try { if (getServer() != null) { getServer().release(); } } catch (Exception e) { throw new IOException(e.getMessage()); } finally { // parser = null; buffer.clear(); remAllConnectionListener(); } } public void onNewRemoteConnection(Server server, Association association) { this.getParentGuard().onNewRemoteConnection(server, association, this); } public NetworkGuard getParentGuard() { return parentGuard; } public void sendMessage(IMessage message) throws TransportException, OverloadException { try { if (getServer() != null) { getServer().sendMessage(parser.encodeMessage(message)); } } catch (Exception e) { throw new TransportException("Cannot send message: ", TransportError.FailedSendMessage, e); } } protected SCTPTransportServer getServer() { return server; } public boolean isNetworkInitiated() { return false; } public boolean isConnected() { return getServer() != null && getServer().isConnected(); } public InetAddress getRemoteAddress() { return getServer().getDestAddress().getAddress(); } public int getRemotePort() { if (getServer() == null) { logger.debug("server is null"); } else if (getServer().getDestAddress() == null) { logger.debug("dest address is null"); } else if (getServer().getDestAddress().getPort() == 0) { logger.debug("dest address port is 0"); } return getServer().getDestAddress().getPort(); } public void addConnectionListener(IConnectionListener listener) { lock.lock(); try { listeners.add(listener); if (buffer.size() != 0) { for (Event e : buffer) { try { onEvent(e); } catch (AvpDataException e1) { // ignore } } buffer.clear(); } } finally { lock.unlock(); } } public void remAllConnectionListener() { lock.lock(); try { listeners.clear(); } finally { lock.unlock(); } } public void remConnectionListener(IConnectionListener listener) { lock.lock(); try { listeners.remove(listener); } finally { lock.unlock(); } } public boolean isWrapperFor(Class<?> aClass) throws InternalException { return false; } public <T> T unwrap(Class<T> aClass) throws InternalException { return null; } public String getKey() { if (this.cachedKey == null) { this.cachedKey = new StringBuffer("aaa://").append(getRemoteAddress().getHostName()).append(":").append(getRemotePort()) .toString(); } return this.cachedKey; } protected void onDisconnect() throws AvpDataException { onEvent(new Event(EventType.DISCONNECTED)); } protected void onMessageReceived(ByteBuffer message) throws AvpDataException { if (logger.isDebugEnabled()) { logger.debug("Received message of size [{}]", message.array().length); } onEvent(new Event(EventType.MESSAGE_RECEIVED, message)); } protected void onAvpDataException(AvpDataException e) { try { onEvent(new Event(EventType.DATA_EXCEPTION, e)); } catch (AvpDataException e1) { // ignore } } protected void onConnected() { try { onEvent(new Event(EventType.CONNECTED)); } catch (AvpDataException e1) { // ignore } } protected void logDetails() throws AvpDataException { if(logger.isDebugEnabled()) { logger.debug("Listeners for {}", this.getKey()); for (IConnectionListener listener : listeners) { logger.debug("Listener [{}]", listener); } logger.debug("Event Queue for {}", this.getKey()); for (Event event : buffer) { logger.debug("Event [{}]", event); } } } protected void onEvent(Event event) throws AvpDataException { logger.debug("In onEvent for connection [{}]. Getting lock", this.getKey()); lock.lock(); logDetails(); try { // if (processBufferedMessages(event)) { for (IConnectionListener listener : listeners) { switch (event.type) { case CONNECTED: listener.connectionOpened(getKey()); break; case DISCONNECTED: listener.connectionClosed(getKey(), null); break; case MESSAGE_RECEIVED: listener.messageReceived(getKey(), parser.createMessage(event.message)); break; case DATA_EXCEPTION: listener.internalError(getKey(), null, new TransportException("Avp Data Exception:", TransportError.ReceivedBrokenMessage, event.exception)); break; } } // } } finally { lock.unlock(); } } // protected boolean processBufferedMessages(Event event) throws AvpDataException { // if (listeners.size() == 0) { // try { // buffer.add(event); // } catch (IllegalStateException e) { // // FIXME : requires JDK6 : buffer.removeLast(); // Event[] tempBuffer = buffer.toArray(new Event[buffer.size()]); // buffer.remove(tempBuffer[tempBuffer.length - 1]); // buffer.add(event); // } // return false; // } else { // return true; // } // } // ------------------ helper classes ------------------------ private static enum EventType { CONNECTED, DISCONNECTED, MESSAGE_RECEIVED, DATA_EXCEPTION } private static class Event { EventType type; ByteBuffer message; Exception exception; Event(EventType type) { this.type = type; } Event(EventType type, Exception exception) { this(type); this.exception = exception; } Event(EventType type, ByteBuffer message) { this(type); this.message = message; } } }
Java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, TeleStax Inc. and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package org.jdiameter.server.impl.io.sctp; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import org.jdiameter.api.AvpDataException; import org.jdiameter.client.api.io.NotInitializedException; import org.mobicents.protocols.api.Association; import org.mobicents.protocols.api.AssociationListener; import org.mobicents.protocols.api.IpChannelType; import org.mobicents.protocols.api.Management; import org.mobicents.protocols.api.PayloadData; import org.mobicents.protocols.api.Server; import org.mobicents.protocols.api.ServerListener; import org.mobicents.protocols.sctp.ManagementImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class SCTPTransportServer { private Management management = null; private Association serverAssociation = null; private Association remoteClientAssociation = null; private SCTPServerConnection parentConnection; private String serverAssociationName; private String remoteClientAssociationName; private String serverName; protected InetSocketAddress destAddress; protected InetSocketAddress origAddress; private Server server = null; private static final Logger logger = LoggerFactory.getLogger(SCTPTransportServer.class); private int payloadProtocolId = 0; private int streamNumber = 0; public SCTPTransportServer() { } /** * Default constructor * * @param parentConnectionConnection * connection created this transport */ SCTPTransportServer(SCTPServerConnection parentConnectionConnection) { this.parentConnection = parentConnectionConnection; } public SCTPServerConnection getParent() { return parentConnection; } public Management getManagement() { return management; } public void setManagement(Management management) { this.management = management; } public void startNewRemoteConnection(Server server, Association association, String peerAddress, int peerPort) { logger.debug("Initializing new Remote Connection '{}' -> '{}' ---> '{}:{}'", new Object[]{this.origAddress, this.destAddress, peerAddress, peerPort}); remoteClientAssociationName = peerAddress + ":" + peerPort; serverName = server.getName(); try { logger.debug("Adding new server association for [{}:{}]", peerAddress, peerPort); remoteClientAssociation = management.addServerAssociation(peerAddress, peerPort, serverName, remoteClientAssociationName, IpChannelType.SCTP); logger.debug("Setting new Association Listener"); remoteClientAssociation.setAssociationListener(new ServerAssociationListener()); logger.debug("Starting Association: {}", remoteClientAssociationName); management.startAssociation(remoteClientAssociationName); // ammendonca: this is managed, no need to do it manually now. // logger.debug("Setting association socket channel"); // remoteClientAssociation.setSocketChannel(socketChannel); // Accept the connection and make it non-blocking // socketChannel.configureBlocking(false); // Register the new SocketChannel with our Selector, // indicating we'd like to be notified when there's data // waiting to be read // logger.debug("registering socketchannel"); // SelectionKey key1 = socketChannel.register(selector, SelectionKey.OP_READ); // logger.debug("Attaching server association to key1"); // key1.attach(((Association) remoteClientAssociation)); logger.info(String.format("Connected to {}", remoteClientAssociation)); } catch (Exception e) { // ammendonca: this is managed, no need to do it manually now. // try { // socketChannel.close(); // } // catch (IOException ex) { // logger.error("Error closing channel: " + ex.getMessage()); // } logger.error("Failed to initialize new remote connection.", e); } } public void startServer() throws NotInitializedException { logger.debug("Initializing SCTP server"); try { if (this.management == null) { this.management = new ManagementImpl("server-management-" + origAddress.getAddress().getHostAddress() + "." + origAddress.getPort()); this.management.setSingleThread(true); this.management.start(); } logger.debug("Orig Address: '{}:{}'", origAddress.getAddress().getHostAddress(), origAddress.getPort()); logger.debug("Dest Address: '{}'", this.destAddress); serverAssociationName = origAddress.getHostName() + ":" + origAddress.getPort(); serverName = serverAssociationName; // Let's check if we already have the server configured for (Server s : management.getServers()) { if (s.getName().equals(serverName)) { server = s; break; } } // We don't have any, let's create it if (server == null) { server = this.management.addServer(serverName, origAddress.getAddress().getHostAddress(), origAddress.getPort(), IpChannelType.SCTP, true, 10, null); } for (String assocName : server.getAssociations()) { Association a = management.getAssociation(assocName); if (a.getName().equals(serverAssociationName)) { serverAssociation = a; break; } } if (serverAssociation == null) { serverAssociation = this.management.addServerAssociation(origAddress.getAddress().getHostAddress(), origAddress.getPort(), serverName, serverAssociationName, IpChannelType.SCTP); } this.management.setServerListener(new ServerEventListener()); serverAssociation.setAssociationListener(new ServerAssociationListener()); this.management.startAssociation(serverAssociationName); if (!server.isStarted()) { logger.debug("Starting server"); this.management.startServer(serverName); } } catch (Exception e) { logger.error("Failed to initialize client ", e); } if (getParent() == null) { throw new NotInitializedException("No parent connection is set is set"); } logger.debug("Successfuly initialized SCTP Server Host[{}:{}] Peer[{}:{}]", new Object[] { serverAssociation.getHostAddress(), serverAssociation.getHostPort(), serverAssociation.getPeerAddress(), serverAssociation.getPeerPort() }); logger.debug("Server Association Status: Started[{}] Connected[{}] Up[{}] ", new Object[]{serverAssociation.isStarted(), serverAssociation.isConnected(), serverAssociation.isUp()}); logger.trace("Server Association [{}]", serverAssociation); } private class ServerAssociationListener implements AssociationListener { private final Logger logger = LoggerFactory.getLogger(ServerAssociationListener.class); /* * (non-Javadoc) * * @see org.mobicents.protocols.api.AssociationListener#onCommunicationUp(org.mobicents.protocols.api.Association, int, int) */ @Override public void onCommunicationUp(Association association, int maxInboundStreams, int maxOutboundStreams) { logger.debug("onCommunicationUp called for [{}]", this); getParent().onConnected(); } /* * (non-Javadoc) * * @see org.mobicents.protocols.api.AssociationListener#onCommunicationShutdown(org.mobicents.protocols.api.Association) */ @Override public void onCommunicationShutdown(Association association) { logger.debug("onCommunicationShutdown called for [{}]", this); try { getParent().onDisconnect(); if (remoteClientAssociation != null) { management.stopAssociation(remoteClientAssociationName); management.removeAssociation(remoteClientAssociationName); remoteClientAssociation = null; } } catch (Exception e) { logger.debug("Error", e); } } /* * (non-Javadoc) * * @see org.mobicents.protocols.api.AssociationListener#onCommunicationLost(org.mobicents.protocols.api.Association) */ @Override public void onCommunicationLost(Association association) { logger.debug("onCommunicationLost called for [{}]", this); } /* * (non-Javadoc) * * @see org.mobicents.protocols.api.AssociationListener#onCommunicationRestart(org.mobicents.protocols.api.Association) */ @Override public void onCommunicationRestart(Association association) { logger.debug("onCommunicationRestart called for [{}]", this); } /* * (non-Javadoc) * * @see org.mobicents.protocols.api.AssociationListener#onPayload(org.mobicents.protocols.api.Association, * org.mobicents.protocols.api.PayloadData) */ @Override public void onPayload(Association association, PayloadData payloadData) { // set payload and stream number values; payloadProtocolId = payloadData.getPayloadProtocolId(); streamNumber = payloadData.getStreamNumber(); byte[] data = new byte[payloadData.getDataLength()]; System.arraycopy(payloadData.getData(), 0, data, 0, payloadData.getDataLength()); logger.debug("SCTP Server received a message of length: [{}] ", data.length); try { // make a message out of data and process it getParent().onMessageReceived(ByteBuffer.wrap(data)); } catch (AvpDataException e) { logger.debug("Garbage was received. Discarding."); // storage.clear(); getParent().onAvpDataException(e); } } /* * (non-Javadoc) * * @see org.mobicents.protocols.api.AssociationListener#inValidStreamId(org.mobicents.protocols.api.PayloadData) */ @Override public void inValidStreamId(PayloadData payloadData) { // NOP ? } } private class ServerEventListener implements ServerListener { private final Logger logger = LoggerFactory.getLogger(ServerEventListener.class); @Override public void onNewRemoteConnection(Server server, Association association) { logger.debug("Received notfification of a new remote connection!"); try { // notify network guard that new remote connection is done! getParent().onNewRemoteConnection(server, association); } catch (Exception e) { try { // ammendonca: changed. is it right ? // socketChannel.close(); association.stopAnonymousAssociation(); } catch (Exception ex) { logger.error("Error closing channel: " + ex.getMessage()); } } } } public void destroy() throws Exception { // Stop the SCTP logger.debug("Destroying SCTP Server"); if (remoteClientAssociation != null) { this.management.stopAssociation(remoteClientAssociationName); this.management.removeAssociation(remoteClientAssociationName); remoteClientAssociation = null; } if (serverAssociation != null) { this.management.stopAssociation(serverAssociationName); this.management.removeAssociation(serverAssociationName); this.management.stopServer(serverName); this.management.removeServer(serverName); this.management.stop(); serverAssociation = null; } } public void stop() throws Exception { logger.debug("Stopping SCTP Server"); // Note we never stop the server association as it is always listening - we only stop the remote client association if (remoteClientAssociation != null) { this.management.stopAssociation(remoteClientAssociationName); } } public void release() throws Exception { logger.debug("Releasing SCTP Server"); // Note we never release the server association as it is always listening - we only stop the remote client association this.stop(); if (remoteClientAssociation != null) { this.management.removeAssociation(remoteClientAssociationName); remoteClientAssociation = null; } // destAddress = null; } public InetSocketAddress getDestAddress() { return this.destAddress; } public void setDestAddress(InetSocketAddress address) { this.destAddress = address; if (logger.isDebugEnabled()) { logger.debug("Destination address is set to [{}:{}]", destAddress.getHostName(), destAddress.getPort()); } } public void setOrigAddress(InetSocketAddress address) { this.origAddress = address; if (logger.isDebugEnabled()) { logger.debug("Origin address is set to [{}:{}]", origAddress.getHostName(), origAddress.getPort()); } } public InetSocketAddress getOrigAddress() { return this.origAddress; } public void sendMessage(ByteBuffer bytes) throws IOException { if (logger.isDebugEnabled()) { logger.debug("About to send a byte buffer of size [{}] over the SCTP", bytes.array().length); } PayloadData payloadData = new PayloadData(bytes.array().length, bytes.array(), true, false, payloadProtocolId, streamNumber); try { this.remoteClientAssociation.send(payloadData); } catch (Exception e) { logger.error("Failed sending byte buffer over SCTP", e); } if (logger.isDebugEnabled()) { logger.debug("Sent a byte buffer of size [{}] over SCTP", bytes.array().length); } } boolean isConnected() { if (remoteClientAssociation == null) { return false; } return this.remoteClientAssociation.isConnected(); } }
Java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, TeleStax Inc. and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package org.jdiameter.server.impl.io.sctp; import java.net.InetAddress; import java.nio.channels.Selector; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.jdiameter.client.api.parser.IMessageParser; import org.jdiameter.common.api.concurrent.DummyConcurrentFactory; import org.jdiameter.common.api.concurrent.IConcurrentFactory; import org.jdiameter.server.api.IMetaData; import org.jdiameter.server.api.io.INetworkConnectionListener; import org.jdiameter.server.api.io.INetworkGuard; import org.mobicents.protocols.api.Association; import org.mobicents.protocols.api.Server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * SCTP implementation of {@link org.jdiameter.server.api.io.INetworkGuard}. * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class NetworkGuard implements INetworkGuard { private static final Logger logger = LoggerFactory.getLogger(NetworkGuard.class); protected IMessageParser parser; protected IConcurrentFactory concurrentFactory; protected int port; protected CopyOnWriteArrayList<INetworkConnectionListener> listeners = new CopyOnWriteArrayList<INetworkConnectionListener>(); protected boolean isWork = false; protected Selector selector; protected List<SCTPServerConnection> serverConnections; protected InetAddress[] localAddresses; @Deprecated public NetworkGuard(InetAddress inetAddress, int port, IMessageParser parser) throws Exception { this(inetAddress, port, null, parser, null); } public NetworkGuard(InetAddress inetAddress, int port, IConcurrentFactory concurrentFactory, IMessageParser parser, IMetaData data) throws Exception { this(new InetAddress[]{inetAddress}, port, concurrentFactory, parser, data); } public NetworkGuard(InetAddress[] inetAddresses, int port, IConcurrentFactory concurrentFactory, IMessageParser parser, IMetaData data) throws Exception { this.port = port; this.localAddresses = inetAddresses; this.parser = parser; this.concurrentFactory = concurrentFactory == null ? new DummyConcurrentFactory() : concurrentFactory; this.serverConnections = new ArrayList<SCTPServerConnection>(); try { for (InetAddress ia : inetAddresses) { final SCTPServerConnection sctpServerConnection = new SCTPServerConnection(null, ia, port, parser, null, this); this.serverConnections.add(sctpServerConnection); } } catch (Exception exc) { try{ destroy(); } catch(Exception e) { // ignore } throw new Exception(exc); } } public void run() { try { while (isWork) { Thread.sleep(10000); } } catch (Exception exc) { logger.warn("Server socket stopped", exc); } } public void addListener(INetworkConnectionListener listener) { if (!listeners.contains(listener)) { listeners.add(listener); } } public void remListener(INetworkConnectionListener listener) { listeners.remove(listener); } @Override public String toString() { return "NetworkGuard:" + (this.serverConnections.size() != 0 ? this.serverConnections : "closed"); } public void onNewRemoteConnection(Server globalServer, Association association, SCTPServerConnection connection) { logger.debug("New remote connection"); try { final String peerAddress = association.getPeerAddress(); final int peerPort = association.getPeerPort(); final String localAddress = association.getHostAddress(); final int localPort = association.getHostPort(); SCTPServerConnection remoteClientConnection = new SCTPServerConnection(null, InetAddress.getByName(peerAddress), peerPort, InetAddress.getByName(localAddress), localPort, parser, null, this, globalServer, association, connection.getManagement()); notifyListeners(remoteClientConnection); } catch (Exception exc) { logger.error("Error creating new remote connection"); } } public void destroy() { logger.debug("Destroying"); Iterator<SCTPServerConnection> it = this.serverConnections.iterator(); while (it.hasNext()) { try { SCTPServerConnection server = it.next(); it.remove(); if (server != null && server.isConnected()) { server.disconnect(); server.destroy(); } } catch (Exception e) { logger.error("", e); } } } private void notifyListeners(SCTPServerConnection server) { for (INetworkConnectionListener listener : this.listeners) { try { listener.newNetworkConnection(server); } catch (Exception e) { logger.debug("Connection listener threw exception!", e); } } } }
Java
/* * JBoss, Home of Professional Open Source. * Copyright 2012, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file 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.server.impl.io.tls; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.CopyOnWriteArrayList; import org.jdiameter.api.Configuration; import org.jdiameter.client.api.parser.IMessageParser; import org.jdiameter.client.impl.transport.tls.TLSClientConnection; import org.jdiameter.client.impl.transport.tls.TLSUtils; import org.jdiameter.common.api.concurrent.DummyConcurrentFactory; import org.jdiameter.common.api.concurrent.IConcurrentFactory; import org.jdiameter.server.api.IMetaData; import org.jdiameter.server.api.io.INetworkConnectionListener; import org.jdiameter.server.api.io.INetworkGuard; import org.jdiameter.server.impl.helpers.Parameters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * TLS implementation of {@link org.jdiameter.server.api.io.INetworkGuard}. * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public class NetworkGuard implements INetworkGuard, Runnable { private static final Logger logger = LoggerFactory.getLogger(NetworkGuard.class); private IMessageParser parser; private IConcurrentFactory concurrentFactory; private int port; private CopyOnWriteArrayList<INetworkConnectionListener> listeners = new CopyOnWriteArrayList<INetworkConnectionListener>(); private boolean isWork = false; // private SSLServerSocket serverSocket; private ServerSocket serverSocket; private Configuration localPeerSSLConfig; private Thread thread; private String secRef; public NetworkGuard(InetAddress inetAddress, int port, IConcurrentFactory concurrentFactory, IMessageParser parser, IMetaData data) throws Exception { this.port = port; this.parser = parser; this.concurrentFactory = concurrentFactory == null ? new DummyConcurrentFactory() : concurrentFactory; this.thread = this.concurrentFactory.getThread("NetworkGuard", this); // extract sec_ref from local peer; Configuration conf = data.getConfiguration(); if (!conf.isAttributeExist(Parameters.SecurityRef.ordinal())) { throw new IllegalArgumentException("No security_ref attribute present in local peer!"); } String secRef = conf.getStringValue(Parameters.SecurityRef.ordinal(), ""); // now need to get proper security data. this.localPeerSSLConfig = TLSUtils.getSSLConfiguration(conf, secRef); if (this.localPeerSSLConfig == null) { throw new IllegalArgumentException("No Security for security_reference '" + secRef + "'"); } // SSLContext sslContext = TLSUtils.getSecureContext(localPeerSSLConfig); try { // SSLServerSocketFactory sslServerSocketFactory = sslContext.getServerSocketFactory(); // this.serverSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(); this.serverSocket = new ServerSocket(); this.serverSocket.bind(new InetSocketAddress(inetAddress, port)); this.isWork = true; logger.info("Open server socket {} ", serverSocket); this.thread.start(); } catch (Exception exc) { destroy(); throw new Exception(exc); } } @Override public void run() { try { while (this.isWork) { // without timeout when we kill socket, this causes errors, bug in VM ? try { Socket clientConnection = serverSocket.accept(); logger.info("Open incomming SSL connection {}", clientConnection); TLSClientConnection client = new TLSClientConnection(null, this.localPeerSSLConfig, this.concurrentFactory, clientConnection, parser); this.notifyListeners(client); } catch (Exception e) { logger.debug("Failed to accept connection,", e); } } } catch (Exception exc) { logger.warn("Server socket stopped", exc); } } /* * (non-Javadoc) * * @see org.jdiameter.server.api.io.INetworkGuard#addListener(org.jdiameter.server .api.io.INetworkConnectionListener) */ @Override public void addListener(INetworkConnectionListener listener) { if (!this.listeners.contains(listener)) { this.listeners.add(listener); } } /* * (non-Javadoc) * * @see org.jdiameter.server.api.io.INetworkGuard#remListener(org.jdiameter.server .api.io.INetworkConnectionListener) */ @Override public void remListener(INetworkConnectionListener listener) { this.listeners.remove(listener); } /* * (non-Javadoc) * * @see org.jdiameter.server.api.io.INetworkGuard#destroy() */ @Override public void destroy() { try { this.isWork = false; try { if (this.thread != null) { this.thread.join(2000); if (this.thread.isAlive()) { // FIXME: remove ASAP this.thread.interrupt(); } thread = null; } } catch (InterruptedException e) { logger.debug("Can not stop thread", e); } if (this.serverSocket != null) { this.serverSocket.close(); this.serverSocket = null; } } catch (IOException e) { logger.error("", e); } } // ------------------------- private section --------------------------- private void notifyListeners(TLSClientConnection client) { for (INetworkConnectionListener listener : this.listeners) { try { listener.newNetworkConnection(client); } catch (Exception e) { logger.debug("Connection listener threw exception!", e); } } } }
Java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, TeleStax Inc. and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * * This file incorporates work covered by the following copyright and * permission notice: * * JBoss, Home of Professional Open Source * Copyright 2007-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.server.impl.io.tcp; import static org.jdiameter.server.impl.helpers.Parameters.BindDelay; import org.jdiameter.client.api.parser.IMessageParser; import org.jdiameter.client.impl.transport.tcp.TCPClientConnection; import org.jdiameter.common.api.concurrent.DummyConcurrentFactory; import org.jdiameter.common.api.concurrent.IConcurrentFactory; import org.jdiameter.server.api.IMetaData; import org.jdiameter.server.api.io.INetworkConnectionListener; import org.jdiameter.server.api.io.INetworkGuard; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * TCP implementation of {@link org.jdiameter.server.api.io.INetworkGuard}. * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class NetworkGuard implements INetworkGuard { private static final Logger logger = LoggerFactory.getLogger(NetworkGuard.class); protected IMessageParser parser; protected IConcurrentFactory concurrentFactory; protected int port; protected long bindDelay; protected CopyOnWriteArrayList<INetworkConnectionListener> listeners = new CopyOnWriteArrayList<INetworkConnectionListener>(); protected boolean isWork = false; // protected Selector selector; // protected ServerSocket serverSocket; //private Thread thread; private List<GuardTask> tasks = new ArrayList<GuardTask>(); @Deprecated public NetworkGuard(InetAddress inetAddress, int port, IMessageParser parser) throws Exception { this(inetAddress, port, null, parser, null); } public NetworkGuard(InetAddress inetAddress, int port, IConcurrentFactory concurrentFactory, IMessageParser parser, IMetaData data) throws Exception { this(new InetAddress[]{inetAddress}, port, concurrentFactory, parser, data); } public NetworkGuard(InetAddress[] inetAddress, int port, IConcurrentFactory concurrentFactory, IMessageParser parser, IMetaData data) throws Exception { this.port = port; this.parser = parser; this.concurrentFactory = concurrentFactory == null ? new DummyConcurrentFactory() : concurrentFactory; //this.thread = this.concurrentFactory.getThread("NetworkGuard", this); this.bindDelay = data.getConfiguration().getLongValue(BindDelay.ordinal(), (Long) BindDelay.defValue()); try { for (int addrIdx = 0; addrIdx < inetAddress.length; addrIdx++) { GuardTask guardTask = new GuardTask(new InetSocketAddress(inetAddress[addrIdx], port)); Thread t = this.concurrentFactory.getThread(guardTask); guardTask.thread = t; tasks.add(guardTask); } isWork = true; for (GuardTask gt : this.tasks) { gt.start(); } //thread.start(); } catch (Exception exc) { destroy(); throw new Exception(exc); } } public void addListener(INetworkConnectionListener listener) { if (!listeners.contains(listener)) { listeners.add(listener); } } public void remListener(INetworkConnectionListener listener) { listeners.remove(listener); } @Override public String toString() { return "NetworkGuard:" + (this.tasks.size() != 0 ? this.tasks : "closed"); } public void destroy() { isWork = false; Iterator<GuardTask> it = this.tasks.iterator(); while(it.hasNext()){ GuardTask gt = it.next(); it.remove(); gt.cleanTask(); } } private class GuardTask implements Runnable { private Thread thread; private Selector selector; private ServerSocket serverSocket; private final ScheduledExecutorService binder = Executors.newSingleThreadScheduledExecutor(); public GuardTask(final InetSocketAddress addr) throws IOException { if(bindDelay > 0) { logger.info("Socket binding will be delayed by {}ms...", bindDelay); } Runnable task = new Runnable() { public void run() { try { logger.debug("Binding {} after delaying {}ms...", addr, bindDelay); final ServerSocketChannel ssc = ServerSocketChannel.open(); ssc.configureBlocking(false); serverSocket = ssc.socket(); serverSocket.bind(addr); selector = Selector.open(); ssc.register(selector, SelectionKey.OP_ACCEPT, addr); logger.info("Open server socket {} ", serverSocket); } catch (IOException e) { throw new RuntimeException(e); } } }; binder.schedule(task, bindDelay, TimeUnit.MILLISECONDS); } public void start() { this.thread.start(); } public void run() { try { while (isWork) { if (selector == null) { logger.trace("Selector is still null, stack is waiting for binding..."); Thread.sleep(250); continue; } // without timeout when we kill socket, this causes errors, bug in VM ? int num = selector.select(100); if (num == 0) continue; Set<SelectionKey> keys = selector.selectedKeys(); try { for (SelectionKey key : keys) { if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) { try { Socket s = serverSocket.accept(); logger.info("Open incomming connection {}", s); TCPClientConnection client = new TCPClientConnection(null, concurrentFactory, s, parser, null); // PCB added logging logger.debug("Finished initialising TCPClientConnection for {}", s); for (INetworkConnectionListener listener : listeners) { listener.newNetworkConnection(client); } } catch (Exception e) { logger.warn("Can not create incoming connection", e); } } } } catch (Exception e) { logger.debug("Failed to accept connection,", e); } finally { keys.clear(); } } } catch (Exception exc) { logger.warn("Server socket stopped", exc); } } public void cleanTask() { try { if (thread != null) { thread.join(2000); if (thread.isAlive()) { // FIXME: remove ASAP thread.interrupt(); } thread = null; } } catch (InterruptedException e) { logger.debug("Can not stop thread", e); } if (selector != null) { try { selector.close(); } catch (Exception e) { // ignore } selector = null; } if (serverSocket != null) { try { serverSocket.close(); } catch (Exception e) { // ignore } serverSocket = null; } } @Override public String toString() { return "GuardTask [serverSocket=" + serverSocket + "]"; } } }
Java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, TeleStax Inc. and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * * This file incorporates work covered by the following copyright and * permission notice: * * JBoss, Home of Professional Open Source * Copyright 2007-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.server.impl.io; import static java.lang.Class.forName; import java.lang.reflect.Constructor; import java.net.InetAddress; import org.jdiameter.api.Configuration; import org.jdiameter.client.api.io.TransportError; import org.jdiameter.client.api.io.TransportException; import org.jdiameter.client.api.parser.IMessageParser; import org.jdiameter.client.impl.helpers.AppConfiguration; import org.jdiameter.common.api.concurrent.IConcurrentFactory; import org.jdiameter.server.api.IMetaData; import org.jdiameter.server.api.io.INetworkConnectionListener; import org.jdiameter.server.api.io.INetworkGuard; import org.jdiameter.server.api.io.ITransportLayerFactory; import org.jdiameter.server.impl.helpers.ExtensionPoint; import org.jdiameter.server.impl.helpers.Parameters; /** * * @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 TransportLayerFactory extends org.jdiameter.client.impl.transport.TransportLayerFactory implements ITransportLayerFactory { private final IConcurrentFactory concurrentFactory; private final IMetaData metaData; private Class<INetworkGuard> networkGuardClass; private Constructor<INetworkGuard> networkGuardConstructor; public TransportLayerFactory(Configuration conf, IConcurrentFactory concurrentFactory, IMessageParser parser, IMetaData metaData) throws TransportException { super(conf, parser); this.concurrentFactory = concurrentFactory; this.metaData = metaData; String networkGuardClassName = null; Configuration[] children = config.getChildren(Parameters.Extensions.ordinal()); // extract network guard class name. AppConfiguration internalExtensions = (AppConfiguration) children[ExtensionPoint.Internal.id()]; networkGuardClassName = internalExtensions.getStringValue(ExtensionPoint.InternalNetworkGuard.ordinal(), (String) ExtensionPoint.InternalNetworkGuard.defValue()); try { // TODO: this should be enough to check if class has interface!? this.networkGuardClass = (Class<INetworkGuard>) forName(networkGuardClassName); if (!INetworkGuard.class.isAssignableFrom(this.networkGuardClass)) throw new TransportException("Specified class does not inherit INetworkGuard interface " + this.networkGuardClass, TransportError.Internal); } catch (Exception e) { throw new TransportException("Cannot prepare specified guard class " + this.networkGuardClass, TransportError.Internal, e); } try { // TODO: this is bad practice, IConnection is interface and this code enforces constructor type to be present! networkGuardConstructor = this.networkGuardClass.getConstructor(InetAddress[].class, Integer.TYPE, IConcurrentFactory.class, IMessageParser.class, IMetaData.class); } catch (Exception e) { throw new TransportException("Cannot find required constructor", TransportError.Internal, e); } } public INetworkGuard createNetworkGuard(InetAddress inetAddress, int port) throws TransportException { try { return networkGuardConstructor.newInstance(inetAddress, port, this.concurrentFactory, this.parser, this.metaData); } catch (Exception e) { throw new TransportException(TransportError.NetWorkError, e); } } public INetworkGuard createNetworkGuard(InetAddress inetAddress, final int port, final INetworkConnectionListener listener) throws TransportException { INetworkGuard guard; try { guard = networkGuardConstructor.newInstance(inetAddress, port, this.concurrentFactory, this.parser, this.metaData); } catch (Exception e) { throw new TransportException(TransportError.NetWorkError, e); } guard.addListener(listener); return guard; } public INetworkGuard createNetworkGuard(InetAddress[] inetAddress, int port) throws TransportException { try { return networkGuardConstructor.newInstance(inetAddress, port, this.concurrentFactory, this.parser, this.metaData); } catch (Exception e) { throw new TransportException(TransportError.NetWorkError, e); } } public INetworkGuard createNetworkGuard(InetAddress[] inetAddress, int port, INetworkConnectionListener listener) throws TransportException { INetworkGuard guard; try { guard = networkGuardConstructor.newInstance(inetAddress, port, this.concurrentFactory, this.parser, this.metaData); } catch (Exception e) { throw new TransportException(TransportError.NetWorkError, e); } guard.addListener(listener); return guard; } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.api; import org.jdiameter.api.MutablePeerTable; import org.jdiameter.client.api.IMessage; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.client.api.controller.IPeerTable; /** * This interface describe extends methods of base class * * @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 interface IMutablePeerTable extends MutablePeerTable, IPeerTable { /** * Check message on duplicate * @param request checked message * @return true if messahe has duplicate into storage */ public IMessage isDuplicate(IMessage request); /** * Save message to duplicate storage * @param key key of message * @param answer message */ public void saveToDuplicate(String key, IMessage answer); /** * Return instance of session factory * @return instance of session factory */ ISessionFactory getSessionFactory(); }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.api; /** * This interface describe extends methods of base class * * @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 interface IStateMachine extends org.jdiameter.client.api.fsm.IStateMachine { }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.api; import org.jdiameter.api.Network; import org.jdiameter.api.NetworkReqListener; import org.jdiameter.client.api.IMessage; /** * This interface append to base interface some * special methods. * * @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 interface INetwork extends Network { /** * Return NetworkListener instance for specified application-id * @param message message * @return NetworkListener instance for specified selector * @see org.jdiameter.api.NetworkReqListener */ NetworkReqListener getListener(IMessage message); /** * This method set peer manager for addPeer/remPeer methods * @param manager PeerTable instance */ void setPeerManager(IMutablePeerTable manager); }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.api; import org.jdiameter.client.api.fsm.IContext; import org.jdiameter.client.api.io.IConnection; /** * This interface describe extends methods of base class * * @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 interface IPeer extends org.jdiameter.client.api.controller.IPeer { /** * Return true if peer must start reconnect procedure * * @return true if peer must start reconnect procedure */ boolean isAttemptConnection(); /** * Return action context * * @return action context */ IContext getContext(); /** * Return peer connection * * @return peer connection */ IConnection getConnection(); /** * Add new network connection (wait CER/CEA) * * @param conn new network connection */ void addIncomingConnection(IConnection conn); /** * Set result of election * * @param isElection result of election */ void setElection(boolean isElection); /** * Set overload manager * * @param ovrManager overload manager */ void notifyOvrManager(IOverloadManager ovrManager); }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.api; import org.jdiameter.api.ApplicationId; /** * This interface describe extends methods of base class * * @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 interface IMetaData extends org.jdiameter.client.api.IMetaData { /** * Add new Application Id to support application list * @param applicationId applicationId */ public void addApplicationId(ApplicationId applicationId); /** * Remove Application id from support application list * @param applicationId applicationId */ public void remApplicationId(ApplicationId applicationId); /** * @deprecated * Reload parameters */ public void reload(); }
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.server.api.agent; import org.jdiameter.server.api.agent.IAgent; /** * * @author babass */ public interface IProxy extends IAgent { }
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.server.api.agent; import java.io.Serializable; import java.util.Properties; import org.jdiameter.api.Configuration; import org.jdiameter.api.InternalException; /** * Interface through which agent can access configuration options for realm. * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public interface IAgentConfiguration extends Serializable { public Properties getProperties(); /** * Parse resource and return implementation. May return null if pased argument is null. * @param agentConfiguration * @return * @throws InternalException */ public IAgentConfiguration parse(String agentConfiguration) throws InternalException; /** * @param agentConfiguration * @return */ public IAgentConfiguration parse(Configuration agentConfiguration) throws InternalException; }
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.server.api.agent; /** * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public interface IRedirect extends IAgent { /** * Default property name for redirect host usage. */ public static final String RHU_PROPERTY = "rdr.host.usage"; public static final int RHU_DONT_CACHE = 0; public static final int RHU_ALL_SESSION = 1; public static final int RHU_ALL_REALM = 2; public static final int RHU_REALM_AND_APPLICATION = 3; public static final int RHU_ALL_APPLICATION = 4; public static final int RHU_ALL_HOST = 5; public static final int RHU_ALL_USER = 6; }
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.server.api.agent; import org.jdiameter.api.Answer; import org.jdiameter.api.EventListener; import org.jdiameter.api.Request; import org.jdiameter.client.api.IRequest; import org.jdiameter.client.api.controller.IRealm; /** * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public interface IAgent extends /*NetworkReqListener,*/ EventListener<Request, Answer> { /** * This method use for process new network requests. * @param request request message * @return answer immediate answer messsage. Method may return null and an * Answer will be sent later on */ Answer processRequest(IRequest request, IRealm matchedRealm); //realm should be matched for all agents iirc, soooo :) }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.api; import org.jdiameter.api.Configuration; import org.jdiameter.api.InternalException; import org.jdiameter.client.api.fsm.IContext; import org.jdiameter.common.api.concurrent.IConcurrentFactory; /** * Peer FSM factory * * @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 interface IFsmFactory extends org.jdiameter.client.api.fsm.IFsmFactory { // todo move to common api IStateMachine createInstanceFsm(IContext context, IConcurrentFactory concurrentFactory, Configuration config) throws InternalException; }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.api; /** * This interface describe extends methods of base class * * @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 interface IRouter extends org.jdiameter.client.api.router.IRouter{ }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.api; import org.jdiameter.api.ApplicationId; import org.jdiameter.api.OverloadManager; import org.jdiameter.api.URI; /** * This interface describe extends methods of base class * * @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 interface IOverloadManager extends OverloadManager { /** * Return true if application has overload * @param appId application id * @return true if application has overload */ public boolean isParenAppOverload(final ApplicationId appId); /** * eturn true if application has overload by predefined type * @param appId application id * @param type type of overload (CPU, Memory... ) * @return true if application has overload */ public boolean isParenAppOverload(final ApplicationId appId, int type); /** * Notification about overload * @param index overload entry index * @param uri peer uri * @param value overload value */ public void changeNotification(int index, URI uri, double value); }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.api.io; import org.jdiameter.client.api.io.IConnection; /** * This interface allow notifies consumers about created connections * * @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 interface INetworkConnectionListener { /** * Invoked when an new connection created. * * @param connection created connections */ public void newNetworkConnection(IConnection connection); }
Java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, TeleStax Inc. and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * * This file incorporates work covered by the following copyright and * permission notice: * * JBoss, Home of Professional Open Source * Copyright 2007-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.server.api.io; import org.jdiameter.client.api.io.TransportException; import java.net.InetAddress; /** * Factory of Network Layer elements. This interface append to parent interface * additional method for creating INetWorkGuard guard instances. * Additional parameters (Configuration, Parsers and etc) injection to instance over constructor * * @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 interface ITransportLayerFactory extends org.jdiameter.client.api.io.ITransportLayerFactory { /** * Create INetworkGuard instance with predefined parameters * * @param inetAddress address of server socket * @param port port of server socket * @return INetWorkGuard instance * @throws TransportException */ INetworkGuard createNetworkGuard(InetAddress inetAddress, int port) throws TransportException; /** * Create INetworkGuard instance with predefined parameters * * @param inetAddress address of server socket * @param port port of server socket * @param listener event listener * @return INetWorkGuard instance * @throws TransportException */ INetworkGuard createNetworkGuard(InetAddress inetAddress, int port, INetworkConnectionListener listener) throws TransportException; /** * Create INetworkGuard instance with predefined parameters * * @param inetAddress address of server socket * @param port port of server socket * @return INetWorkGuard instance * @throws TransportException */ INetworkGuard createNetworkGuard(InetAddress[] inetAddress, int port) throws TransportException; /** * Create INetworkGuard instance with predefined parameters * * @param inetAddress address of server socket * @param port port of server socket * @param listener event listener * @return INetWorkGuard instance * @throws TransportException */ INetworkGuard createNetworkGuard(InetAddress[] inetAddress, int port, INetworkConnectionListener listener) throws TransportException; }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.server.api.io; /** * This interface describe INetWorkConnectionListener consumer * * @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 interface INetworkGuard { /** * Append new listener * * @param listener listener instance */ public void addListener(INetworkConnectionListener listener); /** * Remove listener * * @param listener listener instance */ public void remListener(INetworkConnectionListener listener); /** * Release all attached resources (socket and etc) */ public void destroy(); }
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.common.impl.timer; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.Serializable; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.commons.pool.BasePoolableObjectFactory; import org.apache.commons.pool.impl.GenericObjectPool; import org.jdiameter.api.BaseSession; import org.jdiameter.client.api.IContainer; import org.jdiameter.common.api.concurrent.IConcurrentFactory; import org.jdiameter.common.api.data.ISessionDatasource; import org.jdiameter.common.api.timer.ITimerFacility; import org.jdiameter.common.impl.app.AppSessionImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Local implementation of timer facility for {@link ITimerFacility} * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public class LocalTimerFacilityImpl implements ITimerFacility { private static final Logger logger = LoggerFactory.getLogger(LocalTimerFacilityImpl.class); private ScheduledThreadPoolExecutor executor; private ISessionDatasource sessionDataSource; // TimerTaskHandle pooling to minimize impact on Eden space and avoid too // much GC, consequently not loosing time during GC private final GenericObjectPool pool = new GenericObjectPool(new TimerTaskHandleFactory(), 100000, GenericObjectPool.WHEN_EXHAUSTED_GROW, 10, 20000); public LocalTimerFacilityImpl(IContainer container) { super(); this.executor = (ScheduledThreadPoolExecutor) container.getConcurrentFactory().getScheduledExecutorService(IConcurrentFactory.ScheduledExecServices.ApplicationSession.name()); this.sessionDataSource = container.getAssemblerFacility().getComponentInstance(ISessionDatasource.class); } /* * (non-Javadoc) * * @see org.jdiameter.common.api.timer.ITimerFacility#cancel(java.io.Serializable) */ public void cancel(Serializable f) { if (f != null && f instanceof TimerTaskHandle) { TimerTaskHandle timerTaskHandle = (TimerTaskHandle) f; if (timerTaskHandle.future != null) { if (executor.remove((Runnable) timerTaskHandle.future)) { timerTaskHandle.future.cancel(false); returnTimerTaskHandle(timerTaskHandle); } } } } /* * (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 milliseconds) throws IllegalArgumentException { String id = sessionId + "/" + timerName; logger.debug("Scheduling timer with id [{}]", id); TimerTaskHandle ir = borrowTimerTaskHandle(); ir.id = id; ir.sessionId = sessionId; ir.timerName = timerName; ir.future = this.executor.schedule(ir, milliseconds, TimeUnit.MILLISECONDS); return ir; } protected void returnTimerTaskHandle(TimerTaskHandle timerTaskHandle) { try { pool.returnObject(timerTaskHandle); } catch (Exception e) { logger.warn(e.getMessage()); } } protected TimerTaskHandle borrowTimerTaskHandle() { try { TimerTaskHandle timerTaskHandle = (TimerTaskHandle) pool.borrowObject(); return timerTaskHandle; } catch (Exception e) { logger.error("", e); } return null; } class TimerTaskHandleFactory extends BasePoolableObjectFactory { @Override public Object makeObject() throws Exception { return new TimerTaskHandle(); } @Override public void passivateObject(Object obj) throws Exception { TimerTaskHandle timerTaskHandle = (TimerTaskHandle) obj; timerTaskHandle.id = null; timerTaskHandle.sessionId = null; timerTaskHandle.timerName = null; timerTaskHandle.future = null; } } private final class TimerTaskHandle implements Runnable, Externalizable { // its not really serializable; private String sessionId; private String timerName; private String id; //for debug, easier to check what's going on and what that timer does. private transient ScheduledFuture<?> future; public void run() { try { BaseSession bSession = sessionDataSource.getSession(sessionId); if (bSession == null || !bSession.isAppSession()) { // FIXME: error ? logger.error("Base Session is null for sessionId: {}", sessionId); return; } else { try { AppSessionImpl impl = (AppSessionImpl) bSession; impl.onTimer(timerName); } catch (Exception e) { logger.error("Caught exception from app session object!", e); } } } catch (Exception e) { logger.error("Failure executing timer task witb id: " + id, e); } finally { returnTimerTaskHandle(this); } } /* * (non-Javadoc) * * @see java.io.Externalizable#writeExternal(java.io.ObjectOutput) */ @Override public void writeExternal(ObjectOutput out) throws IOException { throw new IOException("Failed to serialize local timer!"); } /* * (non-Javadoc) * * @see java.io.Externalizable#readExternal(java.io.ObjectInput) */ @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { throw new IOException("Failed to deserialize local timer!"); } } }
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.common.impl.data; import java.util.HashMap; import java.util.concurrent.ConcurrentHashMap; import org.jdiameter.api.BaseSession; import org.jdiameter.api.NetworkReqListener; import org.jdiameter.client.api.IContainer; import org.jdiameter.client.api.ISession; import org.jdiameter.common.api.app.IAppSessionData; import org.jdiameter.common.api.app.IAppSessionDataFactory; 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.rf.IRfSessionData; import org.jdiameter.common.api.app.ro.IRoSessionData; import org.jdiameter.common.api.app.rx.IRxSessionData; import org.jdiameter.common.api.app.s6a.IS6aSessionData; import org.jdiameter.common.api.app.sh.IShSessionData; import org.jdiameter.common.api.data.ISessionDatasource; import org.jdiameter.common.impl.app.acc.AccLocalSessionDataFactory; import org.jdiameter.common.impl.app.auth.AuthLocalSessionDataFactory; import org.jdiameter.common.impl.app.cca.CCALocalSessionDataFactory; import org.jdiameter.common.impl.app.cxdx.CxDxLocalSessionDataFactory; import org.jdiameter.common.impl.app.gx.GxLocalSessionDataFactory; import org.jdiameter.common.impl.app.rf.RfLocalSessionDataFactory; import org.jdiameter.common.impl.app.ro.RoLocalSessionDataFactory; import org.jdiameter.common.impl.app.rx.RxLocalSessionDataFactory; import org.jdiameter.common.impl.app.s6a.S6aLocalSessionDataFactory; import org.jdiameter.common.impl.app.sh.ShLocalSessionDataFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Local implementation of session datasource for {@link ISessionDatasource} * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public class LocalDataSource implements ISessionDatasource { //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>>(); private ConcurrentHashMap<String, SessionEntry> sessionIdToEntry = new ConcurrentHashMap<String, LocalDataSource.SessionEntry>(); private static final Logger logger = LoggerFactory.getLogger(LocalDataSource.class); public LocalDataSource() { appSessionDataFactories.put(ICCASessionData.class, new CCALocalSessionDataFactory()); appSessionDataFactories.put(IRoSessionData.class, new RoLocalSessionDataFactory()); appSessionDataFactories.put(IRfSessionData.class, new RfLocalSessionDataFactory()); appSessionDataFactories.put(IGxSessionData.class, new GxLocalSessionDataFactory()); appSessionDataFactories.put(IAccSessionData.class, new AccLocalSessionDataFactory()); appSessionDataFactories.put(IAuthSessionData.class, new AuthLocalSessionDataFactory()); appSessionDataFactories.put(IShSessionData.class, new ShLocalSessionDataFactory()); appSessionDataFactories.put(ICxDxSessionData.class, new CxDxLocalSessionDataFactory()); appSessionDataFactories.put(IRxSessionData.class, new RxLocalSessionDataFactory()); appSessionDataFactories.put(IS6aSessionData.class, new S6aLocalSessionDataFactory()); } public LocalDataSource(IContainer container) { this(); } public boolean exists(String sessionId) { return this.sessionIdToEntry.containsKey(sessionId); } public void setSessionListener(String sessionId, NetworkReqListener data) { logger.debug("setSessionListener({}, {})", sessionId, data); SessionEntry se = sessionIdToEntry.get(sessionId); if(se != null) { se.listener = data; } else { throw new IllegalArgumentException("No Session entry for id: " + sessionId); } } public NetworkReqListener getSessionListener(String sessionId) { SessionEntry se = sessionIdToEntry.get(sessionId); logger.debug("getSessionListener({}) => {}", sessionId, se); return se != null ? se.listener : null; } public NetworkReqListener removeSessionListener(String sessionId) { SessionEntry se = sessionIdToEntry.get(sessionId); logger.debug("removeSessionListener({}) => {}", sessionId, se); if(se != null) { NetworkReqListener lst = se.listener; se.listener = null; return lst; } else { return null; } } public void addSession(BaseSession session) { logger.debug("addSession({})", session); SessionEntry se = null; String sessionId = session.getSessionId(); //FIXME: check here replicable vs not replicable? if(this.sessionIdToEntry.containsKey(sessionId)) { se = this.sessionIdToEntry.get(sessionId); if( !(se.session instanceof ISession) || se.session.isReplicable()) { //must be not replicable so we can "overwrite" throw new IllegalArgumentException("Sessin with id: "+sessionId+", already exists!"); } else { this.sessionIdToEntry.put(sessionId, se); } } else { se = new SessionEntry(); } se.session = session; this.sessionIdToEntry.put(session.getSessionId(), se); } public BaseSession getSession(String sessionId) { SessionEntry se = sessionIdToEntry.get(sessionId); logger.debug("getSession({}) => {}", sessionId, se); return se != null ? se.session : null; } public void removeSession(String sessionId) { SessionEntry se = this.sessionIdToEntry.remove(sessionId); logger.debug("removeSession({}) => {}", sessionId, se); } /* (non-Javadoc) * @see org.jdiameter.common.api.data.ISessionDatasource#start() */ public void start() { // NOP } /* (non-Javadoc) * @see org.jdiameter.common.api.data.ISessionDatasource#stop() */ public void stop() { // NOP } /* (non-Javadoc) * @see org.jdiameter.common.api.data.ISessionDatasource#isClustered() */ public boolean isClustered() { return false; } @Override public String toString() { return "LocalDataSource [sessionIdToEntry=" + sessionIdToEntry + "]"; } //simple class to reduce collections overhead. private class SessionEntry { BaseSession session; NetworkReqListener listener; @Override public String toString() { return "SessionEntry [session=" + session + ", listener=" + listener + "]"; } } /* * (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); } }
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.common.impl.app.sh; import org.jdiameter.api.Request; import org.jdiameter.api.sh.events.ProfileUpdateRequest; import org.jdiameter.common.impl.app.AppRequestEventImpl; /** * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class ProfileUpdateRequestImpl extends AppRequestEventImpl implements ProfileUpdateRequest { private static final long serialVersionUID = 1L; public ProfileUpdateRequestImpl(Request request) { super(request); } }
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.common.impl.app.sh; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.sh.ClientShSession; import org.jdiameter.api.sh.ServerShSession; import org.jdiameter.client.impl.app.sh.ShClientSessionDataLocalImpl; import org.jdiameter.common.api.app.IAppSessionDataFactory; import org.jdiameter.common.api.app.sh.IShSessionData; import org.jdiameter.server.impl.app.sh.ShServerSessionDataLocalImpl; /** * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public class ShLocalSessionDataFactory implements IAppSessionDataFactory<IShSessionData>{ /* (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)) { ShClientSessionDataLocalImpl data = new ShClientSessionDataLocalImpl(); data.setSessionId(sessionId); return data; } else if(clazz.equals(ServerShSession.class)) { ShServerSessionDataLocalImpl data = new ShServerSessionDataLocalImpl(); data.setSessionId(sessionId); return data; } throw new IllegalArgumentException(clazz.toString()); } }
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.common.impl.app.sh; import org.jdiameter.api.Answer; import org.jdiameter.api.Request; import org.jdiameter.api.sh.events.PushNotificationAnswer; import org.jdiameter.common.impl.app.AppAnswerEventImpl; /** * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class PushNotificationAnswerImpl extends AppAnswerEventImpl implements PushNotificationAnswer { private static final long serialVersionUID = 1L; /** * @param answer */ public PushNotificationAnswerImpl(Answer answer) { super(answer); } /** * @param request * @param vendorId * @param resultCode */ public PushNotificationAnswerImpl(Request request, long vendorId, long resultCode) { super(request, vendorId, resultCode); } /** * @param request * @param resultCode */ public PushNotificationAnswerImpl(Request request, long resultCode) { super(request, resultCode); } /** * @param request */ public PushNotificationAnswerImpl(Request request) { super(request); } }
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.common.impl.app.sh; import org.jdiameter.api.Answer; import org.jdiameter.api.Request; import org.jdiameter.api.sh.events.SubscribeNotificationsAnswer; import org.jdiameter.common.impl.app.AppAnswerEventImpl; /** * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class SubscribeNotificationsAnswerImpl extends AppAnswerEventImpl implements SubscribeNotificationsAnswer { private static final long serialVersionUID = 1L; /** * @param answer */ public SubscribeNotificationsAnswerImpl(Answer answer) { super(answer); } /** * @param request * @param vendorId * @param resultCode */ public SubscribeNotificationsAnswerImpl(Request request, long vendorId, long resultCode) { super(request, vendorId, resultCode); } /** * @param request * @param resultCode */ public SubscribeNotificationsAnswerImpl(Request request, long resultCode) { super(request, resultCode); } /** * @param request */ public SubscribeNotificationsAnswerImpl(Request request) { super(request); } }
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.common.impl.app.sh; import org.jdiameter.api.Request; import org.jdiameter.api.sh.events.PushNotificationRequest; import org.jdiameter.common.impl.app.AppRequestEventImpl; /** * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class PushNotificationRequestImpl extends AppRequestEventImpl implements PushNotificationRequest { private static final long serialVersionUID = 1L; public PushNotificationRequestImpl(Request request) { super(request); } }
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.common.impl.app.sh; import org.jdiameter.api.Request; import org.jdiameter.api.sh.events.SubscribeNotificationsRequest; import org.jdiameter.common.impl.app.AppRequestEventImpl; /** * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class SubscribeNotificationsRequestImpl extends AppRequestEventImpl implements SubscribeNotificationsRequest { private static final long serialVersionUID = 1L; public SubscribeNotificationsRequestImpl(Request request) { super(request); } }
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.common.impl.app.sh; import org.jdiameter.api.Request; import org.jdiameter.api.sh.events.UserDataRequest; import org.jdiameter.common.impl.app.AppRequestEventImpl; /** * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class UserDataRequestImpl extends AppRequestEventImpl implements UserDataRequest { private static final long serialVersionUID = 1L; public UserDataRequestImpl(Request request) { super(request); } }
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.common.impl.app.sh; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.jdiameter.api.NetworkReqListener; import org.jdiameter.api.app.StateChangeListener; import org.jdiameter.api.app.StateMachine; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.common.api.app.sh.IShSessionData; import org.jdiameter.common.impl.app.AppSessionImpl; /** * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public abstract class ShSession extends AppSessionImpl implements NetworkReqListener, StateMachine { protected Lock sendAndStateLock = new ReentrantLock(); protected transient List<StateChangeListener> stateListeners = new CopyOnWriteArrayList<StateChangeListener>(); public ShSession(ISessionFactory sf, IShSessionData data) { super(sf, data); } public void addStateChangeNotification(StateChangeListener listener) { if (!stateListeners.contains(listener)) { stateListeners.add(listener); } } public void removeStateChangeNotification(StateChangeListener listener) { stateListeners.remove(listener); } public void release() { //stateListeners.clear(); super.release(); } }
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.common.impl.app.sh; import org.jdiameter.api.Answer; import org.jdiameter.api.Request; import org.jdiameter.api.sh.events.ProfileUpdateAnswer; import org.jdiameter.common.impl.app.AppAnswerEventImpl; /** * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class ProfileUpdateAnswerImpl extends AppAnswerEventImpl implements ProfileUpdateAnswer { private static final long serialVersionUID = 1L; /** * @param answer */ public ProfileUpdateAnswerImpl(Answer answer) { super(answer); } /** * @param request * @param vendorId * @param resultCode */ public ProfileUpdateAnswerImpl(Request request, long vendorId, long resultCode) { super(request, vendorId, resultCode); } /** * @param request * @param resultCode */ public ProfileUpdateAnswerImpl(Request request, long resultCode) { super(request, resultCode); } /** * @param request */ public ProfileUpdateAnswerImpl(Request request) { super(request); } }
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.common.impl.app.sh; import org.jdiameter.api.Answer; import org.jdiameter.api.ApplicationId; 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.SessionFactory; import org.jdiameter.api.app.AppAnswerEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.app.StateChangeListener; import org.jdiameter.api.sh.ClientShSession; import org.jdiameter.api.sh.ClientShSessionListener; import org.jdiameter.api.sh.ServerShSession; import org.jdiameter.api.sh.ServerShSessionListener; import org.jdiameter.api.sh.events.ProfileUpdateAnswer; import org.jdiameter.api.sh.events.ProfileUpdateRequest; import org.jdiameter.api.sh.events.PushNotificationAnswer; import org.jdiameter.api.sh.events.PushNotificationRequest; import org.jdiameter.api.sh.events.SubscribeNotificationsAnswer; import org.jdiameter.api.sh.events.SubscribeNotificationsRequest; import org.jdiameter.api.sh.events.UserDataAnswer; import org.jdiameter.api.sh.events.UserDataRequest; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.client.impl.app.sh.IShClientSessionData; import org.jdiameter.client.impl.app.sh.ShClientSessionImpl; import org.jdiameter.common.api.app.IAppSessionDataFactory; import org.jdiameter.common.api.app.sh.IShMessageFactory; import org.jdiameter.common.api.app.sh.IShSessionData; import org.jdiameter.common.api.app.sh.IShSessionFactory; import org.jdiameter.common.api.data.ISessionDatasource; import org.jdiameter.server.impl.app.sh.IShServerSessionData; import org.jdiameter.server.impl.app.sh.ShServerSessionImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class ShSessionFactoryImpl implements IShSessionFactory, StateChangeListener<AppSession>, ClientShSessionListener, ServerShSessionListener, IShMessageFactory { protected Logger logger = LoggerFactory.getLogger(ShSessionFactoryImpl.class); // Listeners provided by developer ---------------------------------------- protected ClientShSessionListener clientShSessionListener; protected ServerShSessionListener serverShSessionListener; protected IShMessageFactory messageFactory; //not used. protected StateChangeListener<AppSession> stateChangeListener; // Our magic -------------------------------------------------------------- protected ISessionFactory sessionFactory; protected ISessionDatasource sessionDataSource; protected IAppSessionDataFactory<IShSessionData> sessionDataFactory; protected long messageTimeout = 10000; // 10s default timeout protected static final long applicationId = 16777217; public ShSessionFactoryImpl(SessionFactory sessionFactory) { super(); this.sessionFactory = (ISessionFactory) sessionFactory; this.sessionDataSource = this.sessionFactory.getContainer().getAssemblerFacility().getComponentInstance(ISessionDatasource.class); this.sessionDataFactory = (IAppSessionDataFactory<IShSessionData>) this.sessionDataSource.getDataFactory(IShSessionData.class); if(this.sessionDataFactory == null) { logger.debug("No factory for Sh Application data, using default/local."); this.sessionDataFactory = new ShLocalSessionDataFactory(); } } /** * @return the clientShSessionListener */ public ClientShSessionListener getClientShSessionListener() { if (this.clientShSessionListener == null) { return this; } else { return clientShSessionListener; } } /** * @param clientShSessionListener * the clientShSessionListener to set */ public void setClientShSessionListener(ClientShSessionListener clientShSessionListener) { this.clientShSessionListener = clientShSessionListener; } /** * @return the serverShSessionListener */ public ServerShSessionListener getServerShSessionListener() { if (this.serverShSessionListener == null) { return this; } else { return serverShSessionListener; } } /** * @param serverShSessionListener * the serverShSessionListener to set */ public void setServerShSessionListener(ServerShSessionListener serverShSessionListener) { this.serverShSessionListener = serverShSessionListener; } /** * @return the messageFactory */ public IShMessageFactory getMessageFactory() { if (this.messageFactory == null) { return this; } else { return messageFactory; } } /** * @param messageFactory * the messageFactory to set */ public void setMessageFactory(IShMessageFactory messageFactory) { this.messageFactory = messageFactory; } /** * @return the stateChangeListener */ public StateChangeListener<AppSession> getStateChangeListener() { return stateChangeListener; } /** * @param stateChangeListener * the stateChangeListener to set */ public void setStateChangeListener(StateChangeListener<AppSession> stateChangeListener) { this.stateChangeListener = stateChangeListener; } // IAppSession ------------------------------------------------------------ /* * (non-Javadoc) * * @see org.jdiameter.common.api.app.IAppSessionFactory#getNewSession(java.lang.String, java.lang.Class, * org.jdiameter.api.ApplicationId, java.lang.Object[]) */ public AppSession getNewSession(String sessionId, Class<? extends AppSession> aClass, ApplicationId applicationId, Object[] args) { try { // FIXME: add proper handling for SessionId if (aClass == ClientShSession.class) { ShClientSessionImpl clientSession = null; if (sessionId == null) { if (args != null && args.length > 0 && args[0] instanceof Request) { Request request = (Request) args[0]; sessionId = request.getSessionId(); } else { sessionId = this.sessionFactory.getSessionId(); } } IShClientSessionData sessionData = (IShClientSessionData) this.sessionDataFactory.getAppSessionData(ClientShSession.class, sessionId); sessionData.setApplicationId(applicationId); clientSession = new ShClientSessionImpl(sessionData, this.getMessageFactory(), sessionFactory, this.getClientShSessionListener()); sessionDataSource.addSession(clientSession); clientSession.getSessions().get(0).setRequestListener(clientSession); return clientSession; } else if (aClass == ServerShSession.class) { ShServerSessionImpl serverSession = null; if (sessionId == null) { if (args != null && args.length > 0 && args[0] instanceof Request) { Request request = (Request) args[0]; sessionId = request.getSessionId(); } else { sessionId = this.sessionFactory.getSessionId(); } } IShServerSessionData sessionData = (IShServerSessionData) this.sessionDataFactory.getAppSessionData(ServerShSession.class, sessionId); sessionData.setApplicationId(applicationId); serverSession = new ShServerSessionImpl(sessionData, this.getMessageFactory(), sessionFactory, getServerShSessionListener()); sessionDataSource.addSession(serverSession); serverSession.getSessions().get(0).setRequestListener(serverSession); return serverSession; } else { throw new IllegalArgumentException("Wrong session class: [" + aClass + "]. Supported[" + ClientShSession.class + "]"); } } catch (IllegalArgumentException iae) { throw iae; } catch (Exception e) { logger.error("Failure to obtain new Sh Session.", e); } return null; } @Override public AppSession getSession(String sessionId, Class<? extends AppSession> aClass) { if (sessionId == null) { throw new IllegalArgumentException("Session-Id must not be null"); } if(!this.sessionDataSource.exists(sessionId)) { return null; } AppSession appSession = null; try { if(aClass == ServerShSession.class) { IShServerSessionData sessionData = (IShServerSessionData) this.sessionDataFactory.getAppSessionData(ServerShSession.class, sessionId); appSession = new ShServerSessionImpl(sessionData, this.getMessageFactory(), sessionFactory, getServerShSessionListener()); appSession.getSessions().get(0).setRequestListener((NetworkReqListener) appSession); } else if (aClass == ClientShSession.class) { IShClientSessionData sessionData = (IShClientSessionData) this.sessionDataFactory.getAppSessionData(ClientShSession.class, sessionId); appSession = new ShClientSessionImpl(sessionData, this.getMessageFactory(), sessionFactory, this.getClientShSessionListener()); appSession.getSessions().get(0).setRequestListener((NetworkReqListener) appSession); } else { throw new IllegalArgumentException("Wrong session class: " + aClass + ". Supported[" + ServerShSession.class + "," + ClientShSession.class + "]"); } } catch (Exception e) { logger.error("Failure to obtain new Sh Session.", e); } return appSession; } // Methods to handle default values for user listeners -------------------- @SuppressWarnings("unchecked") public void stateChanged(Enum oldState, Enum newState) { logger.info("Diameter Sh SessionFactory :: stateChanged :: oldState[{}], newState[{}]", oldState, newState); } /* * (non-Javadoc) * * @see org.jdiameter.api.app.StateChangeListener#stateChanged(java.lang.Object, java.lang.Enum, java.lang.Enum) */ @SuppressWarnings("unchecked") public void stateChanged(AppSession source, Enum oldState, Enum newState) { logger.info("Diameter Sh SessionFactory :: stateChanged :: source[{}], oldState[{}], newState[{}]", new Object[] { source, oldState, newState }); } // Message Handlers ------------------------------------------------------- /* * (non-Javadoc) * * @see org.jdiameter.api.sh.ClientShSessionListener#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 { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see org.jdiameter.api.sh.ClientShSessionListener#doProfileUpdateAnswerEvent(org.jdiameter.api.sh.ClientShSession, * org.jdiameter.api.sh.events.ProfileUpdateRequest, org.jdiameter.api.sh.events.ProfileUpdateAnswer) */ public void doProfileUpdateAnswerEvent(ClientShSession session, ProfileUpdateRequest request, ProfileUpdateAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see org.jdiameter.api.sh.ClientShSessionListener#doPushNotificationRequestEvent( * org.jdiameter.api.sh.ClientShSession, org.jdiameter.api.sh.events.PushNotificationRequest) */ public void doPushNotificationRequestEvent(ClientShSession session, PushNotificationRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see org.jdiameter.api.sh.ClientShSessionListener#doSubscribeNotificationsAnswerEvent(org.jdiameter.api.sh.ClientShSession, * org.jdiameter.api.sh.events.SubscribeNotificationsRequest, org.jdiameter.api.sh.events.SubscribeNotificationsAnswer) */ public void doSubscribeNotificationsAnswerEvent(ClientShSession session, SubscribeNotificationsRequest request, SubscribeNotificationsAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see * org.jdiameter.api.sh.ClientShSessionListener#doUserDataAnswerEvent(org * .jdiameter.api.sh.ClientShSession, * org.jdiameter.api.sh.events.UserDataRequest, * org.jdiameter.api.sh.events.UserDataAnswer) */ public void doUserDataAnswerEvent(ClientShSession session, UserDataRequest request, UserDataAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see * org.jdiameter.api.sh.ServerShSessionListener#doProfileUpdateRequestEvent * (org.jdiameter.api.sh.ServerShSession, * org.jdiameter.api.sh.events.ProfileUpdateRequest) */ public void doProfileUpdateRequestEvent(ServerShSession session, ProfileUpdateRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see * org.jdiameter.api.sh.ServerShSessionListener#doPushNotificationAnswerEvent * (org.jdiameter.api.sh.ServerShSession, * org.jdiameter.api.sh.events.PushNotificationRequest, * org.jdiameter.api.sh.events.PushNotificationAnswer) */ public void doPushNotificationAnswerEvent(ServerShSession session, PushNotificationRequest request, PushNotificationAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @seeorg.jdiameter.api.sh.ServerShSessionListener# * doSubscribeNotificationsRequestEvent * (org.jdiameter.api.sh.ServerShSession, * org.jdiameter.api.sh.events.SubscribeNotificationsRequest) */ public void doSubscribeNotificationsRequestEvent(ServerShSession session, SubscribeNotificationsRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } /* * (non-Javadoc) * * @see * org.jdiameter.api.sh.ServerShSessionListener#doUserDataRequestEvent(org * .jdiameter.api.sh.ServerShSession, * org.jdiameter.api.sh.events.UserDataRequest) */ public void doUserDataRequestEvent(ServerShSession session, UserDataRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { // TODO Auto-generated method stub } // Message Factory ---------------------------------------------------------- public AppAnswerEvent createProfileUpdateAnswer(Answer answer) { return new ProfileUpdateAnswerImpl(answer); } public AppRequestEvent createProfileUpdateRequest(Request request) { return new ProfileUpdateRequestImpl(request); } public AppAnswerEvent createPushNotificationAnswer(Answer answer) { return new PushNotificationAnswerImpl(answer); } public AppRequestEvent createPushNotificationRequest(Request request) { return new PushNotificationRequestImpl(request); } public AppAnswerEvent createSubscribeNotificationsAnswer(Answer answer) { return new SubscribeNotificationsAnswerImpl(answer); } public AppRequestEvent createSubscribeNotificationsRequest(Request request) { return new SubscribeNotificationsRequestImpl(request); } public AppAnswerEvent createUserDataAnswer(Answer answer) { return new UserDataAnswerImpl(answer); } public AppRequestEvent createUserDataRequest(Request request) { return new UserDataRequestImpl(request); } public long getApplicationId() { return applicationId; } public long getMessageTimeout() { return messageTimeout; } }
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.common.impl.app.sh; import org.jdiameter.api.Answer; import org.jdiameter.api.Request; import org.jdiameter.api.sh.events.UserDataAnswer; import org.jdiameter.common.impl.app.AppAnswerEventImpl; /** * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class UserDataAnswerImpl extends AppAnswerEventImpl implements UserDataAnswer { private static final long serialVersionUID = 1L; /** * @param answer */ public UserDataAnswerImpl(Answer answer) { super(answer); } /** * @param request * @param vendorId * @param resultCode */ public UserDataAnswerImpl(Request request, long vendorId, long resultCode) { super(request, vendorId, resultCode); } /** * @param request * @param resultCode */ public UserDataAnswerImpl(Request request, long resultCode) { super(request, resultCode); } /** * @param request */ public UserDataAnswerImpl(Request request) { super(request); } }
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.common.impl.app.cca; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpDataException; import org.jdiameter.api.Request; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.cca.events.JCreditControlRequest; import org.jdiameter.common.impl.app.AppRequestEventImpl; 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 JCreditControlRequestImpl extends AppRequestEventImpl implements JCreditControlRequest { private static final long serialVersionUID = 1L; protected Logger logger = LoggerFactory.getLogger(JCreditControlRequestImpl.class); private static final int REQUESTED_ACTION_AVP_CODE = 436; private static final int CC_REQUEST_TYPE_AVP_CODE = 416; public JCreditControlRequestImpl(AppSession session, String destRealm, String destHost) { super(session.getSessions().get(0).createRequest(code, session.getSessionAppId(), destRealm, destHost)); } public JCreditControlRequestImpl(Request request) { super(request); } public boolean isRequestedActionAVPPresent() { return super.message.getAvps().getAvp(REQUESTED_ACTION_AVP_CODE) != null; } public int getRequestedActionAVPValue() { Avp requestedActionAvp = super.message.getAvps().getAvp(REQUESTED_ACTION_AVP_CODE); if(requestedActionAvp != null) { try { return requestedActionAvp.getInteger32(); } catch (AvpDataException e) { logger.debug("Failure trying to obtain Requested-Action AVP value", e); } } return -1; } public boolean isRequestTypeAVPPresent() { return super.message.getAvps().getAvp(CC_REQUEST_TYPE_AVP_CODE) != null; } public int getRequestTypeAVPValue() { Avp requestTypeAvp = super.message.getAvps().getAvp(CC_REQUEST_TYPE_AVP_CODE); if(requestTypeAvp != null) { try { return requestTypeAvp.getInteger32(); } catch (AvpDataException e) { logger.debug("Failure trying to obtain CC-Request-Type AVP value", e); } } return -1; } }
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.common.impl.app.cca; import java.util.concurrent.ScheduledFuture; import org.jdiameter.api.Answer; import org.jdiameter.api.ApplicationId; import org.jdiameter.api.InternalException; import org.jdiameter.api.Message; import org.jdiameter.api.Request; import org.jdiameter.api.SessionFactory; import org.jdiameter.api.app.AppAnswerEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.app.StateChangeListener; import org.jdiameter.api.auth.events.ReAuthAnswer; import org.jdiameter.api.auth.events.ReAuthRequest; import org.jdiameter.api.cca.ClientCCASession; import org.jdiameter.api.cca.ClientCCASessionListener; import org.jdiameter.api.cca.ServerCCASession; import org.jdiameter.api.cca.ServerCCASessionListener; import org.jdiameter.api.cca.events.JCreditControlAnswer; import org.jdiameter.api.cca.events.JCreditControlRequest; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.client.impl.app.cca.ClientCCASessionImpl; import org.jdiameter.client.impl.app.cca.IClientCCASessionData; import org.jdiameter.common.api.app.IAppSessionDataFactory; import org.jdiameter.common.api.app.cca.ICCAMessageFactory; import org.jdiameter.common.api.app.cca.ICCASessionData; import org.jdiameter.common.api.app.cca.ICCASessionFactory; import org.jdiameter.common.api.app.cca.IClientCCASessionContext; import org.jdiameter.common.api.app.cca.IServerCCASessionContext; import org.jdiameter.common.api.data.ISessionDatasource; import org.jdiameter.common.impl.app.auth.ReAuthAnswerImpl; import org.jdiameter.common.impl.app.auth.ReAuthRequestImpl; import org.jdiameter.server.impl.app.cca.IServerCCASessionData; import org.jdiameter.server.impl.app.cca.ServerCCASessionImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public class CCASessionFactoryImpl implements ICCASessionFactory, ClientCCASessionListener, ServerCCASessionListener, StateChangeListener<AppSession>, ICCAMessageFactory, IServerCCASessionContext, IClientCCASessionContext { // Message timeout value (in milliseconds) protected int defaultDirectDebitingFailureHandling = 0; protected int defaultCreditControlFailureHandling = 0; // its seconds protected long defaultValidityTime = 60; protected long defaultTxTimerValue = 30; // local not replicated listeners: protected ClientCCASessionListener clientSessionListener; protected ServerCCASessionListener serverSessionListener; protected StateChangeListener<AppSession> stateListener; protected IServerCCASessionContext serverContextListener; protected IClientCCASessionContext clientContextListener; protected ICCAMessageFactory messageFactory; protected Logger logger = LoggerFactory.getLogger(CCASessionFactoryImpl.class); protected ISessionDatasource iss; protected ISessionFactory sessionFactory = null; protected IAppSessionDataFactory<ICCASessionData> sessionDataFactory; public CCASessionFactoryImpl(){}; public CCASessionFactoryImpl(SessionFactory sessionFactory) { super(); init(sessionFactory); } /** * @param sessionFactory2 */ public void init(SessionFactory sessionFactory) { this.sessionFactory = (ISessionFactory) sessionFactory; this.iss = this.sessionFactory.getContainer().getAssemblerFacility().getComponentInstance(ISessionDatasource.class); this.sessionDataFactory = (IAppSessionDataFactory<ICCASessionData>) this.iss.getDataFactory(ICCASessionData.class); if(this.sessionDataFactory == null) { logger.debug("No factory for CCA Application data, using default/local."); this.sessionDataFactory = new CCALocalSessionDataFactory(); } } public CCASessionFactoryImpl(SessionFactory sessionFactory, int defaultDirectDebitingFailureHandling, int defaultCreditControlFailureHandling, long defaultValidityTime, long defaultTxTimerValue) { this(sessionFactory); this.defaultDirectDebitingFailureHandling = defaultDirectDebitingFailureHandling; this.defaultCreditControlFailureHandling = defaultCreditControlFailureHandling; this.defaultValidityTime = defaultValidityTime; this.defaultTxTimerValue = defaultTxTimerValue; } /** * @return the clientSessionListener */ public ClientCCASessionListener getClientSessionListener() { if (clientSessionListener != null) { return clientSessionListener; } else { return this; } } /** * @param clientSessionListener * the clientSessionListener to set */ public void setClientSessionListener(ClientCCASessionListener clientSessionListener) { this.clientSessionListener = clientSessionListener; } /** * @return the serverSessionListener */ public ServerCCASessionListener getServerSessionListener() { if (serverSessionListener != null) { return serverSessionListener; } else { return this; } } /** * @param serverSessionListener * the serverSessionListener to set */ public void setServerSessionListener(ServerCCASessionListener serverSessionListener) { this.serverSessionListener = serverSessionListener; } /** * @return the serverContextListener */ public IServerCCASessionContext getServerContextListener() { if (serverContextListener != null) { return serverContextListener; } else { return this; } } /** * @param serverContextListener * the serverContextListener to set */ public void setServerContextListener(IServerCCASessionContext serverContextListener) { this.serverContextListener = serverContextListener; } /** * @return the clientContextListener */ public IClientCCASessionContext getClientContextListener() { if (clientContextListener != null) { return clientContextListener; } else { return this; } } /** * @return the messageFactory */ public ICCAMessageFactory getMessageFactory() { if (messageFactory != null) { return messageFactory; } else { return this; } } /** * @param messageFactory * the messageFactory to set */ public void setMessageFactory(ICCAMessageFactory messageFactory) { this.messageFactory = messageFactory; } /** * @param clientContextListener * the clientContextListener to set */ public void setClientContextListener(IClientCCASessionContext clientContextListener) { this.clientContextListener = clientContextListener; } /** * @return the sessionFactory */ public SessionFactory getSessionFactory() { return sessionFactory; } /** * @param sessionFactory * the sessionFactory to set */ public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = (ISessionFactory) sessionFactory; } /** * @return the stateListener */ public StateChangeListener<AppSession> getStateListener() { if (this.stateListener != null) { return stateListener; } else { return this; } } /** * @param stateListener * the stateListener to set */ public void setStateListener(StateChangeListener<AppSession> stateListener) { this.stateListener = stateListener; } @Override public AppSession getSession(String sessionId, Class<? extends AppSession> aClass) { if (sessionId == null) { throw new IllegalArgumentException("SessionId must not be null"); } if(!this.iss.exists(sessionId)) { return null; } AppSession appSession = null; try { if (aClass == ClientCCASession.class) { ClientCCASessionImpl clientSession = null; IClientCCASessionData data = (IClientCCASessionData) this.sessionDataFactory.getAppSessionData(ClientCCASession.class, sessionId); clientSession = new ClientCCASessionImpl(data, this.getMessageFactory(), sessionFactory, this.getClientSessionListener(), this.getClientContextListener(), this.getStateListener()); clientSession.getSessions().get(0).setRequestListener(clientSession); appSession = clientSession; } else if (aClass == ServerCCASession.class) { ServerCCASessionImpl serverSession = null; IServerCCASessionData data = (IServerCCASessionData) this.sessionDataFactory.getAppSessionData(ServerCCASession.class, sessionId); serverSession = new ServerCCASessionImpl(data, this.getMessageFactory(), sessionFactory, this.getServerSessionListener(), this.getServerContextListener(), this.getStateListener()); serverSession.getSessions().get(0).setRequestListener(serverSession); appSession = serverSession; } else { throw new IllegalArgumentException("Wrong session class: " + aClass + ". Supported[" + ClientCCASession.class + "," + ServerCCASession.class + "]"); } } catch (Exception e) { logger.error("Failure to obtain new Credit-Control Session.", e); } return appSession; } @Override public AppSession getNewSession(String sessionId, Class<? extends AppSession> aClass, ApplicationId applicationId, Object[] args) { AppSession appSession = null; try { //TODO: add check to test if session exists. if (aClass == ClientCCASession.class) { ClientCCASessionImpl clientSession = null; if (sessionId == null) { if (args != null && args.length > 0 && args[0] instanceof Request) { Request request = (Request) args[0]; sessionId = request.getSessionId(); } else { sessionId = this.sessionFactory.getSessionId(); } } IClientCCASessionData data = (IClientCCASessionData) this.sessionDataFactory.getAppSessionData(ClientCCASession.class, sessionId); data.setApplicationId(applicationId); clientSession = new ClientCCASessionImpl(data, this.getMessageFactory(), sessionFactory, this.getClientSessionListener(), this.getClientContextListener(), this.getStateListener()); // this goes first! iss.addSession(clientSession); clientSession.getSessions().get(0).setRequestListener(clientSession); appSession = clientSession; } else if (aClass == ServerCCASession.class) { ServerCCASessionImpl serverSession = null; if (sessionId == null) { if (args != null && args.length > 0 && args[0] instanceof Request) { Request request = (Request) args[0]; sessionId = request.getSessionId(); } else { sessionId = this.sessionFactory.getSessionId(); } } IServerCCASessionData data = (IServerCCASessionData) this.sessionDataFactory.getAppSessionData(ServerCCASession.class, sessionId); data.setApplicationId(applicationId); serverSession = new ServerCCASessionImpl(data, this.getMessageFactory(), sessionFactory, this.getServerSessionListener(), this.getServerContextListener(), this.getStateListener()); iss.addSession(serverSession); serverSession.getSessions().get(0).setRequestListener(serverSession); appSession = serverSession; } else { throw new IllegalArgumentException("Wrong session class: " + aClass + ". Supported[" + ClientCCASession.class + "," + ServerCCASession.class + "]"); } } catch (Exception e) { logger.error("Failure to obtain new Credit-Control Session.", e); } return appSession; } // default implementation of methods so there are no exception! // ------------------------------------------------ // Message Handlers --------------------------------------------------------- public void doCreditControlRequest(ServerCCASession session, JCreditControlRequest request) throws InternalException { } public void doCreditControlAnswer(ClientCCASession session, JCreditControlRequest request, JCreditControlAnswer answer) throws InternalException { } public void doReAuthRequest(ClientCCASession session, ReAuthRequest request) throws InternalException { } public void doReAuthAnswer(ServerCCASession session, ReAuthRequest request, ReAuthAnswer answer) throws InternalException { } public void doOtherEvent(AppSession session, AppRequestEvent request, AppAnswerEvent answer) throws InternalException { } // Message Factory Methods -------------------------------------------------- public JCreditControlAnswer createCreditControlAnswer(Answer answer) { return new JCreditControlAnswerImpl(answer); } public JCreditControlRequest createCreditControlRequest(Request req) { return new JCreditControlRequestImpl(req); } public ReAuthAnswer createReAuthAnswer(Answer answer) { return new ReAuthAnswerImpl(answer); } public ReAuthRequest createReAuthRequest(Request req) { return new ReAuthRequestImpl(req); } // Context Methods ---------------------------------------------------------- public void stateChanged(Enum oldState, Enum newState) { logger.info("Diameter CCA SessionFactory :: stateChanged :: oldState[{}], newState[{}]", oldState, newState); } /* * (non-Javadoc) * * @see org.jdiameter.api.app.StateChangeListener#stateChanged(java.lang.Object, java.lang.Enum, java.lang.Enum) */ public void stateChanged(AppSession source, Enum oldState, Enum newState) { logger.info("Diameter CCA SessionFactory :: stateChanged :: source[{}], oldState[{}], newState[{}]", new Object[]{source, oldState, newState}); } // FIXME: add ctx methods proxy calls! public void sessionSupervisionTimerExpired(ServerCCASession session) { // this.resourceAdaptor.sessionDestroyed(session.getSessions().get(0).getSessionId(), session); session.release(); } public void sessionSupervisionTimerReStarted(ServerCCASession session, ScheduledFuture future) { // TODO Complete this method. } public void sessionSupervisionTimerStarted(ServerCCASession session, ScheduledFuture future) { // TODO Complete this method. } public void sessionSupervisionTimerStopped(ServerCCASession session, ScheduledFuture future) { // TODO Complete this method. } public void timeoutExpired(Request request) { // FIXME What should we do when there's a timeout? } public void denyAccessOnDeliverFailure(ClientCCASession clientCCASessionImpl, Message request) { // TODO Complete this method. } public void denyAccessOnFailureMessage(ClientCCASession clientCCASessionImpl) { // TODO Complete this method. } public void denyAccessOnTxExpire(ClientCCASession clientCCASessionImpl) { clientCCASessionImpl.release(); } public int getDefaultCCFHValue() { return defaultCreditControlFailureHandling; } public int getDefaultDDFHValue() { return defaultDirectDebitingFailureHandling; } public long getDefaultTxTimerValue() { return defaultTxTimerValue; } public void grantAccessOnDeliverFailure(ClientCCASession clientCCASessionImpl, Message request) { // TODO Auto-generated method stub } public void grantAccessOnFailureMessage(ClientCCASession clientCCASessionImpl) { // TODO Auto-generated method stub } public void grantAccessOnTxExpire(ClientCCASession clientCCASessionImpl) { // TODO Auto-generated method stub } public void indicateServiceError(ClientCCASession clientCCASessionImpl) { // TODO Auto-generated method stub } public void txTimerExpired(ClientCCASession session) { // this.resourceAdaptor.sessionDestroyed(session.getSessions().get(0).getSessionId(), session); session.release(); } public long[] getApplicationIds() { // FIXME: What should we do here? return new long[] { 4 }; } public long getDefaultValidityTime() { return this.defaultValidityTime; } }
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.common.impl.app.cca; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.cca.ClientCCASession; import org.jdiameter.api.cca.ServerCCASession; import org.jdiameter.client.impl.app.cca.ClientCCASessionDataLocalImpl; import org.jdiameter.common.api.app.IAppSessionDataFactory; import org.jdiameter.common.api.app.cca.ICCASessionData; import org.jdiameter.server.impl.app.cca.ServerCCASessionDataLocalImpl; /** * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public class CCALocalSessionDataFactory implements IAppSessionDataFactory<ICCASessionData>{ /* (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)) { ClientCCASessionDataLocalImpl data = new ClientCCASessionDataLocalImpl(); data.setSessionId(sessionId); return data; } else if(clazz.equals(ServerCCASession.class)) { ServerCCASessionDataLocalImpl data = new ServerCCASessionDataLocalImpl(); data.setSessionId(sessionId); return data; } throw new IllegalArgumentException(clazz.toString()); } }
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.common.impl.app.cca; import org.jdiameter.api.Answer; import org.jdiameter.api.Avp; import org.jdiameter.api.AvpDataException; import org.jdiameter.api.Request; import org.jdiameter.api.cca.events.JCreditControlAnswer; import org.jdiameter.common.impl.app.AppAnswerEventImpl; 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 JCreditControlAnswerImpl extends AppAnswerEventImpl implements JCreditControlAnswer { private static final long serialVersionUID = 1L; protected Logger logger = LoggerFactory.getLogger(JCreditControlAnswerImpl.class); private static final int CREDIT_CONTROL_FAILURE_HANDLING_AVP_CODE = 427; private static final int DIRECT_DEBITING_FAILURE_HANDLING_AVP_CODE = 428; private static final int REQUESTED_ACTION_AVP_CODE = 436; private static final int CC_REQUEST_TYPE_AVP_CODE = 416; private static final int VALIDITY_TIME_AVP_CODE = 448; /** * @param answer */ public JCreditControlAnswerImpl(Answer answer) { super(answer); } /** * @param request * @param vendorId * @param resultCode */ public JCreditControlAnswerImpl(Request request, long vendorId, long resultCode) { super(request, vendorId, resultCode); } /** * @param request * @param resultCode */ public JCreditControlAnswerImpl(Request request, long resultCode) { super(request, resultCode); } /** * @param request */ public JCreditControlAnswerImpl(Request request) { super(request); } public boolean isCreditControlFailureHandlingAVPPresent() { return super.message.getAvps().getAvp(CREDIT_CONTROL_FAILURE_HANDLING_AVP_CODE) != null; } public int getCredidControlFailureHandlingAVPValue() { Avp credidControlFailureHandlingAvp = super.message.getAvps().getAvp(CREDIT_CONTROL_FAILURE_HANDLING_AVP_CODE); if(credidControlFailureHandlingAvp != null) { try { return credidControlFailureHandlingAvp.getInteger32(); } catch (AvpDataException e) { logger.debug("Failure trying to obtain Credit-Control-Failure-Handling AVP value", e); } } return -1; } public boolean isDirectDebitingFailureHandlingAVPPresent() { return super.message.getAvps().getAvp(DIRECT_DEBITING_FAILURE_HANDLING_AVP_CODE) != null; } public int getDirectDebitingFailureHandlingAVPValue() { Avp directDebitingFailureHandlingAvp = super.message.getAvps().getAvp(DIRECT_DEBITING_FAILURE_HANDLING_AVP_CODE); if(directDebitingFailureHandlingAvp != null) { try { return directDebitingFailureHandlingAvp.getInteger32(); } catch (AvpDataException e) { logger.debug("Failure trying to obtain Direct-Debiting-Failure-Handling AVP value", e); } } return -1; } public Avp getValidityTimeAvp() { return super.message.getAvps().getAvp(VALIDITY_TIME_AVP_CODE); } public boolean isRequestTypeAVPPresent() { return super.message.getAvps().getAvp(CC_REQUEST_TYPE_AVP_CODE) != null; } public int getRequestTypeAVPValue() { Avp requestTypeAvp = super.message.getAvps().getAvp(CC_REQUEST_TYPE_AVP_CODE); if(requestTypeAvp != null) { try { return requestTypeAvp.getInteger32(); } catch (AvpDataException e) { logger.debug("Failure trying to obtain CC-Request-Type AVP value", e); } } return -1; } public boolean isRequestedActionAVPPresent() { return super.message.getAvps().getAvp(REQUESTED_ACTION_AVP_CODE) != null; } public int getRequestedActionAVPValue() { Avp requestedActionAvp = super.message.getAvps().getAvp(REQUESTED_ACTION_AVP_CODE); if(requestedActionAvp != null) { try { return requestedActionAvp.getInteger32(); } catch (AvpDataException e) { logger.debug("Failure trying to obtain Requested-Action AVP value", e); } } return -1; } }
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.common.impl.app.cca; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.jdiameter.api.NetworkReqListener; import org.jdiameter.api.app.StateChangeListener; import org.jdiameter.api.cca.CCASession; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.common.api.app.IAppSessionData; import org.jdiameter.common.impl.app.AppSessionImpl; /** * * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public abstract class AppCCASessionImpl extends AppSessionImpl implements CCASession,NetworkReqListener { protected Lock sendAndStateLock = new ReentrantLock(); //FIXME: those must be recreated from local resources! //FIXME: change this to single ref! //FIXME: use FastList ? protected List<StateChangeListener> stateListeners = new CopyOnWriteArrayList<StateChangeListener>(); public AppCCASessionImpl(ISessionFactory sf, IAppSessionData data) { super(sf, data); } public void addStateChangeNotification(StateChangeListener listener) { if (!stateListeners.contains(listener)) { stateListeners.add(listener); } } public void removeStateChangeNotification(StateChangeListener listener) { stateListeners.remove(listener); } public void release() { //stateListeners.clear(); super.release(); } }
Java
/* * JBoss, Home of Professional Open Source * Copyright 2006, 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.common.impl.app; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ScheduledExecutorService; import org.jdiameter.api.ApplicationId; import org.jdiameter.api.Session; import org.jdiameter.api.app.AppSession; import org.jdiameter.client.api.IAssembler; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.common.api.app.IAppSessionData; import org.jdiameter.common.api.concurrent.IConcurrentFactory; import org.jdiameter.common.api.timer.ITimerFacility; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Abstract implementation for {@link AppSession} * * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> * @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a> */ public abstract class AppSessionImpl implements AppSession { private static final Logger logger = LoggerFactory.getLogger(AppSessionImpl.class); protected IAppSessionData appSessionData; protected List<Session> sessions; protected Session session; protected ISessionFactory sf = null; protected ScheduledExecutorService scheduler = null; protected ITimerFacility timerFacility; public AppSessionImpl(ISessionFactory sf, IAppSessionData appSessionData) { if (sf == null) { throw new IllegalArgumentException("SessionFactory must not be null"); } if (appSessionData == null) { throw new IllegalArgumentException("IAppSessionData must not be null"); } try { this.sf = sf; this.appSessionData = appSessionData; IAssembler assembler = ( this.sf).getContainer().getAssemblerFacility(); this.scheduler = assembler.getComponentInstance(IConcurrentFactory.class).getScheduledExecutorService(IConcurrentFactory.ScheduledExecServices.ApplicationSession.name()); this.timerFacility = assembler.getComponentInstance(ITimerFacility.class); this.session = this.sf.getNewSession(this.appSessionData.getSessionId()); //annoying ;[ ArrayList<Session> list = new ArrayList<Session>(); list.add(this.session); this.sessions = Collections.unmodifiableList(list); } catch (Exception e) { throw new IllegalArgumentException(e); } } public long getCreationTime() { return session.getCreationTime(); } public long getLastAccessedTime() { return session.getLastAccessedTime(); } public boolean isValid() { return session == null ? false : session.isValid(); } public ApplicationId getSessionAppId() { return this.appSessionData.getApplicationId(); } public List<Session> getSessions() { return this.sessions; //.... } public void release() { logger.debug("Releasing application session for Session ID '{}' ({}).", getSessionId(), getSessionAppId()); this.session.setRequestListener(null); this.session.release(); this.appSessionData.remove(); } /* * (non-Javadoc) * * @see org.jdiameter.api.BaseSession#getSessionId() */ public String getSessionId() { //use local object, its faster :) return this.session.getSessionId(); } /* * (non-Javadoc) * * @see org.jdiameter.api.BaseSession#isAppSession() */ public boolean isAppSession() { return true; } /* * (non-Javadoc) * * @see org.jdiameter.api.BaseSession#isReplicable() */ public boolean isReplicable() { // FIXME: make this true? return false; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((appSessionData == null) ? 0 : appSessionData.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; AppSessionImpl other = (AppSessionImpl) obj; if (appSessionData == null) { if (other.appSessionData != null) return false; } else if (!appSessionData.equals(other.appSessionData)) return false; return true; } public abstract void onTimer(String timerName); }
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.common.impl.app.cxdx; import java.io.Serializable; import org.jdiameter.api.Request; import org.jdiameter.common.api.app.AppSessionDataLocalImpl; import org.jdiameter.common.api.app.cxdx.CxDxSessionState; 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 class CxDxLocalSessionDataImpl extends AppSessionDataLocalImpl implements ICxDxSessionData{ protected CxDxSessionState state = CxDxSessionState.IDLE; protected Request buffer; protected Serializable tsTimerId; /* (non-Javadoc) * @see org.jdiameter.common.api.app.cxdx.ICxDxSessionData#setCxDxSessionState(org.jdiameter.common.api.app.cxdx.CxDxSessionState) */ @Override public void setCxDxSessionState(CxDxSessionState state) { this.state = state; } /* (non-Javadoc) * @see org.jdiameter.common.api.app.cxdx.ICxDxSessionData#getCxDxSessionState() */ @Override public CxDxSessionState getCxDxSessionState() { return this.state; } /* (non-Javadoc) * @see org.jdiameter.common.api.app.cxdx.ICxDxSessionData#getTsTimerId() */ @Override public Serializable getTsTimerId() { return this.tsTimerId; } /* (non-Javadoc) * @see org.jdiameter.common.api.app.cxdx.ICxDxSessionData#setTsTimerId(java.io.Serializable) */ @Override public void setTsTimerId(Serializable tid) { this.tsTimerId = tid; } /* (non-Javadoc) * @see org.jdiameter.common.api.app.cxdx.ICxDxSessionData#setBuffer(org.jdiameter.api.Message) */ @Override public void setBuffer(Request buffer) { this.buffer = buffer; } /* (non-Javadoc) * @see org.jdiameter.common.api.app.cxdx.ICxDxSessionData#getBuffer() */ @Override public Request getBuffer() { return this.buffer; } }
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.common.impl.app.cxdx; import org.jdiameter.api.Answer; import org.jdiameter.api.ApplicationId; 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.SessionFactory; import org.jdiameter.api.acc.ClientAccSession; import org.jdiameter.api.acc.ServerAccSession; import org.jdiameter.api.app.AppAnswerEvent; import org.jdiameter.api.app.AppRequestEvent; import org.jdiameter.api.app.AppSession; import org.jdiameter.api.app.StateChangeListener; import org.jdiameter.api.cxdx.ClientCxDxSession; import org.jdiameter.api.cxdx.ClientCxDxSessionListener; import org.jdiameter.api.cxdx.ServerCxDxSession; import org.jdiameter.api.cxdx.ServerCxDxSessionListener; import org.jdiameter.api.cxdx.events.JLocationInfoAnswer; import org.jdiameter.api.cxdx.events.JLocationInfoRequest; import org.jdiameter.api.cxdx.events.JMultimediaAuthAnswer; import org.jdiameter.api.cxdx.events.JMultimediaAuthRequest; import org.jdiameter.api.cxdx.events.JPushProfileAnswer; import org.jdiameter.api.cxdx.events.JPushProfileRequest; import org.jdiameter.api.cxdx.events.JRegistrationTerminationAnswer; import org.jdiameter.api.cxdx.events.JRegistrationTerminationRequest; import org.jdiameter.api.cxdx.events.JServerAssignmentAnswer; import org.jdiameter.api.cxdx.events.JServerAssignmentRequest; import org.jdiameter.api.cxdx.events.JUserAuthorizationAnswer; import org.jdiameter.api.cxdx.events.JUserAuthorizationRequest; import org.jdiameter.client.api.ISessionFactory; import org.jdiameter.client.impl.app.cxdx.CxDxClientSessionImpl; import org.jdiameter.client.impl.app.cxdx.IClientCxDxSessionData; import org.jdiameter.common.api.app.IAppSessionDataFactory; import org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory; import org.jdiameter.common.api.app.cxdx.ICxDxSessionData; import org.jdiameter.common.api.app.cxdx.ICxDxSessionFactory; import org.jdiameter.common.api.data.ISessionDatasource; import org.jdiameter.server.impl.app.cxdx.CxDxServerSessionImpl; import org.jdiameter.server.impl.app.cxdx.IServerCxDxSessionData; 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 CxDxSessionFactoryImpl implements ICxDxSessionFactory, ClientCxDxSessionListener, ServerCxDxSessionListener, ICxDxMessageFactory, StateChangeListener<AppSession> { private static final Logger logger = LoggerFactory.getLogger(CxDxSessionFactoryImpl.class); protected ISessionFactory sessionFactory; protected ClientCxDxSessionListener clientSessionListener; protected ServerCxDxSessionListener serverSessionListener; protected ICxDxMessageFactory messageFactory; protected StateChangeListener<AppSession> stateListener; protected ISessionDatasource iss; protected IAppSessionDataFactory<ICxDxSessionData> sessionDataFactory; public CxDxSessionFactoryImpl(SessionFactory sessionFactory) { super(); this.sessionFactory = (ISessionFactory) sessionFactory; this.iss = this.sessionFactory.getContainer().getAssemblerFacility().getComponentInstance(ISessionDatasource.class); this.sessionDataFactory = (IAppSessionDataFactory<ICxDxSessionData>) this.iss.getDataFactory(ICxDxSessionData.class); } /** * @return the clientSessionListener */ public ClientCxDxSessionListener getClientSessionListener() { if (clientSessionListener != null) { return clientSessionListener; } else { return this; } } /** * @param clientSessionListener * the clientSessionListener to set */ public void setClientSessionListener(ClientCxDxSessionListener clientSessionListener) { this.clientSessionListener = clientSessionListener; } /** * @return the serverSessionListener */ public ServerCxDxSessionListener getServerSessionListener() { if (serverSessionListener != null) { return serverSessionListener; } else { return this; } } /** * @param serverSessionListener * the serverSessionListener to set */ public void setServerSessionListener(ServerCxDxSessionListener serverSessionListener) { this.serverSessionListener = serverSessionListener; } /** * @return the messageFactory */ public ICxDxMessageFactory getMessageFactory() { if (messageFactory != null) { return messageFactory; } else { return this; } } /** * @param messageFactory * the messageFactory to set */ public void setMessageFactory(ICxDxMessageFactory messageFactory) { this.messageFactory = messageFactory; } /** * @return the stateListener */ public StateChangeListener<AppSession> getStateListener() { if (stateListener != null) { return stateListener; } else { return this; } } /** * @param stateListener * the stateListener to set */ public void setStateListener(StateChangeListener<AppSession> stateListener) { this.stateListener = stateListener; } @Override public AppSession getSession(String sessionId, Class<? extends AppSession> aClass) { if (sessionId == null) { throw new IllegalArgumentException("SessionId must not be null"); } if (!this.iss.exists(sessionId)) { return null; } AppSession appSession = null; try { if (aClass == ClientCxDxSession.class) { IClientCxDxSessionData sessionData = (IClientCxDxSessionData) this.sessionDataFactory.getAppSessionData(ClientCxDxSession.class, sessionId); CxDxClientSessionImpl clientSession = new CxDxClientSessionImpl(sessionData, this.getMessageFactory(), this.sessionFactory, this.getClientSessionListener()); clientSession.getSessions().get(0).setRequestListener(clientSession); appSession = clientSession; } else if (aClass == ServerCxDxSession.class) { IServerCxDxSessionData sessionData = (IServerCxDxSessionData) this.sessionDataFactory.getAppSessionData(ServerCxDxSession.class, sessionId); CxDxServerSessionImpl serverSession = new CxDxServerSessionImpl(sessionData, getMessageFactory(), sessionFactory, this.getServerSessionListener()); serverSession.getSessions().get(0).setRequestListener(serverSession); appSession = serverSession; } else { throw new IllegalArgumentException("Wrong session class: " + aClass + ". Supported[" + ClientAccSession.class + "," + ServerAccSession.class + "]"); } } catch (Exception e) { logger.error("Failure to obtain new Cx/Dx Session.", e); } return appSession; } /* * (non-Javadoc) * * @see * org.jdiameter.common.api.app.IAppSessionFactory#getNewSession(java.lang * .String, java.lang.Class, org.jdiameter.api.ApplicationId, * java.lang.Object[]) */ public AppSession getNewSession(String sessionId, Class<? extends AppSession> aClass, ApplicationId applicationId, Object[] args) { AppSession appSession = null; if (aClass == ClientCxDxSession.class) { if (sessionId == null) { if (args != null && args.length > 0 && args[0] instanceof Request) { Request request = (Request) args[0]; sessionId = request.getSessionId(); } else { sessionId = this.sessionFactory.getSessionId(); } } IClientCxDxSessionData sessionData = (IClientCxDxSessionData) this.sessionDataFactory.getAppSessionData(ClientCxDxSession.class, sessionId); sessionData.setApplicationId(applicationId); CxDxClientSessionImpl clientSession = new CxDxClientSessionImpl(sessionData, this.getMessageFactory(), this.sessionFactory, this .getClientSessionListener()); iss.addSession(clientSession); clientSession.getSessions().get(0).setRequestListener(clientSession); appSession = clientSession; } else if (aClass == ServerCxDxSession.class) { if (sessionId == null) { if (args != null && args.length > 0 && args[0] instanceof Request) { Request request = (Request) args[0]; sessionId = request.getSessionId(); } else { sessionId = this.sessionFactory.getSessionId(); } } IServerCxDxSessionData sessionData = (IServerCxDxSessionData) this.sessionDataFactory.getAppSessionData(ServerCxDxSession.class, sessionId); sessionData.setApplicationId(applicationId); CxDxServerSessionImpl serverSession = new CxDxServerSessionImpl(sessionData, getMessageFactory(),sessionFactory, this.getServerSessionListener()); iss.addSession(serverSession); serverSession.getSessions().get(0).setRequestListener(serverSession); appSession = serverSession; } else { throw new IllegalArgumentException("Wrong session class: " + aClass + ". Supported[" + ServerCxDxSession.class + "," + ClientCxDxSession.class + "]"); } return appSession; } // Cx/Dx Message Factory Methods ------------------------------------------ /* * (non-Javadoc) * * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createLocationInfoAnswer(org.jdiameter.api.Answer) */ public JLocationInfoAnswer createLocationInfoAnswer(Answer answer) { return new JLocationInfoAnswerImpl(answer); } /* * (non-Javadoc) * * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createLocationInfoRequest(org.jdiameter.api.Request) */ public JLocationInfoRequest createLocationInfoRequest(Request request) { return new JLocationInfoRequestImpl(request); } /* * (non-Javadoc) * * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createMultimediaAuthAnswer(org.jdiameter.api.Answer) */ public JMultimediaAuthAnswer createMultimediaAuthAnswer(Answer answer) { return new JMultimediaAuthAnswerImpl(answer); } /* * (non-Javadoc) * * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createMultimediaAuthRequest(org.jdiameter.api.Request) */ public JMultimediaAuthRequest createMultimediaAuthRequest(Request request) { return new JMultimediaAuthRequestImpl(request); } /* * (non-Javadoc) * * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createPushProfileAnswer(org.jdiameter.api.Answer) */ public JPushProfileAnswer createPushProfileAnswer(Answer answer) { return new JPushProfileAnswerImpl(answer); } /* * (non-Javadoc) * * @seeorg.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createPushProfileRequest(org.jdiameter.api.Request) */ public JPushProfileRequest createPushProfileRequest(Request request) { return new JPushProfileRequestImpl(request); } /* * (non-Javadoc) * * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createRegistrationTerminationAnswer(org.jdiameter.api.Answer) */ public JRegistrationTerminationAnswer createRegistrationTerminationAnswer(Answer answer) { return new JRegistrationTerminationAnswerImpl(answer); } /* * (non-Javadoc) * * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createRegistrationTerminationRequest(org.jdiameter.api.Request) */ public JRegistrationTerminationRequest createRegistrationTerminationRequest(Request request) { return new JRegistrationTerminationRequestImpl(request); } /* * (non-Javadoc) * * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createServerAssignmentAnswer(org.jdiameter.api.Answer) */ public JServerAssignmentAnswer createServerAssignmentAnswer(Answer answer) { return new JServerAssignmentAnswerImpl(answer); } /* * (non-Javadoc) * * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createServerAssignmentRequest(org.jdiameter.api.Request) */ public JServerAssignmentRequest createServerAssignmentRequest(Request request) { return new JServerAssignmentRequestImpl(request); } /* * (non-Javadoc) * * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createUserAuthorizationAnswer(org.jdiameter.api.Answer) */ public JUserAuthorizationAnswer createUserAuthorizationAnswer(Answer answer) { return new JUserAuthorizationAnswerImpl(answer); } /* * (non-Javadoc) * * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#createUserAuthorizationRequest(org.jdiameter.api.Request) */ public JUserAuthorizationRequest createUserAuthorizationRequest(Request request) { return new JUserAuthorizationRequestImpl(request); } /* * (non-Javadoc) * * @see org.jdiameter.common.api.app.cxdx.ICxDxMessageFactory#getApplicationId() */ public long getApplicationId() { return 16777216; } // Session Listeners -------------------------------------------------------- /* * (non-Javadoc) * * @see org.jdiameter.api.cxdx.ServerCxDxSessionListener#doLocationInformationRequest( * org.jdiameter.api.cxdx.ServerCxDxSession, org.jdiameter.api.cxdx.events.JLocationInfoRequest) */ public void doLocationInformationRequest(ServerCxDxSession appSession, JLocationInfoRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { logger.info("Diameter Cx/Dx Session Factory :: doLocationInformationRequest :: appSession[{}], Request[{}]", appSession, request); } /* * (non-Javadoc) * * @see org.jdiameter.api.cxdx.ServerCxDxSessionListener#doMultimediaAuthRequest( * org.jdiameter.api.cxdx.ServerCxDxSession, org.jdiameter.api.cxdx.events.JMultimediaAuthRequest) */ public void doMultimediaAuthRequest(ServerCxDxSession appSession, JMultimediaAuthRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { logger.info("Diameter Cx/Dx Session Factory :: doMultimediaAuthRequest :: appSession[{}], Request[{}]", appSession, request); } /* * (non-Javadoc) * * @see org.jdiameter.api.cxdx.ServerCxDxSessionListener#doOtherEvent(org.jdiameter.api.app.AppSession, * org.jdiameter.api.app.AppRequestEvent, org.jdiameter.api.app.AppAnswerEvent) */ public void doOtherEvent(AppSession appSession, AppRequestEvent request, AppAnswerEvent answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { logger.info("Diameter Cx/Dx Session Factory :: doOtherEvent :: appSession[{}], Request[{}], Answer[{}]", new Object[]{appSession, request, answer}); } /* * (non-Javadoc) * * @see org.jdiameter.api.cxdx.ServerCxDxSessionListener#doPushProfileAnswer(org.jdiameter.api.cxdx.ServerCxDxSession, * org.jdiameter.api.cxdx.events.JPushProfileRequest, org.jdiameter.api.cxdx.events.JPushProfileAnswer) */ public void doPushProfileAnswer(ServerCxDxSession appSession, JPushProfileRequest request, JPushProfileAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { logger.info("Diameter Cx/Dx Session Factory :: doPushProfileAnswer :: appSession[{}], Request[{}], Answer[{}]", new Object[]{appSession, request, answer}); } /* * (non-Javadoc) * * @see org.jdiameter.api.cxdx.ServerCxDxSessionListener#doRegistrationTerminationAnswer(org.jdiameter.api.cxdx.ServerCxDxSession, * org.jdiameter.api.cxdx.events.JRegistrationTerminationRequest, org.jdiameter.api.cxdx.events.JRegistrationTerminationAnswer) */ public void doRegistrationTerminationAnswer(ServerCxDxSession appSession, JRegistrationTerminationRequest request, JRegistrationTerminationAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { logger.info("Diameter Cx/Dx Session Factory :: doRegistrationTerminationAnswer :: appSession[{}], Request[{}], Answer[{}]", new Object[]{appSession, request, answer}); } /* * (non-Javadoc) * * @see * org.jdiameter.api.cxdx.ServerCxDxSessionListener#doServerAssignmentRequest( * org.jdiameter.api.cxdx.ServerCxDxSession, org.jdiameter.api.cxdx.events.JServerAssignmentRequest) */ public void doServerAssignmentRequest(ServerCxDxSession appSession, JServerAssignmentRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { logger.info("Diameter Cx/Dx Session Factory :: doServerAssignmentRequest :: appSession[{}], Request[{}]", appSession, request); } /* * (non-Javadoc) * * @see org.jdiameter.api.cxdx.ServerCxDxSessionListener#doUserAuthorizationRequest( * org.jdiameter.api.cxdx.ServerCxDxSession, org.jdiameter.api.cxdx.events.JUserAuthorizationRequest) */ public void doUserAuthorizationRequest(ServerCxDxSession appSession, JUserAuthorizationRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { logger.info("Diameter Cx/Dx Session Factory :: doUserAuthorizationRequest :: appSession[{}], Request[{}]", appSession, request); } /* * (non-Javadoc) * * @see org.jdiameter.api.cxdx.ClientCxDxSessionListener#doLocationInformationAnswer(org.jdiameter.api.cxdx.ClientCxDxSession, * org.jdiameter.api.cxdx.events.JLocationInfoRequest, org.jdiameter.api.cxdx.events.JLocationInfoAnswer) */ public void doLocationInformationAnswer(ClientCxDxSession appSession, JLocationInfoRequest request, JLocationInfoAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { logger.info("Diameter Cx/Dx Session Factory :: doLocationInformationAnswer :: appSession[{}], Request[{}], Answer[{}]", new Object[]{appSession, request, answer}); } /* * (non-Javadoc) * * @see org.jdiameter.api.cxdx.ClientCxDxSessionListener#doMultimediaAuthAnswer(org.jdiameter.api.cxdx.ClientCxDxSession, * org.jdiameter.api.cxdx.events.JMultimediaAuthRequest, org.jdiameter.api.cxdx.events.JMultimediaAuthAnswer) */ public void doMultimediaAuthAnswer(ClientCxDxSession appSession, JMultimediaAuthRequest request, JMultimediaAuthAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { logger.info("Diameter Cx/Dx Session Factory :: doMultimediaAuthAnswer :: appSession[{}], Request[{}], Answer[{}]", new Object[]{appSession, request, answer}); } /* * (non-Javadoc) * * @see org.jdiameter.api.cxdx.ClientCxDxSessionListener#doPushProfileRequest( * org.jdiameter.api.cxdx.ClientCxDxSession, org.jdiameter.api.cxdx.events.JPushProfileRequest) */ public void doPushProfileRequest(ClientCxDxSession appSession, JPushProfileRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { logger.info("Diameter Cx/Dx Session Factory :: doPushProfileRequest :: appSession[{}], Request[{}]", appSession, request); } /* * (non-Javadoc) * * @seeorg.jdiameter.api.cxdx.ClientCxDxSessionListener#doRegistrationTerminationRequest( * org.jdiameter.api.cxdx.ClientCxDxSession, org.jdiameter.api.cxdx.events.JRegistrationTerminationRequest) */ public void doRegistrationTerminationRequest(ClientCxDxSession appSession, JRegistrationTerminationRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { logger.info("Diameter Cx/Dx Session Factory :: doRegistrationTerminationRequest :: appSession[{}], Request[{}]", appSession, request); } /* * (non-Javadoc) * * @see org.jdiameter.api.cxdx.ClientCxDxSessionListener#doServerAssignmentAnswer(org.jdiameter.api.cxdx.ClientCxDxSession, * org.jdiameter.api.cxdx.events.JServerAssignmentRequest, org.jdiameter.api.cxdx.events.JServerAssignmentAnswer) */ public void doServerAssignmentAnswer(ClientCxDxSession appSession, JServerAssignmentRequest request, JServerAssignmentAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { logger.info("Diameter Cx/Dx Session Factory :: doServerAssignmentAnswer :: appSession[{}], Request[{}], Answer[{}]", new Object[]{appSession, request, answer}); } /* * (non-Javadoc) * * @see org.jdiameter.api.cxdx.ClientCxDxSessionListener#doUserAuthorizationAnswer(org.jdiameter.api.cxdx.ClientCxDxSession, * org.jdiameter.api.cxdx.events.JUserAuthorizationRequest, org.jdiameter.api.cxdx.events.JUserAuthorizationAnswer) */ public void doUserAuthorizationAnswer(ClientCxDxSession appSession, JUserAuthorizationRequest request, JUserAuthorizationAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException { logger.info("Diameter Cx/Dx Session Factory :: doUserAuthorizationAnswer :: appSession[{}], Request[{}], Answer[{}]", new Object[]{appSession, request, answer}); } /* * (non-Javadoc) * * @see org.jdiameter.api.app.StateChangeListener#stateChanged(java.lang.Enum, java.lang.Enum) */ @SuppressWarnings("unchecked") public void stateChanged(Enum oldState, Enum newState) { logger.info("Diameter Cx/Dx Session Factory :: stateChanged :: oldState[{}], newState[{}]", oldState, newState); } /* * (non-Javadoc) * * @see org.jdiameter.api.app.StateChangeListener#stateChanged(java.lang.Object, java.lang.Enum, java.lang.Enum) */ @SuppressWarnings("unchecked") public void stateChanged(AppSession source, Enum oldState, Enum newState) { logger.info("Diameter Cx/Dx Session Factory :: stateChanged :: Session, [{}], oldState[{}], newState[{}]", new Object[]{source, oldState, newState}); } }
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.common.impl.app.cxdx; import org.jdiameter.api.Message; import org.jdiameter.api.cxdx.events.JServerAssignmentRequest; import org.jdiameter.common.impl.app.AppRequestEventImpl; /** * * @author <a href="mailto:baranowb@gmail.com">Bartosz Baranowski </a> * @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a> */ public class JServerAssignmentRequestImpl extends AppRequestEventImpl implements JServerAssignmentRequest { private static final long serialVersionUID = 1L; /** * * @param message */ public JServerAssignmentRequestImpl(Message message) { super(message); message.setRequest(true); } }
Java