Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  
  package org.mobicents.servlet.sip.example;
  
  import java.util.Iterator;
 import java.util.Map;
 
 import  javax.media.mscontrol.MediaSession;
 import  javax.media.mscontrol.MsControlException;
 import  javax.media.mscontrol.join.Joinable.Direction;
 import  javax.media.mscontrol.mediagroup.MediaGroup;
 import  javax.media.mscontrol.networkconnection.NetworkConnection;
 import  javax.media.mscontrol.networkconnection.SdpPortManager;
 import  javax.media.mscontrol.networkconnection.SdpPortManagerException;
 
Sip Servlet handling responses to call initiated due to actions made on the web shopping demo

Author(s):
Jean Deruelle
 
 public class ShoppingSipServlet 
 	extends SipServlet  
 	implements TimerListener {
 	private static final long serialVersionUID = 1L;
 	private static Logger logger = Logger.getLogger(ShoppingSipServlet.class);
 	private static final String CONTACT_HEADER = "Contact";
 	
Creates a new instance of ShoppingSipServlet
 
 	public ShoppingSipServlet() {
 	}
 
 	public void init(ServletConfig servletConfigthrows ServletException {
 		.info("the shopping sip servlet has been started");
 		super.init(servletConfig);
 		try {
 			InitialContext ctx = new InitialContext();
 			OrderManager orderManager = Util.getOrderManager();
 			.info("Reference to OrderManagerBean " + orderManager);
 		} catch (NamingException e) {
 			.error("An exception occured while retrieving the EJB OrderManager",e);
 		}	
 	}		
 	
 
 	protected void doProvisionalResponse(SipServletResponse sipServletResponse)
 		.info("Got : " + sipServletResponse.getStatus() + " "
 				+ sipServletResponse.getMethod());
 		int status = sipServletResponse.getStatus();
 		Boolean isHelpCall = (BooleansipServletResponse.getSession().getAttribute("HelpCall");
 		if (status == . && 
 				"INVITE".equalsIgnoreCase(sipServletResponse.getMethod()) && 
 				(isHelpCall == null || ..equals(isHelpCall))) {
 			//creates the connection
 			Object sdpObj = sipServletResponse.getContent();
 			byte[] sdpBytes = (byte[]) sdpObj;
 			String sdp = new String(sdpBytes);
 			.info("Creating the end to end media connection");
 			sipServletResponse.getSession().setAttribute("playAnnouncement".);
 			sipServletResponse.getSession().setAttribute("audioFilePath", (String)getServletContext().getAttribute("audioFilePath"));
 			NetworkConnection connection = (NetworkConnection)sipServletResponse.getSession().getAttribute("connection");
 			try {
 				connection.getSdpPortManager().processSdpAnswer(sdpBytes);
 			} catch (SdpPortManagerException e) {
 				// TODO Auto-generated catch block
				e.printStackTrace();
catch (MsControlException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
		.info("Got OK");
		SipSession session = resp.getSession();
		Boolean inviteSent = (Booleansession.getAttribute("InviteSent");
		if (inviteSent != null && inviteSent.booleanValue()) {
			return;
		}
		Address secondPartyAddress = (Addressresp.getSession()
				.getAttribute("SecondPartyAddress");
		if (secondPartyAddress != null) {
					.getApplicationSession(), "INVITE"session
					.getRemoteParty(), secondPartyAddress);
			.info("Found second party -- sending INVITE to "
secondPartyAddress);
			String contentType = resp.getContentType();
			if (contentType.trim().equals("application/sdp")) {
				invite.setContent(resp.getContent(), "application/sdp");
			}
			session.setAttribute("LinkedSession"invite.getSession());
			invite.getSession().setAttribute("LinkedSession"session);
			invite.getSession().setAttribute("FirstPartyAck"ack);
			invite.getSession().setAttribute("FirstPartyContent"resp.getContent());
			invite.getSession().setAttribute("HelpCall".);
			invite.send();
			session.setAttribute("InviteSent".);
else {
			.info("Got OK from second party -- sending ACK");
			SipServletRequest secondPartyAck = resp.createAck();
			SipServletRequest firstPartyAck = (SipServletRequestresp
					.getSession().getAttribute("FirstPartyAck");
//					if (resp.getContentType() != null && resp.getContentType().equals("application/sdp")) {
				firstPartyAck.setContent(resp.getContent(),
						"application/sdp");
				secondPartyAck.setContent(resp.getSession().getAttribute("FirstPartyContent"),
						"application/sdp");
//					}
			firstPartyAck.send();
			secondPartyAck.send();
		}
	}
	protected void doSuccessResponse(SipServletResponse sipServletResponse)
		.info("Got : " + sipServletResponse.getStatus() + " "
sipServletResponse.getMethod());
		int status = sipServletResponse.getStatus();
		if (status == . && "INVITE".equalsIgnoreCase(sipServletResponse.getMethod())) {
			Boolean isHelpCall = (BooleansipServletResponse.getSession().getAttribute("HelpCall");
			if(isHelpCall != null && ..equals(isHelpCall)) {
				//Handle the help call use case
				doHelpCallSuccessResponse(sipServletResponse);
else {
				//send ack
				SipServletRequest ackRequest = sipServletResponse.createAck();			
				ackRequest.send();
				//creates the connection
				Object sdpObj = sipServletResponse.getContent();
				byte[] sdpBytes = (byte[]) sdpObj;	
				String pathToAudioDirectory = (String)getServletContext().getAttribute("audioFilePath");
				sipServletResponse.getSession().setAttribute("audioFilePath"pathToAudioDirectory);
				NetworkConnection connection = (NetworkConnection)sipServletResponse.getSession().getAttribute("connection");
				try {
					connection.getSdpPortManager().processSdpAnswer(sdpBytes);
					Thread.sleep(400);
catch (SdpPortManagerException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
catch (MsControlException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
catch (InterruptedException e) {
					// TODO Auto-generated catch block
				}
				MediaGroup mg =(MediaGroup)sipServletResponse.getSession().getAttribute("mediaGroup");
				if(mg != null) {
					.info("Not Creating the end to end media connection, connection already opened");
					MediaConnectionListener.playAnnouncement(mgsipServletResponse.getSession(), pathToAudioDirectory);
				}			
			}
		}
	}
	protected void doErrorResponse(SipServletResponse response)
		.info("Got response: " + response);
			// Avoid re-sending if the auth repeatedly fails.
			if(!"true".equals(response.getSession().getAttribute("FirstResponseRecieved")))
			{
				SipSession sipSession = response.getSession();
				sipSession.setAttribute("FirstResponseRecieved""true");
				AuthInfo authInfo = sipFactory.createAuthInfo();
				authInfo.addAuthInfo(
						response.getStatus(), 
						response.getChallengeRealms().next(), 
						getServletContext().getInitParameter("caller.password"));
				SipServletRequest challengeRequest = response.getSession().createRequest(
						response.getRequest().getMethod());
				challengeRequest.addAuthHeader(responseauthInfo);
				/*
				MsConnection connection =  (MsConnection) 
					sipSession.getAttribute("connection");
				if(connection != null) {
					String sdp = connection.getLocalDescriptor();
					try {
						challengeRequest.setContentLength(sdp.length());
						challengeRequest.setContent(sdp.getBytes(), "application/sdp");						
					} catch (IOException e) {
						logger.error("An unexpected exception occured while sending the request", e);
					}
				}
				logger.info("sending challenge request " + challengeRequest);
				challengeRequest.send();*/
			}
else {					
			super.doErrorResponse(response);
		}
	}
	protected void doBye(SipServletRequest requestthrows ServletException,
		.info("Got bye " + request);
		NetworkConnection connection = (NetworkConnection)request.getSession().getAttribute("connection");
		MediaGroup mg =(MediaGroup)request.getSession().getAttribute("mediaGroup");
		MediaSession session =(MediaSession)request.getSession().getAttribute("mediaSession");
		session.release();
		try {
			Thread.sleep(1000);
catch (InterruptedException e) {
			// TODO Auto-generated catch block
		}
		SipServletResponse ok = request
		ok.send();
		SipSession linkedSession = (SipSessionrequest.getSession()
				.getAttribute("LinkedSession");
		if (linkedSession != null) {
			SipServletRequest bye = linkedSession.createRequest("BYE");
			.info("Sending bye to " + linkedSession.getRemoteParty());
			bye.send();
		}
	}
	protected void doRegister(SipServletRequest reqthrows ServletExceptionIOException {
		.info("Received register request: " + req.getTo());
		Map<StringStringusers = (Map<StringString>) getServletContext().getAttribute("registeredUsersMap");
		int response = .;
		SipServletResponse resp = req.createResponse(response);				
		String fromURI = req.getFrom().getURI().toString();
		int expires = address.getExpires();		
		if(expires < 0) {
			expires = req.getExpires();
		}
		if(expires == 0) {			
			users.remove(fromURI);
			.info("User " + fromURI + " unregistered");
else {			
			users.put(fromURIaddress.getURI().toString());
			//updating the default contact address for the admin
			String adminAddress = (StringgetServletContext().getAttribute("admin.sip");
			if(fromURI.equalsIgnoreCase(adminAddress)) {
				getServletContext().setAttribute("admin.sip.default.contact"address.getURI().toString());
			}
			.info("User " + fromURI + 
					" registered this contact address " + address + 
					" with an Expire time of " + expires);
		}							
		resp.send();
	}
	/*
	 * (non-Javadoc)
	 * @see javax.servlet.sip.TimerListener#timeout(javax.servlet.sip.ServletTimer)
	 */
	public void timeout(ServletTimer timer) {
		SipApplicationSession sipApplicationSession = timer.getApplicationSession();
		Map<StringObjectattributes = (Map<StringObject>)timer.getInfo();
		try {			
			String callerAddress = (String)attributes.get("caller");
			String callerDomain = (String)attributes.get("callerDomain");
			SipURI fromURI = .createSipURI(callerAddresscallerDomain);
			Address fromAddress = .createAddress(fromURI);
			String customerName = (Stringattributes.get("customerName");
			BigDecimal amount = (BigDecimalattributes.get("amountOrder");
			String customerPhone = (Stringattributes.get("customerPhone");
			String customerContact = (Stringattributes.get("customerContact");
			Address toAddress = .createAddress(customerPhone);									
			.info("preparing to call : "toAddress);
			SipServletRequest sipServletRequest = 
				.createRequest(sipApplicationSession"INVITE"fromAddresstoAddress);
			if(attributes.get("adminApproval") != null) {
				.info("preparing speech for admin approval");
				customerContact = (Stringattributes.get("adminContactAddress");
				//TTS file creation		
				StringBuffer stringBuffer = new StringBuffer();
				stringBuffer.append(customerName);
				stringBuffer.append(" has placed an order of $");
				stringBuffer.append(amount);
				stringBuffer.append(". Press 1 to approve and 2 to reject.");				
				sipServletRequest.getSession().setAttribute("speechUri",
						java.net.URI.create("data:" + URLEncoder.encode("ts("stringBuffer +")""UTF-8")));
			}			
			URI requestURI = .createURI(customerContact);			
			sipServletRequest.setRequestURI(requestURI);
			//copying the attributes in the sip session since the media listener depends on it
			Iterator<Entry<String,Object>> attrIterator = attributes.entrySet().iterator();
			while (attrIterator.hasNext()) {
						.next();
				sipServletRequest.getSession().setAttribute(entry.getKey(), entry.getValue());
			}
			SipSession sipSession = sipServletRequest.getSession();
			if (sipSession.getAttribute("deliveryDate") != null) {			
				String announcementFile = . + "/OrderDeliveryDate.wav";
				sipServletRequest.getSession().setAttribute("speechUri",
				java.net.URI.create(announcementFile));
				.info("Preparing to play Delivery Date Announcement : " + announcementFile);
			//Media Server Control Creation
			MediaSession mediaSession = MMSUtil.getMsControl().createMediaSession();
			NetworkConnection conn = mediaSession
			.createNetworkConnection(NetworkConnection.BASIC);
			SdpPortManager sdpManag = conn.getSdpPortManager();
			sdpManag.generateSdpOffer();
			byte[] sdpOffer = null;
			int numTimes = 0;
			while(sdpOffer == null && numTimes<10) {
				sdpOffer = sdpManag.getMediaServerSessionDescription();
				Thread.sleep(500);
				numTimes++;
			}
			MediaGroup mg = mediaSession.createMediaGroup(MediaGroup.PLAYER_SIGNALDETECTOR);
			sipServletRequest.getSession().setAttribute("mediaGroup"mg);
			sipServletRequest.getSession().setAttribute("mediaSession"mediaSession);
			sipServletRequest.setContentLength(sdpOffer.length);
			sipServletRequest.setContent(sdpOffer"application/sdp");	
			listener.setInviteRequest(sipServletRequest);
//			provider.addConnectionListener(listener);
			sipServletRequest.getSession().setAttribute("connection"conn);
			sipServletRequest.send();
			mg.getSignalDetector().addListener(new DTMFListener(mgsipServletRequest.getSession(), .));
			conn.join(Direction.DUPLEX, mg);
			.info("waiting to get the SDP from Media Server before sending the INVITE to " + callerAddress + "@" + callerDomain);
catch (Exception e) {
			.error("An unexpected exception occured while creating the request for delivery date"e);
		}
	}
New to GrepCode? Check out our FAQ X