code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.app.rx;
import org.jdiameter.common.api.app.rx.ClientRxSessionState;
import org.jdiameter.common.api.app.rx.IRxSessionData;
/**
*
* @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 IClientRxSessionData extends IRxSessionData {
public boolean isEventBased();
public void setEventBased(boolean b);
public boolean isRequestTypeSet();
public void setRequestTypeSet(boolean b);
public ClientRxSessionState getClientRxSessionState();
public void setClientRxSessionState(ClientRxSessionState 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.client.impl.app.rx;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.jdiameter.api.Answer;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.EventListener;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Message;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.app.AppAnswerEvent;
import org.jdiameter.api.app.AppEvent;
import org.jdiameter.api.app.AppRequestEvent;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.app.StateChangeListener;
import org.jdiameter.api.app.StateEvent;
import org.jdiameter.api.rx.ClientRxSession;
import org.jdiameter.api.rx.ClientRxSessionListener;
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.IContainer;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.client.api.parser.IMessageParser;
import org.jdiameter.client.api.parser.ParseException;
import org.jdiameter.client.impl.app.rx.Event.Type;
import org.jdiameter.common.api.app.IAppSessionState;
import org.jdiameter.common.api.app.rx.ClientRxSessionState;
import org.jdiameter.common.api.app.rx.IClientRxSessionContext;
import org.jdiameter.common.api.app.rx.IRxMessageFactory;
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 Client 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 ClientRxSessionImpl extends AppRxSessionImpl implements ClientRxSession, NetworkReqListener, EventListener<Request, Answer> {
private static final Logger logger = LoggerFactory.getLogger(ClientRxSessionImpl.class);
// Session State Handling ---------------------------------------------------
//protected boolean isEventBased = true;
//protected boolean requestTypeSet = false;
//protected ClientRxSessionState state = ClientRxSessionState.IDLE;
protected Lock sendAndStateLock = new ReentrantLock();
// Factories and Listeners --------------------------------------------------
protected transient IRxMessageFactory factory;
protected transient ClientRxSessionListener listener;
protected transient IClientRxSessionContext context;
protected transient IMessageParser parser;
protected IClientRxSessionData sessionData;
// protected String originHost, originRealm;
protected long[] authAppIds = new long[]{4};
// Requested Action + Credit-Control and Direct-Debiting Failure-Handling ---
static final int NON_INITIALIZED = -300;
// Session State Handling ---------------------------------------------------
protected boolean isEventBased = false;
//protected boolean requestTypeSet = false;
//protected ClientRxSessionState state = ClientRxSessionState.IDLE;
protected byte[] buffer;
protected String originHost, originRealm;
// Error Codes --------------------------------------------------------------
private static final long INVALID_SERVICE_INFORMATION = 5061L;
private static final long FILTER_RESTRICTIONS = 5062L;
private static final long REQUESTED_SERVICE_NOT_AUTHORIZED = 5063L;
private static final long DUPLICATED_AF_SESSION = 5064L;
private static final long IP_CAN_SESSION_NOT_AVAILABLE = 5065L;
private static final long UNAUTHORIZED_NON_EMERGENCY_SESSION = 5066L;
private static final long UNAUTHORIZED_SPONSORED_DATA_CONNECTIVITY = 5067L;
private static final long DIAMETER_UNABLE_TO_DELIVER = 3002L;
private static final long DIAMETER_TOO_BUSY = 3004L;
private static final long DIAMETER_LOOP_DETECTED = 3005L;
protected static final Set<Long> temporaryErrorCodes;
static {
HashSet<Long> tmp = new HashSet<Long>();
tmp.add(DIAMETER_UNABLE_TO_DELIVER);
tmp.add(DIAMETER_TOO_BUSY);
tmp.add(DIAMETER_LOOP_DETECTED);
temporaryErrorCodes = Collections.unmodifiableSet(tmp);
}
// Session Based Queue
protected ArrayList<Event> eventQueue = new ArrayList<Event>();
public ClientRxSessionImpl(IClientRxSessionData sessionData, IRxMessageFactory fct, ISessionFactory sf, ClientRxSessionListener lst, IClientRxSessionContext ctx,
StateChangeListener<AppSession> stLst) {
super(sf, sessionData);
if (lst == null) {
throw new IllegalArgumentException("Listener can not be null");
}
if (fct.getApplicationIds() == null) {
throw new IllegalArgumentException("ApplicationId can not be less than zero");
}
this.context = (IClientRxSessionContext) ctx;
this.authAppIds = fct.getApplicationIds();
this.listener = lst;
this.factory = fct;
IContainer icontainer = sf.getContainer();
this.parser = icontainer.getAssemblerFacility().getComponentInstance(IMessageParser.class);
this.sessionData = sessionData;
super.addStateChangeNotification(stLst);
}
public void sendAARequest(RxAARequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
try {
this.handleEvent(new Event(true, request, null));
}
catch (AvpDataException e) {
throw new InternalException(e);
}
}
public void sendSessionTermRequest(RxSessionTermRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
try {
this.handleEvent(new Event(true, request, null));
}
catch (AvpDataException e) {
throw new InternalException(e);
}
}
public void sendReAuthAnswer(RxReAuthAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
this.handleEvent(new Event(Event.Type.SEND_RAA, null, answer));
}
public void sendAbortSessionAnswer(RxAbortSessionAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
this.handleEvent(new Event(Event.Type.SEND_ASA, null, answer));
}
public boolean isStateless() {
return false;
}
public boolean isEventBased() {
return this.isEventBased;
}
@SuppressWarnings("unchecked")
public <E> E getState(Class<E> stateType) {
return stateType == ClientRxSessionState.class ? (E) sessionData.getClientRxSessionState() : null;
}
public boolean handleEvent(StateEvent event) throws InternalException, OverloadException {
return this.isEventBased() ? handleEventForEventBased(event) : handleEventForSessionBased(event);
}
protected boolean handleEventForEventBased(StateEvent event) throws InternalException, OverloadException {
try {
sendAndStateLock.lock();
final ClientRxSessionState state = this.sessionData.getClientRxSessionState();
Event localEvent = (Event) event;
Event.Type eventType = (Type) localEvent.getType();
switch (state) {
case IDLE:
switch (eventType) {
case SEND_EVENT_REQUEST:
// Current State: IDLE
// Event: Client or device requests a one-time service
// Action: Send AA event request
// New State: PENDING_E
setState(ClientRxSessionState.PENDING_EVENT);
try {
dispatchEvent(localEvent.getRequest());
}
catch (Exception e) {
// This handles failure to send in PendingI state in FSM table
logger.debug("Failure handling send event request", e);
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
default:
logger.warn("Event Based Handling - Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
case PENDING_EVENT:
switch (eventType) {
case RECEIVE_EVENT_ANSWER:
AppAnswerEvent answer = (AppAnswerEvent) localEvent.getAnswer();
try {
long resultCode = answer.getResultCodeAvp().getUnsigned32();
if (isSuccess(resultCode)) {
// Current State: PENDING_E
// Event: Successful AA event answer received
// Action: Grant service to end user
// New State: IDLE
setState(ClientRxSessionState.IDLE, false);
}
if (isProvisional(resultCode) || isFailure(resultCode)) {
handleFailureMessage(answer, (AppRequestEvent) localEvent.getRequest(), eventType);
}
deliverRxAAAnswer((RxAARequest) localEvent.getRequest(), (RxAAAnswer) localEvent.getAnswer());
}
catch (AvpDataException e) {
logger.debug("Failure handling received answer event", e);
setState(ClientRxSessionState.IDLE, false);
}
break;
default:
logger.warn("Event Based Handling - Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
case PENDING_BUFFERED:
switch (eventType) {
case RECEIVE_EVENT_ANSWER:
// Current State: PENDING_B
// Event: Successful CC answer received
// Action: Delete request
// New State: IDLE
setState(ClientRxSessionState.IDLE, false);
//this.sessionData.setBuffer(null);
buffer = null;
deliverRxAAAnswer((RxAARequest) localEvent.getRequest(), (RxAAAnswer) localEvent.getAnswer());
break;
default:
logger.warn("Event Based Handling - Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
default:
logger.warn("Event Based Handling - Wrong event type ({}) on state {}", eventType, state);
break;
}
dispatch();
return true;
}
catch (Exception e) {
throw new InternalException(e);
}
finally {
sendAndStateLock.unlock();
}
}
protected boolean handleEventForSessionBased(StateEvent event) throws InternalException, OverloadException {
try {
sendAndStateLock.lock();
final ClientRxSessionState state = this.sessionData.getClientRxSessionState();
Event localEvent = (Event) event;
Event.Type eventType = (Type) localEvent.getType();
switch (state) {
case IDLE:
switch (eventType) {
case SEND_AAR:
// Current State: IDLE
// Event: Client or device requests access/service
// Action: Send AAR
// New State: PENDING_AAR
setState(ClientRxSessionState.PENDING_AAR);
try {
dispatchEvent(localEvent.getRequest());
}
catch (Exception e) {
// This handles failure to send in PendingI state in FSM table
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
default:
logger.warn("Session Based Handling - Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
case PENDING_AAR:
AppAnswerEvent answer = (AppAnswerEvent) localEvent.getAnswer();
switch (eventType) {
case RECEIVE_AAA:
long resultCode = answer.getResultCodeAvp().getUnsigned32();
if (isSuccess(resultCode)) {
// Current State: PENDING_AAR
// Event: Successful AA answer received
// New State: OPEN
setState(ClientRxSessionState.OPEN);
}
else if (isProvisional(resultCode) || isFailure(resultCode)) {
handleFailureMessage(answer, (AppRequestEvent) localEvent.getRequest(), eventType);
}
deliverRxAAAnswer((RxAARequest) localEvent.getRequest(), (RxAAAnswer) localEvent.getAnswer());
break;
case SEND_AAR:
case SEND_STR:
// Current State: PENDING_AAR
// Event: User service terminated
// Action: Queue termination event
// New State: PENDING_AAR
// Current State: PENDING_AAR
// Event: Change in request
// Action: Queue changed rating condition event
// New State: PENDING_AAR
eventQueue.add(localEvent);
break;
case RECEIVE_RAR:
deliverReAuthRequest((RxReAuthRequest) localEvent.getRequest());
break;
case SEND_RAA:
// Current State: PENDING_U
// Event: RAR received
// Action: Send RAA
// New State: PENDING_U
try {
dispatchEvent(localEvent.getAnswer());
}
catch (Exception e) {
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
case RECEIVE_ASR:
deliverAbortSessionRequest((RxAbortSessionRequest) localEvent.getRequest());
break;
case SEND_ASA:
try {
dispatchEvent(localEvent.getAnswer());
}
catch (Exception e) {
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
default:
logger.warn("Session Based Handling - Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
case PENDING_STR:
AppAnswerEvent stanswer = (AppAnswerEvent) localEvent.getAnswer();
switch (eventType) {
case RECEIVE_STA:
long resultCode = stanswer.getResultCodeAvp().getUnsigned32();
if (isSuccess(resultCode)) {
// Current State: PENDING_STR
// Event: Successful ST answer received
// New State: IDLE
setState(ClientRxSessionState.IDLE, false);
}
else if (isProvisional(resultCode) || isFailure(resultCode)) {
handleFailureMessage(stanswer, (AppRequestEvent) localEvent.getRequest(), eventType);
}
deliverRxSessionTermAnswer((RxSessionTermRequest) localEvent.getRequest(), (RxSessionTermAnswer) localEvent.getAnswer());
break;
case SEND_AAR:
try {
// Current State: PENDING_STR
// Event: Change in AA request
// Action: -
// New State: PENDING_STR
dispatchEvent(localEvent.getRequest());
// No transition
}
catch (Exception e) {
// This handles failure to send in PendingI state in FSM table
// handleSendFailure(e, eventType);
}
break;
// case RECEIVE_STA:
// // Current State: PENDING_T
// // Event: Successful CC termination answer received
// // Action: -
// // New State: IDLE
//
// // Current State: PENDING_T
// // Event: Failure to send, temporary error, or failed answer
// // Action: -
// // New State: IDLE
//
// //FIXME: Alex broke this, setting back "true" ?
// setState(ClientRxSessionState.IDLE, false);
// //setState(ClientRxSessionState.IDLE, true);
// deliverRxSessionTermAnswer((RxSessionTermRequest) localEvent.getRequest(), (RxSessionTermAnswer) localEvent.getAnswer());
// //setState(ClientRxSessionState.IDLE, true);
// break;
default:
logger.warn("Session Based Handling - Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
case OPEN:
switch (eventType) {
case SEND_AAR:
// Current State: OPEN
// Event: Updated AAR send by AF
// Action: Send AAR update request
// New State: PENDING_AAR
setState(ClientRxSessionState.PENDING_AAR);
try {
dispatchEvent(localEvent.getRequest());
}
catch (Exception e) {
// This handles failure to send in PendingI state in FSM table
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
case SEND_STR:
// Current State: OPEN
// Event: Session Termination event request received to be sent
// Action: Terminate end user's service, send STR termination request
// New State: PENDING STR
setState(ClientRxSessionState.PENDING_STR);
try {
dispatchEvent(localEvent.getRequest());
}
catch (Exception e) {
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
case RECEIVE_RAR:
deliverReAuthRequest((RxReAuthRequest) localEvent.getRequest());
break;
case SEND_RAA:
try {
dispatchEvent(localEvent.getAnswer());
}
catch (Exception e) {
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
case RECEIVE_ASR:
deliverAbortSessionRequest((RxAbortSessionRequest) localEvent.getRequest());
break;
case SEND_ASA:
try {
dispatchEvent(localEvent.getAnswer());
}
catch (Exception e) {
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
default:
logger.warn("Session Based Handling - Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
default:
// any other state is bad
setState(ClientRxSessionState.IDLE, true);
break;
}
dispatch();
return true;
}
catch (Exception e) {
throw new InternalException(e);
}
finally {
sendAndStateLock.unlock();
}
}
public Answer processRequest(Request request) {
RequestDelivery rd = new RequestDelivery();
rd.session = this;
rd.request = request;
super.scheduler.execute(rd);
return null;
}
public void receivedSuccessMessage(Request request, Answer answer) {
AnswerDelivery ad = new AnswerDelivery();
ad.session = this;
ad.request = request;
ad.answer = answer;
super.scheduler.execute(ad);
}
public void timeoutExpired(Request request) {
// if (request.getCommandCode() == RxAAAnswer.code) {
// try {
// handleSendFailure(null, null, request);
// }
// catch (Exception e) {
// logger.debug("Failure processing timeout message for request", e);
// }
// }
}
protected void setState(ClientRxSessionState newState) {
setState(newState, true);
}
@SuppressWarnings("unchecked")
protected void setState(ClientRxSessionState newState, boolean release) {
try {
IAppSessionState oldState = this.sessionData.getClientRxSessionState();
this.sessionData.setClientRxSessionState(newState);
for (StateChangeListener i : stateListeners) {
i.stateChanged(this, (Enum) oldState, (Enum) newState);
}
if (newState == ClientRxSessionState.IDLE) {
if (release) {
this.release();
}
}
}
catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("Failure switching to state " + this.sessionData.getClientRxSessionState() + " (release=" + release + ")", e);
}
}
}
@Override
public void release() {
if (isValid()) {
try {
this.sendAndStateLock.lock();
super.release();
}
catch (Exception e) {
logger.debug("Failed to release session", e);
}
finally {
sendAndStateLock.unlock();
}
}
else {
logger.debug("Trying to release an already invalid session, with Session ID '{}'", getSessionId());
}
}
protected void handleSendFailure(Exception e, Event.Type eventType, Message request) throws Exception {
logger.debug("Failed to send message, type: {} message: {}, failure: {}", new Object[]{eventType, request, e != null ? e.getLocalizedMessage() : ""});
//try {
// setState(ClientRxSessionState.IDLE);
//}
//finally {
// dispatch();
//}
}
protected void handleFailureMessage(final AppAnswerEvent event, final AppRequestEvent request, final Event.Type eventType) {
try {
setState(ClientRxSessionState.IDLE);
}
catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("Failure handling failure message for Event " + event + " (" + eventType + ") and Request " + request, e);
}
}
}
/**
* This makes checks on queue, moves it to proper state if event there is
* present on Open state ;]
*/
protected void dispatch() {
// Event Based ----------------------------------------------------------
if (isEventBased()) {
// Current State: IDLE
// Event: Request in storage
// Action: Send stored request
// New State: PENDING_B
if (buffer != null) {
setState(ClientRxSessionState.PENDING_BUFFERED);
try {
dispatchEvent(new AppRequestEventImpl(messageFromBuffer(ByteBuffer.wrap(buffer))));
}
catch (Exception e) {
try {
handleSendFailure(e, Event.Type.SEND_EVENT_REQUEST, messageFromBuffer(ByteBuffer.wrap(buffer)));
}
catch (Exception e1) {
logger.error("Failure handling buffer send failure", e1);
}
}
}
} // Session Based --------------------------------------------------------
else {
if (sessionData.getClientRxSessionState() == ClientRxSessionState.OPEN && eventQueue.size() > 0) {
try {
this.handleEvent(eventQueue.remove(0));
}
catch (Exception e) {
logger.error("Failure handling queued event", e);
}
}
}
}
protected void deliverRxAAAnswer(RxAARequest request, RxAAAnswer answer) {
try {
listener.doAAAnswer(this, request, answer);
}
catch (Exception e) {
logger.warn("Failure delivering AAA", e);
}
}
protected void deliverRxSessionTermAnswer(RxSessionTermRequest request, RxSessionTermAnswer answer) {
try {
listener.doSessionTermAnswer(this, request, answer);
}
catch (Exception e) {
logger.warn("Failure delivering STA", e);
}
}
protected void deliverReAuthRequest(RxReAuthRequest request) {
try {
listener.doReAuthRequest(this, request);
}
catch (Exception e) {
logger.debug("Failure delivering RAR", e);
}
}
protected void deliverAbortSessionRequest(RxAbortSessionRequest request) {
try {
listener.doAbortSessionRequest(this, request);
}
catch (Exception e) {
logger.debug("Failure delivering RAR", e);
}
}
protected void dispatchEvent(AppEvent event) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
session.send(event.getMessage(), this);
}
protected boolean isProvisional(long resultCode) {
return resultCode >= 1000 && resultCode < 2000;
}
protected boolean isSuccess(long resultCode) {
return resultCode >= 2000 && resultCode < 3000;
}
protected boolean isFailure(long code) {
return (!isProvisional(code) && !isSuccess(code) && ((code >= 3000 && /*code < 4000) || (code >= 5000 &&*/ code < 6000)) && !temporaryErrorCodes.contains(code));
}
/* (non-Javadoc)
* @see org.jdiameter.common.impl.app.AppSessionImpl#isReplicable()
*/
@Override
public boolean isReplicable() {
return true;
}
/* (non-Javadoc)
* @see org.jdiameter.common.impl.app.AppSessionImpl#relink(org.jdiameter.client.api.IContainer)
*/
private final Message messageFromBuffer(ByteBuffer request) throws InternalException {
if (request != null) {
Message m;
try {
m = parser.createMessage(request);
return m;
}
catch (AvpDataException e) {
throw new InternalException("Failed to decode message.", e);
}
}
return null;
}
private ByteBuffer messageToBuffer(IMessage msg) throws InternalException {
try {
return parser.encodeMessage(msg);
}
catch (ParseException e) {
throw new InternalException("Failed to encode message.", e);
}
}
private class RequestDelivery implements Runnable {
ClientRxSession session;
Request request;
public void run() {
try {
switch (request.getCommandCode()) {
case RxReAuthRequest.code:
handleEvent(new Event(Event.Type.RECEIVE_RAR, factory.createReAuthRequest(request), null));
break;
case RxAbortSessionRequest.code:
handleEvent(new Event(Event.Type.RECEIVE_ASR, factory.createAbortSessionRequest(request), null));
break;
default:
listener.doOtherEvent(session, new AppRequestEventImpl(request), null);
break;
}
}
catch (Exception e) {
logger.debug("Failure processing request", e);
}
}
}
private class AnswerDelivery implements Runnable {
ClientRxSession session;
Answer answer;
Request request;
public void run() {
try {
switch (request.getCommandCode()) {
case RxAAAnswer.code:
final RxAARequest myAARequest = factory.createAARequest(request);
final RxAAAnswer myAAAnswer = factory.createAAAnswer(answer);
handleEvent(new Event(false, myAARequest, myAAAnswer));
break;
case RxSessionTermAnswer.code:
final RxSessionTermRequest mySTRequest = factory.createSessionTermRequest(request);
final RxSessionTermAnswer mySTAnswer = factory.createSessionTermAnswer(answer);
handleEvent(new Event(false, mySTRequest, mySTAnswer));
break;
default:
listener.doOtherEvent(session, new AppRequestEventImpl(request), new AppAnswerEventImpl(answer));
break;
}
}
catch (Exception e) {
logger.debug("Failure processing success message", e);
}
}
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(authAppIds);
result = prime * result + (isEventBased ? 1231 : 1237);
result = prime * result + ((originHost == null) ? 0 : originHost.hashCode());
result = prime * result + ((originRealm == null) ? 0 : originRealm.hashCode());
result = prime * result + ((sessionData == null) ? 0 : (sessionData.getClientRxSessionState() == null ? 0 :
sessionData.getClientRxSessionState().hashCode()));
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
ClientRxSessionImpl other = (ClientRxSessionImpl) obj;
if (!Arrays.equals(authAppIds, other.authAppIds)) {
return false;
}
if (isEventBased != other.isEventBased) {
return false;
}
if (originHost == null) {
if (other.originHost != null) {
return false;
}
}
else if (!originHost.equals(other.originHost)) {
return false;
}
if (originRealm == null) {
if (other.originRealm != null) {
return false;
}
}
else if (!originRealm.equals(other.originRealm)) {
return false;
}
if (sessionData == null) {
if (other.sessionData != null)
return false;
}
else if (sessionData.getClientRxSessionState() == null) {
if (other.sessionData.getClientRxSessionState() != null)
return false;
}
else if (!sessionData.getClientRxSessionState().equals(other.sessionData.getClientRxSessionState()))
return false;
return true;
}
public void onTimer(String timerName) {
}
} | Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.app.rx;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.app.AppAnswerEvent;
import org.jdiameter.api.app.AppEvent;
import org.jdiameter.api.app.AppRequestEvent;
import org.jdiameter.api.app.StateEvent;
import org.jdiameter.api.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_AAR, RECEIVE_AAA,
SEND_STR, RECEIVE_STA,
SEND_RAA, RECEIVE_RAR,
SEND_ASA, RECEIVE_ASR,
SEND_EVENT_REQUEST, RECEIVE_EVENT_ANSWER;
}
Type type;
AppRequestEvent request;
AppAnswerEvent answer;
Event(Type type) {
this.type = type;
}
Event(Type type, AppRequestEvent request, AppAnswerEvent answer) {
this.type = type;
this.answer = answer;
this.request = request;
}
Event(boolean isRequest, AppRequestEvent request, AppAnswerEvent answer) throws AvpDataException {
this.answer = answer;
this.request = request;
if (isRequest) {
switch (request.getCommandCode()) {
case RxAARequest.code:
type = Type.SEND_AAR;
break;
case RxSessionTermRequest.code:
type = Type.SEND_STR;
break;
case RxReAuthRequest.code:
type = Type.RECEIVE_RAR;
break;
case RxAbortSessionRequest.code:
type = Type.RECEIVE_ASR;
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.SEND_EVENT_REQUEST;
break;
default:
throw new RuntimeException("Wrong command code value: " + request.getCommandCode());
}
}
else {
switch (answer.getCommandCode()) {
case RxAAAnswer.code:
type = Type.RECEIVE_AAA;
break;
case RxSessionTermAnswer.code:
type = Type.RECEIVE_STA;
break;
case RxReAuthAnswer.code:
type = Type.SEND_RAA;
break;
case RxAbortSessionAnswer.code:
type = Type.SEND_ASA;
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.RECEIVE_EVENT_ANSWER;
break;
default:
throw new RuntimeException("Wrong CC-Request-Type value: " + answer.getCommandCode());
}
}
}
public Enum getType() {
return type;
}
public int compareTo(Object o) {
return 0;
}
public Object getData() {
return request != null ? request : answer;
}
public void setData(Object data) {
// FIXME: What should we do here?! Is it request or answer?
}
public AppEvent getRequest() {
return request;
}
public AppEvent getAnswer() {
return answer;
}
public <E> E encodeType(Class<E> eClass) {
return eClass == Event.Type.class ? (E) type : null;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.app.rx;
import org.jdiameter.common.api.app.AppSessionDataLocalImpl;
import org.jdiameter.common.api.app.rx.ClientRxSessionState;
/**
*
* @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 ClientRxSessionDataLocalImpl extends AppSessionDataLocalImpl implements IClientRxSessionData {
protected boolean isEventBased = true;
protected boolean requestTypeSet = false;
protected ClientRxSessionState state = ClientRxSessionState.IDLE;
/**
*
*/
public ClientRxSessionDataLocalImpl() {
}
public boolean isEventBased() {
return isEventBased;
}
public void setEventBased(boolean isEventBased) {
this.isEventBased = isEventBased;
}
public boolean isRequestTypeSet() {
return requestTypeSet;
}
public void setRequestTypeSet(boolean requestTypeSet) {
this.requestTypeSet = requestTypeSet;
}
public ClientRxSessionState getClientRxSessionState() {
return state;
}
public void setClientRxSessionState(ClientRxSessionState 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.client.impl.app.auth;
import java.io.Serializable;
import org.jdiameter.common.api.app.auth.ClientAuthSessionState;
import org.jdiameter.common.api.app.auth.IAuthSessionData;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public interface IClientAuthSessionData extends IAuthSessionData {
public void setClientAuthSessionState(ClientAuthSessionState state);
public ClientAuthSessionState getClientAuthSessionState();
public boolean isStateless();
public void setStateless(boolean b);
public String getDestinationHost();
public void setDestinationHost(String host);
public String getDestinationRealm();
public void setDestinationRealm(String realm);
public Serializable getTsTimerId();
public void setTsTimerId(Serializable realm);
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.app.auth;
import java.io.Serializable;
import org.jdiameter.common.api.app.AppSessionDataLocalImpl;
import org.jdiameter.common.api.app.auth.ClientAuthSessionState;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ClientAuthSessionDataLocalImpl extends AppSessionDataLocalImpl implements IClientAuthSessionData {
protected ClientAuthSessionState state = ClientAuthSessionState.IDLE;
protected boolean stateless = true;
protected String destinationHost;
protected String destinationRealm;
protected Serializable tsTimerId;
/* (non-Javadoc)
* @see org.jdiameter.client.impl.app.auth.IClientAuthSessionData#setClientAuthSessionState(org.jdiameter.common.api.app.auth.ClientAuthSessionState)
*/
@Override
public void setClientAuthSessionState(ClientAuthSessionState state) {
this.state = state;
}
/* (non-Javadoc)
* @see org.jdiameter.client.impl.app.auth.IClientAuthSessionData#getClientAuthSessionState()
*/
@Override
public ClientAuthSessionState getClientAuthSessionState() {
return this.state;
}
/* (non-Javadoc)
* @see org.jdiameter.client.impl.app.auth.IClientAuthSessionData#isStateless()
*/
@Override
public boolean isStateless() {
return this.stateless;
}
/* (non-Javadoc)
* @see org.jdiameter.client.impl.app.auth.IClientAuthSessionData#setStateless(boolean)
*/
@Override
public void setStateless(boolean b) {
this.stateless = b;
}
/* (non-Javadoc)
* @see org.jdiameter.client.impl.app.auth.IClientAuthSessionData#getDestinationHost()
*/
@Override
public String getDestinationHost() {
return this.destinationHost;
}
/* (non-Javadoc)
* @see org.jdiameter.client.impl.app.auth.IClientAuthSessionData#setDestinationHost(java.lang.String)
*/
@Override
public void setDestinationHost(String host) {
this.destinationHost = host;
}
/* (non-Javadoc)
* @see org.jdiameter.client.impl.app.auth.IClientAuthSessionData#getDestinationRealm()
*/
@Override
public String getDestinationRealm() {
return this.destinationRealm;
}
/* (non-Javadoc)
* @see org.jdiameter.client.impl.app.auth.IClientAuthSessionData#setDestinationRealm(java.lang.String)
*/
@Override
public void setDestinationRealm(String realm) {
this.destinationRealm = realm;
}
/* (non-Javadoc)
* @see org.jdiameter.client.impl.app.auth.IClientAuthSessionData#getTsTimerId()
*/
@Override
public Serializable getTsTimerId() {
return this.tsTimerId;
}
/* (non-Javadoc)
* @see org.jdiameter.client.impl.app.auth.IClientAuthSessionData#setTsTimerId(java.io.Serializable)
*/
@Override
public void setTsTimerId(Serializable tid) {
this.tsTimerId = tid;
}
}
| 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.client.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{
SEND_AUTH_REQUEST,
SEND_AUTH_ANSWER,
SEND_SESSION_TERMINATION_REQUEST,
SEND_SESSION_ABORT_ANSWER,
RECEIVE_AUTH_ANSWER,
RECEIVE_FAILED_AUTH_ANSWER,
RECEIVE_ABORT_SESSION_REQUEST,
RECEIVE_SESSION_TERINATION_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/or its affiliates, and individual
* contributors as indicated by the @authors tag. All rights reserved.
* See the copyright.txt in the distribution for a full listing
* of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU General Public License, v. 2.0.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License,
* v. 2.0 along with this distribution; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.jdiameter.client.impl.app.auth;
import static org.jdiameter.api.Message.SESSION_TERMINATION_REQUEST;
import static org.jdiameter.common.api.app.auth.ClientAuthSessionState.DISCONNECTED;
import static org.jdiameter.common.api.app.auth.ClientAuthSessionState.IDLE;
import static org.jdiameter.common.api.app.auth.ClientAuthSessionState.OPEN;
import static org.jdiameter.common.api.app.auth.ClientAuthSessionState.PENDING;
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.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.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.ClientAuthSession;
import org.jdiameter.api.auth.ClientAuthSessionListener;
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.client.api.ISessionFactory;
import org.jdiameter.common.api.app.IAppSessionState;
import org.jdiameter.common.api.app.auth.ClientAuthSessionState;
import org.jdiameter.common.api.app.auth.IAuthMessageFactory;
import org.jdiameter.common.api.app.auth.IClientAuthActionContext;
import org.jdiameter.common.impl.app.AppAnswerEventImpl;
import org.jdiameter.common.impl.app.AppRequestEventImpl;
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.SessionTermAnswerImpl;
import org.jdiameter.common.impl.app.auth.SessionTermRequestImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Client Authorization session implementation
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ClientAuthSessionImpl extends AppAuthSessionImpl implements ClientAuthSession, EventListener<Request, Answer>, NetworkReqListener {
protected static final Logger logger = LoggerFactory.getLogger(ClientAuthSessionImpl.class);
// Session State Handling ---------------------------------------------------
//protected boolean stateless = false;
//protected ClientAuthSessionState state = IDLE;
protected Lock sendAndStateLock = new ReentrantLock();
// Factories and Listeners --------------------------------------------------
protected transient IAuthMessageFactory factory;
protected transient IClientAuthActionContext context;
protected transient ClientAuthSessionListener listener;
//protected String destHost, destRealm;
//protected ScheduledFuture sessionTimer;
//protected Serializable timerId_ts;
protected static final String TIMER_NAME_TS="AUTH_TS";
protected IClientAuthSessionData sessionData;
// Constructors -------------------------------------------------------------
public ClientAuthSessionImpl(IClientAuthSessionData sessionData,ISessionFactory sf,ClientAuthSessionListener lst, IAuthMessageFactory fct, StateChangeListener<AppSession> scListener,IClientAuthActionContext context, boolean stateless) {
super(sf, sessionData);
if (lst == null) {
throw new IllegalArgumentException("Listener can not be null");
}
if (fct.getApplicationId() == null) {
throw new IllegalArgumentException("ApplicationId can not be null");
}
super.appId = fct.getApplicationId();
this.listener = lst;
this.factory = fct;
this.context = context;
this.sessionData = sessionData;
this.sessionData.setStateless(stateless);
super.addStateChangeNotification(scListener);
}
// ClientAuthSession Implementation methods ---------------------------------
public void sendAbortSessionAnswer(AbortSessionAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_SESSION_ABORT_ANSWER, answer);
}
public void sendAuthRequest(AppRequestEvent request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_AUTH_REQUEST, request);
}
public void sendReAuthAnswer(ReAuthAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_AUTH_ANSWER, answer);
}
public void sendSessionTerminationRequest(SessionTermRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_SESSION_TERMINATION_REQUEST, request);
}
protected void send(Event.Type type, AppEvent event) throws InternalException {
//This is called from app thread, it may be due to callback from our delivery thread, but we dont care
try {
sendAndStateLock.lock();
if (type != null) {
handleEvent(new Event(type, event));
}
session.send(event.getMessage(), this);
// Store last destination information
AvpSet avps = event.getMessage().getAvps();
Avp destRealmAvp = avps.getAvp(Avp.DESTINATION_REALM);
if(destRealmAvp != null) {
sessionData.setDestinationRealm(destRealmAvp.getDiameterIdentity());
}
Avp destHostAvp = avps.getAvp(Avp.DESTINATION_HOST);
if(destHostAvp != null) {
sessionData.setDestinationHost(destHostAvp.getDiameterIdentity());
}
}
catch (Exception e) {
throw new InternalException(e);
}
finally {
sendAndStateLock.unlock();
}
}
public boolean isStateless() {
return this.sessionData.isStateless();
}
@SuppressWarnings("unchecked")
protected void setState(ClientAuthSessionState newState) {
IAppSessionState oldState = sessionData.getClientAuthSessionState();
sessionData.setClientAuthSessionState(newState);
for (StateChangeListener i : stateListeners) {
i.stateChanged(this,(Enum) oldState, (Enum) newState);
}
}
@SuppressWarnings("unchecked")
public <E> E getState(Class<E> eClass) {
return eClass == ClientAuthSessionState.class ? (E) sessionData.getClientAuthSessionState() : null;
}
public boolean handleEvent(StateEvent event) throws InternalException, OverloadException {
return sessionData.isStateless() ? handleEventForStatelessSession(event) : handleEventForStatefulSession(event);
}
public boolean handleEventForStatelessSession(StateEvent event) throws InternalException, OverloadException {
try {
ClientAuthSessionState state = sessionData.getClientAuthSessionState();
ClientAuthSessionState oldState = state;
switch (state) {
case IDLE:
switch ((Event.Type) event.getType()) {
case SEND_AUTH_REQUEST:
// Current State: IDLE
// Event: Client or Device Requests access
// Action: Send service specific auth req
// New State: PENDING
setState(PENDING);
break;
default:
logger.debug("Unknown event {}", event.getType());
break;
}
break;
case PENDING:
switch ((Event.Type) event.getType()) {
case RECEIVE_AUTH_ANSWER:
try {
// Current State: PENDING
// Event: Successful service-specific authorization answer received with Auth-Session-State set to NO_STATE_MAINTAINED
// Action: Grant Access
// New State: OPEN
setState(OPEN);
listener.doAuthAnswerEvent(this, null, (AppAnswerEvent) event.getData());
}
catch (Exception e) {
// Current State: PENDING
// Event: Failed service-specific authorization answer received
// Action: Cleanup
// New State: IDLE
setState(IDLE);
}
break;
default:
logger.debug("Unknown event {}", event.getType());
break;
}
break;
case OPEN:
switch ((Event.Type) event.getType()) {
case SEND_SESSION_ABORT_ANSWER:
case SEND_SESSION_TERMINATION_REQUEST:
// Current State: OPEN
// Event: Service to user is terminated
// Action: Disconnect User/Device
// New State: IDLE
setState(IDLE);
break;
case TIMEOUT_EXPIRES:
// Current State: OPEN
// Event: Session-Timeout Expires on Access Device
// Action: Send STR
// New State: DISCON
try {
if (context != null) {
context.accessTimeoutElapses(this);
Request str = createSessionTermRequest();
context.disconnectUserOrDev(this, str);
session.send(str, this);
}
}
finally {
// IDLE is the same as DISCON
setState(IDLE);
}
break;
default:
logger.debug("Unknown event {}", event.getType());
break;
}
break;
}
// post processing
if (oldState != state) {
if (DISCONNECTED.equals(state) || IDLE.equals(state)) {
cancelTsTimer();
}
else if (OPEN.equals(state) && context != null && context.getAccessTimeout() > 0) {
// sessionTimer = scheduler.schedule(new Runnable() {
// public void run() {
// if (context != null) {
// try {
// handleEvent(new Event(Event.Type.TIMEOUT_EXPIRES, null));
// }
// catch (Exception e) {
// logger.debug("Can not handle event", e);
// }
// }
// }
// }, context.createAccessTimer(), TimeUnit.MILLISECONDS);
cancelTsTimer();
startTsTimer();
}
}
}
catch (Throwable t) {
throw new InternalException(t);
}
return true;
}
public boolean handleEventForStatefulSession(StateEvent event) throws InternalException, OverloadException {
ClientAuthSessionState state = sessionData.getClientAuthSessionState();
ClientAuthSessionState oldState = state;
try {
switch (state) {
case IDLE: {
switch ((Event.Type) event.getType()) {
case SEND_AUTH_REQUEST:
// Current State: IDLE
// Event: Client or Device Requests access
// Action: Send service specific auth req
// New State: PENDING
setState(PENDING);
break;
case RECEIVE_ABORT_SESSION_REQUEST:
// Current State: IDLE
// Event: ASR Received for unknown session
// Action: Send ASA with Result-Code = UNKNOWN_SESSION_ID
// New State: IDLE
// FIXME: Should send ASA with UNKNOWN_SESSION_ID instead ?
listener.doAbortSessionRequestEvent(this, (AbortSessionRequest) event.getData());
break;
default:
logger.debug("Unknown event {}", event.getType());
break;
}
break;
}
case PENDING: {
switch ((Event.Type) event.getType()) {
case RECEIVE_AUTH_ANSWER:
try {
// Current State: PENDING
// Event: Successful service-specific authorization answer received with default Auth-Session-State value
// Action: Grant Access
// New State: OPEN
setState(OPEN);
listener.doAuthAnswerEvent(this, null, (AppAnswerEvent) event.getData());
}
catch (InternalException e) {
// Current State: PENDING
// Event: Successful service-specific authorization answer received but service not provided
// Action: Send STR
// New State: DISCON
// Current State: PENDING
// Event: Error Processing successful service-specific authorization answer
// Action: Send STR
// New State: DISCON
setState(DISCONNECTED);
}
catch (Exception e) {
// Current State: PENDING
// Event: Failed service-specific authorization answer received
// Action: Cleanup
// New State: IDLE
setState(IDLE);
}
break;
default:
logger.debug("Unknown event {}", event.getType());
break;
}
break;
}
case OPEN: {
switch ((Event.Type) event.getType()) {
case SEND_AUTH_REQUEST:
// Current State: OPEN
// Event: User or client device requests access to service
// Action: Send service specific auth req
// New State: OPEN
break;
case RECEIVE_AUTH_ANSWER:
try {
// Current State: OPEN
// Event: Successful service-specific authorization answer received
// Action: Provide Service
// New State: OPEN
listener.doAuthAnswerEvent(this, null, (AppAnswerEvent) event.getData());
}
catch (Exception e) {
// Current State: OPEN
// Event: ASR Received, client will comply with request to end the session
// Action: Send ASA with Result-Code = SUCCESS, Send STR
// New State: DISCON
setState(DISCONNECTED);
}
break;
case RECEIVE_FAILED_AUTH_ANSWER:
// Current State: OPEN
// Event: Failed Service-specific authorization answer received
// Action: Disconnect User/Device
// New State: IDLE
try {
if (context != null) {
Request str = createSessionTermRequest();
context.disconnectUserOrDev(this, str);
session.send(str, this);
}
}
finally {
setState(IDLE);
listener.doAuthAnswerEvent(this, null, (AppAnswerEvent) event.getData());
}
break;
case RECEIVE_ABORT_SESSION_REQUEST:
// Current State: OPEN
// Event: ASR Received (client to take comply or not)
// Action: TBD
// New State: TBD (comply = DISCON, !comply = OPEN)
listener.doAbortSessionRequestEvent(this, (AbortSessionRequestImpl) event.getData());
break;
case SEND_SESSION_TERMINATION_REQUEST:
setState(DISCONNECTED);
break;
case TIMEOUT_EXPIRES:
// Current State: OPEN
// Event: Session-Timeout Expires on Access Device
// Action: Send STR
// New State: DISCON
// Current State: OPEN
// Event: Authorization-Lifetime + Auth-Grace-Period expires on access device
// Action: Send STR
// New State: DISCON
try {
if (context != null) {
context.accessTimeoutElapses(this);
Request str = createSessionTermRequest();
context.disconnectUserOrDev(this, str);
session.send(str, this);
}
}
finally {
setState(DISCONNECTED);
}
break;
}
break;
}
case DISCONNECTED: {
switch ((Event.Type) event.getType()) {
case RECEIVE_ABORT_SESSION_REQUEST:
// Current State: DISCON
// Event: ASR Received
// Action: Send ASA
// New State: DISCON
listener.doAbortSessionRequestEvent(this, (AbortSessionRequest) event.getData());
break;
case RECEIVE_SESSION_TERINATION_ANSWER:
// Current State: DISCON
// Event: STA Received
// Action: Disconnect User/Device
// New State: IDLE
listener.doSessionTerminationAnswerEvent(this, ((SessionTermAnswerImpl) event.getData()));
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 && context.getAccessTimeout() > 0) {
// scheduler.schedule(new Runnable() {
// public void run() {
// if (context != null) {
// try {
// handleEvent(new Event(Event.Type.TIMEOUT_EXPIRES, null));
// }
// catch (Exception e) {
// logger.debug("Can not handle event", e);
// }
// }
// }
// }, context.createAccessTimer(), TimeUnit.MILLISECONDS);
cancelTsTimer();
startTsTimer();
}
}
}
catch (Throwable t) {
throw new InternalException(t);
}
return true;
}
public void receivedSuccessMessage(Request request, Answer answer) {
AnswerDelivery ad = new AnswerDelivery();
ad.session = this;
ad.request = request;
ad.answer = answer;
super.scheduler.execute(ad);
}
public void timeoutExpired(Request request) {
try {
sendAndStateLock.lock();
//FIXME: should this also be async ?
handleEvent(new Event(Event.Type.RECEIVE_FAILED_AUTH_ANSWER, new AppRequestEventImpl(request)));
}
catch (Exception e) {
logger.debug("Can not handle timeout event", e);
}
finally {
sendAndStateLock.unlock();
}
}
public Answer processRequest(Request request) {
RequestDelivery rd = new RequestDelivery();
rd.session = this;
rd.request = request;
super.scheduler.execute(rd);
return null;
}
/* (non-Javadoc)
* @see org.jdiameter.common.impl.app.AppSessionImpl#isReplicable()
*/
@Override
public boolean isReplicable() {
return true;
}
protected void startTsTimer() throws IllegalArgumentException, InternalException {
try {
sendAndStateLock.lock();
sessionData.setTsTimerId(super.timerFacility.schedule(sessionData.getSessionId(), TIMER_NAME_TS, context.getAccessTimeout()));
}
finally {
sendAndStateLock.unlock();
}
}
protected void cancelTsTimer() {
try {
sendAndStateLock.lock();
Serializable timerId = sessionData.getTsTimerId();
if(timerId != null) {
super.timerFacility.cancel(timerId);
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);
if (context != null) {
try {
handleEvent(new Event(Event.Type.TIMEOUT_EXPIRES, null));
}
catch (Exception e) {
logger.debug("Can not handle event", e);
}
}
}
finally {
sendAndStateLock.unlock();
}
}
}
protected AbortSessionAnswer createAbortSessionAnswer(Answer answer) {
return new AbortSessionAnswerImpl(answer);
}
protected AbortSessionRequest createAbortSessionRequest(Request request) {
return new AbortSessionRequestImpl(request);
}
protected ReAuthAnswer createReAuthAnswer(Answer answer) {
return new ReAuthAnswerImpl(answer);
}
protected ReAuthRequest createReAuthRequest(Request request) {
return new ReAuthRequestImpl(request);
}
protected SessionTermAnswer createSessionTermAnswer(Answer answer) {
return new SessionTermAnswerImpl(answer);
}
protected SessionTermRequest createSessionTermRequest(Request request) {
return new SessionTermRequestImpl(request);
}
protected Request createSessionTermRequest() {
return session.createRequest(SESSION_TERMINATION_REQUEST, appId, sessionData.getDestinationRealm(), sessionData.getDestinationHost());
}
@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;
ClientAuthSessionImpl other = (ClientAuthSessionImpl) 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();
}
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 {
ClientAuthSession session;
Request request;
public void run() {
try {
if (request.getCommandCode() == AbortSessionRequestImpl.code) {
handleEvent(new Event(Event.Type.RECEIVE_ABORT_SESSION_REQUEST, createAbortSessionRequest(request)));
} else if (request.getCommandCode() == ReAuthRequestImpl.code) {
listener.doReAuthRequestEvent(session, createReAuthRequest(request));
} else {
listener.doOtherEvent(session, factory.createAuthRequest(request), null);
}
}
catch (Exception e) {
logger.debug("Can not process received request", e);
}
}
}
private class AnswerDelivery implements Runnable {
ClientAuthSession session;
Answer answer;
Request request;
public void run() {
try {
sendAndStateLock.lock();
// FIXME: baranowb: this shouldn't be like that?
if (answer.getCommandCode() == factory.getAuthMessageCommandCode()) {
handleEvent(new Event(Event.Type.RECEIVE_AUTH_ANSWER, factory.createAuthAnswer(answer)));
} else if (answer.getCommandCode() == SessionTermAnswerImpl.code) {
handleEvent(new Event(Event.Type.RECEIVE_SESSION_TERINATION_ANSWER, createSessionTermAnswer(answer)));
}
else {
listener.doOtherEvent(session, factory.createAuthRequest(request), new AppAnswerEventImpl(answer));
}
}
catch (Exception e) {
logger.debug("Can not process received message", e);
}
finally {
sendAndStateLock.unlock();
}
}
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.app.acc;
import java.io.Serializable;
import org.jdiameter.api.Request;
import org.jdiameter.common.api.app.AppSessionDataLocalImpl;
import org.jdiameter.common.api.app.acc.ClientAccSessionState;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ClientAccSessionDataLocalImpl extends AppSessionDataLocalImpl implements IClientAccSessionData {
protected ClientAccSessionState state = ClientAccSessionState.IDLE;
protected Request buffer;
protected String destRealm;
protected String destHost;
protected Serializable tid;
/**
*
*/
public ClientAccSessionDataLocalImpl() {
}
@Override
public void setClientAccSessionState(ClientAccSessionState state) {
this.state = state;
}
@Override
public ClientAccSessionState getClientAccSessionState() {
return this.state;
}
@Override
public void setInterimTimerId(Serializable tid) {
this.tid = tid;
}
@Override
public Serializable getInterimTimerId() {
return this.tid;
}
@Override
public void setDestinationHost(String destHost) {
this.destHost = destHost;
}
@Override
public String getDestinationHost() {
return this.destHost;
}
@Override
public void setDestinationRealm(String destRealm) {
this.destRealm = destRealm;
}
@Override
public String getDestinationRealm() {
return this.destRealm;
}
@Override
public void setBuffer(Request event) {
this.buffer = event;
}
@Override
public Request getBuffer() {
return this.buffer;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.app.acc;
import java.io.Serializable;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Request;
import org.jdiameter.common.api.app.acc.ClientAccSessionState;
import org.jdiameter.common.api.app.acc.IAccSessionData;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public interface IClientAccSessionData extends IAccSessionData {
public void setClientAccSessionState(ClientAccSessionState state);
public ClientAccSessionState getClientAccSessionState();
public void setInterimTimerId(Serializable tid);
public Serializable getInterimTimerId();
public void setDestinationHost(String destHost);
public String getDestinationHost();
public void setDestinationRealm(String destRealm);
public String getDestinationRealm();
public void setBuffer(Request event);
public Request getBuffer();
public void setApplicationId(ApplicationId aid);
public ApplicationId getApplicationId();
}
| 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.client.impl.app.acc;
import org.jdiameter.api.Avp;
import org.jdiameter.api.ResultCode;
import org.jdiameter.api.acc.events.AccountAnswer;
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{
SEND_EVENT_RECORD,
SEND_START_RECORD,
SEND_INTERIM_RECORD,
SEND_STOP_RECORD,
FAILED_SEND_RECORD,
RECEIVED_RECORD,
FAILED_RECEIVE_RECORD
}
Type type;
AppEvent data;
Event(Type type) {
this.type = type;
}
Event(AccountAnswer accountAnswer) throws Exception {
int resCode = ResultCode.SUCCESS;
try {
resCode = accountAnswer.getMessage().getAvps().getAvp(Avp.RESULT_CODE).getInteger32();
} catch (Exception exc) {}
type = (resCode == ResultCode.SUCCESS || (resCode/1000 == 4)) ? Type.RECEIVED_RECORD : Type.FAILED_RECEIVE_RECORD;
data = accountAnswer;
}
Event(AccountRequest accountRequest) throws Exception {
data = accountRequest;
int type = accountRequest.getAccountingRecordType();
switch (type) {
case 1:
this.type = Type.SEND_EVENT_RECORD;
break;
case 2:
this.type = Type.SEND_START_RECORD;
break;
case 3:
this.type = Type.SEND_INTERIM_RECORD;
break;
case 4:
this.type = Type.SEND_STOP_RECORD;
break;
default:
throw new Exception("Unknown type " + type);
}
}
Event(Type type, AccountRequest accountRequest) throws Exception {
this.type = type;
this.data = accountRequest;
}
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 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.app.acc;
import static org.jdiameter.api.Avp.ACCOUNTING_REALTIME_REQUIRED;
import static org.jdiameter.common.api.app.acc.ClientAccSessionState.IDLE;
import static org.jdiameter.common.api.app.acc.ClientAccSessionState.OPEN;
import static org.jdiameter.common.api.app.acc.ClientAccSessionState.PENDING_BUFFERED;
import static org.jdiameter.common.api.app.acc.ClientAccSessionState.PENDING_CLOSE;
import static org.jdiameter.common.api.app.acc.ClientAccSessionState.PENDING_EVENT;
import static org.jdiameter.common.api.app.acc.ClientAccSessionState.PENDING_INTERIM;
import static org.jdiameter.common.api.app.acc.ClientAccSessionState.PENDING_START;
import java.io.Serializable;
import org.jdiameter.api.Answer;
import org.jdiameter.api.Avp;
import org.jdiameter.api.EventListener;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Message;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.acc.ClientAccSession;
import org.jdiameter.api.acc.ClientAccSessionListener;
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.ClientAccSessionState;
import org.jdiameter.common.api.app.acc.IClientAccActionContext;
import org.jdiameter.common.impl.app.AppEventImpl;
import org.jdiameter.common.impl.app.acc.AppAccSessionImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Client Accounting session implementation
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ClientAccSessionImpl extends AppAccSessionImpl implements EventListener<Request, Answer>, ClientAccSession {
private static final Logger logger = LoggerFactory.getLogger(ClientAccSessionImpl.class);
// Constants ----------------------------------------------------------------
public static final int DELIVER_AND_GRANT = 1;
public static final int GRANT_AND_LOSE = 3;
// Session State Handling ---------------------------------------------------
//protected ClientAccSessionState state = IDLE;
// Factories and Listeners --------------------------------------------------
protected IClientAccActionContext context;
protected ClientAccSessionListener listener;
//protected transient IMessageParser parser;
//protected Serializable timerId_interim;
protected static final String TIMER_NAME_INTERIM = "CLIENT_INTERIM";
//protected String destHost, destRealm;
//protected AccountRequest buffer;
protected IClientAccSessionData sessionData;
public ClientAccSessionImpl(IClientAccSessionData sessionData, ISessionFactory sessionFactory,ClientAccSessionListener clientAccSessionListener, IClientAccActionContext iClientAccActionContext,
StateChangeListener<AppSession> stateChangeListener) {
super(sessionFactory,sessionData);
this.sessionData = sessionData;
this.listener = clientAccSessionListener;
this.context = iClientAccActionContext;
super.addStateChangeNotification(stateChangeListener);
}
public void sendAccountRequest(AccountRequest accountRequest) throws InternalException, IllegalStateException, RouteException, OverloadException {
try {
sendAndStateLock.lock();
handleEvent(new Event(accountRequest));
try {
session.send(accountRequest.getMessage(), this);
// Store last destination information
sessionData.setDestinationRealm(accountRequest.getMessage().getAvps().getAvp(Avp.DESTINATION_REALM).getDiameterIdentity());
Avp destHostAvp = accountRequest.getMessage().getAvps().getAvp(Avp.DESTINATION_HOST);
if(destHostAvp != null) {
sessionData.setDestinationHost(destHostAvp.getDiameterIdentity());
}
}
catch (Throwable t) {
logger.debug("Failed to send ACR.", t);
handleEvent(new Event(Event.Type.FAILED_SEND_RECORD, accountRequest));
}
}
catch (Exception exc) {
throw new InternalException(exc);
}
finally {
sendAndStateLock.unlock();
}
}
protected synchronized void storeToBuffer(Request accountRequest) {
sessionData.setBuffer(accountRequest);
}
protected synchronized boolean checkBufferSpace() {
//TODO: make this different op, so it does not have to fetch data.
return sessionData.getBuffer() == null;
}
@SuppressWarnings("unchecked")
protected void setState(IAppSessionState newState) {
IAppSessionState oldState = sessionData.getClientAccSessionState();
sessionData.setClientAccSessionState((ClientAccSessionState) newState);
for (StateChangeListener i : stateListeners) {
i.stateChanged(this,(Enum) oldState, (Enum) newState);
}
}
public boolean isStateless() {
return false;
}
public boolean handleEvent(StateEvent event) throws InternalException, OverloadException {
ClientAccSessionState oldState = sessionData.getClientAccSessionState();
try {
switch (oldState) {
// Idle ==========
case IDLE: {
switch ((Event.Type) event.getType()) {
// Client or device requests access
case SEND_START_RECORD:
// Current State: IDLE
// Event: Client or Device Requests access
// Action: Send accounting start req.
// New State: PENDING_S
setState(PENDING_START);
break;
case SEND_EVENT_RECORD:
// Current State: IDLE
// Event: Client or device requests a one-time service
// Action: Send accounting event req
// New State: PENDING_E
setState(PENDING_EVENT);
break;
// Send buffered message action in other section of this method see below
default:
throw new IllegalStateException("Current state " + oldState + " action " + event.getType());
}
break;
}
// PendingS ==========
case PENDING_START: {
switch ((Event.Type) event.getType()) {
case FAILED_SEND_RECORD:
AccountRequest request = (AccountRequest) event.getData();
Avp accRtReq = request.getMessage().getAvps().getAvp(ACCOUNTING_REALTIME_REQUIRED);
// Current State: PENDING_S
// Event: Failure to send and buffer space available and realtime not equal to DELIVER_AND_GRANT
// Action: Store Start Record
// New State: OPEN
if (checkBufferSpace() && accRtReq != null && accRtReq.getInteger32() != DELIVER_AND_GRANT) {
//... cast overkill...
storeToBuffer((Request) ((AppEventImpl)request).getMessage());
setState(OPEN);
}
else {
// Current State: PENDING_S
// Event: Failure to send and no buffer space available and realtime equal to GRANT_AND_LOSE
// Action: -
// New State: OPEN
if (!checkBufferSpace() && accRtReq != null && accRtReq.getInteger32() == GRANT_AND_LOSE) {
setState(OPEN);
}
else {
// Current State: PENDING_S
// Event: Failure to send and no buffer space available and realtime not equal to GRANT_AND_LOSE
// Action: Disconnect User/Device
// New State: IDLE
if (!checkBufferSpace() && accRtReq != null && accRtReq.getInteger32() != GRANT_AND_LOSE) {
try {
if (context != null) {
Request str = createSessionTermRequest();
context.disconnectUserOrDev(this, str);
session.send(str, this);
}
}
finally {
setState(IDLE);
}
}
}
}
break;
case RECEIVED_RECORD:
// Current State: PENDING_S
// Event: Successful accounting start answer received
// Action: -
// New State: OPEN
processInterimIntervalAvp(event);
setState(OPEN);
break;
case FAILED_RECEIVE_RECORD:
try {
AccountAnswer answer = (AccountAnswer) event.getData();
accRtReq = answer.getMessage().getAvps().getAvp(ACCOUNTING_REALTIME_REQUIRED);
// Current State: PENDING_S
// Event: Failed accounting start answer received and realtime equal to GRANT_AND_LOSE
// Action: -
// New State: OPEN
if (accRtReq != null && accRtReq.getInteger32() == GRANT_AND_LOSE) {
setState(OPEN);
}
else {
// Current State: PENDING_S
// Event: Failed accounting start answer received and realtime not equal to GRANT_AND_LOSE
// Action: Disconnect User/Device
// New State: IDLE
if (accRtReq != null && accRtReq.getInteger32() != GRANT_AND_LOSE) {
try{
if (context != null) {
Request str = createSessionTermRequest();
context.disconnectUserOrDev(this, str);
session.send(str, this);
}
}
finally {
setState(IDLE);
}
}
}
}
catch (Exception e) {
logger.debug("Can not process answer", e);
setState(IDLE);
}
break;
case SEND_STOP_RECORD:
// Current State: PENDING_S
// Event: User service terminated
// Action: Store stop record
// New State: PENDING_S
if (context != null) {
Request str = createSessionTermRequest();
context.disconnectUserOrDev(this,str);
storeToBuffer(str);
}
break;
}
break;
}
// OPEN ==========
case OPEN: {
switch ((Event.Type) event.getType()) {
// User service terminated
case SEND_STOP_RECORD:
// Current State: OPEN
// Event: User service terminated
// Action: Send accounting stop request
// New State: PENDING_L
setState(PENDING_CLOSE);
break;
case SEND_INTERIM_RECORD:
// FIXME: Shouldn't this be different ?
// Current State: OPEN
// Event: Interim interval elapses
// Action: Send accounting interim record
// New State: PENDING_I
setState(PENDING_INTERIM);
break;
// Create timer for "Interim interval elapses" event
case RECEIVED_RECORD:
processInterimIntervalAvp(event);
break;
}
}
break;
//FIXME: add check for abnormal
// PendingI ==========
case PENDING_INTERIM: {
switch ((Event.Type) event.getType()) {
case RECEIVED_RECORD:
// Current State: PENDING_I
// Event: Successful accounting interim answer received
// Action: -
// New State: OPEN
processInterimIntervalAvp(event);
setState(OPEN);
break;
case FAILED_SEND_RECORD:
AccountRequest request = (AccountRequest) event.getData();
Avp accRtReq = request.getMessage().getAvps().getAvp(ACCOUNTING_REALTIME_REQUIRED);
// Current State: PENDING_I
// Event: Failure to send and buffer space available (or old record interim can be overwritten) and realtime not equal to DELIVER_AND_GRANT
// Action: Store interim record
// New State: OPEN
if (checkBufferSpace() && accRtReq != null && accRtReq.getInteger32() != DELIVER_AND_GRANT) {
//... cast overkill...
storeToBuffer((Request) ((AppEventImpl)request).getMessage());
setState(OPEN);
}
else {
// Current State: PENDING_I
// Event: Failure to send and no buffer space available and realtime equal to GRANT_AND_LOSE
// Action: -
// New State: OPEN
if (!checkBufferSpace() && accRtReq != null && accRtReq.getInteger32() == GRANT_AND_LOSE) {
setState(OPEN);
}
else {
// Current State: PENDING_I
// Event: Failure to send and no buffer space available and realtime not equal to GRANT_AND_LOSE
// Action: Disconnect User/Device
// New State: IDLE
if (!checkBufferSpace() && accRtReq != null && accRtReq.getInteger32() != GRANT_AND_LOSE) {
try{
if (context != null) {
Request str = createSessionTermRequest();
context.disconnectUserOrDev(this, str);
session.send(str, this);
}
}
finally {
setState(IDLE);
}
}
}
}
break;
case FAILED_RECEIVE_RECORD:
try {
AccountAnswer answer = (AccountAnswer) event.getData();
accRtReq = answer.getMessage().getAvps().getAvp(ACCOUNTING_REALTIME_REQUIRED);
// Current State: PENDING_I
// Event: Failed accounting interim answer received and realtime equal to GRANT_AND_LOSE
// Action: -
// New State: OPEN
if (accRtReq != null && accRtReq.getInteger32() == GRANT_AND_LOSE) {
setState(OPEN);
}
else {
// Current State: PENDING_I
// Event: Failed account interim answer received and realtime not equal to GRANT_AND_LOSE
// Action: Disconnect User/Device
// New State: IDLE
if (accRtReq != null && accRtReq.getInteger32() != GRANT_AND_LOSE) {
try {
if (context != null) {
Request str = createSessionTermRequest();
context.disconnectUserOrDev(this, str);
session.send(str, this);
}
}
finally {
setState(IDLE);
}
}
}
}
catch (Exception e) {
logger.debug("Can not process received request", e);
setState(IDLE);
}
break;
case SEND_STOP_RECORD:
// Current State: PENDING_I
// Event: User service terminated
// Action: Store stop record
// New State: PENDING_I
if (context != null) {
Request str = createSessionTermRequest();
context.disconnectUserOrDev(this,str);
storeToBuffer(str);
}
break;
}
break;
}
// PendingE ==========
case PENDING_EVENT: {
switch ((Event.Type) event.getType()) {
case RECEIVED_RECORD:
// Current State: PENDING_E
// Event: Successful accounting event answer received
// Action: -
// New State: IDLE
setState(IDLE);
break;
case FAILED_SEND_RECORD:
if (checkBufferSpace()) {
// Current State: PENDING_E
// Event: Failure to send and buffer space available
// Action: Store event record
// New State: IDLE
AccountRequest data = (AccountRequest) event.getData();
//... cast overkill...
storeToBuffer((Request) ((AppEventImpl)data).getMessage());
}
// Current State: PENDING_E
// Event: Failure to send and no buffer space available
// Action: -
// New State: IDLE
setState(IDLE);
break;
case FAILED_RECEIVE_RECORD:
// Current State: PENDING_E
// Event: Failed accounting event answer received
// Action: -
// New State: IDLE
setState(IDLE);
break;
}
break;
}
// PendingB ==========
case PENDING_BUFFERED: {
switch ((Event.Type) event.getType()) {
case RECEIVED_RECORD:
// Current State: PENDING_B
// Event: Successful accounting answer received
// Action: Delete record
// New State: IDLE
synchronized (this) {
storeToBuffer(null);
}
setState(IDLE);
break;
// Failure to send
case FAILED_SEND_RECORD:
// Current State: PENDING_B
// Event: Failure to send
// Action: -
// New State: IDLE
setState(IDLE);
break;
// Failed accounting answer received
case FAILED_RECEIVE_RECORD:
// Current State: PENDING_B
// Event: Failed accounting answer received
// Action: Delete record
// New State: IDLE
synchronized (this) {
storeToBuffer(null);
}
setState(IDLE);
break;
}
break;
}
// PendingL ==========
case PENDING_CLOSE: {
switch ((Event.Type) event.getType()) {
case RECEIVED_RECORD:
// Current State: PENDING_L
// Event: Successful accounting stop answer received
// Action: -
// New State: IDLE
setState(IDLE);
break;
case FAILED_SEND_RECORD:
if (checkBufferSpace()) {
// Current State: PENDING_L
// Event: Failure to send and buffer space available
// Action: Store stop record
// New State: IDLE
AccountRequest data = (AccountRequest) event.getData();
//... cast overkill...
storeToBuffer((Request) ((AppEventImpl)data).getMessage());
}
// Current State: PENDING_L
// Event: Failure to send and no buffer space available
// Action: -
// New State: IDLE
setState(IDLE);
break;
// Failed accounting stop answer received
case FAILED_RECEIVE_RECORD:
// Current State: PENDING_L
// Event: Failed accounting stop answer received
// Action: -
// New State: IDLE
setState(IDLE);
break;
}
break;
}
}
ClientAccSessionState state = sessionData.getClientAccSessionState();
// Post processing
if (oldState != state) {
switch (state) {
// IDLE ===========
case IDLE:
{
// Current State: IDLE
// Event: Records in storage
// Action: Send record
// New State: PENDING_B
try {
synchronized (this) {
if (!checkBufferSpace()) {
session.send(sessionData.getBuffer(), this);
setState(PENDING_BUFFERED);
}
}
}
catch (Exception e) {
logger.debug("can not send buffered message", e);
synchronized (this) {
if (context != null && !checkBufferSpace()) {
if (!context.failedSendRecord(this,(Request) sessionData.getBuffer())) {
storeToBuffer(null);
}
}
}
}
}
}
}
}
catch (Throwable t) {
throw new InternalException(t);
}
return true;
}
protected void processInterimIntervalAvp(StateEvent event) throws InternalException {
// Avp interval = ((AppEvent) event.getData()).getMessage().getAvps().getAvp(Avp.ACCT_INTERIM_INTERVAL);
// if (interval != null) {
// // create timer
// try {
// long v = interval.getUnsigned32();
// if (v != 0) {
// // scheduler.schedule(
// // new Runnable() {
// // public void run() {
// // if (context != null) {
// // try {
// // Request interimRecord = createInterimRecord();
// // context.interimIntervalElapses(interimRecord);
// // sendAndStateLock.lock();
// // session.send(interimRecord, ClientAccSessionImpl.this);
// // setState(PENDING_INTERIM);
// // }
// // catch (Exception e) {
// // logger.debug("Can not process Interim Interval AVP", e);
// // }
// // finally {
// // sendAndStateLock.unlock();
// // }
// // }
// // }
// // },
// // v, TimeUnit.SECONDS
// // );
// cancelInterimTimer();
// this.timerId_interim = startInterimTimer(v);
// }
// }
// catch (AvpDataException e) {
// logger.debug("Unable to retrieve Acct-Interim-Interval AVP value", e);
// }
// }
}
/* (non-Javadoc)
* @see org.jdiameter.common.impl.app.AppSessionImpl#onTimer(java.lang.String)
*/
@Override
public void onTimer(String timerName) {
if(timerName.equals(TIMER_NAME_INTERIM)) {
if (context != null) {
try {
Request interimRecord = createInterimRecord();
context.interimIntervalElapses(this,interimRecord);
sendAndStateLock.lock();
session.send(interimRecord, ClientAccSessionImpl.this);
setState(PENDING_INTERIM);
sessionData.setInterimTimerId(null);
}
catch (Exception e) {
logger.debug("Can not process Interim Interval AVP", e);
}
finally {
sendAndStateLock.unlock();
}
}
}
else {
//....?
}
}
private Serializable startInterimTimer(long v) {
try{
sendAndStateLock.lock();
Serializable interimTimerId = super.timerFacility.schedule(sessionData.getSessionId(), TIMER_NAME_INTERIM, v);
sessionData.setInterimTimerId(interimTimerId);
return interimTimerId;
}
finally {
sendAndStateLock.unlock();
}
}
private void cancelInterimTimer() {
try{
sendAndStateLock.lock();
Serializable interimTimerId = sessionData.getInterimTimerId();
if(interimTimerId != null) {
super.timerFacility.cancel(interimTimerId);
sessionData.setInterimTimerId(null);
}
}
finally {
sendAndStateLock.unlock();
}
}
@SuppressWarnings("unchecked")
public <E> E getState(Class<E> eClass) {
return eClass == ClientAccSessionState.class ? (E) sessionData.getClientAccSessionState() : null;
}
public void receivedSuccessMessage(Request request, Answer answer) {
if (request.getCommandCode() == AccountRequest.code) {
// state should be changed before event listener call
try {
sendAndStateLock.lock();
handleEvent(new Event(createAccountAnswer(answer)));
}
catch (Exception e) {
logger.debug("Can not process received request", e);
}
finally {
sendAndStateLock.unlock();
}
try {
listener.doAccAnswerEvent(this, createAccountRequest(request), createAccountAnswer(answer));
}
catch (Exception e) {
logger.debug("Unable to deliver message to listener.", e);
}
}
else {
try {
listener.doOtherEvent(this, createAccountRequest(request), createAccountAnswer(answer));
}
catch (Exception e) {
logger.debug("Can not process received request", e);
}
}
}
public void timeoutExpired(Request request) {
try {
sendAndStateLock.lock();
handleEvent(new Event(Event.Type.FAILED_SEND_RECORD, createAccountRequest(request)));
}
catch (Exception e) {
logger.debug("Can not handle timeout event", e);
}
finally {
sendAndStateLock.unlock();
}
}
public Answer processRequest(Request request) {
Answer a = request.createAnswer(5001);
return a;
}
/* (non-Javadoc)
* @see org.jdiameter.common.impl.app.AppSessionImpl#isReplicable()
*/
@Override
public boolean isReplicable() {
return true;
}
protected Request createInterimRecord() {
Request interimRecord = session.createRequest(AccountRequest.code, sessionData.getApplicationId(), sessionData.getDestinationRealm(), sessionData.getDestinationHost());
interimRecord.getAvps().addAvp(Avp.ACC_RECORD_TYPE, 3);
return interimRecord;
}
protected Request createSessionTermRequest() {
return session.createRequest(Message.SESSION_TERMINATION_REQUEST, sessionData.getApplicationId(), sessionData.getDestinationRealm(), sessionData.getDestinationHost());
}
@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;
ClientAccSessionImpl other = (ClientAccSessionImpl) 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();
}
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.client.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{
SEND_AUTH_REQUEST,
SEND_AUTH_ANSWER,
SEND_SESSION_TERMINATION_REQUEST,
SEND_SESSION_ABORT_ANSWER,
RECEIVE_AUTH_ANSWER,
RECEIVE_FAILED_AUTH_ANSWER,
RECEIVE_ABORT_SESSION_REQUEST,
RECEIVE_SESSION_TERINATION_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.client.impl.app.gq;
import static org.jdiameter.api.Message.SESSION_TERMINATION_REQUEST;
import static org.jdiameter.common.api.app.auth.ClientAuthSessionState.DISCONNECTED;
import static org.jdiameter.common.api.app.auth.ClientAuthSessionState.IDLE;
import static org.jdiameter.common.api.app.auth.ClientAuthSessionState.OPEN;
import static org.jdiameter.common.api.app.auth.ClientAuthSessionState.PENDING;
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.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.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.gq.GqClientSession;
import org.jdiameter.api.auth.ClientAuthSessionListener;
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.client.api.ISessionFactory;
import org.jdiameter.common.api.app.IAppSessionState;
import org.jdiameter.common.api.app.auth.ClientAuthSessionState;
import org.jdiameter.common.api.app.auth.IAuthMessageFactory;
import org.jdiameter.common.api.app.auth.IClientAuthActionContext;
import org.jdiameter.common.impl.app.AppAnswerEventImpl;
import org.jdiameter.common.impl.app.AppRequestEventImpl;
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.SessionTermAnswerImpl;
import org.jdiameter.common.impl.app.auth.SessionTermRequestImpl;
import org.jdiameter.client.impl.app.auth.IClientAuthSessionData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Client 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 GqClientSessionImpl extends AppAuthSessionImpl implements GqClientSession, EventListener<Request, Answer>, NetworkReqListener {
protected static final Logger logger = LoggerFactory.getLogger(GqClientSessionImpl.class);
// Session State Handling ---------------------------------------------------
protected Lock sendAndStateLock = new ReentrantLock();
// Factories and Listeners --------------------------------------------------
protected transient IAuthMessageFactory factory;
protected transient IClientAuthActionContext context;
protected transient ClientAuthSessionListener listener;
protected static final String TIMER_NAME_TS = "GQ_TS";
protected IClientAuthSessionData sessionData;
// Constructors -------------------------------------------------------------
public GqClientSessionImpl(IClientAuthSessionData sessionData,ISessionFactory sf,ClientAuthSessionListener lst, IAuthMessageFactory fct, StateChangeListener<AppSession> scListener,IClientAuthActionContext context, boolean stateless) {
super(sf, sessionData);
if (lst == null) {
throw new IllegalArgumentException("Listener can not be null");
}
if (fct.getApplicationId() == null) {
throw new IllegalArgumentException("ApplicationId can not be null");
}
super.appId = fct.getApplicationId();
this.listener = lst;
this.factory = fct;
this.context = context;
this.sessionData = sessionData;
this.sessionData.setStateless(stateless);
super.addStateChangeNotification(scListener);
}
// ClientAuthSession Implementation methods ---------------------------------
public void sendAbortSessionAnswer(AbortSessionAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_SESSION_ABORT_ANSWER, answer);
}
public void sendAuthRequest(AppRequestEvent request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_AUTH_REQUEST, request);
}
public void sendReAuthAnswer(ReAuthAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_AUTH_ANSWER, answer);
}
public void sendSessionTerminationRequest(SessionTermRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_SESSION_TERMINATION_REQUEST, request);
}
protected void send(Event.Type type, AppEvent event) throws InternalException {
//This is called from app thread, it may be due to callback from our delivery thread, but we dont care
try {
sendAndStateLock.lock();
if (type != null) {
handleEvent(new Event(type, event));
}
session.send(event.getMessage(), this);
// Store last destination information
AvpSet avps = event.getMessage().getAvps();
Avp destRealmAvp = avps.getAvp(Avp.DESTINATION_REALM);
if(destRealmAvp != null) {
sessionData.setDestinationRealm(destRealmAvp.getDiameterIdentity());
}
Avp destHostAvp = avps.getAvp(Avp.DESTINATION_HOST);
if(destHostAvp != null) {
sessionData.setDestinationHost(destHostAvp.getDiameterIdentity());
}
}
catch (Exception e) {
throw new InternalException(e);
}
finally {
sendAndStateLock.unlock();
}
}
public boolean isStateless() {
return this.sessionData.isStateless();
}
@SuppressWarnings("unchecked")
protected void setState(ClientAuthSessionState newState) {
IAppSessionState oldState = sessionData.getClientAuthSessionState();
sessionData.setClientAuthSessionState(newState);
for (StateChangeListener i : stateListeners) {
i.stateChanged(this,(Enum) oldState, (Enum) newState);
}
}
@SuppressWarnings("unchecked")
public <E> E getState(Class<E> eClass) {
return eClass == ClientAuthSessionState.class ? (E) sessionData.getClientAuthSessionState() : null;
}
public boolean handleEvent(StateEvent event) throws InternalException, OverloadException {
return sessionData.isStateless() ? handleEventForStatelessSession(event) : handleEventForStatefulSession(event);
}
public boolean handleEventForStatelessSession(StateEvent event) throws InternalException, OverloadException {
try {
ClientAuthSessionState state = sessionData.getClientAuthSessionState();
ClientAuthSessionState oldState = state;
switch (state) {
case IDLE:
switch ((Event.Type) event.getType()) {
case SEND_AUTH_REQUEST:
// Current State: IDLE
// Event: Client or Device Requests access
// Action: Send service specific auth req
// New State: PENDING
setState(PENDING);
break;
default:
logger.debug("Unknown event [{}]", event.getType());
break;
}
break;
case PENDING:
switch ((Event.Type) event.getType()) {
case RECEIVE_AUTH_ANSWER:
try {
// Current State: PENDING
// Event: Successful service-specific authorization answer received with Auth-Session-State set to NO_STATE_MAINTAINED
// Action: Grant Access
// New State: OPEN
listener.doAuthAnswerEvent(this, null, (AppAnswerEvent) event.getData());
setState(OPEN);
}
catch (Exception e) {
// Current State: PENDING
// Event: Failed service-specific authorization answer received
// Action: Cleanup
// New State: IDLE
setState(IDLE);
}
break;
case SEND_SESSION_TERMINATION_REQUEST:
// Current State: OPEN
// Event: Service to user is terminated
// Action: Disconnect User/Device
// New State: IDLE
setState(IDLE);
break;
default:
logger.debug("Unknown event [{}]", event.getType());
break;
}
break;
case OPEN:
switch ((Event.Type) event.getType()) {
case SEND_SESSION_ABORT_ANSWER:
case SEND_SESSION_TERMINATION_REQUEST:
// Current State: OPEN
// Event: Service to user is terminated
// Action: Disconnect User/Device
// New State: IDLE
setState(IDLE);
break;
case TIMEOUT_EXPIRES:
// Current State: OPEN
// Event: Session-Timeout Expires on Access Device
// Action: Send STR
// New State: DISCON
if (context != null) {
context.accessTimeoutElapses(this);
Request str = createSessionTermRequest();
context.disconnectUserOrDev(this, str);
session.send(str, this);
}
// IDLE is the same as DISCON
setState(IDLE);
break;
default:
logger.debug("Unknown event [{}]", event.getType());
break;
}
break;
}
// post processing
if (oldState != state) {
if (DISCONNECTED.equals(state) || IDLE.equals(state)) {
cancelTsTimer();
}
else if (OPEN.equals(state) && context != null && context.getAccessTimeout() > 0) {
cancelTsTimer();
startTsTimer();
}
}
}
catch (Throwable t) {
throw new InternalException(t);
}
return true;
}
public boolean handleEventForStatefulSession(StateEvent event) throws InternalException, OverloadException {
ClientAuthSessionState state = sessionData.getClientAuthSessionState();
ClientAuthSessionState oldState = state;
try {
switch (state) {
case IDLE: {
switch ((Event.Type) event.getType()) {
case SEND_AUTH_REQUEST:
// Current State: IDLE
// Event: Client or Device Requests access
// Action: Send service specific auth req
// New State: PENDING
setState(PENDING);
break;
case RECEIVE_ABORT_SESSION_REQUEST:
// Current State: IDLE
// Event: ASR Received for unknown session
// Action: Send ASA with Result-Code = UNKNOWN_SESSION_ID
// New State: IDLE
// FIXME: Should send ASA with UNKNOWN_SESSION_ID instead ?
listener.doAbortSessionRequestEvent(this, (AbortSessionRequest) event.getData());
break;
default:
logger.debug("Unknown event [{}]", event.getType());
break;
}
break;
}
case PENDING: {
switch ((Event.Type) event.getType()) {
case RECEIVE_AUTH_ANSWER:
try {
// Current State: PENDING
// Event: Successful service-specific authorization answer received with default Auth-Session-State value
// Action: Grant Access
// New State: OPEN
listener.doAuthAnswerEvent(this, null, (AppAnswerEvent) event.getData());
setState(OPEN);
}
catch (InternalException e) {
// Current State: PENDING
// Event: Successful service-specific authorization answer received but service not provided
// Action: Send STR
// New State: DISCON
// Current State: PENDING
// Event: Error Processing successful service-specific authorization answer
// Action: Send STR
// New State: DISCON
setState(DISCONNECTED);
}
catch (Exception e) {
// Current State: PENDING
// Event: Failed service-specific authorization answer received
// Action: Cleanup
// New State: IDLE
setState(IDLE);
}
break;
case SEND_SESSION_TERMINATION_REQUEST:
// Current State: OPEN
// Event: Service to user is terminated
// Action: Disconnect User/Device
// New State: IDLE
setState(DISCONNECTED);
break;
default:
logger.debug("Unknown event [{}]", event.getType());
break;
}
break;
}
case OPEN: {
switch ((Event.Type) event.getType()) {
case SEND_AUTH_REQUEST:
// Current State: OPEN
// Event: User or client device requests access to service
// Action: Send service specific auth req
// New State: OPEN
break;
case RECEIVE_AUTH_ANSWER:
try {
// Current State: OPEN
// Event: Successful service-specific authorization answer received
// Action: Provide Service
// New State: OPEN
listener.doAuthAnswerEvent(this, null, (AppAnswerEvent) event.getData());
}
catch (Exception e) {
// Current State: OPEN
// Event: ASR Received, client will comply with request to end the session
// Action: Send ASA with Result-Code = SUCCESS, Send STR
// New State: DISCON
setState(DISCONNECTED);
}
break;
case RECEIVE_FAILED_AUTH_ANSWER:
// Current State: OPEN
// Event: Failed Service-specific authorization answer received
// Action: Disconnect User/Device
// New State: IDLE
if (context != null) {
Request str = createSessionTermRequest();
context.disconnectUserOrDev(this, str);
session.send(str, this);
}
setState(IDLE);
break;
case RECEIVE_ABORT_SESSION_REQUEST:
// Current State: OPEN
// Event: ASR Received (client to take comply or not)
// Action: TBD
// New State: TBD (comply = DISCON, !comply = OPEN)
listener.doAbortSessionRequestEvent(this, (AbortSessionRequestImpl) event.getData());
break;
case SEND_SESSION_TERMINATION_REQUEST:
setState(DISCONNECTED);
break;
case TIMEOUT_EXPIRES:
// Current State: OPEN
// Event: Session-Timeout Expires on Access Device
// Action: Send STR
// New State: DISCON
// Current State: OPEN
// Event: Authorization-Lifetime + Auth-Grace-Period expires on access device
// Action: Send STR
// New State: DISCON
if (context != null) {
context.accessTimeoutElapses(this);
Request str = createSessionTermRequest();
context.disconnectUserOrDev(this, str);
session.send(str, this);
}
setState(DISCONNECTED);
break;
}
break;
}
case DISCONNECTED: {
switch ((Event.Type) event.getType()) {
case RECEIVE_ABORT_SESSION_REQUEST:
// Current State: DISCON
// Event: ASR Received
// Action: Send ASA
// New State: DISCON
listener.doAbortSessionRequestEvent(this, (AbortSessionRequest) event.getData());
break;
case RECEIVE_SESSION_TERINATION_ANSWER:
// Current State: DISCON
// Event: STA Received
// Action: Disconnect User/Device
// New State: IDLE
listener.doSessionTerminationAnswerEvent(this, ((SessionTermAnswerImpl) event.getData()));
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 && context.getAccessTimeout() > 0) {
cancelTsTimer();
startTsTimer();
}
}
}
catch (Throwable t) {
throw new InternalException(t);
}
return true;
}
public void receivedSuccessMessage(Request request, Answer answer) {
AnswerDelivery ad = new AnswerDelivery();
ad.session = this;
ad.request = request;
ad.answer = answer;
super.scheduler.execute(ad);
}
public void timeoutExpired(Request request) {
try {
//FIXME: should this also be async ?
handleEvent(new Event(Event.Type.RECEIVE_FAILED_AUTH_ANSWER, new AppRequestEventImpl(request)));
}
catch (Exception e) {
logger.debug("Can not handle timeout 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() throws IllegalArgumentException, InternalException {
try {
sendAndStateLock.lock();
sessionData.setTsTimerId(super.timerFacility.schedule(sessionData.getSessionId(), TIMER_NAME_TS, context.getAccessTimeout()));
}
finally {
sendAndStateLock.unlock();
}
}
protected void cancelTsTimer() {
try {
sendAndStateLock.lock();
Serializable timerId = sessionData.getTsTimerId();
if(timerId != null) {
super.timerFacility.cancel(timerId);
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);
if (context != null) {
try {
handleEvent(new Event(Event.Type.TIMEOUT_EXPIRES, null));
}
catch (Exception e) {
logger.debug("Can not handle event", e);
}
}
}
finally {
sendAndStateLock.unlock();
}
}
}
protected AbortSessionAnswer createAbortSessionAnswer(Answer answer) {
return new AbortSessionAnswerImpl(answer);
}
protected AbortSessionRequest createAbortSessionRequest(Request request) {
return new AbortSessionRequestImpl(request);
}
protected ReAuthAnswer createReAuthAnswer(Answer answer) {
return new ReAuthAnswerImpl(answer);
}
protected ReAuthRequest createReAuthRequest(Request request) {
return new ReAuthRequestImpl(request);
}
protected SessionTermAnswer createSessionTermAnswer(Answer answer) {
return new SessionTermAnswerImpl(answer);
}
protected SessionTermRequest createSessionTermRequest(Request request) {
return new SessionTermRequestImpl(request);
}
protected Request createSessionTermRequest() {
return session.createRequest(SESSION_TERMINATION_REQUEST, appId, sessionData.getDestinationRealm(), sessionData.getDestinationHost());
}
@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;
GqClientSessionImpl other = (GqClientSessionImpl) 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 {
GqClientSession session;
Request request;
public void run() {
try {
if (request.getCommandCode() == AbortSessionRequestImpl.code) {
handleEvent(new Event(Event.Type.RECEIVE_ABORT_SESSION_REQUEST, createAbortSessionRequest(request)));
}
else if (request.getCommandCode() == ReAuthRequestImpl.code) {
listener.doReAuthRequestEvent(session, createReAuthRequest(request));
}
else {
listener.doOtherEvent(session, factory.createAuthRequest(request), null);
}
}
catch (Exception e) {
logger.debug("Can not process received request", e);
}
}
}
private class AnswerDelivery implements Runnable {
GqClientSession session;
Answer answer;
Request request;
public void run() {
try {
sendAndStateLock.lock();
// FIXME: baranowb: this shouldn't be like that?
if (answer.getCommandCode() == factory.getAuthMessageCommandCode()) {
handleEvent(new Event(Event.Type.RECEIVE_AUTH_ANSWER, factory.createAuthAnswer(answer)));
}
else if (answer.getCommandCode() == SessionTermAnswerImpl.code) {
handleEvent(new Event(Event.Type.RECEIVE_SESSION_TERINATION_ANSWER, createSessionTermAnswer(answer)));
}
else {
listener.doOtherEvent(session, factory.createAuthRequest(request), new AppAnswerEventImpl(answer));
}
}
catch (Exception e) {
logger.debug("Can not process received message", e);
}
finally {
sendAndStateLock.unlock();
}
}
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.app.ro;
import java.io.Serializable;
import org.jdiameter.api.Request;
import org.jdiameter.common.api.app.AppSessionDataLocalImpl;
import org.jdiameter.common.api.app.ro.ClientRoSessionState;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ClientRoSessionDataLocalImpl extends AppSessionDataLocalImpl implements IClientRoSessionData {
protected boolean isEventBased = true;
protected boolean requestTypeSet = false;
protected ClientRoSessionState state = ClientRoSessionState.IDLE;
protected Serializable txTimerId;
//protected JCreditControlRequest txTimerRequest;
protected Request txTimerRequest;
// Event Based Buffer
//protected Message buffer = null;
protected Request buffer;
protected int gatheredRequestedAction = NON_INITIALIZED;
protected int gatheredCCFH = NON_INITIALIZED;
protected int gatheredDDFH = NON_INITIALIZED;
/**
*
*/
public ClientRoSessionDataLocalImpl() {
}
public boolean isEventBased() {
return isEventBased;
}
public void setEventBased(boolean isEventBased) {
this.isEventBased = isEventBased;
}
public boolean isRequestTypeSet() {
return requestTypeSet;
}
public void setRequestTypeSet(boolean requestTypeSet) {
this.requestTypeSet = requestTypeSet;
}
public ClientRoSessionState getClientRoSessionState() {
return state;
}
public void setClientRoSessionState(ClientRoSessionState state) {
this.state = state;
}
public Serializable getTxTimerId() {
return txTimerId;
}
public void setTxTimerId(Serializable txTimerId) {
this.txTimerId = txTimerId;
}
public Request getTxTimerRequest() {
return txTimerRequest;
}
public void setTxTimerRequest(Request txTimerRequest) {
this.txTimerRequest = txTimerRequest;
}
public Request getBuffer() {
return buffer;
}
public void setBuffer(Request buffer) {
this.buffer = buffer;
}
public int getGatheredRequestedAction() {
return gatheredRequestedAction;
}
public void setGatheredRequestedAction(int gatheredRequestedAction) {
this.gatheredRequestedAction = gatheredRequestedAction;
}
public int getGatheredCCFH() {
return gatheredCCFH;
}
public void setGatheredCCFH(int gatheredCCFH) {
this.gatheredCCFH = gatheredCCFH;
}
public int getGatheredDDFH() {
return gatheredDDFH;
}
public void setGatheredDDFH(int gatheredDDFH) {
this.gatheredDDFH = gatheredDDFH;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.app.ro;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.jdiameter.api.Answer;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.EventListener;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Message;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.app.AppAnswerEvent;
import org.jdiameter.api.app.AppEvent;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.api.app.StateChangeListener;
import org.jdiameter.api.app.StateEvent;
import org.jdiameter.api.auth.events.ReAuthAnswer;
import org.jdiameter.api.auth.events.ReAuthRequest;
import org.jdiameter.api.ro.ClientRoSession;
import org.jdiameter.api.ro.ClientRoSessionListener;
import org.jdiameter.api.ro.events.RoCreditControlAnswer;
import org.jdiameter.api.ro.events.RoCreditControlRequest;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.client.api.parser.IMessageParser;
import org.jdiameter.client.api.parser.ParseException;
import org.jdiameter.client.impl.app.ro.Event.Type;
import org.jdiameter.common.api.app.IAppSessionState;
import org.jdiameter.common.api.app.ro.ClientRoSessionState;
import org.jdiameter.common.api.app.ro.IClientRoSessionContext;
import org.jdiameter.common.api.app.ro.IRoMessageFactory;
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.ro.AppRoSessionImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Client Credit-Control Application session implementation
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class ClientRoSessionImpl extends AppRoSessionImpl implements ClientRoSession, NetworkReqListener, EventListener<Request, Answer> {
private static final Logger logger = LoggerFactory.getLogger(ClientRoSessionImpl.class);
// Session State Handling ---------------------------------------------------
protected IClientRoSessionData sessionData;
protected Lock sendAndStateLock = new ReentrantLock();
// Factories and Listeners --------------------------------------------------
protected transient IRoMessageFactory factory;
protected transient ClientRoSessionListener listener;
protected transient IClientRoSessionContext context;
protected transient IMessageParser parser;
// Tx Timer -----------------------------------------------------------------
protected final static String TX_TIMER_NAME = "Ro_CLIENT_TX_TIMER";
protected static final long TX_TIMER_DEFAULT_VALUE = 30 * 60 * 1000; // miliseconds
protected long[] authAppIds = new long[] { 4 };
// Requested Action + Credit-Control and Direct-Debiting Failure-Handling ---
protected static final int CCFH_TERMINATE = 0;
protected static final int CCFH_CONTINUE = 1;
protected static final int CCFH_RETRY_AND_TERMINATE = 2;
private static final int DDFH_TERMINATE_OR_BUFFER = 0;
private static final int DDFH_CONTINUE = 1;
// CC-Request-Type Values ---------------------------------------------------
private static final int DIRECT_DEBITING = 0;
private static final int REFUND_ACCOUNT = 1;
private static final int CHECK_BALANCE = 2;
private static final int PRICE_ENQUIRY = 3;
private static final int EVENT_REQUEST = 4;
// Error Codes --------------------------------------------------------------
private static final long END_USER_SERVICE_DENIED = 4010;
private static final long CREDIT_CONTROL_NOT_APPLICABLE = 4011;
private static final long USER_UNKNOWN = 5030;
private static final long DIAMETER_UNABLE_TO_DELIVER = 3002L;
private static final long DIAMETER_TOO_BUSY = 3004L;
private static final long DIAMETER_LOOP_DETECTED = 3005L;
protected static final Set<Long> temporaryErrorCodes;
static {
HashSet<Long> tmp = new HashSet<Long>();
tmp.add(DIAMETER_UNABLE_TO_DELIVER);
tmp.add(DIAMETER_TOO_BUSY);
tmp.add(DIAMETER_LOOP_DETECTED);
temporaryErrorCodes = Collections.unmodifiableSet(tmp);
}
// Session Based Queue
protected ArrayList<Event> eventQueue = new ArrayList<Event>();
public ClientRoSessionImpl(IClientRoSessionData sessionData, IRoMessageFactory fct, ISessionFactory sf, ClientRoSessionListener lst,IClientRoSessionContext 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");
}
if (sessionData == null) {
throw new IllegalArgumentException("SessionData can not be null");
}
this.context = (IClientRoSessionContext)ctx;
this.sessionData = sessionData;
this.authAppIds = fct.getApplicationIds();
this.listener = lst;
this.factory = fct;
IContainer icontainer = sf.getContainer();
this.parser = icontainer.getAssemblerFacility().getComponentInstance(IMessageParser.class);
super.addStateChangeNotification(stLst);
}
protected int getLocalCCFH() {
return sessionData.getGatheredCCFH() >= 0 ? sessionData.getGatheredCCFH() : context.getDefaultCCFHValue();
}
protected int getLocalDDFH() {
return sessionData.getGatheredDDFH() >= 0 ? sessionData.getGatheredDDFH() : context.getDefaultDDFHValue();
}
public void sendCreditControlRequest(RoCreditControlRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
try {
extractFHAVPs(request, null);
this.handleEvent(new Event(true, request, null));
}
catch (AvpDataException e) {
throw new InternalException(e);
}
}
public void sendReAuthAnswer(ReAuthAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
this.handleEvent(new Event(Event.Type.SEND_RAA, null, answer));
}
public boolean isStateless() {
return false;
}
public boolean isEventBased() {
return sessionData.isEventBased();
}
@SuppressWarnings("unchecked")
public <E> E getState(Class<E> stateType) {
return stateType == ClientRoSessionState.class ? (E) sessionData.getClientRoSessionState() : null;
}
public boolean handleEvent(StateEvent event) throws InternalException, OverloadException {
return this.isEventBased() ? handleEventForEventBased(event) : handleEventForSessionBased(event);
}
protected boolean handleEventForEventBased(StateEvent event) throws InternalException, OverloadException {
try {
sendAndStateLock.lock();
ClientRoSessionState state = sessionData.getClientRoSessionState();
Event localEvent = (Event) event;
Event.Type eventType = (Type) localEvent.getType();
switch (state) {
case IDLE:
switch (eventType) {
case SEND_EVENT_REQUEST:
// Current State: IDLE
// Event: Client or device requests a one-time service
// Action: Send CC event request, start Tx
// New State: PENDING_E
startTx((RoCreditControlRequest) localEvent.getRequest());
setState(ClientRoSessionState.PENDING_EVENT);
try {
dispatchEvent(localEvent.getRequest());
}
catch (Exception e) {
// This handles failure to send in PendingI state in FSM table
logger.debug("Failure handling send event request", e);
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
case PENDING_EVENT:
switch (eventType) {
case RECEIVE_EVENT_ANSWER:
AppAnswerEvent answer = (AppAnswerEvent) localEvent.getAnswer();
try {
long resultCode = answer.getResultCodeAvp().getUnsigned32();
if (isSuccess(resultCode)) {
// Current State: PENDING_E
// Event: Successful CC event answer received
// Action: Grant service to end user
// New State: IDLE
setState(ClientRoSessionState.IDLE, false);
}
if (isProvisional(resultCode) || isFailure(resultCode)) {
handleFailureMessage((RoCreditControlAnswer) answer, (RoCreditControlRequest) localEvent.getRequest(), eventType);
}
deliverRoAnswer((RoCreditControlRequest) localEvent.getRequest(), (RoCreditControlAnswer) localEvent.getAnswer());
}
catch (AvpDataException e) {
logger.debug("Failure handling received answer event", e);
setState(ClientRoSessionState.IDLE, false);
}
break;
case Tx_TIMER_FIRED:
handleTxExpires(localEvent.getRequest().getMessage());
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
case PENDING_BUFFERED:
switch (eventType) {
case RECEIVE_EVENT_ANSWER:
// Current State: PENDING_B
// Event: Successful CC answer received
// Action: Delete request
// New State: IDLE
setState(ClientRoSessionState.IDLE, false);
sessionData.setBuffer(null);
deliverRoAnswer((RoCreditControlRequest) localEvent.getRequest(), (RoCreditControlAnswer) localEvent.getAnswer());
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
dispatch();
return true;
}
catch (Exception e) {
throw new InternalException(e);
}
finally {
sendAndStateLock.unlock();
}
}
protected boolean handleEventForSessionBased(StateEvent event) throws InternalException, OverloadException {
try {
sendAndStateLock.lock();
ClientRoSessionState state = sessionData.getClientRoSessionState();
Event localEvent = (Event) event;
Event.Type eventType = (Type) localEvent.getType();
switch (state) {
case IDLE:
switch (eventType) {
case SEND_INITIAL_REQUEST:
// Current State: IDLE
// Event: Client or device requests access/service
// Action: Send CC initial request, start Tx
// New State: PENDING_I
startTx((RoCreditControlRequest) localEvent.getRequest());
setState(ClientRoSessionState.PENDING_INITIAL);
try {
dispatchEvent(localEvent.getRequest());
}
catch (Exception e) {
// This handles failure to send in PendingI state in FSM table
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
case PENDING_INITIAL:
AppAnswerEvent answer = (AppAnswerEvent) localEvent.getAnswer();
switch (eventType) {
case RECEIVED_INITIAL_ANSWER:
long resultCode = answer.getResultCodeAvp().getUnsigned32();
if (isSuccess(resultCode)) {
// Current State: PENDING_I
// Event: Successful CC initial answer received
// Action: Stop Tx
// New State: OPEN
stopTx();
setState(ClientRoSessionState.OPEN);
}
else if (isProvisional(resultCode) || isFailure(resultCode)) {
handleFailureMessage((RoCreditControlAnswer) answer, (RoCreditControlRequest) localEvent.getRequest(), eventType);
}
deliverRoAnswer((RoCreditControlRequest) localEvent.getRequest(), (RoCreditControlAnswer) localEvent.getAnswer());
break;
case Tx_TIMER_FIRED:
handleTxExpires(localEvent.getRequest().getMessage());
break;
case SEND_UPDATE_REQUEST:
case SEND_TERMINATE_REQUEST:
// Current State: PENDING_I
// Event: User service terminated
// Action: Queue termination event
// New State: PENDING_I
// Current State: PENDING_I
// Event: Change in rating condition
// Action: Queue changed rating condition event
// New State: PENDING_I
eventQueue.add(localEvent);
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
case OPEN:
switch (eventType) {
case SEND_UPDATE_REQUEST:
// Current State: OPEN
// Event: Granted unit elapses and no final unit indication received
// Action: Send CC update request, start Tx
// New State: PENDING_U
// Current State: OPEN
// Event: Change in rating condition in queue
// Action: Send CC update request, start Tx
// New State: PENDING_U
// Current State: OPEN
// Event: Change in rating condition or Validity-Time elapses
// Action: Send CC update request, start Tx
// New State: PENDING_U
// Current State: OPEN
// Event: RAR received
// Action: Send RAA followed by CC update request, start Tx
// New State: PENDING_U
startTx((RoCreditControlRequest) localEvent.getRequest());
setState(ClientRoSessionState.PENDING_UPDATE);
try {
dispatchEvent(localEvent.getRequest());
}
catch (Exception e) {
// This handles failure to send in PendingI state in FSM table
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
case SEND_TERMINATE_REQUEST:
// Current State: OPEN
// Event: Granted unit elapses and final unit action equal to TERMINATE received
// Action: Terminate end user�s service, send CC termination request
// New State: PENDING_T
// Current State: OPEN
// Event: Service terminated in queue
// Action: Send CC termination request
// New State: PENDING_T
// Current State: OPEN
// Event: User service terminated
// Action: Send CC termination request
// New State: PENDING_T
setState(ClientRoSessionState.PENDING_TERMINATION);
try {
dispatchEvent(localEvent.getRequest());
}
catch (Exception e) {
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
case RECEIVED_RAR:
deliverRAR((ReAuthRequest) localEvent.getRequest());
break;
case SEND_RAA:
try {
dispatchEvent(localEvent.getAnswer());
}
catch (Exception e) {
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
case PENDING_UPDATE:
answer = (AppAnswerEvent) localEvent.getAnswer();
switch (eventType) {
case RECEIVED_UPDATE_ANSWER:
long resultCode = answer.getResultCodeAvp().getUnsigned32();
if (isSuccess(resultCode)) {
// Current State: PENDING_U
// Event: Successful CC update answer received
// Action: Stop Tx
// New State: OPEN
stopTx();
setState(ClientRoSessionState.OPEN);
}
else if (isProvisional(resultCode) || isFailure(resultCode)) {
handleFailureMessage((RoCreditControlAnswer) answer, (RoCreditControlRequest) localEvent.getRequest(), eventType);
}
deliverRoAnswer((RoCreditControlRequest) localEvent.getRequest(), (RoCreditControlAnswer) localEvent.getAnswer());
break;
case Tx_TIMER_FIRED:
handleTxExpires(localEvent.getRequest().getMessage());
break;
case SEND_UPDATE_REQUEST:
case SEND_TERMINATE_REQUEST:
// Current State: PENDING_U
// Event: User service terminated
// Action: Queue termination event
// New State: PENDING_U
// Current State: PENDING_U
// Event: Change in rating condition
// Action: Queue changed rating condition event
// New State: PENDING_U
eventQueue.add(localEvent);
break;
case RECEIVED_RAR:
deliverRAR((ReAuthRequest) localEvent.getRequest());
break;
case SEND_RAA:
// Current State: PENDING_U
// Event: RAR received
// Action: Send RAA
// New State: PENDING_U
try {
dispatchEvent(localEvent.getAnswer());
}
catch (Exception e) {
handleSendFailure(e, eventType, localEvent.getRequest().getMessage());
}
break;
}
break;
case PENDING_TERMINATION:
switch (eventType) {
case SEND_UPDATE_REQUEST:
try {
// Current State: PENDING_T
// Event: Change in rating condition
// Action: -
// New State: PENDING_T
dispatchEvent(localEvent.getRequest());
// No transition
}
catch (Exception e) {
// This handles failure to send in PendingI state in FSM table
// handleSendFailure(e, eventType);
}
break;
case RECEIVED_TERMINATED_ANSWER:
// Current State: PENDING_T
// Event: Successful CC termination answer received
// Action: -
// New State: IDLE
// Current State: PENDING_T
// Event: Failure to send, temporary error, or failed answer
// Action: -
// New State: IDLE
//FIXME: Alex broke this, setting back "true" ?
//setState(ClientRoSessionState.IDLE, false);
deliverRoAnswer((RoCreditControlRequest) localEvent.getRequest(), (RoCreditControlAnswer) localEvent.getAnswer());
setState(ClientRoSessionState.IDLE, true);
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
break;
default:
// any other state is bad
setState(ClientRoSessionState.IDLE, true);
}
dispatch();
return true;
}
catch (Exception e) {
throw new InternalException(e);
}
finally {
sendAndStateLock.unlock();
}
}
public Answer processRequest(Request request) {
RequestDelivery rd = new RequestDelivery();
rd.session = this;
rd.request = request;
super.scheduler.execute(rd);
return null;
}
public void receivedSuccessMessage(Request request, Answer answer) {
AnswerDelivery ad = new AnswerDelivery();
ad.session = this;
ad.request = request;
ad.answer = answer;
super.scheduler.execute(ad);
}
public void timeoutExpired(Request request) {
if(request.getCommandCode()== RoCreditControlAnswer.code) {
try {
sendAndStateLock.lock();
handleSendFailure(null, null, request);
}
catch (Exception e) {
logger.debug("Failure processing timeout message for request", e);
}
finally {
sendAndStateLock.unlock();
}
}
}
protected void startTx(RoCreditControlRequest request) {
long txTimerValue = context.getDefaultTxTimerValue();
if (txTimerValue < 0) {
txTimerValue = TX_TIMER_DEFAULT_VALUE;
}
stopTx();
logger.debug("Scheduling TX Timer {}", txTimerValue);
//this.txFuture = scheduler.schedule(new TxTimerTask(this, request), txTimerValue, TimeUnit.SECONDS);
try {
sessionData.setTxTimerRequest((Request) request.getMessage());
sessionData.setTxTimerId(this.timerFacility.schedule(this.sessionData.getSessionId(), TX_TIMER_NAME, TX_TIMER_DEFAULT_VALUE));
}
catch (Exception e) {
throw new IllegalArgumentException("Failed to store request.", e);
}
}
protected void stopTx() {
Serializable txTimerId = this.sessionData.getTxTimerId();
if(txTimerId != null) {
timerFacility.cancel(txTimerId);
sessionData.setTxTimerId(null);
sessionData.setTxTimerRequest(null);
}
}
/* (non-Javadoc)
* @see org.jdiameter.common.impl.app.AppSessionImpl#onTimer(java.lang.String)
*/
@Override
public void onTimer(String timerName) {
if(timerName.equals(TX_TIMER_NAME)) {
new TxTimerTask(this, sessionData.getTxTimerRequest()).run();
}
}
protected void setState(ClientRoSessionState newState) {
setState(newState, true);
}
@SuppressWarnings("unchecked")
protected void setState(ClientRoSessionState newState, boolean release) {
try {
IAppSessionState state = sessionData.getClientRoSessionState();
IAppSessionState oldState = state;
sessionData.setClientRoSessionState(newState);
for (StateChangeListener i : stateListeners) {
i.stateChanged(this,(Enum) oldState, (Enum) newState);
}
if (newState == ClientRoSessionState.IDLE) {
if (release) {
this.release();
}
stopTx();
}
}
catch (Exception e) {
if(logger.isDebugEnabled()) {
logger.debug("Failure switching to state " + sessionData.getClientRoSessionState() + " (release=" + release + ")", e);
}
}
}
@Override
public void release() {
if (isValid()) {
try {
this.sendAndStateLock.lock();
this.stopTx();
super.release();
}
catch (Exception e) {
logger.debug("Failed to release session", e);
}
finally {
this.sendAndStateLock.unlock();
}
}
else {
logger.debug("Trying to release an already invalid session, with Session ID '{}'", getSessionId());
}
}
protected void handleSendFailure(Exception e, Event.Type eventType, Message request) throws Exception {
logger.debug("Failed to send message, type: {} message: {}, failure: {}", new Object[]{eventType, request, e != null ? e.getLocalizedMessage() : ""});
try {
ClientRoSessionState state = sessionData.getClientRoSessionState();
// Event Based ----------------------------------------------------------
if (isEventBased()) {
int gatheredRequestedAction = sessionData.getGatheredRequestedAction();
switch (state) {
case PENDING_EVENT:
if (gatheredRequestedAction == CHECK_BALANCE || gatheredRequestedAction == PRICE_ENQUIRY) {
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action CHECK_BALANCE or PRICE_ENQUIRY
// Action: Indicate service error
// New State: IDLE
setState(ClientRoSessionState.IDLE);
context.indicateServiceError(this);
}
else if (gatheredRequestedAction == DIRECT_DEBITING) {
switch(getLocalDDFH()) {
case DDFH_TERMINATE_OR_BUFFER:
// Current State: PENDING_E
// Event: Failure to send; request action DIRECT_DEBITING; DDFH equal to TERMINATE_OR_BUFFER
// Action: Store request with T-flag
// New State: IDLE
request.setReTransmitted(true);
sessionData.setBuffer((Request) request);
setState(ClientRoSessionState.IDLE, false);
break;
case DDFH_CONTINUE:
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action DIRECT_DEBITING; DDFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnDeliverFailure(this, request);
break;
default:
logger.warn("Invalid Direct-Debiting-Failure-Handling AVP value {}", getLocalDDFH());
}
}
else if (gatheredRequestedAction == REFUND_ACCOUNT) {
// Current State: PENDING_E
// Event: Failure to send or Tx expired; requested action REFUND_ACCOUNT
// Action: Store request with T-flag
// New State: IDLE
setState(ClientRoSessionState.IDLE, false);
request.setReTransmitted(true);
sessionData.setBuffer((Request) request);
}
else {
logger.warn("Invalid Requested-Action AVP value {}", gatheredRequestedAction);
}
break;
case PENDING_BUFFERED:
// Current State: PENDING_B
// Event: Failure to send or temporary error
// Action: -
// New State: IDLE
setState(ClientRoSessionState.IDLE, false);
sessionData.setBuffer(null);// FIXME: Action does not mention, but ...
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
break;
}
}
// Session Based --------------------------------------------------------
else {
switch (getLocalCCFH()) {
case CCFH_CONTINUE:
// Current State: PENDING_I
// Event: Failure to send, or temporary error and CCFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
// Current State: PENDING_U
// Event: Failure to send, or temporary error and CCFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
setState(ClientRoSessionState.IDLE, false);
this.context.grantAccessOnDeliverFailure(this, request);
break;
default:
// Current State: PENDING_I
// Event: Failure to send, or temporary error and CCFH equal to TERMINATE or to RETRY_AND_TERMINATE
// Action: Terminate end user�s service
// New State: IDLE
// Current State: PENDING_U
// Event: Failure to send, or temporary error and CCFH equal to TERMINATE or to RETRY_AND_TERMINATE
// Action: Terminate end user�s service
// New State: IDLE
this.context.denyAccessOnDeliverFailure(this, request);
setState(ClientRoSessionState.IDLE, true);
break;
}
}
}
finally {
dispatch();
}
}
protected void handleFailureMessage(RoCreditControlAnswer event, RoCreditControlRequest request, Event.Type eventType) {
try {
// Event Based ----------------------------------------------------------
long resultCode = event.getResultCodeAvp().getUnsigned32();
ClientRoSessionState state = sessionData.getClientRoSessionState();
Serializable txTimerId = sessionData.getTxTimerId();
if (isEventBased()) {
int gatheredRequestedAction = sessionData.getGatheredRequestedAction();
switch (state) {
case PENDING_EVENT:
if (resultCode == END_USER_SERVICE_DENIED || resultCode == USER_UNKNOWN) {
if(txTimerId != null) {
// Current State: PENDING_E
// Event: CC event answer received with result code END_USER_SERVICE_DENIED or USER_UNKNOWN and Tx running
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
deliverRoAnswer(request, event);
setState(ClientRoSessionState.IDLE);
}
else if(gatheredRequestedAction == DIRECT_DEBITING && txTimerId == null) {
// Current State: PENDING_E
// Event: Failed answer or answer received with result code END_USER_SERVICE DENIED or USER_UNKNOWN; requested action DIRECT_DEBITING; Tx expired
// Action: -
// New State: IDLE
setState(ClientRoSessionState.IDLE);
}
}
else if (resultCode == CREDIT_CONTROL_NOT_APPLICABLE && gatheredRequestedAction == DIRECT_DEBITING) {
// Current State: PENDING_E
// Event: CC event answer received with result code CREDIT_CONTROL_NOT_APPLICABLE; requested action DIRECT_DEBITING
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
deliverRoAnswer(request, event);
setState(ClientRoSessionState.IDLE);
}
else if (temporaryErrorCodes.contains(resultCode)) {
if (gatheredRequestedAction == CHECK_BALANCE || gatheredRequestedAction == PRICE_ENQUIRY) {
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action CHECK_BALANCE or PRICE_ENQUIRY
// Action: Indicate service error
// New State: IDLE
context.indicateServiceError(this);
deliverRoAnswer(request, event);
setState(ClientRoSessionState.IDLE);
}
else if (gatheredRequestedAction == DIRECT_DEBITING) {
if(getLocalDDFH() == DDFH_CONTINUE) {
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action DIRECT_DEBITING; DDFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
deliverRoAnswer(request, event);
setState(ClientRoSessionState.IDLE);
}
else if (getLocalDDFH() == DDFH_TERMINATE_OR_BUFFER && txTimerId != null) {
// Current State: PENDING_E
// Event: Failed CC event answer received or temporary error; requested action DIRECT_DEBITING; DDFH equal to TERMINATE_OR_BUFFER and Tx running
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
deliverRoAnswer(request, event);
setState(ClientRoSessionState.IDLE);
}
}
else if (gatheredRequestedAction == REFUND_ACCOUNT) {
// Current State: PENDING_E
// Event: Temporary error, and requested action REFUND_ACCOUNT
// Action: Store request
// New State: IDLE
sessionData.setBuffer((Request) request);
setState(ClientRoSessionState.IDLE, false);
}
else {
logger.warn("Invalid combination for Ro Client FSM: State {}, Result-Code {}, Requested-Action {}, DDFH {}, Tx {}", new Object[]{state, resultCode, gatheredRequestedAction, getLocalDDFH(), txTimerId});
}
}
else { // Failure
if (gatheredRequestedAction == CHECK_BALANCE || gatheredRequestedAction == PRICE_ENQUIRY) {
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action CHECK_BALANCE or PRICE_ENQUIRY
// Action: Indicate service error
// New State: IDLE
context.indicateServiceError(this);
deliverRoAnswer(request, event);
setState(ClientRoSessionState.IDLE);
}
else if (gatheredRequestedAction == DIRECT_DEBITING) {
if(getLocalDDFH() == DDFH_CONTINUE) {
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action DIRECT_DEBITING; DDFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
deliverRoAnswer(request, event);
setState(ClientRoSessionState.IDLE);
}
else if (getLocalDDFH() == DDFH_TERMINATE_OR_BUFFER && txTimerId != null) {
// Current State: PENDING_E
// Event: Failed CC event answer received or temporary error; requested action DIRECT_DEBITING; DDFH equal to TERMINATE_OR_BUFFER and Tx running
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
deliverRoAnswer(request, event);
setState(ClientRoSessionState.IDLE);
}
}
else if (gatheredRequestedAction == REFUND_ACCOUNT) {
// Current State: PENDING_E
// Event: Failed CC event answer received; requested action REFUND_ACCOUNT
// Action: Indicate service error and delete request
// New State: IDLE
sessionData.setBuffer(null);
context.indicateServiceError(this);
deliverRoAnswer(request, event);
setState(ClientRoSessionState.IDLE);
}
else {
logger.warn("Invalid combination for Ro Client FSM: State {}, Result-Code {}, Requested-Action {}, DDFH {}, Tx {}", new Object[]{state, resultCode, gatheredRequestedAction, getLocalDDFH(), txTimerId});
}
}
break;
case PENDING_BUFFERED:
// Current State: PENDING_B
// Event: Failed CC answer received
// Action: Delete request
// New State: IDLE
sessionData.setBuffer(null);
setState(ClientRoSessionState.IDLE, false);
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
}
}
// Session Based --------------------------------------------------------
else {
switch (state) {
case PENDING_INITIAL:
if (resultCode == CREDIT_CONTROL_NOT_APPLICABLE) {
// Current State: PENDING_I
// Event: CC initial answer received with result code equal to CREDIT_CONTROL_NOT_APPLICABLE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
setState(ClientRoSessionState.IDLE, false);
}
else if ((resultCode == END_USER_SERVICE_DENIED) || (resultCode == USER_UNKNOWN)) {
// Current State: PENDING_I
// Event: CC initial answer received with result code END_USER_SERVICE_DENIED or USER_UNKNOWN
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
setState(ClientRoSessionState.IDLE, false);
}
else {
// Temporary errors and others
switch (getLocalCCFH()) {
case CCFH_CONTINUE:
// Current State: PENDING_I
// Event: Failed CC initial answer received and CCFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
setState(ClientRoSessionState.IDLE, false);
break;
case CCFH_TERMINATE:
case CCFH_RETRY_AND_TERMINATE:
// Current State: PENDING_I
// Event: Failed CC initial answer received and CCFH equal to TERMINATE or to RETRY_AND_TERMINATE
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
setState(ClientRoSessionState.IDLE, false);
break;
default:
logger.warn("Invalid value for CCFH: {}", getLocalCCFH());
break;
}
}
break;
case PENDING_UPDATE:
if (resultCode == CREDIT_CONTROL_NOT_APPLICABLE) {
// Current State: PENDING_U
// Event: CC update answer received with result code equal to CREDIT_CONTROL_NOT_APPLICABLE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
setState(ClientRoSessionState.IDLE, false);
}
else if (resultCode == END_USER_SERVICE_DENIED) {
// Current State: PENDING_U
// Event: CC update answer received with result code END_USER_SERVICE_DENIED
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
setState(ClientRoSessionState.IDLE, false);
}
else {
// Temporary errors and others
switch (getLocalCCFH()) {
case CCFH_CONTINUE:
// Current State: PENDING_U
// Event: Failed CC update answer received and CCFH equal to CONTINUE
// Action: Grant service to end user
// New State: IDLE
context.grantAccessOnFailureMessage(this);
setState(ClientRoSessionState.IDLE, false);
break;
case CCFH_TERMINATE:
case CCFH_RETRY_AND_TERMINATE:
// Current State: PENDING_U
// Event: Failed CC update answer received and CCFH equal to CONTINUE or to RETRY_AND_CONTINUE
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnFailureMessage(this);
setState(ClientRoSessionState.IDLE, false);
break;
default:
logger.warn("Invalid value for CCFH: " + getLocalCCFH());
break;
}
}
break;
default:
logger.warn("Wrong event type ({}) on state {}", eventType, state);
}
}
}
catch (Exception e) {
if(logger.isDebugEnabled()) {
logger.debug("Failure handling failure message for Event " + event + " (" + eventType + ") and Request " + request, e);
}
}
}
protected void handleTxExpires(Message message) {
// Event Based ----------------------------------------------------------
ClientRoSessionState state = sessionData.getClientRoSessionState();
if (isEventBased()) {
int gatheredRequestedAction = sessionData.getGatheredRequestedAction();
if (gatheredRequestedAction == CHECK_BALANCE || gatheredRequestedAction == PRICE_ENQUIRY) {
// Current State: PENDING_E
// Event: Failure to send, temporary error, failed CC event answer received or Tx expired; requested action CHECK_BALANCE or PRICE_ENQUIRY
// Action: Indicate service error
// New State: IDLE
context.indicateServiceError(this);
setState(ClientRoSessionState.IDLE);
}
else if (gatheredRequestedAction == DIRECT_DEBITING) {
if(sessionData.getGatheredDDFH() == DDFH_TERMINATE_OR_BUFFER) {
// Current State: PENDING_E
// Event: Temporary error; requested action DIRECT_DEBITING; DDFH equal to TERMINATE_OR_BUFFER; Tx expired
// Action: Store request
// New State: IDLE
sessionData.setBuffer((Request) message);
setState(ClientRoSessionState.IDLE, false);
}
else {
// Current State: PENDING_E
// Event: Tx expired; requested action DIRECT_DEBITING
// Action: Grant service to end user
// New State: PENDING_E
context.grantAccessOnTxExpire(this);
setState(ClientRoSessionState.PENDING_EVENT);
}
}
else if (gatheredRequestedAction == REFUND_ACCOUNT) {
// Current State: PENDING_E
// Event: Failure to send or Tx expired; requested action REFUND_ACCOUNT
// Action: Store request with T-flag
// New State: IDLE
message.setReTransmitted(true);
sessionData.setBuffer((Request) message);
setState(ClientRoSessionState.IDLE, false);
}
}
// Session Based --------------------------------------------------------
else {
switch (state) {
case PENDING_INITIAL:
switch (getLocalCCFH()) {
case CCFH_CONTINUE:
case CCFH_RETRY_AND_TERMINATE:
// Current State: PENDING_I
// Event: Tx expired and CCFH equal to CONTINUE or to RETRY_AND_TERMINATE
// Action: Grant service to end user
// New State: PENDING_I
context.grantAccessOnTxExpire(this);
break;
case CCFH_TERMINATE:
// Current State: PENDING_I
// Event: Tx expired and CCFH equal to TERMINATE
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnTxExpire(this);
setState(ClientRoSessionState.IDLE, true);
break;
default:
logger.warn("Invalid value for CCFH: " + getLocalCCFH());
break;
}
break;
case PENDING_UPDATE:
switch (getLocalCCFH()) {
case CCFH_CONTINUE:
case CCFH_RETRY_AND_TERMINATE:
// Current State: PENDING_U
// Event: Tx expired and CCFH equal to CONTINUE or to RETRY_AND_TERMINATE
// Action: Grant service to end user
// New State: PENDING_U
context.grantAccessOnTxExpire(this);
break;
case CCFH_TERMINATE:
// Current State: PENDING_U
// Event: Tx expired and CCFH equal to TERMINATE
// Action: Terminate end user�s service
// New State: IDLE
context.denyAccessOnTxExpire(this);
setState(ClientRoSessionState.IDLE, true);
break;
default:
logger.error("Bad value of CCFH: " + getLocalCCFH());
break;
}
break;
default:
logger.error("Unknown state (" + sessionData.getClientRoSessionState() + ") on txExpire");
break;
}
}
}
/**
* This makes checks on queue, moves it to proper state if event there is
* present on Open state ;]
*/
protected void dispatch() {
// Event Based ----------------------------------------------------------
if (isEventBased()) {
// Current State: IDLE
// Event: Request in storage
// Action: Send stored request
// New State: PENDING_B
Request buffer = sessionData.getBuffer();
if (buffer != null) {
setState(ClientRoSessionState.PENDING_BUFFERED);
try {
dispatchEvent(new AppRequestEventImpl(buffer));
}
catch (Exception e) {
try {
handleSendFailure(e, Event.Type.SEND_EVENT_REQUEST,buffer);
}
catch (Exception e1) {
logger.error("Failure handling buffer send failure", e1);
}
}
}
}
// Session Based --------------------------------------------------------
else {
if (sessionData.getClientRoSessionState() == ClientRoSessionState.OPEN && eventQueue.size() > 0) {
try {
this.handleEvent(eventQueue.remove(0));
}
catch (Exception e) {
logger.error("Failure handling queued event", e);
}
}
}
}
protected void deliverRoAnswer(RoCreditControlRequest request, RoCreditControlAnswer answer) {
try {
if(isValid()) {
listener.doCreditControlAnswer(this, request, answer);
}
}
catch (Exception e) {
logger.warn("Failure delivering Ro Answer", e);
}
}
protected void extractFHAVPs(RoCreditControlRequest request, RoCreditControlAnswer answer) throws AvpDataException {
if (answer != null) {
try {
if (answer.isCreditControlFailureHandlingAVPPresent()) {
sessionData.setGatheredCCFH(answer.getCredidControlFailureHandlingAVPValue());
}
}
catch (Exception e) {
logger.debug("Failure trying to obtain Credit-Control-Failure-Handling AVP value", e);
}
try {
if (answer.isDirectDebitingFailureHandlingAVPPresent()) {
sessionData.setGatheredDDFH(answer.getDirectDebitingFailureHandlingAVPValue());
}
}
catch (Exception e) {
logger.debug("Failure trying to obtain Direct-Debit-Failure-Handling AVP value", e);
}
if(!sessionData.isRequestTypeSet()) {
sessionData.setRequestTypeSet(true);
// No need to check if it exists.. it must, if not fail with exception
sessionData.setEventBased(answer.getRequestTypeAVPValue() == EVENT_REQUEST);
}
}
else if (request != null) {
try {
if (request.isRequestedActionAVPPresent()) {
sessionData.setGatheredRequestedAction(request.getRequestedActionAVPValue());
}
}
catch (Exception e) {
logger.debug("Failure trying to obtain Request-Action AVP value", e);
}
if(!sessionData.isRequestTypeSet()) {
sessionData.setRequestTypeSet(true);
// No need to check if it exists.. it must, if not fail with exception
sessionData.setEventBased(request.getRequestTypeAVPValue() == EVENT_REQUEST);
}
}
}
protected void deliverRAR(ReAuthRequest request) {
try {
listener.doReAuthRequest(this, request);
}
catch (Exception e) {
logger.debug("Failure delivering RAR", e);
}
}
protected void dispatchEvent(AppEvent event) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
session.send(event.getMessage(), this);
}
protected boolean isProvisional(long resultCode) {
return resultCode >= 1000 && resultCode < 2000;
}
protected boolean isSuccess(long resultCode) {
return resultCode >= 2000 && resultCode < 3000;
}
protected boolean isFailure(long code) {
return (!isProvisional(code) && !isSuccess(code) && ((code >= 3000 && /*code < 4000) || (code >= 5000 &&*/ code < 6000)) && !temporaryErrorCodes.contains(code));
}
/* (non-Javadoc)
* @see org.jdiameter.common.impl.app.AppSessionImpl#isReplicable()
*/
@Override
public boolean isReplicable() {
return true;
}
private class TxTimerTask implements Runnable {
private ClientRoSession session = null;
private Request request = null;
private TxTimerTask(ClientRoSession session, Request request) {
super();
this.session = session;
this.request = request;
}
public void run() {
try {
sendAndStateLock.lock();
logger.debug("Fired TX Timer");
sessionData.setTxTimerId(null);
sessionData.setTxTimerRequest(null);
try {
context.txTimerExpired(session);
}
catch (Exception e) {
logger.debug("Failure handling TX Timer Expired", e);
}
RoCreditControlRequest req = factory.createCreditControlRequest(request);
handleEvent(new Event(Event.Type.Tx_TIMER_FIRED, req, null));
}
catch (InternalException e) {
logger.error("Internal Exception", e);
}
catch (OverloadException e) {
logger.error("Overload Exception", e);
}
catch (Exception e) {
logger.error("Exception", e);
}
finally {
sendAndStateLock.unlock();
}
}
}
private final Message messageFromBuffer(ByteBuffer request) throws InternalException {
if (request != null) {
Message m;
try {
m = parser.createMessage(request);
return m;
}
catch (AvpDataException e) {
throw new InternalException("Failed to decode message.", e);
}
}
return null;
}
private ByteBuffer messageToBuffer(IMessage msg) throws InternalException {
try {
return parser.encodeMessage(msg);
}
catch (ParseException e) {
throw new InternalException("Failed to encode message.",e);
}
}
private class RequestDelivery implements Runnable {
ClientRoSession session;
Request request;
public void run() {
try {
switch (request.getCommandCode()) {
case ReAuthAnswerImpl.code:
handleEvent(new Event(Event.Type.RECEIVED_RAR, factory.createReAuthRequest(request), null));
break;
default:
listener.doOtherEvent(session, new AppRequestEventImpl(request), null);
break;
}
}
catch (Exception e) {
logger.debug("Failure processing request", e);
}
}
}
private class AnswerDelivery implements Runnable {
ClientRoSession session;
Answer answer;
Request request;
public void run() {
try{
switch(request.getCommandCode())
{
case RoCreditControlAnswer.code:
RoCreditControlRequest _request = factory.createCreditControlRequest(request);
RoCreditControlAnswer _answer = factory.createCreditControlAnswer(answer);
extractFHAVPs(null, _answer );
handleEvent(new Event(false, _request, _answer));
break;
default:
listener.doOtherEvent(session, new AppRequestEventImpl(request), new AppAnswerEventImpl(answer));
break;
}
}
catch(Exception e) {
logger.debug("Failure processing success message", e);
}
}
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.app.ro;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.app.AppAnswerEvent;
import org.jdiameter.api.app.AppEvent;
import org.jdiameter.api.app.AppRequestEvent;
import org.jdiameter.api.app.StateEvent;
import org.jdiameter.api.ro.events.RoCreditControlAnswer;
import org.jdiameter.api.ro.events.RoCreditControlRequest;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class Event implements StateEvent {
public enum Type {
SEND_INITIAL_REQUEST, RECEIVED_INITIAL_ANSWER,
SEND_UPDATE_REQUEST, RECEIVED_UPDATE_ANSWER,
SEND_TERMINATE_REQUEST,RECEIVED_TERMINATED_ANSWER,
RECEIVED_RAR,SEND_RAA,Tx_TIMER_FIRED,
SEND_EVENT_REQUEST, RECEIVE_EVENT_ANSWER;
}
Type type;
AppRequestEvent request;
AppAnswerEvent answer;
Event(Type type) {
this.type = type;
}
Event(Type type, AppRequestEvent request, AppAnswerEvent answer) {
this.type = type;
this.answer = answer;
this.request = request;
}
Event(boolean isRequest, RoCreditControlRequest request, RoCreditControlAnswer answer) throws AvpDataException{
this.answer = answer;
this.request = request;
if(isRequest) {
switch(request.getRequestTypeAVPValue())
{
case 1:
type = Type.SEND_INITIAL_REQUEST;
break;
case 2:
type = Type.SEND_UPDATE_REQUEST;
break;
case 3:
type = Type.SEND_TERMINATE_REQUEST;
break;
case 4:
type = Type.SEND_EVENT_REQUEST;
break;
default:
throw new RuntimeException("Wrong CC-Request-Type value: " + request.getRequestTypeAVPValue());
}
}
else {
switch(answer.getRequestTypeAVPValue())
{
case 1:
type = Type.RECEIVED_INITIAL_ANSWER;
break;
case 2:
type = Type.RECEIVED_UPDATE_ANSWER;
break;
case 3:
type = Type.RECEIVED_TERMINATED_ANSWER;
break;
case 4:
type = Type.RECEIVE_EVENT_ANSWER;
break;
default:
throw new RuntimeException("Wrong CC-Request-Type value: " + answer.getRequestTypeAVPValue());
}
}
}
public Enum getType() {
return type;
}
public int compareTo(Object o) {
return 0;
}
public Object getData() {
return request != null ? request : answer;
}
public void setData(Object data) {
// FIXME: What should we do here?! Is it request or answer?
}
public AppEvent getRequest() {
return request;
}
public AppEvent getAnswer() {
return answer;
}
public <E> E encodeType(Class<E> eClass) {
return eClass == Event.Type.class ? (E) type : null;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.app.ro;
import java.io.Serializable;
import org.jdiameter.api.Request;
import org.jdiameter.common.api.app.ro.ClientRoSessionState;
import org.jdiameter.common.api.app.ro.IRoSessionData;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public interface IClientRoSessionData extends IRoSessionData {
public boolean isEventBased();
public void setEventBased(boolean b);
public boolean isRequestTypeSet();
public void setRequestTypeSet(boolean b);
public ClientRoSessionState getClientRoSessionState();
public void setClientRoSessionState(ClientRoSessionState state);
public Serializable getTxTimerId();
public void setTxTimerId(Serializable txTimerId);
public Request getTxTimerRequest();
public void setTxTimerRequest(Request txTimerRequest);
public Request getBuffer();
public void setBuffer(Request buffer);
public int getGatheredRequestedAction();
public void setGatheredRequestedAction(int gatheredRequestedAction);
public int getGatheredCCFH();
public void setGatheredCCFH(int gatheredCCFH);
public int getGatheredDDFH();
public void setGatheredDDFH(int gatheredDDFH);
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.app.rf;
import java.io.Serializable;
import org.jdiameter.api.Request;
import org.jdiameter.common.api.app.AppSessionDataLocalImpl;
import org.jdiameter.common.api.app.rf.ClientRfSessionState;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ClientRfSessionDataLocalImpl extends AppSessionDataLocalImpl implements IClientRfSessionData {
protected boolean isEventBased = true;
protected boolean requestTypeSet = false;
protected ClientRfSessionState state = ClientRfSessionState.IDLE;
protected Serializable tsTimerId;
protected Request buffer;
protected String destinationHost;
protected String destinationRealm;
/**
*
*/
public ClientRfSessionDataLocalImpl() {
}
public ClientRfSessionState getClientRfSessionState() {
return state;
}
public void setClientRfSessionState(ClientRfSessionState state) {
this.state = state;
}
public Serializable getTsTimerId() {
return tsTimerId;
}
public void setTsTimerId(Serializable txTimerId) {
this.tsTimerId = txTimerId;
}
public Request getBuffer() {
return buffer;
}
public void setBuffer(Request buffer) {
this.buffer = buffer;
}
/*
* (non-Javadoc)
* @see org.jdiameter.client.impl.app.rf.IClientRfSessionData#getDestinationHost()
*/
@Override
public String getDestinationHost() {
return this.destinationHost;
}
/*
* (non-Javadoc)
* @see org.jdiameter.client.impl.app.rf.IClientRfSessionData#setDestinationHost(java.lang.String)
*/
@Override
public void setDestinationHost(String destinationHost) {
this.destinationHost = destinationHost;
}
/*
* (non-Javadoc)
* @see org.jdiameter.client.impl.app.rf.IClientRfSessionData#getDestinationRealm()
*/
@Override
public String getDestinationRealm() {
return this.destinationRealm;
}
/*
* (non-Javadoc)
* @see org.jdiameter.client.impl.app.rf.IClientRfSessionData#setDestinationRealm(java.lang.String)
*/
@Override
public void setDestinationRealm(String destinationRealm) {
this.destinationRealm = destinationRealm;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.app.rf;
import java.io.Serializable;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Request;
import org.jdiameter.common.api.app.rf.ClientRfSessionState;
import org.jdiameter.common.api.app.rf.IRfSessionData;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public interface IClientRfSessionData extends IRfSessionData {
public void setClientRfSessionState(ClientRfSessionState state);
public ClientRfSessionState getClientRfSessionState();
public void setBuffer(Request event);
public Request getBuffer();
public ApplicationId getApplicationId();
public void setApplicationId(ApplicationId appId);
public Serializable getTsTimerId();
public void setTsTimerId(Serializable tid);
public String getDestinationHost();
public void setDestinationHost(String destinationHost);
public String getDestinationRealm();
public void setDestinationRealm(String destinationRealm);
}
| 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.client.impl.app.rf;
import org.jdiameter.api.Avp;
import org.jdiameter.api.ResultCode;
import org.jdiameter.api.app.AppEvent;
import org.jdiameter.api.app.StateEvent;
import org.jdiameter.api.rf.events.RfAccountingAnswer;
import org.jdiameter.api.rf.events.RfAccountingRequest;
/**
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
class Event implements StateEvent {
enum Type{
SEND_EVENT_RECORD,
SEND_START_RECORD,
SEND_INTERIM_RECORD,
SEND_STOP_RECORD,
FAILED_SEND_RECORD,
RECEIVED_RECORD,
FAILED_RECEIVE_RECORD
}
Type type;
AppEvent data;
Event(Type type) {
this.type = type;
}
Event(RfAccountingAnswer accountAnswer) throws Exception {
int resCode = ResultCode.SUCCESS;
try {
resCode = accountAnswer.getMessage().getAvps().getAvp(Avp.RESULT_CODE).getInteger32();
} catch (Exception exc) {}
type = (resCode == ResultCode.SUCCESS || (resCode/1000 == 4)) ? Type.RECEIVED_RECORD : Type.FAILED_RECEIVE_RECORD;
data = accountAnswer;
}
Event(RfAccountingRequest accountRequest) throws Exception {
data = accountRequest;
int type = (int) accountRequest.getAccountingRecordType(); //legal, its int size...
switch (type) {
case 1:
this.type = Type.SEND_EVENT_RECORD;
break;
case 2:
this.type = Type.SEND_START_RECORD;
break;
case 3:
this.type = Type.SEND_INTERIM_RECORD;
break;
case 4:
this.type = Type.SEND_STOP_RECORD;
break;
default:
throw new Exception("Unknown type " + type);
}
}
Event(Type type, RfAccountingRequest accountRequest) throws Exception {
this.type = type;
this.data = accountRequest;
}
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 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.app.rf;
import static org.jdiameter.api.Avp.ACCOUNTING_REALTIME_REQUIRED;
import static org.jdiameter.common.api.app.rf.ClientRfSessionState.IDLE;
import static org.jdiameter.common.api.app.rf.ClientRfSessionState.OPEN;
import static org.jdiameter.common.api.app.rf.ClientRfSessionState.PENDING_BUFFERED;
import static org.jdiameter.common.api.app.rf.ClientRfSessionState.PENDING_CLOSE;
import static org.jdiameter.common.api.app.rf.ClientRfSessionState.PENDING_EVENT;
import static org.jdiameter.common.api.app.rf.ClientRfSessionState.PENDING_INTERIM;
import static org.jdiameter.common.api.app.rf.ClientRfSessionState.PENDING_START;
import java.io.Serializable;
import org.jdiameter.api.Answer;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Avp;
import org.jdiameter.api.EventListener;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Message;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
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.ClientRfSession;
import org.jdiameter.api.rf.ClientRfSessionListener;
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.ClientRfSessionState;
import org.jdiameter.common.api.app.rf.IClientRfActionContext;
import org.jdiameter.common.impl.app.rf.AppRfSessionImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Client Accounting session implementation
*
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ClientRfSessionImpl extends AppRfSessionImpl implements EventListener<Request, Answer>, ClientRfSession {
private static final Logger logger = LoggerFactory.getLogger(ClientRfSessionImpl.class);
// Constants ----------------------------------------------------------------
public static final int DELIVER_AND_GRANT = 1;
public static final int GRANT_AND_LOSE = 3;
// Factories and Listeners --------------------------------------------------
protected transient IClientRfActionContext context;
protected transient ClientRfSessionListener listener;
protected static final String TIMER_NAME_INTERIM = "CLIENT_INTERIM";
protected IClientRfSessionData sessionData;
public ClientRfSessionImpl(IClientRfSessionData sessionData, ISessionFactory sessionFactory,ClientRfSessionListener clientAccSessionListener, IClientRfActionContext iClientRfActionContext,
StateChangeListener<AppSession> stateChangeListener, ApplicationId applicationId) {
super(sessionFactory,sessionData);
super.appId = applicationId;
this.listener = clientAccSessionListener;
this.context = iClientRfActionContext;
this.sessionData = sessionData;
super.addStateChangeNotification(stateChangeListener);
}
public void sendAccountRequest(RfAccountingRequest accountRequest) throws InternalException, IllegalStateException, RouteException, OverloadException {
try {
sendAndStateLock.lock();
handleEvent(new Event(accountRequest));
try {
session.send(accountRequest.getMessage(), this);
// Store last destination information
sessionData.setDestinationRealm(accountRequest.getMessage().getAvps().getAvp(Avp.DESTINATION_REALM).getDiameterIdentity());
Avp destHostAvp = accountRequest.getMessage().getAvps().getAvp(Avp.DESTINATION_HOST);
if(destHostAvp != null) {
sessionData.setDestinationHost(destHostAvp.getDiameterIdentity());
}
}
catch (Throwable t) {
logger.debug("Failed to send ACR.", t);
handleEvent(new Event(Event.Type.FAILED_SEND_RECORD, accountRequest));
}
}
catch (Exception exc) {
throw new InternalException(exc);
}
finally {
sendAndStateLock.unlock();
}
}
protected synchronized void storeToBuffer(Request accountRequest) {
sessionData.setBuffer(accountRequest);
}
protected synchronized boolean checkBufferSpace() {
return sessionData.getBuffer() == null;
}
@SuppressWarnings("unchecked")
protected void setState(IAppSessionState newState) {
IAppSessionState oldState = sessionData.getClientRfSessionState();
sessionData.setClientRfSessionState((ClientRfSessionState) newState);
for (StateChangeListener i : stateListeners) {
i.stateChanged(this,(Enum) oldState, (Enum) newState);
}
}
public boolean isStateless() {
return false;
}
public boolean handleEvent(StateEvent event) throws InternalException, OverloadException {
final ClientRfSessionState state = this.sessionData.getClientRfSessionState();
ClientRfSessionState oldState = state;
try {
switch (state) {
// Idle ==========
case IDLE: {
switch ((Event.Type) event.getType()) {
// Client or device requests access
case SEND_START_RECORD:
// Current State: IDLE
// Event: Client or Device Requests access
// Action: Send accounting start req.
// New State: PENDING_S
setState(PENDING_START);
break;
case SEND_EVENT_RECORD:
// Current State: IDLE
// Event: Client or device requests a one-time service
// Action: Send accounting event req
// New State: PENDING_E
setState(PENDING_EVENT);
break;
// Send buffered message action in other section of this method see below
default:
throw new IllegalStateException("Current state " + state + " action " + event.getType());
}
break;
}
// PendingS ==========
case PENDING_START: {
switch ((Event.Type) event.getType()) {
case FAILED_SEND_RECORD:
RfAccountingRequest request = (RfAccountingRequest) event.getData();
Avp accRtReq = request.getMessage().getAvps().getAvp(ACCOUNTING_REALTIME_REQUIRED);
// Current State: PENDING_S
// Event: Failure to send and buffer space available and realtime not equal to DELIVER_AND_GRANT
// Action: Store Start Record
// New State: OPEN
if (checkBufferSpace() && accRtReq != null && accRtReq.getInteger32() != DELIVER_AND_GRANT) {
storeToBuffer((Request) request.getMessage());
setState(OPEN);
}
else {
// Current State: PENDING_S
// Event: Failure to send and no buffer space available and realtime equal to GRANT_AND_LOSE
// Action: -
// New State: OPEN
if (!checkBufferSpace() && accRtReq != null && accRtReq.getInteger32() == GRANT_AND_LOSE) {
setState(OPEN);
}
else {
// Current State: PENDING_S
// Event: Failure to send and no buffer space available and realtime not equal to GRANT_AND_LOSE
// Action: Disconnect User/Device
// New State: IDLE
try{
if (context != null) {
Request str = createSessionTermRequest();
context.disconnectUserOrDev(this, str);
session.send(str, this);
}
}
finally {
setState(IDLE);
}
}
}
break;
case RECEIVED_RECORD:
// Current State: PENDING_S
// Event: Successful accounting start answer received
// Action: -
// New State: OPEN
processInterimIntervalAvp(event);
setState(OPEN);
break;
case FAILED_RECEIVE_RECORD:
try {
RfAccountingRequest answer = (RfAccountingRequest) event.getData();
accRtReq = answer.getMessage().getAvps().getAvp(ACCOUNTING_REALTIME_REQUIRED);
// Current State: PENDING_S
// Event: Failed accounting start answer received and realtime equal to GRANT_AND_LOSE
// Action: -
// New State: OPEN
if (accRtReq != null && accRtReq.getInteger32() == GRANT_AND_LOSE) {
setState(OPEN);
}
else {
// Current State: PENDING_S
// Event: Failed accounting start answer received and realtime not equal to GRANT_AND_LOSE
// Action: Disconnect User/Device
// New State: IDLE
if (accRtReq != null && accRtReq.getInteger32() != GRANT_AND_LOSE) {
try {
if (context != null) {
Request str = createSessionTermRequest();
context.disconnectUserOrDev(this, str);
session.send(str, this);
}
}
finally {
setState(IDLE);
}
}
}
}
catch (Exception e) {
logger.debug("Can not process answer", e);
setState(IDLE);
}
break;
case SEND_STOP_RECORD:
// Current State: PENDING_S
// Event: User service terminated
// Action: Store stop record
// New State: PENDING_S
if (context != null) {
Request str = createSessionTermRequest();
context.disconnectUserOrDev(this,str);
storeToBuffer(str);
}
break;
}
break;
}
// OPEN ==========
case OPEN: {
switch ((Event.Type) event.getType()) {
// User service terminated
case SEND_STOP_RECORD:
// Current State: OPEN
// Event: User service terminated
// Action: Send accounting stop request
// New State: PENDING_L
setState(PENDING_CLOSE);
break;
case SEND_INTERIM_RECORD:
// FIXME: Shouldn't this be different ?
// Current State: OPEN
// Event: Interim interval elapses
// Action: Send accounting interim record
// New State: PENDING_I
setState(PENDING_INTERIM);
break;
// Create timer for "Interim interval elapses" event
case RECEIVED_RECORD:
processInterimIntervalAvp(event);
break;
}
}
break;
//FIXME: add check for abnormal
// PendingI ==========
case PENDING_INTERIM: {
switch ((Event.Type) event.getType()) {
case RECEIVED_RECORD:
// Current State: PENDING_I
// Event: Successful accounting interim answer received
// Action: -
// New State: OPEN
processInterimIntervalAvp(event);
setState(OPEN);
break;
case FAILED_SEND_RECORD:
RfAccountingRequest request = (RfAccountingRequest) event.getData();
Avp accRtReq = request.getMessage().getAvps().getAvp(ACCOUNTING_REALTIME_REQUIRED);
// Current State: PENDING_I
// Event: Failure to send and buffer space available (or old record interim can be overwritten) and realtime not equal to DELIVER_AND_GRANT
// Action: Store interim record
// New State: OPEN
if (checkBufferSpace() && accRtReq != null && accRtReq.getInteger32() != DELIVER_AND_GRANT) {
storeToBuffer((Request) request.getMessage());
setState(OPEN);
}
else {
// Current State: PENDING_I
// Event: Failure to send and no buffer space available and realtime equal to GRANT_AND_LOSE
// Action: -
// New State: OPEN
if (!checkBufferSpace() && accRtReq != null && accRtReq.getInteger32() == GRANT_AND_LOSE) {
setState(OPEN);
}
else {
// Current State: PENDING_I
// Event: Failure to send and no buffer space available and realtime not equal to GRANT_AND_LOSE
// Action: Disconnect User/Device
// New State: IDLE
if (!checkBufferSpace() && accRtReq != null && accRtReq.getInteger32() != GRANT_AND_LOSE) {
try {
if (context != null) {
Request str = createSessionTermRequest();
context.disconnectUserOrDev(this, str);
session.send(str, this);
}
}
finally {
setState(IDLE);
}
}
}
}
break;
case FAILED_RECEIVE_RECORD:
try {
RfAccountingRequest answer = (RfAccountingRequest) event.getData();
accRtReq = answer.getMessage().getAvps().getAvp(ACCOUNTING_REALTIME_REQUIRED);
// Current State: PENDING_I
// Event: Failed accounting interim answer received and realtime equal to GRANT_AND_LOSE
// Action: -
// New State: OPEN
if (accRtReq != null && accRtReq.getInteger32() == GRANT_AND_LOSE) {
setState(OPEN);
}
else {
// Current State: PENDING_I
// Event: Failed account interim answer received and realtime not equal to GRANT_AND_LOSE
// Action: Disconnect User/Device
// New State: IDLE
if (accRtReq != null && accRtReq.getInteger32() != GRANT_AND_LOSE) {
try {
if (context != null) {
Request str = createSessionTermRequest();
context.disconnectUserOrDev(this,str);
session.send(str, this);
}
}
finally {
setState(IDLE);
}
}
}
}
catch (Exception e) {
logger.debug("Can not process received request", e);
setState(IDLE);
}
break;
case SEND_STOP_RECORD:
// Current State: PENDING_I
// Event: User service terminated
// Action: Store stop record
// New State: PENDING_I
if (context != null) {
Request str = createSessionTermRequest();
context.disconnectUserOrDev(this,str);
storeToBuffer(str);
}
break;
}
break;
}
// PendingE ==========
case PENDING_EVENT: {
switch ((Event.Type) event.getType()) {
case RECEIVED_RECORD:
// Current State: PENDING_E
// Event: Successful accounting event answer received
// Action: -
// New State: IDLE
setState(IDLE);
break;
case FAILED_SEND_RECORD:
if (checkBufferSpace()) {
// Current State: PENDING_E
// Event: Failure to send and buffer space available
// Action: Store event record
// New State: IDLE
RfAccountingRequest data = (RfAccountingRequest) event.getData();
storeToBuffer((Request) data.getMessage());
}
// Current State: PENDING_E
// Event: Failure to send and no buffer space available
// Action: -
// New State: IDLE
setState(IDLE);
break;
case FAILED_RECEIVE_RECORD:
// Current State: PENDING_E
// Event: Failed accounting event answer received
// Action: -
// New State: IDLE
setState(IDLE);
break;
}
break;
}
// PendingB ==========
case PENDING_BUFFERED: {
switch ((Event.Type) event.getType()) {
case RECEIVED_RECORD:
// Current State: PENDING_B
// Event: Successful accounting answer received
// Action: Delete record
// New State: IDLE
synchronized (this) {
storeToBuffer(null);
}
setState(IDLE);
break;
// Failure to send
case FAILED_SEND_RECORD:
// Current State: PENDING_B
// Event: Failure to send
// Action: -
// New State: IDLE
setState(IDLE);
break;
// Failed accounting answer received
case FAILED_RECEIVE_RECORD:
// Current State: PENDING_B
// Event: Failed accounting answer received
// Action: Delete record
// New State: IDLE
synchronized (this) {
storeToBuffer(null);
}
setState(IDLE);
break;
}
break;
}
// PendingL ==========
case PENDING_CLOSE: {
switch ((Event.Type) event.getType()) {
case RECEIVED_RECORD:
// Current State: PENDING_L
// Event: Successful accounting stop answer received
// Action: -
// New State: IDLE
setState(IDLE);
break;
case FAILED_SEND_RECORD:
if (checkBufferSpace()) {
// Current State: PENDING_L
// Event: Failure to send and buffer space available
// Action: Store stop record
// New State: IDLE
RfAccountingRequest data = (RfAccountingRequest) event.getData();
storeToBuffer((Request) data.getMessage());
}
// Current State: PENDING_L
// Event: Failure to send and no buffer space available
// Action: -
// New State: IDLE
setState(IDLE);
break;
// Failed accounting stop answer received
case FAILED_RECEIVE_RECORD:
// Current State: PENDING_L
// Event: Failed accounting stop answer received
// Action: -
// New State: IDLE
setState(IDLE);
break;
}
break;
}
}
// Post processing
if (oldState != state) {
switch (state) {
// IDLE ===========
case IDLE:
{
// Current State: IDLE
// Event: Records in storage
// Action: Send record
// New State: PENDING_B
try {
synchronized (this) {
if (sessionData.getBuffer() != null) {
session.send(sessionData.getBuffer(), this);
setState(PENDING_BUFFERED);
}
}
}
catch (Exception e) {
logger.debug("can not send buffered message", e);
synchronized (this) {
Request buffer = sessionData.getBuffer();
if (context != null && buffer != null) {
if (!context.failedSendRecord(this,buffer)) {
storeToBuffer(null);
}
}
}
}
}
}
}
}
catch (Throwable t) {
throw new InternalException(t);
}
return true;
}
protected void processInterimIntervalAvp(StateEvent event) throws InternalException {
// Avp interval = ((AppEvent) event.getData()).getMessage().getAvps().getAvp(Avp.ACCT_INTERIM_INTERVAL);
// if (interval != null) {
// // create timer
// try {
// long v = interval.getUnsigned32();
// if (v != 0) {
// // scheduler.schedule(
// // new Runnable() {
// // public void run() {
// // if (context != null) {
// // try {
// // Request interimRecord = createInterimRecord();
// // context.interimIntervalElapses(interimRecord);
// // sendAndStateLock.lock();
// // session.send(interimRecord, ClientRfSessionImpl.this);
// // setState(PENDING_INTERIM);
// // }
// // catch (Exception e) {
// // logger.debug("Can not process Interim Interval AVP", e);
// // }
// // finally {
// // sendAndStateLock.unlock();
// // }
// // }
// // }
// // },
// // v, TimeUnit.SECONDS
// // );
// cancelInterimTimer();
// this.timerId_interim = startInterimTimer(v);
// }
// }
// catch (AvpDataException e) {
// logger.debug("Unable to retrieve Acct-Interim-Interval AVP value", e);
// }
// }
}
/* (non-Javadoc)
* @see org.jdiameter.common.impl.app.AppSessionImpl#onTimer(java.lang.String)
*/
@Override
public void onTimer(String timerName) {
if(timerName.equals(TIMER_NAME_INTERIM)) {
if (context != null) {
try {
Request interimRecord = createInterimRecord();
context.interimIntervalElapses(this,interimRecord);
sendAndStateLock.lock();
session.send(interimRecord, ClientRfSessionImpl.this);
setState(PENDING_INTERIM);
sessionData.setTsTimerId(null);
}
catch (Exception e) {
logger.debug("Can not process Interim Interval AVP", e);
}
finally {
sendAndStateLock.unlock();
}
}
}
else {
}
}
private void startInterimTimer(long v) {
try{
sendAndStateLock.lock();
sessionData.setTsTimerId(super.timerFacility.schedule(getSessionId(), TIMER_NAME_INTERIM, v));
return;
}
finally {
sendAndStateLock.unlock();
}
}
private void cancelInterimTimer() {
try{
sendAndStateLock.lock();
final Serializable timerId = this.sessionData.getTsTimerId();
if(timerId != null) {
super.timerFacility.cancel(timerId);
this.sessionData.setTsTimerId(null);
}
}
finally {
sendAndStateLock.unlock();
}
}
@SuppressWarnings("unchecked")
public <E> E getState(Class<E> eClass) {
return eClass == ClientRfSessionState.class ? (E) this.sessionData.getTsTimerId() : null;
}
public void receivedSuccessMessage(Request request, Answer answer) {
if (request.getCommandCode() == RfAccountingRequest.code) {
// state should be changed before event listener call
try {
sendAndStateLock.lock();
handleEvent(new Event(createAccountAnswer(answer)));
}
catch (Exception e) {
logger.debug("Can not process received request", e);
}
finally {
sendAndStateLock.unlock();
}
try {
listener.doRfAccountingAnswerEvent(this, createAccountRequest(request), createAccountAnswer(answer));
}
catch (Exception e) {
logger.debug("Unable to deliver message to listener.", e);
}
}
else {
try {
listener.doOtherEvent(this, createAccountRequest(request), createAccountAnswer(answer));
}
catch (Exception e) {
logger.debug("Can not process received request", e);
}
}
}
public void timeoutExpired(Request request) {
try {
sendAndStateLock.lock();
handleEvent(new Event(Event.Type.FAILED_RECEIVE_RECORD, createAccountRequest(request)));
}
catch (Exception e) {
logger.debug("Can not handle timeout event", e);
}
finally {
sendAndStateLock.unlock();
}
}
public Answer processRequest(Request request) {
if (request.getCommandCode() == RfAccountingRequest.code) {
try {
// FIXME Is this wrong?
listener.doRfAccountingAnswerEvent(this, createAccountRequest(request), null);
}
catch (Exception e) {
logger.debug("Can not process received request", e);
}
}
else {
try {
listener.doOtherEvent(this, createAccountRequest(request), null);
}
catch (Exception e) {
logger.debug("Can not process received request", e);
}
}
return null;
}
/* (non-Javadoc)
* @see org.jdiameter.common.impl.app.AppSessionImpl#isReplicable()
*/
@Override
public boolean isReplicable() {
return true;
}
protected Request createInterimRecord() {
Request interimRecord = session.createRequest(RfAccountingRequest.code, appId, sessionData.getDestinationRealm(), sessionData.getDestinationHost());
interimRecord.getAvps().addAvp(Avp.ACC_RECORD_TYPE, 3);
return interimRecord;
}
protected Request createSessionTermRequest() {
return session.createRequest(Message.SESSION_TERMINATION_REQUEST, appId, sessionData.getDestinationRealm(), sessionData.getDestinationHost());
}
@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;
ClientRfSessionImpl other = (ClientRfSessionImpl) 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();
//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 |
/*
* 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.client.impl.helpers;
import java.util.ArrayList;
/**
* This enumeration defined all parameters of diameter stack 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 Parameters extends Ordinal {
private static final long serialVersionUID = 1L;
protected static int index;
private static ArrayList<Parameters> value = new ArrayList<Parameters>();
/**
* Class name of IOC property
*/
public static final Parameters Assembler = new Parameters("Assembler", String.class, "org.jdiameter.client.impl.helpers.AssemblerImpl");
/**
* Local peer URI property
*/
public static final Parameters OwnDiameterURI = new Parameters("OwnDiameterURI", String.class, "aaa://localhost:3868");
/**
* Local peer ip address property
*/
public static final Parameters OwnIPAddress = new Parameters("OwnIPAddress", String.class, "");
/**
* Local peer realm name property
*/
public static final Parameters OwnRealm = new Parameters("OwnRealm", String.class, "local");
/**
* Local peer vendor id property
*/
public static final Parameters OwnVendorID = new Parameters("OwnVendorID", Long.class, 0L);
/**
* Local peer stack product name property
*/
public static final Parameters OwnProductName = new Parameters("OwnProductName", String.class, "jDiameter");
/**
* Local peer stack firmware version property
*/
public static final Parameters OwnFirmwareRevision = new Parameters("OwnFirmwareRevision", Long.class, 0L);
/**
* Task executor task queue size property
*/
public static final Parameters QueueSize = new Parameters("QueueSize", Integer.class, 10000);
/**
* Message time out property
*/
public static final Parameters MessageTimeOut = new Parameters("MessageTimeOut", Long.class, 60000L);
/**
* Stop stack time out property
*/
public static final Parameters StopTimeOut = new Parameters("StopTimeOut", Long.class, 10000L);
/**
* CEA command time out property
*/
public static final Parameters CeaTimeOut = new Parameters("CeaTimeOut", Long.class, 10000L);
/**
* Peer inactive time out property
*/
public static final Parameters IacTimeOut = new Parameters("IacTimeOut", Long.class, 20000L);
/**
* DWA command time out property
*/
public static final Parameters DwaTimeOut = new Parameters("DwaTimeOut", Long.class, 10000L);
/**
* DPA command time out property
*/
public static final Parameters DpaTimeOut = new Parameters("DpaTimeOut", Long.class, 5000L);
/**
* Reconnect time out property
*/
public static final Parameters RecTimeOut = new Parameters("RecTimeOut", Long.class, 10000L);
/**
* Peer FSM Thread Count property
*/
public static final Parameters PeerFSMThreadCount = new Parameters("PeerFSMThreadCount", Integer.class, 3);
/**
* Orig_host avp set as URI into CER message
*/
public static final Parameters UseUriAsFqdn = new Parameters("UseUriAsFqdn", Boolean.class, false);
/**
* Peer name property
*/
public static final Parameters PeerName = new Parameters("PeerName", String.class, "");
/**
* Peer ip property
*/
public static final Parameters PeerIp = new Parameters("PeerIp", String.class, "");
/**
* Peer local peer port range (format: 1345-1346) property
*/
public static final Parameters PeerLocalPortRange = new Parameters("PeerLocalPortRange", String.class, "");
/**
* Peer rating property
*/
public static final Parameters PeerRating = new Parameters("PeerRating", Integer.class, 0);
/**
* Peer ptoperty
*/
public static final Parameters Peer = new Parameters("Peer", Object.class);
/**
* Real entry property
*/
public static final Parameters RealmEntry = new Parameters("RealmEntry", String.class, "");
/**
* Agent element
*/
public static final Parameters Agent = new Parameters("Agent", Object.class);
/**
* Properties element
*/
public static final Parameters Properties = new Parameters("Properties", Object.class);
/**
* Properties element
*/
public static final Parameters Property = new Parameters("Property ", Object.class);
/**
* Property name
*/
public static final Parameters PropertyName = new Parameters("name", String.class, "");
/**
* Property value
*/
public static final Parameters PropertyValue = new Parameters("value", String.class, "");
/**
* Realm property
*/
public static final Parameters Realm = new Parameters("Realm", Object.class);
/**
* Vendor id property
*/
public static final Parameters VendorId = new Parameters("VendorId", Long.class);
/**
* Authentication application id property
*/
public static final Parameters AuthApplId = new Parameters("AuthApplId", Long.class);
/**
* Accounting application id property
*/
public static final Parameters AcctApplId = new Parameters("AcctApplId", Long.class);
/**
* Application Id property
*/
public static final Parameters ApplicationId = new Parameters("ApplicationId", Object.class);
/**
* Extension point property
*/
public static final Parameters Extensions = new Parameters("Extensions", Object.class);
/**
* Extension point name property
*/
public static final Parameters ExtensionName = new Parameters("ExtensionName", String.class);
/**
* Peer list property
*/
public static final Parameters PeerTable = new Parameters("PeerTable", Object.class);
/**
* Realm list property
*/
public static final Parameters RealmTable = new Parameters("RealmTable", Object.class);
/**
* Security list property
*/
public static final Parameters Security = new Parameters("Security", Object.class);
/**
* Security entry
*/
public static final Parameters SecurityData = new Parameters("SecurityData", Object.class);
/**
* Security data name
*/
public static final Parameters SDName = new Parameters("SDName", String.class);
/**
* Security protocol
*/
public static final Parameters SDProtocol = new Parameters("SDProtocol", String.class, "TLS");
/**
* Security session creation flag
*/
public static final Parameters SDEnableSessionCreation = new Parameters("SDEnableSessionCreation", Boolean.class, false);
/**
* Security client mode flag
*/
public static final Parameters SDUseClientMode= new Parameters("SDUseClientMode", Boolean.class, false);
/**
* Cipher suites separated by ', '
*/
public static final Parameters CipherSuites = new Parameters("CipherSuites", String.class);
/**
* Key data
*/
public static final Parameters KeyData = new Parameters("KeyData", String.class);
/**
* Key manager
*/
public static final Parameters KDManager = new Parameters("KDManager", String.class);
/**
* Key store
*/
public static final Parameters KDStore = new Parameters("KDStore", String.class);
/**
* Key file
*/
public static final Parameters KDFile = new Parameters("KDFile", String.class);
/**
* Key password
*/
public static final Parameters KDPwd = new Parameters("KDPwd", String.class);
/**
* Trust data
*/
public static final Parameters TrustData = new Parameters("TrustData", String.class);
/**
* Key manager
*/
public static final Parameters TDManager = new Parameters("TDManager", String.class);
/**
* Key store
*/
public static final Parameters TDStore = new Parameters("TDStore", String.class);
/**
* Key file
*/
public static final Parameters TDFile = new Parameters("TDFile", String.class);
/**
* Key password
*/
public static final Parameters TDPwd = new Parameters("TDPwd", String.class);
/**
* Reference to security information
*/
public static final Parameters SecurityRef = new Parameters("SecurityRef", String.class);
/**
* XML entry for thread pool
*/
public static final Parameters ThreadPool = new Parameters("ThreadPool", Object.class);
/**
* Thread pool max size
*/
public static final Parameters ThreadPoolSize = new Parameters("ThreadPoolSize", Integer.class, 10);
/**
* Thread pool max size
*/
public static final Parameters ThreadPoolPriority = new Parameters("ThreadPoolPriority", Integer.class, 5);
/**
* Statistic logger properties
*/
public static final Parameters Statistics = new Parameters("Statistics", Object.class);
/**
* Statistic logger start pause
*/
public static final Parameters StatisticsLoggerPause = new Parameters("StatisticsLoggerPause", Long.class, 30000L);
/**
* Statistic logger delay between save statistic information
*/
public static final Parameters StatisticsLoggerDelay = new Parameters("StatisticsLoggerDelay", Long.class, 30000L);
/**
* Statistic flag controlling if statistics are on/off - ie. timer tasks to display are created.
*/
public static final Parameters StatisticsEnabled = new Parameters("StatisticsEnabled", Boolean.class, false);
/**
* List of statistics names which should be enabled.
*/
public static final Parameters StatisticsActiveList = new Parameters("StatisticsActiveList", String.class, false);
/**
* Concurrent configuration root point
*/
public static final Parameters Concurrent = new Parameters("Concurrent", Object.class);
/**
* Concurrent entity name
*/
public static final Parameters ConcurrentEntityName = new Parameters("ConcurrentEntityName", String.class, "Empty");
/**
* Concurrent thread group name
*/
public static final Parameters ConcurrentEntityDescription = new Parameters("ConcurrentEntityDescription", String.class, "ThreadPool");
/**
* Concurrent thread group size
*/
public static final Parameters ConcurrentEntityPoolSize = new Parameters("ConcurrentEntityPoolSize", Integer.class, 4);
/**
* Dictionary root
*/
public static final Parameters Dictionary = new Parameters("Dictionary", Object.class);
/**
* Dictionary Class name
*/
public static final Parameters DictionaryClass = new Parameters("DictionaryClass", String.class, "org.jdiameter.common.impl.validation.DictionaryImpl");
/**
* Dictionary Validation enabled
*/
public static final Parameters DictionaryEnabled = new Parameters("DictionaryEnabled", Boolean.class, false);
/**
* Dictionary Send Level Validation
*/
public static final Parameters DictionarySendLevel = new Parameters("DictionarySendLevel", String.class, "MESSAGE");
/**
* Dictionary Receive Level Validation
*/
public static final Parameters DictionaryReceiveLevel = new Parameters("DictionaryReceiveLevel", String.class, "OFF");
/**
* Return all parameters as iterator
*
* @return all parameters as iterator
*/
public static Iterable<Parameters> values() {
return value;
}
private Class type;
private Object defValue;
protected Parameters(String name, Class type) {
this.name = name;
this.type = type;
ordinal = index++;
value.add(this);
}
protected Parameters(String name, Class type, Object defValue) {
this.name = name;
this.type = type;
this.defValue = defValue;
ordinal = index++;
value.add(this);
}
/**
* Return default value of property
*
* @return default value of property
*/
public Object defValue() {
return defValue;
}
/**
* Return type of property
*
* @return type of property
*/
public Class type() {
return type;
}
}
| 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.client.impl.helpers;
import java.io.Serializable;
/**
* This class provide ordinality properties to childs
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public abstract class Ordinal implements Serializable {
private static final long serialVersionUID = 1L;
protected String name;
protected int ordinal;
/**
* Return name of element
* @return name of element
*/
public String name() {
return name;
}
/**
* Return id of element
* @return id of element
*/
public int ordinal() {
return ordinal;
}
}
| 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.client.impl.helpers;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.StringTokenizer;
/**
* This class allows to convert string to IPv4/IPv6 object instance
*
* @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 IPConverter {
/**
* Convert defined string to IPv4 object instance
* @param address string representation of ip address
* @return IPv4 object instance
*/
public static InetAddress InetAddressByIPv4(String address) {
StringTokenizer addressTokens = new StringTokenizer(address, ".");
byte[] bytes;
if (addressTokens.countTokens() == 4)
bytes = new byte[]{
getByBytes(addressTokens),
getByBytes(addressTokens),
getByBytes(addressTokens),
getByBytes(addressTokens)
};
else
return null;
try {
return InetAddress.getByAddress(bytes);
} catch (UnknownHostException e) {
return null;
}
}
private static byte getByBytes(StringTokenizer addressTokens) {
int word = Integer.parseInt(addressTokens.nextToken());
return (byte) (word & 0xff);
}
/**
* Convert defined string to IPv6 object instance
* @param address string representation of ip address
* @return IPv6 object instance
*/
public static InetAddress InetAddressByIPv6(String address) {
StringTokenizer addressTokens = new StringTokenizer(address, ":");
byte[] bytes = new byte[16];
if (addressTokens.countTokens() == 8) {
int count = 0;
while (addressTokens.hasMoreTokens()) {
int word = Integer.parseInt(addressTokens.nextToken(), 16);
bytes[count * 2] = (byte) ((word >> 8) & 0xff);
bytes[count * 2 + 1] = (byte) (word & 0xff);
count++;
}
} else
return null;
try {
return InetAddress.getByAddress(bytes);
} catch (UnknownHostException e) {
return null;
}
}
}
| 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.client.impl.helpers;
import static org.jdiameter.server.impl.helpers.ExtensionPoint.*;
import static org.jdiameter.client.impl.helpers.Parameters.AcctApplId;
import static org.jdiameter.client.impl.helpers.Parameters.Agent;
import static org.jdiameter.client.impl.helpers.Parameters.ApplicationId;
import static org.jdiameter.client.impl.helpers.Parameters.AuthApplId;
import static org.jdiameter.client.impl.helpers.Parameters.CeaTimeOut;
import static org.jdiameter.client.impl.helpers.Parameters.CipherSuites;
import static org.jdiameter.client.impl.helpers.Parameters.Concurrent;
import static org.jdiameter.client.impl.helpers.Parameters.ConcurrentEntityDescription;
import static org.jdiameter.client.impl.helpers.Parameters.ConcurrentEntityName;
import static org.jdiameter.client.impl.helpers.Parameters.ConcurrentEntityPoolSize;
import static org.jdiameter.client.impl.helpers.Parameters.Dictionary;
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.DpaTimeOut;
import static org.jdiameter.client.impl.helpers.Parameters.DwaTimeOut;
import static org.jdiameter.client.impl.helpers.Parameters.IacTimeOut;
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.MessageTimeOut;
import static org.jdiameter.client.impl.helpers.Parameters.OwnDiameterURI;
import static org.jdiameter.client.impl.helpers.Parameters.OwnFirmwareRevision;
import static org.jdiameter.client.impl.helpers.Parameters.OwnIPAddress;
import static org.jdiameter.client.impl.helpers.Parameters.OwnProductName;
import static org.jdiameter.client.impl.helpers.Parameters.OwnRealm;
import static org.jdiameter.client.impl.helpers.Parameters.OwnVendorID;
import static org.jdiameter.client.impl.helpers.Parameters.PeerIp;
import static org.jdiameter.client.impl.helpers.Parameters.PeerFSMThreadCount;
import static org.jdiameter.client.impl.helpers.Parameters.PeerLocalPortRange;
import static org.jdiameter.client.impl.helpers.Parameters.PeerName;
import static org.jdiameter.client.impl.helpers.Parameters.PeerRating;
import static org.jdiameter.client.impl.helpers.Parameters.PeerTable;
import static org.jdiameter.client.impl.helpers.Parameters.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.QueueSize;
import static org.jdiameter.client.impl.helpers.Parameters.RealmEntry;
import static org.jdiameter.client.impl.helpers.Parameters.RealmTable;
import static org.jdiameter.client.impl.helpers.Parameters.RecTimeOut;
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.Statistics;
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.StopTimeOut;
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.ThreadPool;
import static org.jdiameter.client.impl.helpers.Parameters.ThreadPoolPriority;
import static org.jdiameter.client.impl.helpers.Parameters.ThreadPoolSize;
import static org.jdiameter.client.impl.helpers.Parameters.TrustData;
import static org.jdiameter.client.impl.helpers.Parameters.UseUriAsFqdn;
import static org.jdiameter.client.impl.helpers.Parameters.VendorId;
import static org.jdiameter.server.impl.helpers.Parameters.RealmEntryExpTime;
import static org.jdiameter.server.impl.helpers.Parameters.RealmEntryIsDynamic;
import static org.jdiameter.server.impl.helpers.Parameters.RealmHosts;
import static org.jdiameter.server.impl.helpers.Parameters.RealmLocalAction;
import static org.jdiameter.server.impl.helpers.Parameters.RealmName;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
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 org.jdiameter.api.Configuration;
import 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;
/**
* This class provide loading and verification configuration for client 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-client.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("Network")) {
addNetwork(c.item(i));
}
else if (nodeName.equals("Security")) {
addSecurity(c.item(i));
}
else if (nodeName.equals("Extensions")) {
addExtensions(c.item(i));
}
}
}
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));
}
}
}
protected void addIPAddress(Node node) {
String nodeName = node.getNodeName();
if (nodeName.equals("IPAddress"))
add(OwnIPAddress, getValue(node));
}
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")) {
items.add(addApplication(c.item(i)));
}
}
add(ApplicationId, items.toArray(EMPTY_ARRAY));
}
protected Configuration addApplication(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("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
appendOtherParameter(c.item(i));
}
}
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 appendOtherParameter(Node node) {
}
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 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) {
AppConfiguration peerConfig = getInstance()
.add(PeerRating, new Integer(node.getAttributes().getNamedItem("rating").getNodeValue()))
.add(PeerName, node.getAttributes().getNamedItem("name").getNodeValue());
if (node.getAttributes().getNamedItem("ip") != null) {
peerConfig.add(PeerIp, node.getAttributes().getNamedItem("ip").getNodeValue());
}
if (node.getAttributes().getNamedItem("portRange") != null) {
peerConfig.add(PeerLocalPortRange, node.getAttributes().getNamedItem("portRange").getNodeValue());
}
if (node.getAttributes().getNamedItem("security_ref") != null) {
peerConfig.add(SecurityRef, node.getAttributes().getNamedItem("security_ref").getNodeValue());
}
return peerConfig;
}
protected Configuration addRealm(Node node) {
AppConfiguration realmEntry = getInstance().
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 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 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("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("SessionDatasource")) { addInternalExtension(InternalSessionDatasource, getValue(c.item(i))); }
else if (nodeName.equals("TimerFacility")) { addInternalExtension(InternalTimerFacility, getValue(c.item(i))); }
//FIXME: possibly should not be in client...
else if (nodeName.equals("AgentRedirect")) { addInternalExtension(InternalAgentRedirect, getValue(c.item(i))); }
else if (nodeName.equals("AgentConfiguration")) { add(InternalAgentConfiguration,getValue(c.item(i))) ; }
else if (nodeName.equals("StatisticProcessor")) { addInternalExtension(InternalStatisticProcessor,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.client.impl.helpers;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 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 Ordinal {
private static final long serialVersionUID = 1L;
protected static int index;
/**
* MetaData implementation class name
*/
public static final ExtensionPoint InternalMetaData = new ExtensionPoint("InternalMetaData", "org.jdiameter.client.impl.MetaDataImpl");
/**
* Message parser implementation class name
*/
public static final ExtensionPoint InternalMessageParser = new ExtensionPoint("InternalMessageParser", "org.jdiameter.client.impl.parser.MessageParser");
/**
* Element message implementation class name
*/
public static final ExtensionPoint InternalElementParser = new ExtensionPoint("InternalElementParser", "org.jdiameter.client.impl.parser.ElementParser");
/**
* Router enginr implementation class name
*/
public static final ExtensionPoint InternalRouterEngine = new ExtensionPoint("InternalRouterEngine", "org.jdiameter.client.impl.router.RouterImpl");
/**
* Peer controller implementation class name
*/
public static final ExtensionPoint InternalPeerController = new ExtensionPoint("InternalPeerController", "org.jdiameter.client.impl.controller.PeerTableImpl");
/**
* Realm controller implementation class name
*/
public static final ExtensionPoint InternalRealmController = new ExtensionPoint("InternalRealmController", "org.jdiameter.client.impl.controller.RealmTableImpl");
/**
* Session factory implementation class name
*/
public static final ExtensionPoint InternalSessionFactory = new ExtensionPoint("InternalSessionFactory", "org.jdiameter.client.impl.SessionFactoryImpl");
/**
* Class name of connection interface implementation
*/
public static final ExtensionPoint InternalConnectionClass = new ExtensionPoint("InternalConnection","org.jdiameter.client.impl.transport.tcp.TCPClientConnection");
/**
* Transport factory implementation class name
*/
public static final ExtensionPoint InternalTransportFactory = new ExtensionPoint("InternalTransportFactory", "org.jdiameter.client.impl.transport.TransportLayerFactory");
/**
* Peer FSM factory implementation class name
*/
public static final ExtensionPoint InternalPeerFsmFactory = new ExtensionPoint("InternalPeerFsmFactory", "org.jdiameter.client.impl.fsm.FsmFactoryImpl");
/**
* Statistic factory implementation class name
*/
public static final ExtensionPoint InternalStatisticFactory = new ExtensionPoint("InternalStatisticFactory", "org.jdiameter.common.impl.statistic.StatisticManagerImpl");
/**
* Statistic factory implementation class name
*/
public static final ExtensionPoint InternalStatisticProcessor = new ExtensionPoint("InternalStatisticProcessor", "org.jdiameter.common.impl.statistic.StatisticProcessorImpl");
/**
* Concurrent factory implementation class name
*/
public static final ExtensionPoint InternalConcurrentFactory = new ExtensionPoint("InternalConcurrentFactory", "org.jdiameter.common.impl.concurrent.ConcurrentFactory");
/**
* Concurrent entity factory implementation class name
*/
public static final ExtensionPoint InternalConcurrentEntityFactory = new ExtensionPoint("InternalConcurrentEntityFactory", "org.jdiameter.common.impl.concurrent.ConcurrentEntityFactory");
/**
* Redirect Agent implementation class name
*/
public static final ExtensionPoint InternalAgentRedirect = new ExtensionPoint("InternalAgentRedirect", "org.jdiameter.server.impl.agent.RedirectAgentImpl");
/**
* Proxy Agent implementation class name
*/
public static final ExtensionPoint InternalAgentProxy = new ExtensionPoint("InternalAgentProxy", "org.jdiameter.server.impl.agent.ProxyAgentImpl");
/**
* Agent Conf implementation class name
*/
public static final ExtensionPoint InternalAgentConfiguration = new ExtensionPoint("InternalAgentConfiguration", "org.jdiameter.server.impl.agent.AgentConfigurationImpl");
/**
* Session Datasource class name
*/
public static final ExtensionPoint InternalSessionDatasource = new ExtensionPoint("InternalSessionDatasource", "org.jdiameter.common.impl.data.LocalDataSource");
/**
* Timer Facility class name
*/
public static final ExtensionPoint InternalTimerFacility = new ExtensionPoint("InternalTimerFacility", "org.jdiameter.common.impl.timer.LocalTimerFacilityImpl");
/**
* List of internal extension point
*/
public static final ExtensionPoint Internal = new ExtensionPoint(
"Internal", 0,
InternalMetaData,
InternalMessageParser,
InternalElementParser,
InternalRouterEngine,
InternalPeerController,
InternalRealmController,
InternalSessionFactory,
//DONT add this, this will make assembler to try to create instance and he will fail :)
//InternalConnectionClass,
InternalTransportFactory,
InternalPeerFsmFactory,
InternalStatisticFactory,
InternalConcurrentFactory,
InternalConcurrentEntityFactory,
InternalTimerFacility,
InternalSessionDatasource,
InternalAgentRedirect,
InternalAgentProxy,
InternalAgentConfiguration,
InternalStatisticProcessor
);
/**
* Stack layer
*/
public static final ExtensionPoint StackLayer = new ExtensionPoint("StackLayer", 1);
/**
* Controller layer
*/
public static final ExtensionPoint ControllerLayer = new ExtensionPoint("ControllerLayer", 2);
/**
* Transport layer
*/
public static final ExtensionPoint TransportLayer = new ExtensionPoint("TransportLayer", 3);
private ExtensionPoint[] elements = new ExtensionPoint[0];
private String defaultValue = "";
private int id = -1;
/**
* Type's count of extension point
*/
public static final int COUNT = 3;
/**
* Create instance of class
*/
public ExtensionPoint() {
this.ordinal = index++;
}
protected ExtensionPoint(String name, String defaultValue) {
this();
this.name = name;
this.defaultValue = defaultValue;
}
protected ExtensionPoint(String name, ExtensionPoint... elements) {
this();
this.name = name;
this.elements = elements;
}
protected ExtensionPoint(String name, int id, ExtensionPoint... elements) {
this();
this.name = name;
this.id = id;
this.elements = elements;
}
/**
* Append extension point entries
*
* @param elements array of append extension point entries
*/
public void appendElements(ExtensionPoint... elements) {
List<ExtensionPoint> rc = new ArrayList<ExtensionPoint>();
rc.addAll(Arrays.asList(this.elements));
rc.addAll(Arrays.asList(elements));
this.elements = rc.toArray(new ExtensionPoint[0]);
}
/**
* Return parameters of extension point
*
* @return array parameters of extension point
*/
public ExtensionPoint[] getExtensionPoints() {
return elements;
}
/**
* Return default value of extension point
*
* @return default value of extension point
*/
public String defValue() {
return defaultValue;
}
/**
* Return id of extension point
*
* @return id of extension point
*/
public int id() {
return id;
}
}
| 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.client.impl.helpers;
import org.jdiameter.api.Configuration;
/**
* This interface provide methods for change configuration object
*
* @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 AppConfiguration extends Configuration {
/**
* Add elements to configuration
* @param e elements identifier
* @param value array of elements
* @return instance of configuration
*/
public AppConfiguration add(Ordinal e, Configuration... value);
/**
*
* @param e element identifier
* @param value parameter value
* @return instance of configuration
*/
public AppConfiguration add(Ordinal e, Object value);
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2006-2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.helpers;
import org.jdiameter.api.Configuration;
import static org.jdiameter.client.impl.helpers.ExtensionPoint.*;
import static org.jdiameter.client.impl.helpers.Parameters.ExtensionName;
import static org.jdiameter.client.impl.helpers.Parameters.Extensions;
import java.util.concurrent.ConcurrentHashMap;
/**
* 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 implements AppConfiguration {
protected final Configuration[] EMPTY_ARRAY = new Configuration[0];
private final ConcurrentHashMap<Integer, Object> elements = new ConcurrentHashMap<Integer, Object>();
/**
* Create instance of class with system default parameters
*
* @return instance of class with system default parameters
*/
public static AppConfiguration getInstance() {
return new EmptyConfiguration(false);
}
/**
* Create instance of class. Internal parameters will be appends
*/
protected EmptyConfiguration() {
this(true);
}
/**
* Create instance of class
*
* @param callInit if value is true then this constructor appends internal configuration parameters
*/
private EmptyConfiguration(boolean callInit) {
if (callInit)
add(Extensions, getInstance(). // Internal extension point
add(ExtensionName, ExtensionPoint.Internal.name()).
add(InternalMetaData, InternalMetaData.defValue()).
add(InternalRouterEngine, InternalRouterEngine.defValue()).
add(InternalMessageParser, InternalMessageParser.defValue()).
add(InternalElementParser, InternalElementParser.defValue()).
add(InternalTransportFactory, InternalTransportFactory.defValue()).
add(InternalConnectionClass, InternalConnectionClass.defValue()).
add(InternalPeerFsmFactory, InternalPeerFsmFactory.defValue()).
add(InternalSessionFactory, InternalSessionFactory.defValue()).
add(InternalPeerController, InternalPeerController.defValue()).
add(InternalRealmController, InternalRealmController.defValue()).
add(InternalAgentRedirect, InternalAgentRedirect.defValue()).
add(InternalAgentConfiguration, InternalAgentConfiguration.defValue()).
add(InternalSessionDatasource, InternalSessionDatasource.defValue()).
add(InternalTimerFacility, InternalTimerFacility.defValue()).
add(InternalStatisticFactory, InternalStatisticFactory.defValue()
),
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())
);
}
/**
* @see AppConfiguration class
*/
public AppConfiguration add(Ordinal e, Configuration... value) {
elements.put(e.ordinal(), value);
return this;
}
/**
* @see AppConfiguration class
*/
public AppConfiguration add(Ordinal e, Object value) {
if (value instanceof Configuration) {
elements.put(e.ordinal(), new Configuration[]{(Configuration) value});
} else {
elements.put(e.ordinal(), value);
}
return this;
}
protected void putValue(int key, Object value) {
elements.put(key, value);
}
protected Object getValue(int key) {
return elements.get(key);
}
protected void removeValue(int... keys) {
for (int i : keys) elements.remove(i);
}
protected AppConfiguration add(int e, Configuration... value) {
elements.put(e, value);
return this;
}
/**
* @see org.jdiameter.api.Configuration class
*/
public byte getByteValue(int i, byte b) {
return (Byte) (isAttributeExist(i) ? elements.get(i) : b);
}
/**
* @see org.jdiameter.api.Configuration class
*/
public int getIntValue(int i, int i1) {
return (Integer) (isAttributeExist(i) ? elements.get(i) : i1);
}
/**
* @see org.jdiameter.api.Configuration class
*/
public long getLongValue(int i, long l) {
return (Long) (isAttributeExist(i) ? elements.get(i) : l);
}
/**
* @see org.jdiameter.api.Configuration class
*/
public double getDoubleValue(int i, double v) {
return (Double) (isAttributeExist(i) ? elements.get(i) : v);
}
/**
* @see org.jdiameter.api.Configuration class
*/
public byte[] getByteArrayValue(int i, byte[] bytes) {
return (byte[]) (isAttributeExist(i) ? elements.get(i) : bytes);
}
/**
* @see org.jdiameter.api.Configuration class
*/
public boolean getBooleanValue(int i, boolean b) {
return (Boolean) (isAttributeExist(i) ? elements.get(i) : b);
}
/**
* @see org.jdiameter.api.Configuration class
*/
public String getStringValue(int i, String defValue) {
String result = (String) elements.get(i);
return result != null ? result : defValue;
}
/**
* @see org.jdiameter.api.Configuration class
*/
public boolean isAttributeExist(int i) {
return elements.containsKey(i);
}
/**
* @see org.jdiameter.api.Configuration class
*/
public Configuration[] getChildren(int i) {
return (Configuration[]) elements.get(i);
}
/**
* Return string representation of configuration
*
* @return string representation of configuration
*/
public String toString() {
StringBuffer buf = new StringBuffer("Configuration");
buf.append("{");
for (Integer key : elements.keySet()) {
Object value = elements.get(key);
Parameters pr = getParameterByIndex(key);
if (pr == null) continue;
if (pr.name().equals(Extensions.name())) continue;
if (value instanceof Configuration[]) {
buf.append('\n');
}
buf.append(pr.name());
buf.append("=");
if (value instanceof Configuration[])
for (Configuration i : ((Configuration[]) value))
buf.append(i.toString()).append('\n');
else
buf.append(value);
buf.append(", ");
}
buf.deleteCharAt(buf.length() - 1);
buf.deleteCharAt(buf.length() - 1);
buf.append("}");
return buf.toString();
}
private Parameters getParameterByIndex(int index) {
for (Parameters p : Parameters.values()) {
if (p.ordinal() == index) return p;
}
return null;
}
}
| 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.client.impl.helpers;
import static org.jdiameter.client.impl.helpers.ExtensionPoint.ControllerLayer;
import static org.jdiameter.client.impl.helpers.ExtensionPoint.Internal;
import static org.jdiameter.client.impl.helpers.ExtensionPoint.InternalElementParser;
import static org.jdiameter.client.impl.helpers.ExtensionPoint.InternalMessageParser;
import static org.jdiameter.client.impl.helpers.ExtensionPoint.InternalMetaData;
import static org.jdiameter.client.impl.helpers.ExtensionPoint.InternalPeerController;
import static org.jdiameter.client.impl.helpers.ExtensionPoint.InternalPeerFsmFactory;
import static org.jdiameter.client.impl.helpers.ExtensionPoint.InternalRouterEngine;
import static org.jdiameter.client.impl.helpers.ExtensionPoint.InternalSessionFactory;
import static org.jdiameter.client.impl.helpers.ExtensionPoint.InternalTransportFactory;
import static org.jdiameter.client.impl.helpers.ExtensionPoint.StackLayer;
import static org.jdiameter.client.impl.helpers.ExtensionPoint.TransportLayer;
import static org.jdiameter.client.impl.helpers.Parameters.ExtensionName;
import static org.jdiameter.client.impl.helpers.Parameters.Extensions;
import org.jdiameter.api.Configuration;
import org.jdiameter.client.api.IAssembler;
import org.picocontainer.MutablePicoContainer;
import org.picocontainer.PicoBuilder;
/**
* IoC 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 AssemblerImpl implements IAssembler {
AssemblerImpl parent;
final AssemblerImpl[] childs = new AssemblerImpl[ExtensionPoint.COUNT];
final MutablePicoContainer pico = new PicoBuilder().withCaching().build();
/**
* Create instance of class with predefined configuration
*
* @param config configuration of stack
* @throws Exception if generated internal exception
*/
public AssemblerImpl(Configuration config) throws Exception {
Configuration[] ext = config.getChildren(Extensions.ordinal());
for (Configuration e : ext) {
String extName = e.getStringValue(ExtensionName.ordinal(), "");
// TODO: server?
// Create structure of containers
if (extName.equals(ExtensionPoint.Internal.name())) {
fill(ExtensionPoint.Internal.getExtensionPoints(), e, true);
}
else if (extName.equals(ExtensionPoint.StackLayer.name())) {
updatePicoContainer(config, StackLayer, InternalMetaData, InternalSessionFactory, InternalMessageParser, InternalElementParser);
}
else if (extName.equals(ExtensionPoint.ControllerLayer.name())) {
updatePicoContainer(config, ControllerLayer, InternalPeerController, InternalPeerFsmFactory, InternalRouterEngine);
}
else if (extName.equals(ExtensionPoint.TransportLayer.name())) {
updatePicoContainer(config, TransportLayer, InternalTransportFactory);
}
}
}
private void updatePicoContainer(Configuration config, ExtensionPoint pointType, ExtensionPoint... updEntries) throws ClassNotFoundException {
for (ExtensionPoint e : updEntries) {
Configuration[] internalConf = config.getChildren(Extensions.ordinal());
String oldValue = internalConf[Internal.id()].getStringValue(e.ordinal(), null);
String newValue = internalConf[pointType.id()].getStringValue(e.ordinal(), null);
if (oldValue != null && newValue != null) {
pico.removeComponent(Class.forName(oldValue));
pico.addComponent(Class.forName(newValue));
}
}
}
/**
* Create child Assembler
*
* @param parent parent assembler
* @param e child configuration
* @param p extension poit
* @throws Exception
*/
protected AssemblerImpl(AssemblerImpl parent, Configuration e, ExtensionPoint p) throws Exception {
this.parent = parent;
fill(p.getExtensionPoints(), e, false);
}
private void fill(ExtensionPoint[] codes, Configuration e, boolean check) throws Exception {
//NOTE: this installs components, but no instances created!
for (ExtensionPoint c : codes) {
String value = e.getStringValue(c.ordinal(), c.defValue());
if (!check && (value == null || value.trim().length() == 0)) {
return;
}
try {
pico.addComponent(Class.forName(value));
}
catch (NoClassDefFoundError exc) {
throw new Exception(exc);
}
}
}
/**
* @see org.picocontainer.MutablePicoContainer
*/
public <T> T getComponentInstance(Class<T> aClass) {
return (T) pico.getComponent(aClass);
}
/**
* @see org.picocontainer.MutablePicoContainer
*/
public void registerComponentInstance(Object object) {
pico.addComponent(object);
}
public void registerComponentImplementation(Class aClass) {
pico.addComponent(aClass);
}
/**
* @see org.picocontainer.MutablePicoContainer
*/
public void registerComponentImplementation(Class<?> aClass, Object object) {
pico.addComponent(object, aClass);
}
public void unregister(Class aClass) {
pico.removeComponent(aClass);
}
/**
* @see org.picocontainer.MutablePicoContainer
*/
public void destroy() {
pico.dispose();
}
/**
* return parent IOC
*/
public IAssembler getParent() {
return parent;
}
/**
* Get childs IOCs
*
* @return childs IOCs
*/
public IAssembler[] getChilds() {
return childs;
}
}
| 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.client.impl.helpers;
import java.util.ArrayList;
import java.util.logging.Logger;
/**
* This enumeration contains all logger usage in JDiameter stack 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 Loggers extends Ordinal {
private static final long serialVersionUID = 1L;
protected static int index;
private static ArrayList<Loggers> value = new ArrayList<Loggers>();
/**
* Logs the stack lifecycle
*/
public static final Loggers Stack = new Loggers("Stack", null ,"Logs the stack lifecycle");
/**
* Logs the peers
*/
public static final Loggers Peer = new Loggers("Peer", "peer","Logs the peers");
/**
* Logs the peer manager subsystem
*/
public static final Loggers PeerTable = new Loggers("PeerTable", "peertable","Logs the peer table subsystem");
/**
* Logs the peers fsm
*/
public static final Loggers FSM = new Loggers("FSM", "peer.fsm","Logs the peers fsm");
/**
* Logs the message parser
*/
public static final Loggers Parser = new Loggers("Parser", "parser","Logs the message parser");
/**
* Logs the avp opetations processing
*/
public static final Loggers AVP = new Loggers("AVP", "parser.avp","Logs the avp opetations processing");
/**
* Logs the message opetations/lifecycle processing
*/
public static final Loggers Message = new Loggers("Message", "parser.message","Logs the message opetations/lifecycle processing");
/**
* Logs the message router subsystem
*/
public static final Loggers Router = new Loggers("Router", "router","Logs the message router subsystem");
/**
* Logs the transport(tcp) opetations processing
*/
public static final Loggers Transport = new Loggers("Transport", "TCPTransport","Logs the transport(tcp) opetations processing");
/**
* Return Iterator of all entries
* @return Iterator of all entries
*/
public static Iterable<Loggers> values(){
return value;
}
private String description;
private String fullName;
protected Loggers(String name, String fullName, String desc) {
this.name = name;
if (fullName == null)
this.fullName = "jDiameter";
else
this.fullName = "jDiameter." + fullName;
this.description = desc;
ordinal = index++;
value.add(this);
}
/**
* Return full name of logger
*
* @return full name of logger
*/
public String fullName() {
return fullName;
}
/**
* Return description of logger
*
* @return description of logger
*/
public String description() {
return description;
}
/**
* Return logger instance
*
* @return logger instance
*/
public Logger logger() {
return Logger.getLogger(fullName);
}
}
| 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.client.impl.helpers;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* This class provide uid range generator functionality
*
* @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 UIDGenerator { // todo remove or redesign
private /*static*/ long value; // static causes repetitions
private final static Lock mutex = new ReentrantLock();
private final static ThreadLocal<Delta> ranges = new ThreadLocal<Delta>() {
protected synchronized Delta initialValue() {
return new Delta();
}
};
private static class Delta {
long start;
long stop;
public long update(long value) {
start = value;
stop = value + 1;
return stop;
}
}
/**
* Create instance of class
*/
public UIDGenerator() {
value = System.currentTimeMillis();
}
/**
* Create instance of class with predefined start value
*
* @param startValue start value of counter
*/
public UIDGenerator(long startValue) {
value = startValue;
}
/**
* Return next uid as int
*
* @return uid
*/
public int nextInt() {
return (int) (0x7FFFFFFF & nextLong());
}
/**
* Return next uid as long
*
* @return uid as long
*/
public long nextLong() {
Delta d = ranges.get();
if (d.start <= d.stop) {
mutex.lock();
value = d.update(value);
mutex.unlock();
}
return d.start++;
}
}
| 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.client.impl.parser;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.AvpSet;
import org.jdiameter.client.api.parser.ParseException;
import org.jdiameter.client.api.parser.IElementParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.util.Date;
/**
*
* 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 ElementParser implements IElementParser {
private static final Logger logger = LoggerFactory.getLogger(ElementParser.class);
/**
* This is seconds shift (70 years in seconds) applied to date,
* since NTP date starts since 1900, not 1970.
*/
private static final long SECOND_SHIFT = 2208988800L;
private static final int INT_INET4 = 1;
private static final int INT_INET6 = 2;
private static final int INT32_SIZE = 4;
private static final int INT64_SIZE = 8;
private static final int FLOAT32_SIZE = 4;
private static final int FLOAT64_SIZE = 8;
public int bytesToInt(byte[] rawData) throws AvpDataException {
return prepareBuffer(rawData, INT32_SIZE).getInt();
}
public long bytesToLong(byte[] rawData) throws AvpDataException {
return prepareBuffer(rawData, INT64_SIZE).getLong();
}
public float bytesToFloat(byte[] rawData) throws AvpDataException {
return prepareBuffer(rawData, INT32_SIZE).getFloat();
}
public double bytesToDouble(byte[] rawData) throws AvpDataException {
return prepareBuffer(rawData, FLOAT64_SIZE).getDouble();
}
protected ByteBuffer prepareBuffer(byte [] bytes, int len) throws AvpDataException {
if (bytes.length != len)
throw new AvpDataException("Incorrect data length");
//ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
//buffer.put(bytes);
//buffer.flip();
return ByteBuffer.wrap(bytes);
}
public String bytesToOctetString(byte[] rawData) throws AvpDataException {
try {
//TODO: veirfy ISO-8859-1 is correct here, according to google results its only ... western EU..
//TODO: verify this, it octet sting we can not discard some chars, we have no idea whats there....
// issue: http://code.google.com/p/mobicents/issues/detail?id=2757
// char[] ca = new String(rawData, "iso-8859-1").toCharArray();
// StringBuffer rc = new StringBuffer(ca.length);
//
// for (char c:ca)
// if (c != (char)0x0)
// { //easier to debug...
// rc.append(c);
// }
//
// return rc.toString();
return new String(rawData, "iso-8859-1");
} catch (UnsupportedEncodingException e) {
throw new AvpDataException("Invalid data type", e);
}
}
public String bytesToUtf8String(byte[] rawData) throws AvpDataException {
try {
char[] ca = new String(rawData, "utf8").toCharArray();
StringBuffer rc = new StringBuffer(ca.length);
for (char c:ca)
if (c != (char)0x0) rc.append(c);
return rc.toString();
} catch (Exception e) {
throw new AvpDataException("Invalid data type", e);
}
}
public Date bytesToDate(byte[] rawData) throws AvpDataException {
try {
byte[] tmp = new byte[8];
System.arraycopy(rawData, 0 , tmp, 4, 4);
return new Date(((bytesToLong(tmp) - SECOND_SHIFT) * 1000L));
} catch (Exception e) {
throw new AvpDataException(e);
}
}
public InetAddress bytesToAddress(byte[] rawData) throws AvpDataException {
InetAddress inetAddress;
byte[] address;
try {
if (rawData[INT_INET4] == INT_INET4) {
address = new byte[4];
System.arraycopy(rawData, 2, address, 0, address.length);
inetAddress = Inet4Address.getByAddress(address);
} else {
address = new byte[16];
System.arraycopy(rawData, 2, address, 0, address.length);
inetAddress = Inet6Address.getByAddress(address);
}
} catch (Exception e) {
throw new AvpDataException(e);
}
return inetAddress;
}
public byte [] int32ToBytes(int value){
byte [] bytes = new byte[INT32_SIZE];
//ByteBuffer buffer = ByteBuffer.allocate(INT32_SIZE);
ByteBuffer buffer = ByteBuffer.wrap(bytes);
buffer.putInt(value);
//buffer.flip();
//buffer.get(bytes);
return bytes;
}
public byte [] intU32ToBytes(long value){
// FIXME: this needs to reworked!
byte [] bytes = new byte[INT32_SIZE];
ByteBuffer buffer = ByteBuffer.allocate(INT64_SIZE);
buffer.putLong(value);
buffer.flip();
buffer.get(bytes);
buffer.get(bytes);
return bytes;
}
public byte [] int64ToBytes(long value){
byte [] bytes = new byte[INT64_SIZE];
//ByteBuffer buffer = ByteBuffer.allocate(INT64_SIZE);
ByteBuffer buffer = ByteBuffer.wrap(bytes);
buffer.putLong(value);
//buffer.flip();
//buffer.get(bytes);
return bytes;
}
public byte [] float32ToBytes(float value){
byte [] bytes = new byte[FLOAT32_SIZE];
//ByteBuffer buffer = ByteBuffer.allocate(FLOAT32_SIZE);
ByteBuffer buffer = ByteBuffer.wrap(bytes);
buffer.putFloat(value);
//buffer.flip();
//buffer.get(bytes);
return bytes;
}
public byte [] float64ToBytes(double value){
byte [] bytes = new byte[FLOAT64_SIZE];
//ByteBuffer buffer = ByteBuffer.allocate(FLOAT64_SIZE);
ByteBuffer buffer = ByteBuffer.wrap(bytes);
buffer.putDouble(value);
//buffer.flip();
//buffer.get(bytes);
return bytes;
}
public byte[] octetStringToBytes(String value) throws ParseException{
try {
return value.getBytes("iso-8859-1");
}
catch (UnsupportedEncodingException e) {
throw new ParseException(e);
}
}
public byte[] utf8StringToBytes(String value) throws ParseException {
try {
return value.getBytes("utf8");
}
catch (Exception e) {
throw new ParseException(e);
}
}
public byte[] addressToBytes(InetAddress address) {
byte byteAddrOrig[] = address.getAddress();
byte[] data = new byte[byteAddrOrig.length + 2];
int addrType = address instanceof Inet4Address ? INT_INET4 : INT_INET6;
data[0] = (byte) ((addrType >> 8) & 0xFF);
data[INT_INET4] = (byte) ((addrType >> 0) & 0xFF);
System.arraycopy(byteAddrOrig, 0, data, 2, byteAddrOrig.length);
return data;
}
public byte[] dateToBytes(Date date) {
byte[] data = new byte[4];
System.arraycopy(int64ToBytes((date.getTime()/1000L) + SECOND_SHIFT), 4, data, 0, 4);
return data;
}
public <T> T bytesToObject(java.lang.Class<?> iface, byte[] rawdata) throws AvpDataException {
return null;
}
public byte [] objectToBytes(Object data) throws ParseException {
return null;
}
public AvpSetImpl decodeAvpSet(byte[] buffer) throws IOException, AvpDataException {
return this.decodeAvpSet(buffer, 0);
}
/**
*
* @param buffer
* @param shift - shift in buffer, for instance for whole message it will have non zero value
* @return
* @throws IOException
* @throws AvpDataException
*/
public AvpSetImpl decodeAvpSet(byte[] buffer, int shift) throws IOException, AvpDataException {
AvpSetImpl avps = new AvpSetImpl();
int tmp, counter = shift;
DataInputStream in = new DataInputStream(new ByteArrayInputStream(buffer, shift, buffer.length /* - shift ? */));
while (counter < buffer.length) {
int code = in.readInt();
tmp = in.readInt();
int flags = (tmp >> 24) & 0xFF;
int length = tmp & 0xFFFFFF;
if(length < 0 || counter + length > buffer.length) {
throw new AvpDataException("Not enough data in buffer!");
}
long vendor = 0;
if ((flags & 0x80) != 0) {
vendor = in.readInt();
}
// Determine body L = length - 4(code) -1(flags) -3(length) [-4(vendor)]
byte[] rawData = new byte[length - (8 + (vendor == 0 ? 0 : 4))];
in.read(rawData);
// skip remaining.
// TODO: Do we need to padd everything? Or on send stack should properly fill byte[] ... ?
if (length % 4 != 0) {
for (int i; length % 4 != 0; length += i) {
i = (int) in.skip((4 - length % 4));
}
}
AvpImpl avp = new AvpImpl(code, (short) flags, (int) vendor, rawData);
avps.addAvp(avp);
counter += length;
}
return avps;
}
public byte[] encodeAvpSet(AvpSet avps) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
DataOutputStream data = new DataOutputStream(out);
for (Avp a : avps) {
if (a instanceof AvpImpl) {
AvpImpl aImpl = (AvpImpl) a;
if (aImpl.rawData.length == 0 && aImpl.groupedData != null) {
aImpl.rawData = encodeAvpSet(a.getGrouped());
}
data.write(encodeAvp(aImpl));
}
}
}
catch (Exception e) {
logger.debug("Error during encode avps", e);
}
return out.toByteArray();
}
public byte[] encodeAvp(AvpImpl avp) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
DataOutputStream data = new DataOutputStream(out);
data.writeInt(avp.getCode());
int flags = (byte) ((avp.getVendorId() != 0 ? 0x80 : 0) |
(avp.isMandatory() ? 0x40 : 0) | (avp.isEncrypted() ? 0x20 : 0));
int origLength = avp.getRaw().length + 8 + (avp.getVendorId() != 0 ? 4 : 0);
// newLength is never used. Should it?
//int newLength = origLength;
//if (newLength % 4 != 0) {
// newLength += 4 - (newLength % 4);
//}
data.writeInt(((flags << 24) & 0xFF000000) + origLength);
if (avp.getVendorId() != 0) {
data.writeInt((int) avp.getVendorId());
}
data.write(avp.getRaw());
if (avp.getRaw().length % 4 != 0) {
for(int i = 0; i < 4 - avp.getRaw().length % 4; i++) {
data.write(0);
}
}
}
catch (Exception e) {
logger.debug("Error during encode avp", e);
}
return out.toByteArray();
}
}
| 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.client.impl.parser;
/*
* https://jdiameter.dev.java.net/
*
* License: GPL v3
*
* e-mail: erick.svenson@yahoo.com
*
*/
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.URI;
import org.jdiameter.client.api.parser.ParseException;
/**
*
* @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 AvpSetImpl implements AvpSet {
// FIXME: by default 3588.4-1 says: 'M' should be set to true;
// FIXME: by default 3588.x says: if grouped has at least on AVP with 'M' set, it also has to have 'M' set! - TODO: add backmapping.
private static final long serialVersionUID = 1L;
private static final ElementParser parser = new ElementParser();
List<Avp> avps = new ArrayList<Avp>();
AvpSetImpl() {
}
public Avp getAvp(int avpCode) {
for (Avp avp : this.avps) {
if (avp.getCode() == avpCode) {
return avp;
}
}
return null;
}
public Avp getAvpByIndex(int avpIndex) {
return this.avps.get(avpIndex);
}
public Avp getAvp(int avpCode, long vendorId) {
for (Avp avp : this.avps) {
if (avp.getCode() == avpCode && avp.getVendorId() == vendorId) {
return avp;
}
}
return null;
}
public AvpSet getAvps(int avpCode) {
AvpSet result = new AvpSetImpl();
for (Avp avp : this.avps) {
if (avp.getCode() == avpCode) {
result.addAvp(avp);
}
}
return result;
}
public AvpSet getAvps(int avpCode, long vendorId) {
AvpSet result = new AvpSetImpl();
for (Avp avp : this.avps) {
if (avp.getCode() == avpCode && avp.getVendorId() == vendorId) {
result.addAvp(avp);
}
}
return result;
}
public AvpSet removeAvp(int avpCode) {
return removeAvp(avpCode, 0);
}
public AvpSet removeAvp(int avpCode, long vendorId) {
AvpSet result = new AvpSetImpl();
// for (Avp avp : this.avps) {
// if (avp.getCode() == avpCode) {
// result.addAvp(avp);
// this.avps.remove(avp);
// }
// }
Iterator<Avp> it = this.avps.iterator();
while(it.hasNext()) {
Avp avp = it.next();
if (avp.getCode() == avpCode && avp.getVendorId() == vendorId) {
result.addAvp(avp);
it.remove();
}
}
return result;
}
public Avp removeAvpByIndex(int i) {
return (i >= this.avps.size()) ? null : this.avps.remove(i);
}
public Avp[] asArray() {
return this.avps.toArray(new Avp[avps.size()]);
}
public Avp addAvp(int avpCode, long value, boolean asUnsigned) {
Avp res = new AvpImpl(avpCode, 0, 0, asUnsigned ? parser.intU32ToBytes(value) : parser.int64ToBytes(value));
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, long value, boolean mFlag, boolean pFlag, boolean asUnsigned) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags , 0, asUnsigned ? parser.intU32ToBytes(value) : parser.int64ToBytes(value));
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, long value, long vndId, boolean mFlag, boolean pFlag, boolean asUnsigned) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, vndId, asUnsigned ? parser.intU32ToBytes(value) : parser.int64ToBytes(value));
this.avps.add(res);
return res;
}
public void insertAvp(int index, Avp... avps) {
this.avps.addAll(index, Arrays.asList(avps));
}
public void insertAvp(int index, AvpSet avpSet) {
this.avps.addAll(index, Arrays.asList(avpSet.asArray()));
}
public Avp insertAvp(int index, int avpCode, long value, boolean asUnsigned) {
Avp res = new AvpImpl(avpCode, 0, 0, asUnsigned ? parser.intU32ToBytes(value) : parser.int64ToBytes(value));
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, long value, boolean mFlag, boolean pFlag, boolean asUnsigned) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags , 0, asUnsigned ? parser.intU32ToBytes(value) : parser.int64ToBytes(value));
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, long value, long vndId, boolean mFlag, boolean pFlag, boolean asUnsigned) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, vndId, asUnsigned ? parser.intU32ToBytes(value) : parser.int64ToBytes(value));
this.avps.add(res);
return res;
}
public AvpSet insertGroupedAvp(int index, int avpCode) {
AvpImpl res = new AvpImpl(avpCode, 0, 0, new byte[0]);
res.groupedData = new AvpSetImpl();
this.avps.add(index, res);
return res.groupedData;
}
public int size() {
return this.avps.size();
}
public void addAvp(AvpSet avpSet) {
for (Avp a:avpSet) avps.add(a);
}
public void addAvp(Avp... avps) {
for (Avp a : avps) {
// No need to clone AVP, right?
// Avp res = new AvpImpl(a);
if(a != null) {
this.avps.add(a);
}
}
}
public Avp addAvp(int avpCode, byte[] rawData) {
Avp res = new AvpImpl(avpCode, 0, 0, rawData);
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, byte[] rawData, boolean mFlag, boolean pFlag) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags , 0, rawData);
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, byte[] rawData, long vndId, boolean mFlag, boolean pFlag) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, vndId, rawData);
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, int value) {
Avp res = new AvpImpl(avpCode, 0, 0, parser.int32ToBytes(value));
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, int value, boolean mFlag, boolean pFlag) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, 0, parser.int32ToBytes(value));
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, int value, long vndId, boolean mFlag, boolean pFlag) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, vndId, parser.int32ToBytes(value));
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, long value) {
Avp res = new AvpImpl(avpCode, 0, 0, parser.int64ToBytes(value) );
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, long value, boolean mFlag, boolean pFlag) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, 0, parser.int64ToBytes(value) );
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, long value, long vndId, boolean mFlag, boolean pFlag) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, vndId, parser.int64ToBytes(value) );
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, float value) {
Avp res = new AvpImpl(avpCode, 0, 0, parser.float32ToBytes(value));
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, float value, boolean mFlag, boolean pFlag) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, 0, parser.float32ToBytes(value));
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, float value, long vndId, boolean mFlag, boolean pFlag) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, vndId, parser.float32ToBytes(value));
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, double value) {
Avp res = new AvpImpl(avpCode, 0, 0, parser.float64ToBytes(value));
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, double value, boolean mFlag, boolean pFlag) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, 0, parser.float64ToBytes(value));
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, double value, long vndId, boolean mFlag, boolean pFlag) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, vndId, parser.float64ToBytes(value));
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, String value, boolean asOctetString) {
try {
Avp res = new AvpImpl(avpCode, 0, 0, asOctetString ? parser.octetStringToBytes(value) : parser.utf8StringToBytes(value)
);
this.avps.add(res);
return res;
} catch(Exception e) {
throw new IllegalArgumentException(e);
}
}
public Avp addAvp(int avpCode, String value, boolean mFlag, boolean pFlag, boolean asOctetString) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
try {
Avp res = new AvpImpl(avpCode, flags, 0, asOctetString ? parser.octetStringToBytes(value) : parser.utf8StringToBytes(value)
);
this.avps.add(res);
return res;
} catch(Exception e) {
throw new IllegalArgumentException(e);
}
}
public Avp addAvp(int avpCode, String value, long vndId, boolean mFlag, boolean pFlag, boolean asOctetString) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
try {
Avp res = new AvpImpl(avpCode, flags, vndId, asOctetString ? parser.octetStringToBytes(value) : parser.utf8StringToBytes(value)
);
this.avps.add(res);
return res;
} catch(Exception e) {
throw new IllegalArgumentException(e);
}
}
public Avp addAvp(int avpCode, URI value) {
try {
Avp res = new AvpImpl(avpCode, 0, 0, parser.octetStringToBytes(value.toString()));
this.avps.add(res);
return res;
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
public Avp addAvp(int avpCode, URI value, boolean mFlag, boolean pFlag) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
try {
Avp res = new AvpImpl(avpCode, flags, 0, parser.octetStringToBytes(value.toString()));
this.avps.add(res);
return res;
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
public Avp addAvp(int avpCode, URI value, long vndId, boolean mFlag, boolean pFlag) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
try {
Avp res = new AvpImpl(avpCode, flags, vndId, parser.octetStringToBytes(value.toString()));
this.avps.add(res);
return res;
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
public Avp addAvp(int avpCode, InetAddress value) {
Avp res = new AvpImpl(avpCode, 0, 0, parser.addressToBytes(value));
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, InetAddress value, boolean mFlag, boolean pFlag) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, 0, parser.addressToBytes(value));
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, InetAddress value, long vndId, boolean mFlag, boolean pFlag) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, vndId, parser.addressToBytes(value));
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, Date value) {
Avp res = new AvpImpl(avpCode, 0, 0, parser.dateToBytes(value));
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, Date value, boolean mFlag, boolean pFlag) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, 0, parser.dateToBytes(value));
this.avps.add(res);
return res;
}
public Avp addAvp(int avpCode, Date value, long vndId, boolean mFlag, boolean pFlag) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, vndId, parser.dateToBytes(value));
this.avps.add(res);
return res;
}
public AvpSet addGroupedAvp(int avpCode) {
AvpImpl res = new AvpImpl(avpCode, 0, 0, new byte[0] );
res.groupedData = new AvpSetImpl();
this.avps.add(res);
return res.groupedData;
}
public AvpSet addGroupedAvp(int avpCode, boolean mFlag, boolean pFlag) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
AvpImpl res = new AvpImpl(avpCode, flags, 0, new byte[0] );
res.groupedData = new AvpSetImpl();
this.avps.add(res);
return res.groupedData;
}
public AvpSet addGroupedAvp(int avpCode, long vndId, boolean mFlag, boolean pFlag) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
AvpImpl res = new AvpImpl(avpCode, flags, vndId, new byte[0] );
res.groupedData = new AvpSetImpl();
this.avps.add(res);
return res.groupedData;
}
public Avp insertAvp(int index, int avpCode, byte[] value) {
Avp res = new AvpImpl(avpCode, 0, 0, value);
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, byte[] value, boolean mFlag, boolean pFlag) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, 0, value);
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, byte[] value, long vndId, boolean mFlag, boolean pFlag) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, vndId, value);
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, int value) {
Avp res = new AvpImpl(avpCode, 0, 0, parser.int32ToBytes(value));
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, int value, boolean mFlag, boolean pFlag) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, 0, parser.int32ToBytes(value));
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, int value, long vndId, boolean mFlag, boolean pFlag) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, vndId, parser.int32ToBytes(value));
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, long value) {
Avp res = new AvpImpl(avpCode, 0, 0, parser.int64ToBytes(value));
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, long value, boolean mFlag, boolean pFlag) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, 0, parser.int64ToBytes(value));
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, long value, long vndId, boolean mFlag, boolean pFlag) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, vndId, parser.int64ToBytes(value));
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, float value) {
Avp res = new AvpImpl(avpCode, 0, 0, parser.float32ToBytes(value));
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, float value, boolean mFlag, boolean pFlag) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, 0, parser.float32ToBytes(value));
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, float value, long vndId, boolean mFlag, boolean pFlag) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, vndId, parser.float32ToBytes(value));
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, double value) {
Avp res = new AvpImpl(avpCode, 0, 0, parser.float64ToBytes(value));
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, double value, boolean mFlag, boolean pFlag) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, 0, parser.float64ToBytes(value));
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, double value, long vndId, boolean mFlag, boolean pFlag) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, vndId, parser.float64ToBytes(value));
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, String value, boolean asOctetString) {
try {
Avp res = new AvpImpl(avpCode, 0, 0, asOctetString ? parser.octetStringToBytes(value) :
parser.utf8StringToBytes(value));
this.avps.add(index, res);
return res;
} catch(Exception e) {
throw new IllegalArgumentException(e);
}
}
public Avp insertAvp(int index, int avpCode, String value, boolean mFlag, boolean pFlag, boolean asOctetString) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
try {
Avp res = new AvpImpl(avpCode, flags, 0, asOctetString ? parser.octetStringToBytes(value) :
parser.utf8StringToBytes(value));
this.avps.add(index, res);
return res;
} catch(Exception e) {
throw new IllegalArgumentException(e);
}
}
public Avp insertAvp(int index, int avpCode, String value, long vndId, boolean mFlag, boolean pFlag, boolean asOctetString) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
try {
Avp res = new AvpImpl(avpCode, flags, vndId, asOctetString ? parser.octetStringToBytes(value) :
parser.utf8StringToBytes(value));
this.avps.add(index, res);
return res;
} catch(Exception e) {
throw new IllegalArgumentException(e);
}
}
public Avp insertAvp(int index, int avpCode, URI value) {
try {
Avp res = new AvpImpl(avpCode, 0, 0, parser.octetStringToBytes(value.toString()));
this.avps.add(index, res);
return res;
} catch(Exception e) {
throw new IllegalArgumentException(e);
}
}
public Avp insertAvp(int index, int avpCode, URI value, boolean mFlag, boolean pFlag) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
try {
Avp res = new AvpImpl(avpCode, flags, 0, parser.octetStringToBytes(value.toString()));
this.avps.add(index, res);
return res;
} catch(Exception e) {
throw new IllegalArgumentException(e);
}
}
public Avp insertAvp(int index, int avpCode, URI value, long vndId, boolean mFlag, boolean pFlag) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
try {
Avp res = new AvpImpl(avpCode, flags, vndId, parser.octetStringToBytes(value.toString()));
this.avps.add(index, res);
return res;
} catch(Exception e) {
throw new IllegalArgumentException(e);
}
}
public Avp insertAvp(int index, int avpCode, InetAddress value) {
Avp res = new AvpImpl(avpCode, 0, 0, parser.addressToBytes(value));
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, InetAddress value, boolean mFlag, boolean pFlag) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, 0, parser.addressToBytes(value));
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, InetAddress value, long vndId, boolean mFlag, boolean pFlag) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, vndId, parser.addressToBytes(value));
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, Date value) {
Avp res = new AvpImpl(avpCode, 0, 0, parser.dateToBytes(value));
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, Date value, boolean mFlag, boolean pFlag) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, 0, parser.dateToBytes(value));
this.avps.add(index, res);
return res;
}
public Avp insertAvp(int index, int avpCode, Date value, long vndId, boolean mFlag, boolean pFlag) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
Avp res = new AvpImpl(avpCode, flags, vndId, parser.dateToBytes(value));
this.avps.add(index, res);
return res;
}
public AvpSet insertGroupedAvp(int index, int avpCode, boolean mFlag, boolean pFlag) {
int flags = ((mFlag ? 0x40:0) | (pFlag ? 0x20:0));
AvpImpl res = new AvpImpl(avpCode, flags, 0, new byte[0] );
res.groupedData = new AvpSetImpl();
this.avps.add(index, res);
return res.groupedData;
}
public AvpSet insertGroupedAvp(int index, int avpCode, long vndId, boolean mFlag, boolean pFlag) {
int flags = ((vndId !=0 ? 0x80:0) | (mFlag ? 0x40:0) | (pFlag ? 0x20:0));
AvpImpl res = new AvpImpl(avpCode, flags, vndId, new byte[0] );
res.groupedData = new AvpSetImpl();
this.avps.add(index, res);
return res.groupedData;
}
public boolean isWrapperFor(Class<?> aClass) throws InternalException {
return false;
}
public <T> T unwrap(Class<T> aClass) throws InternalException {
return null;
}
public Iterator<Avp> iterator() {
// Iterator contract demands it to be able to remove items
// return Collections.unmodifiableList(this.avps).iterator();
return this.avps.iterator();
}
@Override
public String toString() {
return new StringBuffer("AvpSetImpl [avps=").append(avps).append("]@").append(super.hashCode()).toString();
}
}
| 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.client.impl.parser;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.jdiameter.api.Answer;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.InternalException;
import org.jdiameter.client.api.IEventListener;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.controller.IPeer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Represents a Diameter message.
*
* @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 MessageImpl implements IMessage {
private static final long serialVersionUID = 1L;
private static final Logger logger = LoggerFactory.getLogger(MessageImpl.class);
private static final MessageParser parser = new MessageParser();
int state = STATE_NOT_SENT;
short version = 1, flags;
int commandCode;
long applicationId;
long hopByHopId;
boolean notMutableHopByHop;
long endToEndId;
AvpSetImpl avpSet;
boolean isNetworkRequest = false;
transient IPeer peer;
transient TimerTask timerTask;
transient IEventListener listener;
// Cached result for getApplicationIdAvps() method. It is called extensively and takes some time.
// Potential place for dirt, but Application IDs don't change during message life time.
transient List<ApplicationId> applicationIds;
/**
* Create empty message
*
* @param parser
* @param commandCode
* @param appId
*/
MessageImpl(int commandCode, long appId) {
this.commandCode = commandCode;
this.applicationId = appId;
this.avpSet = new AvpSetImpl();
this.endToEndId = parser.getNextEndToEndId();
}
/**
* Create empty message
*
* @param parser
* @param commandCode
* @param applicationId
* @param flags
* @param hopByHopId
* @param endToEndId
* @param avpSet
*/
MessageImpl(int commandCode, long applicationId, short flags, long hopByHopId, long endToEndId, AvpSetImpl avpSet) {
this(commandCode, applicationId);
this.flags = flags;
this.hopByHopId = hopByHopId;
this.endToEndId = endToEndId;
if (avpSet != null) {
this.avpSet = avpSet;
}
}
// /**
// * Create empty message
// *
// * @param metaData
// * @param parser
// * @param commandCode
// * @param appId
// */
// MessageImpl(MetaData metaData, MessageParser parser, int commandCode, long appId) {
// this(commandCode, appId);
// try {
// getAvps().addAvp(Avp.ORIGIN_HOST, metaData.getLocalPeer().getUri().getFQDN(), true, false, true);
// getAvps().addAvp(Avp.ORIGIN_REALM, metaData.getLocalPeer().getRealmName(), true, false, true);
// }
// catch (Exception e) {
// logger.debug("Can not create message", e);
// }
// }
/**
* Create Answer
*
* @param request parent request
*/
private MessageImpl(MessageImpl request) {
this(request.getCommandCode(), request.getHeaderApplicationId());
copyHeader(request);
setRequest(false);
parser.copyBasicAvps(this, request, true);
}
public byte getVersion() {
return (byte) version;
}
public boolean isRequest() {
return (flags & 0x80) != 0;
}
public void setRequest(boolean b) {
if (b) {
flags |= 0x80;
}
else {
flags &= 0x7F;
}
}
public boolean isProxiable() {
return (flags & 0x40) != 0;
}
public void setProxiable(boolean b) {
if (b) {
flags |= 0x40;
}
else {
flags &= 0xBF;
}
}
public boolean isError() {
return (flags & 0x20) != 0;
}
public void setError(boolean b) {
if (b) {
flags |= 0x20;
}
else {
flags &= 0xDF;
}
}
public boolean isReTransmitted() {
return (flags & 0x10) != 0;
}
public void setReTransmitted(boolean b) {
if (b) {
flags |= 0x10;
}
else {
flags &= 0xEF;
}
}
public int getCommandCode() {
return this.commandCode;
}
public String getSessionId() {
try {
Avp avpSessionId = avpSet.getAvp(Avp.SESSION_ID);
return avpSessionId != null ? avpSessionId.getUTF8String() : null;
}
catch (AvpDataException ade) {
logger.error("Failed to fetch Session-Id", ade);
return null;
}
}
public Answer createAnswer() {
MessageImpl answer = new MessageImpl(this);
return answer;
}
public Answer createAnswer(long resultCode) {
MessageImpl answer = new MessageImpl(this);
try {
answer.getAvps().addAvp(Avp.RESULT_CODE, resultCode, true, false, true);
}
catch (Exception e) {
logger.debug("Can not create answer message", e);
}
//Its set in constructor.
//answer.setRequest(false);
return answer;
}
public Answer createAnswer(long vendorId, long experementalResultCode) {
MessageImpl answer = new MessageImpl(this);
try {
AvpSet exp_code = answer.getAvps().addGroupedAvp(297, true, false);
exp_code.addAvp(Avp.VENDOR_ID, vendorId, true, false, true);
exp_code.addAvp(Avp.EXPERIMENTAL_RESULT_CODE, experementalResultCode, true, false, true);
}
catch (Exception e) {
logger.debug("Can not create answer message", e);
}
answer.setRequest(false);
return answer;
}
public long getApplicationId() {
return applicationId;
}
public ApplicationId getSingleApplicationId() {
return getSingleApplicationId(this.applicationId);
}
public List<ApplicationId> getApplicationIdAvps() {
if (this.applicationIds != null) {
return this.applicationIds;
}
List<ApplicationId> rc = new ArrayList<ApplicationId>();
try {
AvpSet authAppId = avpSet.getAvps(Avp.AUTH_APPLICATION_ID);
for (Avp anAuthAppId : authAppId) {
rc.add(ApplicationId.createByAuthAppId((anAuthAppId).getInteger32()));
}
AvpSet accAppId = avpSet.getAvps(Avp.ACCT_APPLICATION_ID);
for (Avp anAccAppId : accAppId) {
rc.add(ApplicationId.createByAccAppId((anAccAppId).getInteger32()));
}
AvpSet specAppId = avpSet.getAvps(Avp.VENDOR_SPECIFIC_APPLICATION_ID);
for (Avp aSpecAppId : specAppId) {
long vendorId = 0, acctApplicationId = 0, authApplicationId = 0;
AvpSet avps = (aSpecAppId).getGrouped();
for (Avp localAvp : avps) {
if (localAvp.getCode() == Avp.VENDOR_ID) {
vendorId = localAvp.getUnsigned32();
}
if (localAvp.getCode() == Avp.AUTH_APPLICATION_ID) {
authApplicationId = localAvp.getUnsigned32();
}
if (localAvp.getCode() == Avp.ACCT_APPLICATION_ID) {
acctApplicationId = localAvp.getUnsigned32();
}
}
if (authApplicationId != 0) {
rc.add(ApplicationId.createByAuthAppId(vendorId, authApplicationId));
}
if (acctApplicationId != 0) {
rc.add(ApplicationId.createByAccAppId(vendorId, acctApplicationId));
}
}
}
catch (Exception exception) {
return new ArrayList<ApplicationId>();
}
this.applicationIds = rc;
return this.applicationIds;
}
public ApplicationId getSingleApplicationId(long applicationId) {
logger.debug("In getSingleApplicationId for application id [{}]", applicationId);
List<ApplicationId> appIds = getApplicationIdAvps();
logger.debug("Application Ids in this message are:");
ApplicationId firstOverall = null;
ApplicationId firstWithZeroVendor = null;
ApplicationId firstWithNonZeroVendor = null;
for (ApplicationId id : appIds) {
logger.debug("[{}]", id);
if (firstOverall == null) {
firstOverall = id;
}
if (applicationId != 0) {
if (firstWithZeroVendor == null && id.getVendorId() == 0 && (applicationId == id.getAuthAppId() || applicationId == id.getAcctAppId())) {
firstWithZeroVendor = id;
}
if (firstWithNonZeroVendor == null && id.getVendorId() != 0 && (applicationId == id.getAuthAppId() || applicationId == id.getAcctAppId())) {
firstWithNonZeroVendor = id;
break;
}
}
}
ApplicationId toReturn = null;
if (firstWithNonZeroVendor != null) {
toReturn = firstWithNonZeroVendor;
logger.debug("Returning [{}] as the first application id because its the first vendor specific one found", toReturn);
}
else if (firstWithZeroVendor != null) {
toReturn = firstWithZeroVendor;
logger.debug("Returning [{}] as the first application id because there are no vendor specific ones found", toReturn);
}
else {
toReturn = firstOverall;
logger.debug("Returning [{}] as the first application id because none with the requested app ids were found", toReturn);
}
if (toReturn == null) {
// TODO: ammendonca: improve this (find vendor? use common app list map?)
logger.debug("There are no Application-Id AVPs. Using the value in the header and assuming as Auth Application-Id [{}]", this.applicationId);
toReturn = ApplicationId.createByAuthAppId(this.applicationId);
}
return toReturn;
}
public long getHopByHopIdentifier() {
return hopByHopId;
}
public long getEndToEndIdentifier() {
return endToEndId;
}
public AvpSet getAvps() {
return avpSet;
}
protected void copyHeader(MessageImpl request) {
endToEndId = request.endToEndId;
hopByHopId = request.hopByHopId;
version = request.version;
flags = request.flags;
peer = request.peer;
}
public Avp getResultCode() {
return getAvps().getAvp(Avp.RESULT_CODE);
}
public void setNetworkRequest(boolean isNetworkRequest) {
this.isNetworkRequest = isNetworkRequest;
}
public boolean isNetworkRequest() {
return isNetworkRequest;
}
public boolean isWrapperFor(Class<?> aClass) throws InternalException {
return false;
}
public <T> T unwrap(Class<T> aClass) throws InternalException {
return null;
}
// Inner API
public void setHopByHopIdentifier(long hopByHopId) {
if (hopByHopId < 0) {
this.hopByHopId = -hopByHopId;
this.notMutableHopByHop = true;
}
else {
if (!this.notMutableHopByHop) {
this.hopByHopId = hopByHopId;
}
}
}
public void setEndToEndIdentifier(long endByEndId) {
this.endToEndId = endByEndId;
}
public IPeer getPeer() {
return peer;
}
public void setPeer(IPeer peer) {
this.peer = peer;
}
public int getState() {
return state;
}
public long getHeaderApplicationId() {
return applicationId;
}
public void setHeaderApplicationId(long applicationId) {
this.applicationId = applicationId;
}
public int getFlags() {
return flags;
}
public void setState(int newState) {
state = newState;
}
public void createTimer(ScheduledExecutorService scheduledFacility, long timeOut, TimeUnit timeUnit) {
timerTask = new TimerTask(this);
timerTask.setTimerHandler(scheduledFacility, scheduledFacility.schedule(timerTask, timeOut, timeUnit));
}
public void runTimer() {
if (timerTask != null && !timerTask.isDone() && !timerTask.isCancelled()) {
timerTask.run();
}
}
public boolean isTimeOut() {
return timerTask != null && timerTask.isDone() && !timerTask.isCancelled();
}
public void setListener(IEventListener listener) {
this.listener = listener;
}
public IEventListener getEventListener() {
return listener;
}
public void clearTimer() {
if (timerTask != null) {
timerTask.cancel();
}
}
public String toString() {
return "MessageImpl{" + "commandCode=" + commandCode + ", flags=" + flags + '}';
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MessageImpl message = (MessageImpl) o;
return applicationId == message.applicationId && commandCode == message.commandCode &&
endToEndId == message.endToEndId && hopByHopId == message.hopByHopId;
}
public int hashCode() {
long result;
result = commandCode;
result = 31 * result + applicationId;
result = 31 * result + hopByHopId;
result = 31 * result + endToEndId;
return new Long(result).hashCode();
}
public String getDuplicationKey() {
try {
return getDuplicationKey(getAvps().getAvp(Avp.ORIGIN_HOST).getDiameterIdentity(), getEndToEndIdentifier());
}
catch (AvpDataException e) {
throw new IllegalArgumentException(e);
}
}
public String getDuplicationKey(String host, long endToEndId) {
return host + endToEndId;
}
public Object clone() {
try {
return parser.createMessage(parser.encodeMessage(this));
}
catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
protected static class TimerTask implements Runnable {
ScheduledFuture timerHandler;
MessageImpl message;
ScheduledExecutorService scheduledFacility;
public TimerTask(MessageImpl message) {
this.message = message;
}
public void setTimerHandler(ScheduledExecutorService scheduledFacility, ScheduledFuture timerHandler) {
this.scheduledFacility = scheduledFacility;
this.timerHandler = timerHandler;
}
public void run() {
try {
if (message != null && message.state != STATE_ANSWERED) {
IEventListener listener = null;
if (message.listener instanceof IEventListener) {
listener = message.listener;
}
if (listener != null && listener.isValid()) {
if (message.peer != null) {
message.peer.remMessage(message);
}
message.listener.timeoutExpired(message);
}
}
}
catch(Throwable e) {
logger.debug("Can not process timeout", e);
}
}
public void cancel() {
if (timerHandler != null) {
timerHandler.cancel(true);
if (scheduledFacility instanceof ThreadPoolExecutor && timerHandler instanceof Runnable) {
((ThreadPoolExecutor) scheduledFacility).remove((Runnable) timerHandler);
}
}
message = null;
}
public boolean isDone() {
return timerHandler != null && timerHandler.isDone();
}
public boolean isCancelled() {
return timerHandler == null || timerHandler.isCancelled();
}
}
}
| 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.client.impl.parser;
import static org.jdiameter.api.Avp.ACCT_APPLICATION_ID;
import static org.jdiameter.api.Avp.AUTH_APPLICATION_ID;
import static org.jdiameter.api.Avp.SESSION_ID;
import static org.jdiameter.api.Avp.VENDOR_SPECIFIC_APPLICATION_ID;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.Request;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.IRequest;
import org.jdiameter.client.api.parser.IMessageParser;
import org.jdiameter.client.api.parser.ParseException;
import org.jdiameter.client.impl.helpers.UIDGenerator;
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 MessageParser extends ElementParser implements IMessageParser {
private static final Logger logger = LoggerFactory.getLogger(MessageParser.class);
protected UIDGenerator endToEndGen = new UIDGenerator(
(int) (TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()) & 0xFFF) << 20
);
public MessageParser() {
}
public IMessage createMessage(ByteBuffer data) throws AvpDataException {
// Read header
try {
byte[] message = data.array();
long tmp;
DataInputStream in = new DataInputStream(new ByteArrayInputStream(message));
tmp = in.readInt();
short version = (short) (tmp >> 24);
if (version != 1) {
throw new Exception("Illegal value of version " + version);
}
if (message.length != (tmp & 0x00FFFFFF)) {
//throw new ParseException("Wrong length of data: " + (tmp & 0x00FFFFFF));
throw new Exception("Wrong length of data: " + (tmp & 0x00FFFFFF));
}
tmp = in.readInt();
short flags = (short) ((tmp >> 24) & 0xFF);
int commandCode = (int) (tmp & 0xFFFFFF);
long applicationId = ((long) in.readInt() << 32) >>> 32;
long hopByHopId = ((long) in.readInt() << 32) >>> 32;
long endToEndId = ((long) in.readInt() << 32) >>> 32;
// Read body
// byte[] body = new byte[message.length - 20];
// System.arraycopy(message, 20, body, 0, body.length);
// AvpSetImpl avpSet = decodeAvpSet(body);
AvpSetImpl avpSet = decodeAvpSet(message, 20);
return new MessageImpl(commandCode, applicationId, flags, hopByHopId, endToEndId, avpSet);
}
catch (Exception exc) {
throw new AvpDataException(exc);
}
}
public <T> T createMessage(Class<?> iface, ByteBuffer data) throws AvpDataException {
if (iface == IMessage.class) {
return (T) createMessage(data);
}
return null;
}
public <T> T createEmptyMessage(Class<?> iface, IMessage parentMessage) {
if (iface == Request.class) {
return (T) createEmptyMessage(parentMessage, parentMessage.getCommandCode());
}
else {
return null;
}
}
public IMessage createEmptyMessage(IMessage prnMessage) {
return createEmptyMessage(prnMessage, prnMessage.getCommandCode());
}
public IMessage createEmptyMessage(IMessage prnMessage, int commandCode) {
//
MessageImpl newMessage = new MessageImpl(
commandCode,
prnMessage.getHeaderApplicationId(),
(short) prnMessage.getFlags(),
prnMessage.getHopByHopIdentifier(),
endToEndGen.nextLong(),
null
);
copyBasicAvps(newMessage, prnMessage, false);
return newMessage;
}
void copyBasicAvps(IMessage newMessage, IMessage prnMessage, boolean invertPoints) {
//left it here, but
Avp avp;
// Copy session id's information
{
avp = prnMessage.getAvps().getAvp(SESSION_ID);
if (avp != null) {
newMessage.getAvps().addAvp(new AvpImpl(avp));
}
avp = prnMessage.getAvps().getAvp(Avp.ACC_SESSION_ID);
if (avp != null) {
newMessage.getAvps().addAvp(new AvpImpl(avp));
}
avp = prnMessage.getAvps().getAvp(Avp.ACC_SUB_SESSION_ID);
if (avp != null) {
newMessage.getAvps().addAvp(new AvpImpl(avp));
}
avp = prnMessage.getAvps().getAvp(Avp.ACC_MULTI_SESSION_ID);
if (avp != null) {
newMessage.getAvps().addAvp(new AvpImpl(avp));
}
}
// Copy Applicatio id's information
{
avp = prnMessage.getAvps().getAvp(VENDOR_SPECIFIC_APPLICATION_ID);
if (avp != null) {
newMessage.getAvps().addAvp(new AvpImpl(avp));
}
avp = prnMessage.getAvps().getAvp(ACCT_APPLICATION_ID);
if (avp != null) {
newMessage.getAvps().addAvp(new AvpImpl(avp));
}
avp = prnMessage.getAvps().getAvp(AUTH_APPLICATION_ID);
if (avp != null) {
newMessage.getAvps().addAvp(new AvpImpl(avp));
}
}
// Copy proxy information
{
AvpSet avps = prnMessage.getAvps().getAvps(Avp.PROXY_INFO);
for (Avp piAvp : avps) {
newMessage.getAvps().addAvp(new AvpImpl(piAvp));
}
}
// Copy route information
{
if (newMessage.isRequest()) {
if (invertPoints) {
// set Dest host
avp = prnMessage.getAvps().getAvp(Avp.ORIGIN_HOST);
if (avp != null) {
newMessage.getAvps().addAvp(new AvpImpl(Avp.DESTINATION_HOST, avp));
}
// set Dest realm
avp = prnMessage.getAvps().getAvp(Avp.ORIGIN_REALM);
if (avp != null) {
newMessage.getAvps().addAvp(new AvpImpl(Avp.DESTINATION_REALM, avp));
}
}
else {
// set Dest host
avp = prnMessage.getAvps().getAvp(Avp.DESTINATION_HOST);
if (avp != null) {
newMessage.getAvps().addAvp(avp);
}
// set Dest realm
avp = prnMessage.getAvps().getAvp(Avp.DESTINATION_REALM);
if (avp != null) {
newMessage.getAvps().addAvp(avp);
}
}
}
// // set Orig host and realm
// try {
// newMessage.getAvps().addAvp(Avp.ORIGIN_HOST, metaData.getLocalPeer().getUri().getFQDN(), true, false, true);
// newMessage.getAvps().addAvp(Avp.ORIGIN_REALM, metaData.getLocalPeer().getRealmName(), true, false, true);
// }
// catch (Exception e) {
// logger.debug("Error copying Origin-Host/Realm AVPs", e);
// }
}
}
public ByteBuffer encodeMessage(IMessage message) throws ParseException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
byte[] rawData = encodeAvpSet(message.getAvps());
DataOutputStream data = new DataOutputStream(out);
// Wasting processor time, are we ?
// int tmp = (1 << 24) & 0xFF000000;
int tmp = (1 << 24);
tmp += 20 + rawData.length;
data.writeInt(tmp);
// Again, unneeded operation ?
// tmp = (message.getFlags() << 24) & 0xFF000000;
tmp = (message.getFlags() << 24);
tmp += message.getCommandCode();
data.writeInt(tmp);
data.write(toBytes(message.getHeaderApplicationId()));
data.write(toBytes(message.getHopByHopIdentifier()));
data.write(toBytes(message.getEndToEndIdentifier()));
data.write(rawData);
}
catch (Exception e) {
//logger.debug("Error during encode message", e);
throw new ParseException("Failed to encode message.", e);
}
try{
return prepareBuffer(out.toByteArray(), out.size());
}
catch(AvpDataException ade) {
throw new ParseException(ade);
}
}
private byte[] toBytes(long value) {
byte[] data = new byte[4];
data[0] = (byte) ((value >> 24) & 0xFF);
data[1] = (byte) ((value >> 16) & 0xFF);
data[2] = (byte) ((value >> 8) & 0xFF);
data[3] = (byte) ((value) & 0xFF);
return data;
}
public IMessage createEmptyMessage(int commandCode, long headerAppId) {
return new MessageImpl(commandCode, headerAppId);
}
public <T> T createEmptyMessage(Class<?> iface, int commandCode, long headerAppId) {
if (iface == IRequest.class) {
return (T) new MessageImpl(commandCode, headerAppId);
}
return null;
}
public int getNextEndToEndId() {
return endToEndGen.nextInt();
}
}
| 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.client.impl.parser;
import java.net.InetAddress;
import java.net.URISyntaxException;
import java.net.UnknownServiceException;
import java.util.Date;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.URI;
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>
*/
class AvpImpl implements Avp {
private static final long serialVersionUID = 1L;
private static final ElementParser parser = new ElementParser();
int avpCode;
long vendorID;
boolean isMandatory = false;
boolean isEncrypted = false;
boolean isVendorSpecific = false;
byte[] rawData = new byte[0];
AvpSet groupedData;
private static final Logger logger = LoggerFactory.getLogger(AvpImpl.class);
AvpImpl(int code, int flags, long vnd, byte[] data) {
avpCode = code;
//
isMandatory = (flags & 0x40) != 0;
isEncrypted = (flags & 0x20) != 0;
isVendorSpecific = (flags & 0x80) != 0;
//
vendorID = vnd;
rawData = data;
}
AvpImpl(Avp avp) {
avpCode = avp.getCode();
vendorID = avp.getVendorId();
isMandatory = avp.isMandatory();
isEncrypted = avp.isEncrypted();
isVendorSpecific = avp.isVendorId();
try {
rawData = avp.getRaw();
if (rawData == null || rawData.length == 0) {
groupedData = avp.getGrouped();
}
}
catch (AvpDataException e) {
logger.debug("Can not create Avp", e);
}
}
public AvpImpl(int newCode, Avp avp) {
this(avp);
avpCode = newCode;
}
public int getCode() {
return avpCode;
}
public boolean isVendorId() {
return isVendorSpecific;
}
public boolean isMandatory() {
return isMandatory;
}
public boolean isEncrypted() {
return isEncrypted;
}
public long getVendorId() {
return vendorID;
}
public byte[] getRaw() throws AvpDataException {
return rawData;
}
public byte[] getOctetString() throws AvpDataException {
return rawData;
}
public String getUTF8String() throws AvpDataException {
try {
return parser.bytesToUtf8String(rawData);
}
catch (Exception e) {
throw new AvpDataException(e, this);
}
}
public int getInteger32() throws AvpDataException {
try {
return parser.bytesToInt(rawData);
}
catch (Exception e) {
throw new AvpDataException(e, this);
}
}
public long getInteger64() throws AvpDataException {
try {
return parser.bytesToLong(rawData);
}
catch (Exception e) {
throw new AvpDataException(e, this);
}
}
public long getUnsigned32() throws AvpDataException {
try {
byte[] u32ext = new byte[8];
System.arraycopy(rawData, 0, u32ext, 4, 4);
return parser.bytesToLong(u32ext);
}
catch (Exception e) {
throw new AvpDataException(e, this);
}
}
public long getUnsigned64() throws AvpDataException {
try {
return parser.bytesToLong(rawData);
}
catch (Exception e) {
throw new AvpDataException(e, this);
}
}
public float getFloat32() throws AvpDataException {
try {
return parser.bytesToFloat(rawData);
}
catch (Exception e) {
throw new AvpDataException(e, this);
}
}
public double getFloat64() throws AvpDataException {
try {
return parser.bytesToDouble(rawData);
}
catch (Exception e) {
throw new AvpDataException(e, this);
}
}
public InetAddress getAddress() throws AvpDataException {
try {
return parser.bytesToAddress(rawData);
}
catch (Exception e) {
throw new AvpDataException(e, this);
}
}
public Date getTime() throws AvpDataException {
try {
return parser.bytesToDate(rawData);
}
catch (Exception e) {
throw new AvpDataException(e, this);
}
}
public String getDiameterIdentity() throws AvpDataException {
try {
return parser.bytesToOctetString(rawData);
}
catch (Exception e) {
throw new AvpDataException(e, this);
}
}
public URI getDiameterURI() throws AvpDataException {
try {
return new URI(parser.bytesToOctetString(rawData));
}
catch (URISyntaxException e) {
throw new AvpDataException(e, this);
}
catch (UnknownServiceException e) {
throw new AvpDataException(e, this);
}
}
public AvpSet getGrouped() throws AvpDataException {
try {
if (groupedData == null) {
groupedData = parser.decodeAvpSet(rawData);
rawData = new byte[0];
}
return groupedData;
}
catch (Exception e) {
throw new AvpDataException(e, this);
}
}
public boolean isWrapperFor(Class<?> aClass) throws InternalException {
return false;
}
public <T> T unwrap(Class<T> aClass) throws InternalException {
return null;
}
public byte[] getRawData() {
return (rawData == null || rawData.length == 0) ? parser.encodeAvpSet(groupedData) : rawData;
}
// Caching toString.. Avp shouldn't be modified once created.
private String toString;
@Override
public String toString() {
if(toString == null) {
this.toString = new StringBuffer("AvpImpl [avpCode=").append(avpCode).append(", vendorID=").append(vendorID).append("]@").append(super.hashCode()).toString();
}
return this.toString;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl;
import org.jdiameter.api.*;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.parser.IMessageParser;
import java.util.concurrent.TimeUnit;
/**
*
* @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 RawSessionImpl extends BaseSessionImpl implements RawSession {
RawSessionImpl(IContainer stack) {
container = stack;
this.parser = (IMessageParser) container.getAssemblerFacility().
getComponentInstance(IMessageParser.class);
}
public Message createMessage(int commandCode, ApplicationId appId, Avp... avps) {
if ( isValid ) {
lastAccessedTime = System.currentTimeMillis();
IMessage m = parser.createEmptyMessage(commandCode, getAppId(appId));
m.getAvps().addAvp(avps);
appendAppId(appId, m);
return m;
} else {
throw new IllegalStateException("Session already released");
}
}
public Message createMessage(int commandCode, ApplicationId appId, long hopByHopIdentifier, long endToEndIdentifier, Avp... avps) {
if ( isValid ) {
lastAccessedTime = System.currentTimeMillis();
IMessage m = parser.createEmptyMessage(commandCode, getAppId(appId));
if (hopByHopIdentifier >= 0)
m.setHopByHopIdentifier(-hopByHopIdentifier);
if (endToEndIdentifier >=0)
m.setEndToEndIdentifier(endToEndIdentifier);
m.getAvps().addAvp(avps);
appendAppId(appId, m);
return m;
} else {
throw new IllegalStateException("Session already released");
}
}
public Message createMessage(Message message, boolean copyAvps) {
if ( isValid ) {
lastAccessedTime = System.currentTimeMillis();
IMessage newMessage = null;
IMessage inner = (IMessage) message;
if (copyAvps) {
newMessage = parser.createEmptyMessage(inner);
MessageUtility.addOriginAvps(newMessage, container.getMetaData());
} else {
newMessage = (IMessage) createMessage(
inner.getCommandCode(),
inner.getSingleApplicationId(),
-1,
-1
);
}
newMessage.setRequest(message.isRequest());
newMessage.setProxiable(message.isProxiable());
newMessage.setError(message.isError());
newMessage.setReTransmitted(message.isReTransmitted());
return newMessage;
} else {
throw new IllegalStateException("Session already released");
}
}
public void send(Message message, EventListener<Message, Message> listener) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
genericSend(message, listener);
}
public void send(Message message, EventListener<Message, Message> listener, long timeOut, TimeUnit timeUnit) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
genericSend(message, listener, timeOut, timeUnit);
}
public void release() {
isValid = false;
container = null;
parser = null;
}
public boolean isWrapperFor(Class<?> iface) throws InternalException {
return iface == Session.class;
}
public <T> T unwrap(Class<T> iface) throws InternalException {
return (T) (iface == Session.class ? new SessionImpl(container) : null);
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl;
import java.io.InputStream;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class VersionProperties {
/**
* The single instance.
*/
public final static VersionProperties instance = new VersionProperties();
/**
* The version properties.
*/
private Properties props;
/**
* Do not allow direct public construction.
*/
private VersionProperties() {
props = loadProperties();
}
/**
* Returns an unmodifiable map of version properties.
*
* @return
*/
public Map getProperties() {
return Collections.unmodifiableMap(props);
}
/**
* Returns the value for the given property name.
*
* @param name
* - The name of the property.
* @return The property value or null if the property is not set.
*/
public String getProperty(final String name) {
return props.getProperty(name);
}
/**
* Returns the version information as a string.
*
* @return Basic information as a string.
*/
public String toString() {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (Object key : props.keySet()) {
if (first) {
first = false;
}
else {
sb.append(" , ");
}
sb.append(key).append(" = ").append(props.get(key));
}
return sb.toString();
}
/**
* Load the version properties from a resource.
*/
private Properties loadProperties() {
props = new Properties();
try {
InputStream in = VersionProperties.class.getResourceAsStream("/META-INF/version.properties");
props.load(in);
in.close();
}
catch (Exception e) {
// failed to load version properties. go with defaults
props.put("vendor", "Mobicents");
props.put("version", "UN.DEFINED");
}
return props;
}
} | Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl;
import static org.jdiameter.client.impl.helpers.ExtensionPoint.ControllerLayer;
import static org.jdiameter.client.impl.helpers.ExtensionPoint.StackLayer;
import static org.jdiameter.client.impl.helpers.ExtensionPoint.TransportLayer;
import static org.jdiameter.client.impl.helpers.Parameters.Assembler;
import static org.jdiameter.common.api.concurrent.IConcurrentFactory.ScheduledExecServices.ProcessingMessageTimer;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.BaseSession;
import org.jdiameter.api.Configuration;
import org.jdiameter.api.DisconnectCause;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.MetaData;
import org.jdiameter.api.Mode;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.Peer;
import org.jdiameter.api.PeerState;
import org.jdiameter.api.PeerTable;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.SessionFactory;
import org.jdiameter.api.app.StateChangeListener;
import org.jdiameter.api.validation.Dictionary;
import org.jdiameter.api.validation.ValidatorLevel;
import org.jdiameter.client.api.IAssembler;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.IMetaData;
import org.jdiameter.client.api.StackState;
import org.jdiameter.client.api.controller.IPeer;
import org.jdiameter.client.api.controller.IPeerTable;
import org.jdiameter.client.impl.helpers.Parameters;
import org.jdiameter.common.api.concurrent.IConcurrentFactory;
import org.jdiameter.common.api.data.ISessionDatasource;
import org.jdiameter.common.api.statistic.IStatisticProcessor;
import org.jdiameter.common.api.timer.ITimerFacility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Use stack extension point
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class StackImpl implements IContainer, StackImplMBean {
private static final Logger log = LoggerFactory.getLogger(StackImpl.class);
protected IAssembler assembler;
protected IConcurrentFactory concurrentFactory;
protected Configuration config;
protected IPeerTable peerManager;
protected StackState state = StackState.IDLE;
protected Lock lock = new ReentrantLock();
/**
* Use for processing request time-out tasks (for all active peers)
*/
protected ScheduledExecutorService scheduledFacility;
@SuppressWarnings("unchecked")
public SessionFactory init(Configuration config) throws IllegalDiameterStateException, InternalException {
lock.lock();
if (log.isInfoEnabled()) {
log.info("(-)(-)(-)(-)(-) Starting " + VersionProperties.instance.getProperty("vendor") + " DIAMETER Stack v" + VersionProperties.instance.getProperty("version") + " (-)(-)(-)(-)(-)");
}
try {
if (state != StackState.IDLE) {
throw new IllegalDiameterStateException();
}
try {
Class assemblerClass = Class.forName(config.getStringValue(Assembler.ordinal(), (String) Assembler.defValue()));
assembler = (IAssembler) assemblerClass.getConstructor(Configuration.class).newInstance(config);
// register common instances
assembler.registerComponentInstance(this);
assembler.registerComponentInstance(config);
}
catch (Exception e) {
throw new InternalException(e);
}
this.config = config;
this.concurrentFactory = (IConcurrentFactory) assembler.getComponentInstance(IConcurrentFactory.class);
try {
Configuration[] dictionaryConfigs = config.getChildren(Parameters.Dictionary.ordinal());
// Initialize with default values
String dictionaryClassName = (String) Parameters.DictionaryClass.defValue();
Boolean validatorEnabled = (Boolean) Parameters.DictionaryEnabled.defValue();
ValidatorLevel validatorSendLevel = ValidatorLevel.fromString((String) Parameters.DictionarySendLevel.defValue());
ValidatorLevel validatorReceiveLevel = ValidatorLevel.fromString((String) Parameters.DictionaryReceiveLevel.defValue());
if (dictionaryConfigs != null && dictionaryConfigs.length > 0) {
Configuration dictionaryConfiguration = dictionaryConfigs[0];
dictionaryClassName = dictionaryConfiguration.getStringValue(Parameters.DictionaryClass.ordinal(), (String) Parameters.DictionaryClass.defValue());
validatorEnabled = dictionaryConfiguration.getBooleanValue(Parameters.DictionaryEnabled.ordinal(), (Boolean) Parameters.DictionaryEnabled.defValue());
validatorSendLevel = ValidatorLevel.fromString(dictionaryConfiguration.getStringValue(Parameters.DictionarySendLevel.ordinal(),
(String) Parameters.DictionarySendLevel.defValue()));
validatorReceiveLevel = ValidatorLevel.fromString(dictionaryConfiguration.getStringValue(Parameters.DictionaryReceiveLevel.ordinal(),
(String) Parameters.DictionaryReceiveLevel.defValue()));
}
createDictionary(dictionaryClassName, validatorEnabled, validatorSendLevel, validatorReceiveLevel);
}
catch (Exception e) {
throw new InternalException(e);
}
// create manager
this.peerManager = (IPeerTable) assembler.getComponentInstance(IPeerTable.class);
this.peerManager.setAssembler(assembler);
this.state = StackState.CONFIGURED;
}
finally {
lock.unlock();
}
if (log.isInfoEnabled()) {
log.info("(-)(-)(-)(-)(-) Started " + VersionProperties.instance.getProperty("vendor") + " DIAMETER Stack v" + VersionProperties.instance.getProperty("version") + " (-)(-)(-)(-)(-)");
}
return (SessionFactory) assembler.getComponentInstance(SessionFactory.class);
}
private void createDictionary(String clazz, boolean validatorEnabled, ValidatorLevel validatorSendLevel, ValidatorLevel validatorReceiveLevel)
throws InternalException {
// Defer call to singleton
DictionarySingleton.init(clazz, validatorEnabled, validatorSendLevel, validatorReceiveLevel);
}
public SessionFactory getSessionFactory() throws IllegalDiameterStateException {
if (state == StackState.CONFIGURED || state == StackState.STARTED) {
// FIXME: When possible, get rid of IoC here.
return (SessionFactory) assembler.getComponentInstance(SessionFactory.class);
}
else {
throw new IllegalDiameterStateException();
}
}
public Dictionary getDictionary() throws IllegalDiameterStateException {
return DictionarySingleton.getDictionary();
}
public void start() throws IllegalDiameterStateException, InternalException {
lock.lock();
try {
if (state != StackState.STOPPED && state != StackState.CONFIGURED) {
throw new IllegalDiameterStateException();
}
scheduledFacility = concurrentFactory.getScheduledExecutorService(ProcessingMessageTimer.name());
assembler.getComponentInstance(ISessionDatasource.class).start();
assembler.getComponentInstance(IStatisticProcessor.class).start();
assembler.getComponentInstance(ITimerFacility.class);
startPeerManager();
state = StackState.STARTED;
}
finally {
lock.unlock();
}
}
@SuppressWarnings("unchecked")
public void start(final Mode mode, long timeOut, TimeUnit timeUnit) throws IllegalDiameterStateException, InternalException {
lock.lock();
try {
if (state != StackState.STOPPED && state != StackState.CONFIGURED) {
throw new IllegalDiameterStateException();
}
scheduledFacility = concurrentFactory.getScheduledExecutorService(ProcessingMessageTimer.name());
assembler.getComponentInstance(IStatisticProcessor.class).start();
assembler.getComponentInstance(ISessionDatasource.class).start();
assembler.getComponentInstance(ITimerFacility.class);
List<Peer> peerTable = peerManager.getPeerTable();
// considering only "to connect" peers are on the table at this time...
final CountDownLatch barrier = new CountDownLatch(Mode.ANY_PEER.equals(mode) ? Math.min(peerTable.size(), 1) : peerTable.size());
StateChangeListener listener = new AbstractStateChangeListener() {
public void stateChanged(Enum oldState, Enum newState) {
if (PeerState.OKAY.equals(newState)) {
barrier.countDown();
}
}
};
for (Peer p : peerTable) {
((IPeer) p).addStateChangeListener(listener);
}
startPeerManager();
try {
barrier.await(timeOut, timeUnit);
if (barrier.getCount() != 0) {
throw new InternalException("TimeOut");
}
state = StackState.STARTED;
}
catch (InterruptedException e) {
throw new InternalException("TimeOut");
}
finally {
for (Peer p : peerTable) {
((IPeer) p).remStateChangeListener(listener);
}
}
}
finally {
lock.unlock();
}
}
private void startPeerManager() throws InternalException {
try {
if (peerManager != null) {
peerManager.start();
}
getMetaData().unwrap(IMetaData.class).updateLocalHostStateId();
}
catch (Exception e) {
throw new InternalException(e);
}
}
@SuppressWarnings("unchecked")
public void stop(long timeOut, TimeUnit timeUnit, int disconnectCause) throws IllegalDiameterStateException, InternalException {
lock.lock();
try {
if (state == StackState.STARTED || state == StackState.CONFIGURED) {
if (log.isInfoEnabled()) {
log.info("(-)(-)(-)(-)(-) Stopping " + VersionProperties.instance.getProperty("vendor") + " DIAMETER Stack v" + VersionProperties.instance.getProperty("version") + " (-)(-)(-)(-)(-)");
}
List<Peer> peerTable = peerManager.getPeerTable();
final CountDownLatch barrier = new CountDownLatch(peerTable.size());
StateChangeListener listener = new AbstractStateChangeListener() {
public void stateChanged(Enum oldState, Enum newState) {
if (PeerState.DOWN.equals(newState)) {
barrier.countDown();
}
}
};
for (Peer p : peerTable) {
if (p.getState(PeerState.class).equals(PeerState.DOWN)) {
barrier.countDown();
}
else {
((IPeer) p).addStateChangeListener(listener);
}
}
if (peerManager != null) {
try {
peerManager.stopping(disconnectCause);
}
catch (Exception e) {
log.warn("Stopping error", e);
}
}
try {
barrier.await(timeOut, timeUnit);
if (barrier.getCount() != 0) {
throw new InternalException("TimeOut");
}
}
catch (InterruptedException e) {
throw new InternalException("TimeOut");
}
finally {
state = StackState.STOPPED;
for (Peer p : peerTable) {
((IPeer) p).remStateChangeListener(listener);
}
}
assembler.getComponentInstance(ISessionDatasource.class).stop();
assembler.getComponentInstance(IStatisticProcessor.class).stop();
try {
if (peerManager != null) {
peerManager.stopped();
}
// Clear all timeout tasks
if (scheduledFacility != null) {
concurrentFactory.shutdownNow(scheduledFacility);
}
}
catch (Exception e) {
log.warn("Stopped error", e);
}
state = StackState.STOPPED;
if (log.isInfoEnabled()) {
log.info("(-)(-)(-)(-)(-) Stopped " + VersionProperties.instance.getProperty("vendor") + " DIAMETER Stack v" + VersionProperties.instance.getProperty("version") + " (-)(-)(-)(-)(-)");
}
}
}
finally {
lock.unlock();
}
}
public void destroy() {
// Be friendly
if (state == StackState.STARTED) {
log.warn("Calling destroy() with Stack in STARTED state. Calling stop(REBOOTING) before, please do it yourself with the proper cause.");
stop(DisconnectCause.REBOOTING);
}
lock.lock();
try {
if (peerManager != null) {
peerManager.destroy();
}
if (assembler != null) {
assembler.destroy();
}
if (scheduledFacility != null) {
concurrentFactory.shutdownNow(scheduledFacility);
}
}
catch (Exception e) {
log.warn("Destroy error", e);
}
finally {
state = StackState.IDLE;
lock.unlock();
}
}
public boolean isActive() {
return state == StackState.STARTED;
}
public java.util.logging.Logger getLogger() {
return java.util.logging.Logger.getAnonymousLogger();
}
public MetaData getMetaData() {
if (state == StackState.IDLE) {
throw new IllegalStateException("Meta data not defined");
}
return (MetaData) assembler.getComponentInstance(IMetaData.class);
}
@SuppressWarnings("unchecked")
public <T extends BaseSession> T getSession(String sessionId, Class<T> clazz) throws InternalException {
if (getState() == StackState.IDLE) {
throw new InternalException("Illegal state of stack");
}
BaseSession bs = assembler.getComponentInstance(ISessionDatasource.class).getSession(sessionId);
return bs != null ? (T) bs : null;
}
public boolean isWrapperFor(Class<?> aClass) throws InternalException {
boolean isWrap = aClass == PeerTable.class;
if (!isWrap) {
isWrap = assembler.getChilds()[StackLayer.id()].getComponentInstance(aClass) != null;
}
if (!isWrap) {
isWrap = assembler.getChilds()[ControllerLayer.id()].getComponentInstance(aClass) != null;
}
if (!isWrap) {
isWrap = assembler.getChilds()[TransportLayer.id()].getComponentInstance(aClass) != null;
}
return isWrap;
}
@SuppressWarnings("unchecked")
public <T> T unwrap(Class<T> aClass) throws InternalException {
Object unwrapObject = null;
if (aClass == PeerTable.class) {
unwrapObject = assembler.getComponentInstance(aClass);
}
// TODO: "layers" should be removed....
if (unwrapObject == null) {
unwrapObject = assembler.getChilds()[StackLayer.id()].getComponentInstance(aClass);
}
if (unwrapObject == null) {
unwrapObject = assembler.getChilds()[ControllerLayer.id()].getComponentInstance(aClass);
}
if (unwrapObject == null) {
unwrapObject = assembler.getChilds()[TransportLayer.id()].getComponentInstance(aClass);
}
return (T) unwrapObject;
}
// Extended methods
public StackState getState() {
return state;
}
public Configuration getConfiguration() {
return config;
}
public IAssembler getAssemblerFacility() {
return assembler;
}
public void sendMessage(IMessage message) throws RouteException, AvpDataException, IllegalDiameterStateException, IOException {
peerManager.sendMessage(message);
}
public void addSessionListener(String sessionId, NetworkReqListener listener) {
peerManager.addSessionReqListener(sessionId, listener);
}
public void removeSessionListener(String sessionId) {
peerManager.removeSessionListener(sessionId);
}
public ScheduledExecutorService getScheduledFacility() {
return scheduledFacility;
}
public IConcurrentFactory getConcurrentFactory() {
return this.concurrentFactory;
}
public String configuration() {
return config != null ? config.toString() : "not set";
}
public String metaData() {
try {
return getMetaData().toString();
}
catch (Exception exc) {
return "not set";
}
}
public String peerDescription(String name) {
try {
for (Peer p : unwrap(PeerTable.class).getPeerTable()) {
if (p.getUri().getFQDN().equals(name)) {
return p.toString();
}
}
}
catch (InternalException e) {
log.debug("InternalException", e);
}
return "not set";
}
public String peerList() {
try {
return unwrap(PeerTable.class).getPeerTable().toString();
}
catch (InternalException e) {
return "not set";
}
}
public void stop(int disconnectCause) {
try {
stop(10, TimeUnit.SECONDS, disconnectCause);
}
catch (Exception e) {
log.debug("Exception", e);
}
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl;
import org.jdiameter.api.*;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.client.api.IEventListener;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.parser.IMessageParser;
import static org.jdiameter.client.impl.helpers.Parameters.MessageTimeOut;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Implementation for {@link BaseSession}.
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public abstract class BaseSessionImpl implements BaseSession {
protected final long creationTime = System.currentTimeMillis();
protected long lastAccessedTime = creationTime;
protected boolean isValid = true;
protected String sessionId;
protected transient IContainer container;
protected transient IMessageParser parser;
protected NetworkReqListener reqListener;
public long getCreationTime() {
return creationTime;
}
public long getLastAccessedTime() {
return lastAccessedTime;
}
public boolean isValid() {
return isValid;
}
public String getSessionId() {
return sessionId;
}
/* (non-Javadoc)
* @see org.jdiameter.api.BaseSession#isAppSession()
*/
public boolean isAppSession() {
return false;
}
/* (non-Javadoc)
* @see org.jdiameter.api.BaseSession#isReplicable()
*/
public boolean isReplicable() {
return false;
}
protected void genericSend(Message message, EventListener listener) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
if (isValid) {
long timeOut = container.getConfiguration().getLongValue(MessageTimeOut.ordinal(), (Long) MessageTimeOut.defValue());
genericSend(message, listener, timeOut, TimeUnit.MILLISECONDS);
}
else {
throw new IllegalDiameterStateException("Session already released");
}
}
protected void genericSend(Message aMessage, EventListener listener, long timeout, TimeUnit timeUnit) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
if (isValid) {
lastAccessedTime = System.currentTimeMillis();
IMessage message = (IMessage) aMessage;
IEventListener localListener = createListenerWrapper(listener);
if (message.isRequest()) {
message.setListener(localListener);
// Auto set system avps
if (message.getAvps().getAvpByIndex(0).getCode() != Avp.SESSION_ID && sessionId != null) {
// Just to make sure it doesn't get duplicated
message.getAvps().removeAvp(Avp.SESSION_ID);
message.getAvps().insertAvp(0, Avp.SESSION_ID, sessionId, true, false, false);
}
}
//Add Origin-Host/Realm AVPs if not present
MessageUtility.addOriginAvps(aMessage, container.getMetaData());
if (message.getState() != IMessage.STATE_NOT_SENT && message.getState() != IMessage.STATE_ANSWERED) {
throw new IllegalDiameterStateException("Illegal state");
}
message.createTimer(container.getScheduledFacility(), timeout, timeUnit);
try {
container.sendMessage(message);
}
catch(RouteException e) {
message.clearTimer();
throw e;
}
catch (Exception e) {
message.clearTimer();
throw new InternalException(e);
}
}
else {
throw new IllegalDiameterStateException("Session already released");
}
}
@SuppressWarnings("unchecked")
protected IEventListener createListenerWrapper(final EventListener listener) {
return listener == null ? null : new MyEventListener(this, listener);
}
public Future<Message> send(final Message message) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
MyFuture future = new MyFuture();
future.send(message);
return future;
}
public Future<Message> send(Message message, long timeOut, TimeUnit timeUnit) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
MyFuture future = new MyFuture();
future.send(message, timeOut, timeUnit);
return future;
}
private class MyFuture implements Future<Message> {
private boolean canceled;
private boolean done;
private boolean timeOut;
private Lock lock = new ReentrantLock();
private CountDownLatch block = new CountDownLatch(1);
private Message result;
public boolean cancel(boolean mayInterruptIfRunning) {
lock.lock();
try {
canceled = true;
done = false;
block.countDown();
}
finally {
lock.unlock();
}
return true;
}
public boolean isCancelled() {
return canceled;
}
public boolean isDone() {
return done;
}
public Message get() throws InterruptedException, ExecutionException {
try {
block.await();
}
catch (Exception e) {
throw new ExecutionException(e);
}
Message rc = canceled ? null : result;
result = null;
return rc;
}
public Message get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
try {
block.await(timeout, unit);
}
catch (Exception e) {
throw new ExecutionException(e);
}
if (timeOut) {
throw new TimeoutException();
}
Message rc = canceled ? null : result;
result = null;
return rc;
}
private IEventListener createListener() {
return new IEventListener() {
public void setValid(boolean value) {
}
public boolean isValid() {
return !canceled;
}
public void receivedSuccessMessage(Request r, Answer a) {
lock.lock();
try {
if (!canceled) {
result = a;
canceled = false;
done = true;
}
block.countDown();
}
finally {
lock.unlock();
}
}
public void timeoutExpired(Request message) {
lock.lock();
try {
if (!canceled) {
done = true;
timeOut = true;
}
block.countDown();
}
finally {
lock.unlock();
}
}
};
}
public void send(Message message) throws RouteException, OverloadException, IllegalDiameterStateException, InternalException {
genericSend(message, createListener());
}
public void send(Message message, long timeOut, TimeUnit timeUnit) throws RouteException, OverloadException, IllegalDiameterStateException, InternalException {
genericSend(message, createListener(), timeOut, timeUnit);
}
}
/**
* Appends an *-Application-Id AVP to the message, if none is present already.
*
* @param appId the application-id value
* @param m the message to append the *-Application-Id
*/
protected void appendAppId(ApplicationId appId, Message m) {
if (appId == null) {
return;
}
// check if any application-id avp is already present.
// we could use m.getApplicationIdAvps().size() > 0 but this should spare a few cpu cycles
for(Avp avp : m.getAvps()) {
int code = avp.getCode();
if(code == Avp.ACCT_APPLICATION_ID || code == Avp.AUTH_APPLICATION_ID || code == Avp.VENDOR_SPECIFIC_APPLICATION_ID) {
return;
}
}
if (appId.getVendorId() == 0) {
if (appId.getAcctAppId() != 0) {
m.getAvps().addAvp(Avp.ACCT_APPLICATION_ID, appId.getAcctAppId(), true, false, true);
}
if (appId.getAuthAppId() != 0) {
m.getAvps().addAvp(Avp.AUTH_APPLICATION_ID, appId.getAuthAppId(), true, false, true);
}
}
else {
AvpSet avp = m.getAvps().addGroupedAvp(Avp.VENDOR_SPECIFIC_APPLICATION_ID, true, false);
avp.addAvp(Avp.VENDOR_ID, appId.getVendorId(), true, false, true);
if (appId.getAuthAppId() != 0) {
avp.addAvp(Avp.AUTH_APPLICATION_ID, appId.getAuthAppId(), true, false, true);
}
if (appId.getAcctAppId() != 0) {
avp.addAvp(Avp.ACCT_APPLICATION_ID, appId.getAcctAppId(), true, false, true);
}
}
}
protected long getAppId(ApplicationId appId) {
if (appId == null) {
return 0;
}
// if (appId.getVendorId() == 0) {
if (appId.getAcctAppId() != 0) {
return appId.getAcctAppId();
}
if (appId.getAuthAppId() != 0) {
return appId.getAuthAppId();
}
// }
return appId.getVendorId();
}
}
class MyEventListener implements IEventListener {
BaseSessionImpl session;
EventListener listener;
boolean isValid = true;
public MyEventListener(BaseSessionImpl session, EventListener listener) {
this.session = session;
this.listener = listener;
}
public void setValid(boolean value) {
isValid = value;
if (!isValid) {
session = null;
listener = null;
}
}
public boolean isValid() {
return isValid;
}
@SuppressWarnings("unchecked")
public void receivedSuccessMessage(Request request, Answer answer) {
if (isValid) {
session.lastAccessedTime = System.currentTimeMillis();
listener.receivedSuccessMessage(request, answer);
}
}
@SuppressWarnings("unchecked")
public void timeoutExpired(Request message) {
if (isValid) {
session.lastAccessedTime = System.currentTimeMillis();
listener.timeoutExpired(message);
}
}
public int hashCode() {
return listener == null ? 0 : listener.hashCode();
}
public boolean equals(Object obj) {
return listener != null && listener.equals(obj);
}
public String toString() {
return listener == null ? "null" : listener.toString();
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2006-2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.router;
import static org.jdiameter.client.impl.helpers.Parameters.AcctApplId;
import static org.jdiameter.client.impl.helpers.Parameters.Agent;
import static org.jdiameter.client.impl.helpers.Parameters.ApplicationId;
import static org.jdiameter.client.impl.helpers.Parameters.AuthApplId;
import static org.jdiameter.client.impl.helpers.Parameters.OwnRealm;
import static org.jdiameter.client.impl.helpers.Parameters.RealmEntry;
import static org.jdiameter.client.impl.helpers.Parameters.RealmTable;
import static org.jdiameter.client.impl.helpers.Parameters.VendorId;
import static org.jdiameter.server.impl.helpers.Parameters.RealmEntryExpTime;
import static org.jdiameter.server.impl.helpers.Parameters.RealmEntryIsDynamic;
import static org.jdiameter.server.impl.helpers.Parameters.RealmHosts;
import static org.jdiameter.server.impl.helpers.Parameters.RealmLocalAction;
import static org.jdiameter.server.impl.helpers.Parameters.RealmName;
import static org.jdiameter.server.impl.helpers.Parameters.RequestTable;
import static org.jdiameter.server.impl.helpers.Parameters.RequestTableClearSize;
import static org.jdiameter.server.impl.helpers.Parameters.RequestTableSize;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.UnknownServiceException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
//PCB added for thread safe
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.Configuration;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.LocalAction;
import org.jdiameter.api.Message;
import org.jdiameter.api.MetaData;
import org.jdiameter.api.PeerState;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.URI;
import org.jdiameter.client.api.IAnswer;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.IRequest;
import org.jdiameter.client.api.controller.IPeer;
import org.jdiameter.client.api.controller.IPeerTable;
import org.jdiameter.client.api.controller.IRealm;
import org.jdiameter.client.api.controller.IRealmTable;
import org.jdiameter.client.api.router.IRouter;
import org.jdiameter.client.impl.helpers.AppConfiguration;
import org.jdiameter.client.impl.helpers.Parameters;
import org.jdiameter.common.api.concurrent.IConcurrentFactory;
import org.jdiameter.server.api.agent.IAgentConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Diameter Routing Core
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class RouterImpl implements IRouter {
public static final int DONT_CACHE = 0;
public static final int ALL_SESSION = 1;
public static final int ALL_REALM = 2;
public static final int REALM_AND_APPLICATION = 3;
public static final int ALL_APPLICATION = 4;
public static final int ALL_HOST = 5;
public static final int ALL_USER = 6;
//
private static final Logger logger = LoggerFactory.getLogger(RouterImpl.class);
protected MetaData metaData;
//
//private ConcurrentHashMap<String, String[]> network = new ConcurrentHashMap<String, String[]>();
protected IRealmTable realmTable;
// Redirection feature
public final int REDIRECT_TABLE_SIZE = 1024;
//TODO: index it differently.
protected List<RedirectEntry> redirectTable = new ArrayList<RedirectEntry>(REDIRECT_TABLE_SIZE);
protected IConcurrentFactory concurrentFactory;
protected IContainer container;
// Answer routing feature
public static int REQUEST_TABLE_SIZE = 10 * 1024;
public static int REQUEST_TABLE_CLEAR_SIZE = 2 * 1024;
protected Lock requestEntryTableLock = new ReentrantLock();
protected ReadWriteLock redirectTableLock = new ReentrantReadWriteLock();
//PCB added
protected Map<String, AnswerEntry> requestEntryMap;
//protected List<Long> requestSortedEntryTable = new ArrayList<Long>();
protected boolean isStopped = true;
public RouterImpl(IContainer container,IConcurrentFactory concurrentFactory, IRealmTable realmTable,Configuration config, MetaData aMetaData) {
this.concurrentFactory = concurrentFactory;
this.metaData = aMetaData;
this.realmTable = realmTable;
this.container = container;
logger.debug("Constructor for RouterImpl: Calling loadConfiguration");
loadConfiguration(config);
}
protected void loadConfiguration(Configuration config) {
logger.debug("Loading Router Configuration. Populating Realms, Application IDs, etc");
//add local realm : this might not be good
String localRealm = config.getStringValue(OwnRealm.ordinal(),null);
String localHost = config.getStringValue(Parameters.OwnDiameterURI.ordinal(),null);
try {
this.realmTable.addLocalRealm(localRealm, new URI(localHost).getFQDN());
}
catch (UnknownServiceException use) {
throw new RuntimeException("Unable to create URI from Own URI config value:" + localHost, use);
}
catch (URISyntaxException use) {
throw new RuntimeException("Unable to create URI from Own URI config value:" + localHost, use);
}
if (config.getChildren(RequestTable.ordinal()) != null) {
AppConfiguration requestTableConfig = (AppConfiguration) config.getChildren(org.jdiameter.server.impl.helpers.Parameters.RequestTable.ordinal())[0];
int tSize = (int)requestTableConfig.getIntValue(RequestTableSize.ordinal(),(Integer) RequestTableSize.defValue());
int tClearSize = (int)requestTableConfig.getIntValue(RequestTableClearSize.ordinal(),(Integer) RequestTableClearSize.defValue());
if(tClearSize >= tSize) {
logger.warn("Configuration entry RequestTable, attribute 'clear_size' [{}] should not be greater than 'size' [{}]. Adjusting.", tSize, tClearSize);
while (tClearSize >= tSize) {
tSize *= 10;
}
}
REQUEST_TABLE_SIZE = (int) tSize;
REQUEST_TABLE_CLEAR_SIZE = (int) tClearSize;
}
//PCB added thread safety
this.requestEntryMap = new ConcurrentHashMap<String, AnswerEntry>(REQUEST_TABLE_SIZE);
logger.debug("Configured Request Table with size[{}] and clear size[{}].", REQUEST_TABLE_SIZE, REQUEST_TABLE_CLEAR_SIZE);
//add realms based on realm table.
if (config.getChildren(RealmTable.ordinal()) != null) {
logger.debug("Going to loop through configured realms and add them into a network map");
for (Configuration items : config.getChildren(RealmTable.ordinal())) {
if (items != null) {
Configuration[] m = items.getChildren(RealmEntry.ordinal());
for (Configuration c : m) {
try {
String name = c.getStringValue(RealmName.ordinal(), "");
logger.debug("Getting config for realm [{}]", name);
ApplicationId appId = null;
{
Configuration[] apps = c.getChildren(ApplicationId.ordinal());
if (apps != null) {
for (Configuration a : apps) {
if (a != null) {
long vnd = a.getLongValue(VendorId.ordinal(), 0);
long auth = a.getLongValue(AuthApplId.ordinal(), 0);
long acc = a.getLongValue(AcctApplId.ordinal(), 0);
if (auth != 0) {
appId = org.jdiameter.api.ApplicationId.createByAuthAppId(vnd, auth);
}
else {
appId = org.jdiameter.api.ApplicationId.createByAccAppId(vnd, acc);
}
if (logger.isDebugEnabled()) {
logger.debug("Realm [{}] has application Acct [{}] Auth [{}] Vendor [{}]", new Object[]{name, appId.getAcctAppId(), appId.getAuthAppId(), appId.getVendorId()});
}
break;
}
}
}
}
String[] hosts = c.getStringValue(RealmHosts.ordinal(), (String) RealmHosts.defValue()).split(",");
logger.debug("Adding realm [{}] with hosts [{}] to network map", name, hosts);
LocalAction locAction = LocalAction.valueOf(c.getStringValue(RealmLocalAction.ordinal(), "0"));
boolean isDynamic = c.getBooleanValue(RealmEntryIsDynamic.ordinal(), false);
long expirationTime = c.getLongValue(RealmEntryExpTime.ordinal(), 0);
//check if there is Agent, ATM we support only props there.
IAgentConfiguration agentConfImpl = null;
Configuration[] confs = c.getChildren(Agent.ordinal());
if(confs != null && confs.length > 0) {
Configuration agentConfiguration = confs[0]; //only one!
agentConfImpl = this.container.getAssemblerFacility().getComponentInstance(IAgentConfiguration.class);
if(agentConfImpl != null) {
agentConfImpl = agentConfImpl.parse(agentConfiguration);
}
}
this.realmTable.addRealm(name, appId, locAction, agentConfImpl, isDynamic, expirationTime, hosts);
}
catch (Exception e) {
logger.warn("Unable to append realm entry", e);
}
}
}
}
}
}
public void registerRequestRouteInfo(IRequest request) {
logger.debug("Entering registerRequestRouteInfo");
try {
// PCB removed lock
// requestEntryTableLock.writeLock().lock();
long hopByHopId = request.getHopByHopIdentifier();
Avp hostAvp = request.getAvps().getAvp(Avp.ORIGIN_HOST);
Avp realmAvp = request.getAvps().getAvp(Avp.ORIGIN_REALM);
AnswerEntry entry = new AnswerEntry(hopByHopId, hostAvp != null ? hostAvp.getDiameterIdentity() : null,
realmAvp != null ? realmAvp.getDiameterIdentity() : null);
int s = requestEntryMap.size();
// PCB added logging
logger.debug("RequestRoute map size is [{}]", s);
//PCB added
if (s > REQUEST_TABLE_CLEAR_SIZE) {
try {
requestEntryTableLock.lock();
s = requestEntryMap.size();
logger.debug("After 'lock', RequestRoute map size is [{}]", s);
// The double-check with a gap is in case while about to clear the map, it drops below REQUEST_TABLE_SIZE due to a
// response being sent, and then the lock might not be in effect for another thread
// Hence lock at REQUEST_TABLE_CLEAR_SIZE and clear at REQUEST_TABLE_SIZE so that all threads would be locked not
// just the first to reach REQUEST_TABLE_SIZE
if (s > REQUEST_TABLE_SIZE) {
// Going to clear it out and suffer the consequences of some messages possibly not being routed back the clients..
logger.warn("RequestRoute map size is [{}]. There's probably a leak. Cleaning up after a short wait...", s);
// Lets do our best to avoid lost messages by locking table from writes (as this is the only code writing to it),
// sleeping for a while for responses to be sent and then clearing it
Thread.sleep(5000);
logger.warn("RequestRoute map size is now [{}] after sleeping. Clearing it!", requestEntryMap.size());
requestEntryMap.clear();
}
}
catch (Exception e) {
logger.warn("Failure trying to clear RequestRoute map", e);
}
finally {
requestEntryTableLock.unlock();
}
}
String messageKey = makeRoutingKey(request);
logger.debug("Adding request key [{}] to RequestRoute map for routing answers back to the requesting peer", messageKey);
requestEntryMap.put(messageKey, entry);
// requestSortedEntryTable.add(hopByHopId);
}
catch (Exception e) {
logger.warn("Unable to store route info", e);
}
finally {
// requestEntryTableLock.writeLock().unlock();
}
}
// PCB - Made better routing algorithm that should not grow all the time
private String makeRoutingKey(Message message) {
String sessionId = message.getSessionId();
return new StringBuilder(sessionId != null ? sessionId : "null").append(message.getEndToEndIdentifier())
.append(message.getHopByHopIdentifier()).toString();
}
public String[] getRequestRouteInfo(IMessage message) {
String messageKey = makeRoutingKey(message);
AnswerEntry ans = requestEntryMap.get(messageKey);
if (ans != null) {
if (logger.isDebugEnabled()) {
logger.debug("getRequestRouteInfo found host [{}] and realm [{}] for Message key Id [{}]", new Object[]{ans.getHost(), ans.getRealm(), messageKey});
}
return new String[] {ans.getHost(), ans.getRealm()};
}
else {
if(logger.isWarnEnabled()) {
logger.warn("Could not find route info for message key [{}]. Table size is [{}]", messageKey, requestEntryMap.size());
}
return null;
}
}
//PCB added
public void garbageCollectRequestRouteInfo(IMessage message) {
String messageKey = makeRoutingKey(message);
requestEntryMap.remove(messageKey);
}
public IPeer getPeer(IMessage message, IPeerTable manager) throws RouteException, AvpDataException {
logger.debug("Getting a peer for message [{}]", message);
//FIXME: add ability to send without matching realm+peer pair?, that is , route based on peer table entries?
//that is, if msg.destHost != null > getPeer(msg.destHost).sendMessage(msg);
String destRealm = null;
String destHost = null;
IRealm matchedRealm = null;
String[] info = null;
// Get destination information
if(message.isRequest()) {
Avp avpRealm = message.getAvps().getAvp(Avp.DESTINATION_REALM);
if (avpRealm == null) {
throw new RouteException("Destination realm avp is empty");
}
destRealm = avpRealm.getDiameterIdentity();
Avp avpHost = message.getAvps().getAvp(Avp.DESTINATION_HOST);
if (avpHost != null) {
destHost = avpHost.getDiameterIdentity();
}
if(logger.isDebugEnabled()) {
logger.debug("Looking up peer for request: [{}], DestHost=[{}], DestRealm=[{}]", new Object[] {message,destHost, destRealm});
}
matchedRealm = (IRealm) this.realmTable.matchRealm(message);
}
else {
//answer, search
info = getRequestRouteInfo(message);
if (info != null) {
destHost = info[0];
destRealm = info[1];
logger.debug("Message is an answer. Host is [{}] and Realm is [{}] as per hopbyhop info from request", destHost, destRealm);
if (destRealm == null) {
logger.warn("Destination-Realm was null for hopbyhop id " + message.getHopByHopIdentifier());
}
}
else {
logger.debug("No Host and realm found based on hopbyhop id of the answer associated request");
}
//FIXME: if no info, should not send it ?
//FIXME: add strict deff in route back table so stack does not have to lookup?
if(logger.isDebugEnabled()) {
logger.debug("Looking up peer for answer: [{}], DestHost=[{}], DestRealm=[{}]", new Object[] {message,destHost, destRealm});
}
matchedRealm = (IRealm) this.realmTable.matchRealm((IAnswer)message,destRealm);
}
// IPeer peer = getPeerPredProcessing(message, destRealm, destHost);
//
// if (peer != null) {
// logger.debug("Found during preprocessing...[{}]", peer);
// return peer;
// }
// Check realm name
//TODO: check only if it exists?
if (matchedRealm == null) {
throw new RouteException("Unknown realm name [" + destRealm + "]");
}
// THIS IS GET PEER, NOT ROUTE!!!!!!!
// Redirect processing
//redirectProcessing(message, destRealm, destHost);
// Check previous context information, this takes care of most answers.
if (message.getPeer() != null && destHost != null && destHost.equals(message.getPeer().getUri().getFQDN()) && message.getPeer().hasValidConnection()) {
if(logger.isDebugEnabled()) {
logger.debug("Select previous message usage peer [{}]", message.getPeer());
}
return message.getPeer();
}
// Balancing procedure
IPeer c = (IPeer) (destHost != null ? manager.getPeer(destHost) : null);
if (c != null && c.hasValidConnection()) {
logger.debug("Found a peer using destination host avp [{}] peer is [{}] with a valid connection.", destHost, c);
//here matchedRealm MAY
return c;
}
else {
logger.debug("Finding peer by destination host avp [host={}] did not find anything. Now going to try finding one by destination realm [{}]", destHost, destRealm);
String peers[] = matchedRealm.getPeerNames();
if (peers == null || peers.length == 0) {
throw new RouteException("Unable to find context by route information [" + destRealm + " ," + destHost + "]");
}
// Collect peers
ArrayList<IPeer> availablePeers = new ArrayList<IPeer>(5);
logger.debug("Looping through peers in realm [{}]", destRealm);
for (String peerName : peers) {
IPeer localPeer = (IPeer) manager.getPeer(peerName);
if(logger.isDebugEnabled()) {
logger.debug("Checking peer [{}] for name [{}]", new Object[]{localPeer,peerName});
}
// ammendonca: added peer state check.. should not be needed but
// hasValidConnection is returning true for disconnected peers in *FTFlowTests
if (localPeer != null && localPeer.getState(PeerState.class) == PeerState.OKAY) {
if(localPeer.hasValidConnection()) {
if(logger.isDebugEnabled()) {
logger.debug("Found available peer to add to available peer list with uri [{}] with a valid connection", localPeer.getUri().toString());
}
availablePeers.add(localPeer);
}
else {
if(logger.isDebugEnabled()) {
logger.debug("Found a peer with uri [{}] with no valid connection", localPeer.getUri());
}
}
}
}
if(logger.isDebugEnabled()) {
logger.debug("Performing Realm routing. Realm [{}] has the following peers available [{}] from list [{}]", new Object[] {destRealm, availablePeers, Arrays.asList(peers)});
}
// Balancing
IPeer peer = selectPeer(availablePeers);
if (peer == null) {
throw new RouteException("Unable to find valid connection to peer[" + destHost + "] in realm[" + destRealm + "]");
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Load balancing selected peer with uri [{}]", peer.getUri());
}
}
return peer;
}
}
public IRealmTable getRealmTable() {
return this.realmTable;
}
public void processRedirectAnswer(IRequest request, IAnswer answer, IPeerTable table) throws InternalException, RouteException {
try {
Avp destinationRealmAvp = request.getAvps().getAvp(Avp.DESTINATION_REALM);
if(destinationRealmAvp == null) {
throw new RouteException("Request to be routed has no Destination-Realm AVP!"); // sanity check... if user messes with us
}
String destinationRealm = destinationRealmAvp.getDiameterIdentity();
String[] redirectHosts = null;
if (answer.getAvps().getAvps(Avp.REDIRECT_HOST) != null) {
AvpSet avps = answer.getAvps().getAvps(Avp.REDIRECT_HOST);
redirectHosts = new String[avps.size()];
int i = 0;
// loop detected
for (Avp avp : avps) {
String r = avp.getDiameterIdentity();
if (r.equals(metaData.getLocalPeer().getUri().getFQDN())) {
throw new RouteException("Loop detected");
}
redirectHosts[i++] = r;
}
}
//
int redirectUsage = DONT_CACHE;
Avp redirectHostUsageAvp = answer.getAvps().getAvp(Avp.REDIRECT_HOST_USAGE);
if (redirectHostUsageAvp != null) {
redirectUsage = redirectHostUsageAvp.getInteger32();
}
if (redirectUsage != DONT_CACHE) {
long redirectCacheTime = 0;
Avp redirectCacheMaxTimeAvp = answer.getAvps().getAvp(Avp.REDIRECT_MAX_CACHE_TIME);
if (redirectCacheMaxTimeAvp != null) {
redirectCacheTime = redirectCacheMaxTimeAvp.getUnsigned32();
}
String primaryKey = null;
ApplicationId secondaryKey = null;
switch (redirectUsage) {
case ALL_SESSION:
primaryKey = request.getSessionId();
break;
case ALL_REALM:
primaryKey = destinationRealm;
break;
case REALM_AND_APPLICATION:
primaryKey = destinationRealm;
secondaryKey = ((IMessage)request).getSingleApplicationId();
break;
case ALL_APPLICATION:
secondaryKey = ((IMessage)request).getSingleApplicationId();
break;
case ALL_HOST:
Avp destinationHostAvp = ((IRequest)request).getAvps().getAvp(Avp.DESTINATION_HOST);
if(destinationHostAvp == null) {
throw new RouteException("Request to be routed has no Destination-Host AVP!"); // sanity check... if user messes with us
}
primaryKey = destinationHostAvp.getDiameterIdentity();
break;
case ALL_USER:
Avp userNameAvp = answer.getAvps().getAvp(Avp.USER_NAME);
if (userNameAvp == null) {
throw new RouteException("Request to be routed has no User-Name AVP!"); // sanity check... if user messes with us
}
primaryKey = userNameAvp.getUTF8String();
break;
}
//
if(redirectTable.size()> REDIRECT_TABLE_SIZE) {
try {
//yes, possible that this will trigger this procedure twice, but thats worst than locking always.
redirectTableLock.writeLock().lock();
trimRedirectTable();
}
finally {
redirectTableLock.writeLock().unlock();
}
}
if (REDIRECT_TABLE_SIZE > redirectTable.size()) {
RedirectEntry e = new RedirectEntry(primaryKey, secondaryKey, redirectCacheTime, redirectUsage, redirectHosts, destinationRealm);
redirectTable.add(e);
//redirectProcessing(answer,destRealm.getOctetString(),destHost !=null ? destHost.getOctetString():null);
//we dont have to elect?
updateRoute(request,e.getRedirectHost());
}
else {
if (redirectHosts != null && redirectHosts.length > 0) {
String destHost = redirectHosts[0];
//setRouteInfo(answer, getRealmForPeer(destHost), destHost);
updateRoute(request,destHost);
}
}
}
else {
if (redirectHosts != null && redirectHosts.length > 0) {
String destHost = redirectHosts[0];
//setRouteInfo(answer, getRealmForPeer(destHost), destHost);
updateRoute(request,destHost);
}
}
//now send
table.sendMessage((IMessage)request);
}
catch (AvpDataException exc) {
throw new InternalException(exc);
}
catch (IllegalDiameterStateException e) {
throw new InternalException(e);
}
catch (IOException e) {
throw new InternalException(e);
}
}
/**
*
*/
private void trimRedirectTable() {
for(int index = 0; index < redirectTable.size(); index++) {
try{
if(redirectTable.get(index).getExpiredTime() <= System.currentTimeMillis()) {
redirectTable.remove(index);
index--; //a trick :)
}
}
catch(Exception e) {
logger.debug("Error in redirect task cleanup.", e);
break;
}
}
}
/**
* @param request
* @param destHost
*/
private void updateRoute(IRequest request, String destHost) {
// Realm does not change I think... :)
request.getAvps().removeAvp(Avp.DESTINATION_HOST);
request.getAvps().addAvp(Avp.DESTINATION_HOST, destHost, true, false, true);
}
public boolean updateRoute(IRequest message) throws RouteException, AvpDataException {
AvpSet set = message.getAvps();
Avp destRealmAvp = set.getAvp(Avp.DESTINATION_REALM);
Avp destHostAvp = set.getAvp(Avp.DESTINATION_HOST);
if(destRealmAvp == null) {
throw new RouteException("Request does not have Destination-Realm AVP!");
}
String destRealm = destRealmAvp.getDiameterIdentity();
String destHost = destHostAvp != null ? destHostAvp.getDiameterIdentity() : null;
boolean matchedEntry = false;
String userName = null;
// get Session id
String sessionId = message.getSessionId();
//
Avp avpUserName = message.getAvps().getAvp(Avp.USER_NAME);
// Get application id
ApplicationId appId = ((IMessage)message).getSingleApplicationId();
// User name
if (avpUserName != null) {
userName = avpUserName.getUTF8String();
}
// Processing table
try{
redirectTableLock.readLock().lock();
for (int index = 0;index<redirectTable.size();index++) {
RedirectEntry e = redirectTable.get(index);
switch (e.getUsageType()) {
case ALL_SESSION: // Usage type: ALL SESSION
matchedEntry = sessionId != null && e.primaryKey != null & sessionId.equals(e.primaryKey);
break;
case ALL_REALM: // Usage type: ALL REALM
matchedEntry = destRealm != null && e.primaryKey != null & destRealm.equals(e.primaryKey);
break;
case REALM_AND_APPLICATION: // Usage type: REALM AND APPLICATION
matchedEntry = destRealm != null & appId != null & e.primaryKey != null & e.secondaryKey != null & destRealm.equals(e.primaryKey)
& appId.equals(e.secondaryKey);
break;
case ALL_APPLICATION: // Usage type: ALL APPLICATION
matchedEntry = appId != null & e.secondaryKey != null & appId.equals(e.secondaryKey);
break;
case ALL_HOST: // Usage type: ALL HOST
matchedEntry = destHost != null & e.primaryKey != null & destHost.equals(e.primaryKey);
break;
case ALL_USER: // Usage type: ALL USER
matchedEntry = userName != null & e.primaryKey != null & userName.equals(e.primaryKey);
break;
}
// Update message redirect information
if (matchedEntry) {
String newDestHost = e.getRedirectHost();
//String newDestRealm = getRealmForPeer(destHost);
//setRouteInfo(message, destRealm, newDestHost);
updateRoute(message, newDestHost);
logger.debug("Redirect message from host={}; to new-host={}, realm={} ", new Object[] { destHost, newDestHost,destRealm});
return true;
}
}
}
finally {
redirectTableLock.readLock().unlock();
}
return false;
}
protected IPeer getPeerPredProcessing(IMessage message, String destRealm, String destHost) {
return null;
}
public void start() {
if (isStopped) {
//redirectScheduler = concurrentFactory.getScheduledExecutorService(RedirectMessageTimer.name());
//redirectEntryHandler = redirectScheduler.scheduleAtFixedRate(redirectTask, 1, 1, TimeUnit.SECONDS);
isStopped = false;
}
}
public void stop() {
isStopped = true;
// if (redirectEntryHandler != null) {
// redirectEntryHandler.cancel(true);
//}
if (redirectTable != null) {
redirectTable.clear();
}
if (requestEntryMap != null) {
requestEntryMap.clear();
}
//PCB removed
//if (requestSortedEntryTable != null) {
// requestSortedEntryTable.clear();
//}
//if (redirectScheduler != null) {
// concurrentFactory.shutdownNow(redirectScheduler);
//}
}
public void destroy() {
try {
if (!isStopped) {
stop();
}
}
catch (Exception exc) {
logger.error("Unable to stop router", exc);
}
//redirectEntryHandler = null;
//redirectScheduler = null;
redirectTable = null;
requestEntryMap = null;
requestEntryMap = null;
}
protected IPeer selectPeer(List<IPeer> availablePeers) {
IPeer p = null;
for (IPeer c : availablePeers) {
if (p == null || c.getRating() >= p.getRating()) {
p = c;
}
}
return p;
}
// protected void redirectProcessing(IMessage message, final String destRealm, final String destHost) throws AvpDataException {
// String userName = null;
// // get Session id
// String sessionId = message.getSessionId();
// //
// Avp avpUserName = message.getAvps().getAvp(Avp.USER_NAME);
// // Get application id
// ApplicationId appId = message.getSingleApplicationId();
// // User name
// if (avpUserName != null)
// userName = avpUserName.getUTF8String();
// // Processing table
// for (RedirectEntry e : redirectTable.values()) {
// boolean matchedEntry = false;
// switch (e.getUsageType()) {
// case ALL_SESSION: // Usage type: ALL SESSION
// matchedEntry = sessionId != null && e.primaryKey != null &
// sessionId.equals(e.primaryKey);
// break;
// case ALL_REALM: // Usage type: ALL REALM
// matchedEntry = destRealm != null && e.primaryKey != null &
// destRealm.equals(e.primaryKey);
// break;
// case REALM_AND_APPLICATION: // Usage type: REALM AND APPLICATION
// matchedEntry = destRealm != null & appId != null & e.primaryKey != null & e.secondaryKey != null &
// destRealm.equals(e.primaryKey) & appId.equals(e.secondaryKey);
// break;
// case ALL_APPLICATION: // Usage type: ALL APPLICATION
// matchedEntry = appId != null & e.secondaryKey != null &
// appId.equals(e.secondaryKey);
// break;
// case ALL_HOST: // Usage type: ALL HOST
// matchedEntry = destHost != null & e.primaryKey != null &
// destHost.equals(e.primaryKey);
// break;
// case ALL_USER: // Usage type: ALL USER
// matchedEntry = userName != null & e.primaryKey != null &
// userName.equals(e.primaryKey);
// break;
// }
// // Update message redirect information
// if (matchedEntry) {
// String newDestHost = e.getRedirectHost();
// // FIXME: Alexandre: Should use newDestHost?
// String newDestRealm = getRealmForPeer(destHost);
// setRouteInfo(message, destRealm, newDestHost);
// logger.debug("Redirect message from host={}; realm={} to new-host={}; new-realm={}",
// new Object[] {destHost, destRealm, newDestHost, newDestRealm});
// return;
// }
// }
// }
//
// private void setRouteInfo(IMessage message, String destRealm, String destHost) {
// message.getAvps().removeAvp(Avp.DESTINATION_REALM);
// message.getAvps().removeAvp(Avp.DESTINATION_HOST);
// if (destRealm != null)
// message.getAvps().addAvp(Avp.DESTINATION_REALM, destRealm, true, false, true);
// if (destHost != null)
// message.getAvps().addAvp(Avp.DESTINATION_HOST, destHost, true, false, true);
// }
//does not make sense, there can be multple realms :/
// public String getRealmForPeer(String destHost) {
// for (String key : getRealmsName()) {
// for (String h : getRealmPeers(key)) {
// if (h.trim().equals(destHost.trim()))
// return key;
// }
// }
// return null;
// }
protected class RedirectEntry {
final long createTime = System.currentTimeMillis();
String primaryKey;
ApplicationId secondaryKey;
long liveTime;
int usageType;
String[] hosts;
String destinationRealm;
public RedirectEntry(String key1, ApplicationId key2, long time, int usage, String[] aHosts, String destinationRealm) throws InternalError {
// Check arguments
if (key1 == null && key2 == null) {
throw new InternalError("Incorrect redirection key.");
}
if (aHosts == null || aHosts.length == 0) {
throw new InternalError("Incorrect redirection hosts.");
}
// Set values
this.primaryKey = key1;
this.secondaryKey = key2;
this.liveTime = time * 1000;
this.usageType = usage;
this.hosts = aHosts;
this.destinationRealm = destinationRealm;
}
public int getUsageType() {
return usageType;
}
public String[] getRedirectHosts() {
return hosts;
}
public String getRedirectHost() {
return hosts[hosts.length - 1];
}
public long getExpiredTime() {
return createTime + liveTime;
}
public int hashCode() {
int result = (primaryKey != null ? primaryKey.hashCode() : 0);
result = 31 * result + (secondaryKey != null ? secondaryKey.hashCode() : 0);
result = 31 * result + (int) (liveTime ^ (liveTime >>> 32));
result = 31 * result + usageType;
result = 31 * result + (hosts != null ? hosts.hashCode() : 0);
return result;
}
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (other instanceof RedirectEntry) {
RedirectEntry that = (RedirectEntry) other;
return liveTime == that.liveTime && usageType == that.usageType &&
Arrays.equals(hosts, that.hosts) && !(primaryKey != null ? !primaryKey.equals(that.primaryKey) : that.primaryKey != null) &&
!(secondaryKey != null ? !secondaryKey.equals(that.secondaryKey) : that.secondaryKey != null);
}
else {
return false;
}
}
}
protected class AnswerEntry {
final long createTime = System.nanoTime();
Long hopByHopId;
String host, realm;
public AnswerEntry(Long hopByHopId) {
this.hopByHopId = hopByHopId;
}
public AnswerEntry(Long hopByHopId, String host, String realm) throws InternalError {
this.hopByHopId = hopByHopId;
this.host = host;
this.realm = realm;
}
public long getCreateTime() {
return createTime;
}
public Long getHopByHopId() {
return hopByHopId;
}
public String getHost() {
return host;
}
public String getRealm() {
return realm;
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AnswerEntry that = (AnswerEntry) o;
return hopByHopId == that.hopByHopId;
}
public String toString() {
return "AnswerEntry{" + "createTime=" + createTime + ", hopByHopId=" + hopByHopId + '}';
}
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl;
import org.jdiameter.api.app.StateChangeListener;
/**
* Implementation of state change methods.
* Developer can provide implementation of particular methods required.
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public abstract class AbstractStateChangeListener<T> implements StateChangeListener<T> {
/*
* (non-Javadoc)
* @see org.jdiameter.api.app.StateChangeListener#stateChanged(java.lang.Enum, java.lang.Enum)
*/
@SuppressWarnings("unchecked")
public void stateChanged(Enum oldState, Enum newState) {
// Stub method
}
/*
* (non-Javadoc)
* @see org.jdiameter.api.app.StateChangeListener#stateChanged(java.lang.Object, java.lang.Enum, java.lang.Enum)
*/
@SuppressWarnings("unchecked")
public void stateChanged(T source, Enum oldState, Enum newState) {
// Stub method
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl;
import static org.jdiameter.client.impl.helpers.Parameters.AcctApplId;
import static org.jdiameter.client.impl.helpers.Parameters.ApplicationId;
import static org.jdiameter.client.impl.helpers.Parameters.AuthApplId;
import static org.jdiameter.client.impl.helpers.Parameters.OwnDiameterURI;
import static org.jdiameter.client.impl.helpers.Parameters.OwnFirmwareRevision;
import static org.jdiameter.client.impl.helpers.Parameters.OwnIPAddress;
import static org.jdiameter.client.impl.helpers.Parameters.OwnProductName;
import static org.jdiameter.client.impl.helpers.Parameters.OwnRealm;
import static org.jdiameter.client.impl.helpers.Parameters.OwnVendorID;
import static org.jdiameter.client.impl.helpers.Parameters.VendorId;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryType;
import java.lang.management.MemoryUsage;
import java.net.InetAddress;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.net.UnknownServiceException;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Configuration;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Peer;
import org.jdiameter.api.PeerState;
import org.jdiameter.api.PeerStateListener;
import org.jdiameter.api.StackType;
import org.jdiameter.api.URI;
import org.jdiameter.api.app.StateChangeListener;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.IMetaData;
import org.jdiameter.client.api.controller.IPeer;
import org.jdiameter.client.api.fsm.EventTypes;
import org.jdiameter.client.api.io.IConnectionListener;
import org.jdiameter.client.api.io.TransportException;
import org.jdiameter.client.impl.helpers.IPConverter;
import org.jdiameter.common.api.data.ISessionDatasource;
import org.jdiameter.common.api.statistic.IStatistic;
import org.jdiameter.common.api.statistic.IStatisticManager;
import org.jdiameter.common.api.statistic.IStatisticRecord;
import org.jdiameter.common.impl.controller.AbstractPeer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Use stack extension point
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class MetaDataImpl implements IMetaData {
private static final Logger logger = LoggerFactory.getLogger(MetaDataImpl.class);
protected List<MemoryPoolMXBean> beans = ManagementFactory.getMemoryPoolMXBeans();
protected IContainer stack;
protected long state;
protected IPeer peer;
protected Set<ApplicationId> appIds = new LinkedHashSet<ApplicationId>();
protected final ISessionDatasource sessionDataSource;
public MetaDataImpl(IContainer s) {
this.stack = s;
this.sessionDataSource = s.getAssemblerFacility().getComponentInstance(ISessionDatasource.class);
}
public MetaDataImpl(IContainer s, IStatisticManager statisticFactory) {
this(s);
this.peer = newLocalPeer(statisticFactory);
IStatisticRecord heapMemory = statisticFactory.newCounterRecord(IStatisticRecord.Counters.HeapMemory,
new IStatisticRecord.LongValueHolder() {
public long getValueAsLong() {
for (MemoryPoolMXBean bean : beans) {
MemoryType memoryType = bean.getType();
MemoryUsage memoryUsage = bean.getUsage();
if (memoryType == MemoryType.HEAP) {
return memoryUsage.getUsed();
}
}
return 0;
}
public String getValueAsString() {
return String.valueOf(getValueAsLong());
}
}
);
IStatisticRecord noHeapMemory = statisticFactory.newCounterRecord(IStatisticRecord.Counters.NoHeapMemory,
new IStatisticRecord.LongValueHolder() {
public long getValueAsLong() {
for (MemoryPoolMXBean bean : beans) {
MemoryType memoryType = bean.getType();
MemoryUsage memoryUsage = bean.getUsage();
if (memoryType != MemoryType.HEAP) {
return memoryUsage.getUsed();
}
}
return 0;
}
public String getValueAsString() {
return String.valueOf(getValueAsLong());
}
}
);
peer.getStatistic().appendCounter(heapMemory, noHeapMemory);
}
protected IPeer newLocalPeer(IStatisticManager statisticFactory) {
return new ClientLocalPeer(statisticFactory);
}
public Peer getLocalPeer() {
return peer;
}
public int getMajorVersion() {
return 2;
}
public int getMinorVersion() {
return 1;
}
public StackType getStackType() {
return StackType.TYPE_CLIENT;
}
public Configuration getConfiguration() {
return stack.getConfiguration();
}
public void updateLocalHostStateId() {
state = System.currentTimeMillis();
}
public long getLocalHostStateId() {
return state;
}
public boolean isWrapperFor(Class<?> aClass) throws InternalException {
return aClass == IMetaData.class;
}
@SuppressWarnings("unchecked")
public <T> T unwrap(Class<T> aClass) throws InternalException {
if (aClass == IMetaData.class) {
return (T) this;
}
return null;
}
protected class ClientLocalPeer extends AbstractPeer implements IPeer {
protected AtomicLong hopByHopId = new AtomicLong(0);
protected InetAddress[] addresses = new InetAddress[0];
public void resetAddresses() {
addresses = new InetAddress[0];
}
public void connect() throws IllegalDiameterStateException {
throw new IllegalDiameterStateException("Illegal operation");
}
public void disconnect(int disconnectCause) throws IllegalDiameterStateException {
throw new IllegalDiameterStateException("Illegal operation");
}
public ClientLocalPeer(IStatisticManager statisticFactory) {
//FIXME: remove NULL?
super(null, statisticFactory);
createPeerStatistics();
}
@SuppressWarnings("unchecked")
public <E> E getState(Class<E> anEnum) {
switch (stack.getState()) {
case IDLE:
return (E) PeerState.DOWN;
case CONFIGURED:
return (E) PeerState.INITIAL;
case STARTED:
return (E) PeerState.OKAY;
case STOPPED:
return (E) PeerState.SUSPECT;
}
return (E) PeerState.DOWN;
}
public URI getUri() {
try {
return new URI(stack.getConfiguration().getStringValue(OwnDiameterURI.ordinal(), (String) OwnDiameterURI.defValue()));
}
catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
catch (UnknownServiceException e) {
throw new IllegalArgumentException(e);
}
}
public String getRealmName() {
return stack.getConfiguration().getStringValue(OwnRealm.ordinal(), (String) OwnRealm.defValue());
}
public long getVendorId() {
return stack.getConfiguration().getLongValue(OwnVendorID.ordinal(), (Long) OwnVendorID.defValue());
}
public String getProductName() {
return stack.getConfiguration().getStringValue(OwnProductName.ordinal(), (String) OwnProductName.defValue());
}
public long getFirmware() {
return stack.getConfiguration().getLongValue(OwnFirmwareRevision.ordinal(), -1L);
}
public Set<ApplicationId> getCommonApplications() {
if(logger.isDebugEnabled()) {
logger.debug("In getCommonApplications appIds size is [{}]", appIds.size());
}
if (appIds.isEmpty()) {
Configuration[] apps = stack.getConfiguration().getChildren(ApplicationId.ordinal());
if (apps != null) {
if(logger.isDebugEnabled()) {
logger.debug("Stack configuration has apps list size of [{}]. Looping through them", apps.length);
}
for (Configuration a : apps) {
long vnd = a.getLongValue(VendorId.ordinal(), 0L);
long auth = a.getLongValue(AuthApplId.ordinal(), 0L);
long acc = a.getLongValue(AcctApplId.ordinal(), 0L);
if (logger.isDebugEnabled()) {
logger.debug("Adding app id vendor [{}] auth [{}] acc [{}]", new Object[]{vnd, auth, acc});
}
if (auth != 0) {
appIds.add(org.jdiameter.api.ApplicationId.createByAuthAppId(vnd, auth));
}
if (acc != 0) {
appIds.add(org.jdiameter.api.ApplicationId.createByAccAppId(vnd, acc));
}
}
}
else {
logger.debug("Apps is null - we have no apps in the stack configuration.");
}
}
return appIds;
}
public InetAddress[] getIPAddresses() {
if (addresses.length == 0) {
String address = stack.getConfiguration().getStringValue(OwnIPAddress.ordinal(), null);
if (address == null || address.length() == 0) {
try {
addresses = new InetAddress[]{InetAddress.getByName(getUri().getFQDN())};
}
catch (UnknownHostException e) {
logger.debug("Can not get IP by URI {}", e);
try {
addresses = new InetAddress[]{InetAddress.getLocalHost()};
}
catch (UnknownHostException e1) {
addresses = new InetAddress[0];
}
}
}
else {
InetAddress ia = IPConverter.InetAddressByIPv4(address);
if (ia == null) {
ia = IPConverter.InetAddressByIPv6(address);
}
if (ia == null) {
try {
addresses = new InetAddress[]{InetAddress.getLocalHost()};
}
catch (UnknownHostException e) {
addresses = new InetAddress[0];
}
}
else {
addresses = new InetAddress[]{ia};
}
}
}
return addresses;
}
public IStatistic getStatistic() {
return statistic;
}
public String toString() {
return "Peer{" +
"\n\tUri=" + getUri() + "; RealmName=" + getRealmName() + "; VendorId=" + getVendorId() +
";\n\tProductName=" + getProductName() + "; FirmWare=" + getFirmware() +
";\n\tAppIds=" + getCommonApplications() +
";\n\tIPAddresses=" + Arrays.asList(getIPAddresses()).toString() + ";" + "\n}";
}
public int getRating() {
return 0;
}
public void addPeerStateListener(PeerStateListener peerStateListener) {
}
public void removePeerStateListener(PeerStateListener peerStateListener) {
}
public long getHopByHopIdentifier() {
return hopByHopId.incrementAndGet();
}
public void addMessage(IMessage message) {
}
public void remMessage(IMessage message) {
}
public IMessage[] remAllMessage() {
return new IMessage[0];
}
public boolean handleMessage(EventTypes type, IMessage message, String key) throws TransportException, OverloadException, InternalException {
return false;
}
public boolean sendMessage(IMessage message) throws TransportException, OverloadException {
return false;
}
public boolean hasValidConnection() {
return false;
}
public void setRealm(String realm) {
}
public void addStateChangeListener(StateChangeListener listener) {
}
public void remStateChangeListener(StateChangeListener listener) {
}
public void addConnectionListener(IConnectionListener listener) {
}
public void remConnectionListener(IConnectionListener listener) {
}
/* (non-Javadoc)
* @see org.jdiameter.client.api.controller.IPeer#isConnected()
*/
public boolean isConnected() {
return true; // it's own peer
}
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.controller;
import static org.jdiameter.client.impl.helpers.Parameters.PeerIp;
import static org.jdiameter.client.impl.helpers.Parameters.PeerLocalPortRange;
import static org.jdiameter.client.impl.helpers.Parameters.PeerName;
import static org.jdiameter.client.impl.helpers.Parameters.PeerRating;
import static org.jdiameter.client.impl.helpers.Parameters.StopTimeOut;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.UnknownServiceException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.Configuration;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.MetaData;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.Peer;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.URI;
import org.jdiameter.api.validation.AvpNotAllowedException;
import org.jdiameter.api.validation.Dictionary;
import org.jdiameter.client.api.IAssembler;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.IMetaData;
import org.jdiameter.client.api.IRequest;
import org.jdiameter.client.api.controller.IPeer;
import org.jdiameter.client.api.controller.IPeerTable;
import org.jdiameter.client.api.fsm.IFsmFactory;
import org.jdiameter.client.api.io.ITransportLayerFactory;
import org.jdiameter.client.api.io.TransportException;
import org.jdiameter.client.api.parser.IMessageParser;
import org.jdiameter.client.api.router.IRouter;
import org.jdiameter.client.impl.DictionarySingleton;
import org.jdiameter.client.impl.helpers.Parameters;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class PeerTableImpl implements IPeerTable {
private static final Logger logger = LoggerFactory.getLogger(PeerTableImpl.class);
// Peer table
protected ConcurrentHashMap<String, Peer> peerTable = new ConcurrentHashMap<String, Peer>();
protected boolean isStarted;
protected long stopTimeOut;
protected IAssembler assembler;
protected IRouter router;
protected MetaData metaData;
protected IConcurrentFactory concurrentFactory;
// XXX: FT/HA // protected ConcurrentHashMap<String, NetworkReqListener> sessionReqListeners = new ConcurrentHashMap<String, NetworkReqListener>();
protected ISessionDatasource sessionDatasource;
protected final Dictionary dictionary = DictionarySingleton.getDictionary();
protected PeerTableImpl() {
}
public PeerTableImpl(Configuration globalConfig, MetaData metaData, IContainer stack,IRouter router, IFsmFactory fsmFactory,
ITransportLayerFactory transportFactory, IStatisticManager statisticFactory,
IConcurrentFactory concurrentFactory, IMessageParser parser) {
init(stack,router, globalConfig, metaData, fsmFactory, transportFactory, statisticFactory, concurrentFactory, parser);
}
protected void init( IContainer stack,IRouter router, Configuration globalConfig, MetaData metaData, IFsmFactory fsmFactory,
ITransportLayerFactory transportFactory, IStatisticManager statisticFactory,
IConcurrentFactory concurrentFactory, IMessageParser parser) {
logger.debug("Initializing Peer Table.");
this.router = router;
this.metaData = metaData;
this.concurrentFactory = concurrentFactory;
this.stopTimeOut = globalConfig.getLongValue(StopTimeOut.ordinal(), (Long) StopTimeOut.defValue());
this.sessionDatasource = stack.getAssemblerFacility().getComponentInstance(ISessionDatasource.class);
logger.debug("Populating peerTable from configuration");
Configuration[] peers = globalConfig.getChildren(Parameters.PeerTable.ordinal());
if (peers != null && peers.length > 0) {
for (Configuration peerConfig : peers) {
if (peerConfig.isAttributeExist(PeerName.ordinal())) {
String uri = peerConfig.getStringValue(PeerName.ordinal(), null);
int rating = peerConfig.getIntValue(PeerRating.ordinal(), 0);
String ip = peerConfig.getStringValue(PeerIp.ordinal(), null);
String portRange = peerConfig.getStringValue(PeerLocalPortRange.ordinal(), null);
try {
// create predefined peer
IPeer peer = (IPeer) createPeer(rating, uri, ip, portRange, metaData, globalConfig, peerConfig, fsmFactory, transportFactory, statisticFactory, concurrentFactory, parser);
if (peer != null) {
//NOTE: this depends on conf, in normal case realm is younger part of FQDN, but in some cases
//conf peers may contain IPs only... sucks.
peer.setRealm(router.getRealmTable().getRealmForPeer(peer.getUri().getFQDN()));
peerTable.put(peer.getUri().getFQDN(), peer);
logger.debug("Appended peer [{}] to peer table", peer);
}
}
catch (Exception e) {
logger.warn("Unable to create peer [" + uri + "]", e);
}
}
}
}
}
protected Peer createPeer(int rating, String uri, String ip, String portRange, MetaData metaData, Configuration config, Configuration peerConfig,
IFsmFactory fsmFactory, ITransportLayerFactory transportFactory, IStatisticManager statisticFactory, IConcurrentFactory concurrentFactory, IMessageParser parser)
throws InternalException, TransportException, URISyntaxException, UnknownServiceException {
return new PeerImpl(this, rating, new URI(uri), ip, portRange, metaData.unwrap(IMetaData.class), config,
peerConfig, fsmFactory, transportFactory, statisticFactory, concurrentFactory, parser, this.sessionDatasource);
}
public List<Peer> getPeerTable() {
return new ArrayList<Peer>(peerTable.values());
}
public void sendMessage(IMessage message) throws IllegalDiameterStateException, RouteException, AvpDataException, IOException {
if (!isStarted) {
throw new IllegalDiameterStateException("Stack is down");
}
// Get context
IPeer peer;
if (message.isRequest()) {
if (logger.isDebugEnabled()) {
logger.debug("Send request {} [destHost={}; destRealm={}]", new Object[] {message,
message.getAvps().getAvp(Avp.DESTINATION_HOST) != null ? message.getAvps().getAvp(Avp.DESTINATION_HOST).getOctetString() : "",
message.getAvps().getAvp(Avp.DESTINATION_REALM) != null ? message.getAvps().getAvp(Avp.DESTINATION_REALM).getOctetString() : ""});
}
// Check local request
if(router.updateRoute((IRequest)message)) {
if(logger.isDebugEnabled()) {
logger.debug("Updated route on message {} [destHost={}; destRealm={}]", new Object[] {message,
message.getAvps().getAvp(Avp.DESTINATION_HOST) != null ? message.getAvps().getAvp(Avp.DESTINATION_HOST).getOctetString() : "",
message.getAvps().getAvp(Avp.DESTINATION_REALM) != null ? message.getAvps().getAvp(Avp.DESTINATION_REALM).getOctetString() : ""});
}
}
peer = router.getPeer(message, this);
logger.debug("Selected peer [{}] for sending message [{}]", peer, message);
if (peer == metaData.getLocalPeer()) {
logger.debug("Request [{}] will be processed by local service", message);
}
else {
message.setHopByHopIdentifier(peer.getHopByHopIdentifier());
peer.addMessage(message);
message.setPeer(peer);
}
}
else {
logger.debug("Message is an answer");
peer = message.getPeer();
if (peer == null) {
logger.debug("Peer is null so we will use router.getPeer to find a peer");
peer = router.getPeer(message, this);
if (peer == null) {
throw new RouteException( "Cannot found remote context for sending message" );
}
logger.debug("Found a peer [{}] and setting it as the peer in the message", peer);
message.setPeer(peer);
}
}
try {
logger.debug("Calling sendMessage on peer [{}]", peer);
if (!peer.sendMessage(message)) {
throw new IOException("Can not send message");
}
else {
logger.debug("Message was submitted to be sent, now adding statistics");
if (message.isRequest()) {
if(peer.getStatistic().isEnabled())
peer.getStatistic().getRecordByName(IStatisticRecord.Counters.AppGenRequest.name()).inc();
}
else {
if(peer.getStatistic().isEnabled())
peer.getStatistic().getRecordByName(IStatisticRecord.Counters.AppGenResponse.name()).inc();
}
}
}
catch (Exception e) {
logger.error("Can not send message", e);
if (message.isRequest()) {
if(peer.getStatistic().isEnabled())
peer.getStatistic().getRecordByName(IStatisticRecord.Counters.AppGenRejectedRequest.name()).inc();
}
else {
if(peer.getStatistic().isEnabled())
peer.getStatistic().getRecordByName(IStatisticRecord.Counters.AppGenRejectedResponse.name()).inc();
}
if(e instanceof AvpNotAllowedException) {
throw (AvpNotAllowedException) e;
}
else {
throw new IOException(e.getMessage());
}
}
}
public void addSessionReqListener(String sessionId, NetworkReqListener listener) {
// XXX: FT/HA // sessionReqListeners.put(sessionId, listener);
logger.debug("Adding sessionId [{}] to sessionDatasource", sessionId);
sessionDatasource.setSessionListener(sessionId, listener);
}
public Map<String, NetworkReqListener> getSessionReqListeners() {
// XXX: FT/HA // return sessionReqListeners;
return null;
}
public IPeer getPeer(String fqdn) {
logger.debug("In getPeer for peer with FQDN [{}]. Going to find a matching entry in peerTable", fqdn);
IPeer peer = (IPeer) peerTable.get(fqdn);
if (peer == null) {
logger.debug("No peer found in getPeer for peer [{}] will return null", fqdn);
return null;
}
logger.debug("Found matching peer [{}]. Is connection open ? {}.", peer.getUri(), peer.hasValidConnection());
return peer;
}
public void removeSessionListener(String sessionId) {
// XXX: FT/HA // sessionReqListeners.remove(sessionId);
sessionDatasource.removeSessionListener(sessionId);
}
public void setAssembler(IAssembler assembler) {
this.assembler = assembler;
}
// Life cycle
public void start() throws IllegalDiameterStateException, IOException {
logger.debug("Starting PeerTable. Going to call connect on all peers in the peerTable");
for(Peer peer : peerTable.values()) {
try {
peer.connect();
}
catch (Exception e) {
logger.warn("Can not start connect procedure to peer [" + peer + "]", e);
}
}
logger.debug("Calling start on the router");
router.start();
isStarted = true;
}
public void stopped() {
logger.debug("Calling stopped() on PeerTableImpl");
// XXX: FT/HA // if (sessionReqListeners != null) {
// XXX: FT/HA // sessionReqListeners.clear();
// XXX: FT/HA // }
for (Peer p : peerTable.values()) {
for (IMessage m : ((IPeer) p).remAllMessage()) {
try {
m.runTimer();
}
catch(Exception e) {
logger.debug("Unable to stop timer on message", e);
}
}
}
if (concurrentFactory != null) {
try {
// Wait for some threads which may take longer...
// FIXME: Change this once we get rid of ThreadGroup and hard interrupting threads.
// boolean interrupted = false;
long remWaitTime = 2000;
logger.debug("Stopping thread group and waiting a max of {}ms for all threads to finish", remWaitTime);
while(concurrentFactory.getThreadGroup().activeCount() > 0 && remWaitTime > 0) {
long waitTime = 250;
Thread.sleep(waitTime);
remWaitTime -= waitTime;
logger.debug("Waited {}ms. Time remaining to wait: {}ms. {} Thread still active.", new Object[]{waitTime, remWaitTime, concurrentFactory.getThreadGroup().activeCount()});
// it did not terminated, let's interrupt
// FIXME: remove ASAP, this is very bad, it kills threads in middle of op,
// killing FSM of peer for instance, after that its not usable.
// if(remWaitTime <= 0 && !interrupted) {
// interrupted = true;
// remWaitTime = 2000;
// logger.debug("Stopping thread group did not work. Interrupting and waiting a max of {}ms for all threads to finish", remWaitTime);
// concurrentFactory.getThreadGroup().interrupt();
// }
}
}
catch (Exception e) {
logger.warn("Unable to stop executor");
}
}
router.stop();
}
public void stopping(int disconnectCause) {
logger.debug("In stopping. Going to disconnect all peers in peer table");
isStarted = false;
for (Peer peer : peerTable.values()) {
try {
peer.disconnect(disconnectCause);
}
catch (Exception e) {
logger.warn("Failure disconnecting peer [" + peer.getUri().toString() + "]", e);
}
}
}
public void destroy() {
logger.debug("In destroy. Going to destroy concurrentFactory's thread group");
if (concurrentFactory != null) {
try {
// concurrentFactory.getThreadGroup().interrupt();
// concurrentFactory.getThreadGroup().stop(); //had to add it to make testStartStopStart pass....
// concurrentFactory.getThreadGroup().destroy();
}
catch (IllegalThreadStateException itse) {
if(logger.isDebugEnabled()) {
logger.debug("Failure trying to destroy ThreadGroup probably due to existing active threads. Use stop() before destroy(). (nr_threads={})", concurrentFactory.getThreadGroup().activeCount());
}
}
catch(ThreadDeath td) {
// The class ThreadDeath is specifically a subclass of Error rather than Exception, even though it is a
// "normal occurrence", because many applications catch all occurrences of Exception and then discard the
// exception. ....
}
}
if (router != null) {
logger.debug("Calling destroy on router");
router.destroy();
}
router = null;
peerTable = null;
assembler = null;
}
// Extension interface
public boolean isWrapperFor(Class<?> aClass) throws InternalException {
return false;
}
public <T> T unwrap(Class<T> aClass) throws InternalException {
return null;
}
protected class PeerTableThreadFactory implements ThreadFactory {
public final AtomicLong sequence = new AtomicLong(0);
private int priority = Thread.NORM_PRIORITY;
private ThreadGroup factoryThreadGroup = new ThreadGroup("JDiameterThreadGroup[" + sequence.incrementAndGet() + "]");
public PeerTableThreadFactory(int priority) {
super();
this.priority = priority;
}
public Thread newThread(Runnable r) {
Thread t = new Thread(this.factoryThreadGroup, r);
if(logger.isDebugEnabled()) {
logger.debug("Creating new thread in thread group JDiameterThreadGroup. Thread name is [{}]", t.getName());
}
t.setPriority(this.priority);
// TODO ? t.start();
return t;
}
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.controller;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.LocalAction;
import org.jdiameter.client.api.controller.IRealm;
import org.jdiameter.server.api.agent.IAgent;
import org.jdiameter.server.api.agent.IAgentConfiguration;
/**
* The Realm class implements rows in the Diameter Realm routing table.
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class RealmImpl implements IRealm {
protected String name;
protected ApplicationId appId;
protected LocalAction action;
protected boolean dynamic;
protected long expirationTime;
protected Collection<String> hosts = new ConcurrentLinkedQueue<String>();
protected IAgent agent;
protected IAgentConfiguration agentConfiguration;
public RealmImpl(String name, ApplicationId applicationId, LocalAction localAction,
IAgent agent, IAgentConfiguration agentConfiguration, boolean dynamic, long expirationTime, String... hosts) {
this.hosts.addAll(Arrays.asList(hosts));
this.name = name;
this.appId = applicationId;
this.action = localAction;
this.dynamic = dynamic;
this.expirationTime = expirationTime;
this.agent = agent;
this.agentConfiguration = agentConfiguration;
}
/**
* Return name of this realm
*
* @return name
*/
public String getName() {
return name;
}
/**
* Return applicationId associated with this realm
*
* @return applicationId
*/
public ApplicationId getApplicationId() {
return appId;
}
/**
* Return realm local action for this realm
*
* @return realm local action
*/
public LocalAction getLocalAction() {
return action;
}
/**
* Return list of real peers
*
* @return array of realm peers
*/
public String[] getPeerNames() {
return hosts.toArray(new String[hosts.size()]);
}
/**
* Append new host (peer) to this realm
*
* @param host
* name of peer host
*/
public void addPeerName(String name) {
hosts.add(name);
}
/**
* Remove peer from this realm
*
* @param host
* name of peer host
*/
public void removePeerName(String s) {
hosts.remove(name);
}
/**
* Return true if this realm is dynamic updated
*
* @return true if this realm is dynamic updated
*/
public boolean isDynamic() {
return dynamic;
}
/**
* Return expiration time for this realm in milisec
*
* @return expiration time
*/
public long getExpirationTime() {
return expirationTime;
}
public boolean hasPeerName(String name) {
return this.hosts.contains(name);
}
public IAgent getAgent() {
return agent;
}
public IAgentConfiguration getAgentConfiguration() {
return this.agentConfiguration;
}
public boolean isLocal() {
return false;
}
@Override
public String toString() {
return "RealmImpl [name=" + name + ", appId=" + appId + ", action=" + action + ", dynamic=" + dynamic +
", expirationTime=" + expirationTime + ", hosts=" + hosts + ", agent=" + agent + "]";
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.controller;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Avp;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.LocalAction;
import org.jdiameter.api.Realm;
import org.jdiameter.api.Statistic;
import org.jdiameter.client.api.IAnswer;
import org.jdiameter.client.api.IAssembler;
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.IAgent;
import org.jdiameter.server.api.agent.IAgentConfiguration;
import org.jdiameter.server.api.agent.IProxy;
import org.jdiameter.server.api.agent.IRedirect;
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 RealmTableImpl implements IRealmTable {
private static final Logger logger = LoggerFactory.getLogger(RealmTableImpl.class);
// maps name->realms (cause there might be more than one realm defined, with different app id.
protected Map<String, RealmSet> realmNameToRealmSet = new HashMap<String, RealmSet>();
// "cache" so we don't have to combine all realms
protected List<String> allRealmsSet = new ArrayList<String>();
protected String localRealmName;
protected String localHost;
protected IAssembler assembler;
public RealmTableImpl(IContainer con) {
this.assembler = con.getAssemblerFacility();
}
public boolean realmExists(String realmName) {
// NOTE: this is still valid for local realm
return (this.realmNameToRealmSet.containsKey(realmName) && this.realmNameToRealmSet.get(realmName).size() > 0);
}
public Realm addRealm(String realmName, ApplicationId applicationId, LocalAction action, String agentConfiguration, boolean dynamic, long expirationTime, String[] hosts) throws InternalException {
logger.debug("Adding realm [{}] into network map", realmName);
IAgentConfiguration agentConf = this.assembler.getComponentInstance(IAgentConfiguration.class);
if(agentConf != null) {
agentConf = agentConf.parse(agentConfiguration);
}
return addRealm(realmName, applicationId, action, agentConf, dynamic, expirationTime, hosts);
}
public Realm addRealm(String realmName, ApplicationId applicationId, LocalAction action, IAgentConfiguration agentConf, boolean dynamic, long expirationTime, String[] hosts) throws InternalException {
IAgent agent = null;
switch (action) {
case LOCAL:
case RELAY:
break;
case PROXY:
agent = this.assembler.getComponentInstance(IProxy.class);
break;
case REDIRECT:
agent = this.assembler.getComponentInstance(IRedirect.class);
break;
}
RealmImpl realmImpl = new RealmImpl(realmName, applicationId, action, agent,agentConf, dynamic, expirationTime, hosts);
addRealm(realmImpl);
return realmImpl;
}
/*
* (non-Javadoc)
* @see org.jdiameter.client.api.controller.IRealmTable#getRealm(java.lang.String, org.jdiameter.api.ApplicationId)
*/
public Realm getRealm(String realmName, ApplicationId applicationId) {
RealmSet rs = this.realmNameToRealmSet.get(realmName);
return rs == null ? null : rs.getRealm(applicationId);
}
/*
* (non-Javadoc)
* @see org.jdiameter.client.api.controller.IRealmTable#removeRealmApplicationId(java.lang.String, org.jdiameter.api.ApplicationId)
*/
public Realm removeRealmApplicationId(String realmName, ApplicationId appId) {
RealmSet set = this.realmNameToRealmSet.get(realmName);
if (set != null) {
Realm r = set.getRealm(appId);
set.removeRealm(appId);
if (set.size() == 0 && !realmName.equals(this.localRealmName)) {
this.realmNameToRealmSet.remove(realmName);
this.allRealmsSet.remove(realmName);
}
return r;
}
return null;
}
/*
* (non-Javadoc)
* @see org.jdiameter.client.api.controller.IRealmTable#removeRealms(java.lang.String)
*/
public Collection<Realm> removeRealm(String realmName) {
RealmSet set = null;
if (realmName.equals(this.localRealmName)) {
set = this.realmNameToRealmSet.get(realmName);
}
else {
set = this.realmNameToRealmSet.remove(realmName);
if (set != null) {
Collection<Realm> present = set.values();
allRealmsSet.remove(realmName);
return new ArrayList<Realm>(present);
}
}
return null;
}
/*
* (non-Javadoc)
* @see org.jdiameter.client.api.controller.IRealmTable#getRealms(java.lang.String)
*/
public Collection<Realm> getRealms(String realmName) {
RealmSet set = this.realmNameToRealmSet.get(realmName);
if (set != null) {
Collection<Realm> present = set.values();
return new ArrayList<Realm>(present);
}
return null;
}
/*
* (non-Javadoc)
* @see org.jdiameter.client.api.controller.IRealmTable#getRealms()
*/
public Collection<Realm> getRealms() {
ArrayList<Realm> rss = new ArrayList<Realm>();
Set<String> keys = new HashSet<String>(this.realmNameToRealmSet.keySet());
for (String key : keys) {
RealmSet rs = this.realmNameToRealmSet.get(key);
rss.addAll(rs.values());
}
return rss;
}
/*
* (non-Javadoc)
* @see org.jdiameter.client.api.controller.IRealmTable#matchRealm(org.jdiameter.client.api.IRequest)
*/
public Realm matchRealm(IRequest request) {
try {
// once again casting...
IMessage req = (IMessage) request;
String destinationRealm = req.getAvps().getAvp(Avp.DESTINATION_REALM).getDiameterIdentity();
// we have req, we need match, not dummy longest from right BS match.
return this.matchRealm(req, destinationRealm);
}
catch (Exception e) {
logger.error("Unable to read Destination-Realm AVP to match realm to request", e);
}
return null;
}
/*
* (non-Javadoc)
* @see org.jdiameter.client.api.controller.IRealmTable#matchRealm(org.jdiameter.client.api.IAnswer, java.lang.String)
*/
public Realm matchRealm(IAnswer message, String destRealm) {
return this.matchRealm((IMessage) message, destRealm);
}
/*
* (non-Javadoc)
* @see org.jdiameter.client.api.controller.IRealmTable#getRealmForPeer(java.lang.String)
*/
public String getRealmForPeer(String fqdn) {
//
Collection<Realm> realms = getRealms();
for (Realm r : realms) {
IRealm ir = (IRealm) r;
if (ir.hasPeerName(fqdn)) {
return ir.getName();
}
}
return null;
}
/**
* @param appId
*/
public void addLocalApplicationId(ApplicationId appId) {
RealmSet rs = getRealmSet(localRealmName, false);
rs.addRealm(new RealmImpl(localRealmName, appId, LocalAction.LOCAL, null,null, true, -1, this.localHost) {
public boolean isLocal() {
return true;
}
});
}
/**
* @param appId
*/
public void removeLocalApplicationId(ApplicationId appId) {
RealmSet rs = getRealmSet(localRealmName, false);
Realm realm = rs.getRealm(appId);
if (realm.isDynamic()) {
rs.removeRealm(appId);
}
}
/**
* @param localRealm
* @param fqdn
*/
public void addLocalRealm(String localRealm, String fqdn) {
this.localRealmName = localRealm;
this.localHost = fqdn;
getRealmSet(localRealm, true /* adds realm if not present */);
}
// -------------------- helper methods --------------------
protected Realm matchRealm(IMessage message, String realm) {
if (realmExists(realm)) {
ApplicationId singleId = message.getSingleApplicationId();
// check on single app id, than we iterate.
Realm r = getRealm(realm, singleId);
if (r == null) {
List<ApplicationId> appIds = message.getApplicationIdAvps();
for (int index = 0; index < appIds.size(); index++) {
r = getRealm(realm, appIds.get(index));
if (r != null) {
break;
}
}
}
return r;
}
return null;
}
protected void addRealm(Realm realm) throws InternalException {
RealmSet rs = getRealmSet(realm.getName(), true);
rs.addRealm(realm);
allRealmsSet.add(realm.getName());
}
protected RealmSet getRealmSet(String pKey, boolean create) {
RealmSet rs = realmNameToRealmSet.get(pKey);
if (rs == null && create) {
rs = new RealmSet();
realmNameToRealmSet.put(pKey, rs);
}
return rs;
}
private class RealmSet {
// TODO: use two lists and iterate over index?
protected Map<ApplicationId, Realm> appIdToRealm = new HashMap<ApplicationId, Realm>();
/**
* @param realm
* @throws InternalException
*/
public void addRealm(Realm realm) {
if (this.appIdToRealm.containsKey(realm.getApplicationId())) {
Realm presentRealm = this.appIdToRealm.get(realm.getApplicationId());
if (realm.getName().equals(localRealmName)) {
// we need to merge - its a local realm, possibly definition
// of hosts that can handle requests for us.
RealmImpl realmImpl = (RealmImpl) presentRealm;
realmImpl.dynamic = false; // ensure its static
for (String peerName : ((RealmImpl) realm).getPeerNames()) {
realmImpl.addPeerName(peerName);
}
}
else if (!presentRealm.isDynamic() && realm.isDynamic()) {
// its a dynamic realm, present is static, we dont have to
// do a thing?
}
else if (presentRealm.isDynamic() && !realm.isDynamic()) {
// we need to merge?
RealmImpl realmImpl = (RealmImpl) presentRealm;
realmImpl.dynamic = false; // make it static :)
for (String peerName : ((RealmImpl) realm).getPeerNames()) {
realmImpl.addPeerName(peerName);
}
}
else {
if(logger.isDebugEnabled()) {
logger.debug("Entry for realm '{}', already exists: {}", realm, this);
}
}
}
else {
this.appIdToRealm.put(realm.getApplicationId(), realm);
}
}
/**
* @return
*/
public Collection<Realm> values() {
return this.appIdToRealm.values();
}
/**
* @return
*/
public int size() {
return this.appIdToRealm.size();
}
/**
* @param appId
* @return
*/
public Realm getRealm(ApplicationId appId) {
return this.appIdToRealm.get(appId);
}
/**
* @param appId
* @return
*/
public Realm removeRealm(ApplicationId appId) {
return this.appIdToRealm.remove(appId);
}
}
/*
* (non-Javadoc)
* @see org.jdiameter.api.RealmTable#getStatistic(java.lang.String)
*/
@Override
public Statistic getStatistic(String realmName) {
// FIXME: ...
return null;
}
/*
* (non-Javadoc)
* @see org.jdiameter.api.Wrapper#isWrapperFor(java.lang.Class)
*/
@Override
public boolean isWrapperFor(Class<?> iface) throws InternalException {
return false;
}
/*
* (non-Javadoc)
* @see org.jdiameter.api.Wrapper#unwrap(java.lang.Class)
*/
@Override
public <T> T unwrap(Class<T> iface) throws InternalException {
return null;
}
}
| 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.client.impl.controller;
import static org.jdiameter.api.Avp.ACCT_APPLICATION_ID;
import static org.jdiameter.api.Avp.AUTH_APPLICATION_ID;
import static org.jdiameter.api.Avp.DESTINATION_HOST;
import static org.jdiameter.api.Avp.DESTINATION_REALM;
import static org.jdiameter.api.Avp.DISCONNECT_CAUSE;
import static org.jdiameter.api.Avp.ERROR_MESSAGE;
import static org.jdiameter.api.Avp.FIRMWARE_REVISION;
import static org.jdiameter.api.Avp.HOST_IP_ADDRESS;
import static org.jdiameter.api.Avp.ORIGIN_HOST;
import static org.jdiameter.api.Avp.ORIGIN_REALM;
import static org.jdiameter.api.Avp.ORIGIN_STATE_ID;
import static org.jdiameter.api.Avp.PRODUCT_NAME;
import static org.jdiameter.api.Avp.RESULT_CODE;
import static org.jdiameter.api.Avp.SUPPORTED_VENDOR_ID;
import static org.jdiameter.api.Avp.VENDOR_ID;
import static org.jdiameter.api.Avp.VENDOR_SPECIFIC_APPLICATION_ID;
import static org.jdiameter.api.Message.CAPABILITIES_EXCHANGE_REQUEST;
import static org.jdiameter.api.Message.DEVICE_WATCHDOG_REQUEST;
import static org.jdiameter.api.Message.DISCONNECT_PEER_REQUEST;
import static org.jdiameter.client.api.fsm.EventTypes.CEA_EVENT;
import static org.jdiameter.client.api.fsm.EventTypes.CER_EVENT;
import static org.jdiameter.client.api.fsm.EventTypes.CONNECT_EVENT;
import static org.jdiameter.client.api.fsm.EventTypes.DISCONNECT_EVENT;
import static org.jdiameter.client.api.fsm.EventTypes.DPA_EVENT;
import static org.jdiameter.client.api.fsm.EventTypes.DPR_EVENT;
import static org.jdiameter.client.api.fsm.EventTypes.DWA_EVENT;
import static org.jdiameter.client.api.fsm.EventTypes.DWR_EVENT;
import static org.jdiameter.client.api.fsm.EventTypes.INTERNAL_ERROR;
import static org.jdiameter.client.api.fsm.EventTypes.RECEIVE_MSG_EVENT;
import static org.jdiameter.client.api.fsm.EventTypes.STOP_EVENT;
import static org.jdiameter.client.impl.helpers.Parameters.SecurityRef;
import static org.jdiameter.client.impl.helpers.Parameters.UseUriAsFqdn;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.Configuration;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Message;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Peer;
import org.jdiameter.api.PeerState;
import org.jdiameter.api.PeerStateListener;
import org.jdiameter.api.ResultCode;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.URI;
import org.jdiameter.api.app.StateChangeListener;
import org.jdiameter.api.validation.Dictionary;
import org.jdiameter.client.api.IAnswer;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.IMetaData;
import org.jdiameter.client.api.IRequest;
import org.jdiameter.client.api.controller.IPeer;
import org.jdiameter.client.api.fsm.EventTypes;
import org.jdiameter.client.api.fsm.FsmEvent;
import org.jdiameter.client.api.fsm.IContext;
import org.jdiameter.client.api.fsm.IFsmFactory;
import org.jdiameter.client.api.fsm.IStateMachine;
import org.jdiameter.client.api.io.IConnection;
import org.jdiameter.client.api.io.IConnectionListener;
import org.jdiameter.client.api.io.ITransportLayerFactory;
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.api.router.IRouter;
import org.jdiameter.client.impl.AbstractStateChangeListener;
import org.jdiameter.client.impl.DictionarySingleton;
import org.jdiameter.common.api.concurrent.IConcurrentFactory;
import org.jdiameter.common.api.data.ISessionDatasource;
import org.jdiameter.common.api.statistic.IStatistic;
import org.jdiameter.common.api.statistic.IStatisticManager;
import org.jdiameter.common.api.statistic.IStatisticRecord;
import org.jdiameter.common.impl.controller.AbstractPeer;
import org.jdiameter.server.impl.MutablePeerTableImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Client Peer implementation
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class PeerImpl extends AbstractPeer implements IPeer {
private static final Logger logger = LoggerFactory.getLogger(PeerImpl.class);
// Properties
protected InetAddress[] addresses;
protected String realmName;
protected long vendorID;
protected String productName;
protected int firmWare;
protected Set<ApplicationId> commonApplications = new HashSet<ApplicationId>();
protected AtomicLong hopByHopId = new AtomicLong(uid.nextInt());
protected int rating;
protected boolean stopping = false;
// Members
protected IMetaData metaData;
protected PeerTableImpl table;
// Facilities
protected IRouter router;
// XXX: FT/HA // protected Map<String, NetworkReqListener> slc;
protected final Map<Long, IMessage> peerRequests = new ConcurrentHashMap<Long, IMessage>();
protected final Dictionary dictionary = DictionarySingleton.getDictionary();
// FSM layer
protected IStateMachine fsm;
protected IMessageParser parser;
// Feature
protected boolean useUriAsFQDN = false; // Use URI as origin host name into CER command
//session store and data
protected ISessionDatasource sessionDataSource;
// Transport layer
protected IConnection connection;
protected IConnectionListener connListener = new IConnectionListener() {
public void connectionOpened(String connKey) {
logger.debug("Connection to {} is open", uri);
try {
fsm.handleEvent(new FsmEvent(CONNECT_EVENT, connKey));
}
catch (Exception e) {
logger.warn("Unable to run start procedure", e);
}
}
public void connectionClosed(String connKey, List notSent) {
logger.debug("Connection from {} is closed", uri);
for (IMessage request : peerRequests.values()) {
if (request.getState() == IMessage.STATE_SENT) {
request.setReTransmitted(true);
request.setState(IMessage.STATE_NOT_SENT);
try {
peerRequests.remove(request.getHopByHopIdentifier());
table.sendMessage(request);
}
catch (Throwable exc) {
request.setReTransmitted(false);
}
}
}
try {
fsm.handleEvent(new FsmEvent(DISCONNECT_EVENT, connKey));
}
catch (Exception e) {
logger.warn("Unable to run stopping procedure", e);
}
}
public void messageReceived(String connKey, IMessage message) {
boolean req = message.isRequest();
try {
int type = message.getCommandCode();
logger.debug("Receive message type [{}] to peer [{}]", new Object[] {type, connKey});
switch (type) {
case CAPABILITIES_EXCHANGE_REQUEST:
fsm.handleEvent(new FsmEvent(req ? CER_EVENT : CEA_EVENT, message, connKey));
break;
case DEVICE_WATCHDOG_REQUEST:
fsm.handleEvent(new FsmEvent(req ? DWR_EVENT : DWA_EVENT, message, connKey));
break;
case DISCONNECT_PEER_REQUEST:
fsm.handleEvent(new FsmEvent(req ? DPR_EVENT : DPA_EVENT, message));
break;
default:
fsm.handleEvent(new FsmEvent(RECEIVE_MSG_EVENT, message));
break;
}
}
catch (Exception e) {
logger.warn("Error while processing incoming message", e);
if (req) {
try {
message.setRequest(false);
message.setError(true);
message.getAvps().addAvp(Avp.RESULT_CODE, ResultCode.TOO_BUSY, true);
connection.sendMessage(message);
}
catch (Exception exc) {
logger.warn("Unable to send error answer", exc);
}
}
}
}
public void internalError(String connKey, IMessage message, TransportException cause) {
try {
logger.debug("internalError ", cause);
fsm.handleEvent(new FsmEvent(INTERNAL_ERROR, message));
}
catch (Exception e) {
logger.debug("Unable to run internalError procedure", e);
}
}
};
public PeerImpl(final PeerTableImpl table, int rating, URI remotePeer, String ip, String portRange, IMetaData metaData, Configuration config,
Configuration peerConfig, IFsmFactory fsmFactory, ITransportLayerFactory trFactory, IStatisticManager statisticFactory,
IConcurrentFactory concurrentFactory, IMessageParser parser, final ISessionDatasource sessionDataSource) throws InternalException, TransportException {
this(table, rating, remotePeer, ip, portRange, metaData, config, peerConfig, fsmFactory, trFactory, parser, statisticFactory, concurrentFactory, null, sessionDataSource);
}
protected PeerImpl(final PeerTableImpl table, int rating, URI remotePeer, String ip, String portRange, IMetaData metaData,
Configuration config, Configuration peerConfig, IFsmFactory fsmFactory, ITransportLayerFactory trFactory,
IMessageParser parser, IStatisticManager statisticFactory, IConcurrentFactory concurrentFactory,
IConnection connection, final ISessionDatasource sessionDataSource) throws InternalException, TransportException {
super(remotePeer, statisticFactory);
this.table = table;
this.rating = rating;
this.router = table.router;
this.metaData = metaData;
// XXX: FT/HA // this.slc = table.getSessionReqListeners();
this.sessionDataSource = sessionDataSource;
int port = remotePeer.getPort();
InetAddress remoteAddress;
try {
remoteAddress = InetAddress.getByName(ip != null ? ip : remotePeer.getFQDN());
}
catch (UnknownHostException e) {
throw new TransportException("Unable to retrieve host", TransportError.Internal, e);
}
IContext actionContext = getContext();
this.fsm = fsmFactory.createInstanceFsm(actionContext, concurrentFactory, config);
this.fsm.addStateChangeNotification(
new AbstractStateChangeListener() {
public void stateChanged(Enum oldState, Enum newState) {
PeerState s = (PeerState) newState;
if (PeerState.DOWN.equals(s)) {
stopping = false;
}
}
}
);
if (connection == null) {
String ref = peerConfig.getStringValue(SecurityRef.ordinal(), null);
InetAddress localAddress = null;
try {
Peer local = metaData.getLocalPeer();
if (local.getIPAddresses() != null && local.getIPAddresses().length > 0) {
localAddress = local.getIPAddresses()[0];
}
else {
localAddress = InetAddress.getByName(metaData.getLocalPeer().getUri().getFQDN());
}
}
catch (Exception e) {
logger.warn("Unable to get local address", e);
}
int localPort = 0;
if (portRange != null) {
try {
String[] rng = portRange.trim().split("-");
int startRange = Integer.parseInt(rng[0]);
int endRange = Integer.parseInt(rng[1]);
boolean portNotAvailable = false;
int limit = 0;
int maxTries = endRange - startRange + 1;
logger.debug("Selecting local port randomly from range '{}-{}'. Doing {} tries (some ports may not be tested, others tested more than once).", new Object[]{startRange, endRange, maxTries});
do {
portNotAvailable = false;
limit++;
localPort = startRange + new Random().nextInt(endRange - startRange + 1);
logger.trace("Checking if port '{}' is available.", localPort);
//check if port is open
ServerSocket socket = null;
try {
socket = new ServerSocket(localPort);
socket.setReuseAddress(true);
}
catch (IOException e) {
logger.trace("The port '{}' is NOT available.", localPort);
portNotAvailable = true;
}
finally {
// Clean up
if (socket != null) {
logger.trace("The port '{}' is available and will be used.", localPort);
socket.close();
}
}
} while (portNotAvailable && (limit < maxTries));
if(portNotAvailable){
logger.warn("Unable to find available port in port range.");
}
}
catch (Exception exc) {
logger.warn("Unable to get local port.", exc);
}
logger.debug("Create connection with localAddress=[{}]; localPort=[{}]", localAddress, localPort);
}
this.connection = trFactory.createConnection(remoteAddress, concurrentFactory, port, localAddress, localPort, connListener, ref);
}
else {
this.connection = connection;
this.connection.addConnectionListener(connListener);
}
this.parser = parser;
this.addresses = new InetAddress[] {remoteAddress};
this.useUriAsFQDN = config.getBooleanValue(UseUriAsFqdn.ordinal(), (Boolean) UseUriAsFqdn.defValue());
}
public IContext getContext() {
return new ActionContext();
}
private boolean isRedirectAnswer(Avp avpResCode, IMessage answer) {
try {
return (answer.getFlags() & 0x20) != 0 && avpResCode != null && avpResCode.getInteger32() == ResultCode.REDIRECT_INDICATION;
}
catch (AvpDataException e) {
return false;
}
}
public IStatistic getStatistic() {
return statistic;
}
public void addPeerStateListener(final PeerStateListener listener) {
fsm.addStateChangeNotification(new AbstractStateChangeListener() {
public void stateChanged(Enum oldState, Enum newState) {
listener.stateChanged((PeerState) oldState, (PeerState) newState);
}
public int hashCode() {
return listener.hashCode();
}
public boolean equals(Object obj) {
return listener.equals(obj);
}
});
}
public void removePeerStateListener(final PeerStateListener listener) {
//FIXME: fix this... cmon
if (listener != null) {
fsm.remStateChangeNotification(new AbstractStateChangeListener() {
public void stateChanged(Enum oldState, Enum newState) {
listener.stateChanged((PeerState) oldState, (PeerState) newState);
}
public int hashCode() {
return listener.hashCode();
}
public boolean equals(Object obj) {
return listener.equals(obj);
}
});
}
}
private IMessage processRedirectAnswer(IMessage request,IMessage answer) {
int resultCode = ResultCode.SUCCESS;
try {
//it will try to find next hope and send it...
router.processRedirectAnswer((IRequest)request,(IAnswer)answer,table);
return null;
}
catch (RouteException exc) {
// Loop detected (may be stack must send error response to redirect host)
if(logger.isDebugEnabled()) {
logger.debug("Failed to process redirect!",exc);
}
resultCode = ResultCode.LOOP_DETECTED;
}
catch (Throwable exc) {
// Incorrect redirect message
logger.debug("Failed to process redirect!", exc);
resultCode = ResultCode.UNABLE_TO_DELIVER;
}
//why, oh why, peer works as router?....
// // Update destination avps
// if (resultCode == ResultCode.SUCCESS) {
// // Clear avps
// answer.getAvps().removeAvp(RESULT_CODE);
// // Update flags
// answer.setRequest(true);
// answer.setError(false);
// try {
// table.sendMessage(answer);
// answer = null;
// }
// catch (Exception e) {
// logger.warn("Unable to deliver due to error", e);
// resultCode = ResultCode.UNABLE_TO_DELIVER;
// }
// }
if (resultCode != ResultCode.SUCCESS) {
// Restore answer flag
answer.setRequest(false);
answer.setError(true);
answer.getAvps().removeAvp(RESULT_CODE);
answer.getAvps().addAvp(RESULT_CODE, resultCode, true, false, true);
}
return answer;
}
public void connect() throws InternalException, IOException, IllegalDiameterStateException {
if (getState(PeerState.class) != PeerState.DOWN) {
throw new IllegalDiameterStateException("Invalid state:" + getState(PeerState.class));
}
try {
fsm.handleEvent(new FsmEvent(EventTypes.START_EVENT));
}
catch (Exception e) {
throw new InternalException(e);
}
}
public void disconnect(int disconnectCause) throws InternalException, IllegalDiameterStateException {
super.disconnect(disconnectCause);
if (getState(PeerState.class) != PeerState.DOWN) {
stopping = true;
try {
FsmEvent event = new FsmEvent(STOP_EVENT);
event.setData(disconnectCause);
fsm.handleEvent(event);
}
catch (OverloadException e) {
stopping = false;
logger.warn("Error during stopping procedure", e);
}
}
}
public <E> E getState(Class<E> enumc) {
return fsm.getState(enumc);
}
public URI getUri() {
return uri;
}
public InetAddress[] getIPAddresses() {
return addresses;
}
public String getRealmName() {
return realmName;
}
public long getVendorId() {
return vendorID;
}
public String getProductName() {
return productName;
}
public long getFirmware() {
return firmWare;
}
public Set<ApplicationId> getCommonApplications() {
return commonApplications;
}
public long getHopByHopIdentifier() {
return hopByHopId.incrementAndGet();
}
public void addMessage(IMessage message) {
peerRequests.put(message.getHopByHopIdentifier(), message);
}
public void remMessage(IMessage message) {
peerRequests.remove(message.getHopByHopIdentifier());
}
public IMessage[] remAllMessage() {
IMessage[] m = peerRequests.values().toArray(new IMessage[peerRequests.size()]);
peerRequests.clear();
return m;
}
public boolean handleMessage(EventTypes type, IMessage message, String key) throws TransportException, OverloadException, InternalException {
return !stopping && fsm.handleEvent(new FsmEvent(type, message, key));
}
public boolean sendMessage(IMessage message) throws TransportException, OverloadException, InternalException {
if(dictionary != null && dictionary.isEnabled()) {
logger.debug("Message validation is ENABLED. Going to validate message before sending.");
dictionary.validate(message, false);
}
return !stopping && fsm.handleEvent(new FsmEvent(EventTypes.SEND_MSG_EVENT, message));
}
public boolean hasValidConnection() {
return connection != null && connection.isConnected();
}
public void setRealm(String realm) {
realmName = realm;
}
public void addStateChangeListener(StateChangeListener listener) {
fsm.addStateChangeNotification(listener);
}
public void remStateChangeListener(StateChangeListener listener) {
fsm.remStateChangeNotification(listener);
}
public void addConnectionListener(IConnectionListener listener) {
if (connection != null) {
connection.addConnectionListener(listener);
}
}
public void remConnectionListener(IConnectionListener listener) {
if (connection != null) {
connection.remConnectionListener(listener);
}
}
public int getRating() {
return rating;
}
@Override
public boolean isConnected() {
return getState(PeerState.class) == PeerState.OKAY;
}
public String toString() {
return "CPeer{" + "Uri=" + uri + "; State=" + (fsm != null ? fsm.getState(PeerState.class) : "n/a") + "; Con="+ connection + "}";
}
protected void fillIPAddressTable(IMessage message) {
AvpSet avps = message.getAvps().getAvps(HOST_IP_ADDRESS);
if (avps != null) {
ArrayList<InetAddress> t = new ArrayList<InetAddress>();
for (int i = 0; i < avps.size(); i++) {
try {
t.add(avps.getAvpByIndex(i).getAddress());
}
catch (AvpDataException e) {
logger.warn("Unable to retrieve IP Address from Host-IP-Address AVP");
}
}
addresses = t.toArray(new InetAddress[t.size()]);
}
}
protected Set<ApplicationId> getCommonApplicationIds(IMessage message) {
//TODO: fix this, its not correct lookup. It should check realm!
//it does not include application Ids for which listeners register - and on this basis it consume message!
Set<ApplicationId> newAppId = new HashSet<ApplicationId>();
Set<ApplicationId> locAppId = metaData.getLocalPeer().getCommonApplications();
List<ApplicationId> remAppId = message.getApplicationIdAvps();
logger.debug("Checking common applications. Remote applications: {}. Local applications: {}", remAppId, locAppId);
// check common application
for (ApplicationId l : locAppId) {
for (ApplicationId r : remAppId) {
if (l.equals(r)) {
newAppId.add(l);
}
else if (r.getAcctAppId() == INT_COMMON_APP_ID || r.getAuthAppId() == INT_COMMON_APP_ID ||
l.getAcctAppId() == INT_COMMON_APP_ID || l.getAuthAppId() == INT_COMMON_APP_ID) {
newAppId.add(r);
}
}
}
return newAppId;
}
protected void sendErrorAnswer(IRequest request, String errorMessage, int resultCode, Avp ...avpsToAdd) {
logger.debug("Could not process request. Result Code = [{}], Error Message: [{}]", resultCode, errorMessage);
request.setRequest(false);
// Not setting error flag, depends on error code. Will be set @ PeerImpl.ActionContext.sendMessage(IMessage)
// request.setError(true);
request.getAvps().addAvp(RESULT_CODE, resultCode, true, false, true);
//add before removal actions
if(avpsToAdd != null) {
for(Avp a: avpsToAdd) {
request.getAvps().addAvp(a);
}
}
request.getAvps().removeAvp(ORIGIN_HOST);
request.getAvps().removeAvp(ORIGIN_REALM);
request.getAvps().addAvp(ORIGIN_HOST, metaData.getLocalPeer().getUri().getFQDN(), true, false, true);
request.getAvps().addAvp(ORIGIN_REALM, metaData.getLocalPeer().getRealmName(), true, false, true);
if (errorMessage != null) {
request.getAvps().addAvp(ERROR_MESSAGE, errorMessage, false);
}
// Remove trash avp
request.getAvps().removeAvp(DESTINATION_HOST);
request.getAvps().removeAvp(DESTINATION_REALM);
try {
logger.debug("Sending response indicating we could not process request");
sendMessage((IMessage) request);
if(statistic.isEnabled()) {
statistic.getRecordByName(IStatisticRecord.Counters.SysGenResponse.name()).inc();
}
}
catch (Exception e) {
logger.debug("Unable to send answer", e);
}
if(statistic.isEnabled()) {
statistic.getRecordByName(IStatisticRecord.Counters.NetGenRejectedRequest.name()).inc();
}
}
protected class ActionContext implements IContext {
public String toString() {
return new StringBuilder("ActionContext [getPeerDescription()=").append(getPeerDescription()).append(", isConnected()=").append(isConnected()).append(", isRestoreConnection()=").append(isRestoreConnection()).append("]").toString();
}
public void connect() throws InternalException, IOException, IllegalDiameterStateException {
try {
connection.connect();
if(logger.isDebugEnabled()) {
logger.debug("Connected to peer {}", getUri());
}
}
catch (TransportException e) {
logger.debug("Failure establishing connection.", e);
switch (e.getCode()) {
case NetWorkError:
throw new IOException("Unable to connect to " + connection.getKey() + " - " + e.getMessage());
case FailedSendMessage:
throw new IllegalDiameterStateException(e);
default:
throw new InternalException(e);
}
}
}
public void disconnect() throws InternalException, IllegalDiameterStateException {
if (connection != null) {
connection.disconnect();
if(logger.isDebugEnabled()) {
logger.debug("Disconnected from peer {}", getUri());
}
}
}
public String getPeerDescription() {
return uri.toString();
}
public boolean isConnected() {
return (connection != null) && connection.isConnected();
}
public boolean sendMessage(IMessage message) throws TransportException, OverloadException {
// Check message
if (message.isTimeOut()) {
logger.debug("Message {} skipped (timeout)", message);
return false;
}
if (message.getState() == IMessage.STATE_SENT) {
logger.debug("Message {} already sent", message);
return false;
}
// Remove destination information from answer messages
if (!message.isRequest()) {
try {
long resultCode = message.getResultCode().getUnsigned32();
message.setError(resultCode >= 3000 && resultCode < 4000);
}
catch (Exception e) {
logger.debug("Unable to retrieve Result-Code from answer. Not setting ERROR bit.");
// ignore. should not happen
}
// 6.2. Diameter Answer Processing answers and Error messages DONT have those.... pffff.
message.getAvps().removeAvp(DESTINATION_HOST);
message.getAvps().removeAvp(DESTINATION_REALM);
int commandCode = message.getCommandCode();
// We don't want this for CEx/DWx/DPx
if(commandCode != 257 && commandCode != 280 && commandCode != 282) {
if(table instanceof MutablePeerTableImpl) { // available only to server, client skip this step
MutablePeerTableImpl peerTable = (MutablePeerTableImpl) table;
if(peerTable.isDuplicateProtection()) {
String[] originInfo = router.getRequestRouteInfo(message);
if(originInfo != null) {
// message.getDuplicationKey() doesn't work because it's answer
peerTable.saveToDuplicate(message.getDuplicationKey(originInfo[0], message.getEndToEndIdentifier()), message);
}
}
}
}
}
// PCB added this
router.garbageCollectRequestRouteInfo(message);
// Send to network
message.setState(IMessage.STATE_SENT);
logger.debug("Calling connection to send message [{}] to peer [{}] over the network", message, getUri());
connection.sendMessage(message);
logger.debug("Connection sent message [{}] to peer [{}] over the network", message, getUri());
return true;
}
public void sendCerMessage() throws TransportException, OverloadException {
logger.debug("Send CER message");
IMessage message = parser.createEmptyMessage(CAPABILITIES_EXCHANGE_REQUEST, 0);
message.setRequest(true);
message.setHopByHopIdentifier(getHopByHopIdentifier());
if (useUriAsFQDN) {
message.getAvps().addAvp(ORIGIN_HOST, metaData.getLocalPeer().getUri().toString(), true, false, true);
}
else {
message.getAvps().addAvp(ORIGIN_HOST, metaData.getLocalPeer().getUri().getFQDN(), true, false, true);
}
message.getAvps().addAvp(ORIGIN_REALM, metaData.getLocalPeer().getRealmName(), true, false, true);
for (InetAddress ia : metaData.getLocalPeer().getIPAddresses()) {
message.getAvps().addAvp(HOST_IP_ADDRESS, ia, true, false);
}
message.getAvps().addAvp(VENDOR_ID, metaData.getLocalPeer().getVendorId(), true, false, true);
message.getAvps().addAvp(PRODUCT_NAME, metaData.getLocalPeer().getProductName(), false);
for (ApplicationId appId : metaData.getLocalPeer().getCommonApplications()) {
addAppId(appId, message);
}
message.getAvps().addAvp(FIRMWARE_REVISION, metaData.getLocalPeer().getFirmware(), true);
message.getAvps().addAvp(ORIGIN_STATE_ID, metaData.getLocalHostStateId(), true, false, true);
sendMessage(message);
}
public void sendCeaMessage(int resultCode, Message cer, String errMessage) throws TransportException, OverloadException {
}
public void sendDwrMessage() throws TransportException, OverloadException {
logger.debug("Send DWR message");
IMessage message = parser.createEmptyMessage(DEVICE_WATCHDOG_REQUEST, 0);
message.setRequest(true);
message.setHopByHopIdentifier(getHopByHopIdentifier());
// Set content
message.getAvps().addAvp(ORIGIN_HOST, metaData.getLocalPeer().getUri().getFQDN(), true, false, true);
message.getAvps().addAvp(ORIGIN_REALM, metaData.getLocalPeer().getRealmName(), true, false, true);
message.getAvps().addAvp(ORIGIN_STATE_ID, metaData.getLocalHostStateId(), true, false, true);
// Remove trash avp
message.getAvps().removeAvp(DESTINATION_HOST);
message.getAvps().removeAvp(DESTINATION_REALM);
// Send
sendMessage(message);
}
public void sendDwaMessage(IMessage dwr, int resultCode, String errorMessage) throws TransportException, OverloadException {
logger.debug("Send DWA message");
IMessage message = parser.createEmptyMessage(dwr);
message.setRequest(false);
message.setHopByHopIdentifier(dwr.getHopByHopIdentifier());
message.setEndToEndIdentifier(dwr.getEndToEndIdentifier());
// Set content
message.getAvps().addAvp(RESULT_CODE, resultCode, true, false, true);
message.getAvps().addAvp(ORIGIN_HOST, metaData.getLocalPeer().getUri().getFQDN(), true, false, true);
message.getAvps().addAvp(ORIGIN_REALM, metaData.getLocalPeer().getRealmName(), true, false, true);
if (errorMessage != null) {
message.getAvps().addAvp(ERROR_MESSAGE, errorMessage, false);
}
// Remove trash avp
message.getAvps().removeAvp(DESTINATION_HOST);
message.getAvps().removeAvp(DESTINATION_REALM);
// Send
sendMessage(message);
}
public boolean isRestoreConnection() {
return true;
}
public void sendDprMessage(int disconnectCause) throws TransportException, OverloadException {
logger.debug("Send DPR message with Disconnect-Cause [{}]", disconnectCause);
IMessage message = parser.createEmptyMessage(DISCONNECT_PEER_REQUEST, 0);
message.setRequest(true);
message.setHopByHopIdentifier(getHopByHopIdentifier());
message.getAvps().addAvp(ORIGIN_HOST, metaData.getLocalPeer().getUri().getFQDN(), true, false, true);
message.getAvps().addAvp(ORIGIN_REALM, metaData.getLocalPeer().getRealmName(), true, false, true);
message.getAvps().addAvp(DISCONNECT_CAUSE, disconnectCause, true, false);
sendMessage(message);
}
public void sendDpaMessage(IMessage dpr, int resultCode, String errorMessage) throws TransportException, OverloadException {
logger.debug("Send DPA message");
IMessage message = parser.createEmptyMessage(dpr);
message.setRequest(false);
message.setHopByHopIdentifier(dpr.getHopByHopIdentifier());
message.setEndToEndIdentifier(dpr.getEndToEndIdentifier());
message.getAvps().addAvp(RESULT_CODE, resultCode, true, false, true);
message.getAvps().addAvp(ORIGIN_HOST, metaData.getLocalPeer().getUri().getFQDN(), true, false, true);
message.getAvps().addAvp(ORIGIN_REALM, metaData.getLocalPeer().getRealmName(), true, false, true);
if (errorMessage != null) {
message.getAvps().addAvp(ERROR_MESSAGE, errorMessage, false);
}
sendMessage(message);
}
public int processCerMessage(String key, IMessage message) {
return 0;
}
public boolean processCeaMessage(String key, IMessage message) {
boolean rc = true;
try {
Avp origHost = message.getAvps().getAvp(ORIGIN_HOST);
Avp origRealm = message.getAvps().getAvp(ORIGIN_REALM);
Avp vendorId = message.getAvps().getAvp(VENDOR_ID);
Avp prdName = message.getAvps().getAvp(PRODUCT_NAME);
Avp resCode = message.getAvps().getAvp(RESULT_CODE);
Avp frmId = message.getAvps().getAvp(FIRMWARE_REVISION);
if (origHost == null || origRealm == null || vendorId == null) {
logger.warn("Incorrect CEA message (missing mandatory AVPs)");
}
else {
if (realmName == null) {
realmName = origRealm.getDiameterIdentity();
}
if (vendorID == 0) {
vendorID = vendorId.getUnsigned32();
}
fillIPAddressTable(message);
if (productName == null && prdName != null) {
productName = prdName.getUTF8String();
}
if (resCode != null) {
int mrc = resCode.getInteger32();
if (mrc != ResultCode.SUCCESS) {
logger.debug("Result code value {}", mrc);
return false;
}
}
Set<ApplicationId> cai = getCommonApplicationIds(message);
if (cai.size() > 0) {
commonApplications.clear();
commonApplications.addAll(cai);
}
else {
logger.debug("CEA did not contained appId, therefore set local appids to common-appid field");
commonApplications.clear();
commonApplications.addAll(metaData.getLocalPeer().getCommonApplications());
}
if (firmWare == 0 && frmId != null) {
firmWare = frmId.getInteger32();
}
}
}
catch (Exception exc) {
logger.debug("Incorrect CEA message", exc);
rc = false;
}
return rc;
}
public boolean receiveMessage(IMessage message) {
logger.debug("Receiving message in client.");
boolean isProcessed = false;
// TODO: this might not be proper, since there might be no session
// present in case of stateless traffic
if (message.isRequest()) {
logger.debug("Message is a request");
// checks in server side make sure we are legit, now lets check if there is session present
String avpSessionId = message.getSessionId();
if (avpSessionId != null) {
// XXX: FT/HA // NetworkReqListener listener = slc.get(avpSessionId);
NetworkReqListener listener = (NetworkReqListener) sessionDataSource.getSessionListener(avpSessionId);
if (listener != null) {
router.registerRequestRouteInfo(message);
IMessage answer = (IMessage) listener.processRequest(message);
if (answer != null) {
try {
sendMessage(answer);
if(statistic.isEnabled()) {
statistic.getRecordByName(IStatisticRecord.Counters.AppGenResponse.name()).inc();
}
}
catch (Exception e) {
logger.warn("Unable to send immediate answer {}", answer);
}
}
if(statistic.isEnabled()) {
statistic.getRecordByName(IStatisticRecord.Counters.NetGenRequest.name()).inc();
}
isProcessed = true;
}
else {
if(statistic.isEnabled()) {
statistic.getRecordByName(IStatisticRecord.Counters.NetGenRejectedRequest.name()).inc();
}
}
}
}
else {
logger.debug("Message is an answer");
//TODO: check REALMs here?
IMessage request = peerRequests.remove(message.getHopByHopIdentifier());
if (request != null && !request.isTimeOut()) {
request.clearTimer();
request.setState(IMessage.STATE_ANSWERED);
Avp avpResCode = message.getAvps().getAvp(RESULT_CODE);
if (isRedirectAnswer(avpResCode, message)) {
message.setListener(request.getEventListener());
message = processRedirectAnswer(request,message);
//if return value is not null, there was some error, lets try to invoke listener if it exists...
isProcessed = message == null;
}
if (message != null) {
if (request.getEventListener() != null) {
request.getEventListener().receivedSuccessMessage(request, message);
}
else {
logger.debug("Unable to call answer listener for request {} because listener is not set", message);
if(statistic.isEnabled()) {
statistic.getRecordByName(IStatisticRecord.Counters.NetGenRejectedResponse.name()).inc();
}
}
isProcessed = true;
if(statistic.isEnabled()) {
statistic.getRecordByName(IStatisticRecord.Counters.NetGenResponse.name()).inc();
}
}
else {
if(statistic.isEnabled()) {
statistic.getRecordByName(IStatisticRecord.Counters.NetGenRejectedResponse.name()).inc();
}
}
}
else {
if(statistic.isEnabled()) {
statistic.getRecordByName(IStatisticRecord.Counters.NetGenRejectedResponse.name()).inc();
}
}
}
return isProcessed;
}
public int processDwrMessage(IMessage iMessage) {
return ResultCode.SUCCESS;
}
public int processDprMessage(IMessage iMessage) {
return ResultCode.SUCCESS;
}
protected void addAppId(ApplicationId appId, IMessage message) {
if (appId.getVendorId() == 0) {
if (appId.getAuthAppId() != 0) {
message.getAvps().addAvp(AUTH_APPLICATION_ID, appId.getAuthAppId(), true, false, true);
}
else if (appId.getAcctAppId() != 0) {
message.getAvps().addAvp(ACCT_APPLICATION_ID, appId.getAcctAppId(), true, false, true);
}
}
else {
// Avoid duplicates
boolean vendorIdPresent = false;
for(Avp avp : message.getAvps().getAvps(SUPPORTED_VENDOR_ID)) {
try {
if(avp.getUnsigned32() == appId.getVendorId()) {
vendorIdPresent = true;
break;
}
}
catch (Exception e) {
logger.debug("Failed to read Supported-Vendor-Id.", e);
}
}
if(!vendorIdPresent) {
message.getAvps().addAvp(SUPPORTED_VENDOR_ID, appId.getVendorId(), true, false, true);
}
AvpSet vendorApp = message.getAvps().addGroupedAvp(VENDOR_SPECIFIC_APPLICATION_ID, true, false);
vendorApp.addAvp(VENDOR_ID, appId.getVendorId(), true, false, true);
if (appId.getAuthAppId() != 0) {
vendorApp.addAvp(AUTH_APPLICATION_ID, appId.getAuthAppId(), true, false, true);
}
if (appId.getAcctAppId() != 0) {
vendorApp.addAvp(ACCT_APPLICATION_ID, appId.getAcctAppId(), true, false, true);
}
}
}
/* (non-Javadoc)
* @see org.jdiameter.client.api.fsm.IContext#removePeerStatistics()
*/
public void removeStatistics() {
removePeerStatistics();
}
/* (non-Javadoc)
* @see org.jdiameter.client.api.fsm.IContext#createPeerStatistics()
*/
public void createStatistics() {
createPeerStatistics();
}
}
} | Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpSet;
import org.jdiameter.api.Message;
import org.jdiameter.api.MetaData;
/**
* Small util class to separate AVP manipulation code from MessageParser class.
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class MessageUtility {
private MessageUtility() {
}
/**
* Used to set origin, previously done in MessageParser.
*
* @param m
* @param md
*/
public static void addOriginAvps(Message m, MetaData md) {
// FIXME: check for "userFqnAsUri" ?
AvpSet set = m.getAvps();
if (set.getAvp(Avp.ORIGIN_HOST) == null) {
m.getAvps().addAvp(Avp.ORIGIN_HOST, md.getLocalPeer().getUri().getFQDN(), true, false, true);
}
if (set.getAvp(Avp.ORIGIN_REALM) == null) {
m.getAvps().addAvp(Avp.ORIGIN_REALM, md.getLocalPeer().getRealmName(), true, false, true);
}
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl;
import org.jdiameter.api.InternalException;
/**
* Stack MBean interface.
*
* @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 {
/**
* Return string representation of stack instanceconfiguration
* @return string representation of stack instance configuration
*/
String configuration();
/**
* Return string representation of stack instance metadata
* @return string representation of stack instance metadata
*/
String metaData();
/**
* Reurn description (include state) of defined peer
* @param name peer host name
* @return description of defined peer
*/
String peerDescription(String name);
/**
* Return list of peer
* @return list of peer
*/
String peerList();
/**
* Return true if stack is started
* @return true if stack is started
*/
boolean isActive();
/**
* Run stop procedure
*/
void stop(int disconnectCause);
/**
* Run startd procedure
* @throws org.jdiameter.api.IllegalDiameterStateException
* @throws InternalException
*/
void start() throws org.jdiameter.api.IllegalDiameterStateException, 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.client.impl.fsm;
import org.jdiameter.api.Configuration;
import org.jdiameter.api.InternalException;
import org.jdiameter.client.api.fsm.IContext;
import org.jdiameter.client.api.fsm.IFsmFactory;
import org.jdiameter.client.api.fsm.IStateMachine;
import org.jdiameter.common.api.concurrent.IConcurrentFactory;
import org.jdiameter.common.api.statistic.IStatisticManager;
/**
*
* @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 implements IFsmFactory { // TODO: please redesign this code "duplicate"
protected IStatisticManager statisticFactory;
public FsmFactoryImpl(IStatisticManager statisticFactory) {
this.statisticFactory = statisticFactory;
}
public IStateMachine createInstanceFsm(IContext context, IConcurrentFactory concurrentFactory, Configuration config) throws InternalException {
return new org.jdiameter.client.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.client.impl.fsm;
import static org.jdiameter.client.impl.fsm.FsmState.DOWN;
import static org.jdiameter.client.impl.fsm.FsmState.REOPEN;
import static org.jdiameter.client.impl.helpers.Parameters.CeaTimeOut;
import static org.jdiameter.client.impl.helpers.Parameters.DpaTimeOut;
import static org.jdiameter.client.impl.helpers.Parameters.DwaTimeOut;
import static org.jdiameter.client.impl.helpers.Parameters.IacTimeOut;
import static org.jdiameter.client.impl.helpers.Parameters.PeerFSMThreadCount;
import static org.jdiameter.client.impl.helpers.Parameters.QueueSize;
import static org.jdiameter.client.impl.helpers.Parameters.RecTimeOut;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.jdiameter.api.Configuration;
import org.jdiameter.api.DisconnectCause;
import org.jdiameter.api.Message;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.PeerState;
import org.jdiameter.api.app.State;
import org.jdiameter.api.app.StateChangeListener;
import org.jdiameter.api.app.StateEvent;
import org.jdiameter.api.validation.AvpNotAllowedException;
import org.jdiameter.api.validation.Dictionary;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.fsm.EventTypes;
import org.jdiameter.client.api.fsm.FsmEvent;
import org.jdiameter.client.api.fsm.IContext;
import org.jdiameter.client.api.fsm.IStateMachine;
import org.jdiameter.client.impl.DictionarySingleton;
import org.jdiameter.common.api.concurrent.IConcurrentFactory;
import org.jdiameter.common.api.statistic.IStatistic;
import org.jdiameter.common.api.statistic.IStatisticManager;
import org.jdiameter.common.api.statistic.IStatisticRecord;
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 PeerFSMImpl implements IStateMachine {
private static final Logger logger = LoggerFactory.getLogger(PeerFSMImpl.class);
protected final Dictionary dictionary = DictionarySingleton.getDictionary();
protected ConcurrentLinkedQueue<StateChangeListener> listeners;
protected LinkedBlockingQueue<StateEvent> eventQueue;
protected FsmState state = FsmState.DOWN;
protected boolean watchdogSent;
protected long timer;
protected long CEA_TIMEOUT = 0, IAC_TIMEOUT = 0, REC_TIMEOUT = 0, DWA_TIMEOUT = 0, DPA_TIMEOUT = 0;
//PCB made FSM queue multi-threaded
private static int FSM_THREAD_COUNT = 3;
protected final StateEvent timeOutEvent = new FsmEvent(EventTypes.TIMEOUT_EVENT);
protected Random random = new Random();
protected IConcurrentFactory concurrentFactory;
protected IContext context;
protected State[] states;
protected int predefSize;
private Lock lock = new ReentrantLock();
protected IStatisticManager statisticFactory;
protected IStatistic queueStat;
protected IStatisticRecord timeSumm;
protected IStatisticRecord timeCount;
//PCB changed for multi-thread
protected boolean mustRun = false;
protected AtomicInteger numberOfThreadsRunning = new AtomicInteger(0);
public PeerFSMImpl(IContext aContext, IConcurrentFactory concurrentFactory, Configuration config, IStatisticManager statisticFactory) {
this.context = aContext;
this.statisticFactory = statisticFactory;
this.predefSize = config.getIntValue(QueueSize.ordinal(), (Integer) QueueSize.defValue());
//PCB added logging
logger.debug("Maximum FSM Queue size is [{}]", predefSize);
this.eventQueue = new LinkedBlockingQueue<StateEvent>(predefSize);
this.listeners = new ConcurrentLinkedQueue<StateChangeListener>();
loadTimeOuts(config);
this.concurrentFactory = concurrentFactory;
FSM_THREAD_COUNT = config.getIntValue(PeerFSMThreadCount.ordinal(), (Integer) PeerFSMThreadCount.defValue());
runQueueProcessing();
}
public IStatistic getStatistic() {
//
return queueStat;
}
public void removeStateChangeNotification(StateChangeListener stateChangeListener) {
listeners.remove(stateChangeListener);
}
private void runQueueProcessing() {
try {
// PCB - changed way it decides if queue processing must happen in order to allow for multithreaded FSM
lock.lock();
if (numberOfThreadsRunning.get() > 0) {
// runQueueProcessing has been called
return;
}
eventQueue.clear();
mustRun = true;
IStatisticRecord queueSize = statisticFactory.newCounterRecord(IStatisticRecord.Counters.QueueSize, new IStatisticRecord.IntegerValueHolder() {
public int getValueAsInt() {
return eventQueue.size();
}
public String getValueAsString() {
return String.valueOf(getValueAsInt());
}
});
this.timeSumm = statisticFactory.newCounterRecord("TimeSumm", "TimeSumm");
this.timeCount = statisticFactory.newCounterRecord("TimeCount", "TimeCount");
final IStatisticRecord messagePrcAverageTime = statisticFactory.newCounterRecord(IStatisticRecord.Counters.MessageProcessingTime,
new IStatisticRecord.DoubleValueHolder() {
public double getValueAsDouble() {
if(queueStat == null) {
return 0;
}
IStatisticRecord mpta = queueStat.getRecordByName(IStatisticRecord.Counters.MessageProcessingTime.name());
org.jdiameter.api.StatisticRecord[] children = mpta.getChilds();
if (children.length == 2 && children[1].getValueAsLong() != 0) {
long count = children[1].getValueAsLong();
return ((float) children[0].getValueAsLong()) / ((float) (count != 0 ? count : 1));
}
else {
return 0;
}
}
public String getValueAsString() {
return String.valueOf(getValueAsDouble());
}
}, timeSumm, timeCount);
logger.debug("Initializing QueueStat @ Thread[{}]", Thread.currentThread().getName());
queueStat = statisticFactory.newStatistic(context.getPeerDescription(), IStatistic.Groups.PeerFSM, queueSize, messagePrcAverageTime);
logger.debug("Finished Initializing QueueStat @ Thread[{}]", Thread.currentThread().getName());
Runnable fsmQueueProcessor = new Runnable() {
public void run() {
int runningNow = numberOfThreadsRunning.incrementAndGet();
logger.debug("Starting ... [{}] FSM threads are running", runningNow);
//PCB changed for multi-thread
while (mustRun) {
StateEvent event;
try {
event = eventQueue.poll(100, TimeUnit.MILLISECONDS);
if(logger.isDebugEnabled() && event != null) {
logger.debug("Got Event [{}] from Queue", event);
}
}
catch (InterruptedException e) {
logger.debug("Peer FSM stopped", e);
break;
}
//FIXME: baranowb: why this lock is here?
// PCB removed lock
// lock.lock();
try {
if (event != null) {
if (event instanceof FsmEvent && queueStat != null && queueStat.isEnabled()) {
timeSumm.inc(System.currentTimeMillis() - ((FsmEvent) event).getCreatedTime());
timeCount.inc();
}
logger.debug("Process event [{}]. Peer State is [{}]", event, state);
getStates()[state.ordinal()].processEvent(event);
}
if (timer != 0 && timer < System.currentTimeMillis()) {
timer = 0;
if(state != DOWN) { //without this check this event is fired in DOWN state.... it should not be.
logger.debug("Sending timeout event");
handleEvent(timeOutEvent); //FIXME: check why timer is not killed?
}
}
}
catch (Exception e) {
logger.debug("Error during processing FSM event", e);
}
finally {
// PCB removed lock
// lock.unlock();
}
}
//PCB added logging
logger.debug("FSM Thread {} is exiting", Thread.currentThread().getName());
//this happens when peer FSM is down, lets remove stat
statisticFactory.removeStatistic(queueStat);
logger.debug("Setting QueueStat to null @ Thread [{}]", Thread.currentThread().getName());
queueStat = null;
logger.debug("Done Setting QueueStat to null @ Thread [{}]", Thread.currentThread().getName());
int runningNowAfterStop = numberOfThreadsRunning.decrementAndGet();
logger.debug("Stopping ... [{}] FSM threads are running", runningNowAfterStop);
}
};
//PCB added FSM multithread
for (int i = 1; i <= FSM_THREAD_COUNT; i++) {
logger.debug("Starting FSM Thread {} of {}", i, FSM_THREAD_COUNT);
Thread executor = concurrentFactory.getThread("FSM-" + context.getPeerDescription() + "_" + i, fsmQueueProcessor);
executor.start();
}
}
finally {
lock.unlock();
}
}
public double getQueueInfo() {
return eventQueue.size() * 1.0 / predefSize;
}
protected void loadTimeOuts(Configuration config) {
CEA_TIMEOUT = config.getLongValue(CeaTimeOut.ordinal(), (Long) CeaTimeOut.defValue());
IAC_TIMEOUT = config.getLongValue(IacTimeOut.ordinal(), (Long) IacTimeOut.defValue());
DWA_TIMEOUT = config.getLongValue(DwaTimeOut.ordinal(), (Long) DwaTimeOut.defValue());
DPA_TIMEOUT = config.getLongValue(DpaTimeOut.ordinal(), (Long) DpaTimeOut.defValue());
REC_TIMEOUT = config.getLongValue(RecTimeOut.ordinal(), (Long) RecTimeOut.defValue());
}
public void addStateChangeNotification(StateChangeListener stateChangeListener) {
if (!listeners.contains(stateChangeListener)) {
listeners.add(stateChangeListener);
}
}
public void remStateChangeNotification(StateChangeListener stateChangeListener) {
listeners.remove(stateChangeListener);
}
protected void switchToNextState(FsmState newState) {
// Fix for Issue #3026 (http://code.google.com/p/mobicents/issues/detail?id=3026)
// notify only when it's a new public state
if (newState.getPublicState() != state.getPublicState()) {
for (StateChangeListener l : listeners) {
l.stateChanged(state.getPublicState(), newState.getPublicState());
}
}
getStates()[state.ordinal()].exitAction();
if(logger.isDebugEnabled()) {
logger.debug("{} FSM switch state: {} -> {}", new Object[] {context.getPeerDescription(), state, newState});
}
state = newState;
getStates()[state.ordinal()].entryAction();
}
public boolean handleEvent(StateEvent event) throws InternalError, OverloadException {
//if (state.getPublicState() == PeerState.DOWN && event.encodeType(EventTypes.class) == EventTypes.START_EVENT) {
if (logger.isDebugEnabled()) {
logger.debug("Handling event with type [{}]", event.getType());
}
//PCB added FSM multithread
if (numberOfThreadsRunning.get() == 0) {
logger.debug("No FSM threads are running so calling runQueueProcessing()");
runQueueProcessing();
}
if (event.getData() != null && dictionary!= null && dictionary.isEnabled()) {
boolean incoming = event.getType() == EventTypes.RECEIVE_MSG_EVENT;
if(incoming) {
logger.debug("Performing validation to INCOMING message since validator is ENABLED.");
// outgoing are done elsewhere: see BaseSessionImpl
try{
dictionary.validate((Message) event.getData(), incoming);
}
catch(AvpNotAllowedException e) {
logger.error("Failed to validate incoming message.", e);
return false;
}
}
}
else {
logger.debug("Not performing validation to message since validator is DISABLED.");
}
boolean rc = false;
try {
if(logger.isDebugEnabled()) {
logger.debug("Placing event [{}] into linked blocking queue with remaining capacity: [{}].", event, eventQueue.remainingCapacity());
//PCB added logging
//int queueSize = eventQueue.size();
//if (System.currentTimeMillis() - lastLogged > 1000) {
// lastLogged = System.currentTimeMillis();
// if (queueSize >= 5) {
// logger.debug("Diameter Event Queue size is [{}]", queueSize);
// }
//}
}
rc = eventQueue.offer(event, IAC_TIMEOUT, TimeUnit.MILLISECONDS);
}
catch (InterruptedException e) {
logger.debug("Can not put event '" + event.toString() + "' to FSM " + this.toString(), e);
throw new InternalError("Can not put event '" + event.toString() + "' to FSM " + this.toString());
}
if (!rc) {
throw new OverloadException("FSM overloaded");
}
return true;
}
//PCB added logging
//private static long lastLogged;
protected void setInActiveTimer() {
timer = IAC_TIMEOUT - 2 * 1000 + random.nextInt(5) * 1000 + System.currentTimeMillis();
}
public String toString() {
return "PeerFSM{" + "context=" + context + ", state=" + state + '}';
}
public <E> E getState(Class<E> a) {
if (a == PeerState.class) {
return (E) state.getPublicState();
}
else {
return null;
}
}
protected abstract class MyState implements org.jdiameter.api.app.State {
public void entryAction() {
}
public void exitAction() {
}
protected void doEndConnection() {
if (context.isRestoreConnection()) {
timer = REC_TIMEOUT + System.currentTimeMillis();
switchToNextState(REOPEN);
}
else {
switchToNextState(DOWN);
}
}
protected void doDisconnect() {
try {
context.disconnect();
}
catch (Throwable e) {
}
}
protected void setTimer(long value) {
timer = value + System.currentTimeMillis();
}
protected String key(StateEvent event) {
return ((FsmEvent) event).getKey();
}
protected IMessage message(StateEvent event) {
return ((FsmEvent) event).getMessage();
}
protected EventTypes type(StateEvent event) {
return (EventTypes) event.getType();
}
protected void clearTimer() {
timer = 0;
}
}
protected org.jdiameter.api.app.State[] getStates() {
if (states == null) {
states = new org.jdiameter.api.app.State[] { // todo merge and redesign with server fsm
new MyState() // OKEY
{
public void entryAction() {
setInActiveTimer();
watchdogSent = false;
}
public boolean processEvent(StateEvent event) {
switch (event.encodeType(EventTypes.class)) {
case DISCONNECT_EVENT:
timer = REC_TIMEOUT + System.currentTimeMillis();
switchToNextState(FsmState.REOPEN);
break;
case TIMEOUT_EVENT:
try {
context.sendDwrMessage();
setTimer(DWA_TIMEOUT);
if (watchdogSent) {
switchToNextState(FsmState.SUSPECT);
}
else {
watchdogSent = true;
}
}
catch (Throwable e) {
logger.debug("Can not send DWR", e);
doDisconnect();
setTimer(REC_TIMEOUT);
switchToNextState(FsmState.REOPEN);
}
break;
case STOP_EVENT:
try {
if(event.getData() == null) {
context.sendDprMessage(DisconnectCause.REBOOTING);
}
else {
Integer disconnectCause = (Integer) event.getData();
context.sendDprMessage(disconnectCause);
}
setTimer(DPA_TIMEOUT);
switchToNextState(FsmState.STOPPING);
}
catch (Throwable e) {
logger.debug("Can not send DPR", e);
doDisconnect();
switchToNextState(FsmState.DOWN);
}
break;
case RECEIVE_MSG_EVENT:
setInActiveTimer();
context.receiveMessage(message(event));
break;
case DPR_EVENT:
try {
int code = context.processDprMessage(message(event));
context.sendDpaMessage(message(event), code, null);
}
catch (Throwable e) {
logger.debug("Can not send DPA", e);
}
doDisconnect();
switchToNextState(FsmState.DOWN);
break;
case DWR_EVENT:
setInActiveTimer();
try {
int code = context.processDwrMessage(message(event));
context.sendDwaMessage(message(event), code, null);
}
catch (Throwable e) {
logger.debug("Can not send DWA", e);
doDisconnect();
switchToNextState(FsmState.DOWN);
}
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();
setTimer(REC_TIMEOUT);
switchToNextState(FsmState.REOPEN);
}
break;
default:
logger.debug("Unknown event type: {} in state {}", event.encodeType(EventTypes.class), state);
return false;
}
return true;
}
},
new MyState() // SUSPECT
{
public boolean processEvent(StateEvent event) {
switch (event.encodeType(EventTypes.class)) {
case DISCONNECT_EVENT:
setTimer(REC_TIMEOUT);
switchToNextState(FsmState.REOPEN);
break;
case TIMEOUT_EVENT:
doDisconnect();
setTimer(REC_TIMEOUT);
switchToNextState(FsmState.REOPEN);
break;
case STOP_EVENT:
try {
if(event.getData() == null) {
context.sendDprMessage(DisconnectCause.REBOOTING);
}
else {
Integer disconnectCause = (Integer) event.getData();
context.sendDprMessage(disconnectCause);
}
setInActiveTimer();
switchToNextState(FsmState.STOPPING);
}
catch (Throwable e) {
logger.debug("Can not send DPR", e);
doDisconnect();
switchToNextState(FsmState.DOWN);
}
break;
case DPR_EVENT:
try {
int code = context.processDprMessage(message(event));
context.sendDpaMessage(message(event), code, null);
}
catch (Throwable e) {
logger.debug("Can not send DPA", e);
}
doDisconnect();
switchToNextState(FsmState.DOWN);
break;
case DWA_EVENT:
switchToNextState(FsmState.OKAY);
break;
case DWR_EVENT:
try {
int code = context.processDwrMessage(message(event));
context.sendDwaMessage(message(event), code, null);
switchToNextState(FsmState.OKAY);
}
catch (Throwable e) {
logger.debug("Can not send DWA", e);
doDisconnect();
switchToNextState(FsmState.DOWN);
}
break;
case RECEIVE_MSG_EVENT:
context.receiveMessage(message(event));
switchToNextState(FsmState.OKAY);
break;
case SEND_MSG_EVENT:
throw new RuntimeException("Connection is down");
default:
logger.debug("Unknown event type: {} in state {}", event.encodeType(EventTypes.class), state);
return false;
}
return true;
}
},
new MyState() // DOWN
{
public void entryAction() {
clearTimer();
//PCB changed multithread FSM
logger.debug("Setting mustRun to false @ Thread [{}]", Thread.currentThread().getName());
mustRun = false;
logger.debug("Finished Setting mustRun to false @ Thread [{}]", Thread.currentThread().getName());
context.removeStatistics();
}
public boolean processEvent(StateEvent event) {
switch (event.encodeType(EventTypes.class)) {
case START_EVENT:
try {
context.createStatistics();
context.connect();
context.sendCerMessage();
setTimer(CEA_TIMEOUT);
switchToNextState(FsmState.INITIAL);
}
catch (Throwable e) {
logger.debug("Connect error", e);
setTimer(REC_TIMEOUT);
switchToNextState(FsmState.REOPEN);
}
break;
case SEND_MSG_EVENT:
throw new RuntimeException("Connection is down");
case STOP_EVENT:
case DISCONNECT_EVENT:
break;
default:
logger.debug("Unknown event type: {} in state {}", event.encodeType(EventTypes.class), state);
return false;
}
return true;
}
},
new MyState() // REOPEN
{
public boolean processEvent(StateEvent event) {
switch (event.encodeType(EventTypes.class)) {
case CONNECT_EVENT:
try {
context.sendCerMessage();
setTimer(CEA_TIMEOUT);
switchToNextState(FsmState.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("Timeout processed. Can not connect to {}", context.getPeerDescription());
setTimer(REC_TIMEOUT);
}
break;
case STOP_EVENT:
clearTimer();
doDisconnect();
switchToNextState(FsmState.DOWN);
break;
case DISCONNECT_EVENT:
break;
case SEND_MSG_EVENT:
throw new IllegalStateException("Connection is down");
default:
logger.debug("Unknown event type: {} in state {}", event.encodeType(EventTypes.class), state);
return false;
}
return true;
}
},
new MyState() // INITIAL
{
public void entryAction() {
setTimer(CEA_TIMEOUT);
}
public boolean processEvent(StateEvent event) {
switch (event.encodeType(EventTypes.class)) {
case DISCONNECT_EVENT:
setTimer(REC_TIMEOUT);
switchToNextState(FsmState.REOPEN);
break;
case TIMEOUT_EVENT:
doDisconnect();
setTimer(REC_TIMEOUT);
switchToNextState(FsmState.REOPEN);
break;
case STOP_EVENT:
clearTimer();
doDisconnect();
switchToNextState(FsmState.DOWN);
break;
case CEA_EVENT:
clearTimer();
if (context.processCeaMessage(((FsmEvent) event).getKey(), ((FsmEvent) event).getMessage())) {
switchToNextState(FsmState.OKAY);
}
else {
doDisconnect();
setTimer(REC_TIMEOUT);
switchToNextState(FsmState.REOPEN);
}
break;
case SEND_MSG_EVENT:
throw new RuntimeException("Connection is down");
default:
logger.debug("Unknown event type: {} in state {}", event.encodeType(EventTypes.class), state);
return false;
}
return true;
}
},
new MyState() // STOPPING
{
public boolean processEvent(StateEvent event) {
switch (event.encodeType(EventTypes.class)) {
case TIMEOUT_EVENT:
case DPA_EVENT:
doDisconnect();
switchToNextState(FsmState.DOWN);
break;
case RECEIVE_MSG_EVENT:
context.receiveMessage(message(event));
break;
case SEND_MSG_EVENT:
throw new RuntimeException("Stack now is stopping");
case STOP_EVENT:
case DISCONNECT_EVENT:
doDisconnect();
break;
default:
logger.debug("Unknown event type: {} in state {}", event.encodeType(EventTypes.class), 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.client.impl.fsm;
import org.jdiameter.api.PeerState;
/**
*
* @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 FsmState {
protected static int index;
public static FsmState OKAY = new FsmState("OKAY", PeerState.OKAY);
public static FsmState SUSPECT = new FsmState("SUSPECT", PeerState.SUSPECT);
public static FsmState DOWN = new FsmState("DOWN", PeerState.DOWN);
public static FsmState REOPEN = new FsmState("REOPEN", PeerState.REOPEN);
public static FsmState INITIAL = new FsmState("INITIAL", PeerState.INITIAL);
public static FsmState STOPPING = new FsmState("STOPPING", PeerState.DOWN, true);
private String name;
private int ordinal;
private Enum publicState;
private boolean isInternal;
public FsmState(String name, Enum publicState) {
this.name = name;
this.publicState = publicState;
this.ordinal = index++;
}
public FsmState(String name, Enum publicState, boolean isInternal) {
this.name = name;
this.publicState = publicState;
this.isInternal = isInternal;
this.ordinal = index++;
}
public int ordinal() {
return ordinal;
}
public String name() {
return name;
}
public Enum getPublicState() {
return publicState;
}
public boolean isInternal() {
return isInternal;
}
public String toString() {
return name;
}
} | 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.client.impl.transport.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.PayloadData;
import org.mobicents.protocols.sctp.AssociationImpl;
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 SCTPTransportClient {
private static final int CONNECT_DELAY = 5000;
private static final int DELAY = 50;
private ManagementImpl management = null;
private AssociationImpl clientAssociation = null;
private SCTPClientConnection parentConnection;
private String clientAssociationName;
protected InetSocketAddress destAddress;
protected InetSocketAddress origAddress;
private int payloadProtocolId = 0;
private int streamNumber = 0;
private static final Logger logger = LoggerFactory.getLogger(SCTPTransportClient.class);
public SCTPTransportClient() {
}
/**
* Default constructor
*
* @param concurrentFactory
* factory for create threads
* @param parenConnection
* connection created this transport
*/
SCTPTransportClient(SCTPClientConnection parenConnection) {
this.parentConnection = parenConnection;
}
public void initialize() throws IOException, NotInitializedException {
logger.debug("Initializing SCTPTransportClient. Origin address is [{}] and destination address is [{}]", origAddress,
destAddress);
if (destAddress == null) {
throw new NotInitializedException("Destination address is not set");
}
logger.debug("Initializing SCTP client");
clientAssociationName = origAddress.getHostName() + "." + origAddress.getPort();
try {
if (this.management == null) {
this.management = new ManagementImpl(clientAssociationName);
this.management.setConnectDelay(1);// Try connecting every 10 secs
this.management.setSingleThread(true);
this.management.start();
logger.debug("Management initialized.");
}
else {
logger.debug("Management already initialized.");
}
if (this.clientAssociation == null) {
logger.debug("Creating CLIENT ASSOCIATION '{}'. Origin Address [{}] <=> Dest Address [{}]", new Object[] {
clientAssociationName, origAddress, destAddress });
this.clientAssociation = this.management.addAssociation(origAddress.getAddress().getHostAddress(),
origAddress.getPort(), destAddress.getAddress().getHostAddress(), destAddress.getPort(), clientAssociationName,
IpChannelType.SCTP, null);
}
else {
logger.debug("CLIENT ASSOCIATION '{}'. Origin Address [{}:{}] <=> Dest Address [{}:{}] already present. Re-using it.",
new Object[] { clientAssociation.getName(), clientAssociation.getHostAddress(), clientAssociation.getHostPort(),
clientAssociation.getPeerAddress(), clientAssociation.getPeerPort() });
}
}
catch (Exception e) {
logger.error("Failed to initialize client ", e);
}
}
public SCTPClientConnection getParent() {
return parentConnection;
}
public void start() throws NotInitializedException, IOException {
// for client
logger.debug("Starting SCTP client");
try {
this.clientAssociation.setAssociationListener(new ClientAssociationListener());
this.management.startAssociation(clientAssociationName);
}
catch (Exception e) {
logger.error("Failed to start client ", e);
}
if (getParent() == null) {
throw new NotInitializedException("No parent connection is set");
}
logger.debug("Successfuly initialized SCTP Client Host [{}:{}] Peer [{}:{}]", new Object[] { clientAssociation.getHostAddress(),
clientAssociation.getHostPort(), clientAssociation.getPeerAddress(), clientAssociation.getPeerPort() });
logger.debug("Client Association Status: Started[{}] Connected[{}] Up[{}] ", new Object[]{clientAssociation.isStarted(), clientAssociation.isConnected(), clientAssociation.isUp()});
logger.trace("Client Association [{}]", clientAssociation);
defer();
}
private void defer() throws IOException {
final long endTStamp = System.currentTimeMillis() + CONNECT_DELAY;
while(clientAssociation.isStarted() && !clientAssociation.isConnected() && !clientAssociation.isUp()) {
try {
Thread.sleep(DELAY);
}
catch (InterruptedException e) {
// clear flag and proceed
Thread.interrupted();
throw new IOException("Failed to establish SCTP connection, thread was interrupted waiting for connection.");
}
if(endTStamp < System.currentTimeMillis()){
throw new IOException("Failed to establish SCTP connection!");
}
}
logger.debug("Client Association Status: Started[{}] Connected[{}] Up[{}] ", new Object[]{clientAssociation.isStarted(), clientAssociation.isConnected(), clientAssociation.isUp()});
logger.trace("Client Association [{}]", clientAssociation);
}
private class ClientAssociationListener implements AssociationListener {
private final Logger logger = LoggerFactory.getLogger(ClientAssociationListener.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();
}
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) {
byte[] data = new byte[payloadData.getDataLength()];
System.arraycopy(payloadData.getData(), 0, data, 0, payloadData.getDataLength());
logger.debug("SCTP Client received data 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 ?
}
}
public void stop() throws Exception {
// Stop the SCTP
this.management.stopAssociation(clientAssociationName);
}
public void release() throws Exception {
this.stop();
this.management.removeAssociation(clientAssociationName);
this.management.stop();
this.clientAssociation = 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.clientAssociation.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() {
return clientAssociation != null && this.clientAssociation.isConnected();
}
}
| Java |
/*
* TeleStax, Open Source Cloud Communications
* Copyright 2013, TeleStax and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.transport.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.jdiameter.common.api.concurrent.IConcurrentFactory;
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 SCTPClientConnection implements IConnection {
private static Logger logger = LoggerFactory.getLogger(SCTPClientConnection.class);
private final long createdTime;
private SCTPTransportClient client;
// 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;
protected SCTPClientConnection(IMessageParser parser) {
this.createdTime = System.currentTimeMillis();
this.parser = parser;
client = new SCTPTransportClient(this);
}
public SCTPClientConnection(Configuration config, IConcurrentFactory concurrentFactory, InetAddress remoteAddress,
int remotePort, InetAddress localAddress, int localPort, IMessageParser parser, String ref) {
this(parser);
logger.debug("SCTP Client constructor. Remote [{}:{}] Local [{}:{}]", new Object[] { remoteAddress, remotePort,
localAddress, localPort });
client.setDestAddress(new InetSocketAddress(remoteAddress, remotePort));
client.setOrigAddress(new InetSocketAddress(localAddress, localPort));
}
public SCTPClientConnection(Configuration config, IConcurrentFactory concurrentFactory, InetAddress remoteAddress,
int remotePort, InetAddress localAddress, int localPort, IConnectionListener listener, IMessageParser parser, String ref) {
this(parser);
logger.debug("SCTP Client constructor (with ref). Remote [{}:{}] Local [{}:{}]", new Object[] { remoteAddress, remotePort,
localAddress, localPort });
client.setDestAddress(new InetSocketAddress(remoteAddress, remotePort));
client.setOrigAddress(new InetSocketAddress(localAddress, localPort));
listeners.add(listener);
}
public long getCreatedTime() {
return createdTime;
}
public void connect() throws TransportException {
try {
getClient().initialize();
getClient().start();
}
catch (IOException e) {
throw new TransportException("Cannot init transport: ", TransportError.NetWorkError, e);
}
catch (Exception e) {
throw new TransportException("Cannot init transport: ", TransportError.Internal, e);
}
}
public void disconnect() throws InternalError {
try {
if (getClient() != null) {
getClient().stop();
}
}
catch (Exception e) {
throw new InternalError("Error while stopping transport: " + e.getMessage());
}
}
public void release() throws IOException {
try {
if (getClient() != null) {
getClient().release();
}
}
catch (Exception e) {
throw new IOException(e.getMessage());
}
finally {
parser = null;
buffer.clear();
remAllConnectionListener();
}
}
public void sendMessage(IMessage message) throws TransportException, OverloadException {
try {
if (getClient() != null) {
getClient().sendMessage(parser.encodeMessage(message));
}
}
catch (Exception e) {
throw new TransportException("Cannot send message: ", TransportError.FailedSendMessage, e);
}
}
protected SCTPTransportClient getClient() {
return client;
}
public boolean isNetworkInitiated() {
return false;
}
public boolean isConnected() {
return getClient() != null && getClient().isConnected();
}
public InetAddress getRemoteAddress() {
return getClient().getDestAddress().getAddress();
}
public int getRemotePort() {
return getClient().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 onEvent(Event event) throws AvpDataException {
lock.lock();
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 |
/*
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.transport.tls;
import static org.jdiameter.client.impl.helpers.Parameters.CipherSuites;
import static org.jdiameter.client.impl.helpers.Parameters.SDEnableSessionCreation;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousCloseException;
import java.nio.channels.ClosedByInterruptException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.net.ssl.HandshakeCompletedEvent;
import javax.net.ssl.HandshakeCompletedListener;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import org.jdiameter.api.Avp;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.AvpSet;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.io.NotInitializedException;
import org.jdiameter.client.api.parser.IMessageParser;
import org.jdiameter.client.api.parser.ParseException;
import org.jdiameter.common.api.concurrent.IConcurrentFactory;
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 TLSTransportClient {
// NOTE: SSL Does not provide channels, need to do plain old sync R/W :/
// So SSLSocket.getChannel() returns NULL!
private static final Logger logger = LoggerFactory.getLogger(TLSTransportClient.class);
private TLSClientConnection parentConnection;
private IConcurrentFactory concurrentFactory;
private boolean stop = false;
// flag to indicate that initial shake did happen
private boolean shaken;
// flag indicating that SSL handshake is going on, while this is set to true, no messages can be exchanged.
private boolean shaking;
private Thread readThread;
private InetSocketAddress destAddress;
private InetSocketAddress origAddress;
private String socketDescription = null;
// sync streams to get data.
private InputStream inputStream;
private OutputStream outputStream;
//private SSLSocket sslSocket;
private Socket plainSocket;
public static final int DEFAULT_BUFFER_SIZE = 4096;
public static final int DEFAULT_STORAGE_SIZE = 4096;
private int bufferSize = DEFAULT_BUFFER_SIZE;
private ByteBuffer buffer = ByteBuffer.allocate(this.bufferSize);
private int storageSize = DEFAULT_STORAGE_SIZE;
private ByteBuffer storage = ByteBuffer.allocate(storageSize);
private Lock lock = new ReentrantLock();
private IMessageParser parser;
private final DiameterSSLHandshakeListener handshakeListener = new DiameterSSLHandshakeListener();
private final ReadTask readTash = new ReadTask();
//tell weather we are in a client mode
private boolean client;
private boolean receivedInband;
/**
* Default constructor
*
* @param parenConnection
* connection created this transport
*/
public TLSTransportClient(TLSClientConnection parenConnection, IConcurrentFactory concurrentFactory, IMessageParser parser) {
this.parentConnection = parenConnection;
this.concurrentFactory = concurrentFactory;
this.parser = parser;
}
public void initialize() throws IOException, NotInitializedException {
if (destAddress == null) {
throw new NotInitializedException("Destination address is not set");
}
this.client = true;
// SSLSocketFactory cltFct = parentConnection.getSSLFactory();
// this.sslSocket = (SSLSocket) cltFct.createSocket();
//
// this.sslSocket.setEnableSessionCreation(parentConnection.getSSLConfig().getBooleanValue(SDEnableSessionCreation.ordinal(), true));
// this.sslSocket.setUseClientMode(true);
// if (parentConnection.getSSLConfig().getStringValue(CipherSuites.ordinal(), null) != null) {
// this.sslSocket.setEnabledCipherSuites(parentConnection.getSSLConfig().getStringValue(CipherSuites.ordinal(), null).split(","));
// }
//
// if (this.origAddress != null) {
// this.sslSocket.bind(this.origAddress);
// }
// this.sslSocket.connect(this.destAddress);
//
// // now lets get streams.
// this.sslInputStream = this.sslSocket.getInputStream();
// this.sslOutputStream = this.sslSocket.getOutputStream();
this.plainSocket = new Socket();
if (this.origAddress != null) {
this.plainSocket.bind(this.origAddress);
}
this.plainSocket.connect(this.destAddress);
this.inputStream = this.plainSocket.getInputStream();
this.outputStream = this.plainSocket.getOutputStream();
// now, we need to notify parent, this will START CER/CEA exchange
// on CEA 2xxx we can enable TLS
parentConnection.onConnected();
}
public void initialize(Socket socket) throws IOException, NotInitializedException {
logger.debug("Initialising TLSTransportClient for a socket on [{}]", socket);
this.client = false;
this.plainSocket = socket;
this.socketDescription = socket.toString();
this.destAddress = new InetSocketAddress(socket.getInetAddress(), socket.getPort());
this.inputStream = this.plainSocket.getInputStream();
this.outputStream = this.plainSocket.getOutputStream();
}
public void start() throws NotInitializedException {
// for client
if (this.socketDescription == null) {
this.socketDescription = this.plainSocket.toString();
}
logger.debug("Starting transport. Socket is {}", socketDescription);
if (!this.plainSocket.isConnected()) {
throw new NotInitializedException("Socket is not connected");
}
if (getParent() == null) {
throw new NotInitializedException("No parent connection is set is set");
}
if (this.readThread == null || !this.readThread.isAlive()) {
this.readThread = this.concurrentFactory.getThread("TLSReader", this.readTash);
}
if (!this.readThread.isAlive()) {
this.readThread.setDaemon(true);
this.readThread.start();
}
}
// ---------------- getters & setters ---------------------
public TLSClientConnection getParent() {
return parentConnection;
}
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;
}
// ---------------- helper methods ---------------------
void sendMessage(IMessage message) throws IOException, AvpDataException, NotInitializedException, ParseException {
if (!isConnected()) {
throw new IOException("Failed to send message over [" + socketDescription + "]");
}
//switch to wait for SSL handshake to workout.
if(!isExchangeAllowed()){
//TODO: do more?
return;
}
doTLSPreSendProcessing(message);
final ByteBuffer messageBuffer = this.parser.encodeMessage(message);
if (logger.isDebugEnabled()) {
logger.debug("About to send a byte buffer of size [{}] over the TLS socket [{}]", messageBuffer.array().length, socketDescription);
}
lock.lock();
try {
this.outputStream.write(messageBuffer.array(), messageBuffer.position(), messageBuffer.limit());
doTLSPostSendProcessing(message);
} catch (Exception e) {
logger.debug("Unable to send message", e);
throw new IOException("Error while sending message: " + e);
}
finally {
lock.unlock();
}
if (logger.isDebugEnabled()) {
logger.debug("Sent a byte buffer of size [{}] over the TLS nio socket [{}]", messageBuffer.array().length, socketDescription);
}
}
boolean isConnected() {
return this.plainSocket != null && this.plainSocket.isConnected();
}
void stop() throws Exception {
logger.debug("Stopping transport. Socket is [{}]", socketDescription);
stop = true;
if (plainSocket != null && !plainSocket.isClosed()) {
plainSocket.close();
}
if (this.readThread != null) {
this.readThread.join(100);
}
clearBuffer();
logger.debug("Transport is stopped. Socket is [{}]", socketDescription);
}
public void release() throws Exception {
stop();
destAddress = null;
}
void append(byte[] data) {
if (storage.position() + data.length >= storage.capacity()) {
ByteBuffer tmp = ByteBuffer.allocate(storage.limit() + data.length * 2);
byte[] tmpData = new byte[storage.position()];
storage.flip();
storage.get(tmpData);
tmp.put(tmpData);
storage = tmp;
logger.warn("Increase storage size. Current size is {}", storage.array().length);
}
try {
storage.put(data);
}
catch (BufferOverflowException boe) {
logger.error("Buffer overflow occured", boe);
}
boolean messageReseived;
do {
messageReseived = seekMessage(storage);
} while (messageReseived);
}
private boolean isExchangeAllowed(){
this.lock.lock();
try{
return !this.shaking;
}finally {
this.lock.unlock();
}
}
private boolean isSuccess(IMessage message) throws AvpDataException {
Avp resultAvp = message.getResultCode();
if (resultAvp == null) {
resultAvp = message.getAvps().getAvp(Avp.EXPERIMENTAL_RESULT);
if (resultAvp == null) {
// bad message, ignore
if (logger.isDebugEnabled()) {
logger.debug("Discarding message since SSL handshake has not been performed on [{}], dropped message [{}]. No result type avp.", socketDescription, message);
}
// TODO: anything else?
return false;
}
resultAvp = resultAvp.getGrouped().getAvp(Avp.EXPERIMENTAL_RESULT_CODE);
if (resultAvp == null) {
// bad message, ignore
if (logger.isDebugEnabled()) {
logger.debug("Discarding message since SSL handshake has not been performed on [{}], dropped message [{}]. No result avp.", socketDescription, message);
}
}
}
long resultCode = resultAvp.getUnsigned32();
return resultCode >= 2000 && resultCode < 3000;
}
private boolean seekMessage(ByteBuffer localStorage) {
if (storage.position() == 0) {
return false;
}
storage.flip();
int tmp = localStorage.getInt();
localStorage.position(0);
byte vers = (byte) (tmp >> 24);
if (vers != 1) {
return false;
}
int dataLength = (tmp & 0xFFFFFF);
if (localStorage.limit() < dataLength) {
localStorage.position(localStorage.limit());
localStorage.limit(localStorage.capacity());
return false;
}
byte[] data = new byte[dataLength];
localStorage.get(data);
localStorage.position(dataLength);
localStorage.compact();
ByteBuffer messageBuffer = ByteBuffer.wrap(data);
try {
if (logger.isDebugEnabled()) {
logger.debug("Received message of size [{}]", data.length);
}
IMessage message = this.parser.createMessage(messageBuffer);
// check if
if(isExchangeAllowed()){
doTLSPreReceiveProcessing(message);
getParent().onMessageReceived(message);
}
}
catch (Exception e) {
logger.debug("Garbage was received. Discarding.");
storage.clear();
// not a best way.
getParent().onAvpDataException(new AvpDataException(e));
}
return true;
}
/**
* @param message
* @throws AvpDataException
* @throws NotInitializedException
*/
private void doTLSPreReceiveProcessing(IMessage message) throws AvpDataException, NotInitializedException {
if(this.shaken){
return;
}
if (this.client) {
// if(CEA && message.isSuccess && message.has(inband)){
// startTLS();
// }
if (message.isRequest()) {
return;
}
if (message.getCommandCode() == IMessage.CAPABILITIES_EXCHANGE_ANSWER && isSuccess(message)) {
AvpSet set = message.getAvps();
Avp inbandAvp = set.getAvp(Avp.INBAND_SECURITY_ID);
if (inbandAvp != null && inbandAvp.getUnsigned32() == 1) {
startTLS();
}
}
} else {
// if(CER && message.has(inband)){
// this.receveidInband = true;
// }
if (!message.isRequest()) {
return;
}
AvpSet set = message.getAvps();
Avp inbandAvp = set.getAvp(Avp.INBAND_SECURITY_ID);
if (inbandAvp != null && inbandAvp.getUnsigned32() == 1) {
this.receivedInband = true;
}
}
}
/**
* @param message
*/
private void doTLSPreSendProcessing(IMessage message) {
if (message.getCommandCode() == IMessage.CAPABILITIES_EXCHANGE_REQUEST) {
AvpSet set = message.getAvps();
set.removeAvp(Avp.INBAND_SECURITY_ID);
set.addAvp(Avp.INBAND_SECURITY_ID, 1);
}
}
/**
* @param message
* @throws AvpDataException
* @throws NotInitializedException
*/
private void doTLSPostSendProcessing(IMessage message) throws AvpDataException, NotInitializedException {
// if( !client && !shaken && CEA && message.isSuccess() && receivedInband){
// startTLS;
// }
if (this.shaken || this.client || this.plainSocket instanceof SSLSocket || message.isRequest()
|| message.getCommandCode() != IMessage.CAPABILITIES_EXCHANGE_ANSWER) {
return;
}
if (this.receivedInband && isSuccess(message)) {
this.receivedInband = false;
startTLS();
}
}
/**
* @throws NotInitializedException
*
*/
private void startTLS() throws NotInitializedException {
try {
this.shaking = true;
SSLSocketFactory cltFct = parentConnection.getSSLFactory();
SSLSocket sslSocket = (SSLSocket) cltFct.createSocket(this.plainSocket, null, this.plainSocket.getPort(), false);
sslSocket.setEnableSessionCreation(parentConnection.getSSLConfig().getBooleanValue(
SDEnableSessionCreation.ordinal(), true));
// only clients start shake
if (parentConnection.getSSLConfig().getStringValue(CipherSuites.ordinal(), null) != null) {
sslSocket.setEnabledCipherSuites(parentConnection.getSSLConfig().getStringValue(CipherSuites.ordinal(), null)
.split(","));
}
this.inputStream = sslSocket.getInputStream();
this.outputStream = sslSocket.getOutputStream();
this.plainSocket = sslSocket;
if (this.client) {
sslSocket.setUseClientMode(true);
// TODO: catch this to check for failure
sslSocket.addHandshakeCompletedListener(this.handshakeListener);
sslSocket.startHandshake();
} else {
sslSocket.addHandshakeCompletedListener(this.handshakeListener);
sslSocket.setUseClientMode(false);
}
} catch (Exception e) {
// TODO: ensure close?
throw new NotInitializedException(e);
}
}
private void clearBuffer() throws IOException {
bufferSize = DEFAULT_BUFFER_SIZE;
buffer = ByteBuffer.allocate(bufferSize);
}
// ---------------- helper classes ---------------------
private class DiameterSSLHandshakeListener implements HandshakeCompletedListener {
@Override
public void handshakeCompleted(HandshakeCompletedEvent event) {
// connected comes from here!
try {
lock.lock();
shaking = false;
shaken = true;
((SSLSocket)plainSocket).removeHandshakeCompletedListener(this);
getParent().onConnected();
}
finally {
lock.unlock();
}
}
}
private class ReadTask implements Runnable {
@Override
public void run() {
logger.debug("Transport is started. Socket is [{}]", socketDescription);
try {
while (!stop) {
int dataLength = inputStream.read(buffer.array());
logger.debug("Just read [{}] bytes on [{}]", dataLength, socketDescription);
if (dataLength == -1) {
break;
}
buffer.position(dataLength);
buffer.flip();
byte[] data = new byte[buffer.limit()];
buffer.get(data);
append(data);
buffer.clear();
}
}
catch (ClosedByInterruptException e) {
logger.debug("Transport exception ", e);
}
catch (AsynchronousCloseException e) {
logger.debug("Transport exception ", e);
}
catch (Throwable e) {
logger.debug("Transport exception ", e);
}
finally {
try {
clearBuffer();
if (plainSocket != null && !plainSocket.isClosed()) {
plainSocket.close();
}
getParent().onDisconnect();
}
catch (Exception e) {
logger.debug("Error", e);
}
stop = false;
logger.info("Read thread is stopped for socket [{}]", socketDescription);
}
}
}
} | Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.transport.tls;
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.SDName;
import static org.jdiameter.client.impl.helpers.Parameters.SDProtocol;
import static org.jdiameter.client.impl.helpers.Parameters.Security;
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 java.io.FileInputStream;
import java.security.KeyStore;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.jdiameter.api.Configuration;
/**
* Simple utils class just to have one place for common stuff.
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class TLSUtils {
public static SSLContext getSecureContext(Configuration sslConfig) throws Exception {
// TODO: use classloader to fetch files.
final String contextTransportAlgo = sslConfig.getStringValue(SDProtocol.ordinal(), null);
final Configuration kdConfig = sslConfig.getChildren(KeyData.ordinal())[0];
final Configuration tdConfig = sslConfig.getChildren(TrustData.ordinal())[0];
final String keyManagerAlgo = kdConfig.getStringValue(KDManager.ordinal(), null);
final String keyStoreType = kdConfig.getStringValue(KDStore.ordinal(), null);
final String keyStorePassword = kdConfig.getStringValue(KDPwd.ordinal(), null);
final String keyStoreFile = kdConfig.getStringValue(KDFile.ordinal(), null);
final String trustManagerAlgo = tdConfig.getStringValue(TDManager.ordinal(), null);
final String trustStoreType = tdConfig.getStringValue(TDStore.ordinal(), null);
final String trustStorePassword = tdConfig.getStringValue(TDPwd.ordinal(), null);
final String trustStoreFile = tdConfig.getStringValue(TDFile.ordinal(), null);
return TLSUtils.getSecureContext(contextTransportAlgo, keyManagerAlgo, keyStoreType, keyStorePassword, keyStoreFile, trustManagerAlgo, trustStoreType,
trustStorePassword, trustStoreFile);
}
public static SSLContext getSecureContext(String contextTransportAlgo, String keyManagerAlgo, String keyStoreType, String keyStorePassword,
String keyStoreFile, String trustManagerAlgo, String trustStoreType, String trustStorePassword, String trustStoreFile) throws Exception {
System.err.println(KeyManagerFactory.getDefaultAlgorithm());
System.err.println(TrustManagerFactory.getDefaultAlgorithm());
SSLContext ctx = SSLContext.getInstance(contextTransportAlgo);
// http://docs.oracle.com/javase/6/docs/technotes/guides/security/StandardNames.html
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerAlgo);
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
char[] key = keyStorePassword.toCharArray();
keyStore.load(new FileInputStream(keyStoreFile), key);
keyManagerFactory.init(keyStore, key);
KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
//
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustManagerAlgo);
KeyStore trustKeyStore = KeyStore.getInstance(trustStoreType);
char[] trustKey = trustStorePassword.toCharArray();
trustKeyStore.load(new FileInputStream(trustStoreFile), trustKey);
trustManagerFactory.init(trustKeyStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
//
ctx.init(keyManagers, trustManagers, null);
return ctx;
}
public static Configuration getSSLConfiguration(Configuration cnf, String ref) {
Configuration sec[] = cnf.getChildren(Security.ordinal());// [0].getChildren(SecurityData.ordinal());
for (Configuration i : sec) {
if (i.getStringValue(SDName.ordinal(), "").equals(ref)) {
return i;
}
}
return null;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2012, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.transport.tls;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
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.jdiameter.common.api.concurrent.IConcurrentFactory;
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 TLSClientConnection implements IConnection {
private static Logger logger = LoggerFactory.getLogger(TLSClientConnection.class);
private TLSTransportClient client;
private SSLSocketFactory factory;
private Configuration sslConfig;
private final long createdTime;
private LinkedBlockingQueue<Event> buffer = new LinkedBlockingQueue<Event>(64);
private Lock lock = new ReentrantLock();
private ConcurrentLinkedQueue<IConnectionListener> listeners = new ConcurrentLinkedQueue<IConnectionListener>();
// Cached value for connection key
private String cachedKey = null;
public TLSClientConnection(Configuration config, IConcurrentFactory concurrentFactory, InetAddress remoteAddress, int remotePort, InetAddress localAddress,
int localPort, IMessageParser parser, String ref) {
this.createdTime = System.currentTimeMillis();
this.client = new TLSTransportClient(this, concurrentFactory, parser);
this.client.setDestAddress(new InetSocketAddress(remoteAddress, remotePort));
this.client.setOrigAddress(new InetSocketAddress(localAddress, localPort));
try {
if (ref == null) {
throw new Exception("Can not create connection without TLS parameters");
}
logger.trace("Initializing TLS with reference '{}'", ref);
fillSecurityData(config, ref);
}
catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
public TLSClientConnection(Configuration config, IConcurrentFactory concurrentFactory, InetAddress remoteAddress, int remotePort, InetAddress localAddress,
int localPort, IConnectionListener listener, IMessageParser parser, String ref) {
this.createdTime = System.currentTimeMillis();
this.listeners.add(listener);
this.client = new TLSTransportClient(this, concurrentFactory, parser);
this.client.setDestAddress(new InetSocketAddress(remoteAddress, remotePort));
this.client.setOrigAddress(new InetSocketAddress(localAddress, localPort));
try {
if (ref == null) {
throw new Exception("Can not create connection without TLS parameters");
}
logger.trace("Initializing TLS with reference '{}'", ref);
fillSecurityData(config, ref);
}
catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
public TLSClientConnection(Configuration config, Configuration localPeerSSLConfig, IConcurrentFactory concurrentFactory, Socket socket,
IMessageParser parser) throws Exception {
this.createdTime = System.currentTimeMillis();
this.sslConfig = localPeerSSLConfig;
this.client = new TLSTransportClient(this, concurrentFactory, parser);
this.client.setDestAddress(new InetSocketAddress(socket.getRemoteSocketAddress().toString(), socket.getPort()));
this.client.setOrigAddress(new InetSocketAddress(socket.getInetAddress().getHostAddress(), socket.getLocalPort()));
this.client.initialize(socket);
this.client.start();
try {
if (localPeerSSLConfig == null) {
throw new Exception("Can not create connection without TLS parameters");
}
fillSecurityData(localPeerSSLConfig);
}
catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
private void fillSecurityData(Configuration config, String ref) throws Exception {
sslConfig = TLSUtils.getSSLConfiguration(config, ref);
if (sslConfig == null) {
throw new Exception("Incorrect reference to secutity data");
}
this.factory = getSSLContext(sslConfig);
}
private void fillSecurityData(Configuration config) throws Exception {
this.factory = getSSLContext(config);
}
protected TLSTransportClient getClient() {
return client;
}
public Configuration getSSLConfig() {
return sslConfig;
}
public SSLSocketFactory getSSLFactory() {
return factory;
}
private SSLSocketFactory getSSLContext(Configuration sslConfig) throws Exception {
SSLContext ctx = TLSUtils.getSecureContext(sslConfig);
return ctx.getSocketFactory();
}
public long getCreatedTime() {
return createdTime;
}
public InetAddress getRemoteAddress() {
return getClient().getDestAddress().getAddress();
}
public int getRemotePort() {
return getClient().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 void release() throws IOException {
try {
if (getClient() != null) {
getClient().release();
}
}
catch (Exception e) {
throw new IOException(e.getMessage());
}
finally {
buffer.clear();
remAllConnectionListener();
}
}
public boolean isWrapperFor(Class<?> aClass) throws InternalException {
return false;
}
public <T> T unwrap(Class<T> aClass) throws InternalException {
return null;
}
public boolean isConnected() {
return getClient() != null && getClient().isConnected();
}
public boolean isNetworkInitiated() {
return false;
}
public String getKey() {
if (this.cachedKey == null) {
this.cachedKey = new StringBuffer("aaas://").append(getRemoteAddress().getHostName()).append(":").append(getRemotePort()).toString();
}
return this.cachedKey;
}
public void connect() throws TransportException {
try {
getClient().initialize();
getClient().start();
}
catch (IOException e) {
throw new TransportException("Cannot init transport: ", TransportError.NetWorkError, e);
}
catch (Exception e) {
throw new TransportException("Cannot init transport: ", TransportError.Internal, e);
}
}
public void disconnect() throws InternalError {
try {
if (getClient() != null) {
getClient().stop();
}
}
catch (Exception e) {
throw new InternalError("Error while stopping transport: " + e.getMessage());
}
}
public void sendMessage(IMessage message) throws TransportException, OverloadException {
try {
if (getClient() != null) {
getClient().sendMessage(message);
}
}
catch (Exception e) {
throw new TransportException("Cannot send message: ", TransportError.FailedSendMessage, e);
}
}
protected void onDisconnect() throws AvpDataException {
onEvent(new Event(EventType.DISCONNECTED));
}
protected void onMessageReceived(IMessage 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 onEvent(Event event) throws AvpDataException {
lock.lock();
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(), 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;
IMessage message;
Exception exception;
Event(EventType type) {
this.type = type;
}
Event(EventType type, Exception exception) {
this(type);
this.exception = exception;
}
Event(EventType type, IMessage message) {
this(type);
this.message = message;
}
}
} | Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl.transport.tcp;
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.jdiameter.common.api.concurrent.IConcurrentFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentLinkedQueue;
// FIXME : requires JDK6 : import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class TCPClientConnection implements IConnection {
private static Logger logger = LoggerFactory.getLogger(TCPClientConnection.class);
private final long createdTime;
private TCPTransportClient client;
//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;
protected TCPClientConnection(IConcurrentFactory concurrentFactory, IMessageParser parser) {
this.createdTime = System.currentTimeMillis();
this.parser = parser;
client = new TCPTransportClient(concurrentFactory, this);
}
public TCPClientConnection(Configuration config, IConcurrentFactory concurrentFactory, Socket socket,
IMessageParser parser, String ref) throws Exception {
this(concurrentFactory, parser);
client = new TCPTransportClient(concurrentFactory, this);
client.initialize(socket);
client.start();
}
public TCPClientConnection(Configuration config, IConcurrentFactory concurrentFactory, InetAddress remoteAddress,
int remotePort, InetAddress localAddress, int localPort, IMessageParser parser, String ref) {
this(concurrentFactory, parser);
client.setDestAddress(new InetSocketAddress(remoteAddress, remotePort));
client.setOrigAddress(new InetSocketAddress(localAddress, localPort));
}
public TCPClientConnection(Configuration config, IConcurrentFactory concurrentFactory, InetAddress remoteAddress,
int remotePort, InetAddress localAddress, int localPort, IConnectionListener listener,
IMessageParser parser, String ref) {
this(concurrentFactory, parser);
client.setDestAddress(new InetSocketAddress(remoteAddress, remotePort));
client.setOrigAddress(new InetSocketAddress(localAddress, localPort));
listeners.add(listener);
}
public long getCreatedTime() {
return createdTime;
}
public void connect() throws TransportException {
try {
getClient().initialize();
getClient().start();
}
catch (IOException e) {
throw new TransportException("Cannot init transport: ", TransportError.NetWorkError, e);
}
catch (Exception e) {
throw new TransportException("Cannot init transport: ", TransportError.Internal, e);
}
}
public void disconnect() throws InternalError {
//PCB added logging
logger.debug("In disconnect for [{}]", this.getKey());
try {
if (getClient() != null) {
getClient().stop();
}
}
catch (Exception e) {
throw new InternalError("Error while stopping transport: " + e.getMessage());
}
}
public void release() throws IOException {
//PCB added logging
logger.debug("In release for [{}]", this.getKey());
try {
if (getClient() != null) {
getClient().release();
}
}
catch (Exception e) {
throw new IOException(e.getMessage());
}
finally {
parser = null;
buffer.clear();
remAllConnectionListener();
}
}
public void sendMessage(IMessage message) throws TransportException, OverloadException {
try {
if (getClient() != null) {
//PCB added logging
//Long receivedAt = timerMap.remove(message.getEndToEndIdentifier() + "_"+ message.getHopByHopIdentifier());
//if (receivedAt != null) {
// long millis = System.currentTimeMillis() - receivedAt;
// if (millis >= 200) {
// logger.warn("Diameter Message processing took [{}]ms", millis);
// }
//}
getClient().sendMessage(parser.encodeMessage(message));
//PCB added logging
//if (receivedAt != null) {
// long millis = System.currentTimeMillis() - receivedAt;
// if (millis >= 200) {
// logger.warn("Diameter Message processing and sending took [{}]ms", millis);
// }
//}
}
}
catch (Exception e) {
throw new TransportException("Cannot send message: ", TransportError.FailedSendMessage, e);
}
}
protected TCPTransportClient getClient() {
return client;
}
public boolean isNetworkInitiated() {
return false;
}
public boolean isConnected() {
return getClient() != null && getClient().isConnected();
}
public InetAddress getRemoteAddress() {
return getClient().getDestAddress().getAddress();
}
public int getRemotePort() {
return getClient().getDestAddress().getPort();
}
public void addConnectionListener(IConnectionListener listener) {
lock.lock();
try {
listeners.add(listener);
if (buffer.size() != 0) {
for (Event e : buffer) {
try {
//PCB added logging
logger.debug("Processing event from buffer");
onEvent(e);
}
catch (AvpDataException e1) {
// ignore
}
}
buffer.clear();
}
}
finally {
lock.unlock();
}
}
public void remAllConnectionListener() {
//PCB added logging
logger.debug("Waiting to get lock in order to remove all listeners");
lock.lock();
try {
//PCB added logging
logger.debug("Removing all listeners on [{}]", this.getKey());
listeners.clear();
}
finally {
lock.unlock();
}
}
public void remConnectionListener(IConnectionListener listener) {
lock.lock();
try {
//PCB added logging
logger.debug("Removing listener [{}] on [{}]", listener.getClass().getName(), this.getKey());
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 onEvent(Event event) throws AvpDataException {
//PCB added logging
logger.debug("In onEvent for connection [{}]. Getting lock", this.getKey());
lock.lock();
//PCB added logging
logger.debug("Got lock");
try {
if (processBufferedMessages(event)) {
for (IConnectionListener listener : listeners) {
//PCB added logging
if (logger.isDebugEnabled()) {
logger.debug("Passing event to listener. Event type is [{}]", event.type.toString());
}
switch (event.type) {
case CONNECTED:
listener.connectionOpened(getKey());
break;
case DISCONNECTED:
listener.connectionClosed(getKey(), null);
break;
case MESSAGE_RECEIVED:
//PCB added
IMessage msg = parser.createMessage(event.message);
//timerMap.put(msg.getEndToEndIdentifier() + "_"+ msg.getHopByHopIdentifier(), System.currentTimeMillis());
listener.messageReceived(getKey(), msg);
break;
case DATA_EXCEPTION:
listener.internalError(getKey(), null, new TransportException("Avp Data Exception:",
TransportError.ReceivedBrokenMessage, event.exception));
break;
}
}
}
}
finally {
logger.debug("Releasing lock and finished onEvent for connection [{}]", this.getKey());
lock.unlock();
}
}
//private static final Map<String, Long> timerMap = new ConcurrentHashMap<String, Long>();
protected boolean processBufferedMessages(Event event) throws AvpDataException {
if (listeners.size() == 0) {
//PCB added logging
logger.debug("listeners.size() == 0 on connection [{}]", this.getKey());
try {
buffer.add(event);
}
catch (IllegalStateException e) {
logger.debug("Got IllegalStateException in processBufferedMessages");
// FIXME : requires JDK6 : buffer.removeLast();
Event[] tempBuffer = buffer.toArray(new Event[buffer.size()]);
buffer.remove(tempBuffer[tempBuffer.length-1]);
buffer.add(event);
}
//PCB added logging
logger.debug("processBufferedMessages is returning false");
return false;
}
else {
logger.debug("processBufferedMessages is returning true on connection [{}] as there are listeners", getKey());
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/>
*
* 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.client.impl.transport.tcp;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.client.api.io.NotInitializedException;
import org.jdiameter.common.api.concurrent.IConcurrentFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousCloseException;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class TCPTransportClient implements Runnable {
private TCPClientConnection parentConnection;
private IConcurrentFactory concurrentFactory;
public static final int DEFAULT_BUFFER_SIZE = 1024;
public static final int DEFAULT_STORAGE_SIZE = 2048;
protected boolean stop = false;
protected Thread selfThread;
protected int bufferSize = DEFAULT_BUFFER_SIZE;
protected ByteBuffer buffer = ByteBuffer.allocate(this.bufferSize);
protected InetSocketAddress destAddress;
protected InetSocketAddress origAddress;
protected SocketChannel socketChannel;
protected Lock lock = new ReentrantLock();
protected int storageSize = DEFAULT_STORAGE_SIZE;
protected ByteBuffer storage = ByteBuffer.allocate(storageSize);
private String socketDescription = null;
private static final Logger logger = LoggerFactory.getLogger(TCPTransportClient.class);
//PCB - allow non blocking IO
private static final boolean BLOCKING_IO = false;
private static final long SELECT_TIMEOUT = 500; // milliseconds
public TCPTransportClient() {
}
/**
* Default constructor
*
* @param concurrentFactory factory for create threads
* @param parenConnection connection created this transport
*/
TCPTransportClient(IConcurrentFactory concurrentFactory, TCPClientConnection parenConnection) {
this.parentConnection = parenConnection;
this.concurrentFactory = concurrentFactory;
}
/**
* Network init socket
*/
public void initialize() throws IOException, NotInitializedException {
logger.debug("Initialising TCPTransportClient. Origin address is [{}] and destination address is [{}]", origAddress, destAddress);
if (destAddress == null) {
throw new NotInitializedException("Destination address is not set");
}
socketChannel = SelectorProvider.provider().openSocketChannel();
if (origAddress != null) {
socketChannel.socket().bind(origAddress);
}
socketChannel.connect(destAddress);
//PCB added logging
socketChannel.configureBlocking(BLOCKING_IO);
getParent().onConnected();
}
public TCPClientConnection getParent() {
return parentConnection;
}
public void initialize(Socket socket) throws IOException, NotInitializedException {
logger.debug("Initialising TCPTransportClient for a socket on [{}]", socket);
socketDescription = socket.toString();
socketChannel = socket.getChannel();
//PCB added logging
socketChannel.configureBlocking(BLOCKING_IO);
destAddress = new InetSocketAddress(socket.getInetAddress(), socket.getPort());
}
public void start() throws NotInitializedException {
// for client
if(socketDescription == null && socketChannel != null) {
socketDescription = socketChannel.socket().toString();
}
logger.debug("Starting transport. Socket is {}", socketDescription);
if (socketChannel == null) {
throw new NotInitializedException("Transport is not initialized");
}
if (!socketChannel.isConnected()) {
throw new NotInitializedException("Socket channel is not connected");
}
if (getParent() == null) {
throw new NotInitializedException("No parent connection is set is set");
}
if (selfThread == null || !selfThread.isAlive()) {
selfThread = concurrentFactory.getThread("TCPReader", this);
}
if (!selfThread.isAlive()) {
selfThread.setDaemon(true);
selfThread.start();
}
}
//PCB added logging
public void run() {
// Workaround for Issue #4 (http://code.google.com/p/jdiameter/issues/detail?id=4)
// BEGIN WORKAROUND // Give some time to initialization...
int sleepTime = 250;
logger.debug("Sleeping for {}ms before starting transport so that listeners can all be added and ready for messages", sleepTime);
try {
Thread.sleep(sleepTime);
}
catch (InterruptedException e) {
// ignore
}
logger.debug("Finished sleeping for {}ms. By now, MutablePeerTableImpl should have added its listener", sleepTime);
logger.debug("Transport is started. Socket is [{}]", socketDescription);
Selector selector = null;
try {
selector = Selector.open();
socketChannel.register(selector, SelectionKey.OP_READ);
while (!stop) {
selector.select(SELECT_TIMEOUT);
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
// Get the selection key
SelectionKey selKey = it.next();
// Remove it from the list to indicate that it is being processed
it.remove();
if (selKey.isValid() && selKey.isReadable()) {
// Get channel with bytes to read
SocketChannel sChannel = (SocketChannel) selKey.channel();
int dataLength = sChannel.read(buffer);
logger.debug("Just read [{}] bytes on [{}]", dataLength, socketDescription);
if (dataLength == -1) {
stop = true;
break;
}
buffer.flip();
byte[] data = new byte[buffer.limit()];
buffer.get(data);
append(data);
buffer.clear();
}
}
}
}
catch (ClosedByInterruptException e) {
logger.error("Transport exception ", e);
}
catch (AsynchronousCloseException e) {
logger.error("Transport is closed");
}
catch (Throwable e) {
logger.error("Transport exception ", e);
}
finally {
try {
clearBuffer();
if (selector != null) {
selector.close();
}
if (socketChannel != null && socketChannel.isOpen()) {
socketChannel.close();
}
getParent().onDisconnect();
}
catch (Exception e) {
logger.error("Error", e);
}
stop = false;
logger.info("Read thread is stopped for socket [{}]", socketDescription);
}
}
public void stop() throws Exception {
logger.debug("Stopping transport. Socket is [{}]", socketDescription);
stop = true;
if (socketChannel != null && socketChannel.isOpen()) {
socketChannel.close();
}
if (selfThread != null) {
selfThread.join(100);
}
clearBuffer();
logger.debug("Transport is stopped. Socket is [{}]", socketDescription);
}
public void release() throws Exception {
stop();
destAddress = null;
}
private void clearBuffer() throws IOException {
bufferSize = DEFAULT_BUFFER_SIZE;
buffer = ByteBuffer.allocate(bufferSize);
}
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 TCP nio socket [{}]", bytes.array().length, socketDescription);
}
int rc = 0;
// PCB - removed locking
// lock.lock();
try {
while (rc < bytes.array().length) {
rc += socketChannel.write(bytes);
}
}
catch (Exception e) {
logger.error("Unable to send message", e);
throw new IOException("Error while sending message: " + e);
}
finally {
// lock.unlock();
}
if (rc == -1) {
throw new IOException("Connection closed");
}
if (logger.isDebugEnabled()) {
logger.debug("Sent a byte buffer of size [{}] over the TCP nio socket [{}]", bytes.array().length, socketDescription);
}
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("Transport to ");
if (this.destAddress != null) {
buffer.append(this.destAddress.getHostName());
buffer.append(":");
buffer.append(this.destAddress.getPort());
}
else {
buffer.append("null");
}
buffer.append("@");
buffer.append(super.toString());
return buffer.toString();
}
boolean isConnected() {
return socketChannel != null && socketChannel.isOpen() && socketChannel.isConnected();
}
/**
* Adds data to storage
*
* @param data data to add
*/
private void append(byte[] data) {
if (storage.position() + data.length >= storage.capacity()) {
ByteBuffer tmp = ByteBuffer.allocate(storage.limit() + data.length * 2);
byte[] tmpData = new byte[storage.position()];
storage.flip();
storage.get(tmpData);
tmp.put(tmpData);
storage = tmp;
logger.warn("Increase storage size. Current size is {}", storage.array().length);
}
try {
storage.put(data);
}
catch (BufferOverflowException boe) {
logger.error("Buffer overflow occured", boe);
}
boolean messageReceived;
do {
messageReceived = seekMessage();
} while (messageReceived);
}
private boolean seekMessage() {
// make sure there's actual data written on the buffer
if (storage.position() == 0) {
return false;
}
storage.flip();
try {
// get first four bytes for version and message length
// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Version | Message Length |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
int tmp = storage.getInt();
// reset position so we can now read whole message
storage.position(0);
// check that version is 1, as per RFC 3588 - Section 3:
// This Version field MUST be set to 1 to indicate Diameter Version 1
byte vers = (byte) (tmp >> 24);
if (vers != 1) {
return false;
}
// extract the message length, so we know how much to read
int messageLength = (tmp & 0xFFFFFF);
// verify that we do have the whole message in the storage
if (storage.limit() < messageLength) {
// we don't have it all.. let's restore buffer to receive more
storage.position(storage.limit());
storage.limit(storage.capacity());
logger.debug("Received partial message, waiting for remaining (expected: {} bytes, got {} bytes).", messageLength, storage.position());
return false;
}
// read the complete message
byte[] data = new byte[messageLength];
storage.get(data);
storage.compact();
try {
// make a message out of data and process it
logger.debug("Passing message on to parent");
getParent().onMessageReceived(ByteBuffer.wrap(data));
logger.debug("Finished passing message on to parent");
}
catch (AvpDataException e) {
logger.debug("Garbage was received. Discarding.");
storage.clear();
getParent().onAvpDataException(e);
}
}
catch(BufferUnderflowException bue) {
// we don't have enough data to read message length.. wait for more
storage.position(storage.limit());
storage.limit(storage.capacity());
logger.debug("Buffer underflow occured, waiting for more data.", bue);
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.client.impl.transport;
import org.jdiameter.api.Configuration;
import org.jdiameter.api.InternalException;
import org.jdiameter.client.api.io.*;
import org.jdiameter.client.api.parser.IMessageParser;
import org.jdiameter.client.impl.helpers.AppConfiguration;
import org.jdiameter.client.impl.helpers.ExtensionPoint;
import org.jdiameter.client.impl.helpers.Parameters;
import org.jdiameter.common.api.concurrent.DummyConcurrentFactory;
import org.jdiameter.common.api.concurrent.IConcurrentFactory;
import static java.lang.Class.forName;
import java.lang.reflect.Constructor;
import java.net.InetAddress;
/**
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class TransportLayerFactory implements ITransportLayerFactory {
private Class<IConnection> connectionClass;
private Constructor<IConnection> constructorIAi, constructorIAiCL;
protected IMessageParser parser;
protected Configuration config = null;
public TransportLayerFactory(Configuration config, IMessageParser parser) throws TransportException {
this.config = config;
Configuration[] children = config.getChildren(Parameters.Extensions.ordinal());
AppConfiguration internalExtensions = (AppConfiguration) children[ExtensionPoint.Internal.id()];
String implName = internalExtensions.getStringValue(
ExtensionPoint.InternalConnectionClass.ordinal(), (String) ExtensionPoint.InternalConnectionClass.defValue()
);
try {
//TODO: this should be enough to check if class has interface!?
this.connectionClass = (Class<IConnection>) forName(implName);
if (!IConnection.class.isAssignableFrom(this.connectionClass))
throw new TransportException("Specified class does not inherit IConnection interface " + this.connectionClass, TransportError.Internal);
} catch (Exception e) {
throw new TransportException("Cannot prepare specified connection class " + this.connectionClass, TransportError.Internal, e);
}
try {
//TODO: this is bad practice, IConnection is interface and this code enforces constructor type to be present!
constructorIAiCL = connectionClass.getConstructor(
Configuration.class, IConcurrentFactory.class, InetAddress.class, Integer.TYPE, InetAddress.class,
Integer.TYPE, IConnectionListener.class, IMessageParser.class, String.class);
constructorIAi = connectionClass.getConstructor(
Configuration.class, IConcurrentFactory.class, InetAddress.class, Integer.TYPE, InetAddress.class,
Integer.TYPE, IMessageParser.class, String.class);
}
catch (Exception e) {
throw new TransportException("Cannot find required constructor", TransportError.Internal, e);
}
this.parser = parser;
}
public IConnection createConnection(InetAddress remoteAddress, IConcurrentFactory factory, int remotePort, InetAddress localAddress, int localPort, String ref) throws TransportException {
try {
factory = factory == null ? new DummyConcurrentFactory() : factory;
return constructorIAi.newInstance(config, factory, remoteAddress, remotePort, localAddress, localPort, parser, ref);
} catch (Exception e) {
throw new TransportException("Cannot create an instance of " + connectionClass, TransportError.Internal, e);
}
}
public IConnection createConnection(InetAddress remoteAddress, IConcurrentFactory factory, int remotePort, InetAddress localAddress, int localPort, IConnectionListener listener, String ref) throws TransportException {
try {
factory = factory == null ? new DummyConcurrentFactory() : factory;
return constructorIAiCL.newInstance(config, factory, remoteAddress, remotePort, localAddress, localPort, listener, parser, ref);
} catch (Exception e) {
throw new TransportException("Cannot create an instance of " + connectionClass, TransportError.Internal, e);
}
}
public boolean isWrapperFor(Class<?> aClass) throws InternalException {
return false;
}
public <T> T unwrap(Class<T> aClass) throws InternalException {
return null;
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.impl;
import org.jdiameter.api.*;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.IRequest;
import org.jdiameter.client.api.ISession;
import org.jdiameter.client.api.parser.IMessageParser;
import org.jdiameter.common.api.data.ISessionDatasource;
import java.util.concurrent.TimeUnit;
/**
* Implementation for {@link ISession}
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class SessionImpl extends BaseSessionImpl implements ISession {
SessionImpl(IContainer container) {
setContainer(container);
try {
sessionId = container.getSessionFactory().getSessionId();
}
catch (IllegalDiameterStateException idse) {
throw new IllegalStateException("Unable to generate Session-Id", idse);
}
}
void setContainer(IContainer container) {
this.container = container;
this.parser = (IMessageParser) container.getAssemblerFacility().getComponentInstance(IMessageParser.class);
}
public void send(Message message, EventListener<Request, Answer> listener) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
genericSend(message, listener);
}
public void send(Message message, EventListener<Request, Answer> listener, long timeout, TimeUnit timeUnit) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
genericSend(message, listener, timeout, timeUnit);
}
public void setRequestListener(NetworkReqListener listener) {
if (listener != null) {
super.reqListener = listener;
container.addSessionListener(sessionId, listener);
}
}
public NetworkReqListener getReqListener() {
return super.reqListener;
}
public Request createRequest(int commandCode, ApplicationId appId, String destRealm) {
if (isValid) {
lastAccessedTime = System.currentTimeMillis();
IRequest m = parser.createEmptyMessage(IRequest.class, commandCode, getAppId(appId));
m.setNetworkRequest(false);
m.setRequest(true);
m.getAvps().addAvp(Avp.SESSION_ID, sessionId, true, false, false);
appendAppId(appId, m);
if (destRealm != null) {
m.getAvps().addAvp(Avp.DESTINATION_REALM, destRealm, true, false, true);
}
MessageUtility.addOriginAvps(m, container.getMetaData());
return m;
}
else {
throw new IllegalStateException("Session already released");
}
}
public Request createRequest(int commandCode, ApplicationId appId, String destRealm, String destHost) {
if (isValid) {
lastAccessedTime = System.currentTimeMillis();
IRequest m = parser.createEmptyMessage(IRequest.class, commandCode, getAppId(appId));
m.setNetworkRequest(false);
m.setRequest(true);
m.getAvps().addAvp(Avp.SESSION_ID, sessionId, true, false, false);
appendAppId(appId, m);
if (destRealm != null) {
m.getAvps().addAvp(Avp.DESTINATION_REALM, destRealm, true, false, true);
}
if (destHost != null) {
m.getAvps().addAvp(Avp.DESTINATION_HOST, destHost, true, false, true);
}
MessageUtility.addOriginAvps(m, container.getMetaData());
return m;
}
else {
throw new IllegalStateException("Session already released");
}
}
public Request createRequest(Request prevRequest) {
if (isValid) {
lastAccessedTime = System.currentTimeMillis();
IRequest request = parser.createEmptyMessage(Request.class, (IMessage) prevRequest);
request.setRequest(true);
request.setNetworkRequest(false);
MessageUtility.addOriginAvps(request, container.getMetaData());
return request;
}
else {
throw new IllegalStateException("Session already released");
}
}
public void release() {
isValid = false;
if (container != null) {
container.removeSessionListener(sessionId);
// FIXME
container.getAssemblerFacility().getComponentInstance(ISessionDatasource.class).removeSession(sessionId);
}
container = null;
parser = null;
reqListener = null;
}
public boolean isWrapperFor(Class<?> iface) throws InternalException {
return iface == RawSession.class;
}
@SuppressWarnings("unchecked")
public <T> T unwrap(Class<T> iface) throws InternalException {
return (T) (iface == RawSession.class ? new RawSessionImpl(container) : null);
}
}
| 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.client.api.annotation;
/**
*
* @author erick.svenson@yahoo.com
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class RecoderException extends RuntimeException {
private static final long serialVersionUID = 1L;
public RecoderException(Throwable cause) {
super(cause);
}
} | 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.client.api.annotation;
import org.jdiameter.api.Avp;
import org.jdiameter.api.Message;
import org.jdiameter.api.Request;
/**
* This interface provide methods for create diameter messages from your annotated domain object and
* create domain object from diameter message.
*
* @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 IRecoder {
/**
* Create Request message from specified annotated domain object
*
* @param yourDomainMessageObject annotated domain object
* @param additionalAvp additional avp
* @return message instance
* @throws RecoderException throw if object can not be encoded to diameter message
*/
public Message encodeToRequest(Object yourDomainMessageObject, Avp... additionalAvp) throws RecoderException;
/**
* Create Answer message from specified annotated domain object
*
* @param yourDomainMessageObject annotated domain object
* @param request request message
* @param resultCode result code of answer
* @return message answer instance
* @throws RecoderException throw if object can not be encoded to diameter message
*/
public Message encodeToAnswer(Object yourDomainMessageObject, Request request, long resultCode) throws RecoderException;
/**
* Create specified domain object by message and class of object
*
* @param message diameter message
* @param yourDomainMessageObject class of domain object
* @return instance of domain object
* @throws RecoderException throw if message can not be decoded to domain object
*/
public <T> T decode(Message message, java.lang.Class<T> yourDomainMessageObject) throws RecoderException;
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.api;
import org.jdiameter.api.Answer;
import org.jdiameter.api.EventListener;
import org.jdiameter.api.Request;
/**
* This interface describe extends methods of base class
* Data: $Date: 2008/07/03 19:43:10 $
* Revision: $Revision: 1.1 $
* @version 1.5.0.1
*
* @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 IEventListener extends EventListener<Request,Answer> {
/**
* Set value of valid field
* @param value true is listener yet valid
*/
void setValid(boolean value);
/**
* Return rue if event listener valid(session is not released)
* @return rue if event listener valid
*/
boolean isValid();
}
| 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.client.api;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.Session;
/**
* This interface describe extends methods of base class
* Data: $Date: 2009/07/27 18:05:03 $
* Revision: $Revision: 1.3 $
* @version 1.5.0.1
*
* @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 ISession extends Session {
NetworkReqListener getReqListener();
}
| 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.client.api.parser;
/**
* Signals that an parser exception has occurred in a during decoding message
*
* @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 ParseException extends Exception {
private static final long serialVersionUID = 1L;
/**
* Create instance of class
*/
public ParseException() {
}
/**
* Create instance of class with predefined parameters
* @param message error message
*/
public ParseException(String message) {
super(message);
}
/**
* Create instance of class with predefined parameters
* @param message error message
* @param cause error cause
*/
public ParseException(String message, Throwable cause) {
super(message, cause);
}
/**
* Create instance of class with predefined parameters
* @param cause error cause
*/
public ParseException(Throwable cause) {
super(cause);
}
}
| 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.client.api.parser;
import org.jdiameter.api.AvpDataException;
import java.net.InetAddress;
import java.util.Date;
/**
* Basic interface for diameter basic elements parsers.
*
* @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 IElementParser {
/**
* Convert byte array to int
* @param rawData byte representation of int value
* @return int value
* @throws AvpDataException
*/
int bytesToInt(byte[] rawData) throws AvpDataException;
/**
* Convert byte array to long
* @param rawData byte representation of long value
* @return long value
* @throws AvpDataException
*/
long bytesToLong(byte[] rawData) throws AvpDataException;
/**
* Convert byte array to float
* @param rawData byte representation of float value
* @return float value
* @throws AvpDataException
*/
float bytesToFloat(byte[] rawData) throws AvpDataException;
/**
* Convert byte array to double
* @param rawData byte representation of double value
* @return double value
* @throws AvpDataException
*/
double bytesToDouble(byte[] rawData) throws AvpDataException;
/**
* Convert byte array to octet string
* @param rawData byte representation of octet string value
* @return octet string value
* @throws AvpDataException
*/
String bytesToOctetString(byte[] rawData) throws AvpDataException;
/**
* Convert byte array to utf8 string
* @param rawData byte representation of utf8 string value
* @return utf8 string value
* @throws AvpDataException
*/
String bytesToUtf8String(byte[] rawData) throws AvpDataException;
/**
* Convert byte array to date
* @param rawData byte representation of date value
* @return date value
* @throws AvpDataException
*/
Date bytesToDate(byte[] rawData) throws AvpDataException;
/**
* Convert byte array to InetAddress
* @param rawData byte representation of InetAddress value
* @return InetAddress value
* @throws AvpDataException
*/
InetAddress bytesToAddress(byte[] rawData) throws AvpDataException;
/**
* Convert int to byte array representation
* @param value int value
* @return byte array
*/
byte[] int32ToBytes(int value);
/**
* Convert long to 4-byte array representation
* @param value long value
* @return byte array
*/
byte [] intU32ToBytes(long value);
/**
* Convert long to byte array representation
* @param value long value
* @return byte array
*/
byte[] int64ToBytes(long value);
/**
* Convert float to byte array representation
* @param value float value
* @return byte array
*/
byte[] float32ToBytes(float value);
/**
* Convert double to byte array representation
* @param value double value
* @return byte array
*/
byte[] float64ToBytes(double value);
/**
* Convert octet string to byte array representation
* @param value octet string value
* @return byte array
* @throws ParseException
*/
byte[] octetStringToBytes(String value) throws ParseException;
/**
* Convert utf8 string to byte array representation
* @param value utf8 string value
* @return byte array
* @throws ParseException
*/
byte[] utf8StringToBytes(String value) throws ParseException;
/**
* Convert InetAddress to byte array representation
* @param value InetAddress value
* @return byte array
*/
byte[] addressToBytes(InetAddress value);
/**
* Convert Date to byte array representation
* @param value Date value
* @return byte array
*/
byte[] dateToBytes(Date value);
/**
* Convert byte array to specefied object
* @param rawData byte representation of InetAddress value
* @param iface type of object
* @return object instance
* @throws AvpDataException
*/
<T> T bytesToObject(java.lang.Class<?> iface, byte[] rawData) throws AvpDataException;
/**
* Convert specified object to byte array representation
* @param value object
* @return byte array
* @throws ParseException
*/
byte[] objectToBytes(Object value) throws ParseException;
}
| 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.client.api.parser;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.client.api.IMessage;
import java.nio.ByteBuffer;
/**
* Basic interface for diameter message parsers.
*
* @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 IMessageParser {
/**
* Create message from bytebuffer
* @param data message bytebuffer
* @return instance of message
* @throws AvpDataException
*/
IMessage createMessage(ByteBuffer data) throws AvpDataException;
/**
* Created specified type of message
* @param iface type of message
* @param data message bytebuffer
* @return instance of message
* @throws AvpDataException
*/
<T> T createMessage(java.lang.Class<?> iface, ByteBuffer data) throws AvpDataException;
/**
* Created empty message
* @param commandCode message command code
* @param headerAppId header applicatio id
* @return instance of message
*/
IMessage createEmptyMessage(int commandCode, long headerAppId);
/**
* Created specified type of message
* @param iface type of message
* @param commandCode message command code
* @param headerAppId header applicatio id
* @return instance of message
*/
<T> T createEmptyMessage(Class<?> iface, int commandCode, long headerAppId);
/**
* Created new message with copied of header of parent message
* @param parentMessage parent message
* @return instance of message
*/
IMessage createEmptyMessage(IMessage parentMessage);
/**
* Created new message with copied of header of parent message
* @param parentMessage parent message
* @param commandCode new command code value
* @return instance of message
*/
IMessage createEmptyMessage(IMessage parentMessage, int commandCode);
/**
* Created new message with copied of header of parent message
* @param iface type of message
* @param parentMessage parent message
* @return instance of message
*/
<T> T createEmptyMessage(Class<?> iface, IMessage parentMessage);
/**
* Encode message to ByteBuffer
* @param message diameter message
* @return instance of message
* @throws ParseException
*/
ByteBuffer encodeMessage(IMessage message) throws ParseException;
}
| 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.client.api;
/**
* This interface provide IOC functionality
* Data: $Date: 2009/10/10 20:17:57 $
* Revision: $Revision: 1.2 $
*
* @version 1.5.0.1
*
* @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 IAssembler {
/**
* Return parent IOC
*
* @return IOC instance
*/
IAssembler getParent();
/**
* Return all children
*
* @return all children
*/
IAssembler[] getChilds();
/**
* Register new component
*
* @param aClass class of component
* @return instance of component
*/
<T> T getComponentInstance(Class<T> aClass);
/**
* Register new component
*
* @param object instance of component
*/
void registerComponentInstance(Object object);
/**
* Register new component
*
* @param aClass class of component
* @param object instance of component
*/
void registerComponentImplementation(Class<?> aClass, Object object);
/**
* Release all attached resources
*/
void destroy();
}
| 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.client.api;
import org.jdiameter.api.MetaData;
/**
* This interface describe extends methods of base class
* Data: $Date: 2008/07/03 19:43:10 $
* Revision: $Revision: 1.1 $
* @version 1.5.0.1
*
* @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 MetaData {
/**
* Set new value of host state
*/
void updateLocalHostStateId();
/**
* Return host state value
* @return host state value
*/
long getLocalHostStateId();
}
| 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.client.api;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.client.api.controller.IPeer;
/**
* This interface extends basic message interface
* Data: $Date: 2009/07/27 18:05:03 $
* Revision: $Revision: 1.2 $
* @version 1.5.0.1
*
* @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 IMessage extends IRequest, IAnswer {
/**
* The message is not sent to the network
*/
int STATE_NOT_SENT = 0;
/**
* The message has been sent to the network
*/
int STATE_SENT = 1;
/**
* The message is buffered ( not use yet )
*/
int STATE_BUFFERED = 2;
/**
* Stack received answer to this message
*/
int STATE_ANSWERED = 3;
/**
* Return state of message
* @return state of message
*/
int getState();
/**
* Set new state
* @param newState new state value
*/
void setState(int newState);
/**
* Return header applicationId
* @return header applicationId
*/
long getHeaderApplicationId();
/**
* Set header message application id
* @param applicationId header message application id
*/
void setHeaderApplicationId(long applicationId);
/**
* Return flags as inteher
* @return flags as inteher
*/
int getFlags();
/**
* Create timer for request timout procedure
* @param scheduledFacility timer facility
* @param timeOut value of timeout
* @param timeUnit time unit
*/
void createTimer(ScheduledExecutorService scheduledFacility, long timeOut, TimeUnit timeUnit);
/**
* Execute timer task
*/
void runTimer();
/**
* Cancel timer
*/
void clearTimer();
/**
* Set hop by hop id
* @param hopByHopId hopByHopId value
*/
void setHopByHopIdentifier(long hopByHopId);
/**
* Set end by end id
* @param endByEndId endByEndId value
*/
void setEndToEndIdentifier(long endByEndId);
/**
* Return attached peer
* @return attached peer
*/
IPeer getPeer();
/**
* Attach message to peer
* @param peer attached peer
*/
void setPeer(IPeer peer);
/**
* Return application id
* @return application id
*/
ApplicationId getSingleApplicationId();
/**
* Return application id
* @return application id
*/
ApplicationId getSingleApplicationId(long id);
/**
* Check timeout
* @return true if request has timeout
*/
boolean isTimeOut();
/**
* Set event listener
* @param listener event listener
*/
void setListener(IEventListener listener);
/**
* Return event listener
* @return event listener
*/
IEventListener getEventListener();
/**
* Return duplication key of message
* @return duplication key of message
*/
String getDuplicationKey();
/**
* Generate duplication key
* @param host origination host
* @param endToEndId end to end id
* @return duplication key
*/
String getDuplicationKey(String host, long endToEndId);
/**
* Create clone object
* @return clone
*/
Object clone();
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.api.router;
import org.jdiameter.api.AvpDataException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.RouteException;
import org.jdiameter.client.api.IAnswer;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.IRequest;
import org.jdiameter.client.api.controller.IPeer;
import org.jdiameter.client.api.controller.IPeerTable;
import org.jdiameter.client.api.controller.IRealmTable;
/**
* This class describe Router functionality
*
* @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 {
/**
* Return peer from inner peer table by predefined parameters. Fetches peer based on message content, that is HBH or realm/host avp contents.
* Takes into consideration ApplicationId present in message to pick correct realm definition from RealmTable. This method should be called after {@link #updateRoute}.
* @param message message with routed avps
* @param manager instance of peer manager
* @return peer instance
* @throws RouteException
* @throws AvpDataException
*/
IPeer getPeer(IMessage message, IPeerTable manager) throws RouteException, AvpDataException;
/**
* Return realm table
*
* @return object representing realm table
*/
IRealmTable getRealmTable();
/**
* Register route information by received request. This information will be used
* during answer routing.
* @param request request
*/
void registerRequestRouteInfo(IRequest request);
// PCB - Changed to use a better routing mechanism as hopbyhop was not always unique and the table could also grow too big
/**
* Return Request route info
* @param hopByHopIndentifier Hop-by-Hop Identifier
* @return Array (host and realm)
*/
String[] getRequestRouteInfo(IMessage message);
//PCB added
void garbageCollectRequestRouteInfo(IMessage message);
/**
* Start inner time facilities
*/
void start();
/**
* Stop inner time facilities
*/
void stop();
/**
* Release all resources
*/
void destroy();
/**
* Called when redirect answer is received for request. This method update redirect host information and routes to new destination.
* @param request
* @param answer
* @param table
*/
void processRedirectAnswer(IRequest request, IAnswer answer, IPeerTable table) throws InternalException, RouteException;
/**
* Based on Redirect entries or any other factors, this method changes route information.
* @param message
* @return
* @throws RouteException
* @throws AvpDataException
*/
boolean updateRoute(IRequest message) throws RouteException, AvpDataException;
}
| 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.client.api;
import org.jdiameter.api.Request;
/**
* This interface describe extends methods of base class
* Data: $Date: 2008/07/03 19:43:10 $
* Revision: $Revision: 1.1 $
* @version 1.5.0.1
*
* @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 IRequest extends Request {
/**
* Set network request flag
* @param isNetwork true if this request is neteork
*/
void setNetworkRequest(boolean isNetwork);
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.api.controller;
import java.util.Collection;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.LocalAction;
import org.jdiameter.api.Realm;
import org.jdiameter.api.RealmTable;
import org.jdiameter.client.api.IAnswer;
import org.jdiameter.client.api.IRequest;
import org.jdiameter.server.api.agent.IAgentConfiguration;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public interface IRealmTable extends RealmTable {
public Realm matchRealm(IRequest request);
public Realm matchRealm(IAnswer message, String destRealm);
public Realm getRealm(String realmName, ApplicationId applicationId);
public Realm removeRealmApplicationId(String realmName, ApplicationId appId);
public Collection<Realm> removeRealm(String realmName);
public Collection<Realm> getRealms(String realm);
public Collection<Realm> getRealms();
public String getRealmForPeer(String fqdn);
public void addLocalApplicationId(ApplicationId ap);
public void removeLocalApplicationId(ApplicationId a);
public void addLocalRealm(String localRealm, String fqdn);
/**
* Method which accepts IAgentConfiguration to avoid decode, encode, decode sequences
* @param name
* @param appId
* @param locAction
* @param agentConfImpl
* @param isDynamic
* @param expirationTime
* @param hosts
* @return
* @throws InternalException
*/
public Realm addRealm(String name, ApplicationId appId, LocalAction locAction, IAgentConfiguration agentConfImpl, boolean isDynamic, long expirationTime,
String[] hosts) 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.client.api.controller;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Peer;
import org.jdiameter.api.app.StateChangeListener;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.fsm.EventTypes;
import org.jdiameter.client.api.io.IConnectionListener;
import org.jdiameter.client.api.io.TransportException;
import org.jdiameter.common.api.statistic.IStatistic;
/**
* This interface provide additional methods for Peer interface
*
* @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 Peer {
/**
* Return rating of peer
*
* @return int value
*/
int getRating();
/**
* Return new hop by hop id for new message
*
* @return new hop by hop id
*/
long getHopByHopIdentifier();
/**
* Append request to peer request storage map
*
* @param message request instance
*/
void addMessage(IMessage message);
/**
* Remove request from request storage map
*
* @param message request instance
*/
void remMessage(IMessage message);
/**
* Clear request storage map
*/
IMessage[] remAllMessage();
/**
* Put message to peer fsm
*
* @param message request instance
* @return true if message will be set to FSM
* @throws TransportException
* @throws OverloadException
*/
public boolean handleMessage(EventTypes type, IMessage message, String key) throws TransportException, OverloadException, InternalException;
/**
* Send message to diameter network
*
* @param message request instance
* @return true if message will be set to FSM
* @throws TransportException
* @throws OverloadException
*/
boolean sendMessage(IMessage message) throws TransportException, OverloadException, InternalException;
/**
* Return true if peer has valid connection
*
* @return true if peer has valid connection
*/
boolean hasValidConnection();
/**
* Attach peer to realm
*
* @param realm realm name
*/
void setRealm(String realm);
/**
* Add state change listener
*
* @param listener listener instance
*/
void addStateChangeListener(StateChangeListener listener);
/**
* Remove state change listener
*
* @param listener listener instance
*/
void remStateChangeListener(StateChangeListener listener);
/**
* Add connection state change listener
*
* @param listener listener instance
*/
void addConnectionListener(IConnectionListener listener);
/**
* Remove connection state change listener
*
* @param listener listener instance
*/
void remConnectionListener(IConnectionListener listener);
/**
* Return peer statistic
*
* @return peer statistic
*/
IStatistic getStatistic();
/**
* Return if peer is connected
*
* @return is peer connected
*/
boolean isConnected();
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.api.controller;
import org.jdiameter.api.Realm;
import org.jdiameter.server.api.agent.IAgent;
import org.jdiameter.server.api.agent.IAgentConfiguration;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public interface IRealm extends Realm {
/**
* Return list of real peers
*
* @return array of realm peers
*/
public String[] getPeerNames();
/**
* Append new host (peer) to this realm
*
* @param host
* name of peer host
*/
public void addPeerName(String name);
/**
* Remove peer from this realm
*
* @param host
* name of peer host
*/
public void removePeerName(String name);
/**
* Checks if a peer name belongs to this realm
*
* @param name name of peer host
* @return true if the the peer belongs to this realm, false otherwise
*/
public boolean hasPeerName(String name);
/**
* Get the processing agent for this realm
*
* @return the agent for this realm, if any
*/
public IAgent getAgent();
/**
* Get agent configuration values for this realm.
* @return
*/
public IAgentConfiguration getAgentConfiguration();
}
| 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.client.api.controller;
import org.jdiameter.api.*;
import org.jdiameter.client.api.IAssembler;
import org.jdiameter.client.api.IMessage;
import java.io.IOException;
import java.util.Map;
/**
* This interface provide additional methods for PeerTable interface
*
* @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 IPeerTable extends PeerTable {
/**
* Start peer manager ( start network activity )
*
* @throws IllegalDiameterStateException
* @throws IOException
*/
void start() throws IllegalDiameterStateException, IOException;
/**
* Run stopping procedure (unsynchronized)
*/
void stopping(int disconnectCause);
/**
* Release resources
*/
void stopped();
/**
* Destroy all resources
*/
void destroy();
/**
* Send message to diameter network ( routing procedure )
*
* @param message message instance
* @throws IllegalDiameterStateException
* @throws IOException
* @throws RouteException
* @throws AvpDataException
*/
void sendMessage(IMessage message) throws IllegalDiameterStateException, IOException, RouteException, AvpDataException;
/**
* Register session lister
*
* @param sessionId session id
* @param listener listener listener
*/
void addSessionReqListener(String sessionId, NetworkReqListener listener);
/**
* Return peer from peer table by identity - FQDN host name.
*
* @param fqdn peer host
* @return peer instance
*/
IPeer getPeer(String fqdn);
/**
* Return map of session event listeners
*
* @return map of session event listeners
*/
Map<String, NetworkReqListener> getSessionReqListeners();
/**
* Remove session event listener
*
* @param sessionId id of session
*/
void removeSessionListener(String sessionId);
/**
* Set instance assembler
*
* @param assembler assembler instance
*/
void setAssembler(IAssembler assembler);
}
| 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.client.api;
/**
* This enumeration describe avaliable states of stack
* Data: $Date: 2008/07/03 19:43:10 $
* Revision: $Revision: 1.1 $
* @version 1.5.0.1
*
* @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 enum StackState {
IDLE, CONFIGURED, STARTED, STOPPED
}
| 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.client.api.fsm;
import org.jdiameter.api.app.StateChangeListener;
import org.jdiameter.api.app.StateMachine;
import org.jdiameter.common.api.statistic.IStatistic;
/**
* This interface extends StateMachine interface
*
* @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 StateMachine {
/**
* This method returns occupancy of event queue
* @return occupancy of event queue
*/
double getQueueInfo();
void remStateChangeNotification(StateChangeListener listener);
public IStatistic getStatistic();
}
| 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.client.api.fsm;
import org.jdiameter.api.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Message;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.io.TransportException;
import java.io.IOException;
/**
* This interface describe operations of FSM context object
*
* @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 IContext {
/**
* Start connection procedure to remote peer
* @throws InternalException
* @throws IOException
* @throws org.jdiameter.api.IllegalDiameterStateException
*/
void connect() throws InternalException, IOException, IllegalDiameterStateException;
/**
* Start disconnect procedure from remote peer
* @throws InternalException
* @throws org.jdiameter.api.IllegalDiameterStateException
*/
void disconnect() throws InternalException, IllegalDiameterStateException;
/**
* This method allow sent message to remote peer
* @param message message which one should be sent to remote peer
* @throws TransportException
* @throws OverloadException
*/
boolean sendMessage(IMessage message) throws TransportException, OverloadException;
/**
* This method allow sent CER command to remote peer
* @throws TransportException
* @throws OverloadException
*/
void sendCerMessage() throws TransportException, OverloadException;
/**
* This method allow sent CEA command to remote peer
* @param resultCode value for result-code Avp
* @param errMessage value for error-message Avp
* @throws TransportException
* @throws OverloadException
*/
void sendCeaMessage(int resultCode, Message cer, String errMessage) throws TransportException, OverloadException;
/**
* This method allow sent DWR command to remote peer
* @throws TransportException
* @throws OverloadException
*/
void sendDwrMessage() throws TransportException, OverloadException;
/**
* This method allow sent DWA command to remote peer
* @param dwr parent DWR command receved from remote peer
* @param resultCode value for result-code avp
* @param errorMessage value for error-message avp
* @throws TransportException
* @throws OverloadException
*/
void sendDwaMessage(IMessage dwr, int resultCode, String errorMessage) throws TransportException, OverloadException;
/**
* This method allow sent DPR command to remote peer
* @param disconnectCause value for disconnect-cause avp
* @throws TransportException
* @throws OverloadException
*/
void sendDprMessage(int disconnectCause) throws TransportException, OverloadException;
/**
* This method allow sent DPA command to remote peer
* @param dpr parent DPR command receved from remote peer
* @param resultCode value for result-code avp
* @param errorMessage value for error-message avp
* @throws TransportException
* @throws OverloadException
*/
void sendDpaMessage(IMessage dpr, int resultCode, String errorMessage) throws TransportException, OverloadException;
/**
* This method allow processed message from to remote peer
* @param iMessage message from remote peer
* @return true if message correct processed
*/
boolean receiveMessage(IMessage iMessage);
/**
* This method call when peer instance receive DWR event
* @param iMessage message
* @return result code With this code stack will be send DWA message
*/
int processDwrMessage(IMessage iMessage);
/**
* This method call when peer instance receive DPR event
* @param iMessage message
* @return result code With this code stack will be send DPA message
*/
int processDprMessage(IMessage iMessage);
/**
* This method allow sent CEA command to remote peer
* @param key connection key (host + ":" + port)
* @param message
* @return true if the message is sent to remote peer
*/
boolean processCeaMessage(String key, IMessage message);
/**
* This method allow processed CER command from remote peer
* @param key connection key (host + ":" + port)
* @param message received from remote host
* @return result-code for CEA message or -1 if message can not be processed
*/
int processCerMessage(String key, IMessage message);
/**
* Return true if connection should be restored
* Look AttemptToConnect property of peer
* @return true if connection should be restored
*/
boolean isRestoreConnection();
/**
* Reeturn true if connection already created and connected
* @return true if connection already created and connected
*/
boolean isConnected();
/**
* Return parent peer description
* @return parent peer description
*/
String getPeerDescription();
/**
* Clears statistics for context
*/
void removeStatistics();
/**
* Creates statistics for context
*/
void createStatistics();
}
| 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.client.api.fsm;
/**
* This enumeration describe all fsm events
*
* @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 enum EventTypes {
/**
* Connect event
*/
CONNECT_EVENT (true),
/**
* Disconnect event
*/
DISCONNECT_EVENT (true),
/**
* Operation timeout event
*/
TIMEOUT_EVENT (true),
/**
* Start fsm event
*/
START_EVENT(true),
/**
* Stop fsm event
*/
STOP_EVENT (true),
/**
* Internal error during processing event
*/
INTERNAL_ERROR(true),
/**
* Stack received CER message
*/
CER_EVENT,
/**
* Stack received CEA message
*/
CEA_EVENT,
/**
* Stack received DPR message
*/
DPR_EVENT,
/**
* Stack received DPA message
*/
DPA_EVENT,
/**
* Stack received DWR message
*/
DWR_EVENT,
/**
* Stack received DWA message
*/
DWA_EVENT,
/**
* App send message to network
*/
SEND_MSG_EVENT,
/**
* Stack received Application message
*/
RECEIVE_MSG_EVENT;
boolean highPriority = false;
EventTypes() {
highPriority = false;
}
EventTypes(boolean highPriority) {
this.highPriority = highPriority;
}
public boolean isHighPriority() {
return highPriority;
}
}
| 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.client.api.fsm;
import java.util.concurrent.ExecutorService;
/**
*
* @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 ExecutorFactory {
ExecutorService getExecutor();
}
| 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.client.api.fsm;
import org.jdiameter.api.Configuration;
import org.jdiameter.api.InternalException;
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 {
/**
* Create instance of Peer FSM
*
* @param context FSM context object
* @param concurrentFactory executor facility
* @param config configuration
* @return State machine instance
* @throws InternalException
*/
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.client.api.fsm;
import org.jdiameter.api.app.StateEvent;
import org.jdiameter.client.api.IMessage;
/**
* This class extends behaviour of FSM 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>
*/
public class FsmEvent implements StateEvent {
private String key;
private EventTypes type;
private Object value;
private final long createdTime = System.currentTimeMillis();
/**
* Create instance of class
*
* @param type type of event
*/
public FsmEvent(EventTypes type) {
this.type = type;
}
/**
* Create instance of class with predefined parameters
*
* @param type type of event
* @param key event key
*/
public FsmEvent(EventTypes type, String key) {
this(type);
this.key = key;
}
/**
* Create instance of class with predefined parameters
*
* @param type type of event
* @param value attached message
*/
public FsmEvent(EventTypes type, IMessage value) {
this(type);
this.value = value;
}
/**
* Create instance of class with predefined parameters
*
* @param type type of event
* @param value attached message
* @param key event key
*/
public FsmEvent(EventTypes type, IMessage value, String key) {
this(type, value);
this.key = key;
}
/**
* Return key value
*
* @return key value
*/
public String getKey() {
return key;
}
/**
* Return attached message
*
* @return diameter message
*/
public IMessage getMessage() {
return (IMessage) getData();
}
/**
* Return created time
*
* @return created time
*/
public long getCreatedTime() {
return createdTime;
}
public <E> E encodeType(Class<E> eClass) {
return (E) type;
}
public Enum getType() {
return type;
}
public void setData(Object o) {
value = o;
}
public Object getData() {
return value;
}
public int compareTo(Object o) {
return 0;
}
/**
* Return string representation of instance
*
* @return string representation of instance
*/
public String toString() {
return "Event{name:" + type.name() + ", key:" + key + ", object:" + 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.client.api;
import org.jdiameter.api.Answer;
/**
* This interface describe extends methods of base class
* Now is empty
* Data: $Date: 2008/07/03 19:43:10 $
* Revision: $Revision: 1.1 $
* @version 1.5.0.1
*
* @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 IAnswer extends 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.client.api;
import org.jdiameter.api.*;
import org.jdiameter.common.api.concurrent.IConcurrentFactory;
import java.io.IOException;
import java.util.concurrent.ScheduledExecutorService;
/**
* This interface extends behavior of stack interface
* Data: $Date: 2008/07/03 19:43:10 $
* Revision: $Revision: 1.1 $
* @version 1.5.0.1
*
* @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 IContainer extends Stack {
/**
* Return state of stack
* @return Return state of stack
*/
StackState getState();
/**
* Return configuration instance
* @return configuration instance
*/
Configuration getConfiguration();
/**
* Return root IOC
* @return root IOC
*/
IAssembler getAssemblerFacility();
/**
* Return common Scheduled Executor Service
* @return common Scheduled Executor Service
*/
ScheduledExecutorService getScheduledFacility();
/**
* Return common concurrent factory
* @return
*/
IConcurrentFactory getConcurrentFactory();
/**
* Send message
* @param session session instance
* @throws RouteException
* @throws AvpDataException
* @throws IllegalDiameterStateException
* @throws IOException
*/
void sendMessage(IMessage session) throws RouteException, AvpDataException, IllegalDiameterStateException, IOException;
/**
* Add session listener
* @param sessionId session id
* @param listener listener instance
*/
public void addSessionListener(String sessionId, NetworkReqListener listener);
/**
* Remove session event listener by sessionId
* @param sessionId session identifier
*/
void removeSessionListener(String sessionId);
}
| 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.client.api.io;
/**
* Signals that an exception has occurred in a during start
* transport element. An <code>NotInitializedException</code> is thrown to indicate that
* transport element is not configured.
*
* @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 NotInitializedException extends Exception{
/**
* Create instance of class
*/
public NotInitializedException() {
super();
}
/**
* Create instance of class with predefined parameters
* @param message error message
*/
public NotInitializedException(String message) {
super(message);
}
/**
* Create instance of class with predefined parameters
* @param message error message
* @param cause error cause
*/
public NotInitializedException(String message, Throwable cause) {
super(message, cause);
}
/**
* Create instance of class with predefined parameters
* @param cause error cause
*/
public NotInitializedException(Throwable cause) {
super(cause);
}
}
| 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.client.api.io;
import org.jdiameter.api.Wrapper;
import org.jdiameter.common.api.concurrent.IConcurrentFactory;
import java.net.InetAddress;
/**
* Factory of Network Layer elements.
* Configuration and message parser instances injection by 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 Wrapper {
/**
* Create new IConnection instance with predefined parameters
*
* @param remoteAddress destination host address
* @param factory concurrent factory
* @param remotePort destination port address
* @param localAddress local network adapter address
* @param localPort local socket port
* @param ref reference to additional parameters
* @return IConnection instance
* @throws TransportException
*/
IConnection createConnection(InetAddress remoteAddress, IConcurrentFactory factory, int remotePort, InetAddress localAddress, int localPort, String ref) throws TransportException;
/**
* Create new IConnection instance with predefined parameters
*
* @param remoteAddress destination host address
* @param factory concurrent factory
* @param remotePort destination port address
* @param localAddress local network adapter address
* @param localPort local socket port
* @param listener connection listener instance
* @param ref reference to additional parameters
* @return IConnection instance
* @throws TransportException
*/
IConnection createConnection(InetAddress remoteAddress, IConcurrentFactory factory, int remotePort, InetAddress localAddress, int localPort, IConnectionListener listener, String ref) 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.client.api.io;
/**
* This enumeration describe types on network errors
* These types help to more details define behaviour of high layers
*
* @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 enum TransportError {
/**
* Internal error (network layer exceptions)
*/
Internal,
/**
* Overload errors (overload netowrk queues)
*/
Overload,
/**
* Error during send message procedure (special type)
*/
FailedSendMessage,
/**
* Received broken message (special type)
*/
ReceivedBrokenMessage,
/**
* Network error (io exceptions)
*/
NetWorkError
}
| 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.client.api.io;
import org.jdiameter.client.api.IMessage;
import java.util.List;
/**
* <P>
* An object that registers to be notified of events generated by a
* <code>IConnection</code> object.
* <P>
* The <code>ConnectionListener</code> interface is implemented by a
* PCB component.
*
* @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 IConnectionListener {
/**
* Notifies that connection is created
* @param connKey identifier of created connection
*/
void connectionOpened(String connKey);
/**
* Notifies that connection is closed
* @param connKey identifier of closed connection
* @param notSended array of not sended messages
*/
void connectionClosed(String connKey, List notSended);
/**
* Notifies that connection is received incoming message
* @param connKey identifier of connection
* @param message received incoming message
*/
void messageReceived(String connKey, IMessage message);
/**
* Notifies that connection is generated excpetion
* @param connKey identifier of connection
* @param message the message from that failed
* @param cause generated exceptions
*/
void internalError(String connKey, IMessage message, TransportException cause);
}
| 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.client.api.io;
/**
* Signals that an transport exception has occurred in a during initialize
* transport element.
*
* @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 TransportException extends Exception{
/**
* Error code
*/
TransportError code;
/**
* Create instance of class with predefined parameters
* @param message error message
* @param code error code
*/
public TransportException(String message, TransportError code) {
super(message);
this.code = code;
}
/**
* Create instance of class with predefined parameters
* @param message error message
* @param code error code
* @param cause error cause
*/
public TransportException(String message, TransportError code, Throwable cause) {
super(message, cause);
this.code = code;
}
/**
* Create instance of class with predefined parameters
* @param code error code
* @param cause error cause
*/
public TransportException(TransportError code, Throwable cause) {
super(cause);
this.code = code;
}
/**
* Return code of error
* @return code of error
*/
public TransportError getCode() {
return code;
}
}
| 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.client.api.io;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Wrapper;
import org.jdiameter.client.api.IMessage;
import java.io.IOException;
import java.net.InetAddress;
/**
* A Connection with a remote host.
*
* @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 IConnection extends Wrapper {
/**
* Return created time
* @return created time
*/
public long getCreatedTime();
/**
* Return identifier of connection. For example:
* "[remote_host_name]:[remote_port]"
* @return identifier of connection.
*/
String getKey();
/**
* Connect with remote host
* @throws TransportException
*/
void connect() throws TransportException;
/**
* Disconnect wit remote host
* @throws InternalError
*/
void disconnect() throws InternalError;
/**
* Send message to remote host
* @param message diameter message
* @throws TransportException
* @throws OverloadException
*/
void sendMessage(IMessage message) throws TransportException, OverloadException;
/**
* Clear all attachec resources (close socket)
* @throws IOException
*/
void release() throws IOException;
/**
* Return true if connection is incomming
* @return true if connection is incomming
*/
boolean isNetworkInitiated();
/**
* Return true if is connection is valid
* @return true if is connection is valid
*/
boolean isConnected();
/**
* Return remote host address
* @return remote host address
*/
InetAddress getRemoteAddress();
/**
* Return remote socket port
* @return remote socket port
*/
int getRemotePort();
/**
* Append connection listener
* @param connectionListener listener instance
*/
void addConnectionListener(IConnectionListener connectionListener);
/**
* Remove all connection listeners
*/
void remAllConnectionListener();
/**
* Remove connection listener
* @param connectionListener listener instance
*/
void remConnectionListener(IConnectionListener connectionListener);
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jdiameter.client.api;
import org.jdiameter.api.ApplicationId;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.SessionFactory;
import org.jdiameter.api.app.AppSession;
import org.jdiameter.common.api.app.IAppSessionFactory;
/**
* This interface describe extends methods of base class
*
* @version 1.5.0.1
*
* @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 ISessionFactory extends SessionFactory {
/**
* Method used for creating a new App Session using the specified class with the
* desired Application Id and Session Id.
*
* @param sessionId the session-id for this App Session, if desired
* @param applicationId the application id for this session
* @param aClass the class of the app session object
* @param args
* @return an AppSession instance
* @throws InternalException
*/
<T extends AppSession> T getNewAppSession(String sessionId, ApplicationId applicationId, Class<? extends AppSession> aClass,
Object... args) throws InternalException;
/**
* Registers a new App Session factory.
*
* @param sessionClass the class of the objects being generated by the factory
* @param factory the factory to generate app sessions
*/
void registerAppFacory(Class<? extends AppSession> sessionClass, IAppSessionFactory factory);
/**
* Unregisters an existing App Session factory.
*
* @param sessionClass the class identifier for this factory
*/
void unRegisterAppFacory(Class<? extends AppSession> sessionClass);
/**
* Retrieves the app session factory associated with an app session class
*
* @param sessionClass the class identifier for the desired factory
* @return the App Session Factory instance if registered,
* null if no factory is registered for such class
*/
IAppSessionFactory getAppSessionFactory(Class<? extends AppSession> sessionClass);
/**
*
* @return
*/
IContainer getContainer();
}
| 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;
import static org.jdiameter.client.impl.helpers.Parameters.PeerName;
import static org.jdiameter.client.impl.helpers.Parameters.PeerTable;
import static org.jdiameter.client.impl.helpers.Parameters.StopTimeOut;
import static org.jdiameter.client.impl.helpers.Parameters.UseUriAsFqdn;
import static org.jdiameter.common.api.concurrent.IConcurrentFactory.ScheduledExecServices.ConnectionTimer;
import static org.jdiameter.common.api.concurrent.IConcurrentFactory.ScheduledExecServices.DuplicationMessageTimer;
import static org.jdiameter.common.api.concurrent.IConcurrentFactory.ScheduledExecServices.PeerOverloadTimer;
import static org.jdiameter.server.impl.helpers.Parameters.AcceptUndefinedPeer;
import static org.jdiameter.server.impl.helpers.Parameters.DuplicateProtection;
import static org.jdiameter.server.impl.helpers.Parameters.DuplicateSize;
import static org.jdiameter.server.impl.helpers.Parameters.DuplicateTimer;
import static org.jdiameter.server.impl.helpers.Parameters.PeerAttemptConnection;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URISyntaxException;
import java.net.UnknownServiceException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
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.IllegalDiameterStateException;
import org.jdiameter.api.InternalException;
import org.jdiameter.api.Message;
import org.jdiameter.api.MetaData;
import org.jdiameter.api.MutableConfiguration;
import org.jdiameter.api.MutablePeerTable;
import org.jdiameter.api.Network;
import org.jdiameter.api.Peer;
import org.jdiameter.api.PeerState;
import org.jdiameter.api.PeerTableListener;
import org.jdiameter.api.Realm;
import org.jdiameter.api.Statistic;
import org.jdiameter.api.URI;
import org.jdiameter.client.api.IContainer;
import org.jdiameter.client.api.IMessage;
import org.jdiameter.client.api.ISessionFactory;
import org.jdiameter.client.api.StackState;
import org.jdiameter.client.api.controller.IRealm;
import org.jdiameter.client.api.fsm.EventTypes;
import org.jdiameter.client.api.io.IConnection;
import org.jdiameter.client.api.io.IConnectionListener;
import org.jdiameter.client.api.io.TransportException;
import org.jdiameter.client.api.parser.IMessageParser;
import org.jdiameter.client.impl.controller.PeerTableImpl;
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.IMutablePeerTable;
import org.jdiameter.server.api.INetwork;
import org.jdiameter.server.api.IOverloadManager;
import org.jdiameter.server.api.IPeer;
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.EmptyConfiguration;
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 MutablePeerTableImpl extends PeerTableImpl implements IMutablePeerTable, ConfigurationListener {
private static final Logger logger = LoggerFactory.getLogger(MutablePeerTableImpl.class);
private static final int CONN_INVALIDATE_PERIOD = 60000;
private static final int MAX_PEER_TABLE_SIZE = 10000;
protected Configuration config;
protected ISessionFactory sessionFactory;
protected IFsmFactory fsmFactory;
protected ITransportLayerFactory transportFactory;
protected IMessageParser parser;
protected org.jdiameter.server.api.IRouter router;
// Duplicate handling -------------------------------------------------------
protected boolean duplicateProtection = false;
protected int duplicateSize;
protected long duplicateTimer;
protected ScheduledExecutorService duplicationScheduler = null;
protected ScheduledFuture duplicationHandler = null;
protected ConcurrentHashMap<String, StorageEntry> storageAnswers = new ConcurrentHashMap<String, StorageEntry>();
protected boolean isAcceptUndefinedPeer = false;
// Connections handling -----------------------------------------------------
private ConcurrentHashMap<String, IConnection> incConnections;
private ScheduledExecutorService connScheduler;
private ScheduledFuture connHandler;
// Network management -------------------------------------------------------
protected INetworkGuard networkGuard;
protected INetwork network;
protected Set<String> predefinedPeerTable;
// Overload handling --------------------------------------------------------
protected IOverloadManager ovrManager;
protected ScheduledExecutorService overloadScheduler = null;
protected ScheduledFuture overloadHandler = null;
protected PeerTableListener peerTableListener = null;
protected IStatisticManager statisticFactory;
private IContainer stack;
protected class StorageEntry {
private String duplicationKey;
private long time = System.currentTimeMillis();
private IMessage answer;
public StorageEntry(IMessage message) {
answer = message;
// duplicationKey = message.getDuplicationKey(); doesn't work because it's answer
String[] originInfo = router.getRequestRouteInfo(answer);
duplicationKey = message.getDuplicationKey(originInfo[0], message.getEndToEndIdentifier());
}
public IMessage getMessage() {
return answer;
}
public long getTime() {
return time;
}
public String getDuplicationKey() {
return duplicationKey;
}
}
public MutablePeerTableImpl(Configuration config, MetaData metaData,IContainer stack, org.jdiameter.server.api.IRouter router,
ISessionFactory sessionFactory, IFsmFactory fsmFactory, ITransportLayerFactory trFactory,
IMessageParser parser, INetwork network, IOverloadManager ovrManager,
IStatisticManager statisticFactory, IConcurrentFactory concurrentFactory) {
logger.debug("MutablePeerTableImpl is being created");
this.metaData = metaData;
this.config = config;
this.router = router;
this.sessionFactory = sessionFactory;
this.statisticFactory = statisticFactory;
this.concurrentFactory = concurrentFactory;
this.fsmFactory = fsmFactory;
this.transportFactory = trFactory;
this.parser = parser;
this.network = network;
this.ovrManager = ovrManager;
this.network.setPeerManager(this);
this.stack = stack;
this.isAcceptUndefinedPeer = config.getBooleanValue(AcceptUndefinedPeer.ordinal(), false);
this.duplicateProtection = config.getBooleanValue(DuplicateProtection.ordinal(), (Boolean) DuplicateProtection.defValue());
if (this.duplicateProtection) {
this.duplicateTimer = config.getLongValue(DuplicateTimer.ordinal(), (Long) DuplicateTimer.defValue());
this.duplicateSize = config.getIntValue(DuplicateSize.ordinal(), (Integer) DuplicateSize.defValue());
}
logger.debug("Duplicate Protection Configuration: Enabled? {}, Timer: {}, Size: {}", new Object[]{this.duplicateProtection, this.duplicateTimer, this.duplicateSize});
if (predefinedPeerTable == null) {
predefinedPeerTable = new CopyOnWriteArraySet<String>();
}
if (config instanceof MutableConfiguration) {
((MutableConfiguration) config).addChangeListener(this);
}
logger.debug("MutablePeerTableImpl is starting initialisation by calling init on super class");
init(stack,router, config, metaData, fsmFactory, transportFactory, statisticFactory, concurrentFactory, parser);
logger.debug("MutablePeerTableImpl has finished initialisation");
}
@Override
protected Peer createPeer(int rating, String uri, String ip, String portRange, MetaData metaData, Configuration globalConfig,
Configuration peerConfig, org.jdiameter.client.api.fsm.IFsmFactory fsmFactory,
org.jdiameter.client.api.io.ITransportLayerFactory transportFactory,
IStatisticManager statisticFactory, IConcurrentFactory concurrentFactory,
IMessageParser parser) throws InternalException, TransportException, URISyntaxException, UnknownServiceException {
logger.debug("Creating Peer for URI [{}]", uri);
if (predefinedPeerTable == null) {
logger.debug("Creating new empty predefined peer table");
predefinedPeerTable = new CopyOnWriteArraySet<String>();
}
logger.debug("Adding URI [{}] to predefinedPeerTable", uri);
predefinedPeerTable.add(new URI(uri).getFQDN());
if (peerConfig.getBooleanValue(PeerAttemptConnection.ordinal(), false)) {
logger.debug("Peer at URI [{}] is configured to attempt a connection (i.e. acting as a client) and a new peer instance will be created and returned", uri);
return newPeerInstance(rating, new URI(uri), ip, portRange, true, null,
metaData, globalConfig, peerConfig, (IFsmFactory) fsmFactory,
(ITransportLayerFactory) transportFactory, parser, statisticFactory, concurrentFactory);
}
else {
logger.debug("Peer at URI [{}] is configured to NOT attempt a connection (i.e. acting as a server) and null will be returned", uri);
return null;
}
}
protected IPeer newPeerInstance(int rating, URI uri, String ip, String portRange, boolean attCnn, IConnection connection,
MetaData metaData, Configuration globalConfig, Configuration peerConfig, IFsmFactory fsmFactory,
ITransportLayerFactory transportFactory, IMessageParser parser,
IStatisticManager statisticFactory, IConcurrentFactory concurrentFactory) throws URISyntaxException, UnknownServiceException, InternalException, TransportException {
logger.debug("Creating and returning a new Peer Instance for URI [{}].", uri);
return new org.jdiameter.server.impl.PeerImpl(
rating, uri, ip, portRange, attCnn, connection,
this, (org.jdiameter.server.api.IMetaData) metaData, globalConfig, peerConfig, sessionFactory,
fsmFactory, transportFactory, statisticFactory, concurrentFactory, parser, network, ovrManager, sessionDatasource
);
}
public void setPeerTableListener(PeerTableListener peerTableListener) {
this.peerTableListener = peerTableListener;
}
public boolean elementChanged(int i, Object data) {
Configuration newConf = (Configuration) data;
stopTimeOut = newConf.getLongValue(StopTimeOut.ordinal(), (Long) StopTimeOut.defValue());
duplicateTimer = newConf.getLongValue(DuplicateTimer.ordinal(), (Long) DuplicateTimer.defValue());
isAcceptUndefinedPeer = newConf.getBooleanValue(AcceptUndefinedPeer.ordinal(), false);
return true;
}
public boolean isDuplicateProtection() {
return duplicateProtection;
}
public void start() throws IllegalDiameterStateException, IOException { // TODO: use parent method
logger.debug("Starting MutablePeerTableImpl. Starting router, overload scheduler, connection check timer, etc.");
router.start();
// Start overload manager
overloadScheduler = concurrentFactory.getScheduledExecutorService(PeerOverloadTimer.name());
Runnable overloadTask = new Runnable() {
public void run() {
if (ovrManager != null) {
for (Peer p : peerTable.values()) {
((IPeer) p).notifyOvrManager(ovrManager);
}
}
}
};
overloadHandler = overloadScheduler.scheduleAtFixedRate(overloadTask, 0, 1, TimeUnit.SECONDS);
// Start duplication protection procedure
if (duplicateProtection) {
duplicationScheduler = concurrentFactory.getScheduledExecutorService(DuplicationMessageTimer.name());
Runnable duplicateTask = new Runnable() {
public void run() {
long now = System.currentTimeMillis();
if(logger.isDebugEnabled()) {
logger.debug("Running Duplicate Cleaning Task. Duplicate Storage size is: {}. Removing entries with time <= '{}'", storageAnswers.size(), now - duplicateTimer);
}
for (StorageEntry s : storageAnswers.values()) {
if (s != null && s.getTime() + duplicateTimer <= now) {
if(logger.isTraceEnabled()) {
logger.trace("Duplicate Cleaning Task - Removing Entry with key '{}' and time '{}'", s.getDuplicationKey(), s.getTime());
}
storageAnswers.remove(s.getDuplicationKey());
}
else {
if(logger.isTraceEnabled()) {
logger.trace("Duplicate Cleaning Task - Skipping Entry with key '{}' and time '{}'", s.getDuplicationKey(), s.getTime());
}
}
}
if(logger.isDebugEnabled()) {
logger.debug("Completed Duplicate Cleaning Task. New Duplicate Storage size is: {}. Total task runtime: {}ms", storageAnswers.size(), System.currentTimeMillis() - now);
}
}
};
duplicationHandler = duplicationScheduler.scheduleAtFixedRate(duplicateTask, duplicateTimer, duplicateTimer, TimeUnit.MILLISECONDS);
}
//
connScheduler = concurrentFactory.getScheduledExecutorService(ConnectionTimer.name());
Runnable connectionCheckTask = new Runnable() {
public void run() {
Map<String, IConnection> connections = getIncConnections();
for (IConnection connection : connections.values()) {
if (System.currentTimeMillis() - connection.getCreatedTime() >= CONN_INVALIDATE_PERIOD) {
logger.debug("External connection released by timeout [{}]", connection.getKey());
try {
connection.remAllConnectionListener();
connection.release();
}
catch (IOException e) {
logger.debug("Unable to release connection", e);
}
connections.remove(connection.getKey());
}
}
}
};
connHandler = connScheduler.scheduleAtFixedRate(connectionCheckTask, CONN_INVALIDATE_PERIOD, CONN_INVALIDATE_PERIOD, TimeUnit.MILLISECONDS);
// Start server socket
try {
logger.debug("Creating network guard");
networkGuard = createNetworkGuard(transportFactory);
}
catch (TransportException e) {
// We want the root cause, that's what matters to us...
Throwable t = e;
while (t.getCause() != null) {
t = t.getCause();
}
Peer p = stack.getMetaData().getLocalPeer();
String ips = "";
for(InetAddress ip : p.getIPAddresses()) {
ips += " " + ip.getHostAddress() + ":" + p.getUri().getPort();
}
logger.error("Unable to create server socket for LocalPeer '{}' at{} ({}).", new Object[]{p.getUri().getFQDN(), ips, t.getMessage()});
logger.debug("Unable to create server socket", e);
}
// Connect to predefined peers
for (Peer p : peerTable.values()) {
try {
if(((IPeer) p).isAttemptConnection()) {
p.connect();
}
}
catch (Exception e) {
logger.warn("Unable to start connect procedure for peer [" + p + "]", e);
}
}
isStarted = true;
}
public Set<String> getPredefinedPeerTable() {
return predefinedPeerTable;
}
public ConcurrentHashMap<String, IConnection> getIncConnections() {
if (incConnections == null) {
incConnections = new ConcurrentHashMap<String, IConnection>();
}
return incConnections;
}
private final Object regLock = new Object();
private INetworkGuard createNetworkGuard(final ITransportLayerFactory transportFactory) throws TransportException {
return transportFactory.createNetworkGuard(
metaData.getLocalPeer().getIPAddresses(),
metaData.getLocalPeer().getUri().getPort(),
new INetworkConnectionListener() {
public void newNetworkConnection(final IConnection connection) {
//PCB added logging
logger.debug("newNetworkConnection. connection [{}]", connection.getKey());
synchronized (regLock) {
final IConnectionListener listener = new IConnectionListener() {
public void connectionOpened(String connKey) {
logger.debug("Connection [{}] opened", connKey);
}
@SuppressWarnings("unchecked")
public void connectionClosed(String connKey, List notSended) {
logger.debug("Connection [{}] closed", connKey);
unregister(true);
}
public void messageReceived(String connKey, IMessage message) {
logger.debug("Message [{}] received to peer [{}]", message, connKey);
if (message.isRequest() && message.getCommandCode() == Message.CAPABILITIES_EXCHANGE_REQUEST) {
connection.remConnectionListener(this);
IPeer peer = null;
String host;
try {
host = message.getAvps().getAvp(Avp.ORIGIN_HOST).getDiameterIdentity();
logger.debug("Origin-Host in new received message is [{}]", host);
}
catch (AvpDataException e) {
logger.warn("Unable to retrieve find Origin-Host AVP in CER", e);
unregister(true);
return;
}
String realm;
try {
realm = message.getAvps().getAvp(Avp.ORIGIN_REALM).getDiameterIdentity();
logger.debug("Origin-Realm in new received message is [{}]", realm);
} catch (AvpDataException e) {
logger.warn("Unable to retrieve find Origin-Realm AVP in CER", e);
unregister(true);
return;
}
boolean foundInPredefinedTable = false;
// find into predefined table
for (String fqdn : predefinedPeerTable) {
if(logger.isDebugEnabled()) {
logger.debug("Checking against entry in predefinedPeerTable with FQDN [{}]", fqdn);
}
if (fqdn.equals(host)) {
if(logger.isDebugEnabled()) {
logger.debug("{} == {}", fqdn, host);
}
peer = (IPeer) peerTable.get(fqdn);
foundInPredefinedTable = true; // found but not init
break;
}
else {
if(logger.isDebugEnabled()) {
logger.debug("{} != {}", fqdn, host);
}
}
}
// find in peer table for peer already connected to server but not removed
if (peer == null) {
logger.debug("Peer with FQDN [{}] was not found in predefined peer table. Checking at (previously) connected peers table", host);
peer = (IPeer) peerTable.get(host);
if (peer != null) {
logger.debug("Got peer for FQDN [{}]. Is connection open ? {}.", host, peer.hasValidConnection());
}
else {
logger.debug("Still haven't found peer for FQDN [{}]", host);
}
}
if (peer != null) {
//FIXME: define procedure when 'peer.getRealm() != realm'
logger.debug("Add [{}] connection to peer [{}]", connection, peer);
peer.addIncomingConnection(connection);
try {
logger.debug("Handle [{}] message on peer [{}]", message, peer);
peer.handleMessage(message.isRequest() ? EventTypes.CER_EVENT : EventTypes.CER_EVENT, message, connKey);
}
catch (Exception e) {
logger.debug("Unable to process CER message", e);
}
}
else {
if (isAcceptUndefinedPeer || foundInPredefinedTable) {
try {
int port = connection.getRemotePort();
boolean hostAsUri = config.getBooleanValue(UseUriAsFqdn.ordinal(), (Boolean) UseUriAsFqdn.defValue());
URI uri;
if (hostAsUri || host.startsWith("aaa://")) {
uri = new URI(host);
}
else {
uri = new URI("aaa://" + host + ":" + port);
}
peer = newPeerInstance(0, uri, connection.getRemoteAddress().getHostAddress(), null, false, connection,
metaData, config, null, fsmFactory, transportFactory, parser, statisticFactory, concurrentFactory);
logger.debug("Created new peer instance [{}] and adding to peer table", peer);
peer.setRealm(realm);
appendPeerToPeerTable(peer);
logger.debug("Handle [{}] message on peer [{}]", message, peer);
peer.handleMessage(message.isRequest() ? EventTypes.CER_EVENT : EventTypes.CER_EVENT, message, connKey);
}
catch (Exception e) {
logger.warn("Unable to create peer", e);
unregister(true);
}
}
else {
logger.info("Skip anonymous connection [{}]", connection);
unregister(true);
}
}
}
else {
logger.debug("Unknown message [{}] by connection [{}]", message, connKey);
unregister(true);
}
}
public void internalError(String connKey, IMessage message, TransportException cause) {
logger.debug("Connection [{}] internalError [{}]", connKey, cause);
unregister(true);
}
public void unregister(boolean release) {
getIncConnections().remove(connection.getKey());
connection.remConnectionListener(this);
if (release && connection.isConnected()) {
try {
connection.release();
}
catch (IOException e) {
logger.debug("Unable to release connection [{}]", connection);
}
}
}
};
//PCB added logging
String connKey = connection.getKey();
getIncConnections().put(connection.getKey(), connection);
logger.debug("Inserted connection [{}] into IncConnections", connKey);
connection.addConnectionListener(listener);
logger.debug("Added listener [{}] to connection [{}]", listener, connKey);
}
}
}
);
}
private void appendPeerToPeerTable(IPeer peer) {
logger.debug("Adding Peer[{}] to PeerTable with size {}", peer, peerTable.size());
// Cleaning up if we are at max capacity...
if(peerTable.size() == MAX_PEER_TABLE_SIZE) {
for(String k : peerTable.keySet()) {
Peer p = peerTable.get(k);
if(p != null && p.getState(PeerState.class) == PeerState.DOWN) {
peerTable.remove(k, p);
}
}
}
peerTable.put(peer.getUri().getFQDN(), peer);
if (peerTableListener != null) {
peerTableListener.peerAccepted(peer);
}
}
public void stopping(int disconnectCause) {
super.stopping(disconnectCause);
if (networkGuard != null) {
networkGuard.destroy();
networkGuard = null;
}
//
if (overloadScheduler != null) {
concurrentFactory.shutdownNow(overloadScheduler);
overloadScheduler = null;
overloadHandler.cancel(true);
overloadHandler = null;
}
//
if (duplicationScheduler != null) {
concurrentFactory.shutdownNow(duplicationScheduler);
duplicationScheduler = null;
}
if (duplicationHandler != null) {
duplicationHandler.cancel(true);
duplicationHandler = null;
}
//
if (connScheduler != null) {
concurrentFactory.shutdownNow(connScheduler);
connScheduler = null;
}
if (connHandler != null) {
connHandler.cancel(true);
connHandler = null;
}
//remove incoming data
storageAnswers.clear();
// Clear dynamic peers from peertable
Iterator<String> it = super.peerTable.keySet().iterator();
while(it.hasNext()) {
String fqdn = it.next();
if(this.predefinedPeerTable.contains(fqdn)) {
continue;
}
else {
it.remove();
}
}
}
public Peer addPeer(URI peerURI, String realm, boolean connecting) {
//TODO: add sKey here, now it adds peer to all realms.
//TODO: better, separate addPeer from realm!
try {
Configuration peerConfig = null;
Configuration[] peers = config.getChildren(PeerTable.ordinal());
// find peer config
for (Configuration c : peers) {
if (peerURI.getFQDN().equals(c.getStringValue(PeerName.ordinal(), ""))) {
peerConfig = c;
break;
}
}
if (peerConfig == null) {
peerConfig = new EmptyConfiguration(false).add(PeerAttemptConnection, connecting);
}
IPeer peer = (IPeer) createPeer(0, peerURI.toString(), null, null, metaData, config, peerConfig, fsmFactory,
transportFactory, statisticFactory, concurrentFactory, parser);
if (peer == null) {
return null;
}
peer.setRealm(realm);
appendPeerToPeerTable(peer);
boolean found = false;
Collection<Realm> realms = this.router.getRealmTable().getRealms(realm);
for (Realm r : realms) {
if (r.getName().equals(realm)) {
((IRealm)r).addPeerName(peerURI.toString());
found = true;
break;
}
}
if (!found) {
throw new IllegalArgumentException("Incorrect realm name");
}
if (StackState.STARTED.equals(stack.getState()) && connecting) {
peer.connect();
}
return peer;
}
catch(Exception e) {
logger.debug("Unable to add peer", e);
return null;
}
}
public Set<Realm> getAllRealms() {
return new HashSet<Realm>(router.getRealmTable().getRealms());
}
public Peer removePeer(String host) {
try {
String fqdn = null;
for (String f : peerTable.keySet()) {
if (f.equals(host)) {
fqdn = f;
peerTable.get(fqdn).disconnect(DisconnectCause.BUSY);
}
}
if (fqdn != null) {
predefinedPeerTable.remove(fqdn);
Peer removedPeer = peerTable.remove(fqdn);
if (peerTableListener != null) {
peerTableListener.peerRemoved(removedPeer);
}
return removedPeer;
}
else {
return null;
}
}
catch (Exception e) {
logger.debug("Unable to remove peer", e);
return null;
}
}
public Statistic getStatistic(String name) {
for (Peer p : peerTable.values()) {
if (p.getUri().getFQDN().equals(name)) {
return ((IPeer) p).getStatistic();
}
}
return null;
}
public IMessage isDuplicate(IMessage request) {
String key = request.getDuplicationKey();
if (key != null && storageAnswers != null) {
StorageEntry entry = storageAnswers.get(key);
return entry != null ? (IMessage) entry.getMessage().clone() : null;
}
return null;
}
public void saveToDuplicate(String key, IMessage answer) {
if (storageAnswers != null && storageAnswers.size() < duplicateSize) {
if (key != null) {
StorageEntry se = new StorageEntry((IMessage) answer.clone());
if(logger.isTraceEnabled()) {
logger.trace("Duplicate Protection - Inserting Entry with key '{}' and time '{}'", key, se.getTime());
}
storageAnswers.put(key, se);
}
}
}
public ISessionFactory getSessionFactory() {
return sessionFactory;
}
public boolean isWrapperFor(Class<?> aClass) throws InternalException {
boolean isWrapp = super.isWrapperFor(aClass);
return aClass == MutablePeerTable.class || aClass == Network.class || isWrapp;
}
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);
}
return null;
}
}
| 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.ApplicationId;
import org.jdiameter.api.Configuration;
import org.jdiameter.api.OverloadListener;
import org.jdiameter.api.URI;
import org.jdiameter.server.api.IOverloadManager;
import static org.jdiameter.server.impl.helpers.Parameters.*;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
*
* @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 OverloadManagerImpl implements IOverloadManager {
private ConcurrentLinkedQueue<OverloadInfo> listeners = new ConcurrentLinkedQueue<OverloadInfo>();
private ConcurrentHashMap<Object, AppOverloadInfo> appInfo = new ConcurrentHashMap<Object, AppOverloadInfo>();
public OverloadManagerImpl(Configuration config) {
Configuration[] entries = config.getChildren(OverloadMonitor.ordinal());
if (entries == null) return;
for (Configuration e : entries) {
ApplicationId appId = null;
Configuration[] cAppId = e.getChildren(ApplicationId.ordinal());
for (Configuration i : cAppId) {
if ( i.getLongValue(AuthApplId.ordinal(), 0) != 0 )
appId = org.jdiameter.api.ApplicationId.createByAuthAppId(
i.getLongValue(VendorId.ordinal(), 0),
i.getLongValue(AuthApplId.ordinal(), 0)
);
else
appId = org.jdiameter.api.ApplicationId.createByAccAppId(
i.getLongValue(VendorId.ordinal(), 0),
i.getLongValue(AcctApplId.ordinal(), 0)
);
break;
}
if (appId == null) continue;
AppOverloadInfo info = new AppOverloadInfo(appId);
info.appendEntry(
e.getIntValue(OverloadEntryIndex.ordinal(), 0),
e.getDoubleValue(OverloadEntrylowThreshold.ordinal(), 0),
e.getDoubleValue(OverloadEntryhighThreshold.ordinal(), 0)
);
appInfo.put(appId, info);
}
}
public void parentAppOverloadDetected(ApplicationId applicationId, int type, double value) {
AppOverloadInfo app = appInfo.get(createKey(applicationId));
if (app != null) {
app.updateInformation(type, value);
}
}
public void parentAppOverloadCeased(ApplicationId applicationId, int type) {
AppOverloadInfo app = appInfo.get(createKey(applicationId));
if (app != null) {
app.updateInformation(type, 0);
}
}
private Object createKey(final ApplicationId appId) {
return new Object() {
public int hashCode() {
return appId.hashCode();
}
public boolean equals(Object obj) {
return appId.equals(obj);
}
};
}
public boolean isParenAppOverload(final ApplicationId appId) {
if (appId == null) return false;
AppOverloadInfo app = appInfo.get( createKey(appId) );
return app != null && app.isOverload();
}
public boolean isParenAppOverload(final ApplicationId appId, final int type) {
AppOverloadInfo app = appInfo.get( createKey(appId) );
return app != null && app.isOverload(type);
}
public void addOverloadListener(OverloadListener overloadListener, double lowThreshold, double highThreshold, int qIndex) {
listeners.add(new OverloadInfo(overloadListener, lowThreshold, highThreshold, qIndex));
}
public void removeOverloadListener(OverloadListener overloadListener, int qIndex) {
listeners.remove(new OverloadInfo(overloadListener, qIndex));
}
public void changeNotification(int index, URI uri, double value) {
for (OverloadInfo e : listeners)
if (e.getCode() == index) e.changeNotification(uri, value);
}
public static class AppOverloadInfo {
private ApplicationId appId;
private ArrayList <AppOverloadInfoEntry> entries = new ArrayList<AppOverloadInfoEntry>();
private final Object lock = new Object();
public ApplicationId getAppId() {
return appId;
}
public AppOverloadInfo(ApplicationId appId) {
this.appId = appId;
}
public void appendEntry(int type, double lowThreshold, double highThreshold) {
entries.add(new AppOverloadInfoEntry(type, lowThreshold, highThreshold));
}
public boolean isOverload() {
for (AppOverloadInfoEntry e : entries) {
if (e.isOverload()) return true;
}
return false;
}
public boolean isOverload(int type) {
for (AppOverloadInfoEntry e : entries) {
if (e.getType() == type)
synchronized(lock) {
if (e.isOverload()) return true;
}
}
return false;
}
public void updateInformation(int type, double threshold) {
for (AppOverloadInfoEntry e : entries) {
if (e.getType() == type)
synchronized(lock) {
e.updateInformation(threshold);
}
}
}
}
public static class AppOverloadInfoEntry {
private int type;
private double lowThreshold, highThreshold;
private double currentValue;
private final Object lock = new Object();
public AppOverloadInfoEntry(int type, double lowThreshold, double highThreshold) {
this.type = type;
this.lowThreshold = lowThreshold;
this.highThreshold = highThreshold;
}
public int getType() {
return type;
}
public double getLowThreshold() {
return lowThreshold;
}
public double getHighThreshold() {
return highThreshold;
}
public double getCurrentValue() {
return currentValue;
}
public void updateInformation(double threshold) {
synchronized(lock) {
this.currentValue = threshold;
}
}
public boolean isOverload() {
synchronized(lock) {
return (currentValue >= lowThreshold && currentValue <= highThreshold);
}
}
}
public static class OverloadInfo {
private OverloadListener overloadListener;
private double lowThreshold, highThreshold;
private int qIndex;
private boolean isOverload;
private Lock lock = new ReentrantLock();
public OverloadInfo(OverloadListener overloadListener, int qIndex) {
this.overloadListener = overloadListener;
this.qIndex = qIndex;
}
public OverloadInfo(OverloadListener overloadListener, double lowThreshold, double highThreshold, int qIndex) {
this.overloadListener = overloadListener;
this.lowThreshold = lowThreshold;
this.highThreshold = highThreshold;
this.qIndex = qIndex;
}
public void changeNotification(URI uri, double value) {
if ( value >= lowThreshold && value <= highThreshold ) {
overloadListener.overloadDetected(uri, value);
lock.lock();
isOverload = true;
lock.unlock();
} else {
lock.lock();
if (isOverload) {
overloadListener.overloadCeased(uri);
isOverload = false;
}
lock.unlock();
}
}
public int getCode() {
return qIndex;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
OverloadInfo that = (OverloadInfo) o;
if (qIndex != that.qIndex) return false;
if (overloadListener != null ? !overloadListener.equals(that.overloadListener) : that.overloadListener != null)
return false;
return true;
}
public int hashCode() {
int result;
result = (overloadListener != null ? overloadListener.hashCode() : 0);
result = 31 * result + qIndex;
return result;
}
}
}
| 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.sh;
import org.jdiameter.common.api.app.AppSessionDataLocalImpl;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ShServerSessionDataLocalImpl extends AppSessionDataLocalImpl implements IShServerSessionData {
public ShServerSessionDataLocalImpl() {
}
}
| 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.sh;
import org.jdiameter.api.app.AppEvent;
import org.jdiameter.api.app.StateEvent;
/**
*
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
*/
public class Event implements StateEvent {
enum Type {
RECEIVE_USER_DATA_REQUEST,
RECEIVE_PROFILE_UPDATE_REQUEST,
RECEIVE_SUBSCRIBE_NOTIFICATIONS_REQUEST,
RECEIVE_PUSH_NOTIFICATION_ANSWER,
SEND_PUSH_NOTIFICATION_REQUEST,
SEND_USER_DATA_ANSWER,
SEND_PROFILE_UPDATE_ANSWER,
SEND_SUBSCRIBE_NOTIFICATIONS_ANSWER,
TIMEOUT_EXPIRES,
//Add this to allow app to respond, and in case of app error not to leave it behind
TX_TIMER_EXPIRED;
}
Type type;
AppEvent request;
AppEvent answer;
Event(Type type, AppEvent request, AppEvent answer) {
this.type = type;
this.answer = answer;
this.request = request;
}
public <E> E encodeType(Class<E> eClass) {
return eClass == Type.class ? (E) type : null;
}
public Enum getType() {
return type;
}
public AppEvent getRequest() {
return request;
}
public AppEvent getAnswer() {
return answer;
}
public int compareTo(Object o) {
return 0;
}
public Object getData() {
return request != null ? request : answer;
}
public void setData(Object data) {
// FIXME: What should we do here?! Is it request or answer?
}
}
| Java |
/*
* JBoss, Home of Professional Open Source
* Copyright 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.sh;
import org.jdiameter.common.api.app.sh.IShSessionData;
/**
*
* @author <a href="mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href="mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public interface IShServerSessionData extends IShSessionData {
// stateless
}
| 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.sh;
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.Message;
import org.jdiameter.api.NetworkReqListener;
import org.jdiameter.api.OverloadException;
import org.jdiameter.api.Request;
import org.jdiameter.api.RouteException;
import org.jdiameter.api.app.AppEvent;
import org.jdiameter.api.app.StateEvent;
import org.jdiameter.api.sh.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.common.api.app.sh.IShMessageFactory;
import org.jdiameter.common.impl.app.AppAnswerEventImpl;
import org.jdiameter.common.impl.app.AppRequestEventImpl;
import org.jdiameter.common.impl.app.sh.ShSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Basic implementation of ShServerSession - can be one time - for UDR, PUR and
* constant for SNR-PNR pair, in case when SNA contains response code from range
* different than 2001-2004(success codes) user is responsible for maintaing
* state - releasing etc, same goes if result code is contained
* Experimental-Result AVP <br>
* If ShSession moves to ShSessionState.TERMINATED - it means that no further
* messages can be received via it and it should be discarded. <br>
* <br>
*
* @author <a href = "mailto:baranowb@gmail.com"> Bartosz Baranowski </a>
* @author <a href = "mailto:brainslog@gmail.com"> Alexandre Mendonca </a>
*/
public class ShServerSessionImpl extends ShSession implements ServerShSession, EventListener<Request, Answer>, NetworkReqListener {
private Logger logger = LoggerFactory.getLogger(ShServerSessionImpl.class);
// Session State Handling ---------------------------------------------------
protected Lock sendAndStateLock = new ReentrantLock();
// Factories and Listeners --------------------------------------------------
protected transient IShMessageFactory factory = null;
protected transient ServerShSessionListener listener;
protected IShServerSessionData sessionData;
protected long appId;
public ShServerSessionImpl(IShServerSessionData sessionData, IShMessageFactory fct, ISessionFactory sf, ServerShSessionListener lst) {
super(sf, sessionData);
if(sessionData == null) {
throw new NullPointerException("SessionData must not be null");
}
if (lst == null) {
throw new IllegalArgumentException("Listener can not be null");
}
if (fct.getApplicationId() < 0) {
throw new IllegalArgumentException("ApplicationId can not be less than zero");
}
this.sessionData = sessionData;
this.appId = fct.getApplicationId();
this.listener = lst;
this.factory = fct;
}
public void sendProfileUpdateAnswer(ProfileUpdateAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_PROFILE_UPDATE_ANSWER, null, answer);
}
public void sendPushNotificationRequest(PushNotificationRequest request) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_PUSH_NOTIFICATION_REQUEST, request, null);
}
public void sendSubscribeNotificationsAnswer(SubscribeNotificationsAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_SUBSCRIBE_NOTIFICATIONS_ANSWER, null, answer);
}
public void sendUserDataAnswer(UserDataAnswer answer) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
send(Event.Type.SEND_USER_DATA_ANSWER, null, answer);
}
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 {
sendAndStateLock.lock();
if (request.getApplicationId() == appId) {
if (request.getCommandCode() == PushNotificationRequest.code) {
handleEvent(new Event(Event.Type.TIMEOUT_EXPIRES, factory.createPushNotificationRequest(request), null));
return;
}
}
}
catch (Exception e) {
logger.debug("Failed to process timeout message", e);
}
finally {
sendAndStateLock.unlock();
}
}
public Answer processRequest(Request request) {
RequestDelivery rd = new RequestDelivery();
rd.session = this;
rd.request = request;
super.scheduler.execute(rd);
return null;
}
public <E> E getState(Class<E> stateType) {
return null;
}
public boolean handleEvent(StateEvent event) throws InternalException, OverloadException {
try {
sendAndStateLock.lock();
Event localEvent = (Event) event;
switch ((Event.Type) localEvent.getType()) {
case RECEIVE_PROFILE_UPDATE_REQUEST:
listener.doProfileUpdateRequestEvent(this, (ProfileUpdateRequest) localEvent.getRequest());
break;
case RECEIVE_PUSH_NOTIFICATION_ANSWER:
listener.doPushNotificationAnswerEvent(this, (PushNotificationRequest) localEvent.getRequest(), (PushNotificationAnswer) localEvent.getAnswer());
break;
case RECEIVE_SUBSCRIBE_NOTIFICATIONS_REQUEST:
listener.doSubscribeNotificationsRequestEvent(this, (SubscribeNotificationsRequest) localEvent.getRequest());
break;
case RECEIVE_USER_DATA_REQUEST:
listener.doUserDataRequestEvent(this, (UserDataRequest) localEvent.getRequest());
break;
case SEND_PROFILE_UPDATE_ANSWER:
dispatchEvent(localEvent.getAnswer());
break;
case SEND_PUSH_NOTIFICATION_REQUEST:
dispatchEvent(localEvent.getRequest());
break;
case SEND_SUBSCRIBE_NOTIFICATIONS_ANSWER:
dispatchEvent(localEvent.getAnswer());
break;
case SEND_USER_DATA_ANSWER:
dispatchEvent(localEvent.getAnswer());
break;
case TIMEOUT_EXPIRES:
break;
default:
logger.error("Wrong message type = {} req = {} ans = {}", new Object[]{localEvent.getType(), localEvent.getRequest(), localEvent.getAnswer()});
}
}
catch (IllegalDiameterStateException idse) {
throw new InternalException(idse);
}
catch (RouteException re) {
throw new InternalException(re);
}
finally {
sendAndStateLock.unlock();
}
return true;
}
public boolean isStateless() {
return true;
}
protected void send(Event.Type type, AppEvent request, AppEvent answer) throws InternalException {
try {
//FIXME: isnt this bad? Shouldnt send be before state change?
sendAndStateLock.lock();
if (type != null) {
handleEvent(new Event(type, request, answer));
}
}
catch (Exception exc) {
throw new InternalException(exc);
}
finally {
sendAndStateLock.unlock();
}
}
protected void dispatchEvent(AppEvent event) throws InternalException {
try{
session.send(event.getMessage(), this);
// FIXME: add differentiation on server/client request
}
catch(Exception e) {
logger.debug("Failed to dispatch event", e);
}
}
public void release() {
if (isValid()) {
try {
sendAndStateLock.lock();
super.release();
}
catch (Exception e) {
logger.debug("Failed to release session", e);
}
finally {
sendAndStateLock.unlock();
}
}
else {
logger.debug("Trying to release an already invalid session, with Session ID '{}'", getSessionId());
}
}
protected long extractExpiryTime(Message answer) {
try {
// FIXME: Replace 709 by Avp.EXPIRY_TIME
Avp expiryTimeAvp = answer.getAvps().getAvp(709);
return expiryTimeAvp != null ? expiryTimeAvp.getTime().getTime() : -1;
}
catch (AvpDataException ade) {
logger.debug("Failure trying to extract Expiry-Time AVP value", ade);
}
return -1;
}
/* (non-Javadoc)
* @see org.jdiameter.common.impl.app.AppSessionImpl#isReplicable()
*/
@Override
public boolean isReplicable() {
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (appId ^ (appId >>> 32));
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;
ShServerSessionImpl other = (ShServerSessionImpl) obj;
if (appId != other.appId)
return false;
if (sessionData == null) {
if (other.sessionData != null)
return false;
}
else if (!sessionData.equals(other.sessionData))
return false;
return true;
}
@Override
public void onTimer(String timerName) {
logger.trace("onTimer({})", timerName);
}
private class RequestDelivery implements Runnable {
ServerShSession session;
Request request;
public void run() {
try {
if (request.getApplicationId() == appId) {
if (request.getCommandCode() == SubscribeNotificationsRequest.code) {
handleEvent(new Event(Event.Type.RECEIVE_SUBSCRIBE_NOTIFICATIONS_REQUEST, factory.createSubscribeNotificationsRequest(request), null));
}
else if(request.getCommandCode() == UserDataRequest.code) {
handleEvent(new Event(Event.Type.RECEIVE_USER_DATA_REQUEST, factory.createUserDataRequest(request), null));
}
else if(request.getCommandCode() == ProfileUpdateRequest.code) {
handleEvent(new Event(Event.Type.RECEIVE_PROFILE_UPDATE_REQUEST, factory.createProfileUpdateRequest(request), null));
}
else {
listener.doOtherEvent(session, new AppRequestEventImpl(request), null);
}
}
}
catch (Exception e) {
logger.debug("Failed to process request message", e);
}
}
}
private class AnswerDelivery implements Runnable {
ServerShSession session;
Answer answer;
Request request;
public void run() {
try {
sendAndStateLock.lock();
if (request.getApplicationId() == appId) {
if (request.getCommandCode() == PushNotificationRequest.code) {
handleEvent(new Event(Event.Type.RECEIVE_PUSH_NOTIFICATION_ANSWER, factory.createPushNotificationRequest(request), factory.createPushNotificationAnswer(answer)));
return;
}
else {
listener.doOtherEvent(session, new AppRequestEventImpl(request), new AppAnswerEventImpl(answer));
}
}
else {
logger.warn("Message with Application-Id {} reached Application Session with Application-Id {}. Skipping.", request.getApplicationId(), appId);
}
}
catch (Exception e) {
logger.debug("Failed to process success message", e);
}
finally {
sendAndStateLock.unlock();
}
}
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.