PageRenderTime 30ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/servers/diameter/testsuite/tests/src/test/java/org/mobicents/slee/resources/diameter/tests/framework/TestingFramework.java

http://mobicents.googlecode.com/
Java | 907 lines | 681 code | 126 blank | 100 comment | 169 complexity | 6c30d79807ad3ae4a492c2e30ae61118 MD5 | raw file
Possible License(s): LGPL-3.0, GPL-3.0, LGPL-2.1, GPL-2.0, CC-BY-SA-3.0, CC0-1.0, Apache-2.0, BSD-3-Clause
  1. package org.mobicents.slee.resources.diameter.tests.framework;
  2. import static org.jdiameter.client.impl.helpers.Parameters.AcctApplId;
  3. import static org.jdiameter.client.impl.helpers.Parameters.ApplicationId;
  4. import static org.jdiameter.client.impl.helpers.Parameters.Assembler;
  5. import static org.jdiameter.client.impl.helpers.Parameters.AuthApplId;
  6. import static org.jdiameter.client.impl.helpers.Parameters.OwnDiameterURI;
  7. import static org.jdiameter.client.impl.helpers.Parameters.OwnIPAddress;
  8. import static org.jdiameter.client.impl.helpers.Parameters.OwnRealm;
  9. import static org.jdiameter.client.impl.helpers.Parameters.OwnVendorID;
  10. import static org.jdiameter.client.impl.helpers.Parameters.PeerName;
  11. import static org.jdiameter.client.impl.helpers.Parameters.PeerRating;
  12. import static org.jdiameter.client.impl.helpers.Parameters.PeerTable;
  13. import static org.jdiameter.client.impl.helpers.Parameters.RealmEntry;
  14. import static org.jdiameter.client.impl.helpers.Parameters.RealmTable;
  15. import static org.jdiameter.client.impl.helpers.Parameters.VendorId;
  16. import static org.jdiameter.server.impl.helpers.Parameters.RealmEntryExpTime;
  17. import static org.jdiameter.server.impl.helpers.Parameters.RealmEntryIsDynamic;
  18. import static org.jdiameter.server.impl.helpers.Parameters.RealmHosts;
  19. import static org.jdiameter.server.impl.helpers.Parameters.RealmLocalAction;
  20. import static org.jdiameter.server.impl.helpers.Parameters.RealmName;
  21. import static org.junit.Assert.assertTrue;
  22. import static org.junit.Assert.assertNotNull;
  23. import java.io.InputStream;
  24. import java.text.SimpleDateFormat;
  25. import java.util.ArrayList;
  26. import java.util.Arrays;
  27. import java.util.Date;
  28. import java.util.concurrent.TimeUnit;
  29. import java.util.logging.ConsoleHandler;
  30. import java.util.logging.Level;
  31. import javax.xml.parsers.DocumentBuilder;
  32. import javax.xml.parsers.DocumentBuilderFactory;
  33. import junit.framework.Assert;
  34. import org.jdiameter.api.Answer;
  35. import org.jdiameter.api.Avp;
  36. import org.jdiameter.api.AvpDataException;
  37. import org.jdiameter.api.AvpSet;
  38. import org.jdiameter.api.DisconnectCause;
  39. import org.jdiameter.api.EventListener;
  40. import org.jdiameter.api.IllegalDiameterStateException;
  41. import org.jdiameter.api.InternalException;
  42. import org.jdiameter.api.Message;
  43. import org.jdiameter.api.MetaData;
  44. import org.jdiameter.api.Mode;
  45. import org.jdiameter.api.OverloadException;
  46. import org.jdiameter.api.Request;
  47. import org.jdiameter.api.RouteException;
  48. import org.jdiameter.api.Session;
  49. import org.jdiameter.api.SessionFactory;
  50. import org.jdiameter.api.Stack;
  51. import org.jdiameter.api.StackType;
  52. import org.jdiameter.client.api.parser.ParseException;
  53. import org.jdiameter.client.impl.helpers.EmptyConfiguration;
  54. import org.jdiameter.client.impl.helpers.Loggers;
  55. import org.jdiameter.client.impl.parser.MessageImpl;
  56. import org.jdiameter.client.impl.parser.MessageParser;
  57. import org.mobicents.diameter.dictionary.AvpDictionary;
  58. import org.mobicents.diameter.dictionary.AvpRepresentation;
  59. import org.w3c.dom.Document;
  60. import org.w3c.dom.Element;
  61. import org.w3c.dom.Node;
  62. import org.w3c.dom.NodeList;
  63. public class TestingFramework
  64. {
  65. private static int timeout = 30 * 1000;
  66. private static String clientHost = "127.0.0.1";
  67. private static String clientPort = "13868";
  68. private static String clientURI = "aaa://" + clientHost + ":" + clientPort;
  69. private static String serverHost = "127.0.0.1";
  70. private static String serverPort = "3868";
  71. private static String serverURI = "aaa://" + serverHost + ":" + serverPort;
  72. private static String realmName = "mobicents.org";
  73. private static AvpDictionary avpDictionary = AvpDictionary.INSTANCE;
  74. private ArrayList<Message> receivedMessages = new ArrayList<Message>();
  75. private static Stack stack;
  76. private static SessionFactory factory;
  77. // The AVPs that may be pre-filled in message.
  78. private final int[] prefilledAVPs = new int[]{Avp.DESTINATION_HOST, Avp.DESTINATION_REALM, Avp.ORIGIN_HOST, Avp.ORIGIN_REALM, Avp.SESSION_ID, Avp.VENDOR_SPECIFIC_APPLICATION_ID};
  79. protected MessageParser parser = new MessageParser();
  80. private boolean printAVPs = true;
  81. static
  82. {
  83. // String name = "localhost";
  84. //
  85. // try
  86. // {
  87. // name = InetAddress.getLocalHost().getHostName();
  88. // }
  89. // catch (UnknownHostException ignore)
  90. // {
  91. // // ignore this... use localhost
  92. // }
  93. //
  94. // serverHost = name;
  95. // serverURI = "aaa://" + serverHost + ":" + serverPort;
  96. }
  97. private void initStack()
  98. {
  99. log("Initializing Stack...");
  100. try
  101. {
  102. avpDictionary.parseDictionary(this.getClass().getClassLoader().getResourceAsStream("dictionary.xml"));
  103. log("AVP Dictionary successfully parsed.");
  104. }
  105. catch ( Exception e )
  106. {
  107. e.printStackTrace();
  108. }
  109. try
  110. {
  111. stack = new org.jdiameter.client.impl.StackImpl();
  112. }
  113. catch (Exception e)
  114. {
  115. e.printStackTrace();
  116. stack.destroy();
  117. return;
  118. }
  119. try
  120. {
  121. factory = stack.init(new MyConfiguration());
  122. log("Stack Configuration successfully loaded.");
  123. }
  124. catch (Exception e)
  125. {
  126. e.printStackTrace();
  127. stack.destroy();
  128. return;
  129. }
  130. MetaData metaData = stack.getMetaData();
  131. if (metaData.getStackType() != StackType.TYPE_CLIENT || metaData.getMinorVersion() <= 0)
  132. {
  133. stack.destroy();
  134. logError("Incorrect driver");
  135. return;
  136. }
  137. // Set logger levels
  138. Loggers.Stack.logger().setLevel(Level.OFF);
  139. ConsoleHandler fh = new ConsoleHandler();
  140. fh.setLevel(Level.ALL);
  141. stack.getLogger().addHandler(fh);
  142. stack.getLogger().setUseParentHandlers(false);
  143. log("Stack Logging successfully initialized.");
  144. try
  145. {
  146. log("Connecting to Peers...");
  147. stack.start(Mode.ALL_PEERS, 20, TimeUnit.SECONDS);
  148. log("Connection to Peers successfully completed.");
  149. }
  150. catch (Exception e)
  151. {
  152. e.printStackTrace();
  153. stack.destroy();
  154. return;
  155. }
  156. log("Stack initialization successfully completed.");
  157. }
  158. public void executeTest(InputStream is)
  159. {
  160. try
  161. {
  162. assertNotNull("InputStream must exist.", is);
  163. initStack();
  164. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  165. DocumentBuilder db = dbf.newDocumentBuilder();
  166. Document doc = db.parse(is);
  167. doc.getDocumentElement().normalize();
  168. NodeList scenarioNodes = doc.getChildNodes();
  169. for(int i = 0; i < scenarioNodes.getLength(); i++)
  170. {
  171. Node scenarioNode = scenarioNodes.item(i);
  172. if (scenarioNode.getNodeType() == Node.ELEMENT_NODE)
  173. {
  174. ArrayList<Element> actions = parseScenario( (Element) scenarioNode );
  175. for(Element action : actions)
  176. {
  177. ArrayList<AvpSet> messagesAVPs = parseAction(action);
  178. // Add AVPs
  179. executeAction(action, (Element)action.getElementsByTagName("command").item(0), messagesAVPs);
  180. }
  181. }
  182. }
  183. }
  184. catch (Exception e)
  185. {
  186. e.printStackTrace();
  187. Assert.fail(e.getMessage());
  188. }
  189. finally
  190. {
  191. if(stack != null)
  192. stopStack();
  193. }
  194. }
  195. private void stopStack()
  196. {
  197. try
  198. {
  199. log("Stopping Stack...");
  200. stack.stop(10, TimeUnit.SECONDS, DisconnectCause.REBOOTING);
  201. log("Stack Stopped Successfully.");
  202. }
  203. catch (Exception e)
  204. {
  205. e.printStackTrace();
  206. }
  207. stack.destroy();
  208. try
  209. {
  210. // Let it stop... useful for JUnit tests
  211. Thread.sleep( 1000 );
  212. }
  213. catch ( InterruptedException e )
  214. {
  215. e.printStackTrace();
  216. }
  217. }
  218. /**
  219. * Method for executing the scenario actions
  220. * @param action the action Element to be executed (send or receive)
  221. * @param command the message Element to send or receive (eg. ACR)
  222. * @param avpSet an ArrayList of AvpSet defining the AVPs to be sent in message
  223. * @throws InternalException
  224. * @throws IllegalDiameterStateException
  225. * @throws RouteException
  226. * @throws OverloadException
  227. * @throws AvpDataException
  228. */
  229. private void executeAction(Element action, Element command, ArrayList<AvpSet> avpSet) throws InternalException, IllegalDiameterStateException, RouteException, OverloadException, AvpDataException
  230. {
  231. MySessionEventListener listener = new MySessionEventListener();
  232. if(action.getNodeName().equals("send"))
  233. {
  234. Session session = null;
  235. for(AvpSet avps : avpSet)
  236. {
  237. log("Sending Message...");
  238. int commandCode = command.getAttribute("code").equals("") ? getCommandFromString(command.getAttribute("name")) : Integer.valueOf(command.getAttribute("code"));
  239. if(session == null)
  240. {
  241. if(avps.getAvp(Avp.SESSION_ID) != null)
  242. session = factory.getNewSession(avps.getAvp(Avp.SESSION_ID).getUTF8String());
  243. else
  244. session = factory.getNewSession();
  245. }
  246. else if(avps.getAvp(Avp.SESSION_ID) != null && !session.getSessionId().equals(avps.getAvp(Avp.SESSION_ID).getUTF8String()))
  247. {
  248. session = factory.getNewSession(avps.getAvp(Avp.SESSION_ID).getUTF8String());
  249. }
  250. Request msg = session.createRequest(
  251. commandCode,
  252. org.jdiameter.api.ApplicationId.createByAccAppId(193, 19302),
  253. realmName,
  254. serverHost
  255. );
  256. String messageFlags = command.getAttribute("flags");
  257. if(messageFlags != null && !messageFlags.equals(""))
  258. {
  259. msg.setRequest( messageFlags.contains("request") );
  260. msg.setProxiable( messageFlags.contains("proxiable") );
  261. msg.setError( messageFlags.contains("error") );
  262. msg.setReTransmitted( messageFlags.contains("retransmitted") );
  263. }
  264. // Set hop-by-hop and end-to-end if present
  265. String h2h = command.getAttribute("hop-by-hop");
  266. if(h2h != null && h2h.length() > 0) {
  267. // Adding as negative so it becomes immutable...
  268. ((MessageImpl)msg).setHopByHopIdentifier(-Long.valueOf(h2h));
  269. }
  270. String e2e = command.getAttribute("end-to-end");
  271. if(e2e != null && e2e.length() > 0) {
  272. ((MessageImpl)msg).setEndToEndIdentifier(Long.valueOf(e2e));
  273. }
  274. AvpSet msgAVPs = msg.getAvps();
  275. // In case we want to override pre-filled AVPs
  276. for(int prefilledAVP : prefilledAVPs)
  277. {
  278. if(avps.getAvp(prefilledAVP) != null) {
  279. msgAVPs.removeAvp(prefilledAVP);
  280. }
  281. }
  282. msgAVPs.addAvp( avps );
  283. session.send(msg, listener);
  284. if(printAVPs)
  285. printAvps( msg.getAvps() );
  286. log("Message sent.");
  287. long startTime = System.currentTimeMillis();
  288. try
  289. {
  290. synchronized(TestingFramework.this)
  291. {
  292. if(!listener.hasAnswer()) {
  293. TestingFramework.this.wait(timeout + 1000);
  294. }
  295. }
  296. }
  297. catch (InterruptedException e)
  298. {
  299. e.printStackTrace();
  300. }
  301. long stopTime = System.currentTimeMillis();
  302. if (listener.hasAnswer())
  303. {
  304. log("Processing time: " + (stopTime - startTime) + "ms");
  305. }
  306. }
  307. }
  308. else if(action.getNodeName().equals("receive"))
  309. {
  310. for(AvpSet avps : avpSet)
  311. {
  312. if(receivedMessages.size() > 0)
  313. {
  314. log("Checking received Message...");
  315. Message receivedMessage = receivedMessages.remove(0);
  316. if(printAVPs)
  317. printAvps( receivedMessage.getAvps() );
  318. AvpSet receivedAvps = receivedMessage.getAvps();
  319. int expectedCommandCode = command.getAttribute("code").equals("") ? getCommandFromString(command.getAttribute("name")) : Integer.valueOf(command.getAttribute("code"));
  320. assertTrue( "Unexpected type of Message: Received[" + receivedMessage.getCommandCode() + "] Expected[" + expectedCommandCode + "]",
  321. receivedMessage.getCommandCode() == expectedCommandCode );
  322. // Verify hop-by-hop and end-to-end if present
  323. String h2h = command.getAttribute("hop-by-hop");
  324. if(h2h != null && h2h.length() > 0) {
  325. assertTrue( "Unexpected Hop-By-Hop Identifier: Received[" + receivedMessage.getHopByHopIdentifier() + "] Expected[" + Long.valueOf(h2h) + "]",
  326. receivedMessage.getHopByHopIdentifier() == Long.valueOf(h2h));
  327. }
  328. String e2e = command.getAttribute("end-to-end");
  329. if(e2e != null && e2e.length() > 0) {
  330. assertTrue( "Unexpected End-To-End Identifier: Received[" + receivedMessage.getEndToEndIdentifier() + "] Expected[" + Long.valueOf(e2e) + "]",
  331. receivedMessage.getEndToEndIdentifier() == Long.valueOf(e2e));
  332. }
  333. for(Avp expectedAvp : avps)
  334. {
  335. Avp receivedAvp = null;
  336. assertTrue( "Missing expected AVP: Vendor-Id[" + expectedAvp.getVendorId() + "] Code[" + expectedAvp.getCode() + "]",
  337. (receivedAvp = receivedAvps.getAvp( expectedAvp.getCode(), expectedAvp.getVendorId()) ) != null );
  338. compareAvps(expectedAvp, receivedAvp);
  339. }
  340. log("Finished checking message. All Good!");
  341. }
  342. else
  343. {
  344. log("No message was received... FAILED!");
  345. assertTrue( "No Message was received. Failing.", false);
  346. }
  347. }
  348. }
  349. }
  350. /**
  351. * Compares two AVPs for their value. In case of Grouped AVPs, works recursively.
  352. * @param expectedAvp the expected AVP
  353. * @param receivedAvp the received AVP
  354. * @throws AvpDataException
  355. */
  356. private void compareAvps(Avp expectedAvp, Avp receivedAvp) throws AvpDataException
  357. {
  358. if( avpDictionary.getAvp( expectedAvp.getCode(), expectedAvp.getVendorId()).getType().equals( "Grouped" ) )
  359. {
  360. for(Avp subExpectedAvp : expectedAvp.getGrouped())
  361. {
  362. Avp subReceivedAvp = receivedAvp.getGrouped().getAvp( subExpectedAvp.getCode(), subExpectedAvp.getVendorId() );
  363. compareAvps( subExpectedAvp, subReceivedAvp );
  364. }
  365. }
  366. else
  367. {
  368. assertTrue("Expected AVP Value differs: Vendor-Id[" + expectedAvp.getVendorId() + "] Code[" + expectedAvp.getCode() + "] " +
  369. "Received[" + getAvpValue(receivedAvp) + "] Expected[" + getAvpValue(expectedAvp) + "]",
  370. Arrays.equals(receivedAvp.getRaw(), expectedAvp.getRaw()));
  371. }
  372. }
  373. /**
  374. * Method for parsing an action element and get the corresponding AVPs to be used
  375. * @param action the Element with the action
  376. * @return an ArrayList of AvpSet to be used in the action
  377. * @throws InternalException
  378. */
  379. private ArrayList<AvpSet> parseAction(Element action) throws InternalException
  380. {
  381. log("Parsing Action '" + action.getNodeName() + "'...");
  382. ArrayList<AvpSet> messages = new ArrayList<AvpSet>();
  383. NodeList commandNodes = action.getElementsByTagName("command");
  384. for(int i = 0; i < commandNodes.getLength(); i++)
  385. {
  386. Node commandNode = commandNodes.item(i);
  387. if(commandNode.getNodeType() == Node.ELEMENT_NODE)
  388. {
  389. // Now we add the AVPs
  390. Message msg = parser.createEmptyMessage( Integer.valueOf(0), 0L );
  391. addAvps( msg.getAvps(), commandNode.getChildNodes());
  392. messages.add(msg.getAvps());
  393. }
  394. }
  395. log("Finished Parsing Action '" + action.getNodeName() + "'. It contains " + messages.size() + " messages.");
  396. return messages;
  397. }
  398. /**
  399. * Adds the AVPs present in the NodeList element to the passed AvpSet
  400. * @param avpSet the original set of AVPs, which will be modified and returned
  401. * @param avpNodes the NodeList containing the AVP elements
  402. * @return an AvpSet (the one passed as argument) with the newly added AVPs
  403. */
  404. private AvpSet addAvps(AvpSet avpSet, NodeList avpNodes)
  405. {
  406. for(int a = 0; a < avpNodes.getLength(); a++)
  407. {
  408. Node avpNode = avpNodes.item(a);
  409. if(avpNode.getNodeType() == Node.ELEMENT_NODE)
  410. {
  411. Element avpElem = (Element) avpNode;
  412. String avpCode = avpElem.getAttribute( "code" );
  413. String avpVendor = avpElem.getAttribute( "vendor" );
  414. String avpName = avpElem.getAttribute( "name" );
  415. String avpValue = avpElem.getAttribute( "value" );
  416. AvpRepresentation avpRep = null;
  417. if( !avpCode.equals("") ) {
  418. int code = Integer.valueOf(avpCode);
  419. long vendorId = avpVendor.equals("") ? 0 : Long.valueOf(avpVendor);
  420. avpRep = AvpDictionary.INSTANCE.getAvp( code, vendorId );
  421. }
  422. else if( !avpName.equals( "" ) ) {
  423. avpRep = AvpDictionary.INSTANCE.getAvp(avpName);
  424. }
  425. else {
  426. throw new IllegalArgumentException("AVP Definition missing 'code' and 'name' attribute. At least one must be present.");
  427. }
  428. if(avpRep == null) {
  429. logError("Unable to find AVP with code [" + avpCode + "] and/or name [" + avpName + "] in dictionary. Can't add.");
  430. }
  431. else if(avpRep.getType().equals("Grouped")) {
  432. boolean isMandatory = !(avpRep.getRuleMandatory().equals("mustnot") || avpRep.getRuleMandatory().equals("shouldnot"));
  433. boolean isProtected = avpRep.getRuleProtected().equals("must");
  434. AvpSet gAvp = avpSet.addGroupedAvp(avpRep.getCode(), Long.valueOf(avpRep.getVendorId()), isMandatory, isProtected);
  435. addAvps( gAvp, avpNode.getChildNodes() );
  436. }
  437. else {
  438. avpSet.addAvp( avpRep.getCode(), valueToBytes( avpRep, avpValue ), Long.valueOf(avpRep.getVendorId()), true, false );
  439. }
  440. }
  441. }
  442. return avpSet;
  443. }
  444. /**
  445. * Parses the scenario returning an ArrayList of the actions to perform.
  446. * @param e the scenario Element
  447. * @return an ArrayList of Elements representing the actions
  448. * @throws Exception
  449. */
  450. private ArrayList<Element> parseScenario(Element e) throws Exception
  451. {
  452. log("Parsing Scenario '" + e.getAttribute( "name" ) + "'...");
  453. ArrayList<Element> actions = new ArrayList<Element>();
  454. NodeList actionNodes = e.getChildNodes();
  455. for(int i = 0; i < actionNodes.getLength(); i++)
  456. {
  457. Node actionNode = actionNodes.item(i);
  458. if (actionNode.getNodeType() == Node.ELEMENT_NODE)
  459. {
  460. Element actionElem = (Element)actionNode;
  461. String actionName = actionElem.getNodeName();
  462. if(actionName.equals("send") || actionName.equals("receive"))
  463. {
  464. actions.add( actionElem );
  465. }
  466. else if(actionName.equals("configuration"))
  467. {
  468. log("Found scenario configuration. Loading it...");
  469. configureScenario(actionElem);
  470. }
  471. else
  472. {
  473. throw new Exception("Invalid scenario action (" + actionName + ")");
  474. }
  475. }
  476. }
  477. log("Successfully parsed scenario '" + e.getAttribute( "name" ) + "'. It contains " + actions.size() + " actions.");
  478. return actions;
  479. }
  480. private void configureScenario(Element configElem)
  481. {
  482. NodeList propertyNode = null;
  483. if( (propertyNode = configElem.getElementsByTagName("local-host")).getLength() > 0)
  484. {
  485. clientHost = propertyNode.item(0).getTextContent();
  486. log("Setting local-host to " + clientHost );
  487. }
  488. if( (propertyNode = configElem.getElementsByTagName("local-port")).getLength() > 0)
  489. {
  490. clientPort = propertyNode.item(0).getTextContent();
  491. log("Setting local-port to " + clientPort );
  492. }
  493. if( (propertyNode = configElem.getElementsByTagName("remote-host")).getLength() > 0)
  494. {
  495. serverHost = propertyNode.item(0).getTextContent();
  496. log("Setting remote-host to " + serverHost );
  497. }
  498. if( (propertyNode = configElem.getElementsByTagName("remote-port")).getLength() > 0)
  499. {
  500. serverPort = propertyNode.item(0).getTextContent();
  501. log("Setting remote-port to " + serverPort );
  502. }
  503. if( (propertyNode = configElem.getElementsByTagName("realm-name")).getLength() > 0)
  504. {
  505. realmName = propertyNode.item(0).getTextContent();
  506. log("Setting realm-name to " + realmName );
  507. }
  508. if( (propertyNode = configElem.getElementsByTagName("message-timeout")).getLength() > 0)
  509. {
  510. timeout = Integer.valueOf(propertyNode.item(0).getTextContent());
  511. log("Setting message-timeout to " + timeout );
  512. }
  513. log("Finished configuring scenario.");
  514. }
  515. private class MySessionEventListener implements EventListener<Request, Answer> {
  516. private Answer answer = null;
  517. public void receivedSuccessMessage(Request request, Answer answer)
  518. {
  519. this.answer = answer;
  520. receivedMessages.add( answer );
  521. continueProcessing();
  522. }
  523. public void timeoutExpired(Request request)
  524. {
  525. continueProcessing();
  526. }
  527. public boolean hasAnswer()
  528. {
  529. return answer != null;
  530. }
  531. public Answer getAnswer()
  532. {
  533. return answer;
  534. }
  535. private void continueProcessing()
  536. {
  537. synchronized(TestingFramework.this)
  538. {
  539. TestingFramework.this.notifyAll();
  540. }
  541. }
  542. }
  543. /**
  544. * Class representing the Diameter Test Framework Configuration
  545. */
  546. public static class MyConfiguration extends EmptyConfiguration
  547. {
  548. public MyConfiguration()
  549. {
  550. super();
  551. add(Assembler, Assembler.defValue());
  552. add(OwnDiameterURI, clientURI);
  553. add(OwnIPAddress, "127.0.0.1");
  554. add(OwnRealm, realmName);
  555. add(OwnVendorID, 193L);
  556. // Set Ericsson SDK feature
  557. //add(UseUriAsFqdn, true);
  558. // Set Common Applications
  559. add(ApplicationId,
  560. // AppId 1
  561. getInstance().
  562. add(VendorId, 193L).
  563. add(AuthApplId, 0L).
  564. add(AcctApplId, 19302L)
  565. );
  566. // Set peer table
  567. add(PeerTable,
  568. // Peer 1
  569. getInstance().
  570. add(PeerRating, 1).
  571. add(PeerName, serverURI));
  572. // Set realm table
  573. add(RealmTable,
  574. // Realm 1
  575. getInstance().add(RealmEntry, getInstance().
  576. add(RealmName, realmName).
  577. add(ApplicationId, getInstance().add(VendorId, 193L).add(AuthApplId, 0L).add(AcctApplId, 19302L)).
  578. add(RealmHosts, clientHost + ", " + serverHost).
  579. add(RealmLocalAction, "LOCAL").
  580. add(RealmEntryIsDynamic, false).
  581. add(RealmEntryExpTime, 1000L))
  582. );
  583. }
  584. }
  585. private Object getAvpValue(Avp avp) throws AvpDataException
  586. {
  587. String avpType = avpDictionary.getAvp( avp.getCode(), avp.getVendorId() ).getType();
  588. if(avpType.equals("Integer32"))
  589. {
  590. return avp.getInteger32();
  591. }
  592. else if(avpType.equals( "Unsigned32" ))
  593. {
  594. return avp.getUnsigned32();
  595. }
  596. else if(avpType.equals( "Integer64" ))
  597. {
  598. return avp.getInteger64();
  599. }
  600. else if(avpType.equals( "Unsigned64" ))
  601. {
  602. return avp.getUnsigned64();
  603. }
  604. else if(avpType.equals( "Float32" ))
  605. {
  606. return avp.getFloat32();
  607. }
  608. else if(avpType.equals( "Float64" ))
  609. {
  610. return avp.getFloat64();
  611. }
  612. else if(avpType.equals( "OctetString" ))
  613. {
  614. return avp.getOctetString();
  615. }
  616. else if(avpType.equals( "UTF8String" ))
  617. {
  618. return avp.getUTF8String();
  619. }
  620. else if(avpType.equals("Time"))
  621. {
  622. return avp.getTime();
  623. }
  624. // Default
  625. return avp.getOctetString();
  626. }
  627. /**
  628. * Converts a string value into a byte value
  629. * @param avpRep the AvpRepresentation of the AVP
  630. * @param valueStr the String value of the AVP
  631. * @return a byte[] containing the bytes of the correct format value
  632. */
  633. private byte[] valueToBytes(AvpRepresentation avpRep, String valueStr)
  634. {
  635. String avpType = avpRep.getType();
  636. if(avpType.equals("Integer32"))
  637. {
  638. return parser.int32ToBytes( Integer.valueOf(valueStr) );
  639. }
  640. else if(avpType.equals( "Unsigned32" ))
  641. {
  642. return parser.intU32ToBytes( Long.valueOf(valueStr) );
  643. }
  644. else if(avpType.equals( "Integer64" ))
  645. {
  646. return parser.int64ToBytes( Long.valueOf(valueStr) );
  647. }
  648. else if(avpType.equals( "Unsigned64" ))
  649. {
  650. return parser.int64ToBytes( Long.valueOf(valueStr) );
  651. }
  652. else if(avpType.equals( "Float32" ))
  653. {
  654. return parser.float32ToBytes( Float.valueOf(valueStr) );
  655. }
  656. else if(avpType.equals( "Float64" ))
  657. {
  658. return parser.float64ToBytes( Double.valueOf(valueStr) );
  659. }
  660. else if(avpType.equals( "OctetString" ))
  661. {
  662. try
  663. {
  664. return parser.octetStringToBytes( (valueStr) );
  665. }
  666. catch ( ParseException pe )
  667. {
  668. pe.printStackTrace();
  669. }
  670. }
  671. else if(avpType.equals("Time"))
  672. {
  673. return parser.dateToBytes( new Date(Long.valueOf(valueStr)) );
  674. }
  675. // Default
  676. return valueStr.getBytes();
  677. }
  678. /**
  679. * Prints the AVPs present in an AvpSet
  680. * @param avpSet the AvpSet containing the AVPs to be printed
  681. * @throws AvpDataException
  682. */
  683. private void printAvps(AvpSet avpSet) throws AvpDataException
  684. {
  685. printAvpsAux( avpSet, 0 );
  686. }
  687. /**
  688. * Prints the AVPs present in an AvpSet with a specified 'tab' level
  689. * @param avpSet the AvpSet containing the AVPs to be printed
  690. * @param level an int representing the number of 'tabs' to make a pretty print
  691. * @throws AvpDataException
  692. */
  693. private void printAvpsAux(AvpSet avpSet, int level) throws AvpDataException
  694. {
  695. String prefix = " ".substring( 0, level*2 );
  696. for(Avp avp : avpSet) {
  697. AvpRepresentation avpRep = AvpDictionary.INSTANCE.getAvp( avp.getCode(), avp.getVendorId() );
  698. if(avpRep != null) {
  699. if(avpRep.getType().equals("Grouped")) {
  700. log(prefix + "<avp name=\"" + avpRep.getName() + "\" code=\"" + avp.getCode() + "\" vendor=\"" + avp.getVendorId() + "\">");
  701. printAvpsAux( avp.getGrouped(), level+1 );
  702. log(prefix + "</avp>");
  703. }
  704. else {
  705. String value = "";
  706. if(avpRep.getType().equals("Integer32"))
  707. value = String.valueOf(avp.getInteger32());
  708. else if(avpRep.getType().equals("Integer64") || avpRep.getType().equals("Unsigned64"))
  709. value = String.valueOf(avp.getInteger64());
  710. else if(avpRep.getType().equals("Unsigned32"))
  711. value = String.valueOf(avp.getUnsigned32());
  712. else if(avpRep.getType().equals("Float32"))
  713. value = String.valueOf(avp.getFloat32());
  714. else
  715. value = avp.getUTF8String();
  716. log(prefix + "<avp name=\"" + avpRep.getName() + "\" code=\"" + avp.getCode() + "\" vendor=\"" + avp.getVendorId() + "\" value=\"" + value + "\" />");
  717. }
  718. }
  719. else {
  720. log(prefix + "<avp name=\"?\" code=\"" + avp.getCode() + "\" vendor=\"" + avp.getVendorId() + "\" value=\"" + avp.getOctetString() + "\" />");
  721. }
  722. }
  723. }
  724. /**
  725. * Returns the Command-Code from Short or Long Command Name
  726. * @param name the command name
  727. * @return an int identifying the command
  728. */
  729. private int getCommandFromString(String name)
  730. {
  731. if( name.equals("Capabilities-Exchange-Request") || name.equals("CER") )
  732. return Message.CAPABILITIES_EXCHANGE_REQUEST;
  733. else if( name.equals("Capabilities-Exchange-Answer") || name.equals("CEA") )
  734. return Message.CAPABILITIES_EXCHANGE_ANSWER;
  735. else if( name.equals("Disconnect-Peer-Request") || name.equals("DPR") )
  736. return Message.DISCONNECT_PEER_REQUEST;
  737. else if( name.equals("Disconnect-Peer-Answer") || name.equals("DPA") )
  738. return Message.DISCONNECT_PEER_ANSWER;
  739. else if( name.equals("Device-Watchdog-Request") || name.equals("DWR") )
  740. return Message.DEVICE_WATCHDOG_REQUEST;
  741. else if( name.equals("Device-Watchdog-Answer") || name.equals("DWA") )
  742. return Message.DEVICE_WATCHDOG_ANSWER;
  743. else if( name.equals("Re-Auth-Request") || name.equals("RAR") )
  744. return Message.RE_AUTH_REQUEST;
  745. else if( name.equals("Re-Auth-Answer") || name.equals("RAA") )
  746. return Message.RE_AUTH_ANSWER;
  747. else if( name.equals("Abort-Session-Request") || name.equals("ASR") )
  748. return Message.ABORT_SESSION_REQUEST;
  749. else if( name.equals("Abort-Session-Answer") || name.equals("ASA") )
  750. return Message.ABORT_SESSION_ANSWER;
  751. else if( name.equals("Session-Termination-Request") || name.equals("STR") )
  752. return Message.SESSION_TERMINATION_REQUEST;
  753. else if( name.equals("Session-Termination-Answer") || name.equals("STA") )
  754. return Message.SESSION_TERMINATION_ANSWER;
  755. else if( name.equals("Accounting-Request") || name.equals("ACR") )
  756. return Message.ACCOUNTING_REQUEST;
  757. else if( name.equals("Accounting-Answer") || name.equals("ACA") )
  758. return Message.ACCOUNTING_ANSWER;
  759. return -1;
  760. }
  761. /**
  762. * Logs a message into stdout
  763. * @param message the message to be printed
  764. */
  765. private static void log(String message)
  766. {
  767. SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss:SSS");
  768. String log = "[" + format.format(new Date()) + "] " + message;
  769. System.out.println(log);
  770. }
  771. /**
  772. * Logs a message into stderr
  773. * @param message the message to be printed
  774. */
  775. private static void logError(String message)
  776. {
  777. SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss:SSS");
  778. String log = "[" + format.format(new Date()) + "] " + message;
  779. System.err.println(log);
  780. }
  781. }