file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
Call.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.telephony/src/main/java/org/restcomm/connect/telephony/Call.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.restcomm.connect.telephony; import java.io.IOException; import java.math.BigDecimal; import java.net.InetAddress; import java.net.URI; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.Currency; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.UUID; import java.util.concurrent.TimeUnit; import javax.sdp.SdpException; import javax.servlet.sip.Address; import javax.servlet.sip.AuthInfo; import javax.servlet.sip.ServletParseException; import javax.servlet.sip.SipApplicationSession; import javax.servlet.sip.SipFactory; import javax.servlet.sip.SipServletMessage; import javax.servlet.sip.SipServletRequest; import javax.servlet.sip.SipServletResponse; import javax.servlet.sip.SipSession; import javax.servlet.sip.SipURI; import javax.servlet.sip.TelURL; import javax.sip.header.RecordRouteHeader; import javax.sip.header.RouteHeader; import javax.sip.message.Response; import org.apache.commons.configuration.Configuration; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.mobicents.javax.servlet.sip.SipFactoryExt; import org.mobicents.javax.servlet.sip.SipSessionExt; import org.restcomm.connect.commons.annotations.concurrency.Immutable; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.commons.fsm.Action; import org.restcomm.connect.commons.fsm.FiniteStateMachine; import org.restcomm.connect.commons.fsm.State; import org.restcomm.connect.commons.fsm.Transition; import org.restcomm.connect.commons.fsm.TransitionEndListener; import org.restcomm.connect.commons.fsm.TransitionFailedException; import org.restcomm.connect.commons.fsm.TransitionNotFoundException; import org.restcomm.connect.commons.fsm.TransitionRollbackException; import org.restcomm.connect.commons.patterns.Observe; import org.restcomm.connect.commons.patterns.Observing; import org.restcomm.connect.commons.patterns.StopObserving; import org.restcomm.connect.commons.telephony.CreateCallType; import org.restcomm.connect.commons.util.DNSUtils; import org.restcomm.connect.commons.util.SdpUtils; import org.restcomm.connect.dao.CallDetailRecordsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.entities.CallDetailRecord; import org.restcomm.connect.dao.entities.MediaAttributes; import org.restcomm.connect.http.client.Downloader; import org.restcomm.connect.http.client.DownloaderResponse; import org.restcomm.connect.http.client.HttpRequestDescriptor; import org.restcomm.connect.mscontrol.api.MediaServerControllerFactory; import org.restcomm.connect.mscontrol.api.messages.CloseMediaSession; import org.restcomm.connect.mscontrol.api.messages.Collect; import org.restcomm.connect.mscontrol.api.messages.CreateMediaSession; import org.restcomm.connect.mscontrol.api.messages.JoinBridge; import org.restcomm.connect.mscontrol.api.messages.JoinComplete; import org.restcomm.connect.mscontrol.api.messages.JoinConference; import org.restcomm.connect.mscontrol.api.messages.Leave; import org.restcomm.connect.mscontrol.api.messages.Left; import org.restcomm.connect.mscontrol.api.messages.MediaGroupResponse; import org.restcomm.connect.mscontrol.api.messages.MediaServerControllerStateChanged; import org.restcomm.connect.mscontrol.api.messages.MediaSessionInfo; import org.restcomm.connect.mscontrol.api.messages.Mute; import org.restcomm.connect.mscontrol.api.messages.Play; import org.restcomm.connect.mscontrol.api.messages.Record; import org.restcomm.connect.mscontrol.api.messages.RecordStoped; import org.restcomm.connect.mscontrol.api.messages.StartRecording; import org.restcomm.connect.mscontrol.api.messages.Stop; import org.restcomm.connect.mscontrol.api.messages.StopMediaGroup; import org.restcomm.connect.mscontrol.api.messages.StopRecording; import org.restcomm.connect.mscontrol.api.messages.Unmute; import org.restcomm.connect.mscontrol.api.messages.UpdateMediaSession; import org.restcomm.connect.telephony.api.Answer; import org.restcomm.connect.telephony.api.BridgeStateChanged; import org.restcomm.connect.telephony.api.CallFail; import org.restcomm.connect.telephony.api.CallHoldStateChange; import org.restcomm.connect.telephony.api.CallInfo; import org.restcomm.connect.telephony.api.CallInfoStreamEvent; import org.restcomm.connect.telephony.api.CallResponse; import org.restcomm.connect.telephony.api.CallStateChanged; import org.restcomm.connect.telephony.api.Cancel; import org.restcomm.connect.telephony.api.ChangeCallDirection; import org.restcomm.connect.telephony.api.ConferenceInfo; import org.restcomm.connect.telephony.api.ConferenceResponse; import org.restcomm.connect.telephony.api.Dial; import org.restcomm.connect.telephony.api.GetCallInfo; import org.restcomm.connect.telephony.api.GetCallObservers; import org.restcomm.connect.telephony.api.Hangup; import org.restcomm.connect.telephony.api.InitializeOutbound; import org.restcomm.connect.telephony.api.Reject; import org.restcomm.connect.telephony.api.RemoveParticipant; import org.restcomm.connect.telephony.api.StopWaiting; import org.restcomm.connect.telephony.api.util.B2BUAHelper; import akka.actor.ActorRef; import akka.actor.Props; import akka.actor.ReceiveTimeout; import akka.actor.UntypedActor; import akka.actor.UntypedActorContext; import akka.actor.UntypedActorFactory; import akka.event.Logging; import akka.event.LoggingAdapter; import akka.pattern.Patterns; import akka.util.Timeout; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; /** * @author [email protected] (Thomas Quintana) * @author [email protected] (Jean Deruelle) * @author [email protected] (Amit Bhayani) * @author [email protected] (George Vagenas) * @author [email protected] (Henrique Rosa) * @author [email protected] (Maria Farooq) * */ @Immutable public final class Call extends RestcommUntypedActor implements TransitionEndListener { // Logging private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); // Response Code for Media Server Failure private static final int MEDIA_SERVER_FAILURE_RESPONSE_CODE = 569; // Define possible directions. private static final String INBOUND = "inbound"; private static final String OUTBOUND_API = "outbound-api"; private static final String OUTBOUND_DIAL = "outbound-dial"; // Call Hold actions private static final String CALL_ON_HOLD_ACTION = "action=onHold"; private static final String CALL_OFF_HOLD_ACTION = "action=offHold"; // Finite State Machine private final FiniteStateMachine fsm; private final State uninitialized; private final State initializing; private final State waitingForAnswer; private final State queued; private final State failingBusy; private final State ringing; private final State busy; private final State notFound; private final State canceling; private final State canceled; private final State failingNoAnswer; private final State noAnswer; private final State dialing; private final State updatingMediaSession; private final State inProgress; private final State joining; private final State leaving; private final State stopping; private final State completed; private final State failed; private final State inDialogRequest; private boolean fail; // SIP runtime stuff private final SipFactory factory; private String apiVersion; private Sid accountId; private String name; private SipURI from; private javax.servlet.sip.URI to; // custom headers for SIP Out https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out //headers defined in rcml private Map<String, String> rcmlHeaders; //headers populated by extension to modify existing headers and add new headers private Map<String, ArrayList<String>> extensionHeaders; private String username; private String password; private CreateCallType type; private long timeout; private SipServletRequest invite; private SipServletRequest inDialogInvite; private SipServletResponse lastResponse; private boolean isFromApi; // Call runtime stuff. private final Sid id; private final String instanceId; private CallStateChanged.State external; private String direction; private String forwardedFrom; private DateTime created; private DateTime callUpdatedTime; private final List<ActorRef> observers; private boolean receivedBye; private boolean sentBye; private boolean muted; private boolean webrtc; private boolean initialInviteOkSent; private boolean isStoppingRecord = false; // Conferencing private ActorRef conference; private boolean conferencing; private Sid conferenceSid; // Call Bridging private ActorRef bridge; // Media Session Control runtime stuff private final ActorRef msController; private MediaSessionInfo mediaSessionInfo; // Media Group runtime stuff private CallDetailRecord outgoingCallRecord; private CallDetailRecordsDao recordsDao; private DaoManager daoManager; private boolean liveCallModification; private boolean recording; private URI recordingUri; private Sid recordingSid; private Sid parentCallSid; private MediaAttributes mediaAttributes; // Runtime Setting private Configuration runtimeSettings; private Configuration configuration; private boolean disableSdpPatchingOnUpdatingMediaSession; private boolean useSbc; private Sid inboundCallSid; private boolean inboundConfirmCall; private int collectTimeout; private String collectFinishKey; private boolean collectSipInfoDtmf = false; private boolean enable200OkDelay; private boolean outboundToIms; private String imsProxyAddress; private int imsProxyPort; private boolean actAsImsUa; private boolean isOnHold; private int callDuration; private DateTime recordingStart; private long recordingDuration; private String msCompatibilityMode; private HttpRequestDescriptor requestCallback; ActorRef downloader = null; private URI statusCallback; private String statusCallbackMethod; private List<String> statusCallbackEvent; public static enum CallbackState { INITIATED("initiated"), RINGING("ringing"), ANSWERED("answered"), COMPLETED("completed"); private final String text; private CallbackState(final String text) { this.text = text; } @Override public String toString() { return text; } }; public Call(final Sid accountSid, final SipFactory factory, final MediaServerControllerFactory mediaSessionControllerFactory, final Configuration configuration, final URI statusCallback, final String statusCallbackMethod, final List<String> statusCallbackEvent) { this(accountSid, factory, mediaSessionControllerFactory, configuration, statusCallback, statusCallbackMethod, statusCallbackEvent, null); } public Call(final Sid accountSid, final SipFactory factory, final MediaServerControllerFactory mediaSessionControllerFactory, final Configuration configuration, final URI statusCallback, final String statusCallbackMethod, final List<String> statusCallbackEvent, Map<String, ArrayList<String>> headers) { super(); final ActorRef source = self(); this.accountId = accountSid; this.statusCallback = statusCallback; this.statusCallbackMethod = statusCallbackMethod; this.statusCallbackEvent = statusCallbackEvent; if (statusCallback != null) { downloader = downloader(); } this.extensionHeaders = new HashMap<String, ArrayList<String>>(); if(headers != null){ this.extensionHeaders = headers; } // States for the FSM this.uninitialized = new State("uninitialized", null, null); this.initializing = new State("initializing", new Initializing(source), null); this.waitingForAnswer = new State("waiting for answer", new WaitingForAnswer(source), null); this.queued = new State("queued", new Queued(source), null); this.ringing = new State("ringing", new Ringing(source), null); this.failingBusy = new State("failing busy", new FailingBusy(source), null); this.busy = new State("busy", new Busy(source), null); this.notFound = new State("not found", new NotFound(source), null); //This time the --new Canceling(source)-- is an ActionOnState. Overloaded constructor is used here this.canceling = new State("canceling", new Canceling(source)); this.canceled = new State("canceled", new Canceled(source), null); this.failingNoAnswer = new State("failing no answer", new FailingNoAnswer(source), null); this.noAnswer = new State("no answer", new NoAnswer(source), null); this.dialing = new State("dialing", new Dialing(source), null); this.updatingMediaSession = new State("updating media session", new UpdatingMediaSession(source), null); this.inProgress = new State("in progress", new InProgress(source), null); this.joining = new State("joining", new Joining(source), null); this.leaving = new State("leaving", new Leaving(source), null); this.stopping = new State("stopping", new Stopping(source), null); this.completed = new State("completed", new Completed(source), null); this.failed = new State("failed", new Failed(source), null); this.inDialogRequest = new State("InDialogRequest", new InDialogRequest(source), null); // Transitions for the FSM final Set<Transition> transitions = new HashSet<Transition>(); transitions.add(new Transition(this.uninitialized, this.ringing)); transitions.add(new Transition(this.uninitialized, this.queued)); transitions.add(new Transition(this.uninitialized, this.canceled)); transitions.add(new Transition(this.uninitialized, this.completed)); transitions.add(new Transition(this.queued, this.canceled)); transitions.add(new Transition(this.queued, this.initializing)); transitions.add(new Transition(this.ringing, this.busy)); transitions.add(new Transition(this.ringing, this.notFound)); transitions.add(new Transition(this.ringing, this.canceling)); transitions.add(new Transition(this.ringing, this.canceled)); transitions.add(new Transition(this.ringing, this.failingNoAnswer)); transitions.add(new Transition(this.ringing, this.failingBusy)); transitions.add(new Transition(this.ringing, this.noAnswer)); transitions.add(new Transition(this.ringing, this.initializing)); transitions.add(new Transition(this.ringing, this.updatingMediaSession)); transitions.add(new Transition(this.ringing, this.completed)); transitions.add(new Transition(this.ringing, this.stopping)); transitions.add(new Transition(this.ringing, this.failed)); transitions.add(new Transition(this.initializing, this.canceling)); transitions.add(new Transition(this.initializing, this.dialing)); transitions.add(new Transition(this.initializing, this.failed)); transitions.add(new Transition(this.initializing, this.inProgress)); transitions.add(new Transition(this.initializing, this.waitingForAnswer)); transitions.add(new Transition(this.initializing, this.stopping)); transitions.add(new Transition(this.waitingForAnswer, this.inProgress)); transitions.add(new Transition(this.waitingForAnswer, this.joining)); transitions.add(new Transition(this.waitingForAnswer, this.canceling)); transitions.add(new Transition(this.waitingForAnswer, this.completed)); transitions.add(new Transition(this.waitingForAnswer, this.stopping)); transitions.add(new Transition(this.dialing, this.canceling)); transitions.add(new Transition(this.dialing, this.stopping)); transitions.add(new Transition(this.dialing, this.failingBusy)); transitions.add(new Transition(this.dialing, this.ringing)); transitions.add(new Transition(this.dialing, this.failed)); transitions.add(new Transition(this.dialing, this.failingNoAnswer)); transitions.add(new Transition(this.dialing, this.noAnswer)); transitions.add(new Transition(this.dialing, this.updatingMediaSession)); transitions.add(new Transition(this.inProgress, this.stopping)); transitions.add(new Transition(this.inProgress, this.joining)); transitions.add(new Transition(this.inProgress, this.leaving)); transitions.add(new Transition(this.inProgress, this.failed)); transitions.add(new Transition(this.inProgress, this.inDialogRequest)); transitions.add(new Transition(this.inProgress, this.completed)); transitions.add(new Transition(this.joining, this.inProgress)); transitions.add(new Transition(this.joining, this.stopping)); transitions.add(new Transition(this.joining, this.failed)); transitions.add(new Transition(this.leaving, this.inProgress)); transitions.add(new Transition(this.leaving, this.stopping)); transitions.add(new Transition(this.leaving, this.failed)); transitions.add(new Transition(this.leaving, this.completed)); transitions.add(new Transition(this.canceling, this.canceled)); transitions.add(new Transition(this.canceling, this.completed)); transitions.add(new Transition(this.failingBusy, this.busy)); transitions.add(new Transition(this.failingNoAnswer, this.noAnswer)); transitions.add(new Transition(this.failingNoAnswer, this.canceling)); transitions.add(new Transition(this.updatingMediaSession, this.inProgress)); transitions.add(new Transition(this.updatingMediaSession, this.failed)); transitions.add(new Transition(this.updatingMediaSession, this.stopping)); transitions.add(new Transition(this.stopping, this.completed)); transitions.add(new Transition(this.stopping, this.failed)); transitions.add(new Transition(this.failed, this.completed)); transitions.add(new Transition(this.failed, this.stopping)); transitions.add(new Transition(this.completed, this.stopping)); transitions.add(new Transition(this.completed, this.failed)); // FSM this.fsm = new FiniteStateMachine(this.uninitialized, transitions); this.fsm.addTransitionEndListener(this); // SIP runtime stuff. this.factory = factory; // Conferencing this.conferencing = false; // Media Session Control runtime stuff. this.msController = getContext().actorOf(mediaSessionControllerFactory.provideCallControllerProps()); this.fail = false; // Initialize the runtime stuff. this.id = Sid.generate(Sid.Type.CALL); this.instanceId = RestcommConfiguration.getInstance().getMain().getInstanceId(); this.created = DateTime.now(); this.observers = Collections.synchronizedList(new ArrayList<ActorRef>()); this.receivedBye = false; // Media Group runtime stuff this.liveCallModification = false; this.recording = false; this.configuration = configuration; final Configuration runtime = this.configuration.subset("runtime-settings"); this.disableSdpPatchingOnUpdatingMediaSession = runtime.getBoolean("disable-sdp-patching-on-updating-mediasession", false); this.useSbc = runtime.getBoolean("use-sbc", false); if(useSbc) { if (logger.isDebugEnabled()) { logger.debug("Call: use-sbc is true, disable-sdp-patching-on-updating-mediasession to true"); } disableSdpPatchingOnUpdatingMediaSession = true; } this.enable200OkDelay = runtime.getBoolean("enable-200-ok-delay",false); this.msCompatibilityMode = this.configuration.subset("mscontrol").getString("compatibility", "rms"); if(!runtime.subset("ims-authentication").isEmpty()){ final Configuration imsAuthentication = runtime.subset("ims-authentication"); this.actAsImsUa = imsAuthentication.getBoolean("act-as-ims-ua"); } /* The initialization of mediaAttributes variable assumes the call as AUDIO_ONLY by default. The real value is later replaced when the call is queued, as any of {@link MediaAttribute.MediaType} */ this.mediaAttributes = new MediaAttributes(); } ActorRef downloader() { final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new Downloader(); } }); return getContext().actorOf(props); } private boolean is(State state) { return this.fsm.state().equals(state); } private boolean isInbound() { return INBOUND.equals(this.direction); } private boolean isOutbound() { return !isInbound(); } private CallInfo info() { try { final String from; if(actAsImsUa) { from = this.from.getUser().concat("@").concat(this.from.getHost()); } else { from = this.from.getUser(); } String to = null; if (this.to.isSipURI()) { to = ((SipURI) this.to).getUser(); } else { to = ((TelURL) this.to).getPhoneNumber(); } return new CallInfo(id, accountId, external, type, direction, created, forwardedFrom, name, from, to, invite, lastResponse, webrtc, muted, isFromApi, callUpdatedTime, mediaAttributes); } catch (Exception e) { if (logger.isInfoEnabled()) { logger.info("Problem during preparing call info, exception {}",e); } } return null; } private List<NameValuePair> dialStatusCallbackParameters(final CallbackState state) { final List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("InstanceId", RestcommConfiguration.getInstance().getMain().getInstanceId())); parameters.add(new BasicNameValuePair("AccountSid", accountId.toString())); parameters.add(new BasicNameValuePair("CallSid", id.toString())); parameters.add(new BasicNameValuePair("From", this.from.getUser())); String to = null; if (this.to.isSipURI()) { to = ((SipURI) this.to).getUser(); } else { to = ((TelURL) this.to).getPhoneNumber(); } parameters.add(new BasicNameValuePair("To", to)); parameters.add(new BasicNameValuePair("Direction", direction)); parameters.add(new BasicNameValuePair("CallerName", from.getUser())); parameters.add(new BasicNameValuePair("ForwardedFrom", forwardedFrom)); if (parentCallSid != null) parameters.add(new BasicNameValuePair("ParentCallSid", parentCallSid.toString())); parameters.add(new BasicNameValuePair("CallStatus", state.toString())); if (state.equals(CallbackState.COMPLETED)) { parameters.add(new BasicNameValuePair("CallDuration", String.valueOf(callDuration))); //We never record an outgoing call leg, we only record parent call leg and both legs of the call //are mixed down into a single channel //The recording duration will be used only for REST-API created calls if (recording && direction.equalsIgnoreCase("outbound-api")) { if (recordingUri != null) parameters.add(new BasicNameValuePair("RecordingUrl", recordingUri.toString())); if (recordingSid != null) parameters.add(new BasicNameValuePair("RecordingSid", recordingSid.toString())); if (recordingDuration > -1) parameters.add(new BasicNameValuePair("RecordingDuration", String.valueOf(recordingDuration))); } } //RFC 2822 (example: Mon, 15 Aug 2005 15:52:01 +0000) DateTimeFormatter fmt = DateTimeFormat.forPattern("EEE, dd MMM YYYY HH:mm:ss ZZZZ"); final String timestamp = DateTime.now().toString(fmt); parameters.add(new BasicNameValuePair("Timestamp", timestamp)); parameters.add(new BasicNameValuePair("CallbackSource", "call-progress-events")); String sequence = "0"; switch (state) { case INITIATED: sequence = "0"; break; case RINGING: sequence = "1"; break; case ANSWERED: sequence = "2"; break; case COMPLETED: sequence = "3"; break; default: sequence = "0"; break; } parameters.add(new BasicNameValuePair("SequenceNumber", sequence)); if (logger.isDebugEnabled()) { String msg = String.format("Created parameters for Call StatusCallback for state %s and sequence %s uri %s",state,sequence,statusCallback.toString()); logger.debug(msg); } return parameters; } private void executeStatusCallback(final CallbackState state, boolean ask) { if (statusCallback != null) { if (statusCallbackEvent.remove(state.toString())) { if (logger.isDebugEnabled()) { String msg = String.format("About to execute Call StatusCallback for state %s to StatusCallback %s. Call from %s to %s direction %s", state.text, statusCallback.toString(), from.toString(), to.toString(), direction); logger.debug(msg); } if (statusCallbackMethod == null) { statusCallbackMethod = "POST"; } final List<NameValuePair> parameters = dialStatusCallbackParameters(state); if (parameters != null) { requestCallback = new HttpRequestDescriptor(statusCallback, statusCallbackMethod, parameters); if (!ask) { downloader.tell(requestCallback, null); } else { final Timeout timeout = new Timeout(Duration.create(5, TimeUnit.SECONDS)); Future<Object> future = (Future<Object>) Patterns.ask(downloader, requestCallback, timeout); DownloaderResponse downloaderResponse = null; try { downloaderResponse = (DownloaderResponse) Await.result(future, Duration.create(10, TimeUnit.SECONDS)); } catch (Exception e) { logger.error("Exception during callback with ask pattern"); } } } } else { if (logger.isDebugEnabled()) { String msg = String.format("Call StatusCallback will not be sent because its either not in the statusCallbackEvent list or already sent, state %s . Call from %s to %s direction %s", state.text, from.toString(), to.toString(), direction); logger.debug(msg); } } } else if(logger.isInfoEnabled()){ logger.info("status callback is null"); } } private void forwarding(final Object message) { // XXX does nothing } private SipURI getInitialIpAddressPort(SipServletMessage message) throws ServletParseException, UnknownHostException { // Issue #268 - https://bitbucket.org/telestax/telscale-restcomm/issue/268 // First get the Initial Remote Address (real address that the request came from) // Then check the following: // 1. If contact header address is private network address // 2. If there are no "Record-Route" headers (there is no proxy in the call) // 3. If contact header address != real ip address // Finally, if all of the above are true, create a SIP URI using the realIP address and the SIP port // and store it to the sip session to be used as request uri later SipURI uri = null; try { String realIP = message.getInitialRemoteAddr(); Integer realPort = message.getInitialRemotePort(); if (realPort == null || realPort == -1) { realPort = 5060; } if (realPort == 0) { realPort = message.getRemotePort(); } final ListIterator<String> recordRouteHeaders = message.getHeaders("Record-Route"); final Address contactAddr = factory.createAddress(message.getHeader("Contact")); InetAddress contactInetAddress = DNSUtils.getByName(((SipURI) contactAddr.getURI()).getHost()); InetAddress inetAddress = DNSUtils.getByName(realIP); int remotePort = message.getRemotePort(); int contactPort = ((SipURI) contactAddr.getURI()).getPort(); String remoteAddress = message.getRemoteAddr(); // Issue #332: https://telestax.atlassian.net/browse/RESTCOMM-332 final String initialIpBeforeLB = message.getHeader("X-Sip-Balancer-InitialRemoteAddr"); String initialPortBeforeLB = message.getHeader("X-Sip-Balancer-InitialRemotePort"); String contactAddress = ((SipURI) contactAddr.getURI()).getHost(); if (initialIpBeforeLB != null) { if (initialPortBeforeLB == null) initialPortBeforeLB = "5060"; if(logger.isInfoEnabled()) { logger.info("We are behind load balancer, storing Initial Remote Address " + initialIpBeforeLB + ":" + initialPortBeforeLB + " to the session for later use"); } realIP = initialIpBeforeLB + ":" + initialPortBeforeLB; uri = factory.createSipURI(null, realIP); } else if (contactInetAddress.isSiteLocalAddress() && !recordRouteHeaders.hasNext() && !contactInetAddress.toString().equalsIgnoreCase(inetAddress.toString())) { if(logger.isInfoEnabled()) { logger.info("Contact header address " + contactAddr.toString() + " is a private network ip address, storing Initial Remote Address " + realIP + ":" + realPort + " to the session for later use"); } realIP = realIP + ":" + realPort; uri = factory.createSipURI(null, realIP); } } catch (Exception e) { logger.warning("Exception while trying to get the Initial IP Address and Port: "+e); } return uri; } @Override public void onReceive(Object message) throws Exception { final Class<?> klass = message.getClass(); final ActorRef self = self(); final ActorRef sender = sender(); final State state = fsm.state(); if(logger.isInfoEnabled()) { logger.info("********** Call's " + self().path() + " Current State: \"" + state.toString()+" direction: "+direction); logger.info("********** Call " + self().path() + " Processing Message: \"" + klass.getName() + " sender : " + sender.path().toString()); } if (Observe.class.equals(klass)) { onObserve((Observe) message, self, sender); } else if (StopObserving.class.equals(klass)) { onStopObserving((StopObserving) message, self, sender); } else if (GetCallObservers.class.equals(klass)) { onGetCallObservers((GetCallObservers) message, self, sender); } else if (GetCallInfo.class.equals(klass)) { onGetCallInfo((GetCallInfo) message, sender); } else if (InitializeOutbound.class.equals(klass)) { onInitializeOutbound((InitializeOutbound) message, self, sender); } else if (ChangeCallDirection.class.equals(klass)) { onChangeCallDirection((ChangeCallDirection) message, self, sender); } else if (Answer.class.equals(klass)) { onAnswer((Answer) message, self, sender); } else if (Dial.class.equals(klass)) { onDial((Dial) message, self, sender); } else if (Reject.class.equals(klass)) { onReject((Reject) message, self, sender); } else if (CallFail.class.equals(klass)) { fsm.transition(message, failed); } else if (JoinComplete.class.equals(klass)) { onJoinComplete((JoinComplete) message, self, sender); } else if (StartRecording.class.equals(klass)) { onStartRecordingCall((StartRecording) message, self, sender); } else if (StopRecording.class.equals(klass)) { onStopRecordingCall((StopRecording) message, self, sender); } else if (Cancel.class.equals(klass)) { onCancel((Cancel) message, self, sender); } else if (message instanceof ReceiveTimeout) { onReceiveTimeout((ReceiveTimeout) message, self, sender); } else if (message instanceof SipServletRequest) { onSipServletRequest((SipServletRequest) message, self, sender); } else if (message instanceof SipServletResponse) { onSipServletResponse((SipServletResponse) message, self, sender); } else if (Hangup.class.equals(klass)) { onHangup((Hangup) message, self, sender); } else if (org.restcomm.connect.telephony.api.NotFound.class.equals(klass)) { onNotFound((org.restcomm.connect.telephony.api.NotFound) message, self, sender); } else if (MediaServerControllerStateChanged.class.equals(klass)) { onMediaServerControllerStateChanged((MediaServerControllerStateChanged) message, self, sender); } else if (JoinConference.class.equals(klass)) { onJoinConference((JoinConference) message, self, sender); } else if (JoinBridge.class.equals(klass)) { onJoinBridge((JoinBridge) message, self, sender); } else if (Leave.class.equals(klass)) { onLeave((Leave) message, self, sender); } else if (Left.class.equals(klass)) { onLeft((Left) message, self, sender); } else if (Record.class.equals(klass)) { onRecord((Record) message, self, sender); } else if (Play.class.equals(klass)) { onPlay((Play) message, self, sender); } else if (Collect.class.equals(klass)) { onCollect((Collect) message, self, sender); } else if (StopMediaGroup.class.equals(klass)) { onStopMediaGroup((StopMediaGroup) message, self, sender); } else if (Mute.class.equals(klass)) { onMute((Mute) message, self, sender); } else if (Unmute.class.equals(klass)) { onUnmute((Unmute) message, self, sender); } else if (ConferenceResponse.class.equals(klass)) { onConferenceResponse((ConferenceResponse) message); } else if (BridgeStateChanged.class.equals(klass)) { onBridgeStateChanged((BridgeStateChanged) message, self, sender); } else if (CallHoldStateChange.class.equals(klass)) { onCallHoldStateChange((CallHoldStateChange)message, sender); } else if (StopWaiting.class.equals(klass)) { onStopWaiting((StopWaiting)message, sender); } else if (RecordStoped.class.equals(klass)) { onRecordStoped((RecordStoped) message, sender); } } @Override public void onTransitionEnd(State was, State is, Object event) { CallInfo callInfo = info(); if (callInfo != null) { getContext().system() .eventStream() .publish(new CallInfoStreamEvent(callInfo)); } } private void onStopWaiting(StopWaiting message, ActorRef sender) throws Exception { if(is(waitingForAnswer)) { sendInviteOk(); } } private void onConferenceResponse(ConferenceResponse conferenceResponse) { //ConferenceResponse received ConferenceInfo ci = (ConferenceInfo) conferenceResponse.get(); if (logger.isInfoEnabled()) { String infoMsg = String.format("Conference response, name %s, state %s, participants %d", ci.name(), ci.state(), ci.globalParticipants()); logger.info(infoMsg); } } private void onCallHoldStateChange(CallHoldStateChange message, ActorRef sender) throws IOException{ if (logger.isInfoEnabled()) { logger.info("CallHoldStateChange received, state: " + message.state() + " isOnHold " + isOnHold); } if(is(inProgress)){ if (!isOnHold && CallHoldStateChange.State.ONHOLD.equals(message.state())) { final SipServletRequest messageRequest = invite.getSession().createRequest("MESSAGE"); messageRequest.setContent(CALL_ON_HOLD_ACTION, "text/plain"); messageRequest.send(); isOnHold = true; } else if (isOnHold && CallHoldStateChange.State.OFFHOLD.equals(message.state())) { final SipServletRequest messageRequest = invite.getSession().createRequest("MESSAGE"); messageRequest.setContent(CALL_OFF_HOLD_ACTION, "text/plain"); messageRequest.send(); isOnHold = false; } } } private void onRecordStoped (RecordStoped message, ActorRef sender) { isStoppingRecord = false; if (is(stopping)) { msController.tell(new CloseMediaSession(), self()); context().setReceiveTimeout(Duration.create(2000, TimeUnit.MILLISECONDS)); } } private void addCustomHeaders(SipServletMessage message) { if (apiVersion != null) message.addHeader("X-RestComm-ApiVersion", apiVersion); if (accountId != null) message.addHeader("X-RestComm-AccountSid", accountId.toString()); // no need to append instance id, it will already be part of call sid by default // https://github.com/RestComm/Restcomm-Connect/issues/1907 // message.addHeader("X-RestComm-CallSid", instanceId+"-"+id.toString()); message.addHeader("X-RestComm-CallSid", id.toString()); } // Allow updating of the callInfo at the VoiceInterpreter so that we can do Dial SIP Screening // (https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out) accurately from latest response // received private void sendCallInfoToObservers() { for (final ActorRef observer : this.observers) { observer.tell(new CallResponse(info()), self()); } } private void processInfo(final SipServletRequest request) throws IOException { //Seems we will receive DTMF over SIP INFO, we should start timeout timer //to simulate the collect timeout when using the RMS collectSipInfoDtmf = true; context().setReceiveTimeout(Duration.create(collectTimeout, TimeUnit.SECONDS)); final SipServletResponse okay = request.createResponse(SipServletResponse.SC_OK); addCustomHeaders(okay); okay.send(); String digits = null; if (request.getContentType().equalsIgnoreCase("application/dtmf-relay")) { final String content = new String(request.getRawContent()); digits = content.split("\n")[0].replaceFirst("Signal=", "").trim(); } else { digits = new String(request.getRawContent()); } if (digits != null) { MediaGroupResponse<String> infoResponse = new MediaGroupResponse<String>(digits); for (final ActorRef observer : observers) { observer.tell(infoResponse, self()); } this.msController.tell(new Stop(), self()); } } /* * ACTIONS */ private abstract class AbstractAction implements Action { protected final ActorRef source; public AbstractAction(final ActorRef source) { super(); this.source = source; } } private final class Queued extends AbstractAction { public Queued(final ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { final InitializeOutbound request = (InitializeOutbound) message; name = request.name(); from = request.from(); to = request.to(); apiVersion = request.apiVersion(); accountId = request.accountId(); username = request.username(); password = request.password(); type = request.type(); parentCallSid = request.getParentCallSid(); recordsDao = request.getDaoManager().getCallDetailRecordsDao(); isFromApi = request.isFromApi(); outboundToIms = request.isOutboundToIms(); imsProxyAddress = request.getImsProxyAddress(); imsProxyPort = request.getImsProxyPort(); String toHeaderString = to.toString(); rcmlHeaders = new HashMap<String, String>(); if (toHeaderString.indexOf('?') != -1) { // custom headers parsing for SIP Out // https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out // we keep only the to URI without the headers to = (SipURI) factory.createURI(toHeaderString.substring(0, toHeaderString.lastIndexOf('?'))); String headersString = toHeaderString.substring(toHeaderString.lastIndexOf('?') + 1); StringTokenizer tokenizer = new StringTokenizer(headersString, "&"); while (tokenizer.hasMoreTokens()) { String headerNameValue = tokenizer.nextToken(); String headerName = headerNameValue.substring(0, headerNameValue.lastIndexOf('=')); String headerValue = headerNameValue.substring(headerNameValue.lastIndexOf('=') + 1); rcmlHeaders.put(headerName, headerValue); } } timeout = request.timeout(); direction = request.isFromApi() ? OUTBOUND_API : OUTBOUND_DIAL; webrtc = request.isWebrtc(); mediaAttributes = request.getMediaAttributes(); // Notify the observers. external = CallStateChanged.State.QUEUED; final CallStateChanged event = new CallStateChanged(external); for (final ActorRef observer : observers) { observer.tell(event, source); } if (recordsDao != null) { CallDetailRecord cdr = recordsDao.getCallDetailRecord(id); if (cdr == null) { final CallDetailRecord.Builder builder = CallDetailRecord.builder(); builder.setSid(id); builder.setInstanceId(RestcommConfiguration.getInstance().getMain().getInstanceId()); builder.setDateCreated(created); builder.setAccountSid(accountId); String toUser = null; if(to.isSipURI()){ toUser = ((SipURI)to).getUser(); } else{ toUser = ((TelURL)to).getPhoneNumber(); } builder.setTo(toUser); builder.setCallerName(name); builder.setStartTime(new DateTime()); String fromString = (from.getUser() != null ? from.getUser() : "CALLS REST API"); builder.setFrom(fromString); // builder.setForwardedFrom(callInfo.forwardedFrom()); // builder.setPhoneNumberSid(phoneId); builder.setStatus(external.name()); builder.setDirection("outbound-api"); builder.setApiVersion(apiVersion); builder.setPrice(new BigDecimal("0.00")); // TODO implement currency property to be read from Configuration builder.setPriceUnit(Currency.getInstance("USD")); final StringBuilder buffer = new StringBuilder(); buffer.append("/").append(apiVersion).append("/Accounts/"); buffer.append(accountId.toString()).append("/Calls/"); buffer.append(id.toString()); final URI uri = URI.create(buffer.toString()); builder.setUri(uri); builder.setCallPath(self().path().toString()); builder.setParentCallSid(parentCallSid); outgoingCallRecord = builder.build(); recordsDao.addCallDetailRecord(outgoingCallRecord); } else { cdr.setStatus(external.name()); } } } } private final class Dialing extends AbstractAction { public Dialing(final ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { final MediaServerControllerStateChanged response = (MediaServerControllerStateChanged) message; final ActorRef self = self(); mediaSessionInfo = response.getMediaSession(); // Create a SIP invite to initiate a new session. final SipURI uri; if (!outboundToIms) { final StringBuilder buffer = new StringBuilder(); buffer.append(((SipURI)to).getHost()); if (((SipURI)to).getPort() > -1) { buffer.append(":").append(((SipURI)to).getPort()); } String transport = ((SipURI)to).getTransportParam(); if (transport != null) { buffer.append(";transport=").append(((SipURI)to).getTransportParam()); } uri = factory.createSipURI(null, buffer.toString()); } else { uri = factory.createSipURI(null, imsProxyAddress); uri.setPort(imsProxyPort); uri.setLrParam(true); } final SipApplicationSession application = factory.createApplicationSession(); application.setAttribute(Call.class.getName(), self); String callId = null; String userAgent = null; if(outboundToIms && !configuration.subset("runtime-settings").subset("ims-authentication").isEmpty()){ final Configuration imsAuthentication = configuration.subset("runtime-settings").subset("ims-authentication"); final String callIdPrefix = imsAuthentication.getString("call-id-prefix"); userAgent = imsAuthentication.getString("user-agent"); callId = callIdPrefix + UUID.randomUUID().toString(); } if (name != null && !name.isEmpty()) { // Create the from address using the inital user displayed name // Example: From: "Alice" <sip:userpart@host:port> final Address fromAddress = factory.createAddress(from, name); final Address toAddress = factory.createAddress(to); invite = ((SipFactoryExt)factory).createRequestWithCallID(application, "INVITE", fromAddress, toAddress, callId); } else { invite = ((SipFactoryExt)factory).createRequestWithCallID(application, "INVITE", from, to, callId); } if(!useSbc) { invite.pushRoute(uri); } if(userAgent!=null){ invite.setHeader("User-Agent", userAgent); } addCustomHeadersToMap(rcmlHeaders); // adding custom headers for SIP Out // https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out addHeadersToMessage(invite, rcmlHeaders, "X-"); //the extension headers will override any headers B2BUAHelper.addHeadersToMessage(invite, extensionHeaders, factory); final SipSession session = invite.getSession(); session.setHandler("CallManager"); // Issue: https://telestax.atlassian.net/browse/RESTCOMM-608 // If this is a call to Restcomm client or SIP URI bypass LB if (logger.isInfoEnabled()) logger.info("bypassLoadBalancer is set to: "+RestcommConfiguration.getInstance().getMain().getBypassLbForClients()); if (RestcommConfiguration.getInstance().getMain().getBypassLbForClients()) { if (type.equals(CreateCallType.CLIENT) || type.equals(CreateCallType.SIP)) { ((SipSessionExt) session).setBypassLoadBalancer(true); ((SipSessionExt) session).setBypassProxy(true); } } String offer = null; if (mediaSessionInfo.usesNat()) { final String externalIp = mediaSessionInfo.getExternalAddress().getHostAddress(); final byte[] sdp = mediaSessionInfo.getLocalSdp().getBytes(); offer = SdpUtils.patch("application/sdp", sdp, externalIp); } else { offer = mediaSessionInfo.getLocalSdp(); } offer = SdpUtils.endWithNewLine(offer); invite.setContent(offer, "application/sdp"); // Send the invite. invite.send(); // Set the timeout period. // final UntypedActorContext context = getContext(); // if (logger.isDebugEnabled()) { // logger.debug("About to set timeout to "+timeout); // } // context.setReceiveTimeout(Duration.create(timeout, TimeUnit.SECONDS)); // deadline = Duration.create(timeout, TimeUnit.SECONDS).fromNow(); // if (deadline != null) { // String msg = String.format("Deadline left %s", deadline.timeLeft().toSeconds()); // logger.debug(msg); // } executeStatusCallback(CallbackState.INITIATED, false); } /** * addCustomHeadersToMap */ private void addCustomHeadersToMap(Map<String, String> headers) { if (apiVersion != null) headers.put("RestComm-ApiVersion", apiVersion); if (accountId != null) headers.put("RestComm-AccountSid", accountId.toString()); headers.put("RestComm-CallSid", id.toString()); } //TODO: put this in a central place private void addHeadersToMessage(SipServletRequest message, Map<String, String> headers, String keyPrepend) { try { for (Map.Entry<String, String> entry : headers.entrySet()) { String headerName = null; if (entry.getKey().startsWith("X-")) { headerName = entry.getKey(); } else { headerName = keyPrepend + entry.getKey(); } message.addHeader(headerName , entry.getValue()); } } catch (IllegalArgumentException iae) { if(logger.isErrorEnabled()) { logger.error("Exception while setting message header: "+iae.getMessage()); } } } } private final class Ringing extends AbstractAction { public Ringing(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { if (message instanceof SipServletRequest) { invite = (SipServletRequest) message; from = (SipURI) invite.getFrom().getURI(); to = invite.getTo().getURI(); timeout = -1; direction = INBOUND; try { // Send a ringing response final SipServletResponse ringing = invite.createResponse(SipServletResponse.SC_RINGING); addCustomHeaders(ringing); // ringing.addHeader("X-RestComm-CallSid", id.toString()); ringing.send(); } catch (IllegalStateException exception) { if(logger.isDebugEnabled()) { logger.debug("Exception while creating 180 response to inbound invite request, "+exception); } fsm.transition(message, canceled); } SipURI initialInetUri = getInitialIpAddressPort(invite); if (initialInetUri != null) { invite.getSession().setAttribute("realInetUri", initialInetUri); } } else if (message instanceof SipServletResponse) { // Timeout still valid in case we receive a 180, we don't know if the // call will be eventually answered. // Issue 585: https://telestax.atlassian.net/browse/RESTCOMM-585 // final UntypedActorContext context = getContext(); // context.setReceiveTimeout(Duration.Undefined()); SipURI initialInetUri = getInitialIpAddressPort((SipServletResponse)message); if (initialInetUri != null) { ((SipServletResponse)message).getSession().setAttribute("realInetUri", initialInetUri); } executeStatusCallback(CallbackState.RINGING, false); } // Notify the observers. external = CallStateChanged.State.RINGING; final CallStateChanged event = new CallStateChanged(external); for (final ActorRef observer : observers) { observer.tell(event, source); } if (outgoingCallRecord != null && isOutbound()) { outgoingCallRecord = outgoingCallRecord.setStatus(external.name()); recordsDao.updateCallDetailRecord(outgoingCallRecord); } } } private final class Canceling extends AbstractAction { public Canceling(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { try { if (isOutbound() && (invite.getSession().getState() != SipSession.State.INITIAL || invite.getSession().getState() != SipSession.State.TERMINATED)) { if(invite.getSession().getState() != SipSession.State.CONFIRMED) { final UntypedActorContext context = getContext(); context.setReceiveTimeout(Duration.Undefined()); final SipServletRequest cancel = invite.createCancel(); addCustomHeaders(cancel); cancel.send(); if (logger.isInfoEnabled()) { logger.info("Sent CANCEL for Call: "+self().path()+", state: "+fsm.state()+", direction: "+direction); } } else { // if sip session is already confirmed, cancel wont work so we need to send bye. // https://telestax.atlassian.net/browse/RESTCOMM-1623 if (logger.isInfoEnabled()) { logger.info("Got Cancel request for call: "+self().path()+", state: "+fsm.state()+", direction: "+direction); logger.info("Call's sip session is already confirmed so restcomm will send BYE instead of CANCEL."); sendBye(new Hangup()); } } } } catch (Exception e) { StringBuffer strBuffer = new StringBuffer(); strBuffer.append("Exception while trying to create Cancel for Call with the following details, from: "+from+" to: "+to+" direction: "+direction+" call state: "+fsm.state()); if (invite != null) { strBuffer.append(" , invite RURI: "+invite.getRequestURI()); } else { strBuffer.append(" , invite is NULL! "); } strBuffer.append(" Exception: "+e.getMessage()); logger.warning(strBuffer.toString()); } msController.tell(new CloseMediaSession(), source); //Github issue 2261 - https://github.com/RestComm/Restcomm-Connect/issues/2261 //Set a ReceivedTimeout duration to make sure call doesn't block waiting for the response from MmsCallController context().setReceiveTimeout(Duration.create(2000, TimeUnit.MILLISECONDS)); } } private final class Canceled extends AbstractAction { public Canceled(ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { //A no-answer call will be cancelled and will arrive here. In that case don't change the external case //since no-answer is a final state and we need to keep it so observer knows how the call ended // if (!external.equals(CallStateChanged.State.NO_ANSWER)) { external = CallStateChanged.State.CANCELED; // final CallStateChanged event = new CallStateChanged(external); // for (final ActorRef observer : observers) { // observer.tell(event, source); // } // } // Record call data if (outgoingCallRecord != null && isOutbound()) { if(logger.isInfoEnabled()) { logger.info("Going to update CDR to CANCEL, call sid: "+id+" from: "+from+" to: "+to+" direction: "+direction); } outgoingCallRecord = outgoingCallRecord.setStatus(external.name()); recordsDao.updateCallDetailRecord(outgoingCallRecord); } fsm.transition(message, completed); } } private abstract class Failing extends AbstractAction { public Failing(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { if (message instanceof ReceiveTimeout) { final UntypedActorContext context = getContext(); context.setReceiveTimeout(Duration.Undefined()); } callUpdatedTime = DateTime.now(); msController.tell(new CloseMediaSession(), source); } } private final class FailingBusy extends Failing { public FailingBusy(final ActorRef source) { super(source); } } private final class FailingNoAnswer extends Failing { public FailingNoAnswer(final ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { if(logger.isInfoEnabled()) { logger.info("Call moves to failing state because no answer"); } fsm.transition(message, noAnswer); } } private final class Busy extends AbstractAction { public Busy(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); // Send SIP BUSY to remote peer if (Reject.class.equals(klass) && is(ringing) && isInbound()) { Reject reject = (Reject) message; SipServletResponse rejectResponse; if (reject.getReason().equalsIgnoreCase("busy")) { rejectResponse = invite.createResponse(SipServletResponse.SC_BUSY_HERE); } else { rejectResponse = invite.createResponse(SipServletResponse.SC_DECLINE); } addCustomHeaders(rejectResponse); rejectResponse.send(); } // Explicitly invalidate the application session. // if (invite.getSession().isValid()) // invite.getSession().invalidate(); // if (invite.getApplicationSession().isValid()) // invite.getApplicationSession().invalidate(); // Notify the observers. external = CallStateChanged.State.BUSY; final CallStateChanged event = new CallStateChanged(external, lastResponse.getStatus()); for (final ActorRef observer : observers) { observer.tell(event, source); } // Record call data if (outgoingCallRecord != null && isOutbound()) { outgoingCallRecord = outgoingCallRecord.setStatus(external.name()); recordsDao.updateCallDetailRecord(outgoingCallRecord); outgoingCallRecord = outgoingCallRecord.setDuration(0); recordsDao.updateCallDetailRecord(outgoingCallRecord); final int seconds = (int) ((DateTime.now().getMillis() - outgoingCallRecord.getStartTime().getMillis()) / 1000); outgoingCallRecord = outgoingCallRecord.setRingDuration(seconds); recordsDao.updateCallDetailRecord(outgoingCallRecord); } if(isOutbound()){ executeStatusCallback(CallbackState.COMPLETED, true); } } } private final class NotFound extends AbstractAction { public NotFound(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); // Send SIP NOT_FOUND to remote peer if (org.restcomm.connect.telephony.api.NotFound.class.equals(klass) && isInbound()) { final SipServletResponse notFound = invite.createResponse(SipServletResponse.SC_NOT_FOUND); addCustomHeaders(notFound); notFound.send(); } // Notify the observers. external = CallStateChanged.State.NOT_FOUND; final CallStateChanged event = new CallStateChanged(external, SipServletResponse.SC_NOT_FOUND); for (final ActorRef observer : observers) { observer.tell(event, source); } // Record call data if (outgoingCallRecord != null && isOutbound()) { outgoingCallRecord = outgoingCallRecord.setStatus(external.name()); recordsDao.updateCallDetailRecord(outgoingCallRecord); } } } private final class NoAnswer extends AbstractAction { public NoAnswer(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { // // Explicitly invalidate the application session. // if (invite.getSession().isValid()) // invite.getSession().invalidate(); // if (invite.getApplicationSession().isValid()) // invite.getApplicationSession().invalidate(); // Notify the observers. external = CallStateChanged.State.NO_ANSWER; final CallStateChanged event = new CallStateChanged(external, SipServletResponse.SC_REQUEST_TIMEOUT); for (final ActorRef observer : observers) { observer.tell(event, source); } // Record call data if (outgoingCallRecord != null && isOutbound()) { outgoingCallRecord = outgoingCallRecord.setStatus(external.name()); recordsDao.updateCallDetailRecord(outgoingCallRecord); } } } private final class Failed extends AbstractAction { public Failed(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { if (isInbound()) { try { SipSession session = invite.getSession(); SipSession.State sessionState = session.getState(); if (session.isValid()) { if (sessionState.name().equalsIgnoreCase(SipSession.State.CONFIRMED.name()) && !receivedBye) { //send BYE Hangup hangup = (message instanceof Hangup) ? (Hangup)message : new Hangup(); sendBye(hangup); } else if (!sessionState.name().equalsIgnoreCase(SipSession.State.TERMINATED.name())){ //send invite response SipServletResponse resp = null; if (message instanceof CallFail) { resp = invite.createResponse(500, "Problem to setup the call"); String reason = ((CallFail) message).getReason(); if (reason != null) resp.addHeader("Reason", reason); } else { // https://github.com/RestComm/Restcomm-Connect/issues/1663 // We use 569 only if there is a problem to reach RMS as LB can be configured to take out // nodes that send back 569. This is meant to protect the cluster from nodes where the RMS // is in bad state and not responding anymore resp = invite.createResponse(MEDIA_SERVER_FAILURE_RESPONSE_CODE, "Problem to setup services"); } addCustomHeaders(resp); resp.send(); } } } catch (Exception e) { logger.error("Exception while trying to prepare failed response, exception: "+e); } } else { if (message instanceof CallFail) sendBye(new Hangup(((CallFail) message).getReason())); } // Notify the observers. external = CallStateChanged.State.FAILED; CallStateChanged event = null; if (lastResponse != null) { event = new CallStateChanged(external, lastResponse.getStatus()); } else { event = new CallStateChanged(external); } for (final ActorRef observer : observers) { observer.tell(event, source); } // Record call data if (outgoingCallRecord != null && isOutbound()) { outgoingCallRecord = outgoingCallRecord.setStatus(external.name()); recordsDao.updateCallDetailRecord(outgoingCallRecord); } if(isOutbound()){ executeStatusCallback(CallbackState.COMPLETED, true); } } } private final class Initializing extends AbstractAction { public Initializing(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { // Start observing state changes in the MSController final Observe observe = new Observe(super.source); msController.tell(observe, super.source); // Initialize the MS Controller CreateMediaSession command = null; if (isOutbound()) { command = new CreateMediaSession("sendrecv", "", true, webrtc, id, mediaAttributes); } else { if (!liveCallModification) { command = generateRequest(invite); } else { if (lastResponse != null && lastResponse.getStatus() == 200) { command = generateRequest(lastResponse); } // TODO no else may lead to NullPointerException } } msController.tell(command, source); } } private final class InDialogRequest extends AbstractAction { public InDialogRequest(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { SipServletRequest request = (SipServletRequest) message; if (logger.isDebugEnabled()) { logger.debug("IN-Dialog INVITE received: "+request.getRequestURI().toString()); } CreateMediaSession command = generateRequest(request); msController.tell(command, self()); } } private CreateMediaSession generateRequest(SipServletMessage sipMessage) throws IOException, SdpException, ServletParseException { final byte[] sdp = sipMessage.getRawContent(); String offer = SdpUtils.getSdp(sipMessage.getContentType(), sipMessage.getRawContent()); if (!disableSdpPatchingOnUpdatingMediaSession) { String externalIp = null; final SipURI externalSipUri = (SipURI) sipMessage.getSession().getAttribute("realInetUri"); if (externalSipUri != null) { if (logger.isInfoEnabled()) { logger.info("ExternalSipUri stored in the sip session : " + externalSipUri.toString() + " will use host: " + externalSipUri.getHost().toString()); } externalIp = externalSipUri.getHost().toString(); } else { externalIp = sipMessage.getInitialRemoteAddr(); if (logger.isInfoEnabled()) { logger.info("ExternalSipUri stored in the session was null, will use the message InitialRemoteAddr: " + externalIp); } } offer = SdpUtils.patch(sipMessage.getContentType(), sdp, externalIp); } //Prepare media attributes to be used by call controller final boolean isAudioSdp = SdpUtils.isAudioSDP(sipMessage.getContentType(), sipMessage.getRawContent()); final boolean isVideoSdp = SdpUtils.isVideoSDP(sipMessage.getContentType(), sipMessage.getRawContent()); if(isAudioSdp && isVideoSdp){ //Call with audio and video mediaAttributes = new MediaAttributes(MediaAttributes.MediaType.AUDIO_VIDEO, MediaAttributes.VideoResolution.SEVEN_TWENTY_P); } else if (isVideoSdp) { //Call with video and no audio mediaAttributes = new MediaAttributes(MediaAttributes.MediaType.VIDEO_ONLY, MediaAttributes.VideoResolution.SEVEN_TWENTY_P); } //mediaAttributes remains with default value (AUDIO_ONLY) if both isAudioSdp and isVideoSdp are false return new CreateMediaSession("sendrecv", offer, false, webrtc, inboundCallSid, mediaAttributes); } private final class UpdatingMediaSession extends AbstractAction { public UpdatingMediaSession(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { if (is(dialing) || is(ringing)) { final UntypedActorContext context = getContext(); context.setReceiveTimeout(Duration.Undefined()); } final SipServletResponse response = (SipServletResponse) message; // Issue 99: https://bitbucket.org/telestax/telscale-restcomm/issue/99 if (response.getStatus() == SipServletResponse.SC_OK && isOutbound()) { String initialIpBeforeLB = null; String initialPortBeforeLB = null; try { initialIpBeforeLB = response.getHeader("X-Sip-Balancer-InitialRemoteAddr"); initialPortBeforeLB = response.getHeader("X-Sip-Balancer-InitialRemotePort"); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Exception during check of LB custom headers for IP address and port"); } } final SipServletRequest ack = response.createAck(); addCustomHeaders(ack); SipSession session = response.getSession(); if (initialIpBeforeLB != null ) { if (initialPortBeforeLB == null) initialPortBeforeLB = "5060"; if (logger.isDebugEnabled()) { logger.debug("We are behind load balancer, checking if the request URI needs to be patched"); } String realIP = initialIpBeforeLB + ":" + initialPortBeforeLB; SipURI uri = factory.createSipURI(((SipURI) ack.getRequestURI()).getUser(), realIP); boolean patchRURI = true; try { // https://github.com/RestComm/Restcomm-Connect/issues/1336 checking if the initial IP and Port behind LB is part of the route set or not ListIterator<? extends Address> routes = ack.getAddressHeaders(RouteHeader.NAME); while(routes.hasNext() && patchRURI) { SipURI route = (SipURI) routes.next().getURI(); String routeHost = route.getHost(); int routePort = route.getPort(); if(routePort < 0) { routePort = 5060; } if (logger.isDebugEnabled()) { logger.debug("Checking if route " + routeHost + ":" + routePort + " is matching ip and port before LB " + initialIpBeforeLB + ":" + initialPortBeforeLB + " for the ACK request"); } if(routeHost.equalsIgnoreCase(initialIpBeforeLB) && routePort == Integer.parseInt(initialPortBeforeLB)) { if (logger.isDebugEnabled()) { logger.debug("route " + route + " is matching ip and port before LB " + initialIpBeforeLB + ":" + initialPortBeforeLB + " for the ACK request, so not patching the Request-URI"); } patchRURI = false; } } } catch (ServletParseException e) { logger.error("Impossible to parse the route set from the ACK " + ack, e); } if(patchRURI) { if(logger.isDebugEnabled()) { logger.debug("We are behind load balancer, will use: " + initialIpBeforeLB + ":" + initialPortBeforeLB + " for ACK message, "); } ack.setRequestURI(uri); } } else if (!ack.getHeaders("Route").hasNext()) { final SipServletRequest originalInvite = response.getRequest(); final SipURI realInetUri = (SipURI) originalInvite.getRequestURI(); if ((SipURI) session.getAttribute("realInetUri") == null) { // session.setAttribute("realInetUri", factory.createSipURI(null, realInetUri.getHost()+":"+realInetUri.getPort())); session.setAttribute("realInetUri", realInetUri); } final InetAddress ackRURI = DNSUtils.getByName(((SipURI) ack.getRequestURI()).getHost()); final int ackRURIPort = ((SipURI) ack.getRequestURI()).getPort(); if (realInetUri != null && (ackRURI.isSiteLocalAddress() || ackRURI.isAnyLocalAddress() || ackRURI.isLoopbackAddress()) && (ackRURIPort != realInetUri.getPort())) { if(logger.isInfoEnabled()) { logger.info("Using the real ip address and port of the sip client " + realInetUri.toString() + " as a request uri of the ACK"); } realInetUri.setUser(((SipURI) ack.getRequestURI()).getUser()); ack.setRequestURI(realInetUri); } } ack.send(); if(logger.isInfoEnabled()) { logger.info("Just sent out ACK : " + ack.toString()); } } //Set Call created time, only for "Talk time". callUpdatedTime = DateTime.now(); //Update CDR for Outbound Call. if (recordsDao != null) { if (outgoingCallRecord != null && isOutbound()) { final int seconds = (int) ((DateTime.now().getMillis() - outgoingCallRecord.getStartTime().getMillis()) / 1000); outgoingCallRecord = outgoingCallRecord.setRingDuration(seconds); recordsDao.updateCallDetailRecord(outgoingCallRecord); outgoingCallRecord = outgoingCallRecord.setStartTime(DateTime.now()); recordsDao.updateCallDetailRecord(outgoingCallRecord); outgoingCallRecord = outgoingCallRecord.setStatus(external.name()); recordsDao.updateCallDetailRecord(outgoingCallRecord); } } String answer = null; if (!disableSdpPatchingOnUpdatingMediaSession) { if (logger.isInfoEnabled()) { logger.info("Will patch SDP answer from 200 OK received with the external IP Address from Response on updating media session"); } final String externalIp = response.getInitialRemoteAddr(); final byte[] sdp = response.getRawContent(); answer = SdpUtils.patch(response.getContentType(), sdp, externalIp); } else { if (logger.isInfoEnabled()) { logger.info("SDP Patching on updating media session is disabled"); } answer = SdpUtils.getSdp(response.getContentType(), response.getRawContent()); } final UpdateMediaSession update = new UpdateMediaSession(answer); msController.tell(update, source); } } private final class WaitingForAnswer extends AbstractAction { public WaitingForAnswer(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { // Notify the observers. if (external != null && !external.equals(CallStateChanged.State.WAIT_FOR_ANSWER)) { external = CallStateChanged.State.WAIT_FOR_ANSWER; final CallStateChanged event = new CallStateChanged(external); for (final ActorRef observer : observers) { observer.tell(event, source); } } } } private final class InProgress extends AbstractAction { public InProgress(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { // Notify the observers. if (external != null && !external.equals(CallStateChanged.State.IN_PROGRESS)) { external = CallStateChanged.State.IN_PROGRESS; final CallStateChanged event = new CallStateChanged(external); for (final ActorRef observer : observers) { observer.tell(event, source); } // Record call data if (outgoingCallRecord != null && isOutbound() && !outgoingCallRecord.getStatus().equalsIgnoreCase("in_progress")) { outgoingCallRecord = outgoingCallRecord.setStatus(external.toString()); String toUser = null; if(to.isSipURI()){ toUser = ((SipURI)to).getUser(); } else{ toUser = ((TelURL)to).getPhoneNumber(); } outgoingCallRecord = outgoingCallRecord.setAnsweredBy(toUser); if (conferencing) { outgoingCallRecord = outgoingCallRecord.setConferenceSid(conferenceSid); outgoingCallRecord = outgoingCallRecord.setMuted(muted); } recordsDao.updateCallDetailRecord(outgoingCallRecord); } if (isOutbound()) { executeStatusCallback(CallbackState.ANSWERED, false); } } } } private final class Joining extends AbstractAction { public Joining(ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { msController.tell(message, super.source); } } private final class Leaving extends AbstractAction { public Leaving(ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { Leave leaveMsg = (Leave) message; if (!leaveMsg.isLiveCallModification()) { if (!receivedBye) { // Conference was stopped and this call was asked to leave // Send BYE to remote client sendBye(new Hangup("Conference time limit reached")); } } else { liveCallModification = true; } msController.tell(message, self()); } } private final class Stopping extends AbstractAction { public Stopping(final ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { // Stops media operations and closes media session if (logger.isDebugEnabled()) { if (message instanceof SipServletRequest) { logger.debug("At Call Stopping state because of SipServletRequest: "+((SipServletRequest)message).getMethod()); } else if (message instanceof Hangup) { logger.debug("At Call Stopping state because of Hangup: "+((Hangup)message)); } else { logger.debug("At Call Stopping state because of Message: "+message); } } // If working with XMS and RC is trying to stop Recording, Should not send CloseMediaSession otherwise this signal will be Ignore by RC. if (!isStoppingRecord || !msCompatibilityMode.equalsIgnoreCase("xms")) { msController.tell(new CloseMediaSession(), source); //Github issue 2261 - https://github.com/RestComm/Restcomm-Connect/issues/2261 //Set a ReceivedTimeout duration to make sure call doesn't block waiting for the response from MmsCallController context().setReceiveTimeout(Duration.create(2000, TimeUnit.MILLISECONDS)); } } } private final class Completed extends AbstractAction { public Completed(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { if(logger.isInfoEnabled()) { logger.info("Completing Call sid: "+id+" from: "+from+" to: "+to+" direction: "+direction+" current external state: "+external); } //In the case of canceled that reach the completed method, don't change the external state if (!external.equals(CallStateChanged.State.CANCELED)) { // Notify the observers. external = CallStateChanged.State.COMPLETED; } CallStateChanged event = new CallStateChanged(external); if (external.equals(CallStateChanged.State.CANCELED)) { event = new CallStateChanged(external); } for (final ActorRef observer : observers) { observer.tell(event, source); } if(logger.isInfoEnabled()) { logger.info("Call sid: "+id+" from: "+from+" to: "+to+" direction: "+direction+" new external state: "+external); } // Record call data if (outgoingCallRecord != null && isOutbound()) { outgoingCallRecord = outgoingCallRecord.setStatus(external.toString()); final DateTime now = DateTime.now(); outgoingCallRecord = outgoingCallRecord.setEndTime(now); callDuration = (int) ((now.getMillis() - outgoingCallRecord.getStartTime().getMillis()) / 1000); outgoingCallRecord = outgoingCallRecord.setDuration(callDuration); recordsDao.updateCallDetailRecord(outgoingCallRecord); if(logger.isDebugEnabled()) { logger.debug("Start: " + outgoingCallRecord.getStartTime()); logger.debug("End: " + outgoingCallRecord.getEndTime()); logger.debug("Duration: " + callDuration); logger.debug("Just updated CDR for completed call"); } } if (isOutbound()) { executeStatusCallback(CallbackState.COMPLETED, true); } } } /* * EVENTS */ private void onRecord(Record message, ActorRef self, ActorRef sender) { if (is(inProgress)) { // Forward to media server controller this.recording = true; this.msController.tell(message, sender); } } private void onPlay(Play message, ActorRef self, ActorRef sender) { if (is(inProgress)) { // Forward to media server controller this.msController.tell(message, sender); } } private void onCollect(Collect message, ActorRef self, ActorRef sender) { if (is(inProgress)) { collectTimeout = message.timeout(); collectFinishKey = message.endInputKey(); // Forward to media server controller this.msController.tell(message, sender); } } private void onStopMediaGroup(StopMediaGroup message, ActorRef self, ActorRef sender) { if (is(inProgress) || is(waitingForAnswer)) { // Forward to media server controller this.msController.tell(message, sender); if (conferencing && message.isLiveCallModification()) { liveCallModification = true; self().tell(new Leave(true), self()); } } else { if (logger.isDebugEnabled()) { logger.debug("Got StopMediaGroup but Call is already in state: "+fsm.state()); } } } private void onMute(Mute message, ActorRef self, ActorRef sender) { if (is(inProgress)) { // Forward to media server controller this.msController.tell(message, sender); muted = true; } } private void onUnmute(Unmute message, ActorRef self, ActorRef sender) { if (is(inProgress) && muted) { // Forward to media server controller this.msController.tell(message, sender); muted = false; if (logger.isInfoEnabled()) { final String infoMsg = String.format("Call %s, direction %s, unmuted", self().path(), direction); logger.info(infoMsg); } } } private void onObserve(Observe message, ActorRef self, ActorRef sender) throws Exception { final ActorRef observer = message.observer(); if (observer != null) { synchronized (this.observers) { this.observers.add(observer); observer.tell(new Observing(self), self); } } } private void onStopObserving(StopObserving stopObservingMessage, ActorRef self, ActorRef sender) throws Exception { final ActorRef observer = stopObservingMessage.observer(); if (observer != null) { observer.tell(stopObservingMessage, self); this.observers.remove(observer); } else { Iterator<ActorRef> observerIter = observers.iterator(); while (observerIter.hasNext()) { ActorRef observerNext = observerIter.next(); observerNext.tell(stopObservingMessage, self); if(logger.isInfoEnabled()) { logger.info("Sent stop observing for call, from: "+from+" to: "+to+" direction: "+direction+" to observer: "+observerNext.path()+" observer is terminated: "+observerNext.isTerminated()); } // this.observers.remove(observerNext); } this.observers.clear(); } } private void onGetCallObservers(GetCallObservers message, ActorRef self, ActorRef sender) throws Exception { sender.tell(new CallResponse<List<ActorRef>>(this.observers), self); } private void onGetCallInfo(GetCallInfo message, ActorRef sender) throws Exception { sender.tell(new CallResponse(info()), self()); } private void onInitializeOutbound(InitializeOutbound message, ActorRef self, ActorRef sender) throws Exception { if (is(uninitialized)) { fsm.transition(message, queued); } } private void onChangeCallDirection(ChangeCallDirection message, ActorRef self, ActorRef sender) { // Needed for LiveCallModification API where the outgoing call also needs to move to the new destination. this.direction = INBOUND; this.liveCallModification = true; this.conferencing = false; this.conference = null; this.bridge = null; } private void onAnswer(Answer message, ActorRef self, ActorRef sender) throws Exception { inboundCallSid = message.callSid(); inboundConfirmCall = message.confirmCall(); if (is(ringing) && !invite.getSession().getState().equals(SipSession.State.TERMINATED)) { fsm.transition(message, initializing); } else { fsm.transition(message, canceled); } } private void onDial(Dial message, ActorRef self, ActorRef sender) throws Exception { if (is(queued)) { fsm.transition(message, initializing); } } private void onReject(Reject message, ActorRef self, ActorRef sender) throws Exception { if (is(ringing)) { fsm.transition(message, busy); } } private void onCancel(Cancel message, ActorRef self, ActorRef sender) throws Exception { if (is(initializing) || is(dialing) || is(ringing) || is(failingNoAnswer)) { if(logger.isInfoEnabled()) { String msg = String.format("Got Cancel %s for call %s, from %s, to %s, direction %s, fsm state %s, will Cancel the call", message, self(), from, to, direction, fsm.state()); logger.info(msg); } fsm.transition(message, canceling); } else if (is(inProgress) || is(updatingMediaSession)) { if(logger.isInfoEnabled()) { String msg = String.format("Got Cancel %s for call %s, from %s, to %s, direction %s, fsm state %s, will Hangup the call", message, self(), from, to, direction, fsm.state()); logger.info(msg); } onHangup(new Hangup(), self(), sender()); } else { if(logger.isInfoEnabled()) { String msg = String.format("Got Cancel %s for call %s, from %s, to %s, direction %s, fsm state %s", message, self(), from, to, direction, fsm.state()); logger.info(msg); } } } private void onReceiveTimeout(ReceiveTimeout message, ActorRef self, ActorRef sender) throws Exception { getContext().setReceiveTimeout(Duration.Undefined()); if (is(ringing) || is(dialing)) { fsm.transition(message, failingNoAnswer); } else if(is(inProgress) && collectSipInfoDtmf) { if (logger.isInfoEnabled()) { logger.info("Collecting DTMF with SIP INFO, inter digit timeout fired. Will send finishKey to observers"); } MediaGroupResponse<String> infoResponse = new MediaGroupResponse<String>(collectFinishKey); for (final ActorRef observer : observers) { observer.tell(infoResponse, self()); } } else if (is(stopping)) { if (logger.isInfoEnabled()) { //Github issue 2261 - https://github.com/RestComm/Restcomm-Connect/issues/2261 String msg = "Seems that MmsCallControler response from stopping never arrived, move the FSM accordingly"; logger.info(msg); } context().setReceiveTimeout(Duration.Undefined()); if (fail) { if (logger.isDebugEnabled()) { logger.debug("OnReceiveTimeout - moving to Failed state"); } fsm.transition(message, failed); } else { if (logger.isDebugEnabled()) { logger.debug("OnReceiveTimeout - moving to Completed state"); } fsm.transition(message, completed); } } else if(logger.isInfoEnabled()) { logger.info("Timeout received for Call : "+self().path()+" isTerminated(): "+self().isTerminated()+". Sender: " + sender.path().toString() + " State: " + this.fsm.state() + " Direction: " + direction + " From: " + from + " To: " + to); } } private void onSipServletRequest(SipServletRequest message, ActorRef self, ActorRef sender) throws Exception { final String method = message.getMethod(); if ("INVITE".equalsIgnoreCase(method)) { if (is(uninitialized)) { fsm.transition(message, ringing); } if (is(inProgress)) { if (logger.isDebugEnabled()) { logger.debug("IN-Dialog INVITE received: "+message.getRequestURI().toString()); } inDialogInvite = message; String answer = null; if (!disableSdpPatchingOnUpdatingMediaSession) { if (logger.isInfoEnabled()) { logger.info("Will patch SDP answer from 200 OK received with the external IP Address from Response on updating media session"); } final String externalIp = message.getInitialRemoteAddr(); final byte[] sdp = message.getRawContent(); answer = SdpUtils.patch(message.getContentType(), sdp, externalIp); } else { if (logger.isInfoEnabled()) { logger.info("SDP Patching on updating media session is disabled"); } answer = SdpUtils.getSdp(message.getContentType(), message.getRawContent()); } final UpdateMediaSession update = new UpdateMediaSession(answer); msController.tell(update, self()); if(isCallOnHoldSdp(answer)){ final CallHoldStateChange.State onHold = CallHoldStateChange.State.ONHOLD; for (final ActorRef observer : this.observers) { observer.tell(new CallHoldStateChange(onHold), self()); } } else if(isCallOffHoldSdp(answer)){ final CallHoldStateChange.State offHold = CallHoldStateChange.State.OFFHOLD; for (final ActorRef observer : this.observers) { observer.tell(new CallHoldStateChange(offHold), self()); } } } } else if ("CANCEL".equalsIgnoreCase(method)) { if (is(initializing)) { fsm.transition(message, canceling); } else if ((is(ringing) || is(waitingForAnswer)) && isInbound()) { fsm.transition(message, canceling); } // XXX can receive SIP cancel any other time? } else if ("BYE".equalsIgnoreCase(method)) { // Reply to BYE with OK this.receivedBye = true; final SipServletRequest bye = (SipServletRequest) message; final SipServletResponse okay = bye.createResponse(SipServletResponse.SC_OK); okay.send(); // Stop recording if necessary if (recording) { if (!direction.contains("outbound")) { // Initial Call sent BYE recording = false; isStoppingRecord = true; if(logger.isInfoEnabled()) { logger.info("Call Direction: " + direction); logger.info("Initial Call - Will stop recording now"); } msController.tell(new Stop(false), self); return; } else if (direction.equalsIgnoreCase("outbound-api")){ //REST API Outgoing call, calculate recording recordingDuration = (DateTime.now().getMillis() - recordingStart.getMillis())/1000; } else if (conference != null) { // Outbound call sent BYE. !Important conference is the initial call here. conference.tell(new StopRecording(accountId, runtimeSettings, daoManager), null); } } if (conferencing) { // Tell conference to remove the call from participants list // before moving to a stopping state conference.tell(new RemoveParticipant(self), self); } else { // Clean media resources as necessary if (!is(completed)) fsm.transition(message, stopping); } } else if ("INFO".equalsIgnoreCase(method)) { processInfo(message); } else if ("ACK".equalsIgnoreCase(method)) { if (isInbound() && (is(initializing) || is(waitingForAnswer))) { if(logger.isInfoEnabled()) { logger.info("ACK received moving state to inProgress"); } fsm.transition(message, inProgress); } } } private void onSipServletResponse(SipServletResponse message, ActorRef self, ActorRef sender) throws Exception { this.lastResponse = message; final int code = message.getStatus(); switch (code) { case SipServletResponse.SC_CALL_BEING_FORWARDED: { forwarding(message); break; } case SipServletResponse.SC_RINGING: case SipServletResponse.SC_SESSION_PROGRESS: { if (!is(ringing)) { if(logger.isInfoEnabled()) { logger.info("Got 180 Ringing for Call: "+self().path()+" To: "+to+" sender: "+sender.path()+" observers size: "+observers.size()); } fsm.transition(message, ringing); } break; } case SipServletResponse.SC_BUSY_HERE: case SipServletResponse.SC_BUSY_EVERYWHERE: case SipServletResponse.SC_DECLINE: { sendCallInfoToObservers(); //Important. If state is DIALING, then do nothing about the BUSY. If not DIALING state move to failingBusy // // Notify the observers. // external = CallStateChanged.State.BUSY; // final CallStateChanged event = new CallStateChanged(external); // for (final ActorRef observer : observers) { // observer.tell(event, self); // } // XXX shouldnt it move to failingBusy IF dialing ???? // if (is(dialing)) { // break; // } else { // fsm.transition(message, failingBusy); // } if (!is(failingNoAnswer)) fsm.transition(message, failingBusy); break; } case SipServletResponse.SC_UNAUTHORIZED: case SipServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED: { // Handles Auth for https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out if ((this.username!= null || this.username.isEmpty()) && (this.password != null && this.password.isEmpty())) { sendCallInfoToObservers(); fsm.transition(message, failed); } else { AuthInfo authInfo = this.factory.createAuthInfo(); String authHeader = message.getHeader("Proxy-Authenticate"); if (authHeader == null) { authHeader = message.getHeader("WWW-Authenticate"); } String tempRealm = authHeader.substring(authHeader.indexOf("realm=\"") + "realm=\"".length()); String realm = tempRealm.substring(0, tempRealm.indexOf("\"")); authInfo.addAuthInfo(message.getStatus(), realm, this.username, this.password); SipServletRequest challengeRequest = message.getSession().createRequest(message.getRequest().getMethod()); challengeRequest.addAuthHeader(message, authInfo); challengeRequest.setContent(this.invite.getContent(), this.invite.getContentType()); this.invite = challengeRequest; // https://github.com/Mobicents/RestComm/issues/147 Make sure we send the SDP again this.invite.setContent(message.getRequest().getContent(), "application/sdp"); if (outboundToIms) { final SipURI uri = factory.createSipURI(null, imsProxyAddress); uri.setPort(imsProxyPort); uri.setLrParam(true); challengeRequest.pushRoute(uri); } //FIXME:should check for the Ims pushed Route? B2BUAHelper.addHeadersToMessage(challengeRequest, extensionHeaders, factory); challengeRequest.send(); } break; } // https://github.com/Mobicents/RestComm/issues/148 // Session in Progress Response should trigger MMS to start the Media Session // case SipServletResponse.SC_SESSION_PROGRESS: case SipServletResponse.SC_OK: { if (is(dialing) || (is(ringing) && !"inbound".equals(direction))) { fsm.transition(message, updatingMediaSession); } break; } default: { if (code >= 400 && code != 487) { if (code == 487 && isOutbound()) { String initialIpBeforeLB = null; String initialPortBeforeLB = null; try { initialIpBeforeLB = message.getHeader("X-Sip-Balancer-InitialRemoteAddr"); initialPortBeforeLB = message.getHeader("X-Sip-Balancer-InitialRemotePort"); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Exception during check of LB custom headers for IP address and port"); } } final SipServletRequest ack = message.createAck(); addCustomHeaders(ack); SipSession session = message.getSession(); if (initialIpBeforeLB != null ) { if (initialPortBeforeLB == null) initialPortBeforeLB = "5060"; if(logger.isInfoEnabled()) { logger.info("We are behind load balancer, will use: " + initialIpBeforeLB + ":" + initialPortBeforeLB + " for ACK message, "); } String realIP = initialIpBeforeLB + ":" + initialPortBeforeLB; SipURI uri = factory.createSipURI(((SipURI) ack.getRequestURI()).getUser(), realIP); ack.setRequestURI(uri); } else if (!ack.getHeaders("Route").hasNext()) { final SipServletRequest originalInvite = message.getRequest(); final SipURI realInetUri = (SipURI) originalInvite.getRequestURI(); if ((SipURI) session.getAttribute("realInetUri") == null) { session.setAttribute("realInetUri", realInetUri); } final InetAddress ackRURI = DNSUtils.getByName(((SipURI) ack.getRequestURI()).getHost()); final int ackRURIPort = ((SipURI) ack.getRequestURI()).getPort(); if (realInetUri != null && (ackRURI.isSiteLocalAddress() || ackRURI.isAnyLocalAddress() || ackRURI.isLoopbackAddress()) && (ackRURIPort != realInetUri.getPort())) { if(logger.isInfoEnabled()) { logger.info("Using the real ip address and port of the sip client " + realInetUri.toString() + " as a request uri of the ACK"); } realInetUri.setUser(((SipURI) ack.getRequestURI()).getUser()); ack.setRequestURI(realInetUri); } } ack.send(); if(logger.isInfoEnabled()) { logger.info("Just sent out ACK : " + ack.toString()); } } this.fail = true; fsm.transition(message, stopping); } } } } private void onHangup(Hangup message, ActorRef self, ActorRef sender) throws Exception { if(logger.isDebugEnabled()) { String msg = String.format("Got Hangup %s for call %s, from %s, to %s, fsm state %s, conferencing %s, conference %s ", message, self(), from, to, fsm.state(), conferencing, conference); logger.debug(msg); } if (is(completed)) { if (logger.isDebugEnabled()) { logger.debug("Got Hangup but already in completed state"); } CallStateChanged event = new CallStateChanged(external); for (final ActorRef observer : observers) { observer.tell(event, self()); } return; } // Stop recording if necessary if (recording) { recording = false; if(logger.isInfoEnabled()) { logger.info("Call - Will stop recording now"); } msController.tell(new Stop(true), self); } if (is(updatingMediaSession) || is(ringing) || is(queued) || is(dialing) || is(inProgress) || is(waitingForAnswer)) { if (conferencing) { // Tell conference to remove the call from participants list // before moving to a stopping state conference.tell(new RemoveParticipant(self()), self()); }else { if (!receivedBye && !sentBye) { // Send BYE to client if RestComm took initiative to hangup the call sendBye(message); } // Move to next state to clean media resources and close session fsm.transition(message, stopping); } } else if (is(failingNoAnswer)) { fsm.transition(message, canceling); } else if (is(stopping)) { fsm.transition(message, completed); } else { if (!is(leaving) && !is(canceling) && !is(canceled)) fsm.transition(message, stopping); } } private void sendBye(Hangup hangup) throws IOException, TransitionNotFoundException, TransitionFailedException, TransitionRollbackException { final SipSession session = invite.getSession(); final String sessionState = session.getState().name(); if (sessionState == SipSession.State.TERMINATED.name()) { if (logger.isInfoEnabled()) { logger.info("SipSession already TERMINATED, will not send BYE"); } return; } else { if (logger.isInfoEnabled()) { logger.info("About to send BYE, session state: " + sessionState); } } if (sessionState == SipSession.State.INITIAL.name() || (sessionState == SipSession.State.EARLY.name() && isInbound())) { int sipResponse = (enable200OkDelay && hangup.getSipResponse() != null) ? hangup.getSipResponse() : Response.SERVER_INTERNAL_ERROR; final SipServletResponse resp = invite.createResponse(sipResponse); if (hangup.getMessage() != null && !hangup.getMessage().equals("")) { resp.addHeader("Reason",hangup.getMessage()); } addCustomHeaders(resp); resp.send(); fsm.transition(hangup, completed); return; } if (sessionState == SipSession.State.EARLY.name()) { final SipServletRequest cancel = invite.createCancel(); if (hangup.getMessage() != null && !hangup.getMessage().equals("")) { cancel.addHeader("Reason",hangup.getMessage()); } addCustomHeaders(cancel); cancel.send(); external = CallStateChanged.State.CANCELED; fsm.transition(hangup, completed); return; } else { final SipServletRequest bye = session.createRequest("BYE"); addCustomHeaders(bye); if (hangup.getMessage() != null && !hangup.getMessage().equals("")) { bye.addHeader("Reason",hangup.getMessage()); } SipURI realInetUri = (SipURI) session.getAttribute("realInetUri"); InetAddress byeRURI = DNSUtils.getByName(((SipURI) bye.getRequestURI()).getHost()); // INVITE sip:[email protected] SIP/2.0 // Record-Route: <sip:10.154.28.245:5065;transport=udp;lr;node_host=10.13.169.214;node_port=5080;version=0> // Record-Route: <sip:10.154.28.245:5060;transport=udp;lr;node_host=10.13.169.214;node_port=5080;version=0> // Record-Route: <sip:67.231.8.195;lr=on;ftag=gK0043eb81> // Record-Route: <sip:67.231.4.204;r2=on;lr=on;ftag=gK0043eb81> // Record-Route: <sip:192.168.6.219;r2=on;lr=on;ftag=gK0043eb81> // Accept: application/sdp // Allow: INVITE,ACK,CANCEL,BYE // Via: SIP/2.0/UDP 10.154.28.245:5065;branch=z9hG4bK1cdb.193075b2.058724zsd_0 // Via: SIP/2.0/UDP 10.154.28.245:5060;branch=z9hG4bK1cdb.193075b2.058724_0 // Via: SIP/2.0/UDP 67.231.8.195;branch=z9hG4bK1cdb.193075b2.0 // Via: SIP/2.0/UDP 67.231.4.204;branch=z9hG4bK1cdb.f9127375.0 // Via: SIP/2.0/UDP 192.168.16.114:5060;branch=z9hG4bK00B6ff7ff87ed50497f // From: <sip:[email protected]>;tag=gK0043eb81 // To: <sip:[email protected]> // Call-ID: [email protected] // CSeq: 393447729 INVITE // Max-Forwards: 67 // Contact: <sip:[email protected]:5060> // Diversion: <sip:[email protected]:5060>;privacy=off;screen=no; reason=unknown; counter=1 // Supported: replaces // Content-Disposition: session;handling=required // Content-Type: application/sdp // Remote-Party-ID: <sip:[email protected]:5060>;privacy=off;screen=no // X-Sip-Balancer-InitialRemoteAddr: 67.231.8.195 // X-Sip-Balancer-InitialRemotePort: 5060 // Route: <sip:10.13.169.214:5080;transport=udp;lr> // Content-Length: 340 ListIterator<String> recordRouteList = invite.getHeaders(RecordRouteHeader.NAME); if (invite.getHeader("X-Sip-Balancer-InitialRemoteAddr") != null) { if(logger.isInfoEnabled()){ logger.info("We are behind LoadBalancer and will remove the first two RecordRoutes since they are the LB node"); } if(recordRouteList.hasNext()) { recordRouteList.next(); recordRouteList.remove(); if(recordRouteList.hasNext()) { recordRouteList.next(); recordRouteList.remove(); } else { logger.warning("Missing second LB Record Route record"); } } else { logger.warning("Missing LB Record Route records"); } } if (recordRouteList.hasNext()) { if(logger.isInfoEnabled()) { logger.info("Record Route is set, wont change the Request URI"); } } else { if(logger.isInfoEnabled()) { logger.info("Checking RURI, realInetUri: " + realInetUri + " byeRURI: " + byeRURI); } if(logger.isDebugEnabled()) { logger.debug("byeRURI.isSiteLocalAddress(): " + byeRURI.isSiteLocalAddress()); logger.debug("byeRURI.isAnyLocalAddress(): " + byeRURI.isAnyLocalAddress()); logger.debug("byeRURI.isLoopbackAddress(): " + byeRURI.isLoopbackAddress()); } if (realInetUri != null && (byeRURI.isSiteLocalAddress() || byeRURI.isAnyLocalAddress() || byeRURI.isLoopbackAddress())) { if(logger.isInfoEnabled()) { logger.info("real ip address of the sip client " + realInetUri.toString() + " is not null, checking if the request URI needs to be patched"); } boolean patchRURI = true; try { // https://github.com/RestComm/Restcomm-Connect/issues/1336 checking if the initial IP and Port behind LB is part of the route set or not ListIterator<? extends Address> routes = bye.getAddressHeaders(RouteHeader.NAME); while(routes.hasNext() && patchRURI) { SipURI route = (SipURI) routes.next().getURI(); String routeHost = route.getHost(); int routePort = route.getPort(); if(routePort < 0) { routePort = 5060; } if (logger.isDebugEnabled()) { logger.debug("Checking if route " + routeHost + ":" + routePort + " is matching ip and port of realNetURI " + realInetUri.getHost() + ":" + realInetUri.getPort() + " for the BYE request"); } if(routeHost.equalsIgnoreCase(realInetUri.getHost()) && routePort == realInetUri.getPort()) { if (logger.isDebugEnabled()) { logger.debug("route " + route + " is matching ip and port of realNetURI "+ realInetUri.getHost() + ":" + realInetUri.getPort() + " for the BYE request, so not patching the Request-URI"); } patchRURI = false; } } } catch (ServletParseException e) { logger.error("Impossible to parse the route set from the BYE " + bye, e); } if(patchRURI) { if(logger.isInfoEnabled()) { logger.info("Using the real ip address of the sip client " + realInetUri.toString() + " as a request uri of the BYE request"); } bye.setRequestURI(realInetUri); } } } if(logger.isInfoEnabled()) { logger.info("Will sent out BYE to: " + bye.getRequestURI()); } try { bye.send(); sentBye = true; } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Exception during Send Bye: "+e.toString()); } } } } private void onNotFound(org.restcomm.connect.telephony.api.NotFound message, ActorRef self, ActorRef sender) throws Exception { if (is(ringing)) { fsm.transition(message, notFound); } } private void onMediaServerControllerStateChanged(MediaServerControllerStateChanged message, ActorRef self, ActorRef sender) throws Exception { if(logger.isInfoEnabled()) { logger.info("onMediaServerControllerStateChanged " + message.getState() + " inboundConfirmCall " + inboundConfirmCall); } switch (message.getState()) { case PENDING: if (is(initializing)) { fsm.transition(message, dialing); } break; case ACTIVE: if (is(initializing) || is(updatingMediaSession)) { SipSession.State sessionState = invite.getSession().getState(); if (!(SipSession.State.CONFIRMED.equals(sessionState) || SipSession.State.TERMINATED.equals(sessionState))) { // Issue #1649: mediaSessionInfo = message.getMediaSession(); if(inboundConfirmCall){ sendInviteOk(); } else{ fsm.transition(message, waitingForAnswer); } } else if (SipSession.State.CONFIRMED.equals(sessionState) && is(inProgress)) { // We have an ongoing call and Restcomm executes new RCML app on that // If the sipSession state is Confirmed, then update SDP with the new SDP from MMS SipServletRequest reInvite = invite.getSession().createRequest("INVITE"); addCustomHeaders(reInvite); mediaSessionInfo = message.getMediaSession(); final byte[] sdp = mediaSessionInfo.getLocalSdp().getBytes(); String answer = null; if (mediaSessionInfo.usesNat()) { final String externalIp = mediaSessionInfo.getExternalAddress().getHostAddress(); answer = SdpUtils.patch("application/sdp", sdp, externalIp); } else { answer = mediaSessionInfo.getLocalSdp().toString(); } // Issue #215: // https://bitbucket.org/telestax/telscale-restcomm/issue/215/restcomm-adds-extra-newline-to-sdp answer = SdpUtils.endWithNewLine(answer); reInvite.setContent(answer, "application/sdp"); reInvite.send(); } // Make sure the SIP session doesn't end pre-maturely. invite.getApplicationSession().setExpires(0); if(isInbound()){ if(logger.isInfoEnabled()) { logger.info("current state: "+fsm.state()+" , will wait for OK to move to inProgress"); } } else{ fsm.transition(message, inProgress); } } else if(is(inProgress) && inDialogRequest != null) { mediaSessionInfo = message.getMediaSession(); final byte[] sdp = mediaSessionInfo.getLocalSdp().getBytes(); String answer = null; if (mediaSessionInfo.usesNat()) { final String externalIp = mediaSessionInfo.getExternalAddress().getHostAddress(); answer = SdpUtils.patch("application/sdp", sdp, externalIp); } else { answer = mediaSessionInfo.getLocalSdp().toString(); } // Issue #215: // https://bitbucket.org/telestax/telscale-restcomm/issue/215/restcomm-adds-extra-newline-to-sdp answer = SdpUtils.endWithNewLine(answer); SipServletResponse resp = inDialogInvite.createResponse(Response.OK); resp.setContent(answer, "application/sdp"); resp.send(); } break; case INACTIVE: if (is(stopping)) { context().setReceiveTimeout(Duration.Undefined()); if (logger.isDebugEnabled()) { String msg = String.format("On MediaServerContollerStateChanged, message: INACTIVE, Call state: %s, Fail: %s", fsm.state(), fail); logger.debug(msg); } if (fail) { if (logger.isDebugEnabled()) { logger.debug("At Call Stopping state, moving to Failed state"); } fsm.transition(message, failed); } else { if (logger.isDebugEnabled()) { logger.debug("At Call Stopping state, moving to Completed state"); } fsm.transition(message, completed); } } else if (is(canceling)) { fsm.transition(message, canceled); } else if (is(failingBusy)) { fsm.transition(message, busy); } else if (is(failingNoAnswer)) { fsm.transition(message, noAnswer); } else if (is(joining)) { // https://telestax.atlassian.net/browse/RESTCOMM-1343 // if call was in joining state and we received INACTIVE MS response. // means: MS failed to bridge the call to the conference. // call should move to failed state so proper sip response is generated & // call resources get cleaned up logger.error("Call failed to join conference, media operation to connect call with conference failed."); // Let conference know the call exited the room so // it does not keep waiting for it to complete the join this.conferencing = false; this.conference.tell(new Left(self()), self); this.conference = null; fsm.transition(new Hangup("failed to join conference"), failed); } break; case FAILED: if (is(initializing) || is(updatingMediaSession) || is(joining) || is(leaving) || is(inProgress)) { fsm.transition(message, failed); } break; default: break; } } private void onJoinBridge(JoinBridge message, ActorRef self, ActorRef sender) throws Exception { if (is(inProgress) || is(waitingForAnswer)) { this.bridge = sender; this.fsm.transition(message, joining); } } private void onJoinConference(JoinConference message, ActorRef self, ActorRef sender) throws Exception { if (logger.isInfoEnabled()) { logger.info("********************* onJoinConference *********************"); } if (is(inProgress)) { this.conferencing = true; this.conference = sender; this.conferenceSid = message.getSid(); this.fsm.transition(message, joining); } } private void onJoinComplete(JoinComplete message, ActorRef self, ActorRef sender) throws Exception { //The CallController will send to the Call the JoinComplete message when the join completes if (is(joining)) { // Forward message to the bridge if (conferencing) { if (outgoingCallRecord != null && isOutbound()) { if (logger.isInfoEnabled()) { logger.info("Updating CDR for outgoing call: "+id.toString()+", call status: "+external.name()+", to include Conference details, conference: "+conferenceSid); } outgoingCallRecord = outgoingCallRecord.setConferenceSid(conferenceSid); outgoingCallRecord = outgoingCallRecord.setMuted(muted); recordsDao.updateCallDetailRecord(outgoingCallRecord); } this.conference.tell(message, self); } else { this.bridge.tell(message, self); } // Move to state In Progress fsm.transition(message, inProgress); } } private void onLeave(Leave message, ActorRef self, ActorRef sender) throws Exception { if (is(inProgress)) { fsm.transition(message, leaving); } else { if (logger.isDebugEnabled()) { logger.debug("Received Leave for Call: "+self.path()+", but state is :"+fsm.state().toString()); } } } private void onLeft(Left message, ActorRef self, ActorRef sender) throws Exception { if (is(leaving)) { if (conferencing) { // Let conference know the call exited the room this.conferencing = false; this.conference.tell(new Left(self()), self); this.conference = null; if (logger.isDebugEnabled()) { logger.debug("Call left conference room and notification sent to conference actor"); } } if (!liveCallModification) { // After leaving let the Interpreter know the Call is ready. fsm.transition(message, stopping); } else { if (muted) { // Forward to media server controller this.msController.tell(new Unmute(), sender); muted = false; } if (!receivedBye) { fsm.transition(message, inProgress); } else { fsm.transition(message, completed); } } } } private void onStartRecordingCall(StartRecording message, ActorRef self, ActorRef sender) throws Exception { if (is(inProgress)) { if (runtimeSettings == null) { this.runtimeSettings = message.getRuntimeSetting(); } if (daoManager == null) { daoManager = message.getDaoManager(); } if (accountId == null) { accountId = message.getAccountId(); } // Forward message for Media Session Controller to handle message.setCallId(this.id); this.msController.tell(message, sender); this.recording = true; this.recordingUri = message.getRecordingUri(); this.recordingSid = message.getRecordingSid(); this.recordingStart = DateTime.now(); } } private void onStopRecordingCall(StopRecording message, ActorRef self, ActorRef sender) throws Exception { if (is(inProgress) && this.recording) { // Forward message for Media Session Controller to handle this.msController.tell(message, sender); this.recording = false; recordingDuration = (DateTime.now().getMillis() - recordingStart.getMillis())/1000; } } private void onBridgeStateChanged(BridgeStateChanged message, ActorRef self, ActorRef sender) throws Exception { if (is(inProgress) && isInbound() && enable200OkDelay) { switch (message.getState()) { case BRIDGED: sendInviteOk(); break; case FAILED: fsm.transition(message, stopping); default: break; } } else { if (logger.isDebugEnabled()) { logger.debug("Received BridgeStateChanged for Call: "+self.path()+", but state is :"+fsm.state().toString()); } } } private void sendInviteOk() throws Exception{ if (logger.isInfoEnabled()) { logger.info("sending initial invite ok, initialInviteOkSent:"+ initialInviteOkSent); } if(!initialInviteOkSent){ final SipServletResponse okay = invite.createResponse(SipServletResponse.SC_OK); final byte[] sdp = mediaSessionInfo.getLocalSdp().getBytes(); String answer = null; if (mediaSessionInfo.usesNat()) { final String externalIp = mediaSessionInfo.getExternalAddress().getHostAddress(); answer = SdpUtils.patch("application/sdp", sdp, externalIp); } else { answer = mediaSessionInfo.getLocalSdp().toString(); } // Issue #215: // https://bitbucket.org/telestax/telscale-restcomm/issue/215/restcomm-adds-extra-newline-to-sdp answer = SdpUtils.endWithNewLine(answer); okay.setContent(answer, "application/sdp"); addCustomHeaders(okay); okay.send(); initialInviteOkSent = true; } } private boolean isCallOnHoldSdp(String answer){ if(answer.contains("a=inactive")){ return true; } if(answer.contains("a=sendonly")){ return true; } return false; } private boolean isCallOffHoldSdp(String answer){ if(answer.contains("a=sendrecv")){ return true; } if(!answer.contains("a=inactive")){ return true; } return false; } @Override public void postStop() { try { if (logger.isInfoEnabled()) { logger.info("Call actor at postStop, path: "+self().path()+", direction: "+direction+", state: "+fsm.state()+", isTerminated: "+self().isTerminated()+", sender: "+sender()); } onStopObserving(new StopObserving(), self(), null); getContext().stop(msController); } catch (Exception exception) { if(logger.isInfoEnabled()) { logger.info("Exception during Call postStop while trying to remove observers: "+exception); } } if(actAsImsUa && outgoingCallRecord!=null){ recordsDao.removeCallDetailRecord(outgoingCallRecord.getSid()); } super.postStop(); } }
135,045
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
BridgeManager.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.telephony/src/main/java/org/restcomm/connect/telephony/BridgeManager.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2013, Telestax Inc and individual contributors * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.connect.telephony; import akka.actor.ActorRef; import akka.actor.Props; import akka.actor.UntypedActor; import akka.actor.UntypedActorFactory; import akka.event.Logging; import akka.event.LoggingAdapter; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.commons.patterns.Observe; import org.restcomm.connect.dao.entities.MediaAttributes; import org.restcomm.connect.mscontrol.api.MediaServerControllerFactory; import org.restcomm.connect.telephony.api.BridgeManagerResponse; import org.restcomm.connect.telephony.api.BridgeStateChanged; import org.restcomm.connect.telephony.api.CreateBridge; /** * @author Henrique Rosa ([email protected]) * */ public class BridgeManager extends RestcommUntypedActor { private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); private final MediaServerControllerFactory factory; public BridgeManager(final MediaServerControllerFactory factory) { super(); this.factory = factory; } private ActorRef createBridge(final MediaAttributes mediaAttributes) { final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new Bridge(factory, mediaAttributes); } }); return getContext().actorOf(props); } /* * Events */ @Override public void onReceive(Object message) throws Exception { final Class<?> klass = message.getClass(); final ActorRef self = self(); final ActorRef sender = sender(); if (CreateBridge.class.equals(klass)) { onCreateBridge((CreateBridge) message, self, sender); } else if (BridgeStateChanged.class.equals(klass)) { onBridgeStateChanged((BridgeStateChanged) message, self, sender); } } private void onCreateBridge(CreateBridge message, ActorRef self, ActorRef sender) { // Create a new bridge ActorRef bridge = createBridge(message.mediaAttributes()); // Observe state changes in the bridge for termination purposes bridge.tell(new Observe(self), self); // Send bridge to remote actor final BridgeManagerResponse response = new BridgeManagerResponse(bridge); sender.tell(response, self); } private void onBridgeStateChanged(BridgeStateChanged message, ActorRef self, ActorRef sender) { switch (message.getState()) { case INACTIVE: case FAILED: context().stop(sender); break; default: // Do not care about other states break; } } }
3,753
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Conference.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.telephony/src/main/java/org/restcomm/connect/telephony/Conference.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.restcomm.connect.telephony; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.joda.time.DateTime; import org.mobicents.servlet.restcomm.mscontrol.messages.MediaServerConferenceControllerStateChanged; import org.restcomm.connect.commons.annotations.concurrency.Immutable; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.commons.fsm.Action; import org.restcomm.connect.commons.fsm.FiniteStateMachine; import org.restcomm.connect.commons.fsm.State; import org.restcomm.connect.commons.fsm.Transition; import org.restcomm.connect.commons.patterns.Observe; import org.restcomm.connect.commons.patterns.Observing; import org.restcomm.connect.commons.patterns.StopObserving; import org.restcomm.connect.dao.CallDetailRecordsDao; import org.restcomm.connect.dao.ConferenceDetailRecordsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.entities.CallDetailRecord; import org.restcomm.connect.dao.entities.ConferenceDetailRecord; import org.restcomm.connect.http.client.CallApiResponse; import org.restcomm.connect.http.client.api.CallApiClient; import org.restcomm.connect.mscontrol.api.MediaServerControllerFactory; import org.restcomm.connect.mscontrol.api.messages.CreateMediaSession; import org.restcomm.connect.mscontrol.api.messages.JoinCall; import org.restcomm.connect.mscontrol.api.messages.JoinComplete; import org.restcomm.connect.mscontrol.api.messages.Leave; import org.restcomm.connect.mscontrol.api.messages.Left; import org.restcomm.connect.mscontrol.api.messages.MediaServerControllerStateChanged.MediaServerControllerState; import org.restcomm.connect.mscontrol.api.messages.Play; import org.restcomm.connect.mscontrol.api.messages.StartRecording; import org.restcomm.connect.mscontrol.api.messages.Stop; import org.restcomm.connect.mscontrol.api.messages.StopMediaGroup; import org.restcomm.connect.mscontrol.api.messages.StopRecording; import org.restcomm.connect.telephony.api.AddParticipant; import org.restcomm.connect.telephony.api.ConferenceInfo; import org.restcomm.connect.telephony.api.ConferenceModeratorPresent; import org.restcomm.connect.telephony.api.ConferenceResponse; import org.restcomm.connect.telephony.api.ConferenceStateChanged; import org.restcomm.connect.telephony.api.GetConferenceInfo; import org.restcomm.connect.telephony.api.Hangup; import org.restcomm.connect.telephony.api.RemoveParticipant; import org.restcomm.connect.telephony.api.StartConference; import org.restcomm.connect.telephony.api.StopConference; import akka.actor.ActorRef; import akka.actor.Props; import akka.actor.ReceiveTimeout; import akka.actor.UntypedActor; import akka.actor.UntypedActorFactory; import akka.event.Logging; import akka.event.LoggingAdapter; import jain.protocol.ip.mgcp.message.parms.ConnectionMode; import scala.concurrent.duration.Duration; /** * @author [email protected] (Thomas Quintana) * @author [email protected] (Amit Bhayani) * @author [email protected] (Henrique Rosa) * @author [email protected] (Maria Farooq) */ @Immutable public final class Conference extends RestcommUntypedActor { private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); // Finite state machine private final FiniteStateMachine fsm; private final State uninitialized; private final State initializing; private final State waiting; private final State running; private final State evicting; private final State stopping; private final State stopped; private final State failed; // Runtime stuff private final String name; private final String accountSid; private final String friendlyName; private Sid sid; private final List<ActorRef> calls; private final List<ActorRef> observers; private boolean moderatorPresent = false; // Media Session Controller private final ActorRef mscontroller; private final DaoManager storage; private int globalNoOfParticipants; private ConferenceStateChanged.State waitingState; private final ActorRef conferenceCenter; private ActorRef callApiClient; private static final Sid SUPER_ADMIN_ACCOUNT_SID = new Sid("ACae6e420f425248d6a26948c17a9e2acf"); public Conference(final String name, final MediaServerControllerFactory factory, final DaoManager storage, final ActorRef conferenceCenter) { super(); final ActorRef source = self(); // Finite states this.uninitialized = new State("uninitialized", null, null); this.initializing = new State("initializing", new Initializing(source)); this.waiting = new State("waiting", new Waiting(source)); this.running = new State("running", new Running(source)); this.evicting = new State("evicting", new Evicting(source)); this.stopping = new State("stopping", new Stopping(source)); this.stopped = new State("stopped", new Stopped(source)); this.failed = new State("failed", new Failed(source)); // State transitions final Set<Transition> transitions = new HashSet<Transition>(); transitions.add(new Transition(uninitialized, initializing)); transitions.add(new Transition(initializing, waiting)); transitions.add(new Transition(initializing, stopping)); transitions.add(new Transition(initializing, failed)); transitions.add(new Transition(waiting, running)); transitions.add(new Transition(waiting, evicting)); transitions.add(new Transition(waiting, stopping)); transitions.add(new Transition(running, evicting)); transitions.add(new Transition(running, stopping)); transitions.add(new Transition(evicting, stopping)); transitions.add(new Transition(stopping, stopped)); transitions.add(new Transition(stopping, failed)); // Finite state machine this.fsm = new FiniteStateMachine(uninitialized, transitions); // Runtime stuff this.name = name; final String[] cnfNameAndAccount = name.split(":"); accountSid = cnfNameAndAccount[0]; friendlyName = cnfNameAndAccount[1]; this.storage = storage; this.conferenceCenter = conferenceCenter; //generate it later at MRB level, by watching if same conference is running on another RC instance. //this.sid = Sid.generate(Sid.Type.CONFERENCE); this.mscontroller = getContext().actorOf(factory.provideConferenceControllerProps()); this.calls = new ArrayList<ActorRef>(); this.observers = new ArrayList<ActorRef>(); } private boolean is(State state) { return this.fsm.state().equals(state); } private boolean isRunning() { return is(waiting) || is(running); } private void broadcast(final Object message) { if (!this.observers.isEmpty()) { final ActorRef self = self(); for (ActorRef observer : observers) { if (!observer.isTerminated()) { observer.tell(message, self); } else { if (logger.isDebugEnabled()) { logger.debug("Conference broadcase, Observer is terminated: "+observer.path()); } } } } } @Override public void onReceive(Object message) throws Exception { final Class<?> klass = message.getClass(); final ActorRef sender = sender(); ActorRef self = self(); final State state = fsm.state(); if (logger.isInfoEnabled()) { logger.info(" ********** Conference " + self().path() + " Current State: " + state.toString()); logger.info(" ********** Conference " + self().path() + " Sender: " + sender); logger.info(" ********** Conference " + self().path() + " Processing Message: " + klass.getName()); } if (Observe.class.equals(klass)) { onObserve((Observe) message, self, sender); } else if (StopObserving.class.equals(klass)) { onStopObserving((StopObserving) message, self, sender); } else if (GetConferenceInfo.class.equals(klass)) { onGetConferenceInfo(self, sender); } else if (StartConference.class.equals(klass)) { onStartConference((StartConference) message, self, sender); } else if (StopConference.class.equals(klass)) { onStopConference((StopConference) message, self, sender); } else if (ConferenceModeratorPresent.class.equals(klass)) { onConferenceModeratorPresent((ConferenceModeratorPresent) message, self, sender); } else if (AddParticipant.class.equals(klass)) { onAddParticipant((AddParticipant) message, self, sender); } else if (RemoveParticipant.class.equals(klass)) { onRemoveParticipant((RemoveParticipant) message, self, sender); } else if (Left.class.equals(klass)) { onLeft((Left) message, self, sender); } else if (JoinComplete.class.equals(klass)) { onJoinComplete((JoinComplete) message, self, sender); } else if (MediaServerConferenceControllerStateChanged.class.equals(klass)) { onMediaServerControllerStateChanged((MediaServerConferenceControllerStateChanged) message, self, sender); } else if (Play.class.equals(klass)) { onPlay((Play) message, self, sender); } else if (StartRecording.class.equals(klass)) { onStartRecording((StartRecording) message, self, sender); } else if (StopRecording.class.equals(klass)) { onStopRecording((StopRecording) message, self, sender); } else if (message instanceof ReceiveTimeout) { onReceiveTimeout((ReceiveTimeout) message, self, sender); } else if (CallApiResponse.class.equals(klass)) { onCallApiResponse((CallApiResponse) message, self, sender); } } /* * ACTIONS */ private abstract class AbstractAction implements Action { protected final ActorRef source; public AbstractAction(final ActorRef source) { super(); this.source = source; } } private class Initializing extends AbstractAction { public Initializing(ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { StartConference startConference = (StartConference) message; // Start observing state changes in the MSController final Observe observe = new Observe(super.source); mscontroller.tell(observe, super.source); ConferenceInfo information = createConferenceInfo(); // Initialize the MS Controller final CreateMediaSession createMediaSession = new CreateMediaSession(startConference.callSid(), information.name(), startConference.mediaAttributes()); mscontroller.tell(createMediaSession, super.source); } } private final class Waiting extends AbstractAction { public Waiting(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { //As MRB have generated Sid for this conference and saved in db. MediaServerConferenceControllerStateChanged mediaServerConferenceControllerStateChanged = (MediaServerConferenceControllerStateChanged) message; sid = mediaServerConferenceControllerStateChanged.conferenceSid(); String stateStr= mediaServerConferenceControllerStateChanged.conferenceState(); //this is to cover the scenario where initial state is not moderatorAbsent and maybe moderator is present on another node. waitingState = ConferenceStateChanged.translateState(stateStr, ConferenceStateChanged.State.RUNNING_MODERATOR_ABSENT); moderatorPresent = mediaServerConferenceControllerStateChanged.moderatorPresent(); if(logger.isInfoEnabled()) { logger.info("################################## Conference " + name + " has sid: "+sid +" stateStr: "+stateStr+" initial state: "+waitingState); } broadcast(new ConferenceStateChanged(name, waitingState)); startConferenceTimer(); } } private final class Running extends AbstractAction { public Running(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { ConferenceModeratorPresent msg = (ConferenceModeratorPresent)message; // Stop the background music if present mscontroller.tell(new StopMediaGroup(msg.beep()), super.source); updateConferenceStatus(ConferenceStateChanged.State.RUNNING_MODERATOR_PRESENT); // Notify the observers broadcast(new ConferenceStateChanged(name, ConferenceStateChanged.State.RUNNING_MODERATOR_PRESENT)); } } private class Evicting extends AbstractAction { public Evicting(ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { // Tell every participant to leave the conference room // NOTE: calls list will only be update in the onLeft() event! for (final ActorRef call : calls) { final Leave leave = new Leave(); call.tell(leave, super.source); } //tell call api client to kick all remote calls kickoutRemoteParticipants(); // Stop the conference if ALL local participants have been evicted if (calls.isEmpty()) { fsm.transition(message, stopping); } } } private class Stopping extends AbstractAction { public Stopping(ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { // Ask the MS Controller to stop // This will stop any current media operations and clean media resources mscontroller.tell(new Stop(), super.source); // Tell conferenceCentre that conference is in stopping state. // https://github.com/RestComm/Restcomm-Connect/issues/2312 conferenceCenter.tell(new ConferenceStateChanged(name, ConferenceStateChanged.State.STOPPING), self()); } } private abstract class FinalizingAction extends AbstractAction { protected final ConferenceStateChanged.State finalState; public FinalizingAction(ActorRef source, ConferenceStateChanged.State state) { super(source); finalState = state; } @Override public void execute(Object message) throws Exception { // Notify the observers. broadcast(new ConferenceStateChanged(name, this.finalState)); observers.clear(); } } private final class Stopped extends FinalizingAction { public Stopped(final ActorRef source) { super(source, ConferenceStateChanged.State.COMPLETED); } } private final class Failed extends FinalizingAction { public Failed(final ActorRef source) { super(source, ConferenceStateChanged.State.FAILED); } } /* * EVENTS */ private void onObserve(Observe message, ActorRef self, ActorRef sender) { final ActorRef observer = message.observer(); if (observer != null) { this.observers.add(observer); observer.tell(new Observing(self), self); } } private void onStopObserving(StopObserving message, ActorRef self, ActorRef sender) { final ActorRef observer = message.observer(); if (observer != null) { observers.remove(observer); } } private void onGetConferenceInfo(ActorRef self, ActorRef sender) throws Exception { sender.tell(new ConferenceResponse<ConferenceInfo>(createConferenceInfo()), self); } private ConferenceInfo createConferenceInfo() throws Exception{ ConferenceInfo information = null; int globalNoOfParticipants = getGlobalNoOfParticipants(); if (is(waiting)) { information = new ConferenceInfo(sid, calls, waitingState, name, moderatorPresent, globalNoOfParticipants); } else if (is(running)) { information = new ConferenceInfo(sid, calls, ConferenceStateChanged.State.RUNNING_MODERATOR_PRESENT, name, moderatorPresent, globalNoOfParticipants); } else if (is(stopped)) { information = new ConferenceInfo(sid, calls, ConferenceStateChanged.State.COMPLETED, name, moderatorPresent, globalNoOfParticipants); } else { information = new ConferenceInfo(sid, calls, null, name, moderatorPresent, globalNoOfParticipants); } return information; } private void onStartConference(StartConference message, ActorRef self, ActorRef sender) throws Exception { if (is(uninitialized)) { this.fsm.transition(message, initializing); }else{ logger.warning("Received StartConference from sender : "+sender.path()+" but the state is: "+fsm.state().toString()); } } private void onStopConference(StopConference message, ActorRef self, ActorRef sender) throws Exception { if (is(initializing)) { this.fsm.transition(message, stopped); } else if (is(waiting) || is(running)) { this.fsm.transition(message, evicting); }else{ logger.warning("Received StopConference from sender : "+sender.path()+" but the state is: "+fsm.state().toString()); } } private void onConferenceModeratorPresent(ConferenceModeratorPresent message, ActorRef self, ActorRef sender) throws Exception { if (is(waiting)) { this.fsm.transition(message, running); } } private void onAddParticipant(AddParticipant message, ActorRef self, ActorRef sender) { if (isRunning()) { final JoinCall joinCall = new JoinCall(message.call(), ConnectionMode.Confrnce, this.sid, message.mediaAttributes()); this.mscontroller.tell(joinCall, self); }else{ logger.error("Received AddParticipant for Call: "+message.call().path()+" but the state is: "+fsm.state().toString()); sender.tell(new ConferenceStateChanged(name, ConferenceStateChanged.State.STOPPING), self()); } } private void onRemoveParticipant(RemoveParticipant message, ActorRef self, ActorRef sender) throws Exception { if (isRunning()) { if (logger.isInfoEnabled()) { logger.info("Received RemoveParticipants for Call: "+message.call().path()); } // Kindly ask participant to leave final ActorRef call = message.call(); final Leave leave = new Leave(); call.tell(leave, self); } else { logger.warning("Received RemoveParticipants for Call: "+message.call().path()+" but the state is: "+fsm.state().toString()); } } private void onLeft(Left message, ActorRef self, ActorRef sender) throws Exception { if (is(running) || is(waiting) || is(evicting)) { // Participant successfully left the conference. boolean removed = calls.remove(sender); if(!removed) logger.error("Call was not in conference participant list. Call: "+sender.path()); int participantsNr = calls.size(); if(logger.isInfoEnabled()) { logger.info("################################## Conference " + name + " has " + participantsNr + " participants"); } ConferenceResponse conferenceResponse = new ConferenceResponse(message); broadcast(conferenceResponse); if (logger.isDebugEnabled()) { logger.debug("Call left conference room and notification sent to observers."); } // Stop the conference when ALL participants have been evicted if (calls.isEmpty()) { fsm.transition(message, stopping); } } } private void onMediaServerControllerStateChanged(MediaServerConferenceControllerStateChanged message, ActorRef self, ActorRef sender) throws Exception { MediaServerControllerState state = message.getState(); if (logger.isInfoEnabled()) { logger.info("MediaServerControllerState state: "+state); } switch (state) { case ACTIVE: if (is(initializing)) { this.fsm.transition(message, waiting); } break; case INACTIVE: if (is(stopping)) { this.fsm.transition(message, stopped); } break; case FAILED: if (is(initializing)) { this.fsm.transition(message, failed); } break; default: logger.warning("received an unknown state from MediaServerController: "+state); break; } } private void onJoinComplete(JoinComplete message, ActorRef self, ActorRef sender) throws Exception { this.mscontroller.tell(message, sender); this.calls.add(sender); if (logger.isInfoEnabled()) { logger.info("Conference name: "+name+", path: "+self().path()+", received JoinComplete from Call: "+sender.path()+", number of participants currently: "+calls.size()+", will send conference info to observers"); } if (observers != null && observers.size() > 0) { Iterator<ActorRef> iter = observers.iterator(); ConferenceInfo ci = createConferenceInfo(); sender.tell(new ConferenceResponse<ConferenceInfo>(ci), self()); while (iter.hasNext()) { ActorRef observer = iter.next(); //First send conferenceInfo observer.tell(new ConferenceResponse<ConferenceInfo>(ci), self()); //Next send the JoinComplete message observer.tell(message, self()); } } } private void onPlay(Play message, ActorRef self, ActorRef sender) { if (isRunning()) { moderatorPresent = message.isConfModeratorPresent(); if (logger.isInfoEnabled()) { logger.info("Received Play message for conference: "+this.name+" , number of local participants: "+this.calls.size()+ " globalNoOfParticipants: "+globalNoOfParticipants+", isRunning: true, isModeratorPresent: "+this.moderatorPresent + " iterations: "+message.iterations()); } // Forward message to media server controller this.mscontroller.tell(message, sender); } else { if (logger.isInfoEnabled()) { logger.info("Play will not be processed for conference since its not in running state: "+this.name+" , number of local participants: "+this.calls.size()+ " globalNoOfParticipants: "+globalNoOfParticipants+" , isRunning: false, isModeratorPresent: "+this.moderatorPresent+ " iterations: "+message.iterations()); } } } private void onStartRecording(StartRecording message, ActorRef self, ActorRef sender) { if (isRunning()) { // Forward message to media server controller this.mscontroller.tell(message, sender); }else{ logger.warning("Received StartRecording from sender : "+sender.path()+" but the state is: "+fsm.state().toString()); } } private void onStopRecording(StopRecording message, ActorRef self, ActorRef sender) { if (isRunning()) { // Forward message to media server controller this.mscontroller.tell(message, sender); }else{ logger.warning("Received StopRecording from sender : "+sender.path()+" but the state is: "+fsm.state().toString()); } } private void onReceiveTimeout(ReceiveTimeout message, ActorRef self, ActorRef sender) throws Exception { if (logger.isInfoEnabled()) { logger.info("Conference Received Timeout, will stop conference now."); } onStopConference(new StopConference(), self, sender); } private void onCallApiResponse(CallApiResponse message, ActorRef self, ActorRef sender) { if (logger.isInfoEnabled()) { logger.info(String.format("Conference will stop sender of CallApiResponse: %s", sender)); } getContext().stop(sender); } /** * get global total no of participants from db * @throws Exception */ private int getGlobalNoOfParticipants() throws Exception{ if(sid == null){ globalNoOfParticipants = calls.size(); }else{ CallDetailRecordsDao dao = storage.getCallDetailRecordsDao(); globalNoOfParticipants = dao.getTotalRunningCallDetailRecordsByConferenceSid(sid); } if(logger.isDebugEnabled()) logger.debug("sid: "+sid+"globalNoOfParticipants: "+globalNoOfParticipants); return globalNoOfParticipants; } private void updateConferenceStatus(ConferenceStateChanged.State state){ if(sid != null){ final ConferenceDetailRecordsDao dao = storage.getConferenceDetailRecordsDao(); ConferenceDetailRecord cdr = dao.getConferenceDetailRecord(sid); cdr = cdr.setStatus(state.name()); dao.updateConferenceDetailRecordStatus(cdr); } } /** * startConferenceTimer - conference should expire after 4 hours/(configurable) */ private void startConferenceTimer() { final long conferenceTotalLifeInMillis = RestcommConfiguration.getInstance().getMain().getConferenceTimeout()*1000; final long conferenceRemainingLife = conferenceTotalLifeInMillis - conferenceAge(); context().setReceiveTimeout(Duration.create(conferenceRemainingLife, TimeUnit.MILLISECONDS)); if(logger.isInfoEnabled()) logger.info(String.format("conference timer started for: %s milliseconds", conferenceRemainingLife)); } /** * @return conference age in milli seconds */ private long conferenceAge() { if(sid != null){ final ConferenceDetailRecordsDao dao = storage.getConferenceDetailRecordsDao(); ConferenceDetailRecord cdr = dao.getConferenceDetailRecord(sid); if(cdr == null){ logger.warning(String.format("Conference cdr is null for sid: %s", sid)); }else{ return DateTime.now().getMillis()-cdr.getDateCreated().getMillis(); } } return 0; } private void kickoutRemoteParticipants(){ if(sid != null){ List<CallDetailRecord> callDetailRecords = storage.getCallDetailRecordsDao().getRunningCallDetailRecordsByConferenceSid(sid); if(callDetailRecords == null || callDetailRecords.isEmpty()){ if (logger.isDebugEnabled()) logger.debug("no active participants found."); } else { try { if (logger.isDebugEnabled()) logger.debug("total conference participants are: "+callDetailRecords.size()); Iterator<CallDetailRecord> iterator = callDetailRecords.iterator(); while(iterator.hasNext()){ final CallDetailRecord CallDR = iterator.next(); //kick only remote participants if(!CallDR.getInstanceId().equals(RestcommConfiguration.getInstance().getMain().getInstanceId())){ ActorRef callApiClient = callApiClient(CallDR.getSid()); callApiClient.tell(new Hangup("conference timed out", SUPER_ADMIN_ACCOUNT_SID, CallDR), self()); } } } catch (Exception e) { logger.error("Exception while trying to terminate conference via api: ", e); } } }else { if (logger.isInfoEnabled()) logger.info("sid is null hence no remote participants will be kickedout"); } } protected ActorRef callApiClient(final Sid callSid) { final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new CallApiClient(callSid, storage); } }); return getContext().actorOf(props); } @Override public void postStop() { if (!fsm.state().equals(uninitialized)) { if(logger.isInfoEnabled()) { logger.info("Conference: " + self().path() + "At the postStop() method."); } if(callApiClient != null && !callApiClient.isTerminated()) getContext().stop(callApiClient); getContext().stop(self()); } super.postStop(); } }
30,673
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
UserAgentManagerProxy.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.telephony/src/main/java/org/restcomm/connect/telephony/ua/UserAgentManagerProxy.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.restcomm.connect.telephony.ua; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.ReceiveTimeout; import akka.actor.UntypedActor; import akka.actor.UntypedActorFactory; import org.apache.commons.configuration.Configuration; import org.apache.log4j.Logger; import org.restcomm.connect.dao.DaoManager; import scala.concurrent.duration.Duration; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.sip.SipFactory; import javax.servlet.sip.SipServlet; import javax.servlet.sip.SipServletContextEvent; import javax.servlet.sip.SipServletListener; import javax.servlet.sip.SipServletRequest; import javax.servlet.sip.SipServletResponse; import java.io.IOException; import java.util.concurrent.TimeUnit; /** * @author [email protected] (Thomas Quintana) * @author <a href="mailto:[email protected]">gvagenas</a> */ public final class UserAgentManagerProxy extends SipServlet implements SipServletListener{ private static final long serialVersionUID = 1L; private static Logger logger = Logger.getLogger(UserAgentManagerProxy.class); private ActorSystem system; private ActorRef manager; private ServletContext servletContext; private int pingInterval; private Configuration configuration; public UserAgentManagerProxy() { super(); } @Override public void destroy() { logger.info("About to destroy UserAgentManager"); if (system != null) system.stop(manager); } @Override protected void doRequest(final SipServletRequest request) throws ServletException, IOException { manager.tell(request, null); } // @Override // protected void doResponse(final SipServletResponse response) throws ServletException, IOException { // manager.tell(response, null); // } @Override protected void doSuccessResponse(final SipServletResponse response) throws ServletException, IOException { manager.tell(response, null); } @Override protected void doErrorResponse(final SipServletResponse response) throws ServletException, IOException { if(logger.isDebugEnabled()) { // https://github.com/RestComm/Restcomm-Connect/issues/1419 avoid using error to avoid polluting alerts on logentries. logger.debug("response: \n"+response.toString()+"\n"); } manager.tell(response, null); } // @Override // public void init(final ServletConfig config) throws ServletException { // configuration.setProperty(ServletConfig.class.getName(), config); // } private ActorRef manager(final Configuration configuration, final SipFactory factory, final DaoManager storage) { final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new UserAgentManager(configuration, factory, storage, servletContext); } }); return system.actorOf(props); } @Override public void servletInitialized(SipServletContextEvent event) { if (event.getSipServlet().getClass().equals(UserAgentManagerProxy.class)) { servletContext = event.getServletContext(); configuration = (Configuration) servletContext.getAttribute(Configuration.class.getName()); final SipFactory factory = (SipFactory) servletContext.getAttribute(SIP_FACTORY); final DaoManager storage = (DaoManager) servletContext.getAttribute(DaoManager.class.getName()); system = (ActorSystem) servletContext.getAttribute(ActorSystem.class.getName()); logger.info("About to create new UserAgentManager"); manager = manager(configuration, factory, storage); pingInterval = configuration.subset("runtime-settings").getInt("ping-interval", 60); system.scheduler().schedule(Duration.create(5, TimeUnit.SECONDS), Duration.create(pingInterval, TimeUnit.SECONDS), manager, ReceiveTimeout.getInstance(), system.dispatcher()); } } }
5,039
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
UserAgentManager.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.telephony/src/main/java/org/restcomm/connect/telephony/ua/UserAgentManager.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.restcomm.connect.telephony.ua; import akka.actor.ActorRef; import akka.actor.ReceiveTimeout; import akka.event.Logging; import akka.event.LoggingAdapter; import org.apache.commons.configuration.Configuration; import org.joda.time.DateTime; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.RegistrationsDao; import org.restcomm.connect.dao.common.OrganizationUtil; import org.restcomm.connect.dao.entities.Registration; import org.restcomm.connect.monitoringservice.MonitoringService; import org.restcomm.connect.telephony.api.GetCall; import org.restcomm.connect.telephony.api.Hangup; import org.restcomm.connect.telephony.api.UserRegistration; import org.restcomm.connect.telephony.api.util.CallControlHelper; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.sip.Address; import javax.servlet.sip.Parameterable; import javax.servlet.sip.ServletParseException; import javax.servlet.sip.SipApplicationSession; import javax.servlet.sip.SipFactory; import javax.servlet.sip.SipServletMessage; import javax.servlet.sip.SipServletRequest; import javax.servlet.sip.SipServletResponse; import javax.servlet.sip.SipSession; import javax.servlet.sip.SipURI; import java.io.IOException; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import static java.lang.Integer.parseInt; import static javax.servlet.sip.SipServlet.OUTBOUND_INTERFACES; import static javax.servlet.sip.SipServletResponse.SC_BUSY_EVERYWHERE; import static javax.servlet.sip.SipServletResponse.SC_BUSY_HERE; import static javax.servlet.sip.SipServletResponse.SC_OK; import static javax.servlet.sip.SipServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED; import static javax.servlet.sip.SipServletResponse.SC_UNAUTHORIZED; import static org.restcomm.connect.commons.util.HexadecimalUtils.toHex; /** * @author [email protected] (Thomas Quintana) * @author [email protected] */ public final class UserAgentManager extends RestcommUntypedActor { private static final int DEFAUL_IMS_PROXY_PORT = -1; private static final String REGISTER = "REGISTER"; private static final String REQ_PARAMETER = "Req"; private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); private boolean authenticateUsers = true; private final SipFactory factory; private final DaoManager storage; private final ServletContext servletContext; private ActorRef monitoringService; private final int pingInterval; private final String instanceId; private boolean useSbc; // IMS authentication private boolean actAsImsUa; private String imsProxyAddress; private int imsProxyPort; private String imsDomain; private String clientAlgorithm; private String clientQop; public UserAgentManager(final Configuration configuration, final SipFactory factory, final DaoManager storage, final ServletContext servletContext) { super(); // this.configuration = configuration; this.servletContext = servletContext; monitoringService = (ActorRef) servletContext.getAttribute(MonitoringService.class.getName()); final Configuration runtime = configuration.subset("runtime-settings"); this.authenticateUsers = runtime.getBoolean("authenticate"); clientAlgorithm = RestcommConfiguration.getInstance().getMain().getClientAlgorithm(); clientQop = RestcommConfiguration.getInstance().getMain().getClientQOP(); this.factory = factory; this.storage = storage; pingInterval = runtime.getInt("ping-interval", 60); logger.info("About to run firstTimeCleanup()"); instanceId = RestcommConfiguration.getInstance().getMain().getInstanceId(); if(!runtime.subset("ims-authentication").isEmpty()){ final Configuration imsAuthentication = runtime.subset("ims-authentication"); this.actAsImsUa = imsAuthentication.getBoolean("act-as-ims-ua"); if (actAsImsUa) { this.imsProxyAddress = imsAuthentication.getString("proxy-address"); this.imsProxyPort = imsAuthentication.getInt("proxy-port"); if (imsProxyPort == 0) { imsProxyPort = DEFAUL_IMS_PROXY_PORT; } this.imsDomain = imsAuthentication.getString("domain"); if (actAsImsUa && (imsProxyAddress == null || imsProxyAddress.isEmpty() || imsDomain == null || imsDomain.isEmpty())) { logger.warning("ims proxy-address or domain is not configured"); } this.actAsImsUa = actAsImsUa && imsProxyAddress != null && !imsProxyAddress.isEmpty() && imsDomain != null && !imsDomain.isEmpty(); } } useSbc = runtime.getBoolean("use-sbc", false); firstTimeCleanup(); } private void firstTimeCleanup() { if (logger.isInfoEnabled()) logger.info("Initial registration cleanup. Will check existing registrations in DB and cleanup appropriately"); final RegistrationsDao registrations = storage.getRegistrationsDao(); List<Registration> results = registrations.getRegistrationsByInstanceId(instanceId); for (final Registration result : results) { if (result.isWebRTC()) { //If this is a WebRTC registration remove it since after restart the websocket connection is gone if (logger.isInfoEnabled()) logger.info("Will remove WebRTC client: "+result.getLocation()); registrations.removeRegistration(result); monitoringService.tell(new UserRegistration(result.getUserName(), result.getLocation(), false, result.getOrganizationSid()), self()); } else { final DateTime expires = result.getDateExpires(); if (expires.isBeforeNow() || expires.isEqualNow()) { if (logger.isInfoEnabled()) { logger.info("Registration: " + result.getLocation() + " expired and will be removed now"); } registrations.removeRegistration(result); monitoringService.tell(new UserRegistration(result.getUserName(), result.getLocation(), false, result.getOrganizationSid()), self()); monitoringService.tell(new GetCall(result.getLocation()), self()); } else { final DateTime updated = result.getDateUpdated(); Long pingIntervalMillis = new Long(pingInterval * 1000 * 3); if ((DateTime.now().getMillis() - updated.getMillis()) > pingIntervalMillis) { //Last time this registration updated was older than (pingInterval * 3), looks like it doesn't respond to OPTIONS if (logger.isInfoEnabled()) { logger.info("Registration: " + result.getLocation() + " didn't respond to OPTIONS and will be removed now"); } registrations.removeRegistration(result); monitoringService.tell(new UserRegistration(result.getUserName(), result.getLocation(), false, result.getOrganizationSid()), self()); monitoringService.tell(new GetCall(result.getLocation()), self()); } } } } results = registrations.getRegistrationsByInstanceId(instanceId); if (logger.isInfoEnabled()) logger.info("Initial registration cleanup finished, starting Restcomm with "+results.size()+" registrations"); } private void clean() throws ServletException { final RegistrationsDao registrations = storage.getRegistrationsDao(); final List<Registration> results = registrations.getRegistrationsByInstanceId(instanceId); for (final Registration result : results) { final DateTime expires = result.getDateExpires(); if (expires.isBeforeNow() || expires.isEqualNow()) { if(logger.isInfoEnabled()) { logger.info("Registration: "+result.getAddressOfRecord()+" expired. Will ping again."); } //Instead of removing registrations we ping the client one last time to ensure it was not a temporary loss // of connectivity. We don't need to remove the registration here. It will be handled only if the OPTIONS ping // times out and the related calls from the client cleaned up as well try{ ping(result.getLocation(),result.getAddressOfRecord()); }catch(ServletParseException spe){ logger.warning("Bad Parameters: "+result.getLocation() + "," + result.getAddressOfRecord()); registrations.removeRegistration(result); } //registrations.removeRegistration(result); //monitoringService.tell(new UserRegistration(result.getUserName(), result.getLocation(), false), self()); } else { final DateTime updated = result.getDateUpdated(); Long pingIntervalMillis = new Long(pingInterval * 1000 * 3); if ((DateTime.now().getMillis() - updated.getMillis()) > pingIntervalMillis) { //Last time this registration updated was older than (pingInterval * 3), looks like it doesn't respond to OPTIONS if (logger.isInfoEnabled()) { logger.info("Registration: " + result.getAddressOfRecord() + " didn't respond to OPTIONS. Will ping again."); } // Instead of removing registrations we ping the client one last time to ensure it was not a temporary loss // of connectivity. We don't need to remove the registration here. It will be handled only if the OPTIONS ping // times out and the related calls from the client cleaned up as well try{ ping(result.getLocation(),result.getAddressOfRecord()); }catch(ServletParseException spe){ logger.warning("Bad Parameters: "+result.getLocation() + "," + result.getAddressOfRecord()); registrations.removeRegistration(result); } // registrations.removeRegistration(result); // monitoringService.tell(new UserRegistration(result.getUserName(), result.getLocation(), false), self()); } } } } private void disconnectActiveCalls(ActorRef call) { if (call != null && !call.isTerminated()) { call.tell(new Hangup("Registration_Removed"), self()); //callManager.tell(new DestroyCall(call), self()); if (logger.isDebugEnabled()) { logger.debug("Disconnected call: "+call.path()+" , after registration removed"); } } } private String header(final String nonce, final String realm, final String scheme) { final StringBuilder buffer = new StringBuilder(); buffer.append(scheme).append(" "); if(clientAlgorithm != null && !clientAlgorithm.isEmpty()){ buffer.append("algorithm=\"").append(clientAlgorithm).append("\", "); buffer.append("qop=\"").append(clientQop).append("\", "); } buffer.append("realm=\"").append(realm).append("\", "); buffer.append("nonce=\"").append(nonce).append("\""); return buffer.toString(); } private void authenticate(final Object message) throws IOException { final SipServletRequest request = (SipServletRequest) message; final SipServletResponse response = request.createResponse(SC_PROXY_AUTHENTICATION_REQUIRED); final String nonce = nonce(); final SipURI uri = (SipURI) request.getTo().getURI(); final String realm = uri.getHost(); final String header = header(nonce, realm, "Digest"); response.addHeader("Proxy-Authenticate", header); response.send(); } private void keepAlive() throws Exception { final RegistrationsDao registrations = storage.getRegistrationsDao(); final List<Registration> results = registrations.getRegistrationsByInstanceId(instanceId); if (results != null && results.size() > 0) { if (logger.isDebugEnabled()) { logger.debug("Registrations for InstanceId: "+ instanceId +" , returned "+results.size()+" registrations"); } for (final Registration result : results) { final String location = result.getLocation(); final String aor = result.getAddressOfRecord(); try{ ping(location,aor); }catch(ServletParseException spe){ logger.warning("Bad Parameters: aor:" + aor + ", location:"+ location); registrations.removeRegistration(result); } } } else { if (logger.isDebugEnabled()) { logger.debug("Registrations for InstanceId: "+ instanceId +" , returned no registrations"); } } } private String nonce() { final byte[] uuid = UUID.randomUUID().toString().getBytes(); final char[] hex = toHex(uuid); return new String(hex).substring(0, 31); } @Override public void onReceive(final Object message) throws Exception { final Class<?> klass = message.getClass(); final ActorRef sender = sender(); if (logger.isInfoEnabled()) { logger.info("UserAgentManager Processing Message: \"" + klass.getName() + " sender : "+ sender.getClass()+" self is terminated: "+self().isTerminated()); } if (message instanceof ReceiveTimeout) { if (logger.isDebugEnabled()) { logger.debug("Timeout received, ping interval: "+pingInterval+" , will clean up registrations and send keep alive"); } clean(); keepAlive(); } else if (message instanceof SipServletRequest) { final SipServletRequest request = (SipServletRequest) message; final String method = request.getMethod(); if ("REGISTER".equalsIgnoreCase(method)) { if (logger.isDebugEnabled()) { logger.debug("REGISTER request received: "+request.toString()); } if (actAsImsUa) { proxyRequestToIms(request); } else if(authenticateUsers) { // https://github.com/Mobicents/RestComm/issues/29 Allow disabling of SIP authentication final String authorization = request.getHeader("Proxy-Authorization"); if (authorization != null) { if (CallControlHelper.permitted(authorization, method, storage, OrganizationUtil.getOrganizationSidBySipURIHost(storage, (SipURI) request.getFrom().getURI()))) { register(message); } else { SipServletResponse response = ((SipServletRequest) message).createResponse(javax.servlet.sip.SipServletResponse.SC_FORBIDDEN); //Issue #935, Send 403 FORBIDDEN instead of issuing 407 again and again response.send(); } } else { authenticate(message); } } else { register(message); } } } else if (message instanceof SipServletResponse) { SipServletResponse response = (SipServletResponse) message; int responseStatusCode = response.getStatus(); if (responseStatusCode > 400 // https://telestax.atlassian.net/browse/RESTCOMM-1582: Fix for User Agent that reply with BUSY when they are in a call && (responseStatusCode != SC_BUSY_HERE && responseStatusCode != SC_BUSY_EVERYWHERE) && response.getMethod().equalsIgnoreCase("OPTIONS")) { removeRegistration(response); } else if (actAsImsUa && response.getMethod().equalsIgnoreCase(REGISTER)) { proxyResponseFromIms(message, response); } else { pong(message); } } else if(message instanceof ActorRef) { disconnectActiveCalls((ActorRef) message); } } private void removeRegistration(final SipServletMessage sipServletMessage) throws ServletParseException { removeRegistration(sipServletMessage, false); } private void removeRegistration(final SipServletMessage sipServletMessage, boolean locationInContact) throws ServletParseException{ final RegistrationsDao regDao = storage.getRegistrationsDao(); List<Registration> registrations = null; Address toAddress = sipServletMessage.getTo(); SipURI toURI = (SipURI) toAddress.getURI(); String user = toURI.getUser(); SipURI location = null; if(locationInContact || sipServletMessage instanceof SipServletResponse) { if(sipServletMessage.getAddressHeader("Contact") == null) { if(useSbc) { // https://github.com/RestComm/Restcomm-Connect/issues/2741 support for SBC SipServletRequest originalRequest = ((SipServletResponse)sipServletMessage).getRequest(); if(logger.isDebugEnabled()) { logger.debug("Original request for the OPTIONS: " + originalRequest); } if(originalRequest == null) { location = (SipURI) sipServletMessage.getTo().getURI(); registrations = regDao.getRegistrations(user, OrganizationUtil.getOrganizationSidBySipURIHost(storage, toURI)); if(logger.isDebugEnabled()) { logger.debug("no Contact in OPTIONS response or original request so can't get the right location, getting all registrations " + registrations + " from " + toURI); } } else { location = (SipURI) originalRequest.getRequestURI(); } } else { location = (SipURI) sipServletMessage.getTo().getURI(); } } else { location = (SipURI)sipServletMessage.getAddressHeader("Contact").getURI(); } } else { location = (SipURI)((SipServletRequest)sipServletMessage).getRequestURI(); } if(logger.isDebugEnabled()) { logger.debug("Error response for the OPTIONS to: "+location+" will remove registration"); } if(registrations == null || registrations.isEmpty()) { int port= location.getPort(); if(port > 0) { registrations = regDao.getRegistrationsByLocation(user, "%"+location.getHost()+":"+location.getPort()); } else { registrations = regDao.getRegistrationsByLocation(user, "%"+location.getHost()); } } if(logger.isDebugEnabled()) { logger.debug("Resultant registrations of given criteria, that will be removed are:"+registrations); } if (registrations != null) { Iterator<Registration> iter = registrations.iterator(); SipURI regLocation = null; while (iter.hasNext()) { Registration reg = iter.next(); try { regLocation = (SipURI) factory.createURI(reg.getLocation()); } catch (ServletParseException e) {} // Long pingIntervalMillis = new Long(pingInterval * 1000 * 3); // boolean optionsTimeout = ((DateTime.now().getMillis() - reg.getDateUpdated().getMillis()) > pingIntervalMillis); if(logger.isDebugEnabled()) { logger.debug("regLocation: " + regLocation + " reg.getAddressOfRecord(): "+reg.getAddressOfRecord() + " reg.getLocation(): "+reg.getLocation() + ", reg.getDateExpires(): " + reg.getDateExpires() + ", reg.getDateUpdated(): " + reg.getDateUpdated() + ", location: " + location + ", reg.getLocation().contains(location): " + reg.getLocation().contains(location.toString())); if (reg.getDateExpires().isBeforeNow() || reg.getDateExpires().isEqualNow()) { logger.debug("Registration: "+ reg.getAddressOfRecord()+" expired"); } } String locationStored = getLocationWithoutParameters(regLocation); String locationToTest = getLocationWithoutParameters(location); // We clean up only if the location is similar to the registration location to avoid cleaning up all registration lcoation for the AOR // We keep getting REGISTER and allow for some leeway in case of connectivity issues from restcomm clients. // if (regLocation != null && optionsTimeout && reg.getLocation().contains(location) && if (locationStored != null && locationStored.equalsIgnoreCase(locationToTest) ) { // && (reg.getAddressOfRecord().equalsIgnoreCase(regLocation.toString()) || reg.getLocation().equalsIgnoreCase(regLocation.toString()))) { if(logger.isDebugEnabled()) { logger.debug("Registration: " + reg.getLocation() + " failed to response to OPTIONS and will be removed"); } regDao.removeRegistration(reg); monitoringService.tell(new UserRegistration(reg.getUserName(), reg.getLocation(), false, reg.getOrganizationSid()), self()); monitoringService.tell(new GetCall(reg.getLocation()), self()); } else { if (logger.isDebugEnabled()) { String msg = String.format("Registration DID NOT removed. SIP Message location: %s, registration location (in DB) %s.", locationToTest, reg.getLocation()); logger.debug(msg); } } } } } private String getLocationWithoutParameters(final SipURI location) { String result = null; result = "sip:"+location.getUser()+"@"+location.getHost()+":"+location.getPort(); return result; } private void patch(final SipURI uri, final String address, final int port) throws UnknownHostException { uri.setHost(address); uri.setPort(port); } private void ping(final String location, final String aor) throws ServletException { final SipApplicationSession application = factory.createApplicationSession(); String toTransport = ((SipURI) factory.createURI(aor)).getTransportParam(); if (toTransport == null) { // RESTCOMM-301 NPE in RestComm Ping toTransport = "udp"; } /* sometime users on webrtc clients like olympus, closes the tab instead of properly hangup. * so removing this check so we could send OPTIONS to WebRtc clients as well: * if (toTransport.equalsIgnoreCase("ws") || toTransport.equalsIgnoreCase("wss")) { return; }*/ final SipURI outboundInterface = outboundInterface(toTransport); StringBuilder buffer = new StringBuilder(); buffer.append("sip:restcomm").append("@").append(outboundInterface.getHost()); final String from = buffer.toString(); SipServletRequest ping = null; SipURI uri = null; if(useSbc) { // https://github.com/RestComm/Restcomm-Connect/issues/2741 support for SBC ping = factory.createRequest(application, "OPTIONS", from, aor); uri = (SipURI) factory.createURI(location); //uri = (SipURI) factory.createURI(getLocationWithoutParameters(uri)); ping.setRequestURI(uri.clone()); } else { ping = factory.createRequest(application, "OPTIONS", from, location); uri = (SipURI) factory.createURI(location); } ping.pushRoute(uri); final SipSession session = ping.getSession(); session.setHandler("UserAgentManager"); if(logger.isDebugEnabled()) { logger.debug("About to send OPTIONS keepalive to: "+uri); } try { ping.send(); } catch (IOException e) { if (logger.isInfoEnabled()) { logger.info("There was a problem while trying to ping client: "+uri+" , will remove registration. " + e.getMessage()); } removeRegistration(ping); } } private void pong(final Object message) { final SipServletResponse response = (SipServletResponse) message; if (response.getApplicationSession().isValid()) { try { response.getApplicationSession().setInvalidateWhenReady(true); } catch (IllegalStateException ise) { if (logger.isDebugEnabled()) { logger.debug("The session was already invalidated, nothing to do"); } } } final RegistrationsDao registrations = storage.getRegistrationsDao(); SipURI toUri = (SipURI)response.getTo().getURI(); String location = "%"+toUri.getHost()+":"+toUri.getPort(); List<Registration> registrationList = registrations.getRegistrationsByLocation(toUri.getUser(), location); //Registration here shouldn't be null. Update it if(registrationList != null && !registrationList.isEmpty()){ Registration registration = registrationList.get(0).updated(); registrations.updateRegistration(registration); }else{ if (logger.isDebugEnabled()) { logger.debug(String.format("UAM pong: Could not find any registration for %s Location %s", toUri.getUser(), location)); } } } private SipURI outboundInterface(String toTransport) { SipURI result = null; @SuppressWarnings("unchecked") final List<SipURI> uris = (List<SipURI>) servletContext.getAttribute(OUTBOUND_INTERFACES); for (final SipURI uri : uris) { final String transport = uri.getTransportParam(); if (toTransport != null && toTransport.equalsIgnoreCase(transport)) { result = uri; } } return result; } private void register(final Object message) throws Exception { final SipServletRequest request = (SipServletRequest) message; final Address contact = request.getAddressHeader("Contact"); // Get the expiration time. int ttl = contact.getExpires(); if (ttl == -1) { final String expires = request.getHeader("Expires"); if (expires != null) { ttl = parseInt(expires); } else { ttl = 3600; } } // Make sure registrations don't last more than 1 hour. if (ttl > 3600) { ttl = 3600; } if (logger.isDebugEnabled()) { logger.debug("Register request received for contact: "+contact+", and ttl: "+ttl); } // Get the rest of the information needed for a registration record. String name = contact.getDisplayName(); String ua = request.getHeader("User-Agent"); final SipURI to = (SipURI) request.getTo().getURI(); final String aor = to.toString(); final String user = to.getUser().trim(); final SipURI uri = (SipURI) contact.getURI(); final String ip = request.getInitialRemoteAddr(); final int port = request.getInitialRemotePort(); String transport = (uri.getTransportParam()==null?request.getParameter("transport"):uri.getTransportParam()); //Issue #935, take transport of initial request-uri if contact-uri has no transport parameter //If RURI is secure (SIPS) then pick TLS for transport - https://github.com/RestComm/Restcomm-Connect/issues/1956 if (((SipURI)request.getRequestURI()).isSecure()) { transport = "tls"; } if (transport == null && !request.getInitialTransport().equalsIgnoreCase("udp")) { //Issue1068, if Contact header or RURI doesn't specify transport, check InitialTransport from transport = request.getInitialTransport(); } boolean isLBPresent = false; // https://github.com/RestComm/Restcomm-Connect/issues/2741 only do that for non SBC Use cases if(!useSbc) { //Issue 306: https://telestax.atlassian.net/browse/RESTCOMM-306 final String initialIpBeforeLB = request.getHeader("X-Sip-Balancer-InitialRemoteAddr"); final String initialPortBeforeLB = request.getHeader("X-Sip-Balancer-InitialRemotePort"); if(initialIpBeforeLB != null && !initialIpBeforeLB.isEmpty() && initialPortBeforeLB != null && !initialPortBeforeLB.isEmpty()) { if(logger.isInfoEnabled()) { logger.info("Client in front of LB. Patching URI: "+uri.toString()+" with IP: "+initialIpBeforeLB+" and PORT: "+initialPortBeforeLB+" for USER: "+user); } patch(uri, initialIpBeforeLB, Integer.valueOf(initialPortBeforeLB)); isLBPresent = true; } else { if(logger.isInfoEnabled()) { logger.info("Patching URI: " + uri.toString() + " with IP: " + ip + " and PORT: " + port + " for USER: " + user); } patch(uri, ip, port); } } final String address = createAddress(request); // Prepare the response. final SipServletResponse response = request.createResponse(SC_OK); // Update the data store. final Sid sid = Sid.generate(Sid.Type.REGISTRATION); final DateTime now = DateTime.now(); // Issue 87 // (http://www.google.com/url?q=https://bitbucket.org/telestax/telscale-restcomm/issue/87/verb-and-not-working-for-end-to-end-calls%23comment-5855486&usd=2&usg=ALhdy2_mIt4FU4Yb_EL-s0GZCpBG9BB8eQ) // if display name or UA are null, the hasRegistration returns 0 even if there is a registration if (name == null) name = user; if (ua == null) ua = "GenericUA"; boolean webRTC = isWebRTC(transport, ua); Sid organizationSid = OrganizationUtil.getOrganizationSidBySipURIHost(storage, to); final Registration registration = new Registration(sid, instanceId, now, now, aor, name, user, ua, ttl, address, webRTC, isLBPresent, organizationSid); final RegistrationsDao registrations = storage.getRegistrationsDao(); if (ttl == 0) { // Remove Registration if ttl=0 registrations.removeRegistration(registration); response.setHeader("Expires", "0"); monitoringService.tell(new UserRegistration(user, address, false, organizationSid), self()); if(logger.isInfoEnabled()) { logger.info("The user agent manager unregistered " + user + " at address "+address+":"+port); } } else { monitoringService.tell(new UserRegistration(user, address, true, organizationSid), self()); if (registrations.hasRegistration(registration)) { // Update Registration if exists registrations.updateRegistration(registration); if(logger.isInfoEnabled()) { logger.info("The user agent manager updated " + user + " at address " + address+":"+port); } } else { // Add registration since it doesn't exists on the DB registrations.addRegistration(registration); if(logger.isInfoEnabled()) { logger.info("The user agent manager registered " + user + " at address " + address+":"+port); } } response.setHeader("Contact", contact(uri, ttl)); } // Success response.send(); // Cleanup // if(request.getSession().isValid()) { // request.getSession().invalidate(); // } try { if (request != null) { if (request.getApplicationSession() != null) { if (request.getApplicationSession().isValid()) { try { request.getApplicationSession().setInvalidateWhenReady(true); } catch (IllegalStateException exception) { logger.warning("Illegal State: while trying to setInvalidateWhenReady(true) for application session, message: "+exception.getMessage()); } } } else { if (logger.isInfoEnabled()) { logger.info("After sent response: "+response.toString()+" for Register request, application session is NULL!"); } } } else { if (logger.isInfoEnabled()) { logger.info("After sent response: "+response.toString()+" for Register request, request is NULL!"); } } } catch (Exception e) { logger.error("Exception while trying to setInvalidateWhenReady(true) after sent response to register : "+response.toString()+" exception: "+e); } } private String createAddress(SipServletRequest request) throws ServletParseException { final Address contact = request.getAddressHeader("Contact"); final SipURI contactUri = (SipURI) contact.getURI(); final SipURI to = (SipURI) request.getTo().getURI(); final String user = useSbc ? contactUri.getUser().trim() : to.getUser().trim(); String transport = (contactUri.getTransportParam()==null?request.getParameter("transport"):contactUri.getTransportParam()); //Issue #935, take transport of initial request-uri if contact-uri has no transport parameter //If RURI is secure (SIPS) then pick TLS for transport - https://github.com/RestComm/Restcomm-Connect/issues/1956 if (((SipURI)request.getRequestURI()).isSecure()) { transport = "tls"; } if (transport == null && !request.getInitialTransport().equalsIgnoreCase("udp")) { //Issue1068, if Contact header or RURI doesn't specify transport, check InitialTransport from transport = request.getInitialTransport(); } final StringBuffer buffer = new StringBuffer(); if (((SipURI)request.getRequestURI()).isSecure()) { buffer.append("sips:"); } else { buffer.append("sip:"); } int contactPort = contactUri.getPort(); if(contactPort < 0) { if(transport == null || transport.equalsIgnoreCase("udp") || transport.equalsIgnoreCase("tcp")) { contactPort = 5060; } else if(transport.equalsIgnoreCase("tls")) { contactPort = 5061; } else if (transport.equalsIgnoreCase("ws")) { contactPort = 5081; } else if (transport.equalsIgnoreCase("wss")) { contactPort = 5082; } } buffer.append(normalize(user)).append("@").append(contactUri.getHost()).append(":").append(contactPort); // https://bitbucket.org/telestax/telscale-restcomm/issue/142/restcomm-support-for-other-transports-than if (transport != null) { buffer.append(";transport=").append(transport); } Iterator<String> extraParameterNames = contactUri.getParameterNames(); while (extraParameterNames.hasNext()) { String paramName = extraParameterNames.next(); if (!paramName.equalsIgnoreCase("transport")) { String paramValue = contactUri.getParameter(paramName); buffer.append(";"); buffer.append(paramName); buffer.append("="); buffer.append(paramValue); } } return buffer.toString(); } /** * Checks whether the client is WebRTC or not. * * <p> * A client is considered WebRTC if one of the following statements is true:<br> * 1. The chosen transport is WebSockets (transport=ws).<br> * 2. The chosen transport is WebSockets Secured (transport=wss).<br> * 3. The User-Agent corresponds to one of TeleStax mobile clients. * </p> * * @param transport * @param userAgent * @return */ private boolean isWebRTC(String transport, String userAgent) { return "ws".equalsIgnoreCase(transport) || "wss".equalsIgnoreCase(transport) || userAgent.toLowerCase().contains("restcomm"); } private String contact(final SipURI uri, final int expires) throws ServletParseException { final Address contact = factory.createAddress(uri); contact.setExpires(expires); return contact.toString(); } private Map<String, String> toMap(final String header) { final Map<String, String> map = new HashMap<String, String>(); final int endOfScheme = header.indexOf(" "); map.put("scheme", header.substring(0, endOfScheme).trim()); final String[] tokens = header.substring(endOfScheme + 1).split(","); for (final String token : tokens) { final String[] values = token.trim().split("=",2); //Issue #935, split only for first occurrence of "=" map.put(values[0].toLowerCase(), values[1].replace("\"", "")); } return map; } private void proxyResponseFromIms(Object message, SipServletResponse response) throws ServletParseException, IOException { if(logger.isDebugEnabled()) { logger.debug("REGISTER IMS Response received: "+message); } final SipServletRequest incomingRequest = (SipServletRequest) response.getApplicationSession().getAttribute(REQ_PARAMETER); String wwwAuthenticate = response.getHeader("WWW-Authenticate"); final Address contact = incomingRequest.getAddressHeader("Contact"); final SipURI uri = (SipURI) contact.getURI(); final String ip = incomingRequest.getInitialRemoteAddr(); final int port = incomingRequest.getInitialRemotePort(); String ua = incomingRequest.getHeader("User-Agent"); String name = contact.getDisplayName(); final SipURI to = (SipURI) incomingRequest.getTo().getURI(); final String aor = to.toString(); final String user = to.getUser(); boolean isLBPresent = false; //Issue 306: https://telestax.atlassian.net/browse/RESTCOMM-306 final String initialIpBeforeLB = incomingRequest.getHeader("X-Sip-Balancer-InitialRemoteAddr"); final String initialPortBeforeLB = incomingRequest.getHeader("X-Sip-Balancer-InitialRemotePort"); if(initialIpBeforeLB != null && !initialIpBeforeLB.isEmpty() && initialPortBeforeLB != null && !initialPortBeforeLB.isEmpty()) { if(logger.isInfoEnabled()) { logger.info("Client in front of LB. Patching URI: "+uri.toString()+" with IP: "+initialIpBeforeLB+" and PORT: "+initialPortBeforeLB+" for USER: "+user); } patch(uri, initialIpBeforeLB, Integer.valueOf(initialPortBeforeLB)); isLBPresent = true; } else { if(logger.isInfoEnabled()) { logger.info("Patching URI: " + uri.toString() + " with IP: " + ip + " and PORT: " + port + " for USER: " + user); } patch(uri, ip, port); } SipServletResponse incomingLegResponse = incomingRequest.createResponse(response.getStatus(), response.getReasonPhrase()); if (wwwAuthenticate != null) { incomingLegResponse.addHeader("WWW-Authenticate", wwwAuthenticate); } int ttl = 3600; final Address imsContact = response.getAddressHeader("Contact"); if (imsContact != null) { ttl = imsContact.getExpires(); if (ttl == -1) { final String expires = response.getRequest().getHeader("Expires"); if (expires != null) { ttl = parseInt(expires); } else { ttl = 3600; } } final SipURI sipURI = (SipURI) contact.getURI(); String newContact = contact(sipURI, ttl); if(logger.isInfoEnabled()) { logger.info("ttl: "+ttl); logger.info("new contact: "+newContact); } incomingLegResponse.setHeader("Contact", newContact); } if(logger.isInfoEnabled()) { if(response.getSession().isValid()) { logger.info("outgoing leg state: "+response.getSession().getState()); } if(incomingLegResponse.getSession().isValid()) { logger.info("incoming leg state: "+incomingLegResponse.getSession().getState()); } } if (response.getStatus()>=400 && response.getStatus() != SC_UNAUTHORIZED && response.getStatus() != SC_PROXY_AUTHENTICATION_REQUIRED) { removeRegistration(incomingRequest, true); } else if (response.getStatus()==200) { String transport = (uri.getTransportParam()==null?incomingRequest.getParameter("transport"):uri.getTransportParam()); //Issue #935, take transport of initial request-uri if contact-uri has no transport parameter if (transport == null && !incomingRequest.getInitialTransport().equalsIgnoreCase("udp")) { //Issue1068, if Contact header or RURI doesn't specify transport, check InitialTransport from transport = incomingRequest.getInitialTransport(); } final Sid sid = Sid.generate(Sid.Type.REGISTRATION); final DateTime now = DateTime.now(); final StringBuffer buffer = new StringBuffer(); buffer.append("sip:").append(normalize(user)).append("@").append(uri.getHost()).append(":").append(uri.getPort()); // https://bitbucket.org/telestax/telscale-restcomm/issue/142/restcomm-support-for-other-transports-than if (transport != null) { buffer.append(";transport=").append(transport); } final String address = buffer.toString(); if (name == null) name = user; if (ua == null) ua = "GenericUA"; boolean webRTC = isWebRTC(transport, ua); Sid organizationSid = OrganizationUtil.getOrganizationSidBySipURIHost(storage, to); final Registration registration = new Registration(sid, RestcommConfiguration.getInstance().getMain().getInstanceId(), now, now, aor, name, user, ua, ttl, address, webRTC, isLBPresent, organizationSid); final RegistrationsDao registrations = storage.getRegistrationsDao(); if (ttl == 0) { // Remove Registration if ttl=0 registrations.removeRegistration(registration); incomingLegResponse.setHeader("Expires", "0"); monitoringService.tell(new UserRegistration(user, address, false, organizationSid), self()); if(logger.isInfoEnabled()) { logger.info("The user agent manager unregistered " + user + " at address "+address+":"+port); } } else { monitoringService.tell(new UserRegistration(user, address, true, organizationSid), self()); if (registrations.hasRegistration(registration)) { // Update Registration if exists registrations.updateRegistration(registration); if(logger.isInfoEnabled()) { logger.info("The user agent manager updated " + user + " at address " + address+":"+port); } } else { // Add registration since it doesn't exists on the DB registrations.addRegistration(registration); if(logger.isInfoEnabled()) { logger.info("The user agent manager registered " + user + " at address " + address+":"+port); } } } } incomingLegResponse.send(); if(logger.isDebugEnabled()) { logger.debug("REGISTER IMS Response sent: "+incomingLegResponse); } } /** * normalize: normalize clients that contain @ sign in user e.g. [email protected] * @param user * @return */ private String normalize(String user) { if(user != null){ if(user.contains("@")) user = user.replaceAll("@", "%40"); } if(logger.isDebugEnabled()) logger.debug("Normalized User = " + user); return user; } private void proxyRequestToIms(SipServletRequest request) throws ServletParseException, IOException { // TODO question - this method is deprecated but only that can be used to set callId which has to be the same for both REGISTER messages final SipServletRequest outgoingRequest = factory.createRequest(request, true); Parameterable via = outgoingRequest.getParameterableHeader("Via"); if (via == null) { seltLocalContact(outgoingRequest); } else { String[] strings = via.getValue().trim().split(" "); if (strings.length != 2) { seltLocalContact(outgoingRequest); } else { outgoingRequest.removeHeader("Contact"); String addressFromVia = strings[1].trim(); Address address = factory.createAddress("sip:" + addressFromVia); outgoingRequest.setAddressHeader("Contact", address); } } request.getApplicationSession().setAttribute(REQ_PARAMETER, request); final SipURI routeToRegistrar = factory.createSipURI(null, imsProxyAddress); routeToRegistrar.setLrParam(true); routeToRegistrar.setPort(imsProxyPort); outgoingRequest.pushRoute(routeToRegistrar); final SipURI requestUri = factory.createSipURI(null, imsDomain); outgoingRequest.setRequestURI(requestUri); if(logger.isDebugEnabled()) { logger.debug("Sending to ims proxy: "+ outgoingRequest); } outgoingRequest.send(); } private void seltLocalContact(SipServletRequest outgoingRequest) throws ServletParseException { Address contact = outgoingRequest.getAddressHeader("Contact"); SipURI sipURI = ((SipURI)contact.getURI()); sipURI.setPort(outgoingRequest.getLocalPort()); sipURI.setHost(outgoingRequest.getLocalAddr()); } @Override public void postStop() { try { if (logger.isInfoEnabled()) { logger.info("UserAgentManager actor at postStop, path: "+self().path()+", isTerminated: "+self().isTerminated()+", sender: "+sender()); if (storage != null){ logger.info("Number of current Registrations:" + storage.getRegistrationsDao().getRegistrations().size()); } } } catch (Exception exception) { if(logger.isInfoEnabled()) { logger.info("Exception during UserAgentManager postStop"); } } super.postStop(); } }
49,265
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ProxyManagerProxy.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.telephony/src/main/java/org/restcomm/connect/telephony/proxy/ProxyManagerProxy.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.restcomm.connect.telephony.proxy; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.UntypedActor; import akka.actor.UntypedActorFactory; import org.apache.commons.configuration.Configuration; import org.apache.log4j.Logger; import org.restcomm.connect.dao.DaoManager; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.sip.SipFactory; import javax.servlet.sip.SipServlet; import javax.servlet.sip.SipServletContextEvent; import javax.servlet.sip.SipServletListener; import javax.servlet.sip.SipServletRequest; import javax.servlet.sip.SipServletResponse; import java.io.IOException; /** * @author [email protected] (Thomas Quintana) * @author <a href="mailto:[email protected]">gvagenas</a> */ public final class ProxyManagerProxy extends SipServlet implements SipServletListener { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(ProxyManagerProxy.class); private ActorSystem system; private ActorRef manager; private ServletContext context; public ProxyManagerProxy() { super(); } @Override public void destroy() { if (system != null) system.stop(manager); } @Override protected void doRequest(final SipServletRequest request) throws ServletException, IOException { manager.tell(request, null); } @Override protected void doResponse(final SipServletResponse response) throws ServletException, IOException { manager.tell(response, null); } @Override public void init(final ServletConfig config) throws ServletException { super.init(config); // final ServletContext context = config.getServletContext(); // final SipFactory factory = (SipFactory) context.getAttribute(SIP_FACTORY); // Configuration configuration = (Configuration) context.getAttribute(Configuration.class.getName()); // configuration = configuration.subset("runtime-settings"); // final String address = configuration.getString("external-ip"); // final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); // system = (ActorSystem) context.getAttribute(ActorSystem.class.getName()); // manager = manager(config, factory, storage, address); // context.setAttribute(ProxyManager.class.getName(), manager); } private ActorRef manager(final ServletContext servletContext, final SipFactory factory, final DaoManager storage, final String address) { final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new ProxyManager(servletContext, factory, storage, address); } }); return system.actorOf(props); } @Override public void servletInitialized(SipServletContextEvent event) { if (event.getSipServlet().getClass().equals(ProxyManagerProxy.class)) { if(logger.isInfoEnabled()) { logger.info("ProxyManagerProxy sip servlet initialized. Will proceed to create ProxyManager"); } context = event.getServletContext(); final SipFactory factory = (SipFactory) context.getAttribute(SIP_FACTORY); Configuration configuration = (Configuration) context.getAttribute(Configuration.class.getName()); configuration = configuration.subset("runtime-settings"); final String address = configuration.getString("external-ip"); final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); system = (ActorSystem) context.getAttribute(ActorSystem.class.getName()); manager = manager(context, factory, storage, address); context.setAttribute(ProxyManager.class.getName(), manager); } } }
4,920
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ProxyManager.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.telephony/src/main/java/org/restcomm/connect/telephony/proxy/ProxyManager.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.restcomm.connect.telephony.proxy; import akka.actor.ActorContext; import akka.actor.ReceiveTimeout; import akka.event.Logging; import akka.event.LoggingAdapter; import org.joda.time.DateTime; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.GatewaysDao; import org.restcomm.connect.dao.entities.Gateway; import org.restcomm.connect.telephony.api.RegisterGateway; import scala.concurrent.duration.Duration; import javax.servlet.ServletContext; import javax.servlet.sip.Address; import javax.servlet.sip.AuthInfo; import javax.servlet.sip.ServletParseException; import javax.servlet.sip.SipApplicationSession; import javax.servlet.sip.SipFactory; import javax.servlet.sip.SipServletRequest; import javax.servlet.sip.SipServletResponse; import javax.servlet.sip.SipSession; import javax.servlet.sip.SipURI; import javax.sip.header.ContactHeader; import java.util.List; import java.util.concurrent.TimeUnit; import static javax.servlet.sip.SipServlet.OUTBOUND_INTERFACES; import static javax.servlet.sip.SipServletResponse.*; /** * @author [email protected] (Thomas Quintana) * @author [email protected] */ public final class ProxyManager extends RestcommUntypedActor { private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); private static final int ttl = 1800; private final ServletContext servletContext; private final SipFactory factory; private final DaoManager storage; private final String address; public ProxyManager(final ServletContext servletContext, final SipFactory factory, final DaoManager storage, final String address) { super(); this.servletContext = servletContext; this.factory = factory; this.storage = storage; this.address = address; final ActorContext context = context(); context.setReceiveTimeout(Duration.create(60, TimeUnit.SECONDS)); registerFirstTime(); if(logger.isInfoEnabled()) { logger.info("Proxy Manager started."); } } private void authenticate(final Object message) { final SipServletResponse response = (SipServletResponse) message; final SipApplicationSession application = response.getApplicationSession(); final Gateway gateway = (Gateway) application.getAttribute(Gateway.class.getName()); final int status = response.getStatus(); final AuthInfo authentication = factory.createAuthInfo(); final String realm = response.getChallengeRealms().next(); final String user = gateway.getUserName(); final String password = gateway.getPassword(); authentication.addAuthInfo(status, realm, user, password); register(gateway, authentication, response); } private Address contact(final Gateway gateway, final int expires) throws ServletParseException { SipURI outboundInterface = null; if (address != null && !address.isEmpty()) { if(address.contains(":")) { outboundInterface = (SipURI) factory.createSipURI(null, address); } else { outboundInterface = outboundInterface(address, "udp"); } } else { outboundInterface = outboundInterface(); } if (outboundInterface == null) outboundInterface = (SipURI) factory.createSipURI(null, address); final String user = gateway.getUserName(); final String host = outboundInterface.getHost(); int port = outboundInterface.getPort(); if (port == -1) { port = outboundInterface().getPort(); } // github#2519, If the user already has hort part, remove it in Contact String contactUser = user; if (contactUser.contains("@")) { int index = contactUser.indexOf("@"); contactUser = contactUser.substring(0, index); } final StringBuilder buffer = new StringBuilder(); buffer.append("sip:").append(contactUser).append("@").append(host).append(":").append(port); final Address contact = factory.createAddress(buffer.toString()); contact.setExpires(expires); return contact; } @Override public void onReceive(Object message) throws Exception { if (message instanceof ReceiveTimeout) { refresh(); } else if (message instanceof SipServletResponse) { final SipServletResponse response = (SipServletResponse) message; final int status = response.getStatus(); switch (status) { case SC_PROXY_AUTHENTICATION_REQUIRED: case SC_UNAUTHORIZED: { authenticate(message); } case SC_OK: { update(message); } } } else if (message instanceof RegisterGateway) { register(((RegisterGateway)message).getGateway()); } } private SipURI outboundInterface() { final ServletContext context = servletContext; SipURI result = null; @SuppressWarnings("unchecked") final List<SipURI> uris = (List<SipURI>) context.getAttribute(OUTBOUND_INTERFACES); for (final SipURI uri : uris) { final String transport = uri.getTransportParam(); if ("udp".equalsIgnoreCase(transport)) { result = uri; } } return result; } private SipURI outboundInterface(String address, String transport) { final ServletContext context = servletContext; SipURI result = null; @SuppressWarnings("unchecked") final List<SipURI> uris = (List<SipURI>) context.getAttribute(OUTBOUND_INTERFACES); for (final SipURI uri : uris) { final String interfaceAddress = uri.getHost(); final String interfaceTransport = uri.getTransportParam(); if (address.equalsIgnoreCase(interfaceAddress) && transport.equalsIgnoreCase(interfaceTransport)) { result = uri; } } return result; } private void registerFirstTime() { if(logger.isInfoEnabled()) { logger.info("First time registration for the gateways"); } final GatewaysDao gateways = storage.getGatewaysDao(); final List<Gateway> results = gateways.getGateways(); for (final Gateway result : results) { register(result); } } private void refresh() { final GatewaysDao gateways = storage.getGatewaysDao(); final List<Gateway> results = gateways.getGateways(); for (final Gateway result : results) { final DateTime lastUpdate = result.getDateUpdated(); final DateTime expires = lastUpdate.plusSeconds(result.getTimeToLive()); if (expires.isBeforeNow() || expires.isEqualNow()) { register(result); } } } private void register(final Gateway gateway) { if(logger.isInfoEnabled()) { logger.info("About to register gateway: "+gateway.getFriendlyName()); } register(gateway, null, null); } private void register(final Gateway gateway, final AuthInfo authentication, final SipServletResponse response) { try { final SipApplicationSession application = factory.createApplicationSession(); application.setAttribute(Gateway.class.getName(), gateway); final String user = gateway.getUserName(); final String proxy = gateway.getProxy(); final StringBuilder buffer = new StringBuilder(); // github#2519, If the user already has hort part, we dont need to add RC address if (user.contains("@")) { buffer.append("sip:").append(user); } else { buffer.append("sip:").append(user).append("@").append(proxy); } final String aor = buffer.toString(); // Set maximum expire time to 3600s final int expires = (gateway.getTimeToLive() > 0 && gateway.getTimeToLive() <= 3600) ? gateway.getTimeToLive() : ttl; final Address contact = contact(gateway, expires); // Issue http://code.google.com/p/restcomm/issues/detail?id=65 SipServletRequest register = null; if (response != null) { final String method = response.getRequest().getMethod(); register = response.getSession().createRequest(method); } else { register = factory.createRequest(application, "REGISTER", aor, aor); } if (authentication != null && response != null) { register.addAuthHeader(response, authentication); } // If contact header is already in, dont add it any more. if (register.getHeader(ContactHeader.NAME) == null) { register.addAddressHeader("Contact", contact, false); } final SipURI uri = factory.createSipURI(null, proxy); register.pushRoute(uri); register.setRequestURI(uri); final SipSession session = register.getSession(); session.setHandler("ProxyManager"); register.send(); } catch (final Exception exception) { final String name = gateway.getFriendlyName(); logger.error(exception, "Could not send a registration request to the proxy named " + name); } } private void update(final Object message) { final SipServletResponse response = (SipServletResponse) message; final SipApplicationSession application = response.getApplicationSession(); Gateway gateway = (Gateway) application.getAttribute(Gateway.class.getName()); // This will force the gateway's dateUpdated field to now so we can use it // to determine if we need to re-register. gateway = gateway.setTimeToLive(gateway.getTimeToLive()); final GatewaysDao gateways = storage.getGatewaysDao(); gateways.updateGateway(gateway); } }
11,063
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
VoiceRSSSpeechSynthesizerTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.tts.voicerss/src/test/java/org/restcomm/connect/tts/voicerss/VoiceRSSSpeechSynthesizerTest.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.restcomm.connect.tts.voicerss; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.net.URI; import java.net.URL; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.restcomm.connect.commons.cache.DiskCache; import org.restcomm.connect.commons.cache.DiskCacheRequest; import org.restcomm.connect.commons.cache.DiskCacheResponse; import org.restcomm.connect.commons.cache.HashGenerator; import org.restcomm.connect.tts.api.GetSpeechSynthesizerInfo; import org.restcomm.connect.tts.api.SpeechSynthesizerInfo; import org.restcomm.connect.tts.api.SpeechSynthesizerRequest; import org.restcomm.connect.tts.api.SpeechSynthesizerResponse; import scala.concurrent.duration.FiniteDuration; import akka.actor.Actor; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.UntypedActor; import akka.actor.UntypedActorFactory; import akka.testkit.JavaTestKit; /** * @author [email protected] (George Vagenas) */ public final class VoiceRSSSpeechSynthesizerTest { private ActorSystem system; private ActorRef tts; private ActorRef cache; private String tempSystemDirectory; public VoiceRSSSpeechSynthesizerTest() throws ConfigurationException { super(); } @Before public void before() throws Exception { system = ActorSystem.create(); final URL input = getClass().getResource("/voicerss.xml"); final XMLConfiguration configuration = new XMLConfiguration(input); tts = tts(configuration); cache = cache("/tmp/cache", "http://127.0.0.1:8080/restcomm/cache"); // Fix for MacOS systems: only append "/" to temporary path if it doesnt end with it - hrosa String tmpDir = System.getProperty("java.io.tmpdir"); tempSystemDirectory = "file:" + tmpDir + (tmpDir.endsWith("/") ? "" : "/"); } @After public void after() throws Exception { system.shutdown(); } private ActorRef tts(final Configuration configuration) { final String classpath = configuration.getString("[@class]"); return system.actorOf(new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public Actor create() throws Exception { return (UntypedActor) Class.forName(classpath).getConstructor(Configuration.class).newInstance(configuration); } })); } private ActorRef cache(final String path, final String uri) { return system.actorOf(new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new DiskCache(path, uri, true); } })); } @SuppressWarnings("unchecked") @Test public void testInfo() { new JavaTestKit(system) { { final ActorRef observer = getRef(); tts.tell(new GetSpeechSynthesizerInfo(), observer); final SpeechSynthesizerResponse<SpeechSynthesizerInfo> response = this.expectMsgClass( FiniteDuration.create(30, TimeUnit.SECONDS), SpeechSynthesizerResponse.class); assertTrue(response.succeeded()); final Set<String> languages = response.get().languages(); assertTrue(languages.contains("ca")); // assertTrue(languages.contains("zh")); assertTrue(languages.contains("zh-hk")); assertTrue(languages.contains("zh-tw")); assertTrue(languages.contains("da")); assertTrue(languages.contains("nl")); assertTrue(languages.contains("en-au")); assertTrue(languages.contains("en-ca")); assertTrue(languages.contains("en-gb")); assertTrue(languages.contains("en-in")); assertTrue(languages.contains("en")); assertTrue(languages.contains("fi")); assertTrue(languages.contains("fr-ca")); assertTrue(languages.contains("fr")); assertTrue(languages.contains("de")); assertTrue(languages.contains("it")); assertTrue(languages.contains("ja")); assertTrue(languages.contains("ko")); assertTrue(languages.contains("nb")); assertTrue(languages.contains("pl")); assertTrue(languages.contains("pt-br")); assertTrue(languages.contains("pt")); assertTrue(languages.contains("ru")); assertTrue(languages.contains("es-mx")); assertTrue(languages.contains("es")); assertTrue(languages.contains("sv")); } }; } @SuppressWarnings("unchecked") @Test @Ignore //Needs API key public void testSynthesisMan() { new JavaTestKit(system) { { final ActorRef observer = getRef(); String gender = "man"; String woman = "woman"; String language = "en"; String message = "Hello TTS World!"; String hash = HashGenerator.hashMessage(gender, language, message); String womanHash = HashGenerator.hashMessage(woman, language, message); assertTrue(!hash.equalsIgnoreCase(womanHash)); final SpeechSynthesizerRequest synthesize = new SpeechSynthesizerRequest(gender, language, message); tts.tell(synthesize, observer); final SpeechSynthesizerResponse<URI> response = this.expectMsgClass( FiniteDuration.create(30, TimeUnit.SECONDS), SpeechSynthesizerResponse.class); assertTrue(response.succeeded()); DiskCacheRequest diskCacheRequest = new DiskCacheRequest(response.get()); cache.tell(diskCacheRequest, observer); final DiskCacheResponse diskCacheResponse = this.expectMsgClass(FiniteDuration.create(30, TimeUnit.SECONDS), DiskCacheResponse.class); assertTrue(diskCacheResponse.succeeded()); assertEquals(tempSystemDirectory + hash + ".wav", response.get().toString()); assertEquals("http://127.0.0.1:8080/restcomm/cache/" + hash + ".wav", diskCacheResponse.get().toString()); FileUtils.deleteQuietly(new File(response.get())); } }; } @SuppressWarnings("unchecked") @Test @Ignore //Needs API key public void testSynthesisWoman() { new JavaTestKit(system) { { final ActorRef observer = getRef(); String gender = "woman"; String language = "en"; String message = "Hello TTS World!"; String hash = HashGenerator.hashMessage(gender, language, message); final SpeechSynthesizerRequest synthesize = new SpeechSynthesizerRequest(gender, language, message); tts.tell(synthesize, observer); final SpeechSynthesizerResponse<URI> response = this.expectMsgClass( FiniteDuration.create(30, TimeUnit.SECONDS), SpeechSynthesizerResponse.class); assertTrue(response.succeeded()); DiskCacheRequest diskCacheRequest = new DiskCacheRequest(response.get()); cache.tell(diskCacheRequest, observer); final DiskCacheResponse diskCacheResponse = this.expectMsgClass(FiniteDuration.create(30, TimeUnit.SECONDS), DiskCacheResponse.class); assertTrue(diskCacheResponse.succeeded()); assertEquals(tempSystemDirectory + hash + ".wav", response.get().toString()); assertEquals("http://127.0.0.1:8080/restcomm/cache/" + hash + ".wav", diskCacheResponse.get().toString()); FileUtils.deleteQuietly(new File(response.get())); } }; } }
9,302
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
VoiceRSSSpeechSynthesizer.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.tts.voicerss/src/main/java/org/restcomm/connect/tts/voicerss/VoiceRSSSpeechSynthesizer.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.restcomm.connect.tts.voicerss; import akka.actor.ActorRef; import akka.event.Logging; import akka.event.LoggingAdapter; import org.apache.commons.configuration.Configuration; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.restcomm.connect.commons.cache.HashGenerator; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.tts.api.GetSpeechSynthesizerInfo; import org.restcomm.connect.tts.api.SpeechSynthesizerException; import org.restcomm.connect.tts.api.SpeechSynthesizerInfo; import org.restcomm.connect.tts.api.SpeechSynthesizerRequest; import org.restcomm.connect.tts.api.SpeechSynthesizerResponse; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author [email protected] (George Vagenas) */ public final class VoiceRSSSpeechSynthesizer extends RestcommUntypedActor { private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); private static final List<NameValuePair> parameters; static { parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("c", "WAV")); parameters.add(new BasicNameValuePair("f", "8khz_16bit_mono")); } private final URI service; private final Map<String, String> men; public VoiceRSSSpeechSynthesizer(final Configuration configuration) { super(); // Add the credentials. final String apiKey = configuration.getString("apikey"); BasicNameValuePair apiNameValuePair = new BasicNameValuePair("key", apiKey); if (!parameters.contains(apiNameValuePair)) parameters.add(apiNameValuePair); // Initialize the speech synthesizer state. service = URI.create(configuration.getString("service-root")); men = new HashMap<String, String>(); load(configuration); } private SpeechSynthesizerInfo info() { return new SpeechSynthesizerInfo(men.keySet()); } private void load(final Configuration configuration) throws RuntimeException { // Initialize male voices. men.put("ca", configuration.getString("languages.catalan")); men.put("zh-cn", configuration.getString("languages.chinese-china")); men.put("zh-hk", configuration.getString("languages.chinese-hongkong")); men.put("zh-tw", configuration.getString("languages.chinese-taiwan")); men.put("da", configuration.getString("languages.danish")); men.put("nl", configuration.getString("languages.dutch")); men.put("en-au", configuration.getString("languages.english-australia")); men.put("en-ca", configuration.getString("languages.english-canada")); men.put("en-gb", configuration.getString("languages.english-greatbritain")); men.put("en-in", configuration.getString("languages.english-india")); men.put("en", configuration.getString("languages.english-us")); men.put("fi", configuration.getString("languages.finish")); men.put("fr-ca", configuration.getString("languages.french-canada")); men.put("fr", configuration.getString("languages.french-france")); men.put("de", configuration.getString("languages.german")); men.put("it", configuration.getString("languages.italina")); men.put("ja", configuration.getString("languages.japanese")); men.put("ko", configuration.getString("languages.korean")); men.put("nb", configuration.getString("languages.norwegian")); men.put("pl", configuration.getString("languages.polish")); men.put("pt-br", configuration.getString("languages.portuguese-brasil")); men.put("pt", configuration.getString("languages.portuguese-portugal")); men.put("ru", configuration.getString("languages.russian")); men.put("es-mx", configuration.getString("languages.spanish-mexico")); men.put("es", configuration.getString("languages.spanish-spain")); men.put("sv", configuration.getString("languages.swedish")); } @Override public void onReceive(final Object message) throws Exception { final Class<?> klass = message.getClass(); final ActorRef self = self(); final ActorRef sender = sender(); if (SpeechSynthesizerRequest.class.equals(klass)) { try { final URI uri = synthesize(message); if (sender != null) { sender.tell(new SpeechSynthesizerResponse<URI>(uri), self); } } catch (final Exception exception) { logger.error("There was an exception while trying to synthesize message: "+exception); if (sender != null) { sender.tell(new SpeechSynthesizerResponse<URI>(exception), self); } } } else if (GetSpeechSynthesizerInfo.class.equals(klass)) { sender.tell(new SpeechSynthesizerResponse<SpeechSynthesizerInfo>(info()), self); } } private String getLanguage(final String language) { String languageCode = men.get(language); return languageCode; } private URI synthesize(final Object message) throws IOException, SpeechSynthesizerException { final SpeechSynthesizerRequest request = (SpeechSynthesizerRequest) message; final String gender = request.gender(); final String language = request.language(); final String text = request.text(); if (language == null) { if(logger.isInfoEnabled()){ logger.info("There is no suitable speaker to synthesize " + request.language()); } throw new IllegalArgumentException("There is no suitable language to synthesize " + request.language()); } final String hash = HashGenerator.hashMessage(gender, language, text); final List<NameValuePair> query = new ArrayList<NameValuePair>(); query.addAll(parameters); query.add(new BasicNameValuePair("hl", getLanguage(language))); query.add(new BasicNameValuePair("src", text)); final HttpPost post = new HttpPost(service); final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(query, "UTF-8"); post.setEntity(entity); final HttpClient client = new DefaultHttpClient(); final HttpResponse response = client.execute(post); final StatusLine line = response.getStatusLine(); final int status = line.getStatusCode(); if (status == HttpStatus.SC_OK) { Header[] contentType = response.getHeaders("Content-Type"); if (contentType[0].getValue().startsWith("text")) { final StringBuilder buffer = new StringBuilder(); String error = EntityUtils.toString(response.getEntity()); logger.error("VoiceRSSSpeechSynthesizer error: " + error); buffer.append(error); throw new SpeechSynthesizerException(buffer.toString()); } if(logger.isInfoEnabled()){ logger.info("VoiceRSSSpeechSynthesizer success!"); } InputStream is = response.getEntity().getContent(); File file = new File(System.getProperty("java.io.tmpdir") + File.separator + hash + ".wav"); final OutputStream ostream = new FileOutputStream(file); final byte[] buffer = new byte[1024 * 8]; while (true) { final int len = is.read(buffer); if (len <= 0) { break; } ostream.write(buffer, 0, len); } ostream.close(); is.close(); return file.toURI(); } else { if(logger.isInfoEnabled()){ logger.info("VoiceRSSSpeechSynthesizer error, status code: " + line.getStatusCode() + (" reason phrase: ") + line.getReasonPhrase()); } final StringBuilder buffer = new StringBuilder(); buffer.append(line.getStatusCode()).append(" ").append(line.getReasonPhrase()); throw new SpeechSynthesizerException(buffer.toString()); } } }
9,647
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AcapelaSpeechSynthesizerTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.tts.acapela/src/test/java/org/restcomm/connect/tts/acapela/AcapelaSpeechSynthesizerTest.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.restcomm.connect.tts.acapela; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.net.URI; import java.net.URL; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.XMLConfiguration; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.restcomm.connect.commons.cache.DiskCache; import org.restcomm.connect.commons.cache.DiskCacheRequest; import org.restcomm.connect.commons.cache.DiskCacheResponse; import org.restcomm.connect.commons.cache.HashGenerator; import org.restcomm.connect.tts.api.GetSpeechSynthesizerInfo; import org.restcomm.connect.tts.api.SpeechSynthesizerInfo; import org.restcomm.connect.tts.api.SpeechSynthesizerRequest; import org.restcomm.connect.tts.api.SpeechSynthesizerResponse; import scala.concurrent.duration.FiniteDuration; import akka.actor.Actor; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.UntypedActor; import akka.actor.UntypedActorFactory; import akka.testkit.JavaTestKit; /** * @author [email protected] (Thomas Quintana) */ public final class AcapelaSpeechSynthesizerTest { private ActorSystem system; private ActorRef tts; private ActorRef cache; public AcapelaSpeechSynthesizerTest() { super(); } @Before public void before() throws Exception { system = ActorSystem.create(); final URL input = getClass().getResource("/acapela.xml"); final XMLConfiguration configuration = new XMLConfiguration(input); tts = tts(configuration); cache = cache("/tmp/cache", "http://127.0.0.1:8080/restcomm/cache"); } @After public void after() throws Exception { system.shutdown(); } private ActorRef tts(final Configuration configuration) { final String classpath = configuration.getString("[@class]"); return system.actorOf(new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public Actor create() throws Exception { return (UntypedActor) Class.forName(classpath).getConstructor(Configuration.class).newInstance(configuration); } })); } private ActorRef cache(final String path, final String uri) { return system.actorOf(new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new DiskCache(path, uri, true); } })); } @SuppressWarnings("unchecked") @Test public void testInfo() { new JavaTestKit(system) { { final ActorRef observer = getRef(); tts.tell(new GetSpeechSynthesizerInfo(), observer); final SpeechSynthesizerResponse<SpeechSynthesizerInfo> response = this.expectMsgClass( FiniteDuration.create(30, TimeUnit.SECONDS), SpeechSynthesizerResponse.class); assertTrue(response.succeeded()); final Set<String> languages = response.get().languages(); assertTrue(languages.contains("ca")); assertTrue(languages.contains("it")); assertTrue(languages.contains("tr")); assertTrue(languages.contains("no")); assertTrue(languages.contains("ar")); assertTrue(languages.contains("cs")); assertTrue(languages.contains("de")); assertTrue(languages.contains("bp")); assertTrue(languages.contains("el")); assertTrue(languages.contains("dan")); assertTrue(languages.contains("fi")); assertTrue(languages.contains("pt")); assertTrue(languages.contains("pl")); assertTrue(languages.contains("bf")); assertTrue(languages.contains("sv")); assertTrue(languages.contains("fr")); assertTrue(languages.contains("en")); assertTrue(languages.contains("ru")); assertTrue(languages.contains("es")); assertTrue(languages.contains("cf")); assertTrue(languages.contains("nl")); assertTrue(languages.contains("en-gb")); System.out.println(response.get().languages()); } }; } @SuppressWarnings("unchecked") @Test @Ignore //Acapela account is expired public void testSynthesis() { new JavaTestKit(system) { { final ActorRef observer = getRef(); String gender = "man"; String language = "en"; String message = "Hello TTS World!"; String hash = HashGenerator.hashMessage(gender, language, message); final SpeechSynthesizerRequest synthesize = new SpeechSynthesizerRequest(gender, language, message); tts.tell(synthesize, observer); final SpeechSynthesizerResponse<URI> response = this.expectMsgClass( FiniteDuration.create(30, TimeUnit.SECONDS), SpeechSynthesizerResponse.class); assertTrue(response.succeeded()); DiskCacheRequest diskCacheRequest = new DiskCacheRequest(response.get()); cache.tell(diskCacheRequest, observer); final DiskCacheResponse diskCacheResponse = this.expectMsgClass(FiniteDuration.create(30, TimeUnit.SECONDS), DiskCacheResponse.class); assertTrue(diskCacheResponse.succeeded()); assertEquals("hash=" + hash, response.get().getFragment()); assertEquals("http://127.0.0.1:8080/restcomm/cache/" + hash + ".wav", diskCacheResponse.get().toString()); } }; } @SuppressWarnings("unchecked") @Test @Ignore //Acapela account is expired public void testHash() { final String gender = "man"; final String language = "en"; final String text = "Hello There!"; final String calculatedHash = "hash=" + HashGenerator.hashMessage(gender, language, text); new JavaTestKit(system) { { final ActorRef observer = getRef(); final SpeechSynthesizerRequest synthesize = new SpeechSynthesizerRequest(gender, language, text); tts.tell(synthesize, observer); final SpeechSynthesizerResponse<URI> response = this.expectMsgClass( FiniteDuration.create(30, TimeUnit.SECONDS), SpeechSynthesizerResponse.class); assertTrue(response.succeeded()); assertTrue(response.get().getFragment().equals(calculatedHash)); System.out.println(response.get().toString()); } }; } }
7,893
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AcapelaSpeechSynthesizer.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.tts.acapela/src/main/java/org/restcomm/connect/tts/acapela/AcapelaSpeechSynthesizer.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.restcomm.connect.tts.acapela; import akka.actor.ActorRef; import akka.event.Logging; import akka.event.LoggingAdapter; import org.apache.commons.configuration.Configuration; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.restcomm.connect.commons.cache.HashGenerator; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.commons.util.HttpUtils; import org.restcomm.connect.tts.api.GetSpeechSynthesizerInfo; import org.restcomm.connect.tts.api.SpeechSynthesizerException; import org.restcomm.connect.tts.api.SpeechSynthesizerInfo; import org.restcomm.connect.tts.api.SpeechSynthesizerRequest; import org.restcomm.connect.tts.api.SpeechSynthesizerResponse; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author [email protected] (Thomas Quintana) */ public final class AcapelaSpeechSynthesizer extends RestcommUntypedActor { private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); private static final String client = "0-01"; private static final String environment = "RESTCOMM_1.6.0"; private static final String mime = "WAV"; private static final String version = "2"; private static final List<NameValuePair> parameters; static { parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("prot_vers", version)); parameters.add(new BasicNameValuePair("cl_env", environment)); parameters.add(new BasicNameValuePair("cl_vers", client)); parameters.add(new BasicNameValuePair("req_type", null)); parameters.add(new BasicNameValuePair("req_snd_id", null)); parameters.add(new BasicNameValuePair("req_vol", null)); parameters.add(new BasicNameValuePair("req_spd", null)); parameters.add(new BasicNameValuePair("req_vct", null)); parameters.add(new BasicNameValuePair("req_eq1", null)); parameters.add(new BasicNameValuePair("req_eq2", null)); parameters.add(new BasicNameValuePair("req_eq3", null)); parameters.add(new BasicNameValuePair("req_eq4", null)); parameters.add(new BasicNameValuePair("req_snd_type", mime)); parameters.add(new BasicNameValuePair("req_snd_ext", null)); parameters.add(new BasicNameValuePair("req_snd_kbps", null)); parameters.add(new BasicNameValuePair("req_alt_snd_type", null)); parameters.add(new BasicNameValuePair("req_alt_snd_ext", null)); parameters.add(new BasicNameValuePair("req_alt_snd_kbps", null)); parameters.add(new BasicNameValuePair("req_wp", null)); parameters.add(new BasicNameValuePair("req_bp", null)); parameters.add(new BasicNameValuePair("req_mp", null)); parameters.add(new BasicNameValuePair("req_comment", null)); parameters.add(new BasicNameValuePair("req_start_time", null)); parameters.add(new BasicNameValuePair("req_timeout", null)); parameters.add(new BasicNameValuePair("req_asw_type", null)); parameters.add(new BasicNameValuePair("req_asw_as_alt_snd", null)); parameters.add(new BasicNameValuePair("req_err_as_id3", null)); parameters.add(new BasicNameValuePair("req_echo", null)); parameters.add(new BasicNameValuePair("req_asw_redirect_url", null)); } private final URI service; private final Map<String, String> men; private final Map<String, String> women; public AcapelaSpeechSynthesizer(final Configuration configuration) { super(); // Add the credentials. final String application = configuration.getString("application"); final String login = configuration.getString("login"); final String password = configuration.getString("password"); parameters.add(new BasicNameValuePair("cl_app", application)); parameters.add(new BasicNameValuePair("cl_login", login)); parameters.add(new BasicNameValuePair("cl_pwd", password)); // Initialize the speech synthesizer state. service = URI.create(configuration.getString("service-root")); men = new HashMap<String, String>(); women = new HashMap<String, String>(); load(configuration); } private SpeechSynthesizerInfo info() { return new SpeechSynthesizerInfo(women.keySet()); } private void load(final Configuration configuration) throws RuntimeException { // Initialize female voices. women.put("bf", configuration.getString("speakers.belgium-french.female")); women.put("bp", configuration.getString("speakers.brazilian-portuguese.female")); women.put("en-gb", configuration.getString("speakers.british-english.female")); women.put("cf", configuration.getString("speakers.canadian-french.female")); women.put("cs", configuration.getString("speakers.czech.female")); women.put("dan", configuration.getString("speakers.danish.female")); women.put("en", configuration.getString("speakers.english.female")); women.put("fi", configuration.getString("speakers.finnish.female")); women.put("fr", configuration.getString("speakers.french.female")); women.put("de", configuration.getString("speakers.german.female")); women.put("el", configuration.getString("speakers.greek.female")); women.put("it", configuration.getString("speakers.italian.female")); women.put("nl", configuration.getString("speakers.netherlands-dutch.female")); women.put("no", configuration.getString("speakers.norwegian.female")); women.put("pl", configuration.getString("speakers.polish.female")); women.put("pt", configuration.getString("speakers.portuguese.female")); women.put("ru", configuration.getString("speakers.russian.female")); women.put("ar", configuration.getString("speakers.saudi-arabia-arabic.female")); women.put("ca", configuration.getString("speakers.spain-catalan.female")); women.put("es", configuration.getString("speakers.spanish.female")); women.put("sv", configuration.getString("speakers.swedish.female")); women.put("tr", configuration.getString("speakers.turkish.female")); women.put("zh-cn", configuration.getString("speakers.mandarin-chinese.female")); women.put("ja", configuration.getString("speakers.japanese.female")); // Initialize male voices. men.put("bf", configuration.getString("speakers.belgium-french.male")); men.put("bp", configuration.getString("speakers.brazilian-portuguese.male")); men.put("en-gb", configuration.getString("speakers.british-english.male")); men.put("cf", configuration.getString("speakers.canadian-french.male")); men.put("cs", configuration.getString("speakers.czech.male")); men.put("dan", configuration.getString("speakers.danish.male")); men.put("en", configuration.getString("speakers.english.male")); men.put("fi", configuration.getString("speakers.finnish.male")); men.put("fr", configuration.getString("speakers.french.male")); men.put("de", configuration.getString("speakers.german.male")); men.put("el", configuration.getString("speakers.greek.male")); men.put("it", configuration.getString("speakers.italian.male")); men.put("nl", configuration.getString("speakers.netherlands-dutch.male")); men.put("no", configuration.getString("speakers.norwegian.male")); men.put("pl", configuration.getString("speakers.polish.male")); men.put("pt", configuration.getString("speakers.portuguese.male")); men.put("ru", configuration.getString("speakers.russian.male")); men.put("ar", configuration.getString("speakers.saudi-arabia-arabic.male")); men.put("ca", configuration.getString("speakers.spain-catalan.male")); men.put("es", configuration.getString("speakers.spanish.male")); men.put("sv", configuration.getString("speakers.swedish.male")); men.put("tr", configuration.getString("speakers.turkish.male")); men.put("zh-cn", configuration.getString("speakers.mandarin-chinese.male")); men.put("ja", configuration.getString("speakers.japanese.male")); } @Override public void onReceive(final Object message) throws Exception { final Class<?> klass = message.getClass(); final ActorRef self = self(); final ActorRef sender = sender(); if (SpeechSynthesizerRequest.class.equals(klass)) { try { final URI uri = synthesize(message); if (sender != null) { sender.tell(new SpeechSynthesizerResponse<URI>(uri), self); } } catch (final Exception exception) { logger.error("There was an exception while trying to synthesize message: "+exception); if (sender != null) { sender.tell(new SpeechSynthesizerResponse<URI>(exception), self); } } } else if (GetSpeechSynthesizerInfo.class.equals(klass)) { sender.tell(new SpeechSynthesizerResponse<SpeechSynthesizerInfo>(info()), self); } } private String speaker(final String gender, final String language) { String speaker = null; if ("woman".equalsIgnoreCase(gender)) { speaker = women.get(language); if (speaker == null || speaker.isEmpty()) { speaker = men.get(language); } } else if ("man".equalsIgnoreCase(gender)) { speaker = men.get(language); if (speaker == null || speaker.isEmpty()) { speaker = women.get(language); } } else { return null; } return speaker; } private URI synthesize(final Object message) throws IOException, SpeechSynthesizerException { final SpeechSynthesizerRequest request = (SpeechSynthesizerRequest) message; final String gender = request.gender(); final String language = request.language(); final String text = request.text(); final String speaker = speaker(gender, language); if (speaker == null) { if(logger.isInfoEnabled()){ logger.info("There is no suitable speaker to synthesize " + request.language()); } throw new IllegalArgumentException("There is no suitable speaker to synthesize " + request.language()); } final List<NameValuePair> query = new ArrayList<NameValuePair>(); query.addAll(parameters); query.add(new BasicNameValuePair("req_voice", speaker)); query.add(new BasicNameValuePair("req_text", text)); final HttpPost post = new HttpPost(service); final UrlEncodedFormEntity entity = new UrlEncodedFormEntity(query, "UTF-8"); post.setEntity(entity); final HttpClient client = new DefaultHttpClient(); final HttpResponse response = client.execute(post); final StatusLine line = response.getStatusLine(); final int status = line.getStatusCode(); if (status == HttpStatus.SC_OK) { final Map<String, String> results = HttpUtils.toMap(response.getEntity()); if ("OK".equals(results.get("res"))) { if(logger.isInfoEnabled()){ logger.info("AcapelaSpeechSynthesizer success!"); } String ret = results.get("snd_url") + "#hash=" + HashGenerator.hashMessage(gender, language, text); return URI.create(ret); } else { if(logger.isInfoEnabled()){ logger.info("AcapelaSpeechSynthesizer error code: " + results.get("err_code") + " error message: " + results.get("err_msg")); } final StringBuilder buffer = new StringBuilder(); buffer.append(results.get("err_code")).append(" ").append(results.get("err_msg")); throw new SpeechSynthesizerException(buffer.toString()); } } else { if(logger.isInfoEnabled()){ logger.info("AcapelaSpeechSynthesizer error, status code: " + line.getStatusCode() + (" reason phrase: ") + line.getReasonPhrase()); } final StringBuilder buffer = new StringBuilder(); buffer.append(line.getStatusCode()).append(" ").append(line.getReasonPhrase()); throw new SpeechSynthesizerException(buffer.toString()); } } }
13,875
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ISpeechAsrTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.asr/src/test/java/org/restcomm/connect/asr/ISpeechAsrTest.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.restcomm.connect.asr; import akka.actor.Actor; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.UntypedActorFactory; import akka.testkit.JavaTestKit; import java.io.File; import java.net.URL; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.XMLConfiguration; import org.junit.After; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import scala.concurrent.duration.FiniteDuration; /** * @author [email protected] (Thomas Quintana) */ public final class ISpeechAsrTest { private ActorSystem system; private ActorRef asr; public ISpeechAsrTest() { super(); } @Before public void before() throws Exception { system = ActorSystem.create(); final URL input = getClass().getResource("/ispeech.xml"); final XMLConfiguration configuration = new XMLConfiguration(input); asr = asr(configuration); } @After public void after() throws Exception { system.shutdown(); } private ActorRef asr(final Configuration configuration) { return system.actorOf(new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public Actor create() throws Exception { return new ISpeechAsr(configuration); } })); } @SuppressWarnings("unchecked") @Test public void testInfo() { new JavaTestKit(system) { { final ActorRef observer = getRef(); asr.tell(new GetAsrInfo(), observer); final AsrResponse<AsrInfo> response = expectMsgClass(FiniteDuration.create(30, TimeUnit.SECONDS), AsrResponse.class); assertTrue(response.succeeded()); final Set<String> languages = response.get().languages(); assertTrue(languages.contains("en")); assertTrue(languages.contains("en-gb")); assertTrue(languages.contains("es")); assertTrue(languages.contains("it")); assertTrue(languages.contains("fr")); assertTrue(languages.contains("pl")); assertTrue(languages.contains("pt")); } }; } @SuppressWarnings("unchecked") @Test @Ignore //To pass the test the ISpeech account have to be active public void testRecognition() { new JavaTestKit(system) { { final ActorRef observer = getRef(); final File file = new File(getClass().getResource("/hello-world.wav").getPath()); final AsrRequest request = new AsrRequest(file, "en"); asr.tell(request, observer); final AsrResponse<String> response = this.expectMsgClass(FiniteDuration.create(30, TimeUnit.SECONDS), AsrResponse.class); assertTrue(response.succeeded()); assertTrue(response.get().equals("hello world")); } }; } }
4,055
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AsrRequest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.asr/src/main/java/org/restcomm/connect/asr/AsrRequest.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.restcomm.connect.asr; import java.io.File; import java.util.Map; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class AsrRequest { private final File file; private final String language; private final Map<String, Object> attributes; public AsrRequest(final File file, final String language, final Map<String, Object> attributes) { super(); this.file = file; this.language = language; this.attributes = attributes; } public AsrRequest(final File file, final String language) { this(file, language, null); } public Map<String, Object> attributes() { return attributes; } public File file() { return file; } public String language() { return language; } }
1,711
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ISpeechAsr.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.asr/src/main/java/org/restcomm/connect/asr/ISpeechAsr.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.restcomm.connect.asr; import akka.actor.ActorRef; import com.iSpeech.SpeechResult; import com.iSpeech.iSpeechRecognizer; import com.iSpeech.iSpeechRecognizer.SpeechRecognizerEvent; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import java.io.File; import java.util.HashMap; import java.util.Map; import static com.iSpeech.iSpeechRecognizer.FREEFORM_DICTATION; /** * @author [email protected] (Thomas Quintana) */ public final class ISpeechAsr extends RestcommUntypedActor implements SpeechRecognizerEvent { private static final Map<String, String> languages = new HashMap<String, String>(); static { languages.put("en", "en-US"); languages.put("en-gb", "en-GB"); languages.put("es", "es-ES"); languages.put("it", "it-IT"); languages.put("fr", "fr-FR"); languages.put("pl", "pl-PL"); languages.put("pt", "pt-PT"); } private final String key; private final boolean production; public ISpeechAsr(final Configuration configuration) { super(); key = configuration.getString("api-key"); production = configuration.getBoolean("api-key[@production]"); } private AsrInfo info() { return new AsrInfo(languages.keySet()); } @Override public void onReceive(final Object message) throws Exception { final Class<?> klass = message.getClass(); final ActorRef self = self(); final ActorRef sender = sender(); if (AsrRequest.class.equals(klass)) { final AsrRequest request = (AsrRequest) message; final Map<String, Object> attributes = request.attributes(); try { if (attributes != null) { sender.tell(new AsrResponse<String>(recognize(message), attributes), self); } else { sender.tell(new AsrResponse<String>(recognize(message)), self); } } catch (final Exception exception) { if (attributes != null) { sender.tell(new AsrResponse<String>(exception, attributes), self); } else { sender.tell(new AsrResponse<String>(exception), self); } } } else if (GetAsrInfo.class.equals(klass)) { sender.tell(new AsrResponse<AsrInfo>(info()), self); } } private String recognize(final Object message) throws Exception { final AsrRequest request = (AsrRequest) message; final File file = request.file(); final String language = languages.get(request.language()); final iSpeechRecognizer recognizer = iSpeechRecognizer.getInstance(key, production); recognizer.setFreeForm(FREEFORM_DICTATION); recognizer.setLanguage(language); final SpeechResult results = recognizer.startFileRecognize("audio/x-wav", file, this); return results.Text; } @Override public void stateChanged(final int event, final int value, final Exception exception) { if (SpeechRecognizerEvent.RECORDING_ERROR == event) { // We don't use the recorder. } } }
4,063
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AsrInfo.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.asr/src/main/java/org/restcomm/connect/asr/AsrInfo.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.restcomm.connect.asr; import java.util.Set; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class AsrInfo { private final Set<String> languages; public AsrInfo(final Set<String> languages) { super(); this.languages = languages; } public Set<String> languages() { return languages; } }
1,267
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AsrResponse.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.asr/src/main/java/org/restcomm/connect/asr/AsrResponse.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.restcomm.connect.asr; import java.util.Map; import org.restcomm.connect.commons.annotations.concurrency.Immutable; import org.restcomm.connect.commons.patterns.StandardResponse; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class AsrResponse<T> extends StandardResponse<T> { private final Map<String, Object> attributes; public AsrResponse(final T object, final Map<String, Object> attributes) { super(object); this.attributes = attributes; } public AsrResponse(T object) { this(object, null); } public AsrResponse(final Throwable cause, final Map<String, Object> attributes) { super(cause); this.attributes = attributes; } public AsrResponse(final Throwable cause) { this(cause, null); } public AsrResponse(final Throwable cause, final String message, final Map<String, Object> attributes) { super(cause, message); this.attributes = attributes; } public Map<String, Object> attributes() { return attributes; } }
1,910
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
GetAsrInfo.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.asr/src/main/java/org/restcomm/connect/asr/GetAsrInfo.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.restcomm.connect.asr; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class GetAsrInfo { public GetAsrInfo() { super(); } }
1,075
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CheckSubscriberCodeServlet.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.rvd.sampleservices/src/main/java/telestax/rvd/sampleservices/CheckSubscriberCodeServlet.java
package telestax.rvd.sampleservices; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class CheckSubscriberCodeServlet extends HttpServlet { private static final long serialVersionUID = 1L; public CheckSubscriberCodeServlet() { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); /* * This is a simple routing external service. A servlet that given some parameters decides what should be the * next RVD module. */ Gson gson = new GsonBuilder().create(); // If customer code is 123 accept him otherwise goodbye if ( "123".equals(request.getParameter("code")) ) response.getWriter().print( gson.toJson("SubscribersRoom")); else response.getWriter().print( gson.toJson("Goodbye")); } }
1,121
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
EchoServlet.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.rvd.sampleservices/src/main/java/telestax/rvd/sampleservices/EchoServlet.java
package telestax.rvd.sampleservices; import java.io.IOException; import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class EchoServlet extends HttpServlet { private static final long serialVersionUID = 1L; public EchoServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); Gson gson = new GsonBuilder().create(); /* * This is simple echo servlet to be used for testing. All parameters passed to it on the URL are returned as a * JSON object. */ JsonObject params = new JsonObject(); Enumeration<String> e = request.getParameterNames(); while ( e.hasMoreElements() ) { String name = (String) e.nextElement(); params.addProperty( name, request.getParameter(name)); } response.getWriter().print( gson.toJson( params ) ); } }
1,302
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
GetUserDetailsServlet.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.rvd.sampleservices/src/main/java/telestax/rvd/sampleservices/GetUserDetailsServlet.java
package telestax.rvd.sampleservices; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GetUserDetailsServlet extends HttpServlet { private static final long serialVersionUID = 1L; // If the user is found return this public static class UserExistsResponse { // business data String firstname; String lastname; // flow data String nextModule; public UserExistsResponse(String firstname, String lastname, String nextModule) { super(); this.firstname = firstname; this.lastname = lastname; this.nextModule = nextModule; } } // If the user was not found return this public static class UserNotFoundResponse { // flow data only String nextModule; public UserNotFoundResponse(String nextModule) { super(); this.nextModule = nextModule; } } // In an application exception (or any other exception could be the case) was thrown public static class ApplicationExceptionResponse { String error; String nextModule; public ApplicationExceptionResponse(String error, String nextModule) { super(); this.error = error; this.nextModule = nextModule; } } public GetUserDetailsServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); /* Return customer details for the customerId specified. In this example, a static mapping is used but a query to * a database could do as well. */ // Since we use JSON to format our response, Gson comes in handy Gson gson = new GsonBuilder().create(); // Get service input parameters //String customerId = request.getParameter("customerId"); String jsonResponse; try { Integer customerId = Integer.parseInt(request.getParameter("customerId")); if ( customerId == 1 ) { UserExistsResponse existsResponse = new UserExistsResponse("Mickey", "Mouse", "Members"); jsonResponse = gson.toJson(existsResponse); } else if ( customerId == 2 ) { UserExistsResponse existsResponse = new UserExistsResponse("Donald","Duck","Members"); jsonResponse = gson.toJson(existsResponse); } else { // No 'firstname', 'lastname' variables if the user is not a registered customer UserNotFoundResponse notFoundResponse = new UserNotFoundResponse("Guests"); jsonResponse = gson.toJson(notFoundResponse); } } catch (NumberFormatException e) { if ( "".equals(request.getParameter("customerId")) ) { UserNotFoundResponse notFoundResponse = new UserNotFoundResponse("Guests"); jsonResponse = gson.toJson(notFoundResponse); } else { ApplicationExceptionResponse exceptionResponse = new ApplicationExceptionResponse(e.getClass().getSimpleName(), "Error"); jsonResponse = gson.toJson(exceptionResponse); } } response.getWriter().print( jsonResponse ); } }
3,636
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
EndpointMockedTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/test/java/org/restcomm/connect/http/EndpointMockedTest.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.restcomm.connect.http; import java.net.URISyntaxException; import java.util.HashSet; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import org.restcomm.connect.dao.AccountsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.entities.Account; import org.mockito.Mockito; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.Set; import static org.apache.shiro.web.filter.mgt.DefaultFilter.roles; import static org.mockito.Mockito.when; import org.restcomm.connect.dao.ClientsDao; import org.restcomm.connect.dao.OrganizationsDao; import static org.restcomm.connect.http.security.AccountPrincipal.ADMIN_ROLE; import org.restcomm.connect.http.security.PermissionEvaluator; import org.restcomm.connect.identity.IdentityContext; import org.restcomm.connect.identity.UserIdentityContext; /** * Base class for unit testing restcomm endpoints by mocking the following dependent components: * * - Configuration * - DaoManager and individual daos * - ServletContext * - HttpServletRequest * * Extend this class and further customize it to test other endpoints. See sample AccountsEndpointMockedTest * to get an idea how this works. * * @author [email protected] - Orestis Tsakiridis */ public class EndpointMockedTest { Configuration conf; ServletContext servletContext; List<Account> accounts; AccountsDao accountsDao; DaoManager daoManager; HttpServletRequest request; OrganizationsDao orgDao; ClientsDao clientsDao; UserIdentityContext userIdentityContext; void init() throws URISyntaxException { String restcommXmlPath = AccountsEndpointMockedTest.class.getResource("/restcomm.xml").getFile(); try { conf = getConfiguration(restcommXmlPath, "/restcomm", "http://localhost:8080"); } catch (ConfigurationException e) { throw new RuntimeException(); } // create ServletContext mock servletContext = Mockito.mock(ServletContext.class); daoManager = Mockito.mock(DaoManager.class); accountsDao = Mockito.mock(AccountsDao.class); orgDao= Mockito.mock(OrganizationsDao.class); clientsDao= Mockito.mock(ClientsDao.class); userIdentityContext = Mockito.mock(UserIdentityContext.class); Set<String> roles = new HashSet(); roles.add(ADMIN_ROLE); when (userIdentityContext.getEffectiveAccountRoles()).thenReturn(roles); when(servletContext.getAttribute(Configuration.class.getName())).thenReturn(conf); when(daoManager.getAccountsDao()).thenReturn(accountsDao); when(daoManager.getOrganizationsDao()).thenReturn(orgDao); when(daoManager.getClientsDao()).thenReturn(clientsDao); when(servletContext.getAttribute(DaoManager.class.getName())).thenReturn(daoManager); when(servletContext.getAttribute(IdentityContext.class.getName())).thenReturn(new IdentityContext(conf)); // createt request mock request = Mockito.mock(HttpServletRequest.class); when(request.getHeader("Authorization")).thenReturn("Basic YWRtaW5pc3RyYXRvckBjb21wYW55LmNvbTo3N2Y4YzEyY2M3YjhmODQyM2U1YzM4YjAzNTI0OTE2Ng=="); } private Configuration getConfiguration(String path, String homeDirectory, String rootUri) throws ConfigurationException { Configuration xml = null; XMLConfiguration xmlConfiguration = new XMLConfiguration(); xmlConfiguration.setDelimiterParsingDisabled(true); xmlConfiguration.setAttributeSplittingDisabled(true); xmlConfiguration.load(path); xml = xmlConfiguration; xml.setProperty("runtime-settings.home-directory", homeDirectory); xml.setProperty("runtime-settings.root-uri", rootUri); return xml; } }
4,803
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AccountsEndpointMockedTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/test/java/org/restcomm/connect/http/AccountsEndpointMockedTest.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.restcomm.connect.http; import com.sun.jersey.core.util.MultivaluedMapImpl; import java.net.URI; import java.net.URISyntaxException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.commons.configuration.ConfigurationException; import org.joda.time.DateTime; import static org.junit.Assert.assertEquals; import org.junit.Test; import static org.mockito.Mockito.when; import static org.mockito.Mockito.*; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.Organization; /** * A sample unit test for accounts endpoint. It illustrates the use of the EndpointMockedTest. * * @author [email protected] - Orestis Tsakiridis */ public class AccountsEndpointMockedTest extends EndpointMockedTest { @Test public void endpointInitializedAndBasicAuthorizationWork() throws ConfigurationException, URISyntaxException { init(); // setup default mocking values AccountsEndpoint endpoint = new AccountsEndpoint(servletContext); endpoint.init(); } @Test public void statusUpdate() throws ConfigurationException, URISyntaxException { init(); // setup default mocking values Account account = new Account(new Sid("AC00000000000000000000000000000000"),new DateTime(),new DateTime(),"[email protected]","Administrator",new Sid("AC00000000000000000000000000000001"),Account.Type.TRIAL,Account.Status.ACTIVE,"77f8c12cc7b8f8423e5c38b035249166","Administrator",new URI("/uri"), Sid.generate(Sid.Type.ORGANIZATION)); Organization organization = new Organization(account.getOrganizationSid(), "domainName", null, null, Organization.Status.ACTIVE); when(accountsDao.getAccount(any(Sid.class))).thenReturn(account); when(accountsDao.getAccount(any(String.class))).thenReturn(account); when(accountsDao.getAccountToAuthenticate(any(String.class))).thenReturn(account); when(orgDao.getOrganization(any(Sid.class))).thenReturn(organization); when (userIdentityContext.getEffectiveAccount()).thenReturn(account); AccountsEndpoint endpoint = new AccountsEndpoint(servletContext); endpoint.init(); MultivaluedMapImpl multivaluedMapImpl = new MultivaluedMapImpl(); multivaluedMapImpl.putSingle("Status", "active"); Response updateAccount = endpoint.updateAccount(account.getSid().toString(), multivaluedMapImpl, MediaType.APPLICATION_JSON_TYPE, userIdentityContext); assertEquals(200, updateAccount.getStatus()); } }
3,452
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ProfileSchemaTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/test/java/org/restcomm/connect/http/schemas/ProfileSchemaTest.java
package org.restcomm.connect.http.schemas; import org.junit.Test; /* * 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/> * */ import com.fasterxml.jackson.core.JsonPointer; import com.fasterxml.jackson.databind.JsonNode; import com.github.fge.jackson.JsonLoader; import com.github.fge.jsonschema.core.report.ProcessingReport; import com.github.fge.jsonschema.main.JsonSchema; import com.github.fge.jsonschema.main.JsonSchemaFactory; import junit.framework.Assert; import java.io.File; import static org.junit.Assert.assertTrue; /** * * @author */ public class ProfileSchemaTest { public ProfileSchemaTest() { } @Test public void testFreePlan() throws Exception { final JsonNode fstabSchema = JsonLoader.fromResource("/org/restcomm/connect/http/schemas/rc-profile-schema.json"); final JsonNode good = JsonLoader.fromResource("/org/restcomm/connect/http/schemas/freePlan.json"); final JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); final JsonSchema schema = factory.getJsonSchema(fstabSchema); ProcessingReport report; report = schema.validate(good); Assert.assertTrue(report.isSuccess()); } @Test public void testEmptyProfile() throws Exception { final JsonNode fstabSchema = JsonLoader.fromResource("/org/restcomm/connect/http/schemas/rc-profile-schema.json"); final JsonNode good = JsonLoader.fromResource("/org/restcomm/connect/http/schemas/emptyProfile.json"); final JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); final JsonSchema schema = factory.getJsonSchema(fstabSchema); ProcessingReport report; report = schema.validate(good); Assert.assertTrue(report.isSuccess()); } @Test public void testRetrieveAllowedPrefixes() throws Exception { final JsonNode good = JsonLoader.fromResource("/org/restcomm/connect/http/schemas/freePlan.json"); JsonPointer pointer = JsonPointer.compile("/featureEnablement/outboundPSTN/allowedPrefixes"); JsonNode at = good.at(pointer); Assert.assertNotNull(at); Assert.assertTrue(at.isArray()); Assert.assertEquals("+1", at.get(0).asText()); } @Test public void testInvalidFeature() throws Exception { final JsonNode fstabSchema = JsonLoader.fromResource("/org/restcomm/connect/http/schemas/rc-profile-schema.json"); final JsonNode good = JsonLoader.fromResource("/org/restcomm/connect/http/schemas/invalidFeature.json"); final JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); final JsonSchema schema = factory.getJsonSchema(fstabSchema); ProcessingReport report; report = schema.validate(good); Assert.assertFalse(report.isSuccess()); } @Test public void testDefaultPlan() throws Exception { final JsonNode fstabSchema = JsonLoader.fromResource("/org/restcomm/connect/http/schemas/rc-profile-schema.json"); File defaultPlan = new File("../restcomm.application/src/main/webapp/WEB-INF/conf/defaultPlan.json"); final JsonNode good = JsonLoader.fromFile(defaultPlan); final JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); final JsonSchema schema = factory.getJsonSchema(fstabSchema); ProcessingReport report; report = schema.validate(good); assertTrue(report.isSuccess()); } }
4,184
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ApplicationConverterTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/test/java/org/restcomm/connect/http/converter/ApplicationConverterTest.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.restcomm.connect.http.converter; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.thoughtworks.xstream.XStream; import junit.framework.Assert; import org.joda.time.DateTime; import org.junit.Test; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.entities.Application; import org.restcomm.connect.dao.entities.ApplicationNumberSummary; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; /** * @author [email protected] - Orestis Tsakiridis */ public class ApplicationConverterTest { @Test public void testNestedNumbersProperty() throws URISyntaxException { // Initialize Json and XML converters final ApplicationConverter applicationConverter = new ApplicationConverter(null); final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Application.class, applicationConverter); // convert camelCaseFieldNames to camel_case_field_names convention. This will only affect ApplicationNumberSummary builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); builder.setPrettyPrinting(); Gson gson = builder.create(); ApplicationNumberSummaryConverter numberConverter = new ApplicationNumberSummaryConverter(); XStream xstream = new XStream(); //xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(applicationConverter); xstream.registerConverter(numberConverter); xstream.registerConverter(new ApplicationListConverter(null)); xstream.alias("Number",ApplicationNumberSummary.class); //xstream.alias("Numbers", ); //xstream.registerConverter(new RestCommResponseConverter(configuration)); Application app = new Application( new Sid("AP73926e7113fa4d95981aa96b76eca854"), new DateTime(), new DateTime(), "test app", new Sid("ACae6e420f425248d6a26948c17a9e2acf"), "2012-04-24", false, new URI("/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Applications/AP73926e7113fa4d95981aa96b76eca854"),new URI("/visual-designer/services/apps/AP73926e7113fa4d95981aa96b76eca854/controller"), Application.Kind.VOICE); List<ApplicationNumberSummary> numbers = new ArrayList<ApplicationNumberSummary>(); ApplicationNumberSummary numberSummary = new ApplicationNumberSummary( "PN00000000000000000000000000000001", "1234", "+1234", "AP73926e7113fa4d95981aa96b76eca854", null,null,null ); numbers.add(numberSummary); numberSummary = new ApplicationNumberSummary( "PN00000000000000000000000000000002", "1234", "+1234", "AP73926e7113fa4d95981aa96b76eca854", null,null,null ); numbers.add(numberSummary); app.setNumbers(numbers); List<Application> apps = new ArrayList<Application>(); apps.add(app); // test json results String responseJson = gson.toJson(apps); Assert.assertTrue(responseJson.contains("\"numbers\": [")); Assert.assertTrue(responseJson.contains("\"phone_number\": \"+1234\"")); // test xml results String responseXML = xstream.toXML(app); responseXML = responseXML.replaceAll("[ \n]",""); Assert.assertTrue(responseXML.contains("<Numbers><Number>")); Assert.assertTrue(responseXML.contains("<PhoneNumber>+1234</PhoneNumber>")); } }
4,411
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ExtensionsConfigurationEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/ExtensionsConfigurationEndpoint.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2016, 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.restcomm.connect.http; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import javax.annotation.PostConstruct; import javax.annotation.security.RolesAllowed; import javax.servlet.ServletContext; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.MediaType.APPLICATION_XML_TYPE; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.Status.NOT_ACCEPTABLE; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.ok; import static javax.ws.rs.core.Response.status; import org.apache.commons.configuration.Configuration; import org.joda.time.DateTime; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.ExtensionsConfigurationDao; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.extension.api.ConfigurationException; import org.restcomm.connect.extension.api.ExtensionConfiguration; import org.restcomm.connect.http.converter.ExtensionConfigurationConverter; import org.restcomm.connect.http.converter.RestCommResponseConverter; import static org.restcomm.connect.http.security.AccountPrincipal.SUPER_ADMIN_ROLE; /** * Created by gvagenas on 12/10/2016. */ @Path("/ExtensionsConfiguration") @RolesAllowed(SUPER_ADMIN_ROLE) @Singleton public class ExtensionsConfigurationEndpoint extends AbstractEndpoint { private Configuration allConfiguration; private Configuration configuration; private Gson gson; private XStream xstream; private ExtensionsConfigurationDao extensionsConfigurationDao; @Context private ServletContext context; public ExtensionsConfigurationEndpoint() { super(); } @PostConstruct void init() { allConfiguration = (Configuration) context.getAttribute(Configuration.class.getName()); configuration = allConfiguration.subset("runtime-settings"); super.init(configuration); extensionsConfigurationDao = ((DaoManager) context.getAttribute(DaoManager.class.getName())).getExtensionsConfigurationDao(); final ExtensionConfigurationConverter converter = new ExtensionConfigurationConverter(configuration); final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(ExtensionConfiguration.class, converter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(new ExtensionConfigurationConverter(configuration)); xstream.registerConverter(new RestCommResponseConverter(configuration)); } /** * Will be used to get configuration for extension * @param extensionId * @param responseType * @return */ protected Response getConfiguration(final String extensionId, final Sid accountSid, final MediaType responseType) { //Parameter "extensionId" could be the extension Sid or extension name. ExtensionConfiguration extensionConfiguration = null; ExtensionConfiguration extensionAccountConfiguration = null; Sid extensionSid = null; String extensionName = null; if(Sid.pattern.matcher(extensionId).matches()){ extensionSid = new Sid(extensionId); } else { extensionName = extensionId; } if (Sid.pattern.matcher(extensionId).matches()) { try { extensionConfiguration = extensionsConfigurationDao.getConfigurationBySid(extensionSid); } catch (Exception e) { return status(NOT_FOUND).build(); } } else { try { extensionConfiguration = extensionsConfigurationDao.getConfigurationByName(extensionName); } catch (Exception e) { return status(NOT_FOUND).build(); } } if (accountSid!=null) { if(extensionSid == null ){ extensionSid = extensionConfiguration.getSid(); } try { extensionAccountConfiguration = extensionsConfigurationDao.getAccountExtensionConfiguration(accountSid.toString(), extensionSid.toString()); extensionConfiguration.setConfigurationData(extensionAccountConfiguration.getConfigurationData(), extensionAccountConfiguration.getConfigurationType()); } catch (Exception e) { return status(NOT_FOUND).build(); } } if (extensionConfiguration == null) { return status(NOT_FOUND).build(); } else { if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(extensionConfiguration); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(extensionConfiguration), APPLICATION_JSON).build(); } else { return null; } } } private void validate(final MultivaluedMap<String, String> data) throws NullPointerException { if (!data.containsKey("ExtensionName")) { throw new NullPointerException("Extension name can not be null."); } else if (!data.containsKey("ConfigurationData")) { throw new NullPointerException("ConfigurationData can not be null."); } } private ExtensionConfiguration createFrom(final MultivaluedMap<String, String> data, final MediaType responseType) { validate(data); Sid sid = Sid.generate(Sid.Type.EXTENSION_CONFIGURATION); String extension = data.getFirst("ExtensionName"); boolean enabled = Boolean.parseBoolean(data.getFirst("Enabled")); Object configurationData = data.getFirst("ConfigurationData"); ExtensionConfiguration.configurationType configurationType = null; if (responseType.equals(APPLICATION_JSON_TYPE)) { configurationType = ExtensionConfiguration.configurationType.JSON; } else if (responseType.equals(APPLICATION_XML_TYPE)) { configurationType = ExtensionConfiguration.configurationType.XML; } DateTime dateCreated = DateTime.now(); DateTime dateUpdated = DateTime.now(); ExtensionConfiguration extensionConfiguration = new ExtensionConfiguration(sid, extension, enabled, configurationData, configurationType, dateCreated, dateUpdated); return extensionConfiguration; } protected Response postConfiguration(final MultivaluedMap<String, String> data, final MediaType responseType) { Sid accountSid = null; String accountSidQuery = data.getFirst("AccountSid"); if(accountSidQuery != null && !accountSidQuery.isEmpty()){ accountSid = new Sid(accountSidQuery); } //if extension doesnt exist, add new extension String extensionName = data.getFirst("ExtensionName"); ExtensionConfiguration extensionConfiguration = extensionsConfigurationDao.getConfigurationByName(extensionName); if(extensionConfiguration==null){ try { extensionConfiguration = createFrom(data, responseType); } catch (final NullPointerException exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } try { extensionsConfigurationDao.addConfiguration(extensionConfiguration); } catch (ConfigurationException exception) { return status(NOT_ACCEPTABLE).entity(exception.getMessage()).build(); } } if (accountSid!=null) { try { Object configurationData = data.getFirst("ConfigurationData"); // if accountSid exists, then this configuration is account specific, if it doesnt then its global config extensionConfiguration.setConfigurationData(configurationData, extensionConfiguration.getConfigurationType()); extensionsConfigurationDao.addAccountExtensionConfiguration(extensionConfiguration, accountSid); } catch (ConfigurationException exception) { return status(NOT_ACCEPTABLE).entity(exception.getMessage()).build(); } } if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(extensionConfiguration), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(extensionConfiguration); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } protected Response updateConfiguration(String extensionSid, MultivaluedMap<String, String> data, MediaType responseType) { if (!Sid.pattern.matcher(extensionSid).matches()) { return status(BAD_REQUEST).build(); } ExtensionConfiguration extensionConfiguration = extensionsConfigurationDao.getConfigurationBySid(new Sid(extensionSid)); if (extensionConfiguration == null) { return status(NOT_FOUND).build(); } ExtensionConfiguration updatedExtensionConfiguration = null; Sid accountSid = null; String accountSidQuery = data.getFirst("AccountSid"); if(accountSidQuery != null && !accountSidQuery.isEmpty()){ accountSid = new Sid(accountSidQuery); } try { updatedExtensionConfiguration = prepareUpdatedConfiguration(extensionConfiguration, data, responseType); } catch (final NullPointerException exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } try { if (accountSid==null) { extensionsConfigurationDao.updateConfiguration(updatedExtensionConfiguration); } else { extensionsConfigurationDao.updateAccountExtensionConfiguration(updatedExtensionConfiguration, accountSid); } } catch (ConfigurationException exception) { return status(NOT_ACCEPTABLE).entity(exception.getMessage()).build(); } if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(updatedExtensionConfiguration), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(updatedExtensionConfiguration); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } private ExtensionConfiguration prepareUpdatedConfiguration(ExtensionConfiguration existingExtensionConfiguration, MultivaluedMap<String, String> data, MediaType responseType) { validate(data); Sid existingExtensionSid = existingExtensionConfiguration.getSid(); String existingExtensionName = existingExtensionConfiguration.getExtensionName(); boolean enabled = existingExtensionConfiguration.isEnabled(); if (data.getFirst("Enabled") != null) { enabled = Boolean.parseBoolean(data.getFirst("Enabled")); } Object configurationData = data.getFirst("ConfigurationData"); DateTime dateCreated = existingExtensionConfiguration.getDateCreated(); ExtensionConfiguration.configurationType configurationType = null; if (responseType.equals(APPLICATION_JSON_TYPE)) { configurationType = ExtensionConfiguration.configurationType.JSON; } else if (responseType.equals(APPLICATION_XML_TYPE)) { configurationType = ExtensionConfiguration.configurationType.XML; } return new ExtensionConfiguration(existingExtensionSid, existingExtensionName, enabled, configurationData, configurationType, dateCreated ,DateTime.now()); } @Path("/{extensionId}") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getConfigurationAsXml(@PathParam("extensionId") final String extension, @QueryParam("AccountSid") Sid accountSid, @HeaderParam("Accept") String accept) { return getConfiguration(extension, accountSid, retrieveMediaType(accept)); } @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response postConfigurationAsXml(final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept) { return postConfiguration(data, retrieveMediaType(accept)); } @Path("/{extensionSid}") @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response updateConfigurationAsXml(@PathParam("extensionSid") final String extensionSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept) { return updateConfiguration(extensionSid, data, retrieveMediaType(accept)); } }
14,680
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
UssdPushEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/UssdPushEndpoint.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.restcomm.connect.http; import akka.actor.ActorRef; import static akka.pattern.Patterns.ask; import akka.util.Timeout; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import java.net.URI; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.MediaType.APPLICATION_XML_TYPE; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR; import static javax.ws.rs.core.Response.ok; import static javax.ws.rs.core.Response.status; import javax.ws.rs.core.SecurityContext; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.commons.telephony.CreateCallType; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.entities.CallDetailRecord; import org.restcomm.connect.dao.entities.CallDetailRecordList; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.http.converter.CallDetailRecordConverter; import org.restcomm.connect.http.converter.CallDetailRecordListConverter; import org.restcomm.connect.http.converter.RestCommResponseConverter; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.identity.UserIdentityContext; import org.restcomm.connect.telephony.api.CallInfo; import org.restcomm.connect.telephony.api.CallManagerResponse; import org.restcomm.connect.telephony.api.CallResponse; import org.restcomm.connect.telephony.api.CreateCall; import org.restcomm.connect.telephony.api.ExecuteCallScript; import org.restcomm.connect.telephony.api.GetCallInfo; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; /** * @author <a href="mailto:[email protected]">gvagenas</a> * */ @Path("/Accounts/{accountSid}/UssdPush") @Singleton public class UssdPushEndpoint extends AbstractEndpoint { @Context protected ServletContext context; protected Configuration configuration; private ActorRef ussdCallManager; private DaoManager daos; private Gson gson; private GsonBuilder builder; private XStream xstream; private CallDetailRecordListConverter listConverter; public UssdPushEndpoint() { super(); } @PostConstruct public void init() { configuration = (Configuration) context.getAttribute(Configuration.class.getName()); configuration = configuration.subset("runtime-settings"); ussdCallManager = (ActorRef) context.getAttribute("org.restcomm.connect.ussd.telephony.UssdCallManager"); daos = (DaoManager) context.getAttribute(DaoManager.class.getName()); super.init(configuration); CallDetailRecordConverter converter = new CallDetailRecordConverter(configuration); listConverter = new CallDetailRecordListConverter(configuration); builder = new GsonBuilder(); builder.registerTypeAdapter(CallDetailRecord.class, converter); builder.registerTypeAdapter(CallDetailRecordList.class, listConverter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(new RestCommResponseConverter(configuration)); xstream.registerConverter(listConverter); } @SuppressWarnings("unchecked") protected Response putCall(final String accountSid, final MultivaluedMap<String, String> data, final MediaType responseType, UserIdentityContext userIdentityContext) { final Sid accountId = new Sid(accountSid); permissionEvaluator.secure(daos.getAccountsDao().getAccount(accountSid), "RestComm:Create:Calls", userIdentityContext); try { validate(data); } catch (final RuntimeException exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } final String from = data.getFirst("From"); final String to = data.getFirst("To"); final String username = data.getFirst("Username"); final String password = data.getFirst("Password"); Integer timeout = getTimeout(data); timeout = timeout != null ? timeout : 30; final Timeout expires = new Timeout(Duration.create(60, TimeUnit.SECONDS)); CreateCall create = null; //Currently we don't support StatusCallback for USSD Push requests try { create = new CreateCall(from, to, username, password, true, timeout, CreateCallType.USSD, accountId, null, null, null, null, null); create.setCreateCDR(false); Future<Object> future = (Future<Object>) ask(ussdCallManager, create, expires); Object object = Await.result(future, Duration.create(10, TimeUnit.SECONDS)); Class<?> klass = object.getClass(); if (CallManagerResponse.class.equals(klass)) { final CallManagerResponse<ActorRef> managerResponse = (CallManagerResponse<ActorRef>) object; if (managerResponse.succeeded()) { final ActorRef call = managerResponse.get(); future = (Future<Object>) ask(call, new GetCallInfo(), expires); object = Await.result(future, Duration.create(10, TimeUnit.SECONDS)); klass = object.getClass(); if (CallResponse.class.equals(klass)) { final CallResponse<CallInfo> callResponse = (CallResponse<CallInfo>) object; if (callResponse.succeeded()) { final CallInfo callInfo = callResponse.get(); // Execute the call script. final String version = getApiVersion(data); final URI url = getUrl("Url", data); final String method = getMethod("Method", data); final URI fallbackUrl = getUrl("FallbackUrl", data); final String fallbackMethod = getMethod("FallbackMethod", data); final ExecuteCallScript execute = new ExecuteCallScript(call, accountId, version, url, method, fallbackUrl, fallbackMethod, timeout); ussdCallManager.tell(execute, null); // Create a call detail record for the call. // final CallDetailRecord.Builder builder = CallDetailRecord.builder(); // builder.setSid(callInfo.sid()); // builder.setDateCreated(callInfo.dateCreated()); // builder.setAccountSid(accountId); // builder.setTo(to); // builder.setCallerName(callInfo.fromName()); // builder.setFrom(from); // builder.setForwardedFrom(callInfo.forwardedFrom()); // builder.setStatus(callInfo.state().toString()); // final DateTime now = DateTime.now(); // builder.setStartTime(now); // builder.setDirection(callInfo.direction()); // builder.setApiVersion(version); // final StringBuilder buffer = new StringBuilder(); // buffer.append("/").append(version).append("/Accounts/"); // buffer.append(accountId.toString()).append("/Calls/"); // buffer.append(callInfo.sid().toString()); // final URI uri = URI.create(buffer.toString()); // builder.setUri(uri); // // builder.setCallPath(call.path().toString()); // // final CallDetailRecord cdr = builder.build(); // daos.getCallDetailRecordsDao().addCallDetailRecord(cdr); CallDetailRecord cdr = daos.getCallDetailRecordsDao().getCallDetailRecord(callInfo.sid()); if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(cdr), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { return ok(xstream.toXML(new RestCommResponse(cdr)), APPLICATION_XML).build(); } else { return null; } } } } } return status(INTERNAL_SERVER_ERROR).build(); } catch (final Exception exception) { return status(INTERNAL_SERVER_ERROR).entity(exception.getMessage()).build(); } } private Integer getTimeout(final MultivaluedMap<String, String> data) { Integer result = 60; if (data.containsKey("Timeout")) { result = Integer.parseInt(data.getFirst("Timeout")); } return result; } private void validate(final MultivaluedMap<String, String> data) throws NullPointerException { if (!data.containsKey("From")) { throw new NullPointerException("From can not be null."); } else if (!data.containsKey("To")) { throw new NullPointerException("To can not be null."); } else if (!data.containsKey("Url")) { throw new NullPointerException("Url can not be null."); } } @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response putCall(@PathParam("accountSid") final String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return putCall(accountSid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } }
11,671
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AvailablePhoneNumbersMobileXmlEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/AvailablePhoneNumbersMobileXmlEndpoint.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.restcomm.connect.http; import com.sun.jersey.spi.container.ResourceFilters; import com.sun.jersey.spi.resource.Singleton; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.*; import static javax.ws.rs.core.Response.Status.*; import javax.ws.rs.core.SecurityContext; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.http.filters.ExtensionFilter; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.provisioning.number.api.PhoneNumberSearchFilters; import org.restcomm.connect.provisioning.number.api.PhoneNumberType; /** * @author <a href="mailto:[email protected]">gvagenas</a> * @author <a href="mailto:[email protected]">Jean Deruelle</a> */ @Path("/Accounts/{accountSid}/AvailablePhoneNumbers/{IsoCountryCode}/Mobile") @ThreadSafe @Singleton public class AvailablePhoneNumbersMobileXmlEndpoint extends AvailablePhoneNumbersEndpoint { public AvailablePhoneNumbersMobileXmlEndpoint() { super(); } @GET @ResourceFilters({ ExtensionFilter.class }) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getAvailablePhoneNumber(@PathParam("accountSid") final String accountSid, @PathParam("IsoCountryCode") final String isoCountryCode, @QueryParam("AreaCode") String areaCode, @QueryParam("Contains") String filterPattern, @QueryParam("SmsEnabled") String smsEnabled, @QueryParam("MmsEnabled") String mmsEnabled, @QueryParam("VoiceEnabled") String voiceEnabled, @QueryParam("FaxEnabled") String faxEnabled, @QueryParam("UssdEnabled") String ussdEnabled, @QueryParam("RangeSize") String rangeSize, @QueryParam("RangeIndex") String rangeIndex, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { if (isoCountryCode != null && !isoCountryCode.isEmpty()) { int rangeSizeInt = -1; if (rangeSize != null && !rangeSize.isEmpty()) { rangeSizeInt = Integer.parseInt(rangeSize); } int rangeIndexInt = -1; if (rangeIndex != null && !rangeIndex.isEmpty()) { rangeIndexInt = Integer.parseInt(rangeIndex); } Boolean smsEnabledBool = null; if (smsEnabled != null && !smsEnabled.isEmpty()) { smsEnabledBool = Boolean.valueOf(smsEnabled); } Boolean mmsEnabledBool = null; if (mmsEnabled != null && !mmsEnabled.isEmpty()) { mmsEnabledBool = Boolean.valueOf(mmsEnabled); } Boolean voiceEnabledBool = null; if (voiceEnabled != null && !voiceEnabled.isEmpty()) { voiceEnabledBool = Boolean.valueOf(voiceEnabled); } Boolean faxEnabledBool = null; if (faxEnabled != null && !faxEnabled.isEmpty()) { faxEnabledBool = Boolean.valueOf(faxEnabled); } Boolean ussdEnabledBool = null; if (ussdEnabled != null && !ussdEnabled.isEmpty()) { ussdEnabledBool = Boolean.valueOf(ussdEnabled); } PhoneNumberSearchFilters listFilters = new PhoneNumberSearchFilters(areaCode, null, smsEnabledBool, mmsEnabledBool, voiceEnabledBool, faxEnabledBool, ussdEnabledBool, null, null, null, null, null, null, null, rangeSizeInt, rangeIndexInt, PhoneNumberType.Mobile); return getAvailablePhoneNumbers(accountSid, isoCountryCode, listFilters, filterPattern, retrieveMediaType(accept), ContextUtil.convert(sec)); } else { return status(BAD_REQUEST).build(); } } }
4,867
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ConferencesEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/ConferencesEndpoint.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.restcomm.connect.http; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import java.text.ParseException; import java.util.List; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.MediaType.APPLICATION_XML_TYPE; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.Status.UNAUTHORIZED; import static javax.ws.rs.core.Response.ok; import static javax.ws.rs.core.Response.status; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import org.apache.commons.configuration.Configuration; import org.apache.shiro.authz.AuthorizationException; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.ConferenceDetailRecordsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.ConferenceDetailRecord; import org.restcomm.connect.dao.entities.ConferenceDetailRecordFilter; import org.restcomm.connect.dao.entities.ConferenceDetailRecordList; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.http.converter.ConferenceDetailRecordConverter; import org.restcomm.connect.http.converter.ConferenceDetailRecordListConverter; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.http.security.PermissionEvaluator.SecuredType; import org.restcomm.connect.identity.UserIdentityContext; /** * @author [email protected] (Thomas Quintana) * @author [email protected] (Maria Farooq) */ @Path("/Accounts/{accountSid}/Conferences") @ThreadSafe @Singleton public class ConferencesEndpoint extends AbstractEndpoint { @Context protected ServletContext context; protected Configuration configuration; private DaoManager daoManager; private Gson gson; private GsonBuilder builder; private XStream xstream; private ConferenceDetailRecordListConverter listConverter; public ConferencesEndpoint() { super(); } @PostConstruct public void init() { configuration = (Configuration) context.getAttribute(Configuration.class.getName()); configuration = configuration.subset("runtime-settings"); daoManager = (DaoManager) context.getAttribute(DaoManager.class.getName()); super.init(configuration); ConferenceDetailRecordConverter converter = new ConferenceDetailRecordConverter(configuration); listConverter = new ConferenceDetailRecordListConverter(configuration); builder = new GsonBuilder(); builder.registerTypeAdapter(ConferenceDetailRecord.class, converter); builder.registerTypeAdapter(ConferenceDetailRecordList.class, listConverter); builder.setPrettyPrinting(); builder.disableHtmlEscaping(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(listConverter); } protected Response getConference(final String accountSid, final String sid, final MediaType responseType, UserIdentityContext userIdentityContext) { Account account = daoManager.getAccountsDao().getAccount(accountSid); try { permissionEvaluator.secure(account, "RestComm:Read:Conferences", userIdentityContext); } catch (final AuthorizationException exception) { return status(UNAUTHORIZED).build(); } final ConferenceDetailRecordsDao dao = daoManager.getConferenceDetailRecordsDao(); final ConferenceDetailRecord cdr = dao.getConferenceDetailRecord(new Sid(sid)); if (cdr == null) { return status(NOT_FOUND).build(); } else { try { //secureLevelControl(daoManager.getAccountsDao(), accountSid, String.valueOf(cdr.getAccountSid())); permissionEvaluator.secure(account, cdr.getAccountSid(), SecuredType.SECURED_STANDARD, userIdentityContext); } catch (final AuthorizationException exception) { return status(UNAUTHORIZED).build(); } if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(cdr); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(cdr), APPLICATION_JSON).build(); } else { return null; } } } protected Response getConferences(final String accountSid, UriInfo info, MediaType responseType, UserIdentityContext userIdentityContext) { Account account = daoManager.getAccountsDao().getAccount(accountSid); try { permissionEvaluator.secure(account, "RestComm:Read:Conferences", userIdentityContext); //secureLevelControl(daoManager.getAccountsDao(), accountSid, null); } catch (final AuthorizationException exception) { return status(UNAUTHORIZED).build(); } String pageSize = info.getQueryParameters().getFirst("PageSize"); String page = info.getQueryParameters().getFirst("Page"); String status = info.getQueryParameters().getFirst("Status"); String dateCreated = info.getQueryParameters().getFirst("DateCreated"); String dateUpdated = info.getQueryParameters().getFirst("DateUpdated"); String friendlyName = info.getQueryParameters().getFirst("FriendlyName"); if (pageSize == null) { pageSize = "50"; } if (page == null) { page = "0"; } int limit = Integer.parseInt(pageSize); int offset = (page == "0") ? 0 : (((Integer.parseInt(page) - 1) * Integer.parseInt(pageSize)) + Integer .parseInt(pageSize)); ConferenceDetailRecordsDao dao = daoManager.getConferenceDetailRecordsDao(); ConferenceDetailRecordFilter filterForTotal; try { filterForTotal = new ConferenceDetailRecordFilter(accountSid, status, dateCreated, dateUpdated, friendlyName, null, null); } catch (ParseException e) { return status(BAD_REQUEST).build(); } final int total = dao.getTotalConferenceDetailRecords(filterForTotal); if (Integer.parseInt(page) > (total / limit)) { return status(javax.ws.rs.core.Response.Status.BAD_REQUEST).build(); } ConferenceDetailRecordFilter filter; try { filter = new ConferenceDetailRecordFilter(accountSid, status, dateCreated, dateUpdated, friendlyName, limit, offset); } catch (ParseException e) { return status(BAD_REQUEST).build(); } final List<ConferenceDetailRecord> cdrs = dao.getConferenceDetailRecords(filter); listConverter.setCount(total); listConverter.setPage(Integer.parseInt(page)); listConverter.setPageSize(Integer.parseInt(pageSize)); listConverter.setPathUri("/"+getApiVersion(null)+"/"+info.getPath()); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(new ConferenceDetailRecordList(cdrs)); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(new ConferenceDetailRecordList(cdrs)), APPLICATION_JSON).build(); } else { return null; } } @Path("/{sid}") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getConferenceAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getConference(accountSid, sid, retrieveMediaType(accept), ContextUtil.convert(sec)); } @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getConferences(@PathParam("accountSid") final String accountSid, @Context UriInfo info, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getConferences(accountSid, info, retrieveMediaType(accept), ContextUtil.convert(sec)); } }
10,160
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
UsageEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/UsageEndpoint.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.restcomm.connect.http; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import java.util.List; import java.util.regex.Pattern; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.*; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.ok; import static javax.ws.rs.core.Response.status; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import org.apache.commons.configuration.Configuration; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.UsageDao; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.dao.entities.Usage; import org.restcomm.connect.dao.entities.UsageList; import org.restcomm.connect.http.converter.RestCommResponseConverter; import org.restcomm.connect.http.converter.UsageConverter; import org.restcomm.connect.http.converter.UsageListConverter; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.identity.UserIdentityContext; /** * @author [email protected] (Charles Roufay) * @author [email protected] (Alexandre Mendonca) */ @Path("/Accounts/{accountSid}/Usage/Records") @ThreadSafe @Singleton public class UsageEndpoint extends AbstractEndpoint { @Context protected ServletContext context; protected Configuration configuration; protected UsageDao dao; protected Gson gson; protected XStream xstream; @Context private HttpServletRequest servletRequest; public UsageEndpoint() { super(); } public static final Pattern relativePattern = Pattern.compile("(\\+|\\-)(\\d+)day[s]"); @PostConstruct public void init() { final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); configuration = (Configuration) context.getAttribute(Configuration.class.getName()); configuration = configuration.subset("runtime-settings"); super.init(configuration); dao = storage.getUsageDao(); final UsageConverter converter = new UsageConverter(configuration); final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Usage.class, converter); builder.setPrettyPrinting(); gson = builder.disableHtmlEscaping().create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(new UsageListConverter(configuration)); xstream.registerConverter(new RestCommResponseConverter(configuration)); } protected Response getUsage(final String accountSid, final String subresource, UriInfo info, final MediaType responseType, UserIdentityContext userIdentityContext) { permissionEvaluator.secure(accountsDao.getAccount(accountSid), "RestComm:Read:Usage", userIdentityContext); String categoryStr = info.getQueryParameters().getFirst("Category"); String startDateStr = info.getQueryParameters().getFirst("StartDate"); String endDateStr = info.getQueryParameters().getFirst("EndDate"); //pass in reqUri without query params String reqUri = servletRequest.getServletPath() + "/" + info.getPath(false); Usage.Category category = categoryStr != null ? Usage.Category.valueOf(categoryStr) : null; DateTime startDate = new DateTime(0).withTimeAtStartOfDay(); if (startDateStr != null) { try { startDate = DateTimeFormat.forPattern("yyyyy-MM-dd").parseDateTime(startDateStr); } catch (IllegalArgumentException iae) { // TODO: Support relative } } DateTime endDate = new DateTime(); if (endDateStr != null) { try { endDate = DateTimeFormat.forPattern("yyyyy-MM-dd").parseDateTime(endDateStr); } catch (IllegalArgumentException iae) { // TODO: Support relative } } final List<Usage> usage; if (subresource.toLowerCase().equals("daily")) { usage = dao.getUsageDaily(new Sid(accountSid), category, startDate, endDate, reqUri); } else if (subresource.toLowerCase().equals("monthly")) { usage = dao.getUsageMonthly(new Sid(accountSid), category, startDate, endDate, reqUri); } else if (subresource.toLowerCase().equals("yearly")) { usage = dao.getUsageYearly(new Sid(accountSid), category, startDate, endDate, reqUri); } else if (subresource.toLowerCase().equals("alltime")) { usage = dao.getUsageAllTime(new Sid(accountSid), category, startDate, endDate, reqUri); } else if (subresource.toLowerCase().equals("today")) { usage = dao.getUsageAllTime(new Sid(accountSid), category, DateTime.now(), DateTime.now(), reqUri); } else if (subresource.toLowerCase().equals("yesterday")) { usage = dao.getUsageAllTime(new Sid(accountSid), category, DateTime.now().minusDays(1), DateTime.now().minusDays(1), reqUri); } else if (subresource.toLowerCase().equals("thismonth")) { usage = dao.getUsageAllTime(new Sid(accountSid), category, DateTime.now().dayOfMonth().withMinimumValue(), DateTime.now().dayOfMonth().withMaximumValue(), reqUri); } else if (subresource.toLowerCase().equals("lastmonth")) { usage = dao.getUsageAllTime(new Sid(accountSid), category, DateTime.now().minusMonths(1).dayOfMonth().withMinimumValue(), DateTime.now().minusMonths(1).dayOfMonth().withMaximumValue(), reqUri); } else { usage = dao.getUsageAllTime(new Sid(accountSid), category, startDate, endDate, reqUri); } if (usage == null) { return status(NOT_FOUND).build(); } else { if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(usage), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(new UsageList(usage)); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } } @Path("/{subresource}") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getUsageAsXml(@PathParam("accountSid") final String accountSid, @PathParam("subresource") final String subresource, @Context UriInfo info, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getUsage(accountSid, subresource, info, retrieveMediaType(accept), ContextUtil.convert(sec)); } }
7,998
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CallsUtil.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/CallsUtil.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.restcomm.connect.http; import akka.actor.ActorRef; import org.apache.log4j.Logger; import org.restcomm.connect.dao.CallDetailRecordsDao; import org.restcomm.connect.dao.entities.CallDetailRecord; import org.restcomm.connect.mscontrol.api.messages.Mute; import org.restcomm.connect.mscontrol.api.messages.Unmute; import org.restcomm.connect.telephony.api.CallInfo; public class CallsUtil { protected static Logger logger = Logger.getLogger(CallsUtil.class); /** * @param mute - true if we want to mute the call, false otherwise. * @param callInfo - CallInfo * @param call - ActorRef for the call * @param cdr - CallDetailRecord of given call to update mute status in db * @param dao - CallDetailRecordsDao for calls to update mute status in db */ public static void muteUnmuteCall(Boolean mute, CallInfo callInfo, ActorRef call, CallDetailRecord cdr, CallDetailRecordsDao dao){ if(callInfo.state().name().equalsIgnoreCase("IN_PROGRESS") || callInfo.state().name().equalsIgnoreCase("in-progress")){ if(mute){ if(!callInfo.isMuted()){ call.tell(new Mute(), null); }else{ if(logger.isInfoEnabled()) logger.info("Call is already muted."); } }else{ if(callInfo.isMuted()){ call.tell(new Unmute(), null); }else{ if(logger.isInfoEnabled()) logger.info("Call is not muted."); } } cdr = cdr.setMuted(mute); dao.updateCallDetailRecord(cdr); }else{ // Do Nothing. We can only mute/unMute in progress calls } } }
2,593
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
OrganizationsEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/OrganizationsEndpoint.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.restcomm.connect.http; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.core.header.LinkHeader; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import org.apache.commons.configuration.Configuration; import org.joda.time.DateTime; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.core.service.api.ClientPasswordHashingService; import org.restcomm.connect.core.service.api.ProfileService; import org.restcomm.connect.dao.ClientsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.entities.Client; import org.restcomm.connect.dao.entities.Organization; import org.restcomm.connect.dao.entities.OrganizationList; import org.restcomm.connect.dao.entities.Profile; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.dns.DnsProvisioningManager; import org.restcomm.connect.dns.DnsProvisioningManagerProvider; import org.restcomm.connect.http.converter.ClientConverter; import org.restcomm.connect.http.converter.ClientListConverter; import org.restcomm.connect.http.converter.OrganizationConverter; import org.restcomm.connect.http.converter.OrganizationListConverter; import org.restcomm.connect.http.converter.RestCommResponseConverter; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.identity.UserIdentityContext; import javax.annotation.PostConstruct; import javax.annotation.security.RolesAllowed; import javax.servlet.ServletContext; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import java.net.URI; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.MediaType.APPLICATION_XML_TYPE; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.Status.CONFLICT; import static javax.ws.rs.core.Response.Status.FORBIDDEN; import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.ok; import static javax.ws.rs.core.Response.status; import static org.restcomm.connect.http.ProfileEndpoint.PROFILE_REL_TYPE; import static org.restcomm.connect.http.ProfileEndpoint.TITLE_PARAM; import static org.restcomm.connect.http.security.AccountPrincipal.ADMIN_ROLE; import static org.restcomm.connect.http.security.AccountPrincipal.SUPER_ADMIN_ROLE; /** * @author [email protected] (Maria Farooq) */ @Path("/Organizations") @ThreadSafe @RolesAllowed(SUPER_ADMIN_ROLE) @Singleton public class OrganizationsEndpoint extends AbstractEndpoint { @Context private ServletContext context; private DnsProvisioningManager dnsProvisioningManager; private Gson gson; private XStream xstream; private final String MSG_EMPTY_DOMAIN_NAME = "domain name can not be empty. Please, choose a valid name and try again."; private final String MSG_INVALID_DOMAIN_NAME_PATTERN= "Total Length of domain_name can be upto 255 Characters. It can contain only letters, number and hyphen - sign.. Please, choose a valid name and try again."; private final String MSG_DOMAIN_NAME_NOT_AVAILABLE = "This domain name is not available. Please, choose a different name and try again."; private final String SUB_DOMAIN_NAME_VALIDATION_PATTERN="[A-Za-z0-9\\-]{1,255}"; private Pattern pattern; private ProfileService profileService; private ClientPasswordHashingService clientPasswordHashingService; private ClientsDao clientsDao; private OrganizationListConverter listConverter; public OrganizationsEndpoint() { super(); } @PostConstruct void init() { configuration = (Configuration) context.getAttribute(Configuration.class.getName()); super.init(configuration.subset("runtime-settings")); registerConverters(); final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); clientsDao = storage.getClientsDao(); // Make sure there is an authenticated account present when this endpoint is used // get manager from context or create it if it does not exist try { dnsProvisioningManager = new DnsProvisioningManagerProvider(configuration.subset("runtime-settings"), context).get(); } catch(Exception e) { logger.error("Unable to get dnsProvisioningManager", e); } pattern = Pattern.compile(SUB_DOMAIN_NAME_VALIDATION_PATTERN); profileService = (ProfileService)context.getAttribute(ProfileService.class.getName()); clientPasswordHashingService = (ClientPasswordHashingService) context.getAttribute(ClientPasswordHashingService.class.getName()); } private void registerConverters(){ final OrganizationConverter converter = new OrganizationConverter(configuration); listConverter = new OrganizationListConverter(configuration); final ClientConverter clientConverter = new ClientConverter(configuration); final ClientListConverter clientListConverter = new ClientListConverter(configuration); final GsonBuilder builder = new GsonBuilder(); builder.serializeNulls(); builder.registerTypeAdapter(Organization.class, converter); builder.registerTypeAdapter(Client.class, converter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(listConverter); xstream.registerConverter(clientConverter); xstream.registerConverter(clientListConverter); xstream.registerConverter(new RestCommResponseConverter(configuration)); } /** * @param organizationSid * @param responseType * @return */ protected Response getOrganization(final String organizationSid, final MediaType responseType, UriInfo info, UserIdentityContext userIdentityContext) { //First check if the account has the required permissions in general, this way we can fail fast and avoid expensive DAO operations permissionEvaluator.checkPermission("RestComm:Read:Organizations", userIdentityContext); Organization organization = null; if (!Sid.pattern.matcher(organizationSid).matches()) { return status(BAD_REQUEST).build(); } else { try { //if account is not super admin then allow to read only affiliated organization if (!permissionEvaluator.isSuperAdmin(userIdentityContext)) { if (userIdentityContext.getEffectiveAccount().getOrganizationSid().equals(new Sid(organizationSid))) { organization = organizationsDao.getOrganization(new Sid(organizationSid)); } else { return status(FORBIDDEN).build(); } } else { organization = organizationsDao.getOrganization(new Sid(organizationSid)); } } catch (Exception e) { return status(NOT_FOUND).build(); } } if (organization == null) { return status(NOT_FOUND).build(); } else { Response.ResponseBuilder ok = Response.ok(); Profile associatedProfile = profileService.retrieveEffectiveProfileByOrganizationSid(new Sid(organizationSid)); if (associatedProfile != null) { LinkHeader profileLink = composeLink(new Sid(associatedProfile.getSid()), info); ok.header(ProfileEndpoint.LINK_HEADER, profileLink.toString()); } if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(organization); return ok.type(APPLICATION_XML).entity(xstream.toXML(response)).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok.type(APPLICATION_JSON).entity(gson.toJson(organization)).build(); } else { return null; } } } /** * @param info * @param responseType * @return */ protected Response getOrganizations(UriInfo info, final MediaType responseType) { List<Organization> organizations = null; String status = info.getQueryParameters().getFirst("Status"); if(status != null && Organization.Status.getValueOf(status.toLowerCase()) != null){ organizations = organizationsDao.getOrganizationsByStatus(Organization.Status.getValueOf(status.toLowerCase())); }else{ organizations = organizationsDao.getAllOrganizations(); } if (organizations == null || organizations.isEmpty()) { return status(NOT_FOUND).build(); } if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(new OrganizationList(organizations)); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(organizations), APPLICATION_JSON).build(); } else { return null; } } /** * putOrganization create new organization * @param domainName * @param info * @param responseType * @return */ protected Response putOrganization(String domainName, final UriInfo info, MediaType responseType) { if(domainName == null){ return status(BAD_REQUEST).entity(MSG_EMPTY_DOMAIN_NAME ).build(); }else{ //Character verification if(!pattern.matcher(domainName).matches()){ return status(BAD_REQUEST).entity(MSG_INVALID_DOMAIN_NAME_PATTERN).build(); } Organization organization; if(dnsProvisioningManager == null) { //Check if domain_name does not already taken inside restcomm by an organization. organization = organizationsDao.getOrganizationByDomainName(domainName); if(organization != null){ return status(CONFLICT) .entity(MSG_DOMAIN_NAME_NOT_AVAILABLE) .build(); } logger.warn("No DNS provisioning Manager is configured, restcomm will not make any queries to DNS server."); organization = new Organization(Sid.generate(Sid.Type.ORGANIZATION), domainName, DateTime.now(), DateTime.now(), Organization.Status.ACTIVE); organizationsDao.addOrganization(organization); }else { //for example hosted zone id of domain restcomm.com or others. if not provided then default will be used as per configuration String hostedZoneId = info.getQueryParameters().getFirst("HostedZoneId"); //Check if domain_name does not already taken inside restcomm by an organization. String completeDomainName = dnsProvisioningManager.getCompleteDomainName(domainName, hostedZoneId); organization = organizationsDao.getOrganizationByDomainName(completeDomainName); if(organization != null){ return status(CONFLICT) .entity(MSG_DOMAIN_NAME_NOT_AVAILABLE) .build(); } //check if domain name already exists on dns side or not if(dnsProvisioningManager.doesResourceRecordAlreadyExists(domainName, hostedZoneId)){ return status(CONFLICT) .entity(MSG_DOMAIN_NAME_NOT_AVAILABLE) .build(); } if(!dnsProvisioningManager.createResourceRecord(domainName, hostedZoneId)){ logger.error("could not create resource record on dns server"); return status(INTERNAL_SERVER_ERROR).build(); }else{ organization = new Organization(Sid.generate(Sid.Type.ORGANIZATION), completeDomainName, DateTime.now(), DateTime.now(), Organization.Status.ACTIVE); organizationsDao.addOrganization(organization); } } if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(organization); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(organization), APPLICATION_JSON).build(); } else { return null; } } } /** * Hash password for clients of the given organization * @param organizationSid * @param info * @param responseType * @return Response with List<Client> for the Clients that hashed the password */ protected Response migrateClientsOrganization(final String organizationSid, UriInfo info, MediaType responseType, UserIdentityContext userIdentityContext) { //First check if the account has the required permissions in general, this way we can fail fast and avoid expensive DAO operations permissionEvaluator.checkPermission("RestComm:Read:Organizations", userIdentityContext); Organization organization = null; if (!Sid.pattern.matcher(organizationSid).matches()) { return status(BAD_REQUEST).build(); } else { try { if (!permissionEvaluator.isSuperAdmin(userIdentityContext)) { return status(FORBIDDEN).build(); } else { organization = organizationsDao.getOrganization(new Sid(organizationSid)); } } catch (Exception e) { return status(NOT_FOUND).build(); } } if (organization == null) { return status(NOT_FOUND).build(); } else { Response.ResponseBuilder ok = Response.ok(); List<Client> clients = clientsDao.getClientsByOrg(organization.getSid()); Map<String, String> migratedClients = clientPasswordHashingService.hashClientPassword(clients, organization.getDomainName()); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(migratedClients); return ok.type(APPLICATION_XML).entity(xstream.toXML(response)).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok.type(APPLICATION_JSON).entity(gson.toJson(migratedClients)).build(); } else { return null; } } } public LinkHeader composeLink(Sid targetSid, UriInfo info) { String sid = targetSid.toString(); URI uri = info.getBaseUriBuilder().path(ProfileEndpoint.class).path(sid).build(); LinkHeader.LinkHeaderBuilder link = LinkHeader.uri(uri).parameter(TITLE_PARAM, "Profiles"); return link.rel(PROFILE_REL_TYPE).build(); } @Path("/{organizationSid}") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @RolesAllowed({SUPER_ADMIN_ROLE, ADMIN_ROLE}) public Response getOrganizationAsXml(@PathParam("organizationSid") final String organizationSid, @Context UriInfo info, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getOrganization(organizationSid, retrieveMediaType(accept), info, ContextUtil.convert(sec)); } @GET @RolesAllowed(SUPER_ADMIN_ROLE) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getOrganizations(@Context UriInfo info, @HeaderParam("Accept") String accept) { return getOrganizations(info, retrieveMediaType(accept)); } @Path("/{domainName}") @PUT @RolesAllowed(SUPER_ADMIN_ROLE) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response putOrganizationPut(@PathParam("domainName") final String domainName, @Context UriInfo info, @HeaderParam("Accept") String accept) { return putOrganization(domainName, info, retrieveMediaType(accept)); } @Path("/{organizationSid}/Migrate") @PUT @RolesAllowed(SUPER_ADMIN_ROLE) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response migrateClientsOrganizationPut(@PathParam("organizationSid") final String organizationSid, @Context UriInfo info, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return migrateClientsOrganization(organizationSid, info, retrieveMediaType(accept), ContextUtil.convert(sec)); } }
18,599
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ParticipantsEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/ParticipantsEndpoint.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.restcomm.connect.http; import akka.actor.ActorRef; import static akka.pattern.Patterns.ask; import akka.util.Timeout; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import java.util.List; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.MediaType.APPLICATION_XML_TYPE; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR; import static javax.ws.rs.core.Response.Status.NOT_ACCEPTABLE; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.Status.UNAUTHORIZED; import static javax.ws.rs.core.Response.ok; import static javax.ws.rs.core.Response.status; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import org.apache.commons.configuration.Configuration; import org.apache.shiro.authz.AuthorizationException; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.AccountsDao; import org.restcomm.connect.dao.CallDetailRecordsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.RecordingsDao; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.CallDetailRecord; import org.restcomm.connect.dao.entities.CallDetailRecordList; import org.restcomm.connect.dao.entities.Recording; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.http.converter.CallDetailRecordListConverter; import org.restcomm.connect.http.converter.ConferenceParticipantConverter; import org.restcomm.connect.http.converter.RecordingConverter; import org.restcomm.connect.http.converter.RecordingListConverter; import org.restcomm.connect.http.converter.RestCommResponseConverter; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.http.security.PermissionEvaluator.SecuredType; import org.restcomm.connect.identity.UserIdentityContext; import org.restcomm.connect.telephony.api.CallInfo; import org.restcomm.connect.telephony.api.CallResponse; import org.restcomm.connect.telephony.api.GetCall; import org.restcomm.connect.telephony.api.GetCallInfo; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; /** * @author [email protected] (Maria Farooq) */ @Path("/Accounts/{accountSid}/Conferences/{conferenceSid}/Participants") @ThreadSafe @Singleton public class ParticipantsEndpoint extends AbstractEndpoint { @Context private ServletContext context; private Configuration configuration; private ActorRef callManager; private DaoManager daos; private Gson gson; private GsonBuilder builder; private XStream xstream; private CallDetailRecordListConverter listConverter; private AccountsDao accountsDao; private RecordingsDao recordingsDao; private String instanceId; public ParticipantsEndpoint() { super(); } @PostConstruct public void init() { configuration = (Configuration) context.getAttribute(Configuration.class.getName()); configuration = configuration.subset("runtime-settings"); callManager = (ActorRef) context.getAttribute("org.restcomm.connect.telephony.CallManager"); daos = (DaoManager) context.getAttribute(DaoManager.class.getName()); accountsDao = daos.getAccountsDao(); recordingsDao = daos.getRecordingsDao(); super.init(configuration); ConferenceParticipantConverter converter = new ConferenceParticipantConverter(configuration); listConverter = new CallDetailRecordListConverter(configuration); final RecordingConverter recordingConverter = new RecordingConverter(configuration); builder = new GsonBuilder(); builder.registerTypeAdapter(CallDetailRecord.class, converter); builder.registerTypeAdapter(CallDetailRecordList.class, listConverter); builder.registerTypeAdapter(Recording.class, recordingConverter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(recordingConverter); xstream.registerConverter(new RecordingListConverter(configuration)); xstream.registerConverter(new RestCommResponseConverter(configuration)); xstream.registerConverter(listConverter); instanceId = RestcommConfiguration.getInstance().getMain().getInstanceId(); } protected Response getCall(final String accountSid, final String sid, final MediaType responseType, UserIdentityContext userIdentityContext) { Account account = daos.getAccountsDao().getAccount(accountSid); try { permissionEvaluator.secure(account, "RestComm:Read:Calls", userIdentityContext); } catch (final AuthorizationException exception) { return status(UNAUTHORIZED).build(); } final CallDetailRecordsDao dao = daos.getCallDetailRecordsDao(); final CallDetailRecord cdr = dao.getCallDetailRecord(new Sid(sid)); if (cdr == null) { return status(NOT_FOUND).build(); } else { try { permissionEvaluator.secure(account, cdr.getAccountSid(), SecuredType.SECURED_STANDARD, userIdentityContext); } catch (final AuthorizationException exception) { return status(UNAUTHORIZED).build(); } if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(cdr); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(cdr), APPLICATION_JSON).build(); } else { return null; } } } protected Response getCalls(final String accountSid, final String conferenceSid, UriInfo info, MediaType responseType, UserIdentityContext userIdentityContext) { Account account = daos.getAccountsDao().getAccount(accountSid); try { permissionEvaluator.secure(account, "RestComm:Read:Calls", userIdentityContext); } catch (final AuthorizationException exception) { return status(UNAUTHORIZED).build(); } catch (Exception e) { } String pageSize = info.getQueryParameters().getFirst("PageSize"); String page = info.getQueryParameters().getFirst("Page"); if (pageSize == null) { pageSize = "50"; } if (page == null) { page = "0"; } int limit = Integer.parseInt(pageSize); int offset = (page == "0") ? 0 : (((Integer.parseInt(page) - 1) * Integer.parseInt(pageSize)) + Integer .parseInt(pageSize)); CallDetailRecordsDao dao = daos.getCallDetailRecordsDao(); final int total = dao.getTotalRunningCallDetailRecordsByConferenceSid(new Sid(conferenceSid)); if (Integer.parseInt(page) > (total / limit)) { return status(javax.ws.rs.core.Response.Status.BAD_REQUEST).build(); } final List<CallDetailRecord> cdrs = dao.getRunningCallDetailRecordsByConferenceSid(new Sid(conferenceSid)); if (logger.isDebugEnabled()) { final List<CallDetailRecord> allCdrs = dao.getCallDetailRecordsByAccountSid(new Sid(accountSid)); logger.debug("CDR with filter size: "+ cdrs.size()+", all CDR with no filter size: "+allCdrs.size()); logger.debug("CDRs for ConferenceSid: "+conferenceSid); for (CallDetailRecord cdr: allCdrs) { logger.debug("CDR sid: "+cdr.getSid()+", status: "+cdr.getStatus()+", conferenceSid: "+cdr.getConferenceSid()); } } listConverter.setCount(total); listConverter.setPage(Integer.parseInt(page)); listConverter.setPageSize(Integer.parseInt(pageSize)); listConverter.setPathUri("/"+getApiVersion(null)+"/"+info.getPath()); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(new CallDetailRecordList(cdrs)); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(new CallDetailRecordList(cdrs)), APPLICATION_JSON).build(); } else { return null; } } @SuppressWarnings("unchecked") protected Response updateCall(final String sid, final String callSid, final MultivaluedMap<String, String> data, final MediaType responseType, UserIdentityContext userIdentityContext) { final Sid accountSid = new Sid(sid); Account account = daos.getAccountsDao().getAccount(accountSid); try { permissionEvaluator.secure(account, "RestComm:Modify:Calls", userIdentityContext); } catch (final AuthorizationException exception) { return status(UNAUTHORIZED).build(); } final Timeout expires = new Timeout(Duration.create(60, TimeUnit.SECONDS)); final CallDetailRecordsDao dao = daos.getCallDetailRecordsDao(); CallDetailRecord cdr = null; try { cdr = dao.getCallDetailRecord(new Sid(callSid)); if (cdr != null) { try { permissionEvaluator.secure(account, cdr.getAccountSid(), SecuredType.SECURED_STANDARD, userIdentityContext); } catch (final AuthorizationException exception) { return status(UNAUTHORIZED).build(); } } else { return Response.status(NOT_ACCEPTABLE).build(); } } catch (Exception e) { return status(BAD_REQUEST).build(); } Boolean mute = Boolean.valueOf(data.getFirst("Mute")); // Mute/UnMute call if (mute != null) { String callPath = null; final ActorRef call; final CallInfo callInfo; try { callPath = cdr.getCallPath(); Future<Object> future = (Future<Object>) ask(callManager, new GetCall(callPath), expires); call = (ActorRef) Await.result(future, Duration.create(100000, TimeUnit.SECONDS)); future = (Future<Object>) ask(call, new GetCallInfo(), expires); CallResponse<CallInfo> response = (CallResponse<CallInfo>) Await.result(future, Duration.create(100000, TimeUnit.SECONDS)); callInfo = response.get(); } catch (Exception exception) { return status(INTERNAL_SERVER_ERROR).entity(exception.getMessage()).build(); } if(call != null){ try{ CallsUtil.muteUnmuteCall(mute, callInfo, call, cdr, dao); } catch (Exception exception) { return status(INTERNAL_SERVER_ERROR).entity(exception.getMessage()).build(); } } } if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(cdr), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { return ok(xstream.toXML(new RestCommResponse(cdr)), APPLICATION_XML).build(); } else { return null; } } @Path("/{callSid}") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getParticipantAsXml(@PathParam("accountSid") final String accountSid, @PathParam("conferenceSid") final String conferenceSid, @PathParam("callSid") final String callSid, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getCall(accountSid, callSid, retrieveMediaType(accept), ContextUtil.convert(sec)); } @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getParticipants(@PathParam("accountSid") final String accountSid, @PathParam("conferenceSid") final String conferenceSid, @Context UriInfo info, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getCalls(accountSid, conferenceSid, info, retrieveMediaType(accept), ContextUtil.convert(sec)); } @Path("/{callSid}") @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response modifyCall(@PathParam("accountSid") final String accountSid, @PathParam("conferenceSid") final String conferenceSid, @PathParam("callSid") final String callSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return updateCall(accountSid, callSid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } }
15,302
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CallsEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/CallsEndpoint.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.restcomm.connect.http; import akka.actor.ActorRef; import akka.pattern.AskTimeoutException; import static akka.pattern.Patterns.ask; import akka.util.Timeout; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import java.net.URI; import java.net.URL; import java.text.ParseException; import java.util.Map; import java.util.List; import java.util.ArrayList; import java.util.LinkedList; import java.util.Arrays; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import javax.servlet.sip.SipServletResponse; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.MediaType.APPLICATION_XML_TYPE; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.Status.GONE; import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR; import static javax.ws.rs.core.Response.Status.NOT_ACCEPTABLE; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.ok; import static javax.ws.rs.core.Response.status; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.amazonS3.RecordingSecurityLevel; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.commons.telephony.CreateCallType; import org.restcomm.connect.dao.AccountsDao; import org.restcomm.connect.dao.CallDetailRecordsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.RecordingsDao; import org.restcomm.connect.dao.common.Sorting; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.CallDetailRecord; import org.restcomm.connect.dao.entities.CallDetailRecordFilter; import org.restcomm.connect.dao.entities.CallDetailRecordList; import org.restcomm.connect.dao.entities.Recording; import org.restcomm.connect.dao.entities.RecordingList; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.http.converter.CallDetailRecordConverter; import org.restcomm.connect.http.converter.CallDetailRecordListConverter; import org.restcomm.connect.http.converter.RecordingConverter; import org.restcomm.connect.http.converter.RecordingListConverter; import org.restcomm.connect.http.converter.RestCommResponseConverter; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.http.security.PermissionEvaluator.SecuredType; import org.restcomm.connect.identity.UserIdentityContext; import org.restcomm.connect.telephony.api.CallInfo; import org.restcomm.connect.telephony.api.CallManagerResponse; import org.restcomm.connect.telephony.api.CallResponse; import org.restcomm.connect.telephony.api.CreateCall; import org.restcomm.connect.telephony.api.ExecuteCallScript; import org.restcomm.connect.telephony.api.GetCall; import org.restcomm.connect.telephony.api.GetCallInfo; import org.restcomm.connect.telephony.api.Hangup; import org.restcomm.connect.telephony.api.UpdateCallScript; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; //import org.joda.time.DateTime; /** * @author [email protected] (Thomas Quintana) * @author [email protected] (George Vagenas) */ @Path("/Accounts/{accountSid}/Calls") @ThreadSafe @Singleton public class CallsEndpoint extends AbstractEndpoint { private static final String SORTING_URL_PARAM_DATE_CREATED = "DateCreated"; private static final String SORTING_URL_PARAM_FROM = "From"; private static final String SORTING_URL_PARAM_TO = "To"; private static final String SORTING_URL_PARAM_DIRECTION = "Direction"; private static final String SORTING_URL_PARAM_STATUS = "Status"; private static final String SORTING_URL_PARAM_DURATION = "Duration"; private static final String SORTING_URL_PARAM_PRICE = "Price"; @Context private ServletContext context; private Configuration configuration; private ActorRef callManager; private DaoManager daos; private Gson gson; private GsonBuilder builder; private XStream xstream; private CallDetailRecordListConverter listConverter; private AccountsDao accountsDao; private RecordingsDao recordingsDao; private String instanceId; private RecordingSecurityLevel securityLevel = RecordingSecurityLevel.SECURE; private boolean normalizePhoneNumbers; public CallsEndpoint() { super(); } @PostConstruct public void init() { configuration = (Configuration) context.getAttribute(Configuration.class.getName()); Configuration amazonS3Configuration = configuration.subset("amazon-s3"); configuration = configuration.subset("runtime-settings"); callManager = (ActorRef) context.getAttribute("org.restcomm.connect.telephony.CallManager"); daos = (DaoManager) context.getAttribute(DaoManager.class.getName()); accountsDao = daos.getAccountsDao(); recordingsDao = daos.getRecordingsDao(); super.init(configuration); CallDetailRecordConverter converter = new CallDetailRecordConverter(configuration); listConverter = new CallDetailRecordListConverter(configuration); final RecordingConverter recordingConverter = new RecordingConverter(configuration); builder = new GsonBuilder(); builder.registerTypeAdapter(CallDetailRecord.class, converter); builder.registerTypeAdapter(CallDetailRecordList.class, listConverter); builder.registerTypeAdapter(Recording.class, recordingConverter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(recordingConverter); xstream.registerConverter(new RecordingListConverter(configuration)); xstream.registerConverter(new RestCommResponseConverter(configuration)); xstream.registerConverter(listConverter); instanceId = RestcommConfiguration.getInstance().getMain().getInstanceId(); normalizePhoneNumbers = configuration.getBoolean("normalize-numbers-for-outbound-calls"); if (!amazonS3Configuration.isEmpty()) { // Do not fail with NPE is amazonS3Configuration is not present for older install boolean amazonS3Enabled = amazonS3Configuration.getBoolean("enabled"); if (amazonS3Enabled) { securityLevel = RecordingSecurityLevel.valueOf(amazonS3Configuration.getString("security-level", "secure").toUpperCase()); recordingConverter.setSecurityLevel(securityLevel); } } } protected Response getCall(final String accountSid, final String sid, final MediaType responseType, UserIdentityContext userIdentityContext) { Account account = daos.getAccountsDao().getAccount(accountSid); permissionEvaluator.secure(account, "RestComm:Read:Calls", userIdentityContext); final CallDetailRecordsDao dao = daos.getCallDetailRecordsDao(); final CallDetailRecord cdr = dao.getCallDetailRecord(new Sid(sid)); if (cdr == null) { return status(NOT_FOUND).build(); } else { permissionEvaluator.secure(account, cdr.getAccountSid(), SecuredType.SECURED_STANDARD, userIdentityContext); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(cdr); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(cdr), APPLICATION_JSON).build(); } else { return null; } } } // Issue 153: https://bitbucket.org/telestax/telscale-restcomm/issue/153 // Issue 110: https://bitbucket.org/telestax/telscale-restcomm/issue/110 protected Response getCalls(final String accountSid, UriInfo info, MediaType responseType, UserIdentityContext userIdentityContex) { Account account = daos.getAccountsDao().getAccount(accountSid); permissionEvaluator.secure(account, "RestComm:Read:Calls", userIdentityContex); boolean localInstanceOnly = true; try { String localOnly = info.getQueryParameters().getFirst("localOnly"); if (localOnly != null && localOnly.equalsIgnoreCase("false")) localInstanceOnly = false; } catch (Exception e) { } // shall we include sub-accounts cdrs in our query ? boolean querySubAccounts = false; // be default we don't String querySubAccountsParam = info.getQueryParameters().getFirst("SubAccounts"); if (querySubAccountsParam != null && querySubAccountsParam.equalsIgnoreCase("true")) querySubAccounts = true; String pageSize = info.getQueryParameters().getFirst("PageSize"); String page = info.getQueryParameters().getFirst("Page"); // String afterSid = info.getQueryParameters().getFirst("AfterSid"); String recipient = info.getQueryParameters().getFirst("To"); String sender = info.getQueryParameters().getFirst("From"); String status = info.getQueryParameters().getFirst("Status"); String startTime = info.getQueryParameters().getFirst("StartTime"); String endTime = info.getQueryParameters().getFirst("EndTime"); String parentCallSid = info.getQueryParameters().getFirst("ParentCallSid"); String conferenceSid = info.getQueryParameters().getFirst("ConferenceSid"); String reverse = info.getQueryParameters().getFirst("Reverse"); // Format for sorting URL parameter is '?SortBy=<field>:<direction>', for example: '?SortBy=date_created:asc'. In the // future we can extend it to multiple sort fields, like ?SortBy=<field1>:<direction1>,<field2>:<direction2> String sortParameters = info.getQueryParameters().getFirst("SortBy"); // Even though 'Reverse=true/false' URL query parameter isn't documented, old console is using it, so we need // to make sure we are backwards compatible: // - If 'Reverse' is found in the URL but SortBy is not found then we deem that we are servicing an old version of Console // and we should support sorting only for Date field and translate as follows: // > 'Reverse=true': corresponds to SortBy=DateCreated:desc // > 'Reverse=false': corresponds to SortBy=DateCreated:asc // - If Reverse is found in the URL but SortBy is also found we just discard 'Reverse' and service request normally // - If only 'SortBy' is found in the URL then we service the request normally if (reverse != null && sortParameters == null) { if (reverse.equalsIgnoreCase("true")) { sortParameters = SORTING_URL_PARAM_DATE_CREATED + ":" + Sorting.Direction.DESC.name(); } else { sortParameters = SORTING_URL_PARAM_DATE_CREATED + ":" + Sorting.Direction.ASC.name(); } } CallDetailRecordFilter.Builder filterBuilder = CallDetailRecordFilter.Builder.builder(); String sortBy = null; String sortDirection = null; if (sortParameters != null && !sortParameters.isEmpty()) { try { Map<String, String> sortMap = Sorting.parseUrl(sortParameters); sortBy = sortMap.get(Sorting.SORT_BY_KEY); sortDirection = sortMap.get(Sorting.SORT_DIRECTION_KEY); } catch (Exception e) { return status(BAD_REQUEST).entity(buildErrorResponseBody(e.getMessage(), responseType)).build(); } } if (sortBy != null) { if (sortBy.equals(SORTING_URL_PARAM_DATE_CREATED)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByDate(Sorting.Direction.ASC); } else { filterBuilder.sortedByDate(Sorting.Direction.DESC); } } } if (sortBy.equals(SORTING_URL_PARAM_FROM)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByFrom(Sorting.Direction.ASC); } else { filterBuilder.sortedByFrom(Sorting.Direction.DESC); } } } if (sortBy.equals(SORTING_URL_PARAM_TO)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByTo(Sorting.Direction.ASC); } else { filterBuilder.sortedByTo(Sorting.Direction.DESC); } } } if (sortBy.equals(SORTING_URL_PARAM_DIRECTION)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByDirection(Sorting.Direction.ASC); } else { filterBuilder.sortedByDirection(Sorting.Direction.DESC); } } } if (sortBy.equals(SORTING_URL_PARAM_STATUS)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByStatus(Sorting.Direction.ASC); } else { filterBuilder.sortedByStatus(Sorting.Direction.DESC); } } } if (sortBy.equals(SORTING_URL_PARAM_DURATION)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByDuration(Sorting.Direction.ASC); } else { filterBuilder.sortedByDuration(Sorting.Direction.DESC); } } } if (sortBy.equals(SORTING_URL_PARAM_PRICE)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByPrice(Sorting.Direction.ASC); } else { filterBuilder.sortedByPrice(Sorting.Direction.DESC); } } } } if (pageSize == null) { pageSize = "50"; } if (page == null) { page = "0"; } int limit = Integer.parseInt(pageSize); int offset = (page == "0") ? 0 : (((Integer.parseInt(page) - 1) * Integer.parseInt(pageSize)) + Integer .parseInt(pageSize)); // Shall we query cdrs of sub-accounts too ? // if we do, we need to find the sub-accounts involved first List<String> ownerAccounts = null; if (querySubAccounts) { ownerAccounts = new ArrayList<String>(); ownerAccounts.add(accountSid); // we will also return parent account cdrs ownerAccounts.addAll(accountsDao.getSubAccountSidsRecursive(new Sid(accountSid))); } CallDetailRecordsDao dao = daos.getCallDetailRecordsDao(); filterBuilder.byAccountSid(accountSid) .byAccountSidSet(ownerAccounts) .byRecipient(recipient) .bySender(sender) .byStatus(status) .byStartTime(startTime) .byEndTime(endTime) .byParentCallSid(parentCallSid) .byConferenceSid(conferenceSid) .limited(limit, offset); if (!localInstanceOnly) { filterBuilder.byInstanceId(instanceId); } CallDetailRecordFilter filter; try { filter = filterBuilder.build(); } catch (ParseException e) { return status(BAD_REQUEST).build(); } final int total = dao.getTotalCallDetailRecords(filter); if (Integer.parseInt(page) > (total / limit)) { return status(javax.ws.rs.core.Response.Status.BAD_REQUEST).build(); } final List<CallDetailRecord> cdrs = dao.getCallDetailRecords(filter); listConverter.setCount(total); listConverter.setPage(Integer.parseInt(page)); listConverter.setPageSize(Integer.parseInt(pageSize)); listConverter.setPathUri("/" + getApiVersion(null) + "/" + info.getPath()); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(new CallDetailRecordList(cdrs)); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(new CallDetailRecordList(cdrs)), APPLICATION_JSON).build(); } else { return null; } } private void normalize(final MultivaluedMap<String, String> data) throws IllegalArgumentException { final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance(); final String from = data.getFirst("From"); if (!from.contains("@")) { // https://github.com/Mobicents/RestComm/issues/150 Don't complain in case of URIs in the From header data.remove("From"); try { data.putSingle("From", phoneNumberUtil.format(phoneNumberUtil.parse(from, "US"), PhoneNumberFormat.E164)); } catch (final NumberParseException exception) { throw new IllegalArgumentException(exception); } } String to = data.getFirst("To"); if (to.contains("?")) { to = to.substring(0, to.indexOf("?")); } // Only try to normalize phone numbers. if (to.startsWith("client")) { if (to.split(":").length != 2) { throw new IllegalArgumentException(to + " is an invalid client identifier."); } } else if (!to.contains("@")) { data.remove("To"); try { data.putSingle("To", phoneNumberUtil.format(phoneNumberUtil.parse(to, "US"), PhoneNumberFormat.E164)); } catch (final NumberParseException exception) { throw new IllegalArgumentException(exception); } } URI.create(data.getFirst("Url")); } @SuppressWarnings("unchecked") protected Response putCall(final String accountSid, final MultivaluedMap<String, String> data, final MediaType responseType, UserIdentityContext userIdentityContex) { final Sid accountId; try { accountId = new Sid(accountSid); } catch (final IllegalArgumentException exception) { return status(INTERNAL_SERVER_ERROR).entity(buildErrorResponseBody(exception.getMessage(), responseType)).build(); } permissionEvaluator.secure(daos.getAccountsDao().getAccount(accountSid), "RestComm:Create:Calls", userIdentityContex); try { validate(data); } catch (final RuntimeException exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } URI statusCallback = null; String statusCallbackMethod = "POST"; List<String> statusCallbackEvent = new LinkedList<String>(); statusCallbackEvent.add("initiated"); statusCallbackEvent.add("ringing"); statusCallbackEvent.add("answered"); statusCallbackEvent.add("completed"); final String from = data.getFirst("From").trim(); String to = data.getFirst("To").trim(); final String username = data.getFirst("Username"); final String password = data.getFirst("Password"); Integer timeout = getTimeout(data); timeout = timeout != null ? timeout : 30; final Timeout expires = new Timeout(Duration.create(60, TimeUnit.SECONDS)); final URI rcmlUrl = getUrl("Url", data); String customHeaders = getCustomHeaders(to); if (customHeaders != null) { to = (customHeaders != null) ? to.substring(0, to.indexOf("?")) : to; data.remove(to); data.putSingle("To", to); } try { if (normalizePhoneNumbers) normalize(data); } catch (RuntimeException exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } try { if (data.containsKey("StatusCallback")) { statusCallback = new URI(data.getFirst("StatusCallback").trim()); } } catch (Exception e) { //Handle Exception } if (statusCallback != null) { if (data.containsKey("StatusCallbackMethod")) { statusCallbackMethod = data.getFirst("StatusCallbackMethod").trim(); } if (data.containsKey("StatusCallbackEvent")) { statusCallbackEvent.addAll(Arrays.asList(data.getFirst("StatusCallbackEvent").trim().split(","))); } } CreateCall create = null; try { if (to.contains("@")) { create = new CreateCall(from, to, username, password, true, timeout, CreateCallType.SIP, accountId, null, statusCallback, statusCallbackMethod, statusCallbackEvent, customHeaders); } else if (to.startsWith("client")) { create = new CreateCall(from, to, username, password, true, timeout, CreateCallType.CLIENT, accountId, null, statusCallback, statusCallbackMethod, statusCallbackEvent, customHeaders); } else { create = new CreateCall(from, to, username, password, true, timeout, CreateCallType.PSTN, accountId, null, statusCallback, statusCallbackMethod, statusCallbackEvent, customHeaders); } create.setCreateCDR(false); if (callManager == null) callManager = (ActorRef) context.getAttribute("org.restcomm.connect.telephony.CallManager"); Future<Object> future = (Future<Object>) ask(callManager, create, expires); Object object = Await.result(future, Duration.create(10, TimeUnit.SECONDS)); Class<?> klass = object.getClass(); if (CallManagerResponse.class.equals(klass)) { final CallManagerResponse<ActorRef> managerResponse = (CallManagerResponse<ActorRef>) object; if (managerResponse.succeeded()) { List<ActorRef> dialBranches; if (managerResponse.get() instanceof List) { dialBranches = (List<ActorRef>) managerResponse.get(); } else { dialBranches = new CopyOnWriteArrayList<ActorRef>(); dialBranches.add(managerResponse.get()); } List<CallDetailRecord> cdrs = new CopyOnWriteArrayList<CallDetailRecord>(); for (ActorRef call : dialBranches) { future = (Future<Object>) ask(call, new GetCallInfo(), expires); object = Await.result(future, Duration.create(10, TimeUnit.SECONDS)); klass = object.getClass(); if (CallResponse.class.equals(klass)) { final CallResponse<CallInfo> callResponse = (CallResponse<CallInfo>) object; if (callResponse.succeeded()) { final CallInfo callInfo = callResponse.get(); // Execute the call script. final String version = getApiVersion(data); final URI url = rcmlUrl; final String method = getMethod("Method", data); final URI fallbackUrl = getUrl("FallbackUrl", data); final String fallbackMethod = getMethod("FallbackMethod", data); final ExecuteCallScript execute = new ExecuteCallScript(call, accountId, version, url, method, fallbackUrl, fallbackMethod, timeout); callManager.tell(execute, null); cdrs.add(daos.getCallDetailRecordsDao().getCallDetailRecord(callInfo.sid())); } } } if (APPLICATION_XML_TYPE.equals(responseType)) { if (cdrs.size() == 1) { return ok(xstream.toXML(cdrs.get(0)), APPLICATION_XML).build(); } else { final RestCommResponse response = new RestCommResponse(new CallDetailRecordList(cdrs)); return ok(xstream.toXML(response), APPLICATION_XML).build(); } } else if (APPLICATION_JSON_TYPE.equals(responseType)) { if (cdrs.size() == 1) { return ok(gson.toJson(cdrs.get(0)), APPLICATION_JSON).build(); } else { return ok(gson.toJson(cdrs), APPLICATION_JSON).build(); } } else { return null; } // if (APPLICATION_JSON_TYPE.equals(responseType)) { // return ok(gson.toJson(cdrs), APPLICATION_JSON).build(); // } else if (APPLICATION_XML_TYPE.equals(responseType)) { // return ok(xstream.toXML(new RestCommResponse(cdrs)), APPLICATION_XML).build(); // } else { // return null; // } } else { return status(INTERNAL_SERVER_ERROR).entity(managerResponse.cause().getMessage()).build(); } } return status(INTERNAL_SERVER_ERROR).build(); } catch (final Exception exception) { return status(INTERNAL_SERVER_ERROR).entity(exception.getMessage()).build(); } } private String getCustomHeaders(final String to) { String customHeaders = null; if (to.contains("?")) { customHeaders = to.substring(to.indexOf("?") + 1, to.length()); } return customHeaders; } // Issue 139: https://bitbucket.org/telestax/telscale-restcomm/issue/139 @SuppressWarnings("unchecked") protected Response updateCall(final String sid, final String callSid, final MultivaluedMap<String, String> data, final MediaType responseType, UserIdentityContext userIdentityContex) { final Sid accountSid = new Sid(sid); Account account = daos.getAccountsDao().getAccount(accountSid); permissionEvaluator.secure(account, "RestComm:Modify:Calls", userIdentityContex); final Timeout expires = new Timeout(Duration.create(60, TimeUnit.SECONDS)); final CallDetailRecordsDao dao = daos.getCallDetailRecordsDao(); CallDetailRecord cdr = null; try { cdr = dao.getCallDetailRecord(new Sid(callSid)); if (cdr != null) { //allow super admin to perform LCM on any call - https://telestax.atlassian.net/browse/RESTCOMM-1171 if (!permissionEvaluator.isSuperAdmin(userIdentityContex)) { permissionEvaluator.secure(account, cdr.getAccountSid(), SecuredType.SECURED_STANDARD, userIdentityContex); } } else { return Response.status(NOT_ACCEPTABLE).build(); } } catch (Exception e) { return status(BAD_REQUEST).build(); } final String url = data.getFirst("Url"); String method = data.getFirst("Method"); final String status = data.getFirst("Status"); final String fallBackUrl = data.getFirst("FallbackUrl"); String fallBackMethod = data.getFirst("FallbackMethod"); final String statusCallBack = data.getFirst("StatusCallback"); String statusCallbackMethod = data.getFirst("StatusCallbackMethod"); //Restcomm- Move connected call leg (if exists) to the new URL Boolean moveConnectedCallLeg = Boolean.valueOf(data.getFirst("MoveConnectedCallLeg")); Boolean mute = Boolean.valueOf(data.getFirst("Mute")); String callPath = null; final ActorRef call; final CallInfo callInfo; try { callPath = cdr.getCallPath(); Future<Object> future = (Future<Object>) ask(callManager, new GetCall(callPath), expires); call = (ActorRef) Await.result(future, Duration.create(10, TimeUnit.SECONDS)); future = (Future<Object>) ask(call, new GetCallInfo(), expires); CallResponse<CallInfo> response = (CallResponse<CallInfo>) Await.result(future, Duration.create(10, TimeUnit.SECONDS)); callInfo = response.get(); } catch (AskTimeoutException ate) { final String msg = "Call is already completed."; if (logger.isDebugEnabled()) logger.debug("Modify Call LCM for call sid:" + callSid + " AskTimeout while getting call: " + callPath + " restcomm will send " + GONE + " with msg: " + msg); return status(GONE).entity(msg).build(); } catch (Exception exception) { logger.error("Exception while trying to update call callPath: " + callPath + " callSid: " + callSid, exception); return status(INTERNAL_SERVER_ERROR).entity(exception.getMessage()).build(); } if (method == null) method = "POST"; if (url == null && status == null && mute == null) { // Throw exception. We can either redirect a running call using Url or change the state of a Call with Status final String errorMessage = "You can either redirect a running call using \"Url\" or change the state of a Call with \"Status\" or mute a call using \"Mute=true\""; return status(javax.ws.rs.core.Response.Status.CONFLICT).entity(errorMessage).build(); } // Modify state of a call if (status != null) { if (status.equalsIgnoreCase("canceled")) { if (callInfo.state().name().equalsIgnoreCase("queued") || callInfo.state().name().equalsIgnoreCase("ringing")) { if (call != null) { call.tell(new Hangup(), null); } } else if (callInfo.state().name().equalsIgnoreCase("wait_for_answer")) { // We can cancel Wait For Answer calls if (call != null) { call.tell(new Hangup(SipServletResponse.SC_REQUEST_TERMINATED), null); } } else { // Do Nothing. We can only cancel Queued or Ringing calls } } if (status.equalsIgnoreCase("completed")) { // Specifying "completed" will attempt to hang up a call even if it's already in progress. if (call != null) { call.tell(new Hangup(SipServletResponse.SC_REQUEST_TERMINATED), null); } } } if (mute != null && call != null) { try { CallsUtil.muteUnmuteCall(mute, callInfo, call, cdr, dao); } catch (Exception exception) { return status(INTERNAL_SERVER_ERROR).entity(exception.getMessage()).build(); } } if (url != null && call != null) { try { final String version = getApiVersion(data); final URI uri = (new URL(url)).toURI(); URI fallbackUri = (fallBackUrl != null) ? (new URL(fallBackUrl)).toURI() : null; fallBackMethod = (fallBackMethod == null) ? "POST" : fallBackMethod; URI callbackUri = (statusCallBack != null) ? (new URL(statusCallBack)).toURI() : null; statusCallbackMethod = (statusCallbackMethod == null) ? "POST" : statusCallbackMethod; final UpdateCallScript update = new UpdateCallScript(call, accountSid, version, uri, method, fallbackUri, fallBackMethod, callbackUri, statusCallbackMethod, moveConnectedCallLeg); callManager.tell(update, null); } catch (Exception exception) { return status(INTERNAL_SERVER_ERROR).entity(exception.getMessage()).build(); } } else { if (logger.isInfoEnabled()) { if (url == null) { logger.info("Problem during Call Update, Url is null. Make sure you provide Url parameter"); } if (call == null) { logger.info("Problem during Call update, Call is null. Make sure you provide the proper Call SID"); } } } if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(cdr), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { return ok(xstream.toXML(new RestCommResponse(cdr)), APPLICATION_XML).build(); } else { return null; } } private Integer getTimeout(final MultivaluedMap<String, String> data) { Integer result = 60; if (data.containsKey("Timeout")) { result = Integer.parseInt(data.getFirst("Timeout")); } return result; } private void validate(final MultivaluedMap<String, String> data) throws NullPointerException { if (!data.containsKey("From")) { throw new NullPointerException("From can not be null."); } else if (!data.containsKey("To")) { throw new NullPointerException("To can not be null."); } else if (!data.containsKey("Url")) { throw new NullPointerException("Url can not be null."); } } protected Response getRecordingsByCall(final String accountSid, final String callSid, final MediaType responseType, UserIdentityContext userIdentityContext) { permissionEvaluator.secure(accountsDao.getAccount(accountSid), "RestComm:Read:Recordings", userIdentityContext); final List<Recording> recordings = recordingsDao.getRecordingsByCall(new Sid(callSid)); if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(recordings), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(new RecordingList(recordings)); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } @Path("/{sid}") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getCallAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getCall(accountSid, sid, retrieveMediaType(accept), ContextUtil.convert(sec)); } // Issue 153: https://bitbucket.org/telestax/telscale-restcomm/issue/153 // Issue 110: https://bitbucket.org/telestax/telscale-restcomm/issue/110 @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getCalls(@PathParam("accountSid") final String accountSid, @Context UriInfo info, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getCalls(accountSid, info, retrieveMediaType(accept), ContextUtil.convert(sec)); } @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response putCall(@PathParam("accountSid") final String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return putCall(accountSid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } // Issue 139: https://bitbucket.org/telestax/telscale-restcomm/issue/139 @Path("/{sid}") @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response modifyCall(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return updateCall(accountSid, sid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } @GET @Path("/{callSid}/Recordings") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getRecordingsByCallXml(@PathParam("accountSid") String accountSid, @PathParam("callSid") String callSid, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getRecordingsByCall(accountSid, callSid, retrieveMediaType(accept), ContextUtil.convert(sec)); } }
40,705
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
VersionEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/VersionEndpoint.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2013, Telestax Inc and individual contributors * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.connect.http; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.*; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.ok; import javax.ws.rs.core.SecurityContext; import org.apache.commons.configuration.Configuration; import org.apache.log4j.Logger; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.VersionEntity; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.dao.AccountsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.UsageDao; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.http.converter.RestCommResponseConverter; import org.restcomm.connect.http.converter.VersionConverter; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.identity.UserIdentityContext; /** * @author <a href="mailto:[email protected]">gvagenas</a> * */ @Path("/Accounts/{accountSid}/Version") @ThreadSafe @Singleton public class VersionEndpoint extends AbstractEndpoint { private static Logger logger = Logger.getLogger(VersionEndpoint.class); @Context private ServletContext context; private Configuration configuration; private UsageDao dao; private Gson gson; private XStream xstream; private AccountsDao accountsDao; @PostConstruct public void init() { final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); configuration = (Configuration) context.getAttribute(Configuration.class.getName()); configuration = configuration.subset("runtime-settings"); super.init(configuration); dao = storage.getUsageDao(); accountsDao = storage.getAccountsDao(); final VersionConverter converter = new VersionConverter(configuration); final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(VersionEntity.class, converter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(new RestCommResponseConverter(configuration)); } protected Response getVersion(final String accountSid, final MediaType mediaType, UserIdentityContext userIdentityContext ) { permissionEvaluator.secure(accountsDao.getAccount(accountSid), "RestComm:Read:Usage", userIdentityContext); VersionEntity versionEntity = Version.getVersionEntity(); if (versionEntity != null) { if (APPLICATION_XML_TYPE == mediaType) { final RestCommResponse response = new RestCommResponse(versionEntity); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE == mediaType) { Response response = ok(gson.toJson(versionEntity), APPLICATION_JSON).build(); if(logger.isDebugEnabled()){ logger.debug("Supervisor endpoint response: "+gson.toJson(versionEntity)); } return response; } else { return null; } } else { return null; } } @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getVersion(@PathParam("accountSid") final String accountSid, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getVersion(accountSid, retrieveMediaType(accept), ContextUtil.convert(sec)); } }
5,117
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
IncomingPhoneNumbersEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/IncomingPhoneNumbersEndpoint.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.restcomm.connect.http; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.NumberParseException.ErrorType; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat; import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber; import com.sun.jersey.spi.container.ResourceFilters; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import java.net.URI; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.annotation.security.RolesAllowed; import javax.servlet.ServletContext; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.MediaType.APPLICATION_XML_TYPE; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.Status.FORBIDDEN; import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.Status.OK; import static javax.ws.rs.core.Response.noContent; import static javax.ws.rs.core.Response.ok; import static javax.ws.rs.core.Response.status; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import org.apache.commons.configuration.Configuration; import org.joda.time.DateTime; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.commons.loader.ObjectInstantiationException; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.IncomingPhoneNumbersDao; import org.restcomm.connect.dao.OrganizationsDao; import org.restcomm.connect.dao.common.Sorting; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.IncomingPhoneNumber; import org.restcomm.connect.dao.entities.IncomingPhoneNumberFilter; import org.restcomm.connect.dao.entities.IncomingPhoneNumberList; import org.restcomm.connect.dao.entities.Organization; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.dao.entities.SearchFilterMode; import org.restcomm.connect.extension.api.ApiRequest; import org.restcomm.connect.http.converter.AvailableCountriesConverter; import org.restcomm.connect.http.converter.AvailableCountriesList; import org.restcomm.connect.http.converter.IncomingPhoneNumberConverter; import org.restcomm.connect.http.converter.IncomingPhoneNumberListConverter; import org.restcomm.connect.http.converter.RestCommResponseConverter; import org.restcomm.connect.http.filters.ExtensionFilter; import static org.restcomm.connect.http.security.AccountPrincipal.SUPER_ADMIN_ROLE; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.http.security.PermissionEvaluator.SecuredType; import org.restcomm.connect.identity.UserIdentityContext; import org.restcomm.connect.provisioning.number.api.PhoneNumberParameters; import org.restcomm.connect.provisioning.number.api.PhoneNumberProvisioningManager; import org.restcomm.connect.provisioning.number.api.PhoneNumberProvisioningManagerProvider; import org.restcomm.connect.provisioning.number.api.PhoneNumberType; /** * @author [email protected] (Thomas Quintana) * @author [email protected] * @author [email protected] * @author [email protected] */ @Path("/Accounts/{accountSid}/IncomingPhoneNumbers") @ThreadSafe @Singleton public class IncomingPhoneNumbersEndpoint extends AbstractEndpoint { private static final String PHONE_NUMER_PARAM = "PhoneNumber"; private static final String FRIENDLY_NAME_PARAM = "FriendlyName"; @Context private ServletContext context; private PhoneNumberProvisioningManager phoneNumberProvisioningManager; private IncomingPhoneNumberListConverter listConverter; PhoneNumberParameters phoneNumberParameters; String callbackPort = ""; private IncomingPhoneNumbersDao dao; private OrganizationsDao organizationsDao; private XStream xstream; private Gson gson; public IncomingPhoneNumbersEndpoint() { super(); } @PostConstruct public void init() throws ObjectInstantiationException { final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); configuration = (Configuration) context.getAttribute(Configuration.class.getName()); super.init(configuration.subset("runtime-settings")); dao = storage.getIncomingPhoneNumbersDao(); accountsDao = storage.getAccountsDao(); organizationsDao = storage.getOrganizationsDao(); /* phoneNumberProvisioningManager = (PhoneNumberProvisioningManager) context.getAttribute("PhoneNumberProvisioningManager"); if(phoneNumberProvisioningManager == null) { final String phoneNumberProvisioningManagerClass = configuration.getString("phone-number-provisioning[@class]"); Configuration phoneNumberProvisioningConfiguration = configuration.subset("phone-number-provisioning"); Configuration telestaxProxyConfiguration = configuration.subset("runtime-settings").subset("telestax-proxy"); phoneNumberProvisioningManager = (PhoneNumberProvisioningManager) new ObjectFactory(getClass().getClassLoader()) .getObjectInstance(phoneNumberProvisioningManagerClass); ContainerConfiguration containerConfiguration = new ContainerConfiguration(getOutboundInterfaces()); phoneNumberProvisioningManager.init(phoneNumberProvisioningConfiguration, telestaxProxyConfiguration, containerConfiguration); context.setAttribute("phoneNumberProvisioningManager", phoneNumberProvisioningManager); } */ // get manager from context or create it if it does not exist phoneNumberProvisioningManager = new PhoneNumberProvisioningManagerProvider(configuration, context).get(); Configuration callbackUrlsConfiguration = configuration.subset("phone-number-provisioning").subset("callback-urls"); String voiceUrl = callbackUrlsConfiguration.getString("voice[@url]"); if (voiceUrl != null && !voiceUrl.trim().isEmpty()) { String[] voiceUrlArr = voiceUrl.split(":"); if (voiceUrlArr != null && voiceUrlArr.length == 2) { callbackPort = voiceUrlArr[1]; } } phoneNumberParameters = new PhoneNumberParameters( voiceUrl, callbackUrlsConfiguration.getString("voice[@method]"), false, callbackUrlsConfiguration.getString("sms[@url]"), callbackUrlsConfiguration.getString("sms[@method]"), callbackUrlsConfiguration.getString("fax[@url]"), callbackUrlsConfiguration.getString("fax[@method]"), callbackUrlsConfiguration.getString("ussd[@url]"), callbackUrlsConfiguration.getString("ussd[@method]")); final IncomingPhoneNumberConverter converter = new IncomingPhoneNumberConverter(configuration); listConverter = new IncomingPhoneNumberListConverter(configuration); final GsonBuilder builder = new GsonBuilder(); builder.serializeNulls(); builder.registerTypeAdapter(IncomingPhoneNumber.class, converter); builder.registerTypeAdapter(IncomingPhoneNumberList.class, listConverter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(listConverter); xstream.registerConverter(new AvailableCountriesConverter(configuration)); xstream.registerConverter(new RestCommResponseConverter(configuration)); } private IncomingPhoneNumber createFrom(final Sid accountSid, final MultivaluedMap<String, String> data, Sid organizationSid) { final IncomingPhoneNumber.Builder builder = IncomingPhoneNumber.builder(); final Sid sid = Sid.generate(Sid.Type.PHONE_NUMBER); builder.setSid(sid); builder.setAccountSid(accountSid); String phoneNumber = data.getFirst(PHONE_NUMER_PARAM); String cost = data.getFirst("Cost"); builder.setPhoneNumber(phoneNumber); builder.setFriendlyName(getFriendlyName(phoneNumber, data)); if (data.containsKey("VoiceCapable")) { builder.setVoiceCapable(Boolean.parseBoolean(data.getFirst("VoiceCapable"))); } if (data.containsKey("SmsCapable")) { builder.setSmsCapable(Boolean.parseBoolean(data.getFirst("SmsCapable"))); } if (data.containsKey("MmsCapable")) { builder.setMmsCapable(Boolean.parseBoolean(data.getFirst("MmsCapable"))); } if (data.containsKey("FaxCapable")) { builder.setFaxCapable(Boolean.parseBoolean(data.getFirst("FaxCapable"))); } if (data.containsKey("isSIP")) { builder.setPureSip(Boolean.parseBoolean(data.getFirst("isSIP"))); } else { builder.setPureSip(false); } final String apiVersion = getApiVersion(data); builder.setApiVersion(apiVersion); builder.setVoiceUrl(getUrl("VoiceUrl", data)); builder.setVoiceMethod(getMethod("VoiceMethod", data)); builder.setVoiceFallbackUrl(getUrl("VoiceFallbackUrl", data)); builder.setVoiceFallbackMethod(getMethod("VoiceFallbackMethod", data)); builder.setStatusCallback(getUrl("StatusCallback", data)); builder.setStatusCallbackMethod(getMethod("StatusCallbackMethod", data)); builder.setHasVoiceCallerIdLookup(getHasVoiceCallerIdLookup(data)); builder.setVoiceApplicationSid(getSid("VoiceApplicationSid", data)); builder.setSmsUrl(getUrl("SmsUrl", data)); builder.setSmsMethod(getMethod("SmsMethod", data)); builder.setSmsFallbackUrl(getUrl("SmsFallbackUrl", data)); builder.setSmsFallbackMethod(getMethod("SmsFallbackMethod", data)); builder.setSmsApplicationSid(getSid("SmsApplicationSid", data)); builder.setUssdUrl(getUrl("UssdUrl", data)); builder.setUssdMethod(getMethod("UssdMethod", data)); builder.setUssdFallbackUrl(getUrl("UssdFallbackUrl", data)); builder.setUssdFallbackMethod(getMethod("UssdFallbackMethod", data)); builder.setUssdApplicationSid(getSid("UssdApplicationSid", data)); builder.setReferUrl(getUrl("ReferUrl", data)); builder.setReferMethod(getMethod("ReferMethod", data)); builder.setReferApplicationSid(getSid("ReferApplicationSid", data)); builder.setOrganizationSid(organizationSid); final Configuration configuration = this.configuration.subset("runtime-settings"); final StringBuilder buffer = new StringBuilder(); buffer.append("/").append(apiVersion).append("/Accounts/").append(accountSid.toString()) .append("/IncomingPhoneNumbers/").append(sid.toString()); builder.setUri(URI.create(buffer.toString())); return builder.build(); } private String e164(String number) throws NumberParseException { final PhoneNumberUtil numbersUtil = PhoneNumberUtil.getInstance(); if (!number.startsWith("+")) { number = "+" + number; } final PhoneNumber result = numbersUtil.parse(number, "US"); if (numbersUtil.isValidNumber(result)) { return numbersUtil.format(result, PhoneNumberFormat.E164); } else { throw new NumberParseException(ErrorType.NOT_A_NUMBER, "This is not a valid number"); } } private String getFriendlyName(final String phoneNumber, final MultivaluedMap<String, String> data) { String friendlyName = phoneNumber; if (data.containsKey(FRIENDLY_NAME_PARAM)) { friendlyName = data.getFirst(FRIENDLY_NAME_PARAM); } return friendlyName; } protected Response getIncomingPhoneNumber(final String accountSid, final String sid, final MediaType responseType, UserIdentityContext userIdentityContext) { Account operatedAccount = accountsDao.getAccount(accountSid); permissionEvaluator.secure(operatedAccount, "RestComm:Read:IncomingPhoneNumbers", userIdentityContext); try { final IncomingPhoneNumber incomingPhoneNumber = dao.getIncomingPhoneNumber(new Sid(sid)); if (incomingPhoneNumber == null) { return status(NOT_FOUND).build(); } else { // if the account that the resource belongs to does not existb while the resource does, we're having BAD parameters if (operatedAccount == null) { return status(BAD_REQUEST).build(); } permissionEvaluator.secure(operatedAccount, incomingPhoneNumber.getAccountSid(), SecuredType.SECURED_STANDARD, userIdentityContext); if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(incomingPhoneNumber), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(incomingPhoneNumber); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } } catch (Exception e) { logger.error("Exception while performing getIncomingPhoneNumber: ", e); return status(INTERNAL_SERVER_ERROR).build(); } } protected Response getAvailableCountries(final String accountSid, final MediaType responseType, UserIdentityContext userIdentityContext) { permissionEvaluator.secure(accountsDao.getAccount(accountSid), "RestComm:Read:IncomingPhoneNumbers", userIdentityContext); List<String> countries = phoneNumberProvisioningManager.getAvailableCountries(); if (countries == null) { countries = new ArrayList<String>(); countries.add("US"); } if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(countries), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(new AvailableCountriesList(countries)); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } protected Response getIncomingPhoneNumbers(final String accountSid, final PhoneNumberType phoneNumberType, UriInfo info, final MediaType responseType, UserIdentityContext userIdentityContext) { permissionEvaluator.secure(accountsDao.getAccount(accountSid), "RestComm:Read:IncomingPhoneNumbers", userIdentityContext); try { String phoneNumberFilter = info.getQueryParameters().getFirst(PHONE_NUMER_PARAM); String friendlyNameFilter = info.getQueryParameters().getFirst(FRIENDLY_NAME_PARAM); String page = info.getQueryParameters().getFirst("Page"); String reverse = info.getQueryParameters().getFirst("Reverse"); String pageSize = info.getQueryParameters().getFirst("PageSize"); String sortBy = info.getQueryParameters().getFirst("SortBy"); pageSize = (pageSize == null) ? "50" : pageSize; page = (page == null) ? "0" : page; Sorting.Direction direction = (reverse != null && "true".equalsIgnoreCase(reverse)) ? Sorting.Direction.DESC : Sorting.Direction.ASC; sortBy = (sortBy != null) ? sortBy : PHONE_NUMER_PARAM; int limit = Integer.parseInt(pageSize); int pageAsInt = Integer.parseInt(page); int offset = (page == "0") ? 0 : (((pageAsInt - 1) * limit) + limit); IncomingPhoneNumberFilter.Builder filterBuilder = IncomingPhoneNumberFilter.Builder.builder(); filterBuilder.byAccountSid(accountSid); filterBuilder.byFriendlyName(friendlyNameFilter); filterBuilder.byPhoneNumber(phoneNumberFilter); filterBuilder.usingMode(SearchFilterMode.WILDCARD_MATCH); final int total = dao.getTotalIncomingPhoneNumbers(filterBuilder.build()); if (pageAsInt > (total / limit)) { return status(javax.ws.rs.core.Response.Status.BAD_REQUEST).build(); } filterBuilder.byAccountSid(accountSid); filterBuilder.byFriendlyName(friendlyNameFilter); filterBuilder.byPhoneNumber(phoneNumberFilter); if (PHONE_NUMER_PARAM.equals(sortBy)) { filterBuilder.sortedByPhoneNumber(direction); } if (FRIENDLY_NAME_PARAM.equals(sortBy)) { filterBuilder.sortedByfriendly(direction); } filterBuilder.limited(limit, offset); filterBuilder.usingMode(SearchFilterMode.WILDCARD_MATCH); final List<IncomingPhoneNumber> incomingPhoneNumbers = dao.getIncomingPhoneNumbersByFilter(filterBuilder.build()); listConverter.setCount(total); listConverter.setPage(pageAsInt); listConverter.setPageSize(limit); listConverter.setPathUri("/" + getApiVersion(null) + "/" + info.getPath()); if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(new IncomingPhoneNumberList(incomingPhoneNumbers)), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(new IncomingPhoneNumberList(incomingPhoneNumbers)); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } catch (Exception e) { logger.error("Exception while performing getIncomingPhoneNumbers: ", e); return status(INTERNAL_SERVER_ERROR).build(); } } protected Response putIncomingPhoneNumber(final String accountSid, final MultivaluedMap<String, String> data, PhoneNumberType phoneNumberType, final MediaType responseType, UserIdentityContext userIdentityContext) { Account account = accountsDao.getAccount(accountSid); permissionEvaluator.secure(account, "RestComm:Create:IncomingPhoneNumbers", userIdentityContext); try { validate(data); } catch (final NullPointerException exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } try { String number = data.getFirst(PHONE_NUMER_PARAM); String isSIP = data.getFirst("isSIP"); // cater to SIP numbers if (isSIP == null) { try { number = e164(number); } catch (NumberParseException e) { } } Boolean isSip = Boolean.parseBoolean(isSIP); Boolean available = true; IncomingPhoneNumberFilter.Builder filterBuilder = IncomingPhoneNumberFilter.Builder.builder(); filterBuilder.byPhoneNumber(number); List<IncomingPhoneNumber> incomingPhoneNumbers = dao.getIncomingPhoneNumbersByFilter(filterBuilder.build()); /* check if number is occupied by same organization or different. * if it is occupied by different organization then we can add it in current. * but it has to be pure sip as provider numbers must be unique even across organizations. * https://github.com/RestComm/Restcomm-Connect/issues/2073 */ if (incomingPhoneNumbers != null && !incomingPhoneNumbers.isEmpty()) { if (!isSip) { //provider numbers must be unique even across organizations. available = false; } else { for (IncomingPhoneNumber incomingPhoneNumber : incomingPhoneNumbers) { if (incomingPhoneNumber.getOrganizationSid().equals(account.getOrganizationSid())) { available = false; } } } } if (available) { IncomingPhoneNumber incomingPhoneNumber = createFrom(new Sid(accountSid), data, account.getOrganizationSid()); String domainName = organizationsDao.getOrganization(account.getOrganizationSid()).getDomainName(); phoneNumberParameters.setVoiceUrl((callbackPort == null || callbackPort.trim().isEmpty()) ? domainName : domainName + ":" + callbackPort); phoneNumberParameters.setPhoneNumberType(phoneNumberType); org.restcomm.connect.provisioning.number.api.PhoneNumber phoneNumber = convertIncomingPhoneNumbertoPhoneNumber(incomingPhoneNumber); boolean hasSuceeded = false; boolean allowed = true; if (phoneNumberProvisioningManager != null && isSIP == null) { ApiRequest apiRequest = new ApiRequest(accountSid, data, ApiRequest.Type.INCOMINGPHONENUMBER); //Before proceed to buy the DID, check with the extensions if the purchase is allowed or not if (executePreApiAction(apiRequest)) { if (logger.isDebugEnabled()) { logger.debug("buyNumber " + phoneNumber + " phoneNumberParameters: " + phoneNumberParameters); } hasSuceeded = phoneNumberProvisioningManager.buyNumber(phoneNumber, phoneNumberParameters); } else { //Extensions didn't allowed this API action allowed = false; if (logger.isInfoEnabled()) { logger.info("DID purchase is now allowed for this account"); } } executePostApiAction(apiRequest); //If Extension blocked the request, return the proper error response if (!allowed) { String msg = "DID purchase is now allowed for this account"; String error = "DID_QUOTA_EXCEEDED"; return status(FORBIDDEN).entity(buildErrorResponseBody(msg, error, responseType)).build(); } } else if (isSIP != null) { hasSuceeded = true; } if (hasSuceeded) { if (phoneNumber.getFriendlyName() != null) { incomingPhoneNumber.setFriendlyName(phoneNumber.getFriendlyName()); } if (phoneNumber.getPhoneNumber() != null) { incomingPhoneNumber.setPhoneNumber(phoneNumber.getPhoneNumber()); } dao.addIncomingPhoneNumber(incomingPhoneNumber); if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(incomingPhoneNumber), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(incomingPhoneNumber); return ok(xstream.toXML(response), APPLICATION_XML).build(); } } } return status(BAD_REQUEST).entity("21452").build(); } catch (Exception e) { logger.error("Exception while performing putIncomingPhoneNumber: ", e); return status(INTERNAL_SERVER_ERROR).build(); } } public Response updateIncomingPhoneNumber(final String accountSid, final String sid, final MultivaluedMap<String, String> data, final MediaType responseType, UserIdentityContext userIdentityContext) { Account operatedAccount = accountsDao.getAccount(accountSid); permissionEvaluator.secure(operatedAccount, "RestComm:Modify:IncomingPhoneNumbers", userIdentityContext); try { final IncomingPhoneNumber incomingPhoneNumber = dao.getIncomingPhoneNumber(new Sid(sid)); if (incomingPhoneNumber == null) { return status(NOT_FOUND).build(); } permissionEvaluator.secure(operatedAccount, incomingPhoneNumber.getAccountSid(), SecuredType.SECURED_STANDARD, userIdentityContext); boolean updated = true; updated = updateNumberAtPhoneNumberProvisioningManager(incomingPhoneNumber, organizationsDao.getOrganization(operatedAccount.getOrganizationSid())); if (updated) { dao.updateIncomingPhoneNumber(update(incomingPhoneNumber, data)); if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(incomingPhoneNumber), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(incomingPhoneNumber); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } return status(BAD_REQUEST).entity("21452").build(); } catch (Exception e) { logger.error("Exception while performing updateIncomingPhoneNumber: ", e); return status(INTERNAL_SERVER_ERROR).build(); } } private void validate(final MultivaluedMap<String, String> data) throws RuntimeException { if (!data.containsKey(PHONE_NUMER_PARAM) && !data.containsKey("AreaCode")) { throw new NullPointerException("Phone number can not be null."); } } private IncomingPhoneNumber update(final IncomingPhoneNumber incomingPhoneNumber, final MultivaluedMap<String, String> data) { if (data.containsKey("ApiVersion")) { incomingPhoneNumber.setApiVersion(getApiVersion(data)); } if (data.containsKey(FRIENDLY_NAME_PARAM)) { incomingPhoneNumber.setFriendlyName(data.getFirst(FRIENDLY_NAME_PARAM)); } if (data.containsKey("VoiceUrl")) { // for all values that qualify as 'empty' populate property with null URI uri = getUrl("VoiceUrl", data); incomingPhoneNumber.setVoiceUrl(isEmpty(uri.toString()) ? null : uri); } if (data.containsKey("VoiceMethod")) { incomingPhoneNumber.setVoiceMethod(getMethod("VoiceMethod", data)); } if (data.containsKey("VoiceFallbackUrl")) { URI uri = getUrl("VoiceFallbackUrl", data); incomingPhoneNumber.setVoiceFallbackUrl(isEmpty(uri.toString()) ? null : uri); } if (data.containsKey("VoiceFallbackMethod")) { incomingPhoneNumber.setVoiceFallbackMethod(getMethod("VoiceFallbackMethod", data)); } if (data.containsKey("StatusCallback")) { URI uri = getUrl("StatusCallback", data); incomingPhoneNumber.setStatusCallback(isEmpty(uri.toString()) ? null : uri); } if (data.containsKey("StatusCallbackMethod")) { incomingPhoneNumber.setStatusCallbackMethod(getMethod("StatusCallbackMethod", data)); } if (data.containsKey("VoiceCallerIdLookup")) { incomingPhoneNumber.setHasVoiceCallerIdLookup(getHasVoiceCallerIdLookup(data)); } if (data.containsKey("VoiceApplicationSid")) { if (org.apache.commons.lang.StringUtils.isEmpty(data.getFirst("VoiceApplicationSid"))) { incomingPhoneNumber.setVoiceApplicationSid(null); } else { incomingPhoneNumber.setVoiceApplicationSid(getSid("VoiceApplicationSid", data)); } } if (data.containsKey("SmsUrl")) { URI uri = getUrl("SmsUrl", data); incomingPhoneNumber.setSmsUrl(isEmpty(uri.toString()) ? null : uri); } if (data.containsKey("SmsMethod")) { incomingPhoneNumber.setSmsMethod(getMethod("SmsMethod", data)); } if (data.containsKey("SmsFallbackUrl")) { URI uri = getUrl("SmsFallbackUrl", data); incomingPhoneNumber.setSmsFallbackUrl(isEmpty(uri.toString()) ? null : uri); } if (data.containsKey("SmsFallbackMethod")) { incomingPhoneNumber.setSmsFallbackMethod(getMethod("SmsFallbackMethod", data)); } if (data.containsKey("SmsApplicationSid")) { if (org.apache.commons.lang.StringUtils.isEmpty(data.getFirst("SmsApplicationSid"))) { incomingPhoneNumber.setSmsApplicationSid(null); } else { incomingPhoneNumber.setSmsApplicationSid(getSid("SmsApplicationSid", data)); } } if (data.containsKey("ReferUrl")) { URI uri = getUrl("ReferUrl", data); incomingPhoneNumber.setReferUrl(isEmpty(uri.toString()) ? null : uri); } if (data.containsKey("ReferMethod")) { incomingPhoneNumber.setReferMethod(getMethod("ReferMethod", data)); } if (data.containsKey("ReferApplicationSid")) { if (org.apache.commons.lang.StringUtils.isEmpty(data.getFirst("ReferApplicationSid"))) { incomingPhoneNumber.setReferApplicationSid(null); } else { incomingPhoneNumber.setReferApplicationSid(getSid("ReferApplicationSid", data)); } } if (data.containsKey("VoiceCapable")) { incomingPhoneNumber.setVoiceCapable(Boolean.parseBoolean(data.getFirst("VoiceCapable"))); } if (data.containsKey("VoiceCapable")) { incomingPhoneNumber.setVoiceCapable(Boolean.parseBoolean(data.getFirst("VoiceCapable"))); } if (data.containsKey("SmsCapable")) { incomingPhoneNumber.setSmsCapable(Boolean.parseBoolean(data.getFirst("SmsCapable"))); } if (data.containsKey("MmsCapable")) { incomingPhoneNumber.setMmsCapable(Boolean.parseBoolean(data.getFirst("MmsCapable"))); } if (data.containsKey("FaxCapable")) { incomingPhoneNumber.setFaxCapable(Boolean.parseBoolean(data.getFirst("FaxCapable"))); } if (data.containsKey("UssdUrl")) { URI uri = getUrl("UssdUrl", data); incomingPhoneNumber.setUssdUrl(isEmpty(uri.toString()) ? null : uri); } if (data.containsKey("UssdMethod")) { incomingPhoneNumber.setUssdMethod(getMethod("UssdMethod", data)); } if (data.containsKey("UssdFallbackUrl")) { URI uri = getUrl("UssdFallbackUrl", data); incomingPhoneNumber.setUssdFallbackUrl(isEmpty(uri.toString()) ? null : uri); } if (data.containsKey("UssdFallbackMethod")) { incomingPhoneNumber.setUssdFallbackMethod(getMethod("UssdFallbackMethod", data)); } if (data.containsKey("UssdApplicationSid")) { if (org.apache.commons.lang.StringUtils.isEmpty(data.getFirst("UssdApplicationSid"))) { incomingPhoneNumber.setUssdApplicationSid(null); } else { incomingPhoneNumber.setUssdApplicationSid(getSid("UssdApplicationSid", data)); } } incomingPhoneNumber.setDateUpdated(DateTime.now()); return incomingPhoneNumber; } public Response deleteIncomingPhoneNumber(final String accountSid, final String sid, UserIdentityContext userIdentityContext) { Account operatedAccount = accountsDao.getAccount(accountSid); permissionEvaluator.secure(operatedAccount, "RestComm:Delete:IncomingPhoneNumbers", userIdentityContext); try { final IncomingPhoneNumber incomingPhoneNumber = dao.getIncomingPhoneNumber(new Sid(sid)); if (incomingPhoneNumber == null) { return status(NOT_FOUND).build(); } permissionEvaluator.secure(operatedAccount, incomingPhoneNumber.getAccountSid(), SecuredType.SECURED_STANDARD, userIdentityContext); if (phoneNumberProvisioningManager != null && (incomingPhoneNumber.isPureSip() == null || !incomingPhoneNumber.isPureSip())) { phoneNumberProvisioningManager.cancelNumber(convertIncomingPhoneNumbertoPhoneNumber(incomingPhoneNumber)); } dao.removeIncomingPhoneNumber(new Sid(sid)); return noContent().build(); } catch (Exception e) { logger.error("Exception while performing deleteIncomingPhoneNumber: ", e); return status(INTERNAL_SERVER_ERROR).build(); } } /* @SuppressWarnings("unchecked") private List<SipURI> getOutboundInterfaces() { final List<SipURI> uris = (List<SipURI>) context.getAttribute(SipServlet.OUTBOUND_INTERFACES); return uris; } */ public static org.restcomm.connect.provisioning.number.api.PhoneNumber convertIncomingPhoneNumbertoPhoneNumber(IncomingPhoneNumber incomingPhoneNumber) { return new org.restcomm.connect.provisioning.number.api.PhoneNumber( incomingPhoneNumber.getFriendlyName(), incomingPhoneNumber.getPhoneNumber(), null, null, null, null, null, null, null, null, incomingPhoneNumber.isVoiceCapable(), incomingPhoneNumber.isSmsCapable(), incomingPhoneNumber.isMmsCapable(), incomingPhoneNumber.isFaxCapable(), false); } /** * @param targetAccountSid * @param data * @param responseType * @return */ protected Response migrateIncomingPhoneNumbers(String targetAccountSid, MultivaluedMap<String, String> data, MediaType responseType, UserIdentityContext userIdentityContext) { Account effectiveAccount = userIdentityContext.getEffectiveAccount(); permissionEvaluator.secure(effectiveAccount, "RestComm:Modify:IncomingPhoneNumbers", userIdentityContext); try { Account targetAccount = accountsDao.getAccount(targetAccountSid); // this is to avoid if mistakenly provided super admin account as targetAccountSid // if this check is not in place and someone mistakenly provided super admin // then all accounts and sub account in platform will be impacted if (targetAccount == null) { return status(NOT_FOUND).entity("Account not found").build(); } if (targetAccount.getParentSid() == null) { return status(BAD_REQUEST).entity("Super Admin account numbers can not be migrated. Please provide a valid account sid").build(); } else { String organizationSidStr = data.getFirst("OrganizationSid"); if (organizationSidStr == null) { return status(BAD_REQUEST).entity("OrganizationSid cannot be null").build(); } Sid organizationSid = null; try { organizationSid = new Sid(organizationSidStr); } catch (IllegalArgumentException iae) { return status(BAD_REQUEST).entity("OrganizationSid is not valid").build(); } Organization destinationOrganization = organizationsDao.getOrganization(organizationSid); if (destinationOrganization == null) { return status(NOT_FOUND).entity("Destination organization not found").build(); } migrateNumbersFromAccountTree(targetAccount, destinationOrganization); return status(OK).build(); } } catch (Exception e) { logger.error("Exception while performing migrateIncomingPhoneNumbers: ", e); return status(INTERNAL_SERVER_ERROR).build(); } } /** * @param targetAccount * @param destinationOrganization */ private void migrateNumbersFromAccountTree(Account targetAccount, Organization destinationOrganization) { List<String> subAccountsToClose = accountsDao.getSubAccountSidsRecursive(targetAccount.getSid()); if (subAccountsToClose != null && !subAccountsToClose.isEmpty()) { int i = subAccountsToClose.size(); // is is the count of accounts left to process // we iterate backwards to handle child account numbers first, parent account's numbers next while (i > 0) { i--; String migrateSid = subAccountsToClose.get(i); try { Account subAccount = accountsDao.getAccount(new Sid(migrateSid)); migrateSingleAccountNumbers(subAccount, destinationOrganization); } catch (Exception e) { // if anything bad happens, log the error and continue migrating the rest of the accounts numbers. logger.error("Failed migrating (child) account's numbers: account sid '" + migrateSid + "'"); } } } // migrate parent account numbers too migrateSingleAccountNumbers(targetAccount, destinationOrganization); } /** * @param account * @param destinationOrganization */ private void migrateSingleAccountNumbers(Account account, Organization destinationOrganization) { List<IncomingPhoneNumber> incomingPhoneNumbers = dao.getIncomingPhoneNumbers(account.getSid()); if (incomingPhoneNumbers != null) { for (int i = 0; i < incomingPhoneNumbers.size(); i++) { IncomingPhoneNumber incomingPhoneNumber = incomingPhoneNumbers.get(i); incomingPhoneNumber.setOrganizationSid(destinationOrganization.getSid()); //update organization in db dao.updateIncomingPhoneNumber(incomingPhoneNumber); //update number at provider's end if (!updateNumberAtPhoneNumberProvisioningManager(incomingPhoneNumber, destinationOrganization)) { //if number could not be updated at provider's end, log the error and keep moving to next number. logger.error(String.format("could not update number %s at number provider %s ", incomingPhoneNumber.getPhoneNumber(), phoneNumberProvisioningManager)); } } } } /** * @param incomingPhoneNumber * @param organization * @return */ private boolean updateNumberAtPhoneNumberProvisioningManager(IncomingPhoneNumber incomingPhoneNumber, Organization organization) { if (phoneNumberProvisioningManager != null && (incomingPhoneNumber.isPureSip() == null || !incomingPhoneNumber.isPureSip())) { String domainName = organization.getDomainName(); phoneNumberParameters.setVoiceUrl((callbackPort == null || callbackPort.trim().isEmpty()) ? domainName : domainName + ":" + callbackPort); if (logger.isDebugEnabled()) { logger.debug("updateNumber " + incomingPhoneNumber + " phoneNumberParameters: " + phoneNumberParameters); } return phoneNumberProvisioningManager.updateNumber(convertIncomingPhoneNumbertoPhoneNumber(incomingPhoneNumber), phoneNumberParameters); } return true; } @Path("/{sid}") @DELETE public Response deleteIncomingPhoneNumberAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, @Context SecurityContext sec) { return deleteIncomingPhoneNumber(accountSid, sid, ContextUtil.convert(sec)); } @Path("/{sid}") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getIncomingPhoneNumberAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { MediaType acceptType = retrieveMediaType(accept); return getIncomingPhoneNumber(accountSid, sid, acceptType, ContextUtil.convert(sec)); } @Path("/AvailableCountries") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getAvailableCountriesAsXml(@PathParam("accountSid") final String accountSid, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { MediaType acceptType = retrieveMediaType(accept); return getAvailableCountries(accountSid, acceptType, ContextUtil.convert(sec)); } @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getIncomingPhoneNumbers(@PathParam("accountSid") final String accountSid, @Context UriInfo info, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { MediaType acceptType = retrieveMediaType(accept); return getIncomingPhoneNumbers(accountSid, PhoneNumberType.Global, info, acceptType, ContextUtil.convert(sec)); } @POST @ResourceFilters({ExtensionFilter.class}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response putIncomingPhoneNumber(@PathParam("accountSid") final String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { MediaType acceptType = retrieveMediaType(accept); return putIncomingPhoneNumber(accountSid, data, PhoneNumberType.Global, acceptType, ContextUtil.convert(sec)); } @Path("/{sid}") @PUT @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response updateIncomingPhoneNumberAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { MediaType acceptType = retrieveMediaType(accept); return updateIncomingPhoneNumber(accountSid, sid, data, acceptType, ContextUtil.convert(sec)); } @Path("/{sid}") @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response updateIncomingPhoneNumberAsXmlPost(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { MediaType acceptType = retrieveMediaType(accept); return updateIncomingPhoneNumber(accountSid, sid, data, acceptType, ContextUtil.convert(sec)); } // Local Numbers @Path("/Local") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getIncomingLocalPhoneNumbersAsXml(@PathParam("accountSid") final String accountSid, @Context UriInfo info, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { MediaType acceptType = retrieveMediaType(accept); return getIncomingPhoneNumbers(accountSid, PhoneNumberType.Local, info, acceptType, ContextUtil.convert(sec)); } @Path("/Local") @POST @ResourceFilters({ExtensionFilter.class}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response putIncomingLocalPhoneNumberAsXml(@PathParam("accountSid") final String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { MediaType acceptType = retrieveMediaType(accept); return putIncomingPhoneNumber(accountSid, data, PhoneNumberType.Local, acceptType, ContextUtil.convert(sec)); } // Toll Free Numbers @Path("/TollFree") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getIncomingTollFreePhoneNumbersAsXml(@PathParam("accountSid") final String accountSid, @Context UriInfo info, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { MediaType acceptType = retrieveMediaType(accept); return getIncomingPhoneNumbers(accountSid, PhoneNumberType.TollFree, info, acceptType, ContextUtil.convert(sec)); } @Path("/TollFree") @POST @ResourceFilters({ExtensionFilter.class}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response putIncomingTollFreePhoneNumberAsXml(@PathParam("accountSid") final String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { MediaType acceptType = retrieveMediaType(accept); return putIncomingPhoneNumber(accountSid, data, PhoneNumberType.TollFree, acceptType, ContextUtil.convert(sec)); } // Mobile Numbers @Path("/Mobile") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getIncomingMobilePhoneNumbersAsXml(@PathParam("accountSid") final String accountSid, @Context UriInfo info, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { MediaType acceptType = retrieveMediaType(accept); return getIncomingPhoneNumbers(accountSid, PhoneNumberType.Mobile, info, acceptType, ContextUtil.convert(sec)); } @Path("/Mobile") @POST @ResourceFilters({ExtensionFilter.class}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response putIncomingMobilePhoneNumberAsXml(@PathParam("accountSid") final String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { MediaType acceptType = retrieveMediaType(accept); return putIncomingPhoneNumber(accountSid, data, PhoneNumberType.Mobile, acceptType, ContextUtil.convert(sec)); } @Path("/migrate") @POST @RolesAllowed(SUPER_ADMIN_ROLE) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response migrateIncomingPhoneNumbersAsXml(@PathParam("accountSid") final String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { MediaType acceptType = retrieveMediaType(accept); return migrateIncomingPhoneNumbers(accountSid, data, acceptType, ContextUtil.convert(sec)); } }
50,029
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
EmailMessagesEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/EmailMessagesEndpoint.java
package org.restcomm.connect.http; import akka.actor.Actor; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.UntypedActor; import akka.actor.UntypedActorContext; import akka.actor.UntypedActorFactory; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import javax.annotation.PostConstruct; import javax.mail.internet.ContentType; import javax.mail.internet.ParseException; import javax.servlet.ServletContext; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.*; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR; import static javax.ws.rs.core.Response.ok; import static javax.ws.rs.core.Response.status; import javax.ws.rs.core.SecurityContext; import org.apache.commons.configuration.Configuration; import org.apache.log4j.Logger; import org.joda.time.DateTime; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.commons.patterns.Observe; import org.restcomm.connect.commons.patterns.Observing; import org.restcomm.connect.commons.patterns.StopObserving; import org.restcomm.connect.dao.AccountsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.email.EmailService; import org.restcomm.connect.email.api.EmailRequest; import org.restcomm.connect.email.api.EmailResponse; import org.restcomm.connect.email.api.Mail; import org.restcomm.connect.http.converter.EmailMessageConverter; import org.restcomm.connect.http.converter.RestCommResponseConverter; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.identity.UserIdentityContext; /** * @author lefty [email protected] (Lefteris Banos) */ @Path("/Accounts/{accountSid}/Email/Messages") @ThreadSafe @Singleton public class EmailMessagesEndpoint extends AbstractEndpoint { private static Logger logger = Logger.getLogger(EmailMessagesEndpoint.class); @Context protected ServletContext context; protected ActorSystem system; protected Configuration configuration; protected Configuration confemail; protected Gson gson; protected AccountsDao accountsDao; ActorRef mailerService = null; protected XStream xstream; // Send the email. protected Mail emailMsg; public EmailMessagesEndpoint() { super(); } @PostConstruct public void init() { final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); configuration = (Configuration) context.getAttribute(Configuration.class.getName()); confemail=configuration.subset("smtp-service"); configuration = configuration.subset("runtime-settings"); accountsDao = storage.getAccountsDao(); system = (ActorSystem) context.getAttribute(ActorSystem.class.getName()); super.init(configuration); final EmailMessageConverter converter = new EmailMessageConverter(configuration); final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Mail.class, converter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(new RestCommResponseConverter(configuration)); } private void normalize(final MultivaluedMap<String, String> data) throws IllegalArgumentException { final String from = data.getFirst("From"); data.remove("From"); try { data.putSingle("From", validateEmail(from)); } catch (final InvalidEmailException exception) { throw new IllegalArgumentException(exception); } final String to = data.getFirst("To"); data.remove("To"); try { data.putSingle("To", validateEmail(to)); } catch (final InvalidEmailException exception) { throw new IllegalArgumentException(exception); } final String subject = data.getFirst("Subject"); if (subject.length() > 160) { data.remove("Subject"); data.putSingle("Subject", subject.substring(0, 160)); } if (data.containsKey("Type")) { final String contentType = data.getFirst("Type"); try { ContentType cType = new ContentType(contentType); if (cType.getParameter("charset") == null) { cType.setParameter("charset", "UTF-8"); } data.remove("Type"); data.putSingle("Type", cType.toString()); } catch (ParseException exception) { throw new IllegalArgumentException(exception); } } if (data.containsKey("CC")) { final String cc = data.getFirst("CC"); data.remove("CC"); try { data.putSingle("CC", validateEmails(cc)); } catch (final InvalidEmailException exception) { throw new IllegalArgumentException(exception); } } if (data.containsKey("BCC")) { final String bcc = data.getFirst("BCC"); data.remove("BCC"); try { data.putSingle("BCC", validateEmails(bcc)); } catch (final InvalidEmailException exception) { throw new IllegalArgumentException(exception); } } } @SuppressWarnings("unchecked") protected Response putEmailMessage(final String accountSid, final MultivaluedMap<String, String> data, final MediaType responseType, UserIdentityContext userIdentityContext) { permissionEvaluator.secure(accountsDao.getAccount(accountSid), "RestComm:Create:EmailMessages", userIdentityContext); //need to fix for Emails. try { validate(data); normalize(data); } catch (final RuntimeException exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } final String sender = data.getFirst("From"); final String recipient = data.getFirst("To"); final String body = data.getFirst("Body"); final String subject = data.getFirst("Subject"); final String type = data.containsKey("Type") ? data.getFirst("Type") : "text/plain"; final String cc = data.containsKey("CC")?data.getFirst("CC"):" "; final String bcc = data.containsKey("BCC")?data.getFirst("BCC"):" "; try { // Send the email. emailMsg = new Mail(sender, recipient, subject, body ,cc, bcc, DateTime.now(), accountSid, type); if (mailerService == null){ mailerService = session(confemail); } final ActorRef observer = observer(); mailerService.tell(new Observe(observer), observer); if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(emailMsg), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(emailMsg); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } catch (final Exception exception) { return status(INTERNAL_SERVER_ERROR).entity(exception.getMessage()).build(); } } private void validate(final MultivaluedMap<String, String> data) throws NullPointerException { if (!data.containsKey("From")) { throw new NullPointerException("From can not be null."); } else if (!data.containsKey("To")) { throw new NullPointerException("To can not be null."); } else if (!data.containsKey("Body")) { throw new NullPointerException("Body can not be null."); } else if (!data.containsKey("Subject")) { throw new NullPointerException("Subject can not be null."); } } public String validateEmail(String email) throws InvalidEmailException { String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$"; java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern); java.util.regex.Matcher m = p.matcher(email); if (!m.matches()) { String err = "Not a Valid Email Address"; throw new InvalidEmailException(err); } return email; } public String validateEmails(String emails) throws InvalidEmailException { String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$"; java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern); if (emails.indexOf(',') > 0) { String[] emailsArray = emails.split(","); for (int i = 0; i < emailsArray.length; i++) { java.util.regex.Matcher m = p.matcher(emailsArray[i]); if (!m.matches()) { String err = "Not a Valid Email Address:" + emailsArray[i]; throw new InvalidEmailException(err); } } }else{ java.util.regex.Matcher m = p.matcher(emails); if (!m.matches()) { String err = "Not a Valid Email Address"; throw new InvalidEmailException(err); } } return emails; } private ActorRef session(final Configuration configuration) { final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public Actor create() throws Exception { return new EmailService(configuration); } }); return system.actorOf(props); } private ActorRef observer() { final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new EmailSessionObserver(); } }); return system.actorOf(props); } private final class EmailSessionObserver extends RestcommUntypedActor { public EmailSessionObserver() { super(); } @Override public void onReceive(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (EmailResponse.class.equals(klass)) { final EmailResponse response = (EmailResponse) message; if (!response.succeeded()) { logger.error( "There was an error while sending an email :" + response.error(), response.cause()); } final UntypedActorContext context = getContext(); final ActorRef self = self(); mailerService.tell(new StopObserving(self), null); context.stop(self); }else if (Observing.class.equals(klass)){ mailerService.tell(new EmailRequest(emailMsg), self()); } } } private static class InvalidEmailException extends Exception { //Parameterless Constructor public InvalidEmailException() {} //Constructor that accepts a message public InvalidEmailException(String message) { super(message); } } @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response putEmailMessage(@PathParam("accountSid") final String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return putEmailMessage(accountSid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } }
12,783
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
GatewaysEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/GatewaysEndpoint.java
package org.restcomm.connect.http; import akka.actor.ActorRef; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import java.net.URI; import java.util.List; import javax.annotation.PostConstruct; import javax.annotation.security.RolesAllowed; import javax.servlet.ServletContext; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.MediaType.APPLICATION_XML_TYPE; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.ok; import static javax.ws.rs.core.Response.status; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.GatewaysDao; import org.restcomm.connect.dao.entities.Gateway; import org.restcomm.connect.dao.entities.GatewayList; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.http.converter.GatewayConverter; import org.restcomm.connect.http.converter.GatewayListConverter; import org.restcomm.connect.http.converter.RestCommResponseConverter; import org.restcomm.connect.http.security.ContextUtil; import static org.restcomm.connect.http.security.AccountPrincipal.SUPER_ADMIN_ROLE; import org.restcomm.connect.identity.UserIdentityContext; import org.restcomm.connect.telephony.api.RegisterGateway; @Path("/Accounts/{accountSid}/Management/Gateways") @ThreadSafe @RolesAllowed(SUPER_ADMIN_ROLE) @Singleton public class GatewaysEndpoint extends AbstractEndpoint { @Context protected ServletContext context; protected Configuration configuration; protected GatewaysDao dao; protected Gson gson; protected XStream xstream; private ActorRef proxyManager; public GatewaysEndpoint() { super(); } @PostConstruct public void init() { final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); configuration = (Configuration) context.getAttribute(Configuration.class.getName()); configuration = configuration.subset("runtime-settings"); super.init(configuration); dao = storage.getGatewaysDao(); final GatewayConverter converter = new GatewayConverter(configuration); final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Gateway.class, converter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(new GatewayListConverter(configuration)); xstream.registerConverter(new RestCommResponseConverter(configuration)); proxyManager = (ActorRef) context.getAttribute("org.restcomm.connect.telephony.proxy.ProxyManager"); } private Gateway createFrom(final MultivaluedMap<String, String> data) { final Gateway.Builder builder = Gateway.builder(); final Sid sid = Sid.generate(Sid.Type.GATEWAY); builder.setSid(sid); String friendlyName = data.getFirst("FriendlyName"); if (friendlyName == null || friendlyName.isEmpty()) { friendlyName = data.getFirst("UserName"); } builder.setFriendlyName(friendlyName); builder.setPassword(data.getFirst("Password")); builder.setProxy(data.getFirst("Proxy")); final boolean register = Boolean.parseBoolean(data.getFirst("Register")); builder.setRegister(register); builder.setUserName(data.getFirst("UserName")); final int ttl = Integer.parseInt(data.getFirst("TTL")); builder.setTimeToLive(ttl); final StringBuilder buffer = new StringBuilder(); buffer.append("/").append(getApiVersion(data)).append("/Management/").append("Gateways/").append(sid.toString()); builder.setUri(URI.create(buffer.toString())); return builder.build(); } protected Response getGateway(final String accountSid, final String sid, final MediaType responseType) { final Gateway gateway = dao.getGateway(new Sid(sid)); if (gateway == null) { return status(NOT_FOUND).build(); } else { if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(gateway); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(gateway), APPLICATION_JSON).build(); } else { return null; } } } protected Response getGateways(final String accountSid, final MediaType responseType) { final List<Gateway> gateways = dao.getGateways(); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(new GatewayList(gateways)); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(gateways), APPLICATION_JSON).build(); } else { return null; } } protected Response putGateway(final String accountSid, final MultivaluedMap<String, String> data, final MediaType responseType) { try { validate(data); } catch (final RuntimeException exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } final Gateway gateway = createFrom(data); dao.addGateway(gateway); if (proxyManager == null) { proxyManager = (ActorRef) context.getAttribute("org.restcomm.connect.telephony.proxy.ProxyManager"); } proxyManager.tell(new RegisterGateway(gateway), null); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(gateway); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(gateway), APPLICATION_JSON).build(); } else { return null; } } protected Response updateGateway(final String accountSid, final String sid, final MultivaluedMap<String, String> data, final MediaType responseType) { Gateway gateway = dao.getGateway(new Sid(sid)); if (gateway == null) { return status(NOT_FOUND).build(); } else { dao.updateGateway(update(gateway, data)); gateway = dao.getGateway(new Sid(sid)); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(gateway); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(gateway), APPLICATION_JSON).build(); } else { return null; } } } private void validate(final MultivaluedMap<String, String> data) { if (!data.containsKey("UserName")) { throw new NullPointerException("UserName can not be null."); } else if (!data.containsKey("Password")) { throw new NullPointerException("Password can not be null."); } else if (!data.containsKey("Proxy")) { throw new NullPointerException("The Proxy can not be null"); } else if (!data.containsKey("Register")) { throw new NullPointerException("Register must be true or false"); } } private Gateway update(final Gateway gateway, final MultivaluedMap<String, String> data) { Gateway result = gateway; if (data.containsKey("FriendlyName")) { result = result.setFriendlyName(data.getFirst("FriendlyName")); } if (data.containsKey("UserName")) { result = result.setUserName(data.getFirst("UserName")); } if (data.containsKey("Password")) { result = result.setPassword(data.getFirst("Password")); } if (data.containsKey("Proxy")) { result = result.setProxy(data.getFirst("Proxy")); } if (data.containsKey("Register")) { result = result.setRegister(Boolean.parseBoolean("Register")); } if (data.containsKey("TTL")) { result = result.setTimeToLive(Integer.parseInt(data.getFirst("TTL"))); } return result; } private Response deleteGateway(final String accountSid, final String sid, UserIdentityContext userIdentityContext) { permissionEvaluator.secure(super.accountsDao.getAccount(accountSid), "RestComm:Modify:Gateways", userIdentityContext); dao.removeGateway(new Sid(sid)); return ok().build(); } @Path("/{sid}") @DELETE public Response deleteGatewayAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, @Context SecurityContext sec) { return deleteGateway(accountSid, sid,ContextUtil.convert(sec)); } @Path("/{sid}") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getGatewayAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, @HeaderParam("Accept") String accept) { return getGateway(accountSid, sid, retrieveMediaType(accept)); } @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getGatewaysList(@PathParam("accountSid") final String accountSid, @HeaderParam("Accept") String accept) { return getGateways(accountSid, retrieveMediaType(accept)); } @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response createGateway(@PathParam("accountSid") final String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept) { return putGateway(accountSid, data, retrieveMediaType(accept)); } @Path("/{sid}") @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response updateGatewayAsXmlPost(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept) { return updateGateway(accountSid, sid, data, retrieveMediaType(accept)); } @Path("/{sid}") @PUT @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response updateGatewayAsXmlPut(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept) { return updateGateway(accountSid, sid, data, retrieveMediaType(accept)); } }
11,936
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ApplicationsEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/ApplicationsEndpoint.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2015, Telestax Inc and individual contributors * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.connect.http; import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import java.net.URI; import java.util.List; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.MediaType.APPLICATION_XML_TYPE; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.ok; import static javax.ws.rs.core.Response.status; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.AccountsDao; import org.restcomm.connect.dao.ApplicationsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.Application; import org.restcomm.connect.dao.entities.ApplicationList; import org.restcomm.connect.dao.entities.ApplicationNumberSummary; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.http.converter.ApplicationConverter; import org.restcomm.connect.http.converter.ApplicationListConverter; import org.restcomm.connect.http.converter.ApplicationNumberSummaryConverter; import org.restcomm.connect.http.converter.RestCommResponseConverter; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.http.security.PermissionEvaluator.SecuredType; import org.restcomm.connect.identity.UserIdentityContext; /** * @author [email protected] */ @Path("/Accounts/{accountSid}/Applications") @ThreadSafe @Singleton public class ApplicationsEndpoint extends AbstractEndpoint { @Context protected ServletContext context; protected Configuration configuration; protected ApplicationsDao dao; protected Gson gson; protected XStream xstream; protected AccountsDao accountsDao; public ApplicationsEndpoint() { super(); } @PostConstruct public void init() { final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); dao = storage.getApplicationsDao(); accountsDao = storage.getAccountsDao(); configuration = (Configuration) context.getAttribute(Configuration.class.getName()); configuration = configuration.subset("runtime-settings"); super.init(configuration); final ApplicationConverter converter = new ApplicationConverter(configuration); final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Application.class, converter); builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); // if custom converter is not provided, rename camelCase to camel_case. Needed for serializing ApplicationNumberSummary and hopefully other entities too at some point. builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(new ApplicationListConverter(configuration)); xstream.registerConverter(new RestCommResponseConverter(configuration)); xstream.registerConverter(new ApplicationNumberSummaryConverter()); xstream.alias("Number",ApplicationNumberSummary.class); } private Application createFrom(final Sid accountSid, final MultivaluedMap<String, String> data) { final Application.Builder builder = Application.builder(); final Sid sid = Sid.generate(Sid.Type.APPLICATION); builder.setSid(sid); builder.setFriendlyName(data.getFirst("FriendlyName")); builder.setAccountSid(accountSid); builder.setApiVersion(getApiVersion(data)); builder.setHasVoiceCallerIdLookup(new Boolean(data.getFirst("VoiceCallerIdLookup"))); final StringBuilder buffer = new StringBuilder(); buffer.append("/").append(getApiVersion(data)).append("/Accounts/").append(accountSid.toString()) .append("/Applications/").append(sid.toString()); builder.setUri(URI.create(buffer.toString())); builder.setRcmlUrl(getUrl("RcmlUrl", data)); if (data.containsKey("Kind")) { builder.setKind(Application.Kind.getValueOf(data.getFirst("Kind"))); } return builder.build(); } protected Response getApplication(final String accountSid, final String sid, final MediaType responseType, UserIdentityContext userIdentityContext) { Account account; permissionEvaluator.secure(account = accountsDao.getAccount(accountSid), "RestComm:Read:Applications", userIdentityContext); Application application = null; if (Sid.pattern.matcher(sid).matches()) { application = dao.getApplication(new Sid(sid)); } /*else { // disabled support for application retrieval based on FriendlyName. It makes no sense to have it if friendly-name based application uniqueness is no longer supported either. try { // Once not a valid sid, search using the parameter as name String name = URLDecoder.decode(String.valueOf(sid), "UTF-8"); application = dao.getApplication(name); } catch (UnsupportedEncodingException e) { return status(BAD_REQUEST).entity(e.getMessage()).build(); } }*/ if (application == null) { return status(NOT_FOUND).build(); } else { permissionEvaluator.secure(account, application.getAccountSid(), SecuredType.SECURED_APP, userIdentityContext); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(application); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(application), APPLICATION_JSON).build(); } else { return null; } } } protected Response getApplications(final String accountSid, final MediaType responseType, UriInfo uriInfo, UserIdentityContext userIdentityContext) { Account account; account = accountsDao.getAccount(accountSid); permissionEvaluator.secure(account, "RestComm:Read:Applications", SecuredType.SECURED_APP, userIdentityContext); // shall we also return number information with the application ? boolean includeNumbers = false; String tmp = uriInfo.getQueryParameters().getFirst("includeNumbers"); if (tmp != null && tmp.equalsIgnoreCase("true")) includeNumbers = true; final List<Application> applications = dao.getApplicationsWithNumbers(account.getSid()); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(new ApplicationList(applications)); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(applications), APPLICATION_JSON).build(); } else { return null; } } public Response putApplication(final String accountSid, final MultivaluedMap<String, String> data, final MediaType responseType, UserIdentityContext userIdentityContext) { Account account; account = accountsDao.getAccount(accountSid); permissionEvaluator.secure(account, "RestComm:Create:Applications", SecuredType.SECURED_APP, userIdentityContext); try { validate(data); } catch (final NullPointerException exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } // Application application = dao.getApplication(data.getFirst("FriendlyName")); // if (application == null) { // application = createFrom(new Sid(accountSid), data); // dao.addApplication(application); // } else if (!application.getAccountSid().toString().equals(account.getSid().toString())) { // return status(CONFLICT) // .entity("A application with the same name was already created by another account. Please, choose a different name and try again.") // .build(); // } // application uniqueness now relies only on application SID. No checks on the FriendlyName will be done. Application application = createFrom(new Sid(accountSid), data); dao.addApplication(application); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(application); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(application), APPLICATION_JSON).build(); } else { return null; } } private void validate(final MultivaluedMap<String, String> data) throws RuntimeException { if (!data.containsKey("FriendlyName")) { throw new NullPointerException("Friendly name can not be null."); } } protected Response updateApplication(final String accountSid, final String sid, final MultivaluedMap<String, String> data, final MediaType responseType, UserIdentityContext userIdentityContext) { Account account; permissionEvaluator.secure(account = accountsDao.getAccount(accountSid), "RestComm:Modify:Applications",userIdentityContext); final Application application = dao.getApplication(new Sid(sid)); if (application == null) { return status(NOT_FOUND).build(); } else { permissionEvaluator.secure(account, application.getAccountSid(), SecuredType.SECURED_APP, userIdentityContext); final Application applicationUpdate = update(application, data); dao.updateApplication(applicationUpdate); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(applicationUpdate); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(applicationUpdate), APPLICATION_JSON).build(); } else { return null; } } } private Application update(final Application application, final MultivaluedMap<String, String> data) { Application result = application; if (data.containsKey("FriendlyName")) { result = result.setFriendlyName(data.getFirst("FriendlyName")); } if (data.containsKey("VoiceCallerIdLookup")) { result = result.setVoiceCallerIdLookup(new Boolean(data.getFirst("VoiceCallerIdLookup"))); } if (data.containsKey("RcmlUrl")) { result = result.setRcmlUrl(getUrl("RcmlUrl", data)); } if (data.containsKey("Kind")) { result = result.setKind(Application.Kind.getValueOf(data.getFirst("Kind"))); } return result; } private Response deleteApplication(final String accountSid, final String sid, UserIdentityContext userIdentityContext) { Account operatedAccount = accountsDao.getAccount(new Sid(accountSid)); permissionEvaluator.secure(operatedAccount, "RestComm:Modify:Applications", SecuredType.SECURED_APP, userIdentityContext); Application application = dao.getApplication(new Sid(sid)); if (application != null) { permissionEvaluator.secure(operatedAccount, application.getAccountSid(), SecuredType.SECURED_APP, userIdentityContext); } dao.removeApplication(new Sid(sid)); return ok().build(); } @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getApplications(@PathParam("accountSid") final String accountSid, @Context UriInfo uriInfo, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getApplications(accountSid, retrieveMediaType(accept), uriInfo, ContextUtil.convert(sec)); } @Path("/{sid}") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getApplicationAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getApplication(accountSid, sid, retrieveMediaType(accept), ContextUtil.convert(sec)); } @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response putApplication(@PathParam("accountSid") String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return putApplication(accountSid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } @Path("/{sid}") @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response updateApplicationAsXmlPost(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return updateApplication(accountSid, sid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } @Path("/{sid}") @PUT @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response updateApplicationAsXmlPut(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return updateApplication(accountSid, sid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } @Path("/{sid}") @DELETE public Response deleteApplicationAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, @Context SecurityContext sec) { return deleteApplication(accountSid, sid,ContextUtil.convert(sec)); } }
16,680
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
LINK.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/LINK.java
package org.restcomm.connect.http; /* * 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/> * */ import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.ws.rs.HttpMethod; /** * * @author */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @HttpMethod("LINK") public @interface LINK { }
1,177
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SupervisorEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/SupervisorEndpoint.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2013, Telestax Inc and individual contributors * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.connect.http; import akka.actor.ActorRef; import static akka.pattern.Patterns.ask; import akka.util.Timeout; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import java.text.ParseException; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.annotation.security.RolesAllowed; import javax.servlet.ServletContext; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.MediaType.APPLICATION_XML_TYPE; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.ok; import static javax.ws.rs.core.Response.status; import javax.ws.rs.core.UriInfo; import org.apache.commons.configuration.Configuration; import org.apache.log4j.Logger; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.entities.CallDetailRecordFilter; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.http.converter.CallinfoConverter; import org.restcomm.connect.http.converter.MonitoringServiceConverter; import org.restcomm.connect.http.converter.MonitoringServiceConverterCallDetails; import org.restcomm.connect.http.converter.RestCommResponseConverter; import static org.restcomm.connect.http.security.AccountPrincipal.SUPER_ADMIN_ROLE; import org.restcomm.connect.monitoringservice.LiveCallsDetails; import org.restcomm.connect.monitoringservice.MonitoringService; import org.restcomm.connect.telephony.api.CallInfo; import org.restcomm.connect.telephony.api.GetLiveCalls; import org.restcomm.connect.telephony.api.GetStatistics; import org.restcomm.connect.telephony.api.MonitoringServiceResponse; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; /** * @author <a href="mailto:[email protected]">gvagenas</a> * */ @Path("/Accounts/{accountSid}/Supervisor") @ThreadSafe @RolesAllowed(SUPER_ADMIN_ROLE) @Singleton public class SupervisorEndpoint extends AbstractEndpoint{ private static Logger logger = Logger.getLogger(SupervisorEndpoint.class); @Context protected ServletContext context; protected Configuration configuration; private DaoManager daos; private Gson gson; private GsonBuilder builder; private XStream xstream; private ActorRef monitoringService; public SupervisorEndpoint() { super(); } @PostConstruct public void init() { monitoringService = (ActorRef) context.getAttribute(MonitoringService.class.getName()); configuration = (Configuration) context.getAttribute(Configuration.class.getName()); configuration = configuration.subset("runtime-settings"); daos = (DaoManager) context.getAttribute(DaoManager.class.getName()); super.init(configuration); CallinfoConverter converter = new CallinfoConverter(configuration); MonitoringServiceConverter listConverter = new MonitoringServiceConverter(configuration); MonitoringServiceConverterCallDetails callDetailsConverter = new MonitoringServiceConverterCallDetails(configuration); builder = new GsonBuilder(); builder.registerTypeAdapter(CallInfo.class, converter); builder.registerTypeAdapter(MonitoringServiceResponse.class, listConverter); builder.registerTypeAdapter(LiveCallsDetails.class, callDetailsConverter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(listConverter); xstream.registerConverter(callDetailsConverter); xstream.registerConverter(new RestCommResponseConverter(configuration)); } protected Response pong(final String accountSid, final MediaType responseType) { //following 2 things are enough to grant access: 1. a valid authentication token is present. 2 it is a super admin. CallDetailRecordFilter filterForTotal; try { filterForTotal = new CallDetailRecordFilter("", null, null, null, null, null,null, null, null, null, null); } catch (ParseException e) { return status(BAD_REQUEST).build(); } int totalCalls = daos.getCallDetailRecordsDao().getTotalCallDetailRecords(filterForTotal); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse("TotalCalls: "+totalCalls); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson("TotalCalls: "+totalCalls), APPLICATION_JSON).build(); } else { return null; } } protected Response getMetrics(final String accountSid, final UriInfo info, final MediaType responseType) { //following 2 things are enough to grant access: 1. a valid authentication token is present. 2 it is a super admin. boolean withLiveCallDetails = false; boolean withMgcpStats = false; if (info != null && info.getQueryParameters().containsKey("LiveCallDetails") ) { withLiveCallDetails = Boolean.parseBoolean(info.getQueryParameters().getFirst("LiveCallDetails")); } if (info != null && info.getQueryParameters().containsKey("MgcpStats") ) { withMgcpStats = Boolean.parseBoolean(info.getQueryParameters().getFirst("MgcpStats")); } //Get the list of live calls from Monitoring Service MonitoringServiceResponse monitoringServiceResponse; try { final Timeout expires = new Timeout(Duration.create(5, TimeUnit.SECONDS)); GetStatistics getStatistics = new GetStatistics(withLiveCallDetails, withMgcpStats, accountSid); Future<Object> future = (Future<Object>) ask(monitoringService, getStatistics, expires); monitoringServiceResponse = (MonitoringServiceResponse) Await.result(future, Duration.create(5, TimeUnit.SECONDS)); } catch (Exception exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } if (monitoringServiceResponse != null) { if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(monitoringServiceResponse); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { Response response = ok(gson.toJson(monitoringServiceResponse), APPLICATION_JSON).build(); if(logger.isDebugEnabled()){ logger.debug("Supervisor endpoint response: "+gson.toJson(monitoringServiceResponse)); } return response; } else { return null; } } else { return null; } } protected Response getLiveCalls(final String accountSid, final MediaType responseType) { //following 2 things are enough to grant access: 1. a valid authentication token is present. 2 it is a super admin. LiveCallsDetails callDetails; try { final Timeout expires = new Timeout(Duration.create(5, TimeUnit.SECONDS)); GetLiveCalls getLiveCalls = new GetLiveCalls(); Future<Object> future = (Future<Object>) ask(monitoringService, getLiveCalls, expires); callDetails = (LiveCallsDetails) Await.result(future, Duration.create(5, TimeUnit.SECONDS)); } catch (Exception exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } if (callDetails != null) { if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(callDetails); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { Response response = ok(gson.toJson(callDetails), APPLICATION_JSON).build(); if(logger.isDebugEnabled()){ logger.debug("Supervisor endpoint response: "+gson.toJson(callDetails)); } return response; } else { return null; } } else { return null; } } //Register a remote location where Restcomm will send monitoring updates protected Response registerForUpdates(final String accountSid, final UriInfo info, MediaType responseType) { //following 2 things are enough to grant access: 1. a valid authentication token is present. 2 it is a super admin. boolean withLiveCallDetails = false; boolean withMgcpStats = false; if (info != null && info.getQueryParameters().containsKey("LiveCallDetails") ) { withLiveCallDetails = Boolean.parseBoolean(info.getQueryParameters().getFirst("LiveCallDetails")); } if (info != null && info.getQueryParameters().containsKey("MgcpStats") ) { withMgcpStats = Boolean.parseBoolean(info.getQueryParameters().getFirst("MgcpStats")); } //Get the list of live calls from Monitoring Service MonitoringServiceResponse monitoringServiceResponse; try { final Timeout expires = new Timeout(Duration.create(60, TimeUnit.SECONDS)); GetStatistics getStatistics = new GetStatistics(withLiveCallDetails, withMgcpStats, accountSid); Future<Object> future = (Future<Object>) ask(monitoringService, getStatistics, expires); monitoringServiceResponse = (MonitoringServiceResponse) Await.result(future, Duration.create(10, TimeUnit.SECONDS)); } catch (Exception exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } if (monitoringServiceResponse != null) { if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(monitoringServiceResponse); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { Response response = ok(gson.toJson(monitoringServiceResponse), APPLICATION_JSON).build(); return response; } else { return null; } } else { return null; } } //Register a remote location where Restcomm will send monitoring updates for a specific Call protected Response registerForCallUpdates(final String accountSid, final String callSid, final MultivaluedMap<String, String> data, MediaType responseType) { //following 2 things are enough to grant access: 1. a valid authentication token is present. 2 it is a super admin. final String url = data.getFirst("Url"); final String refresh = data.getFirst("Refresh"); boolean withLiveCallDetails = false; boolean withMgcpStats = false; if (data != null && data.containsKey("LiveCallDetails")) { withLiveCallDetails = Boolean.parseBoolean(data.getFirst("LiveCallDetails")); } if (data != null && data.containsKey("MgcpStats") ) { withMgcpStats = Boolean.parseBoolean(data.getFirst("MgcpStats")); } //Get the list of live calls from Monitoring Service MonitoringServiceResponse monitoringServiceResponse; try { final Timeout expires = new Timeout(Duration.create(60, TimeUnit.SECONDS)); GetStatistics getStatistics = new GetStatistics(withLiveCallDetails, withMgcpStats, accountSid); Future<Object> future = (Future<Object>) ask(monitoringService, getStatistics, expires); monitoringServiceResponse = (MonitoringServiceResponse) Await.result(future, Duration.create(10, TimeUnit.SECONDS)); } catch (Exception exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } if (monitoringServiceResponse != null) { if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(monitoringServiceResponse); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { Response response = ok(gson.toJson(monitoringServiceResponse), APPLICATION_JSON).build(); return response; } else { return null; } } else { return null; } } //Simple PING/PONG message @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response ping(@PathParam("accountSid") final String accountSid, @HeaderParam("Accept") String accept) { return pong(accountSid, retrieveMediaType(accept)); } //Get statistics @Path("/metrics") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getMetrics(@PathParam("accountSid") final String accountSid, @Context UriInfo info, @HeaderParam("Accept") String accept) { return getMetrics(accountSid, info, retrieveMediaType(accept)); } //Get live calls @Path("/livecalls") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getLiveCalls(@PathParam("accountSid") final String accountSid, @HeaderParam("Accept") String accept) { return getLiveCalls(accountSid, retrieveMediaType(accept)); } //Register a remote location where Restcomm will send monitoring updates @Path("/remote") @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response registerForMetricsUpdates(@PathParam("accountSid") final String accountSid, @Context UriInfo info, @HeaderParam("Accept") String accept) { return registerForUpdates(accountSid, info, retrieveMediaType(accept)); } //Register a remote location where Restcomm will send monitoring updates for a specific Call @Path("/remote/{sid}") @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response registerForCallMetricsUpdates(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept) { return registerForCallUpdates(accountSid, sid, data, retrieveMediaType(accept)); } }
16,345
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
NotificationsEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/NotificationsEndpoint.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.restcomm.connect.http; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.*; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.*; import static javax.ws.rs.core.Response.Status.*; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.NotificationsDao; import org.restcomm.connect.dao.common.Sorting; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.Notification; import org.restcomm.connect.dao.entities.NotificationFilter; import org.restcomm.connect.dao.entities.NotificationList; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.http.converter.NotificationConverter; import org.restcomm.connect.http.converter.NotificationListConverter; import org.restcomm.connect.http.converter.RestCommResponseConverter; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.http.security.PermissionEvaluator.SecuredType; import org.restcomm.connect.identity.UserIdentityContext; /** * @author [email protected] (Thomas Quintana) */ @Path("/Accounts/{accountSid}/Notifications") @ThreadSafe @Singleton public class NotificationsEndpoint extends AbstractEndpoint { private static final String SORTING_URL_PARAM_DATE_CREATED = "DateCreated"; private static final String SORTING_URL_PARAM_LOG = "Log"; private static final String SORTING_URL_PARAM_ERROR_CODE = "ErrorCode"; private static final String SORTING_URL_PARAM_CALLSID = "CallSid"; private static final String SORTING_URL_PARAM_MESSAGE_TEXT = "MessageText"; @Context private ServletContext context; private Configuration configuration; private NotificationsDao dao; private Gson gson; private XStream xstream; private NotificationListConverter listConverter; private String instanceId; public NotificationsEndpoint() { super(); } @PostConstruct public void init() { final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); configuration = (Configuration) context.getAttribute(Configuration.class.getName()); configuration = configuration.subset("runtime-settings"); super.init(configuration); dao = storage.getNotificationsDao(); final NotificationConverter converter = new NotificationConverter(configuration); listConverter = new NotificationListConverter(configuration); final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Notification.class, converter); builder.registerTypeAdapter(NotificationList.class, listConverter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(new NotificationListConverter(configuration)); xstream.registerConverter(new RestCommResponseConverter(configuration)); xstream.registerConverter(listConverter); instanceId = RestcommConfiguration.getInstance().getMain().getInstanceId(); } protected Response getNotification(final String accountSid, final String sid, final MediaType responseType, UserIdentityContext userIdentityContext) { Account operatedAccount = accountsDao.getAccount(accountSid); permissionEvaluator.secure(operatedAccount, "RestComm:Read:Notifications", userIdentityContext); final Notification notification = dao.getNotification(new Sid(sid)); if (notification == null) { return status(NOT_FOUND).build(); } else { permissionEvaluator.secure(operatedAccount, notification.getAccountSid(), SecuredType.SECURED_STANDARD, userIdentityContext); if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(notification), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(notification); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } } protected Response getNotifications(final String accountSid, UriInfo info, final MediaType responseType, UserIdentityContext userIdentityContext) { permissionEvaluator.secure(accountsDao.getAccount(accountSid), "RestComm:Read:Notifications", userIdentityContext); boolean localInstanceOnly = true; try { String localOnly = info.getQueryParameters().getFirst("localOnly"); if (localOnly != null && localOnly.equalsIgnoreCase("false")) localInstanceOnly = false; } catch (Exception e) { } // shall we include sub-accounts cdrs in our query ? boolean querySubAccounts = false; // be default we don't String querySubAccountsParam = info.getQueryParameters().getFirst("SubAccounts"); if (querySubAccountsParam != null && querySubAccountsParam.equalsIgnoreCase("true")) querySubAccounts = true; String pageSize = info.getQueryParameters().getFirst("PageSize"); String page = info.getQueryParameters().getFirst("Page"); String startTime = info.getQueryParameters().getFirst("StartTime"); String endTime = info.getQueryParameters().getFirst("EndTime"); String error_code = info.getQueryParameters().getFirst("ErrorCode"); String request_url = info.getQueryParameters().getFirst("RequestUrl"); String message_text = info.getQueryParameters().getFirst("MessageText"); String sortParameters = info.getQueryParameters().getFirst("SortBy"); NotificationFilter.Builder filterBuilder = NotificationFilter.Builder.builder(); String sortBy = null; String sortDirection = null; if (sortParameters != null && !sortParameters.isEmpty()) { try { Map<String, String> sortMap = Sorting.parseUrl(sortParameters); sortBy = sortMap.get(Sorting.SORT_BY_KEY); sortDirection = sortMap.get(Sorting.SORT_DIRECTION_KEY); } catch (Exception e) { return status(BAD_REQUEST).entity(buildErrorResponseBody(e.getMessage(), responseType)).build(); } } if (sortBy != null) { if (sortBy.equals(SORTING_URL_PARAM_DATE_CREATED)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByDate(Sorting.Direction.ASC); } else { filterBuilder.sortedByDate(Sorting.Direction.DESC); } } } if (sortBy.equals(SORTING_URL_PARAM_LOG)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByLog(Sorting.Direction.ASC); } else { filterBuilder.sortedByLog(Sorting.Direction.DESC); } } } if (sortBy.equals(SORTING_URL_PARAM_ERROR_CODE)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByErrorCode(Sorting.Direction.ASC); } else { filterBuilder.sortedByErrorCode(Sorting.Direction.DESC); } } } if (sortBy.equals(SORTING_URL_PARAM_CALLSID)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByCallSid(Sorting.Direction.ASC); } else { filterBuilder.sortedByCallSid(Sorting.Direction.DESC); } } } if (sortBy.equals(SORTING_URL_PARAM_MESSAGE_TEXT)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByMessageText(Sorting.Direction.ASC); } else { filterBuilder.sortedByMessageText(Sorting.Direction.DESC); } } } } if (pageSize == null) { pageSize = "50"; } if (page == null) { page = "0"; } int limit = Integer.parseInt(pageSize); int offset = (page.equals("0")) ? 0 : (((Integer.parseInt(page) - 1) * Integer.parseInt(pageSize)) + Integer .parseInt(pageSize)); // Shall we query cdrs of sub-accounts too ? // if we do, we need to find the sub-accounts involved first List<String> ownerAccounts = null; if (querySubAccounts) { ownerAccounts = new ArrayList<String>(); ownerAccounts.add(accountSid); // we will also return parent account cdrs ownerAccounts.addAll(accountsDao.getSubAccountSidsRecursive(new Sid(accountSid))); } filterBuilder.byAccountSid(accountSid) .byAccountSidSet(ownerAccounts) .byStartTime(startTime) .byEndTime(endTime) .byErrorCode(error_code) .byRequestUrl(request_url) .byMessageText(message_text) .limited(limit, offset); if (!localInstanceOnly) { filterBuilder.byInstanceId(instanceId); } NotificationFilter filter; try { filter = filterBuilder.build(); } catch (ParseException e) { return status(BAD_REQUEST).build(); } final int total = dao.getTotalNotification(filter); if (Integer.parseInt(page) > (total / limit)) { return status(javax.ws.rs.core.Response.Status.BAD_REQUEST).build(); } final List<Notification> cdrs = dao.getNotifications(filter); listConverter.setCount(total); listConverter.setPage(Integer.parseInt(page)); listConverter.setPageSize(Integer.parseInt(pageSize)); listConverter.setPathUri(info.getRequestUri().getPath()); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(new NotificationList(cdrs)); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(new NotificationList(cdrs)), APPLICATION_JSON).build(); } else { return null; } } @Path("/{sid}") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getNotificationAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getNotification(accountSid, sid, retrieveMediaType(accept), ContextUtil.convert(sec)); } @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getNotifications(@PathParam("accountSid") final String accountSid, @Context UriInfo info, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getNotifications(accountSid, info, retrieveMediaType(accept), ContextUtil.convert(sec)); } }
13,815
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AvailablePhoneNumbersTollFreeXmlEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/AvailablePhoneNumbersTollFreeXmlEndpoint.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.restcomm.connect.http; import com.sun.jersey.spi.container.ResourceFilters; import com.sun.jersey.spi.resource.Singleton; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.*; import static javax.ws.rs.core.Response.Status.*; import javax.ws.rs.core.SecurityContext; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.http.filters.ExtensionFilter; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.provisioning.number.api.PhoneNumberSearchFilters; import org.restcomm.connect.provisioning.number.api.PhoneNumberType; /** * @author <a href="mailto:[email protected]">gvagenas</a> * @author <a href="mailto:[email protected]">Jean Deruelle</a> */ @Path("/Accounts/{accountSid}/AvailablePhoneNumbers/{IsoCountryCode}/TollFree") @ThreadSafe @Singleton public class AvailablePhoneNumbersTollFreeXmlEndpoint extends AvailablePhoneNumbersEndpoint { public AvailablePhoneNumbersTollFreeXmlEndpoint() { super(); } @GET @ResourceFilters({ ExtensionFilter.class }) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getAvailablePhoneNumber(@PathParam("accountSid") final String accountSid, @PathParam("IsoCountryCode") final String isoCountryCode, @QueryParam("AreaCode") String areaCode, @QueryParam("Contains") String filterPattern, @QueryParam("RangeSize") String rangeSize, @QueryParam("RangeIndex") String rangeIndex, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { if (isoCountryCode != null && !isoCountryCode.isEmpty()) { int rangeSizeInt = -1; if (rangeSize != null && !rangeSize.isEmpty()) { rangeSizeInt = Integer.parseInt(rangeSize); } int rangeIndexInt = -1; if (rangeIndex != null && !rangeIndex.isEmpty()) { rangeIndexInt = Integer.parseInt(rangeIndex); } PhoneNumberSearchFilters listFilters = new PhoneNumberSearchFilters(areaCode, null, null, Boolean.TRUE, null, null, null, null, null, null, null, null, null, null, rangeSizeInt, rangeIndexInt, PhoneNumberType.TollFree); return getAvailablePhoneNumbers(accountSid, isoCountryCode, listFilters, filterPattern, retrieveMediaType(accept), ContextUtil.convert(sec)); } else { return status(BAD_REQUEST).build(); } } }
3,662
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TranscriptionsEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/TranscriptionsEndpoint.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.restcomm.connect.http; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.*; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.*; import static javax.ws.rs.core.Response.Status.*; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.TranscriptionsDao; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.dao.entities.Transcription; import org.restcomm.connect.dao.entities.TranscriptionFilter; import org.restcomm.connect.dao.entities.TranscriptionList; import org.restcomm.connect.http.converter.RestCommResponseConverter; import org.restcomm.connect.http.converter.TranscriptionConverter; import org.restcomm.connect.http.converter.TranscriptionListConverter; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.http.security.PermissionEvaluator.SecuredType; import org.restcomm.connect.identity.UserIdentityContext; /** * @author [email protected] (Thomas Quintana) */ @Path("/Accounts/{accountSid}/Transcriptions") @Singleton public class TranscriptionsEndpoint extends AbstractEndpoint { @Context private ServletContext context; private Configuration configuration; private TranscriptionsDao dao; private Gson gson; private XStream xstream; private TranscriptionListConverter listConverter; private String instanceId; public TranscriptionsEndpoint() { super(); } @PostConstruct public void init() { final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); configuration = (Configuration) context.getAttribute(Configuration.class.getName()); configuration = configuration.subset("runtime-settings"); super.init(configuration); dao = storage.getTranscriptionsDao(); final TranscriptionConverter converter = new TranscriptionConverter(configuration); listConverter = new TranscriptionListConverter(configuration); final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Transcription.class, converter); builder.registerTypeAdapter(TranscriptionList.class, listConverter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(new TranscriptionListConverter(configuration)); xstream.registerConverter(new RestCommResponseConverter(configuration)); xstream.registerConverter(listConverter); instanceId = RestcommConfiguration.getInstance().getMain().getInstanceId(); } private Response getTranscription(final String accountSid, final String sid, final MediaType responseType, UserIdentityContext userIdentityContext) { Account operatedAccount = accountsDao.getAccount(accountSid); permissionEvaluator.secure(operatedAccount, "RestComm:Read:Transcriptions", userIdentityContext); final Transcription transcription = dao.getTranscription(new Sid(sid)); if (transcription == null) { return status(NOT_FOUND).build(); } else { permissionEvaluator.secure(operatedAccount, transcription.getAccountSid(), SecuredType.SECURED_STANDARD, userIdentityContext); if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(transcription), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(transcription); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } } private Response getTranscriptions(final String accountSid, UriInfo info, final MediaType responseType, UserIdentityContext userIdentityContext) { permissionEvaluator.secure(accountsDao.getAccount(accountSid), "RestComm:Read:Transcriptions", userIdentityContext); boolean localInstanceOnly = true; try { String localOnly = info.getQueryParameters().getFirst("localOnly"); if (localOnly != null && localOnly.equalsIgnoreCase("false")) localInstanceOnly = false; } catch (Exception e) { } // shall we include sub-accounts cdrs in our query ? boolean querySubAccounts = false; // be default we don't String querySubAccountsParam = info.getQueryParameters().getFirst("SubAccounts"); if (querySubAccountsParam != null && querySubAccountsParam.equalsIgnoreCase("true")) querySubAccounts = true; String pageSize = info.getQueryParameters().getFirst("PageSize"); String page = info.getQueryParameters().getFirst("Page"); String startTime = info.getQueryParameters().getFirst("StartTime"); String endTime = info.getQueryParameters().getFirst("EndTime"); String transcriptionText = info.getQueryParameters().getFirst("TranscriptionText"); if (pageSize == null) { pageSize = "50"; } if (page == null) { page = "0"; } int limit = Integer.parseInt(pageSize); int offset = (page.equals("0")) ? 0 : (((Integer.parseInt(page) - 1) * Integer.parseInt(pageSize)) + Integer .parseInt(pageSize)); // Shall we query cdrs of sub-accounts too ? // if we do, we need to find the sub-accounts involved first List<String> ownerAccounts = null; if (querySubAccounts) { ownerAccounts = new ArrayList<String>(); ownerAccounts.add(accountSid); // we will also return parent account cdrs ownerAccounts.addAll(accountsDao.getSubAccountSidsRecursive(new Sid(accountSid))); } TranscriptionFilter filterForTotal; try { if (localInstanceOnly) { filterForTotal = new TranscriptionFilter(accountSid, ownerAccounts, startTime, endTime, transcriptionText, null, null); } else { filterForTotal = new TranscriptionFilter(accountSid, ownerAccounts, startTime, endTime, transcriptionText, null, null, instanceId); } } catch (ParseException e) { return status(BAD_REQUEST).build(); } final int total = dao.getTotalTranscription(filterForTotal); if (Integer.parseInt(page) > (total / limit)) { return status(javax.ws.rs.core.Response.Status.BAD_REQUEST).build(); } TranscriptionFilter filter; try { if (localInstanceOnly) { filter = new TranscriptionFilter(accountSid, ownerAccounts, startTime, endTime, transcriptionText, limit, offset); } else { filter = new TranscriptionFilter(accountSid, ownerAccounts, startTime, endTime, transcriptionText, limit, offset, instanceId); } } catch (ParseException e) { return status(BAD_REQUEST).build(); } final List<Transcription> cdrs = dao.getTranscriptions(filter); listConverter.setCount(total); listConverter.setPage(Integer.parseInt(page)); listConverter.setPageSize(Integer.parseInt(pageSize)); listConverter.setPathUri(info.getRequestUri().getPath()); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(new TranscriptionList(cdrs)); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(new TranscriptionList(cdrs)), APPLICATION_JSON).build(); } else { return null; } } @Path("/{sid}") @DELETE public Response deleteTranscription(@PathParam("accountSid") String accountSid, @PathParam("sid") String sid, @Context SecurityContext sec) { Account operatedAccount = super.accountsDao.getAccount(accountSid); permissionEvaluator.secure(operatedAccount, "RestComm:Delete:Transcriptions", ContextUtil.convert(sec)); Transcription transcription = dao.getTranscription(new Sid(sid)); if (transcription != null) { permissionEvaluator.secure(operatedAccount, String.valueOf(transcription.getAccountSid()), SecuredType.SECURED_STANDARD, ContextUtil.convert(sec)); } // TODO return NOT_FOUND if transcrtiption==null dao.removeTranscription(new Sid(sid)); return ok().build(); } @Path("/{sid}") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getTranscriptionAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getTranscription(accountSid, sid, retrieveMediaType(accept), ContextUtil.convert(sec)); } @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getTranscriptions(@PathParam("accountSid") final String accountSid, @Context UriInfo info, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getTranscriptions(accountSid, info, retrieveMediaType(accept), ContextUtil.convert(sec)); } }
11,601
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RecordingsEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/RecordingsEndpoint.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.restcomm.connect.http; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.amazonS3.RecordingSecurityLevel; import org.restcomm.connect.commons.amazonS3.S3AccessTool; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.core.service.api.RecordingService; import org.restcomm.connect.dao.AccountsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.RecordingsDao; import org.restcomm.connect.dao.common.Sorting; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.Recording; import org.restcomm.connect.dao.entities.RecordingFilter; import org.restcomm.connect.dao.entities.RecordingList; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.http.converter.RecordingConverter; import org.restcomm.connect.http.converter.RecordingListConverter; import org.restcomm.connect.http.converter.RestCommResponseConverter; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.http.security.PermissionEvaluator.SecuredType; import org.restcomm.connect.identity.UserIdentityContext; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import java.io.File; import java.net.URI; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.Map; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.MediaType.APPLICATION_XML_TYPE; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.ok; import static javax.ws.rs.core.Response.status; import static javax.ws.rs.core.Response.temporaryRedirect; /** * @author [email protected] (Thomas Quintana) */ @Path("/Accounts/{accountSid}/Recordings") @ThreadSafe @Singleton public class RecordingsEndpoint extends AbstractEndpoint { private static final String SORTING_URL_PARAM_DATE_CREATED = "DateCreated"; private static final String SORTING_URL_PARAM_DURATION = "Duration"; private static final String SORTING_URL_PARAM_CALLSID = "CallSid"; @Context private ServletContext context; private Configuration configuration; private AccountsDao accountsDao; private RecordingsDao dao; private Gson gson; private XStream xstream; private S3AccessTool s3AccessTool; private RecordingSecurityLevel securityLevel = RecordingSecurityLevel.SECURE; private RecordingListConverter listConverter; private String instanceId; private RecordingService recordingService; public RecordingsEndpoint() { super(); } @PostConstruct public void init() { final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); configuration = (Configuration) context.getAttribute(Configuration.class.getName()); Configuration amazonS3Configuration = configuration.subset("amazon-s3"); configuration = configuration.subset("runtime-settings"); super.init(configuration); recordingService = (RecordingService) context.getAttribute(RecordingService.class.getName()); this.accountsDao = storage.getAccountsDao(); dao = storage.getRecordingsDao(); final RecordingConverter converter = new RecordingConverter(configuration); listConverter = new RecordingListConverter(configuration); final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Recording.class, converter); builder.registerTypeAdapter(RecordingList.class, listConverter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(new RecordingListConverter(configuration)); xstream.registerConverter(new RestCommResponseConverter(configuration)); if(!amazonS3Configuration.isEmpty()) { // Do not fail with NPE is amazonS3Configuration is not present for older install boolean amazonS3Enabled = amazonS3Configuration.getBoolean("enabled"); if (amazonS3Enabled) { final String accessKey = amazonS3Configuration.getString("access-key"); final String securityKey = amazonS3Configuration.getString("security-key"); final String bucketName = amazonS3Configuration.getString("bucket-name"); final String bucketFolder = amazonS3Configuration.getString("folder"); final boolean reducedRedundancy = amazonS3Configuration.getBoolean("reduced-redundancy"); final int minutesToRetainPublicUrl = amazonS3Configuration.getInt("minutes-to-retain-public-url", 10); final boolean removeOriginalFile = amazonS3Configuration.getBoolean("remove-original-file"); final String bucketRegion = amazonS3Configuration.getString("bucket-region"); final boolean testing = amazonS3Configuration.getBoolean("testing",false); final String testingUrl = amazonS3Configuration.getString("testing-url",null); s3AccessTool = new S3AccessTool(accessKey, securityKey, bucketName, bucketFolder, reducedRedundancy, minutesToRetainPublicUrl, removeOriginalFile,bucketRegion, testing, testingUrl); securityLevel = RecordingSecurityLevel.valueOf(amazonS3Configuration.getString("security-level", "secure").toUpperCase()); converter.setSecurityLevel(securityLevel); } } xstream.registerConverter(listConverter); instanceId = RestcommConfiguration.getInstance().getMain().getInstanceId(); } protected Response getRecording(final String accountSid, final String sid, final MediaType responseType, UserIdentityContext userIdentityContext) { Account operatedAccount = accountsDao.getAccount(accountSid); permissionEvaluator.secure(operatedAccount, "RestComm:Read:Recordings", userIdentityContext); final Recording recording = dao.getRecording(new Sid(sid)); if (recording == null) { return status(NOT_FOUND).build(); } else { permissionEvaluator.secure(operatedAccount, recording.getAccountSid(), SecuredType.SECURED_STANDARD, userIdentityContext); if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(recording), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(recording); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } } protected Response getRecordings(final String accountSid, UriInfo info, final MediaType responseType, UserIdentityContext userIdentityContext) { permissionEvaluator.secure(accountsDao.getAccount(accountSid), "RestComm:Read:Recordings", userIdentityContext); boolean localInstanceOnly = true; try { String localOnly = info.getQueryParameters().getFirst("localOnly"); if (localOnly != null && localOnly.equalsIgnoreCase("false")) localInstanceOnly = false; } catch (Exception e) { } // shall we include sub-accounts cdrs in our query ? boolean querySubAccounts = false; // be default we don't String querySubAccountsParam = info.getQueryParameters().getFirst("SubAccounts"); if (querySubAccountsParam != null && querySubAccountsParam.equalsIgnoreCase("true")) querySubAccounts = true; String pageSize = info.getQueryParameters().getFirst("PageSize"); String page = info.getQueryParameters().getFirst("Page"); String startTime = info.getQueryParameters().getFirst("StartTime"); String endTime = info.getQueryParameters().getFirst("EndTime"); String callSid = info.getQueryParameters().getFirst("CallSid"); String sortParameters = info.getQueryParameters().getFirst("SortBy"); RecordingFilter.Builder filterBuilder = RecordingFilter.Builder.builder(); String sortBy = null; String sortDirection = null; if (sortParameters != null && !sortParameters.isEmpty()) { try { Map<String, String> sortMap = Sorting.parseUrl(sortParameters); sortBy = sortMap.get(Sorting.SORT_BY_KEY); sortDirection = sortMap.get(Sorting.SORT_DIRECTION_KEY); } catch (Exception e) { return status(BAD_REQUEST).entity(buildErrorResponseBody(e.getMessage(), responseType)).build(); } } if (sortBy != null) { if (sortBy.equals(SORTING_URL_PARAM_DATE_CREATED)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByDate(Sorting.Direction.ASC); } else { filterBuilder.sortedByDate(Sorting.Direction.DESC); } } } if (sortBy.equals(SORTING_URL_PARAM_DURATION)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByDuration(Sorting.Direction.ASC); } else { filterBuilder.sortedByDuration(Sorting.Direction.DESC); } } } if (sortBy.equals(SORTING_URL_PARAM_CALLSID)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByCallSid(Sorting.Direction.ASC); } else { filterBuilder.sortedByCallSid(Sorting.Direction.DESC); } } } } // TODO: Test that we are not imposing different ordering, compared to what we did before this enhancement, when the client is not asking for any type of sorting if (pageSize == null) { pageSize = "50"; } if (page == null) { page = "0"; } int limit = Integer.parseInt(pageSize); int offset = (page.equals("0")) ? 0 : (((Integer.parseInt(page) - 1) * Integer.parseInt(pageSize)) + Integer .parseInt(pageSize)); // Shall we query cdrs of sub-accounts too ? // if we do, we need to find the sub-accounts involved first List<String> ownerAccounts = null; if (querySubAccounts) { ownerAccounts = new ArrayList<String>(); ownerAccounts.add(accountSid); // we will also return parent account cdrs ownerAccounts.addAll(accountsDao.getSubAccountSidsRecursive(new Sid(accountSid))); } /* RecordingFilter filterForTotal; try { if (localInstanceOnly) { filterForTotal = new RecordingFilter(accountSid, ownerAccounts, startTime, endTime, callSid, null, null); } else { filterForTotal = new RecordingFilter(accountSid, ownerAccounts, startTime, endTime, callSid, null, null, instanceId); } } catch (ParseException e) { return status(BAD_REQUEST).build(); } final int total = dao.getTotalRecording(filterForTotal);*/ filterBuilder.byAccountSid(accountSid) .byAccountSidSet(ownerAccounts) .byStartTime(startTime) .byEndTime(endTime) .byCallSid(callSid) .limited(limit, offset); if (!localInstanceOnly) { filterBuilder.byInstanceId(instanceId); } RecordingFilter filter; try { filter = filterBuilder.build(); } catch (ParseException e) { return status(BAD_REQUEST).build(); } final int total = dao.getTotalRecording(filter); if (Integer.parseInt(page) > (total / limit)) { return status(BAD_REQUEST).build(); } /* RecordingFilter filter; try { if (localInstanceOnly) { filter = new RecordingFilter(accountSid, ownerAccounts, startTime, endTime, callSid, limit, offset); } else { filter = new RecordingFilter(accountSid, ownerAccounts, startTime, endTime, callSid, limit, offset, instanceId); } } catch (ParseException e) { return status(BAD_REQUEST).build(); } */ final List<Recording> cdrs = dao.getRecordings(filter); listConverter.setCount(total); listConverter.setPage(Integer.parseInt(page)); listConverter.setPageSize(Integer.parseInt(pageSize)); listConverter.setPathUri(info.getRequestUri().getPath()); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(new RecordingList(cdrs)); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(new RecordingList(cdrs)), APPLICATION_JSON).build(); } else { return null; } } protected Response getRecordingsByCall(final String accountSid, final String callSid, final MediaType responseType, UserIdentityContext userIdentityContext) { permissionEvaluator.secure(accountsDao.getAccount(accountSid), "RestComm:Read:Recordings", userIdentityContext); final List<Recording> recordings = dao.getRecordingsByCall(new Sid(callSid)); if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(recordings), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(new RecordingList(recordings)); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } protected Response getRecordingFile (String accountSid, String sid) { Account operatedAccount = accountsDao.getAccount(accountSid); // secure(operatedAccount, "RestComm:Read:Recordings"); final Recording recording = dao.getRecording(new Sid(sid)); if (recording == null) { if (logger.isInfoEnabled()) { logger.info("Recording with SID: "+sid+", was not found"); } return status(NOT_FOUND).build(); } else { // secure(operatedAccount, recording.getAccountSid(), SecuredType.SECURED_STANDARD); URI recordingUri = null; try { if (recording.getS3Uri() != null) { String fileExtension = recording.getS3Uri().toString().endsWith("wav") ? ".wav" : ".mp4"; recordingUri = s3AccessTool.getPublicUrl(recording.getSid() + fileExtension); if (securityLevel.equals(RecordingSecurityLevel.REDIRECT)) { return temporaryRedirect(recordingUri).build(); } else { String contentType = recordingUri.toURL().openConnection().getContentType(); if (contentType == null || contentType.isEmpty()) { if (fileExtension.equals(".wav")) { contentType = "audio/x-wav"; } else { contentType = "video/mp4"; } } //Fetch recording and serve it from here return ok(recordingUri.toURL().openStream(), contentType).build(); } } else { String path = configuration.getString("recordings-path"); if (!path.endsWith("/")) { path += "/"; } String fileExtension = ".wav"; if (recording.getFileUri() != null) { fileExtension = recording.getFileUri().toString().endsWith("wav") ? ".wav" : ".mp4"; } path += sid.toString() + fileExtension; File recordingFile = new File(URI.create(path)); if (recordingFile.exists()) { //Fetch recording and serve it from here String contentType; if (fileExtension.equals(".wav")) { contentType = "audio/x-wav"; } else { contentType = "video/mp4"; } return ok(recordingFile, contentType).build(); } else { return status(NOT_FOUND).build(); } } } catch (Exception e) { if (logger.isInfoEnabled()) { logger.info("Problem during preparation of Recording file link, ", e); } } } return status(Response.Status.NOT_FOUND).build(); } protected Response deleteRecording(final String accountSid, final String sid, UserIdentityContext userIdentityContext) { Account operatedAccount = accountsDao.getAccount(accountSid); permissionEvaluator.secure(operatedAccount, "RestComm:Delete:Recordings", userIdentityContext); final Recording recording = dao.getRecording(new Sid(sid)); if (recording == null) { return status(NOT_FOUND).build(); } else { permissionEvaluator.secure(operatedAccount, recording.getAccountSid(), SecuredType.SECURED_STANDARD, userIdentityContext); recordingService.removeRecording(recording.getSid()); return Response.status(Response.Status.OK).build(); } } @Path("/{sid}.wav") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getRecordingAsWav(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid) { return getRecordingFile(accountSid, sid); } @Path("/{sid}.mp4") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getRecordingAsMp4(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid) { return getRecordingFile(accountSid, sid); } @Path("/{sid}") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getRecordingAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getRecording(accountSid, sid, retrieveMediaType(accept), ContextUtil.convert(sec)); } @Path("/{sid}") @DELETE @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response deleteRecording(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, @Context SecurityContext sec) { return deleteRecording(accountSid, sid, ContextUtil.convert(sec)); } @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getRecordings(@PathParam("accountSid") final String accountSid, @Context UriInfo info, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getRecordings(accountSid, info, retrieveMediaType(accept), ContextUtil.convert(sec)); } }
22,417
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AnnouncementsEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/AnnouncementsEndpoint.java
package org.restcomm.connect.http; import akka.actor.Actor; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.UntypedActor; import akka.actor.UntypedActorFactory; import static akka.pattern.Patterns.ask; import akka.util.Timeout; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.thoughtworks.xstream.XStream; import java.net.URI; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.servlet.ServletContext; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.MediaType.APPLICATION_XML_TYPE; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.ok; import javax.ws.rs.core.SecurityContext; import org.apache.commons.configuration.Configuration; import org.apache.log4j.Logger; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.cache.DiskCacheFactory; import org.restcomm.connect.commons.cache.DiskCacheRequest; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.AccountsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.entities.Announcement; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.http.converter.AnnouncementConverter; import org.restcomm.connect.http.converter.AnnouncementListConverter; import org.restcomm.connect.http.converter.RestCommResponseConverter; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.identity.UserIdentityContext; import org.restcomm.connect.tts.api.SpeechSynthesizerRequest; import org.restcomm.connect.tts.api.SpeechSynthesizerResponse; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; /** * requested by specific customer,no longer used * @author <a href="mailto:[email protected]">George Vagenas</a> */ //@Path("/Accounts/{accountSid}/Announcements") @ThreadSafe @Deprecated() public class AnnouncementsEndpoint extends AbstractEndpoint { private static Logger logger = Logger.getLogger(AnnouncementsEndpoint.class); @Context private ServletContext context; private Configuration configuration; private Configuration runtime; private ActorRef synthesizer; private ActorRef cache; private Gson gson; private XStream xstream; private URI uri; private ActorSystem system; private AccountsDao accountsDao; public AnnouncementsEndpoint() { super(); } @PostConstruct public void init() { system = (ActorSystem) context.getAttribute(ActorSystem.class.getName()); configuration = (Configuration) context.getAttribute(Configuration.class.getName()); Configuration ttsConfiguration = configuration.subset("speech-synthesizer"); runtime = configuration.subset("runtime-settings"); final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); this.accountsDao = storage.getAccountsDao(); synthesizer = tts(ttsConfiguration); super.init(runtime); final AnnouncementConverter converter = new AnnouncementConverter(configuration); final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Announcement.class, converter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(new AnnouncementListConverter(configuration)); xstream.registerConverter(new RestCommResponseConverter(configuration)); } public Response putAnnouncement(final String accountSid, final MultivaluedMap<String, String> data, final MediaType responseType, UserIdentityContext userIdentityContext) throws Exception { permissionEvaluator.secure(accountsDao.getAccount(accountSid), "RestComm:Create:Announcements", userIdentityContext); if(cache == null) createCacheActor(accountSid); Announcement announcement = createFrom(accountSid, data); if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(announcement), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(announcement); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } private void createCacheActor(final String accountId) { String path = runtime.getString("cache-path"); if (!path.endsWith("/")) { path = path + "/"; } path = path + accountId.toString(); String uri = runtime.getString("cache-uri"); if (!uri.endsWith("/")) { uri = uri + "/"; } uri = uri + accountId.toString(); this.cache = cache(path, uri); } private void precache(final String text, final String gender, final String language) throws Exception { if(logger.isInfoEnabled()){ logger.info("Synthesizing announcement"); } final SpeechSynthesizerRequest synthesize = new SpeechSynthesizerRequest(gender, language, text); Timeout expires = new Timeout(Duration.create(6000, TimeUnit.SECONDS)); Future<Object> future = (Future<Object>) ask(synthesizer, synthesize, expires); Object object = Await.result(future, Duration.create(6000, TimeUnit.SECONDS)); if(object != null) { SpeechSynthesizerResponse<URI> response = (SpeechSynthesizerResponse<URI>)object; uri = response.get(); } final DiskCacheRequest request = new DiskCacheRequest(uri); if(logger.isInfoEnabled()){ logger.info("Caching announcement"); } cache.tell(request, null); } private Announcement createFrom(String accountSid, MultivaluedMap<String, String> data) throws Exception { Sid sid = Sid.generate(Sid.Type.ANNOUNCEMENT); String gender = data.getFirst("Gender"); if (gender == null) { gender = "man"; } String language = data.getFirst("Language"); if (language == null) { language = "en"; } String text = data.getFirst("Text"); if (text != null) { precache(text, gender, language); } if(logger.isInfoEnabled()){ logger.info("Creating annnouncement"); } Announcement announcement = new Announcement(sid, new Sid(accountSid), gender, language, text, uri); return announcement; } private ActorRef tts(final Configuration configuration) { final String classpath = configuration.getString("[@class]"); final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public Actor create() throws Exception { return (UntypedActor) Class.forName(classpath).getConstructor(Configuration.class).newInstance(configuration); } }); return system.actorOf(props); } private ActorRef cache(final String path, final String uri) { final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public Actor create() throws Exception { return new DiskCacheFactory(configuration).getDiskCache(path, uri); } }); return system.actorOf(props); } @PreDestroy private void cleanup() { if(logger.isInfoEnabled()){ logger.info("Stopping actors before endpoint destroy"); } system.stop(cache); system.stop(synthesizer); } @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response putAnnouncement(@PathParam("accountSid") final String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) throws Exception { return putAnnouncement(accountSid, data, retrieveMediaType(accept),ContextUtil.convert(sec)); } }
8,853
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
UNLINK.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/UNLINK.java
package org.restcomm.connect.http; /* * 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/> * */ import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.ws.rs.HttpMethod; /** * * @author */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @HttpMethod("UNLINK") public @interface UNLINK { }
1,181
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ClientsEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/ClientsEndpoint.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.restcomm.connect.http; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import java.net.URI; import java.util.List; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.MediaType.APPLICATION_XML_TYPE; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.Status.CONFLICT; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.ok; import static javax.ws.rs.core.Response.status; import javax.ws.rs.core.SecurityContext; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.commons.util.ClientLoginConstrains; import org.restcomm.connect.dao.ClientsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.Client; import org.restcomm.connect.dao.entities.ClientList; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.http.converter.ClientConverter; import org.restcomm.connect.http.converter.ClientListConverter; import org.restcomm.connect.http.converter.RestCommResponseConverter; import org.restcomm.connect.http.exceptions.PasswordTooWeak; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.http.security.PermissionEvaluator; import org.restcomm.connect.http.security.PermissionEvaluator.SecuredType; import org.restcomm.connect.identity.UserIdentityContext; import org.restcomm.connect.identity.passwords.PasswordValidator; import org.restcomm.connect.identity.passwords.PasswordValidatorFactory; /** * @author [email protected] (Thomas Quintana) */ @Path("/Accounts/{accountSid}/Clients") @ThreadSafe @Singleton public class ClientsEndpoint extends AbstractEndpoint { @Context private ServletContext context; private Configuration configuration; protected ClientsDao dao; private Gson gson; private XStream xstream; public ClientsEndpoint() { super(); } @PostConstruct public void init() { final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); dao = storage.getClientsDao(); configuration = (Configuration) context.getAttribute(Configuration.class.getName()); configuration = configuration.subset("runtime-settings"); super.init(configuration); final ClientConverter converter = new ClientConverter(configuration); final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Client.class, converter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(new ClientListConverter(configuration)); xstream.registerConverter(new RestCommResponseConverter(configuration)); } private Client createFrom(final Sid accountSid, final MultivaluedMap<String, String> data) throws PasswordTooWeak { final Client.Builder builder = Client.builder(); final Sid sid = Sid.generate(Sid.Type.CLIENT); builder.setSid(sid); builder.setApiVersion(getApiVersion(data)); builder.setFriendlyName(getFriendlyName(data.getFirst("Login"), data)); builder.setAccountSid(accountSid); String username = data.getFirst("Login"); builder.setLogin(username); // Validate the password. Should be strong enough String password = data.getFirst("Password"); PasswordValidator validator = PasswordValidatorFactory.createDefault(); if (!validator.isStrongEnough(password)) throw new PasswordTooWeak(); String realm = organizationsDao.getOrganization(accountsDao.getAccount(accountSid).getOrganizationSid()).getDomainName(); builder.setPasswordAlgorithm(RestcommConfiguration.getInstance().getMain().getClientAlgorithm()); builder.setPassword(username, password, realm, RestcommConfiguration.getInstance().getMain().getClientAlgorithm()); builder.setStatus(getStatus(data)); URI voiceUrl = getUrl("VoiceUrl", data); if (voiceUrl != null && voiceUrl.toString().equals("")) { voiceUrl=null; } builder.setVoiceUrl(voiceUrl); String method = getMethod("VoiceMethod", data); if (method == null || method.isEmpty() || method.equals("")) { method = "POST"; } builder.setVoiceMethod(method); builder.setVoiceFallbackUrl(getUrl("VoiceFallbackUrl", data)); builder.setVoiceFallbackMethod(getMethod("VoiceFallbackMethod", data)); // skip null/empty VoiceApplicationSid's (i.e. leave null) if (data.containsKey("VoiceApplicationSid")) { if ( ! org.apache.commons.lang.StringUtils.isEmpty( data.getFirst("VoiceApplicationSid") ) ) builder.setVoiceApplicationSid(getSid("VoiceApplicationSid", data)); } final StringBuilder buffer = new StringBuilder(); buffer.append("/").append(getApiVersion(data)).append("/Accounts/").append(accountSid.toString()) .append("/Clients/").append(sid.toString()); builder.setUri(URI.create(buffer.toString())); if (data.containsKey("IsPushEnabled") && getBoolean("IsPushEnabled", data)) { builder.setPushClientIdentity(sid.toString()); } return builder.build(); } protected Response getClient(final String accountSid, final String sid, final MediaType responseType, UserIdentityContext userIdentityContext) { Account operatedAccount = accountsDao.getAccount(accountSid); permissionEvaluator.secure(operatedAccount, "RestComm:Read:Clients", userIdentityContext); final Client client = dao.getClient(new Sid(sid)); if (client == null) { return status(NOT_FOUND).build(); } else { permissionEvaluator.secure(operatedAccount, client.getAccountSid(), SecuredType.SECURED_STANDARD, userIdentityContext); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(client); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(client), APPLICATION_JSON).build(); } else { return null; } } } protected Response getClients(final String accountSid, final MediaType responseType, UserIdentityContext userIdentityContext) { permissionEvaluator.secure(accountsDao.getAccount(accountSid), "RestComm:Read:Clients", userIdentityContext); final List<Client> clients = dao.getClients(new Sid(accountSid)); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(new ClientList(clients)); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(clients), APPLICATION_JSON).build(); } else { return null; } } private String getFriendlyName(final String login, final MultivaluedMap<String, String> data) { String friendlyName = login; if (data.containsKey("FriendlyName")) { friendlyName = data.getFirst("FriendlyName"); } return friendlyName; } private int getStatus(final MultivaluedMap<String, String> data) { int status = Client.ENABLED; if (data.containsKey("Status")) { try { status = Integer.parseInt(data.getFirst("Status")); } catch (final NumberFormatException ignored) { } } return status; } public Response putClient(final String accountSid, final MultivaluedMap<String, String> data, final MediaType responseType, UserIdentityContext userIdentityContext) { final Account account = accountsDao.getAccount(accountSid); permissionEvaluator.secure(account, "RestComm:Create:Clients",userIdentityContext); try { validate(data); } catch (final NullPointerException | IllegalArgumentException exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } // Issue 109: https://bitbucket.org/telestax/telscale-restcomm/issue/109 Client client = dao.getClient(data.getFirst("Login"), account.getOrganizationSid()); if (client == null) { try { client = createFrom(new Sid(accountSid), data); } catch (PasswordTooWeak passwordTooWeak) { return status(BAD_REQUEST).entity(buildErrorResponseBody("Password too weak",responseType)).type(responseType).build(); } dao.addClient(client); } else if (!client.getAccountSid().toString().equals(accountSid)) { return status(CONFLICT) .entity("A client with the same name was already created by another account. Please, choose a different name and try again.") .build(); } if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(client); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(client), APPLICATION_JSON).build(); } else { return null; } } protected Response updateClient(final String accountSid, final String sid, final MultivaluedMap<String, String> data, final MediaType responseType, UserIdentityContext userIdentityContext) { Account operatedAccount = accountsDao.getAccount(accountSid); permissionEvaluator.secure(operatedAccount, "RestComm:Modify:Clients", userIdentityContext); Client client = dao.getClient(new Sid(sid)); if (client == null) { return status(NOT_FOUND).build(); } else { permissionEvaluator.secure(operatedAccount, client.getAccountSid(), SecuredType.SECURED_STANDARD, userIdentityContext); try { final String realm = organizationsDao.getOrganization(accountsDao.getAccount(client.getAccountSid()).getOrganizationSid()).getDomainName(); client = update(client, realm, data); dao.updateClient(client); } catch (PasswordTooWeak passwordTooWeak) { return status(BAD_REQUEST).entity(buildErrorResponseBody("Password too weak",responseType)).type(responseType).build(); } if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(client); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(client), APPLICATION_JSON).build(); } else { return null; } } } private void validate(final MultivaluedMap<String, String> data) throws RuntimeException { if (!data.containsKey("Login")) { throw new NullPointerException("Login can not be null."); } else if (!data.containsKey("Password")) { throw new NullPointerException("Password can not be null."); } // https://github.com/RestComm/Restcomm-Connect/issues/1979 && https://telestax.atlassian.net/browse/RESTCOMM-1797 if (!ClientLoginConstrains.isValidClientLogin(data.getFirst("Login"))) { String msg = String.format("Login %s contains invalid character(s)",data.getFirst("Login")); if (logger.isDebugEnabled()) { logger.debug(msg); } throw new IllegalArgumentException(msg); } } private Client update(Client client, String realm, final MultivaluedMap<String, String> data) throws PasswordTooWeak { if (data.containsKey("FriendlyName")) { client = client.setFriendlyName(data.getFirst("FriendlyName")); } if (data.containsKey("Password")) { String password = data.getFirst("Password"); PasswordValidator validator = PasswordValidatorFactory.createDefault(); if (!validator.isStrongEnough(password)) { throw new PasswordTooWeak(); } client = client.setPassword(client.getLogin(), password, realm); } if (data.containsKey("Status")) { client = client.setStatus(getStatus(data)); } if (data.containsKey("VoiceUrl")) { URI uri = getUrl("VoiceUrl", data); client = client.setVoiceUrl(isEmpty(uri.toString()) ? null : uri); } if (data.containsKey("VoiceMethod")) { client = client.setVoiceMethod(getMethod("VoiceMethod", data)); } if (data.containsKey("VoiceFallbackUrl")) { URI uri = getUrl("VoiceFallbackUrl", data); client = client.setVoiceFallbackUrl(isEmpty(uri.toString()) ? null :uri); } if (data.containsKey("VoiceFallbackMethod")) { client = client.setVoiceFallbackMethod(getMethod("VoiceFallbackMethod", data)); } if (data.containsKey("VoiceApplicationSid")) { if (org.apache.commons.lang.StringUtils.isEmpty(data.getFirst("VoiceApplicationSid"))) { client = client.setVoiceApplicationSid(null); } else { client = client.setVoiceApplicationSid(getSid("VoiceApplicationSid", data)); } } if (data.containsKey("IsPushEnabled")) { if (getBoolean("IsPushEnabled", data)) { client = client.setPushClientIdentity(client.getSid().toString()); } else { client = client.setPushClientIdentity(null); } } return client; } private Response deleteClient(final String accountSid, final String sid, UserIdentityContext userIdentityContext) { Account operatedAccount =super.accountsDao.getAccount(accountSid); permissionEvaluator.secure(operatedAccount, "RestComm:Delete:Clients", userIdentityContext); Client client = dao.getClient(new Sid(sid)); if (client != null) { permissionEvaluator.secure(operatedAccount, client.getAccountSid(), PermissionEvaluator.SecuredType.SECURED_STANDARD, userIdentityContext); dao.removeClient(new Sid(sid)); return ok().build(); } else { return status(Response.Status.NOT_FOUND).build(); } } @Path("/{sid}") @DELETE public Response deleteClientAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, @Context SecurityContext sec) { return deleteClient(accountSid, sid,ContextUtil.convert(sec)); } @Path("/{sid}") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getClientAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getClient(accountSid, sid, retrieveMediaType(accept), ContextUtil.convert(sec)); } @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getClients(@PathParam("accountSid") final String accountSid, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getClients(accountSid, retrieveMediaType(accept), ContextUtil.convert(sec)); } @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response putClient(@PathParam("accountSid") final String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return putClient(accountSid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } @Path("/{sid}") @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response updateClientAsXmlPost(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return updateClient(accountSid, sid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } @Path("/{sid}") @PUT @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response updateClientAsXmlPut(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return updateClient(accountSid, sid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } }
19,544
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
LogoutEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/LogoutEndpoint.java
package org.restcomm.connect.http; import com.sun.jersey.spi.resource.Singleton; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; /** * @author <a href="mailto:[email protected]">gvagenas</a> */ @Path("/Logout") @Singleton public class LogoutEndpoint extends AbstractEndpoint { @GET public Response logout(@Context HttpServletRequest request) { //SecurityUtils.getSubject().logout(); return Response.ok().build(); } }
566
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ProfileEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/ProfileEndpoint.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.restcomm.connect.http; import com.fasterxml.jackson.databind.JsonNode; import com.github.fge.jackson.JsonLoader; import com.github.fge.jsonschema.core.report.ProcessingReport; import com.github.fge.jsonschema.main.JsonSchema; import com.github.fge.jsonschema.main.JsonSchemaFactory; import com.sun.jersey.core.header.LinkHeader; import com.sun.jersey.core.header.LinkHeader.LinkHeaderBuilder; import com.sun.jersey.spi.resource.Singleton; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.nio.charset.Charset; import java.nio.file.Path; import java.nio.file.Paths; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.PostConstruct; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.servlet.ServletContext; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; import static javax.ws.rs.core.Response.status; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import org.apache.commons.configuration.Configuration; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.core.service.api.ProfileService; import org.restcomm.connect.dao.AccountsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.OrganizationsDao; import org.restcomm.connect.dao.ProfileAssociationsDao; import org.restcomm.connect.dao.ProfilesDao; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.Organization; import org.restcomm.connect.dao.entities.Profile; import static org.restcomm.connect.dao.entities.Profile.DEFAULT_PROFILE_SID; import org.restcomm.connect.dao.entities.ProfileAssociation; import org.restcomm.connect.http.exceptionmappers.CustomReasonPhraseType; import org.restcomm.connect.http.security.AccountPrincipal; import static org.restcomm.connect.http.security.AccountPrincipal.SUPER_ADMIN_ROLE; @javax.ws.rs.Path("/Profiles") @ThreadSafe @RolesAllowed(SUPER_ADMIN_ROLE) @Singleton public class ProfileEndpoint { protected Logger logger = Logger.getLogger(ProfileEndpoint.class); public static final String PROFILE_CONTENT_TYPE = "application/instance+json"; public static final String PROFILE_SCHEMA_CONTENT_TYPE = "application/schema+json"; public static final String PROFILE_REL_TYPE = "related"; public static final String SCHEMA_REL_TYPE = "schema"; public static final String DESCRIBED_REL_TYPE = "describedby"; public static final String LINK_HEADER = "Link"; public static final String PROFILE_ENCODING = "UTF-8"; public static final String TITLE_PARAM = "title"; public static final String ACCOUNTS_PREFIX = "AC"; public static final String ORGANIZATIONS_PREFIX = "OR"; @Context protected ServletContext context; private Configuration runtimeConfiguration; private Configuration rootConfiguration; // top-level configuration element private ProfilesDao profilesDao; private ProfileAssociationsDao profileAssociationsDao; private AccountsDao accountsDao; private OrganizationsDao organizationsDao; protected ProfileService profileService; private JsonNode schemaJson; private JsonSchema profileSchema; public ProfileEndpoint() { super(); } @PostConstruct void init() { rootConfiguration = (Configuration) context.getAttribute(Configuration.class.getName()); runtimeConfiguration = rootConfiguration.subset("runtime-settings"); final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); profileService = (ProfileService)context.getAttribute(ProfileService.class.getName()); profileAssociationsDao = storage.getProfileAssociationsDao(); this.accountsDao = storage.getAccountsDao(); this.organizationsDao = storage.getOrganizationsDao(); profilesDao = ((DaoManager) context.getAttribute(DaoManager.class.getName())).getProfilesDao(); try { schemaJson = JsonLoader.fromResource("/org/restcomm/connect/http/schemas/rc-profile-schema.json"); final JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); profileSchema = factory.getJsonSchema(schemaJson); } catch (Exception e) { logger.error("Error starting Profile endpoint.", e); } } class ProfileExt { Profile profile; String uri; public ProfileExt(Profile profile, String uri) { this.profile = profile; this.uri = uri; } public String getUri() { return uri; } public Date getDateCreated() { return profile.getDateCreated(); } public Date getDateUpdated() { return profile.getDateUpdated(); } public String getSid() { return profile.getSid(); } } public Response getProfiles(UriInfo info) { try { List<Profile> allProfiles = profilesDao.getAllProfiles(); List<ProfileExt> extProfiles = new ArrayList(allProfiles.size()); for (Profile pAux : allProfiles) { URI pURI = info.getBaseUriBuilder().path(this.getClass()).path(pAux.getSid()).build(); extProfiles.add(new ProfileExt(pAux, pURI.toString())); } GenericEntity<List<ProfileExt>> entity = new GenericEntity<List<ProfileExt>>(extProfiles) { }; return Response.ok(entity, MediaType.APPLICATION_JSON).build(); } catch (SQLException ex) { logger.debug("getting profiles", ex); return Response.serverError().entity(ex.getMessage()).build(); } } public Response unlinkProfile(String profileSidStr, HttpHeaders headers) { checkProfileExists(profileSidStr); List<String> requestHeader = checkLinkHeader(headers); LinkHeader link = LinkHeader.valueOf(requestHeader.get(0)); checkRelType(link); String targetSid = retrieveSid(link.getUri()); checkTargetSid(new Sid(targetSid)); profileAssociationsDao.deleteProfileAssociationByTargetSid(targetSid, profileSidStr); return Response.ok().build(); } private String retrieveSid(URI uri) { Path paths = Paths.get(uri.getPath()); return paths.getName(paths.getNameCount() - 1).toString(); } private void checkRelType(LinkHeader link) { if (!link.getRel().contains(PROFILE_REL_TYPE)) { logger.debug("Only related rel type supported"); CustomReasonPhraseType stat = new CustomReasonPhraseType(Response.Status.BAD_REQUEST, "Only related rel type supported"); throw new WebApplicationException(status(stat).build()); } } private List<String> checkLinkHeader(HttpHeaders headers) { List<String> requestHeader = headers.getRequestHeader(LINK_HEADER); if (requestHeader.size() != 1) { logger.debug("Only one Link supported"); CustomReasonPhraseType stat = new CustomReasonPhraseType(Response.Status.BAD_REQUEST, "Only one Link supported"); throw new WebApplicationException(status(stat).build()); } return requestHeader; } public Response linkProfile(String profileSidStr, HttpHeaders headers, UriInfo uriInfo) { checkProfileExists(profileSidStr); List<String> requestHeader = checkLinkHeader(headers); LinkHeader link = LinkHeader.valueOf(requestHeader.get(0)); checkRelType(link); String targetSidStr = retrieveSid(link.getUri()); Sid targetSid = new Sid(targetSidStr); checkTargetSid(targetSid); Sid profileSid = new Sid(profileSidStr); ProfileAssociation assoc = new ProfileAssociation(profileSid, targetSid, new Date(), new Date()); //remove previous link if any profileAssociationsDao.deleteProfileAssociationByTargetSid(targetSidStr); profileAssociationsDao.addProfileAssociation(assoc); return Response.ok().build(); } public Response deleteProfile(String profileSid) { checkProfileExists(profileSid); checkDefaultProfile(profileSid); profilesDao.deleteProfile(profileSid); profileAssociationsDao.deleteProfileAssociationByProfileSid(profileSid); return Response.ok().build(); } private void checkDefaultProfile(String profileSid) { if (profileSid.equals(DEFAULT_PROFILE_SID)) { logger.debug("Modififying default profile is forbidden"); CustomReasonPhraseType stat = new CustomReasonPhraseType(Response.Status.FORBIDDEN, "Modififying default profile is forbidden"); throw new WebApplicationException(status(stat).build()); } } private Profile checkProfileExists(String profileSid) { try { Profile profile = profilesDao.getProfile(profileSid); if (profile != null) { return profile; } else { if (logger.isDebugEnabled()) { logger.debug("Profile not found:" + profileSid); } CustomReasonPhraseType stat = new CustomReasonPhraseType(Response.Status.NOT_FOUND, "Profile not found"); throw new WebApplicationException(status(stat).build()); } } catch (SQLException ex) { logger.debug("SQL issue getting profile.", ex); CustomReasonPhraseType stat = new CustomReasonPhraseType(Response.Status.INTERNAL_SERVER_ERROR, "SQL issue getting profile."); throw new WebApplicationException(status(stat).build()); } } public Response updateProfile(String profileSid, InputStream body, UriInfo info) { checkProfileExists(profileSid); checkDefaultProfile(profileSid); try { String profileStr = IOUtils.toString(body, Charset.forName(PROFILE_ENCODING)); final JsonNode profileJson = JsonLoader.fromString(profileStr); ProcessingReport report = profileSchema.validate(profileJson); if (report.isSuccess()) { Profile profile = new Profile(profileSid, profileStr, new Date(), new Date()); profilesDao.updateProfile(profile); Profile updatedProfile = profilesDao.getProfile(profileSid); return getProfileBuilder(updatedProfile, info).build(); } else { return Response.status(Response.Status.BAD_REQUEST).entity(report.toString()).build(); } } catch (Exception ex) { logger.debug("updating profiles", ex); return Response.serverError().entity(ex.getMessage()).build(); } } public LinkHeader composeSchemaLink(UriInfo info) throws MalformedURLException { URI build = info.getBaseUriBuilder().path(this.getClass()).path("/schemas/rc-profile-schema.json").build(); return LinkHeader.uri(build).rel(DESCRIBED_REL_TYPE).build(); } /** * * @param sid * @return first two chars in sid */ private String extractSidPrefix(Sid sid) { return sid.toString().substring(0, 2); } public LinkHeader composeLink(Sid targetSid, UriInfo info) throws MalformedURLException { String sid = targetSid.toString(); URI uri = null; LinkHeaderBuilder link = null; switch (extractSidPrefix(targetSid)) { case ACCOUNTS_PREFIX: uri = info.getBaseUriBuilder().path(AccountsEndpoint.class).path(sid).build(); link = LinkHeader.uri(uri).parameter(TITLE_PARAM, "Accounts"); break; case ORGANIZATIONS_PREFIX: uri = info.getBaseUriBuilder().path(AccountsEndpoint.class).path(sid).build(); link = LinkHeader.uri(uri).parameter(TITLE_PARAM, "Organizations"); break; default: } if (link != null) { return link.rel(PROFILE_REL_TYPE).build(); } else { return null; } } public void checkTargetSid(Sid sid) { switch (extractSidPrefix(sid)) { case ACCOUNTS_PREFIX: Account acc = accountsDao.getAccount(sid); if (acc == null) { CustomReasonPhraseType stat = new CustomReasonPhraseType(Response.Status.NOT_FOUND, "Account not found"); throw new WebApplicationException(status(stat).build()); } break; case ORGANIZATIONS_PREFIX: Organization org = organizationsDao.getOrganization(sid); if (org == null) { CustomReasonPhraseType stat = new CustomReasonPhraseType(Response.Status.NOT_FOUND, "Organization not found"); throw new WebApplicationException(status(stat).build()); } break; default: CustomReasonPhraseType stat = new CustomReasonPhraseType(Response.Status.NOT_FOUND, "Link not supported"); throw new WebApplicationException(status(stat).build()); } } public ResponseBuilder getProfileBuilder(Profile profile , UriInfo info) { try { Response.ResponseBuilder ok = Response.ok(profile.getProfileDocument()); List<ProfileAssociation> profileAssociationsByProfileSid = profileAssociationsDao.getProfileAssociationsByProfileSid(profile.getSid()); for (ProfileAssociation assoc : profileAssociationsByProfileSid) { LinkHeader composeLink = composeLink(assoc.getTargetSid(), info); ok.header(LINK_HEADER, composeLink.toString()); } ok.header(LINK_HEADER, composeSchemaLink(info)); String profileStr = profile.getProfileDocument();// IOUtils.toString(profile.getProfileDocument(), PROFILE_ENCODING); ok.entity(profileStr); ok.lastModified(profile.getDateUpdated()); ok.type(PROFILE_CONTENT_TYPE); return ok; } catch (Exception ex) { logger.debug("getting profile", ex); return Response.serverError().entity(ex.getMessage()); } } private void checkProfileAccess(String profileSid, SecurityContext secCtx) { AccountPrincipal userPrincipal = (AccountPrincipal) secCtx.getUserPrincipal(); if (!userPrincipal.isSuperAdmin()) { Sid accountSid = userPrincipal.getIdentityContext().getAccountKey().getAccount().getSid(); Profile effectiveProfile = profileService.retrieveEffectiveProfileByAccountSid(accountSid); if (!effectiveProfile.getSid().equals(profileSid)) { CustomReasonPhraseType stat = new CustomReasonPhraseType(Response.Status.FORBIDDEN, "Profile not linked"); throw new WebApplicationException(status(stat).build()); } } } public Response getProfile(String profileSid, UriInfo info, SecurityContext secCtx) { Profile profile = checkProfileExists(profileSid); checkProfileAccess(profileSid, secCtx); return getProfileBuilder(profile, info).build(); } public Response createProfile(InputStream body, UriInfo info) { Response response; try { Sid profileSid = Sid.generate(Sid.Type.PROFILE); String profileStr = IOUtils.toString(body, Charset.forName(PROFILE_ENCODING)); final JsonNode profileJson = JsonLoader.fromString(profileStr); ProcessingReport report = profileSchema.validate(profileJson); if (report.isSuccess()) { Profile profile = new Profile(profileSid.toString(), profileStr, new Date(), new Date()); profilesDao.addProfile(profile); URI location = info.getBaseUriBuilder().path(this.getClass()).path(profileSid.toString()).build(); Profile createdProfile = profilesDao.getProfile(profileSid.toString()); response = getProfileBuilder(createdProfile, info).status(Status.CREATED).location(location).build(); } else { response = Response.status(Response.Status.BAD_REQUEST).entity(report.toString()).build(); } } catch (Exception ex) { logger.debug("creating profile", ex); return Response.serverError().entity(ex.getMessage()).build(); } return response; } public Response getSchema(String schemaId) { try { JsonNode schema = JsonLoader.fromResource("/org/restcomm/connect/http/schemas/" + schemaId); return Response.ok(schema.toString(), PROFILE_SCHEMA_CONTENT_TYPE).build(); } catch (IOException ex) { logger.debug("getting schema", ex); return Response.status(Status.NOT_FOUND).build(); } } private static final String OVERRIDE_HDR = "X-HTTP-Method-Override"; @GET @Produces(APPLICATION_JSON) public Response getProfilesAsJson(@Context UriInfo info) { return getProfiles(info); } @POST @Consumes({PROFILE_CONTENT_TYPE, APPLICATION_JSON}) @Produces({PROFILE_CONTENT_TYPE, APPLICATION_JSON}) public Response createProfileAsJson(InputStream body, @Context UriInfo info) { return createProfile(body, info); } @javax.ws.rs.Path("/{profileSid}") @GET @Produces({PROFILE_CONTENT_TYPE, MediaType.APPLICATION_JSON}) @PermitAll public Response getProfileAsJson(@PathParam("profileSid") final String profileSid, @Context UriInfo info, @Context SecurityContext secCtx) { return getProfile(profileSid, info, secCtx); } @javax.ws.rs.Path("/{profileSid}") @PUT @Consumes({PROFILE_CONTENT_TYPE, MediaType.APPLICATION_JSON}) @Produces({PROFILE_CONTENT_TYPE, MediaType.APPLICATION_JSON}) public Response updateProfileAsJson(@PathParam("profileSid") final String profileSid, InputStream body, @Context UriInfo info, @Context HttpHeaders headers) { if (headers.getRequestHeader(OVERRIDE_HDR) != null && headers.getRequestHeader(OVERRIDE_HDR).size() > 0) { String overrideHdr = headers.getRequestHeader(OVERRIDE_HDR).get(0); switch (overrideHdr) { case "LINK": return linkProfile(profileSid, headers, info); case "UNLINK": return unlinkProfile(profileSid, headers); } } return updateProfile(profileSid, body, info); } @javax.ws.rs.Path("/{profileSid}") @DELETE public Response deleteProfileAsJson(@PathParam("profileSid") final String profileSid) { return deleteProfile(profileSid); } @javax.ws.rs.Path("/{profileSid}") @LINK @Produces(APPLICATION_JSON) public Response linkProfileAsJson(@PathParam("profileSid") final String profileSid, @Context HttpHeaders headers, @Context UriInfo info ) { return linkProfile(profileSid, headers, info); } @javax.ws.rs.Path("/{profileSid}") @UNLINK @Produces(APPLICATION_JSON) public Response unlinkProfileAsJson(@PathParam("profileSid") final String profileSid, @Context HttpHeaders headers) { return unlinkProfile(profileSid, headers); } @javax.ws.rs.Path("/schemas/{schemaId}") @GET @Produces({PROFILE_SCHEMA_CONTENT_TYPE, MediaType.APPLICATION_JSON}) @PermitAll public Response getProfileSchemaAsJson(@PathParam("schemaId") final String schemaId) { return getSchema(schemaId); } }
21,256
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AvailablePhoneNumbersEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/AvailablePhoneNumbersEndpoint.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.restcomm.connect.http; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR; import static javax.ws.rs.core.Response.ok; import static javax.ws.rs.core.Response.status; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.loader.ObjectInstantiationException; import org.restcomm.connect.dao.entities.AvailablePhoneNumber; import org.restcomm.connect.dao.entities.AvailablePhoneNumberList; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.http.converter.AvailablePhoneNumberConverter; import org.restcomm.connect.http.converter.AvailablePhoneNumberListConverter; import org.restcomm.connect.http.converter.RestCommResponseConverter; import org.restcomm.connect.identity.UserIdentityContext; import org.restcomm.connect.provisioning.number.api.PhoneNumber; import org.restcomm.connect.provisioning.number.api.PhoneNumberProvisioningManager; import org.restcomm.connect.provisioning.number.api.PhoneNumberProvisioningManagerProvider; import org.restcomm.connect.provisioning.number.api.PhoneNumberSearchFilters; /** * @author [email protected] (Thomas Quintana) * @author [email protected] */ @ThreadSafe @Singleton public class AvailablePhoneNumbersEndpoint extends AbstractEndpoint { @Context private ServletContext context; private PhoneNumberProvisioningManager phoneNumberProvisioningManager; private XStream xstream; private Gson gson; public AvailablePhoneNumbersEndpoint() { super(); } @PostConstruct public void init() throws ObjectInstantiationException { configuration = (Configuration) context.getAttribute(Configuration.class.getName()); super.init(configuration.subset("runtime-settings")); /* phoneNumberProvisioningManager = (PhoneNumberProvisioningManager) context.getAttribute("PhoneNumberProvisioningManager"); if(phoneNumberProvisioningManager == null) { final String phoneNumberProvisioningManagerClass = configuration.getString("phone-number-provisioning[@class]"); Configuration phoneNumberProvisioningConfiguration = configuration.subset("phone-number-provisioning"); Configuration telestaxProxyConfiguration = configuration.subset("runtime-settings").subset("telestax-proxy"); phoneNumberProvisioningManager = (PhoneNumberProvisioningManager) new ObjectFactory(getClass().getClassLoader()) .getObjectInstance(phoneNumberProvisioningManagerClass); ContainerConfiguration containerConfiguration = new ContainerConfiguration(getOutboundInterfaces()); phoneNumberProvisioningManager.init(phoneNumberProvisioningConfiguration, telestaxProxyConfiguration, containerConfiguration); context.setAttribute("phoneNumberProvisioningManager", phoneNumberProvisioningManager); } */ // get manager from context or create it if it does not exist phoneNumberProvisioningManager = new PhoneNumberProvisioningManagerProvider(configuration, context).get(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(new AvailablePhoneNumberConverter(configuration)); xstream.registerConverter(new AvailablePhoneNumberListConverter(configuration)); xstream.registerConverter(new RestCommResponseConverter(configuration)); final GsonBuilder builder = new GsonBuilder(); builder.setPrettyPrinting(); // builder.serializeNulls(); gson = builder.create(); } protected Response getAvailablePhoneNumbers(final String accountSid, final String isoCountryCode, PhoneNumberSearchFilters listFilters, String filterPattern, final MediaType responseType, UserIdentityContext userIdentityContext) { permissionEvaluator.secure(accountsDao.getAccount(accountSid), "RestComm:Read:AvailablePhoneNumbers", userIdentityContext); String searchPattern = ""; if (filterPattern != null && !filterPattern.isEmpty()) { for(int i = 0; i < filterPattern.length(); i ++) { char c = filterPattern.charAt(i); boolean isDigit = (c >= '0' && c <= '9'); boolean isStar = c == '*'; if(!isDigit && !isStar) { searchPattern = searchPattern.concat(getNumber(c)); } else if (isStar) { searchPattern = searchPattern.concat("\\d"); } else { searchPattern = searchPattern.concat(Character.toString(c)); } } // completing the pattern to match any substring of the number searchPattern = "((" + searchPattern + ")+).*"; Pattern pattern = Pattern.compile(searchPattern); listFilters.setFilterPattern(pattern); } final List<PhoneNumber> phoneNumbers = phoneNumberProvisioningManager.searchForNumbers(isoCountryCode, listFilters); List<AvailablePhoneNumber> availablePhoneNumbers = toAvailablePhoneNumbers(phoneNumbers); if (MediaType.APPLICATION_XML_TYPE.equals(responseType)) { return ok(xstream.toXML(new RestCommResponse(new AvailablePhoneNumberList(availablePhoneNumbers))), MediaType.APPLICATION_XML).build(); } else if (MediaType.APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(phoneNumbers), MediaType.APPLICATION_JSON).build(); } return status(INTERNAL_SERVER_ERROR).build(); // } else { // return status(BAD_REQUEST).build(); // } } // TODO refactor this to see if we can have a single object instead of copying things private List<AvailablePhoneNumber> toAvailablePhoneNumbers(List<PhoneNumber> phoneNumbers) { final List<AvailablePhoneNumber> availablePhoneNumbers = new ArrayList<AvailablePhoneNumber>(); for (PhoneNumber phoneNumber : phoneNumbers) { final AvailablePhoneNumber number = new AvailablePhoneNumber(phoneNumber.getFriendlyName(), phoneNumber.getPhoneNumber(), phoneNumber.getLata(), phoneNumber.getRateCenter(), phoneNumber.getLatitude(), phoneNumber.getLongitude(), phoneNumber.getRegion(), phoneNumber.getPostalCode(), phoneNumber.getIsoCountry(), phoneNumber.getCost(), phoneNumber.isVoiceCapable(), phoneNumber.isSmsCapable(), phoneNumber.isMmsCapable(), phoneNumber.isFaxCapable()); availablePhoneNumbers.add(number); } return availablePhoneNumbers; } public static String getNumber(char letter) { if (letter == 'A' || letter == 'B' || letter == 'C' || letter == 'a' || letter == 'b' || letter == 'c') { return "1"; } else if (letter == 'D' || letter == 'E' || letter == 'F' || letter == 'd' || letter == 'e' || letter == 'f') { return "2"; } else if (letter == 'G' || letter == 'H' || letter == 'I' || letter == 'g' || letter == 'h' || letter == 'i') { return "3"; } else if (letter == 'J' || letter == 'K' || letter == 'L' || letter == 'j' || letter == 'k' || letter == 'l') { return "4"; } else if (letter == 'M' || letter == 'N' || letter == 'O' || letter == 'm' || letter == 'n' || letter == 'o') { return "5"; } else if (letter == 'P' || letter == 'Q' || letter == 'R' || letter == 'S' || letter == 'p' || letter == 'q' || letter == 'r' || letter == 's') { return "6"; } else if (letter == 'T' || letter == 'U' || letter == 'V' || letter == 't' || letter == 'u' || letter == 'v') { return "7"; } else if (letter == 'W' || letter == 'X' || letter == 'Y' || letter == 'Z' || letter == 'w' || letter == 'x' || letter == 'y' || letter == 'z') { return "9"; } return "0"; } /* @SuppressWarnings("unchecked") private List<SipURI> getOutboundInterfaces() { final List<SipURI> uris = (List<SipURI>) context.getAttribute(SipServlet.OUTBOUND_INTERFACES); return uris; } */ }
9,602
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
OutboundProxyEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/OutboundProxyEndpoint.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.restcomm.connect.http; import akka.actor.ActorRef; import static akka.pattern.Patterns.ask; import akka.util.Timeout; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.annotation.security.RolesAllowed; import javax.servlet.ServletContext; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.MediaType.APPLICATION_XML_TYPE; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR; import static javax.ws.rs.core.Response.ok; import static javax.ws.rs.core.Response.status; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.http.converter.RestCommResponseConverter; import static org.restcomm.connect.http.security.AccountPrincipal.SUPER_ADMIN_ROLE; import org.restcomm.connect.telephony.api.GetActiveProxy; import org.restcomm.connect.telephony.api.GetProxies; import org.restcomm.connect.telephony.api.SwitchProxy; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; /** * @author <a href="mailto:[email protected]">gvagenas</a> * */ @Path("/Accounts/{accountSid}/OutboundProxy") @ThreadSafe @RolesAllowed(SUPER_ADMIN_ROLE) @Singleton public class OutboundProxyEndpoint extends AbstractEndpoint { @Context protected ServletContext context; protected Configuration configuration; private ActorRef callManager; private Gson gson; private GsonBuilder builder; private XStream xstream; public OutboundProxyEndpoint() { super(); } @PostConstruct public void init() { configuration = (Configuration) context.getAttribute(Configuration.class.getName()); configuration = configuration.subset("runtime-settings"); callManager = (ActorRef) context.getAttribute("org.restcomm.connect.telephony.CallManager"); super.init(configuration); builder = new GsonBuilder(); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(new RestCommResponseConverter(configuration)); } protected Response getProxies(final String accountSid, final MediaType responseType) { Map<String, String> proxies; final Timeout expires = new Timeout(Duration.create(60, TimeUnit.SECONDS)); try { Future<Object> future = (Future<Object>) ask(callManager, new GetProxies(), expires); proxies = (Map<String, String>) Await.result(future, Duration.create(10, TimeUnit.SECONDS)); } catch (Exception exception) { return status(INTERNAL_SERVER_ERROR).entity(exception.getMessage()).build(); } if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(proxies); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(proxies), APPLICATION_JSON).build(); } else { return null; } } protected Response switchProxy(final String accountSid, final MediaType responseType) { Map<String, String> proxyAfterSwitch; final Timeout expires = new Timeout(Duration.create(60, TimeUnit.SECONDS)); try { Future<Object> future = (Future<Object>) ask(callManager, new SwitchProxy(new Sid(accountSid)), expires); proxyAfterSwitch = (Map<String, String>) Await.result(future, Duration.create(10, TimeUnit.SECONDS)); } catch (Exception exception) { return status(INTERNAL_SERVER_ERROR).entity(exception.getMessage()).build(); } if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(proxyAfterSwitch); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(proxyAfterSwitch), APPLICATION_JSON).build(); } else { return null; } } protected Response getActiveProxy(final String accountSid, final MediaType responseType) { Map<String, String> activeProxy; final Timeout expires = new Timeout(Duration.create(60, TimeUnit.SECONDS)); try { Future<Object> future = (Future<Object>) ask(callManager, new GetActiveProxy(), expires); activeProxy = (Map<String, String>) Await.result(future, Duration.create(10, TimeUnit.SECONDS)); } catch (Exception exception) { return status(INTERNAL_SERVER_ERROR).entity(exception.getMessage()).build(); } if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(activeProxy); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(activeProxy), APPLICATION_JSON).build(); } else { return null; } } @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getProxies(@PathParam("accountSid") final String accountSid, @HeaderParam("Accept") String accept) { return getProxies(accountSid, retrieveMediaType(accept)); } @GET @Path("/switchProxy") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response switchProxy(@PathParam("accountSid") final String accountSid, @HeaderParam("Accept") String accept) { return switchProxy(accountSid, retrieveMediaType(accept)); } @GET @Path("/getActiveProxy") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getActiveProxy(@PathParam("accountSid") final String accountSid, @HeaderParam("Accept") String accept) { return getActiveProxy(accountSid, retrieveMediaType(accept)); } }
7,653
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AvailablePhoneNumbersXmlEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/AvailablePhoneNumbersXmlEndpoint.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.restcomm.connect.http; import com.sun.jersey.spi.container.ResourceFilters; import com.sun.jersey.spi.resource.Singleton; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.*; import static javax.ws.rs.core.Response.Status.*; import javax.ws.rs.core.SecurityContext; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.http.filters.ExtensionFilter; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.provisioning.number.api.PhoneNumberSearchFilters; import org.restcomm.connect.provisioning.number.api.PhoneNumberType; /** * @author <a href="mailto:[email protected]">gvagenas</a> * @author <a href="mailto:[email protected]">Jean Deruelle</a> */ @Path("/Accounts/{accountSid}/AvailablePhoneNumbers/{IsoCountryCode}/Local") @ThreadSafe @Singleton public class AvailablePhoneNumbersXmlEndpoint extends AvailablePhoneNumbersEndpoint { public AvailablePhoneNumbersXmlEndpoint() { super(); } @GET @ResourceFilters({ ExtensionFilter.class }) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getAvailablePhoneNumber(@PathParam("accountSid") final String accountSid, @PathParam("IsoCountryCode") final String isoCountryCode, @QueryParam("AreaCode") String areaCode, @QueryParam("Contains") String filterPattern, @QueryParam("SmsEnabled") String smsEnabled, @QueryParam("MmsEnabled") String mmsEnabled, @QueryParam("VoiceEnabled") String voiceEnabled, @QueryParam("FaxEnabled") String faxEnabled, @QueryParam("UssdEnabled") String ussdEnabled, @QueryParam("NearNumber") String nearNumber, @QueryParam("NearLatLong") String nearLatLong, @QueryParam("Distance") String distance, @QueryParam("InPostalCode") String inPostalCode, @QueryParam("InRegion") String inRegion, @QueryParam("InRateCenter") String inRateCenter, @QueryParam("InLata") String inLata, @QueryParam("RangeSize") String rangeSize, @QueryParam("RangeIndex") String rangeIndex, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { if (isoCountryCode != null && !isoCountryCode.isEmpty()) { int rangeSizeInt = -1; if (rangeSize != null && !rangeSize.isEmpty()) { rangeSizeInt = Integer.parseInt(rangeSize); } int rangeIndexInt = -1; if (rangeIndex != null && !rangeIndex.isEmpty()) { rangeIndexInt = Integer.parseInt(rangeIndex); } Boolean smsEnabledBool = null; if (smsEnabled != null && !smsEnabled.isEmpty()) { smsEnabledBool = Boolean.valueOf(smsEnabled); } Boolean mmsEnabledBool = null; if (mmsEnabled != null && !mmsEnabled.isEmpty()) { mmsEnabledBool = Boolean.valueOf(mmsEnabled); } Boolean voiceEnabledBool = null; if (voiceEnabled != null && !voiceEnabled.isEmpty()) { voiceEnabledBool = Boolean.valueOf(voiceEnabled); } Boolean faxEnabledBool = null; if (faxEnabled != null && !faxEnabled.isEmpty()) { faxEnabledBool = Boolean.valueOf(faxEnabled); } Boolean ussdEnabledBool = null; if (ussdEnabled != null && !ussdEnabled.isEmpty()) { ussdEnabledBool = Boolean.valueOf(ussdEnabled); } PhoneNumberType phoneNumberType = PhoneNumberType.Local; if(!isoCountryCode.equalsIgnoreCase("US")) { phoneNumberType = PhoneNumberType.Global; } PhoneNumberSearchFilters listFilters = new PhoneNumberSearchFilters(areaCode, null, smsEnabledBool, mmsEnabledBool, voiceEnabledBool, faxEnabledBool, ussdEnabledBool, nearNumber, nearLatLong, distance, inPostalCode, inRegion, inRateCenter, inLata, rangeSizeInt, rangeIndexInt, phoneNumberType); return getAvailablePhoneNumbers(accountSid, isoCountryCode, listFilters, filterPattern, retrieveMediaType(accept), ContextUtil.convert(sec)); } else { return status(BAD_REQUEST).build(); } } }
5,453
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
OutgoingCallerIdsEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/OutgoingCallerIdsEndpoint.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.restcomm.connect.http; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat; import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import java.net.URI; import java.util.List; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.MediaType.APPLICATION_XML_TYPE; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.ok; import static javax.ws.rs.core.Response.status; import javax.ws.rs.core.SecurityContext; import org.apache.commons.configuration.Configuration; import org.joda.time.DateTime; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.OutgoingCallerIdsDao; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.OutgoingCallerId; import org.restcomm.connect.dao.entities.OutgoingCallerIdList; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.http.converter.OutgoingCallerIdConverter; import org.restcomm.connect.http.converter.OutgoingCallerIdListConverter; import org.restcomm.connect.http.converter.RestCommResponseConverter; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.http.security.PermissionEvaluator.SecuredType; import org.restcomm.connect.identity.UserIdentityContext; /** * @author [email protected] (Thomas Quintana) */ @Path("/Accounts/{accountSid}/OutgoingCallerIds") @ThreadSafe @Singleton public class OutgoingCallerIdsEndpoint extends AbstractEndpoint { @Context private ServletContext context; private Configuration configuration; private OutgoingCallerIdsDao dao; private Gson gson; private XStream xstream; public OutgoingCallerIdsEndpoint() { super(); } @PostConstruct public void init() { final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); configuration = (Configuration) context.getAttribute(Configuration.class.getName()); configuration = configuration.subset("runtime-settings"); super.init(configuration); dao = storage.getOutgoingCallerIdsDao(); final OutgoingCallerIdConverter converter = new OutgoingCallerIdConverter(configuration); final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(OutgoingCallerId.class, converter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(new OutgoingCallerIdListConverter(configuration)); xstream.registerConverter(new RestCommResponseConverter(configuration)); } private OutgoingCallerId createFrom(final Sid accountSid, final MultivaluedMap<String, String> data) { final Sid sid = Sid.generate(Sid.Type.PHONE_NUMBER); final DateTime now = DateTime.now(); final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance(); PhoneNumber phoneNumber = null; try { phoneNumber = phoneNumberUtil.parse(data.getFirst("PhoneNumber"), "US"); } catch (final NumberParseException ignored) { } String friendlyName = phoneNumberUtil.format(phoneNumber, PhoneNumberFormat.NATIONAL); if (data.containsKey("FriendlyName")) { friendlyName = data.getFirst("FriendlyName"); } final StringBuilder buffer = new StringBuilder(); buffer.append("/").append(getApiVersion(null)).append("/Accounts/").append(accountSid.toString()) .append("/OutgoingCallerIds/").append(sid.toString()); final URI uri = URI.create(buffer.toString()); return new OutgoingCallerId(sid, now, now, friendlyName, accountSid, phoneNumberUtil.format(phoneNumber, PhoneNumberFormat.E164), uri); } protected Response getCallerId(final String accountSid, final String sid, final MediaType responseType, UserIdentityContext userIdentityContext) { Account operatedAccount = accountsDao.getAccount(accountSid); permissionEvaluator.secure(operatedAccount, "RestComm:Read:OutgoingCallerIds", userIdentityContext); final OutgoingCallerId outgoingCallerId = dao.getOutgoingCallerId(new Sid(sid)); if (outgoingCallerId == null) { return status(NOT_FOUND).build(); } else { permissionEvaluator.secure(operatedAccount, outgoingCallerId.getAccountSid(), SecuredType.SECURED_STANDARD, userIdentityContext); if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(outgoingCallerId), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(outgoingCallerId); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } } protected Response getCallerIds(final String accountSid, final MediaType responseType, UserIdentityContext userIdentityContext) { permissionEvaluator.secure(accountsDao.getAccount(accountSid), "RestComm:Read:OutgoingCallerIds", userIdentityContext); final List<OutgoingCallerId> outgoingCallerIds = dao.getOutgoingCallerIds(new Sid(accountSid)); if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(outgoingCallerIds), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(new OutgoingCallerIdList(outgoingCallerIds)); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } protected Response putOutgoingCallerId(final String accountSid, final MultivaluedMap<String, String> data, final MediaType responseType, UserIdentityContext userIdentityContext) { permissionEvaluator.secure(accountsDao.getAccount(accountSid), "RestComm:Create:OutgoingCallerIds", userIdentityContext); try { validate(data); } catch (final NullPointerException exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } final OutgoingCallerId outgoingCallerId = createFrom(new Sid(accountSid), data); dao.addOutgoingCallerId(outgoingCallerId); if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(outgoingCallerId), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(outgoingCallerId); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } protected Response updateOutgoingCallerId(final String accountSid, final String sid, final MultivaluedMap<String, String> data, final MediaType responseType, UserIdentityContext userIdentityContext) { Account operatedAccount = accountsDao.getAccount(accountSid); permissionEvaluator.secure(operatedAccount, "RestComm:Modify:OutgoingCallerIds", userIdentityContext); OutgoingCallerId outgoingCallerId = dao.getOutgoingCallerId(new Sid(sid)); if (outgoingCallerId == null) { return status(NOT_FOUND).build(); } else { permissionEvaluator.secure(operatedAccount, outgoingCallerId.getAccountSid(), SecuredType.SECURED_STANDARD, userIdentityContext); if (data.containsKey("FriendlyName")) { final String friendlyName = data.getFirst("FriendlyName"); outgoingCallerId = outgoingCallerId.setFriendlyName(friendlyName); } dao.updateOutgoingCallerId(outgoingCallerId); if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(outgoingCallerId), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(outgoingCallerId); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } } private void validate(final MultivaluedMap<String, String> data) throws RuntimeException { if (!data.containsKey("PhoneNumber")) { throw new NullPointerException("Phone number can not be null."); } try { PhoneNumberUtil.getInstance().parse(data.getFirst("PhoneNumber"), "US"); } catch (final NumberParseException exception) { throw new IllegalArgumentException("Invalid phone number."); } } private Response deleteOutgoingCallerId(String accountSid, String sid, UserIdentityContext userIdentityContext) { Account operatedAccount = super.accountsDao.getAccount(accountSid); permissionEvaluator.secure(operatedAccount, "RestComm:Delete:OutgoingCallerIds", userIdentityContext); OutgoingCallerId oci = dao.getOutgoingCallerId(new Sid(sid)); if (oci != null) { permissionEvaluator.secure(operatedAccount, String.valueOf(oci.getAccountSid()), SecuredType.SECURED_STANDARD, userIdentityContext); } // TODO return a NOT_FOUND status code here if oci==null maybe ? dao.removeOutgoingCallerId(new Sid(sid)); return ok().build(); } @Path("/{sid}") @DELETE public Response deleteOutgoingCallerIdAsXml(@PathParam("accountSid") String accountSid, @PathParam("sid") String sid, @Context SecurityContext sec) { return deleteOutgoingCallerId(accountSid, sid, ContextUtil.convert(sec)); } @Path("/{sid}") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getCallerIdAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getCallerId(accountSid, sid, retrieveMediaType(accept), ContextUtil.convert(sec)); } @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getCallerIds(@PathParam("accountSid") final String accountSid, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getCallerIds(accountSid, retrieveMediaType(accept), ContextUtil.convert(sec)); } @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response putOutgoingCallerId(@PathParam("accountSid") final String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return putOutgoingCallerId(accountSid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } @Path("/{sid}") @PUT @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response updateOutgoingCallerIdAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return updateOutgoingCallerId(accountSid, sid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } }
14,005
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AccountsEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/AccountsEndpoint.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.restcomm.connect.http; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.core.header.LinkHeader; import com.sun.jersey.core.util.MultivaluedMapImpl; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import org.apache.commons.configuration.Configuration; import org.apache.shiro.crypto.hash.Md5Hash; import org.joda.time.DateTime; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.configuration.sets.RcmlserverConfigurationSet; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.commons.util.ClientLoginConstrains; import org.restcomm.connect.core.service.api.ProfileService; import org.restcomm.connect.dao.ClientsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.IncomingPhoneNumbersDao; import org.restcomm.connect.dao.ProfileAssociationsDao; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.AccountList; import org.restcomm.connect.dao.entities.Client; import org.restcomm.connect.dao.entities.IncomingPhoneNumber; import org.restcomm.connect.dao.entities.Organization; import org.restcomm.connect.dao.entities.Profile; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.extension.api.ApiRequest; import org.restcomm.connect.extension.controller.ExtensionController; import org.restcomm.connect.http.client.rcmlserver.RcmlserverApi; import org.restcomm.connect.http.client.rcmlserver.RcmlserverNotifications; import org.restcomm.connect.http.converter.AccountConverter; import org.restcomm.connect.http.converter.AccountListConverter; import org.restcomm.connect.http.converter.RestCommResponseConverter; import org.restcomm.connect.http.exceptionmappers.CustomReasonPhraseType; import org.restcomm.connect.http.exceptions.InsufficientPermission; import org.restcomm.connect.http.exceptions.PasswordTooWeak; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.http.security.PermissionEvaluator.SecuredType; import org.restcomm.connect.identity.UserIdentityContext; import org.restcomm.connect.identity.passwords.PasswordValidator; import org.restcomm.connect.identity.passwords.PasswordValidatorFactory; import org.restcomm.connect.provisioning.number.api.PhoneNumberProvisioningManager; import org.restcomm.connect.provisioning.number.api.PhoneNumberProvisioningManagerProvider; import javax.annotation.PostConstruct; import javax.annotation.security.RolesAllowed; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.servlet.ServletContext; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import java.net.URI; import java.util.ArrayList; import java.util.List; import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.MediaType.APPLICATION_XML_TYPE; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static javax.ws.rs.core.Response.Status.CONFLICT; import static javax.ws.rs.core.Response.Status.NOT_FOUND; import static javax.ws.rs.core.Response.Status.PRECONDITION_FAILED; import static javax.ws.rs.core.Response.ok; import static javax.ws.rs.core.Response.status; import static org.restcomm.connect.http.ProfileEndpoint.PROFILE_REL_TYPE; import static org.restcomm.connect.http.ProfileEndpoint.TITLE_PARAM; import static org.restcomm.connect.http.security.AccountPrincipal.SUPER_ADMIN_ROLE; /** * @author [email protected] (Thomas Quintana) * @author [email protected] (Maria Farooq) */ @Path("/Accounts") @ThreadSafe @Singleton public class AccountsEndpoint extends AbstractEndpoint { private Configuration runtimeConfiguration; private Configuration rootConfiguration; // top-level configuration element private Gson gson; private XStream xstream; private ClientsDao clientDao; private ProfileAssociationsDao profileAssociationsDao; private ProfileService profileService; public AccountsEndpoint() { super(); } public AccountsEndpoint(ServletContext context) { super(context); } @PostConstruct void init() { rootConfiguration = (Configuration) context.getAttribute(Configuration.class.getName()); runtimeConfiguration = rootConfiguration.subset("runtime-settings"); super.init(runtimeConfiguration); final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); clientDao = storage.getClientsDao(); profileAssociationsDao = storage.getProfileAssociationsDao(); profileService = (ProfileService)context.getAttribute(ProfileService.class.getName()); final AccountConverter converter = new AccountConverter(runtimeConfiguration); final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Account.class, converter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(new AccountListConverter(runtimeConfiguration)); xstream.registerConverter(new RestCommResponseConverter(runtimeConfiguration)); // Make sure there is an authenticated account present when this endpoint is used } private Account createFrom(final Sid accountSid, final MultivaluedMap<String, String> data, Account parent, UserIdentityContext userIdentityContext) throws PasswordTooWeak { validate(data); final DateTime now = DateTime.now(); final String emailAddress = (data.getFirst("EmailAddress")).toLowerCase(); // Issue 108: https://bitbucket.org/telestax/telscale-restcomm/issue/108/account-sid-could-be-a-hash-of-the final Sid sid = Sid.generate(Sid.Type.ACCOUNT, emailAddress); Sid organizationSid=null; String friendlyName = emailAddress; if (data.containsKey("FriendlyName")) { friendlyName = data.getFirst("FriendlyName"); } final Account.Type type = Account.Type.FULL; Account.Status status = Account.Status.ACTIVE; if (data.containsKey("Status")) { status = Account.Status.getValueOf(data.getFirst("Status").toLowerCase()); } if (data.containsKey("OrganizationSid")) { Sid orgSid = new Sid(data.getFirst("OrganizationSid")); // user can add account in same organization if(!orgSid.equals(parent.getOrganizationSid())){ //only super admin can add account in organizations other than it belongs to permissionEvaluator.allowOnlySuperAdmin(userIdentityContext); if(organizationsDao.getOrganization(orgSid) == null){ throw new IllegalArgumentException("provided OrganizationSid does not exist"); } organizationSid = orgSid; } } organizationSid = organizationSid != null ? organizationSid : parent.getOrganizationSid(); final String password = data.getFirst("Password"); PasswordValidator validator = PasswordValidatorFactory.createDefault(); if (!validator.isStrongEnough(password)) throw new PasswordTooWeak(); final String authToken = new Md5Hash(password).toString(); final String role = data.getFirst("Role"); final StringBuilder buffer = new StringBuilder(); buffer.append("/").append(getApiVersion(null)).append("/Accounts/").append(sid.toString()); final URI uri = URI.create(buffer.toString()); return new Account(sid, now, now, emailAddress, friendlyName, accountSid, type, status, authToken, role, uri, organizationSid); } protected Response getAccount(final String accountSid, final MediaType responseType, UriInfo info, UserIdentityContext userIdentityContext) { //First check if the account has the required permissions in general, this way we can fail fast and avoid expensive DAO operations Account account = null; permissionEvaluator.checkPermission("RestComm:Read:Accounts",userIdentityContext); if (Sid.pattern.matcher(accountSid).matches()) { try { account = accountsDao.getAccount(new Sid(accountSid)); } catch (Exception e) { return status(NOT_FOUND).build(); } } else { try { account = accountsDao.getAccount(accountSid); } catch (Exception e) { return status(NOT_FOUND).build(); } } permissionEvaluator.secure(account, "RestComm:Read:Accounts", SecuredType.SECURED_ACCOUNT,userIdentityContext ); if (account == null) { return status(NOT_FOUND).build(); } else { Response.ResponseBuilder ok = Response.ok(); Profile associatedProfile = profileService.retrieveEffectiveProfileByAccountSid(account.getSid()); if (associatedProfile != null) { LinkHeader profileLink = composeLink(new Sid(associatedProfile.getSid()), info); ok.header(ProfileEndpoint.LINK_HEADER, profileLink.toString()); } if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(account); return ok.type(APPLICATION_XML).entity(xstream.toXML(response)).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok.type(APPLICATION_JSON).entity(gson.toJson(account)).build(); } else { return null; } } } // Account removal disabled as per https://github.com/RestComm/Restcomm-Connect/issues/1270 /* protected Response deleteAccount(final String operatedSid) { //First check if the account has the required permissions in general, this way we can fail fast and avoid expensive DAO operations checkPermission("RestComm:Delete:Accounts"); // what if effectiveAccount is null ?? - no need to check since we checkAuthenticatedAccount() in AccountsEndoint.init() final Sid accountSid = userIdentityContext.getEffectiveAccount().getSid(); final Sid sidToBeRemoved = new Sid(operatedSid); Account removedAccount = accountsDao.getAccount(sidToBeRemoved); secure(removedAccount, "RestComm:Delete:Accounts", SecuredType.SECURED_ACCOUNT); // Prevent removal of Administrator account if (operatedSid.equalsIgnoreCase(accountSid.toString())) return status(BAD_REQUEST).build(); if (accountsDao.getAccount(sidToBeRemoved) == null) return status(NOT_FOUND).build(); // the whole tree of sub-accounts has to be removed as well List<String> removedAccounts = accountsDao.getSubAccountSidsRecursive(sidToBeRemoved); if (removedAccounts != null && !removedAccounts.isEmpty()) { int i = removedAccounts.size(); // is is the count of accounts left to process while (i > 0) { i --; String removedSid = removedAccounts.get(i); try { removeSingleAccount(removedSid); } catch (Exception e) { // if anything bad happens, log the error and continue removing the rest of the accounts. logger.error("Failed removing (child) account '" + removedSid + "'"); } } } // remove the parent account too removeSingleAccount(operatedSid); return ok().build(); }*/ /* protected Response deleteAccount(final String operatedSid) { //First check if the account has the required permissions in general, this way we can fail fast and avoid expensive DAO operations checkPermission("RestComm:Delete:Accounts"); // what if effectiveAccount is null ?? - no need to check since we checkAuthenticatedAccount() in AccountsEndoint.init() final Sid accountSid = userIdentityContext.getEffectiveAccount().getSid(); final Sid sidToBeRemoved = new Sid(operatedSid); Account removedAccount = accountsDao.getAccount(sidToBeRemoved); secure(removedAccount, "RestComm:Delete:Accounts", SecuredType.SECURED_ACCOUNT); // Prevent removal of Administrator account if (operatedSid.equalsIgnoreCase(accountSid.toString())) return status(BAD_REQUEST).build(); if (accountsDao.getAccount(sidToBeRemoved) == null) return status(NOT_FOUND).build(); accountsDao.removeAccount(sidToBeRemoved); // Remove its SIP client account clientDao.removeClients(sidToBeRemoved); return ok().build(); } */ /** * Removes all dependent resources of an account. Some resources like * CDRs are excluded. * * @param sid */ private void removeAccoundDependencies(Sid sid) { logger.debug("removing accoutn dependencies"); DaoManager daoManager = (DaoManager) context.getAttribute(DaoManager.class.getName()); // remove dependency entities first and dependent entities last. Also, do safer operation first (as a secondary rule) daoManager.getAnnouncementsDao().removeAnnouncements(sid); daoManager.getNotificationsDao().removeNotifications(sid); daoManager.getShortCodesDao().removeShortCodes(sid); daoManager.getOutgoingCallerIdsDao().removeOutgoingCallerIds(sid); daoManager.getTranscriptionsDao().removeTranscriptions(sid); daoManager.getRecordingsDao().removeRecordings(sid); daoManager.getApplicationsDao().removeApplications(sid); removeIncomingPhoneNumbers(sid,daoManager.getIncomingPhoneNumbersDao()); daoManager.getClientsDao().removeClients(sid); profileAssociationsDao.deleteProfileAssociationByTargetSid(sid.toString()); } /** * Removes incoming phone numbers that belong to an account from the database. * For provided numbers the provider is also contacted to get them released. * * @param accountSid * @param dao */ private void removeIncomingPhoneNumbers(Sid accountSid, IncomingPhoneNumbersDao dao) { List<IncomingPhoneNumber> numbers = dao.getIncomingPhoneNumbers(accountSid); if (numbers != null && numbers.size() > 0) { // manager is retrieved in a lazy way. If any number needs it, it will be first retrieved // from the servlet context. If not there it will be created, stored in context and returned. boolean managerQueried = false; PhoneNumberProvisioningManager manager = null; for (IncomingPhoneNumber number : numbers) { // if this is not just a SIP number try to release it by contacting the provider if (number.isPureSip() == null || !number.isPureSip()) { if ( ! managerQueried ) manager = new PhoneNumberProvisioningManagerProvider(rootConfiguration,context).get(); // try to retrieve/build manager only once if (manager != null) { try { if (! manager.cancelNumber(IncomingPhoneNumbersEndpoint.convertIncomingPhoneNumbertoPhoneNumber(number)) ) { logger.error("Number cancelation failed for provided number '" + number.getPhoneNumber()+"'. Number entity " + number.getSid() + " will stay in database"); } else { dao.removeIncomingPhoneNumber(number.getSid()); } } catch (Exception e) { logger.error("Number cancelation failed for provided number '" + number.getPhoneNumber()+"'",e); } } else logger.error("Number cancelation failed for provided number '" + number.getPhoneNumber()+"'. Provisioning Manager was null. "+"Number entity " + number.getSid() + " will stay in database"); } else { // pureSIP numbers only to be removed from database. No need to contact provider dao.removeIncomingPhoneNumber(number.getSid()); } } } } protected Response getAccounts(final UriInfo info, final MediaType responseType, UserIdentityContext userIdentityContext) { //First check if the account has the required permissions in general, this way we can fail fast and avoid expensive DAO operations permissionEvaluator.checkPermission("RestComm:Read:Accounts",userIdentityContext); final Account account = userIdentityContext.getEffectiveAccount(); if (account == null) { return status(NOT_FOUND).build(); } else { final List<Account> accounts = new ArrayList<Account>(); if (info == null) { accounts.addAll(accountsDao.getChildAccounts(account.getSid())); } else { String organizationSid = info.getQueryParameters().getFirst("OrganizationSid"); String domainName = info.getQueryParameters().getFirst("DomainName"); if(organizationSid != null && !(organizationSid.trim().isEmpty())){ permissionEvaluator.allowOnlySuperAdmin(userIdentityContext); accounts.addAll(accountsDao.getAccountsByOrganization(new Sid(organizationSid))); } else if(domainName != null && !(domainName.trim().isEmpty())){ permissionEvaluator.allowOnlySuperAdmin(userIdentityContext); Organization organization = organizationsDao.getOrganizationByDomainName(domainName); if(organization == null){ return status(NOT_FOUND).build(); } accounts.addAll(accountsDao.getAccountsByOrganization(organization.getSid())); } else { accounts.addAll(accountsDao.getChildAccounts(account.getSid())); } } if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(new AccountList(accounts)); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(accounts), APPLICATION_JSON).build(); } else { return null; } } } protected Response putAccount(final MultivaluedMap<String, String> data, final MediaType responseType,UserIdentityContext userIdentityContext) { //First check if the account has the required permissions in general, this way we can fail fast and avoid expensive DAO operations permissionEvaluator.checkPermission("RestComm:Create:Accounts",userIdentityContext); // check account level depth. If we're already at third level no sub-accounts are allowed to be created List<String> accountLineage = userIdentityContext.getEffectiveAccountLineage(); if (accountLineage.size() >= 2) { // there are already 2+1=3 account levels. Sub-accounts at 4th level are not allowed return status(BAD_REQUEST).entity(buildErrorResponseBody("This account is not allowed to have sub-accounts",responseType)).type(responseType).build(); } // what if effectiveAccount is null ?? - no need to check since we checkAuthenticatedAccount() in AccountsEndoint.init() final Sid sid = userIdentityContext.getEffectiveAccount().getSid(); ExtensionController ec = ExtensionController.getInstance(); ApiRequest apiRequest = new ApiRequest(sid.toString(), data, ApiRequest.Type.CREATE_SUBACCOUNT); if (executePreApiAction(apiRequest)) { final Account parent = accountsDao.getAccount(sid); Account account = null; try { account = createFrom(sid, data, parent,userIdentityContext); } catch (IllegalArgumentException illegalArgumentException) { return status(BAD_REQUEST).entity(illegalArgumentException.getMessage()).build(); }catch (final NullPointerException exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } catch (PasswordTooWeak passwordTooWeak) { return status(BAD_REQUEST).entity(buildErrorResponseBody("Password too weak",responseType)).type(responseType).build(); } // If Account already exists don't add it again /* Account creation rules: - either be Administrator or have the following permission: RestComm:Create:Accounts - only Administrators can choose a role for newly created accounts. Normal users will create accounts with the same role as their own. */ if (accountsDao.getAccount(account.getSid()) == null && !account.getEmailAddress().equalsIgnoreCase("[email protected]")) { if (parent.getStatus().equals(Account.Status.ACTIVE) && permissionEvaluator.isSecuredByPermission("RestComm:Create:Accounts",userIdentityContext)) { if (!permissionEvaluator.hasAccountRole(permissionEvaluator.getAdministratorRole(),userIdentityContext) || !data.containsKey("Role")) { account = account.setRole(parent.getRole()); } accountsDao.addAccount(account); // Create default SIP client data MultivaluedMap<String, String> clientData = new MultivaluedMapImpl(); String username = data.getFirst("EmailAddress").split("@")[0]; clientData.add("Login", username); clientData.add("Password", data.getFirst("Password")); clientData.add("FriendlyName", account.getFriendlyName()); clientData.add("AccountSid", account.getSid().toString()); Client client = clientDao.getClient(clientData.getFirst("Login"), account.getOrganizationSid()); if (client == null) { client = createClientFrom(account.getSid(), clientData); clientDao.addClient(client); } } else { throw new InsufficientPermission(); } } else { return status(CONFLICT).entity("The email address used for the new account is already in use.").build(); } executePostApiAction(apiRequest); if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(account), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(account); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } else { if (logger.isDebugEnabled()) { final String errMsg = "Creation of sub-accounts is not Allowed"; logger.debug(errMsg); } executePostApiAction(apiRequest); String errMsg = "Creation of sub-accounts is not Allowed"; return status(Response.Status.FORBIDDEN).entity(errMsg).build(); } } private Client createClientFrom(final Sid accountSid, final MultivaluedMap<String, String> data) { final Client.Builder builder = Client.builder(); final Sid sid = Sid.generate(Sid.Type.CLIENT); // TODO: need to encrypt this password because it's same with Account // password. // Don't implement now. Opened another issue for it. // String password = new Md5Hash(data.getFirst("Password")).toString(); String password = data.getFirst("Password"); builder.setSid(sid); builder.setAccountSid(accountSid); builder.setApiVersion(getApiVersion(data)); builder.setLogin(data.getFirst("Login")); builder.setPassword(data.getFirst("Login"), password, organizationsDao.getOrganization(accountsDao.getAccount(accountSid).getOrganizationSid()).getDomainName(), ""); builder.setFriendlyName(data.getFirst("FriendlyName")); builder.setStatus(Client.ENABLED); final StringBuilder buffer = new StringBuilder(); buffer.append("/").append(getApiVersion(data)).append("/Accounts/").append(accountSid.toString()) .append("/Clients/").append(sid.toString()); builder.setUri(URI.create(buffer.toString())); return builder.build(); } /** * Fills an account entity object with values supplied from an http request * * @param account * @param data * @return a new instance with given account,and overriden fields from data */ private Account prepareAccountForUpdate(final Account account, final MultivaluedMap<String, String> data, UserIdentityContext userIdentityContext) { Account.Builder accBuilder = Account.builder(); //copy full incoming account, and let override happen //in a separate instance later accBuilder.copy(account); if (data.containsKey("Status")) { Account.Status newStatus = Account.Status.getValueOf(data.getFirst("Status").toLowerCase()); accBuilder.setStatus(newStatus); } if (data.containsKey("FriendlyName")) { accBuilder.setFriendlyName(data.getFirst("FriendlyName")); } if (data.containsKey("Password")) { // if this is a reset-password operation, we also need to set the account status to active if (account.getStatus() == Account.Status.UNINITIALIZED) { accBuilder.setStatus(Account.Status.ACTIVE); } String password = data.getFirst("Password"); PasswordValidator validator = PasswordValidatorFactory.createDefault(); if (!validator.isStrongEnough(password)) { CustomReasonPhraseType stat = new CustomReasonPhraseType(Response.Status.BAD_REQUEST, "Password too weak"); throw new WebApplicationException(status(stat).build()); } final String hash = new Md5Hash(data.getFirst("Password")).toString(); accBuilder.setAuthToken(hash); } if (data.containsKey("Role")) { // Only allow role change for administrators. Multitenancy checks will take care of restricting the modification scope to sub-accounts. if (userIdentityContext.getEffectiveAccountRoles().contains(permissionEvaluator.getAdministratorRole())) { accBuilder.setRole(data.getFirst("Role")); } else { CustomReasonPhraseType stat = new CustomReasonPhraseType(Response.Status.FORBIDDEN, "Only Administrator allowed"); throw new WebApplicationException(status(stat).build()); } } return accBuilder.build(); } /** * update SIP client of the corresponding Account.Password and FriendlyName fields are synched. */ private void updateLinkedClient(Account account, MultivaluedMap<String, String> data) { logger.debug("checking linked client"); String email = account.getEmailAddress(); if (email != null && !email.equals("")) { logger.debug("account email is valid"); String username = email.split("@")[0]; Client client = clientDao.getClient(username, account.getOrganizationSid()); if (client != null) { logger.debug("client found"); // TODO: need to encrypt this password because it's // same with Account password. // Don't implement now. Opened another issue for it. if (data.containsKey("Password")) { // Md5Hash(data.getFirst("Password")).toString(); logger.debug("password changed"); String password = data.getFirst("Password"); client = client.setPassword(client.getLogin(), password, organizationsDao.getOrganization(account.getOrganizationSid()).getDomainName()); } if (data.containsKey("FriendlyName")) { logger.debug("friendlyname changed"); client = client.setFriendlyName(data.getFirst("FriendlyName")); } logger.debug("updating linked client"); clientDao.updateClient(client); } } } protected Response updateAccount(final String identifier, final MultivaluedMap<String, String> data, final MediaType responseType, UserIdentityContext userIdentityContext) { // First check if the account has the required permissions in general, this way we can fail fast and avoid expensive DAO // operations permissionEvaluator.checkPermission("RestComm:Modify:Accounts",userIdentityContext); Account account = getOperatingAccount(identifier); if (account == null) { return status(NOT_FOUND).build(); } else { // since the operated account exists, first thing to do is make sure we have access permissionEvaluator.secure(account, "RestComm:Modify:Accounts", SecuredType.SECURED_ACCOUNT, userIdentityContext); // if the account is already CLOSED, no updates are allowed if (account.getStatus() == Account.Status.CLOSED) { // If the account is CLOSED, no updates are allowed. Return a BAD_REQUEST status code. CustomReasonPhraseType stat = new CustomReasonPhraseType(Response.Status.BAD_REQUEST, "Account is closed"); throw new WebApplicationException(status(stat).build()); } Account modifiedAccount; modifiedAccount = prepareAccountForUpdate(account, data, userIdentityContext); // we are modifying status if (modifiedAccount.getStatus() != null && account.getStatus() != modifiedAccount.getStatus()) { switchAccountStatusTree(modifiedAccount,userIdentityContext); } //update client only if friendlyname or password was changed if (data.containsKey("Password") || data.containsKey("FriendlyName") ) { updateLinkedClient(account, data); } accountsDao.updateAccount(modifiedAccount); if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(modifiedAccount), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(modifiedAccount); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } } private Account getOperatingAccount (String identifier) { Sid sid = null; Account account = null; try { sid = new Sid(identifier); account = accountsDao.getAccount(sid); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Exception trying to get account using SID. Seems we have email as identifier"); } } if (account == null) { account = accountsDao.getAccount(identifier); } return account; } private Organization getOrganization(final MultivaluedMap<String, String> data) { Organization organization = null; String organizationId = null; if (data.containsKey("Organization")) { organizationId = data.getFirst("Organization"); } else { return null; } if (Sid.pattern.matcher(organizationId).matches()) { //Attempt to get Organization by SID organization = organizationsDao.getOrganization(new Sid(organizationId)); return organization; } else { //Attempt to get Organization by domain name organization = organizationsDao.getOrganizationByDomainName(organizationId); return organization; } } protected Response migrateAccountOrganization(final String identifier, final MultivaluedMap<String, String> data, final MediaType responseType, UserIdentityContext userIdentityContext) { Organization organization = getOrganization(data); //Validation 2 - Check if data contains Organization (either SID or domain name) if (organization == null) { return status(PRECONDITION_FAILED).entity("Missing Organization SID or Domain Name").build(); } Account operatingAccount = getOperatingAccount(identifier); //Validation 3 - Operating Account shouldn't be null; if (operatingAccount == null) { return status(NOT_FOUND).build(); } //Validation 4 - Only direct child of super admin account can be migrated to a new organization if (!permissionEvaluator.isDirectChildOfAccount(userIdentityContext.getEffectiveAccount(), operatingAccount)) { return status(BAD_REQUEST).build(); } //Validation 5 - Check if Account already in the requested Organization if (operatingAccount.getOrganizationSid().equals(organization.getSid())) { return status(BAD_REQUEST).entity("Account already in the requested Organization").build(); } //Update Account for the new Organization Account modifiedAccount = operatingAccount.setOrganizationSid(organization.getSid()); accountsDao.updateAccount(modifiedAccount); if (logger.isDebugEnabled()) { String msg = String.format("Parent Account %s migrated to Organization %s", modifiedAccount.getSid(), organization.getSid()); logger.debug(msg); } //Update Child accounts and their numbers List<Account> childAccounts = accountsDao.getChildAccounts(operatingAccount.getSid()); for (Account child : childAccounts) { if (!child.getOrganizationSid().equals(organization.getSid())) { Account modifiedChildAccount = child.setOrganizationSid(organization.getSid()); accountsDao.updateAccount(modifiedChildAccount); if (logger.isDebugEnabled()) { String msg = String.format("Child Account %s from Parent Account %s, migrated to Organization %s", modifiedChildAccount.getSid(), modifiedAccount.getSid(), organization.getSid()); logger.debug(msg); } } } if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(modifiedAccount), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(modifiedAccount); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } private void sendRVDStatusNotification(Account updatedAccount, UserIdentityContext userIdentityContext) { logger.debug("sendRVDStatusNotification"); // set rcmlserverApi in case we need to also notify the application sever (RVD) RestcommConfiguration rcommConfiguration = RestcommConfiguration.getInstance(); RcmlserverConfigurationSet config = rcommConfiguration.getRcmlserver(); if (config != null && config.getNotify()) { logger.debug("notification enabled"); // first send account removal notification to RVD now that the applications of the account still exist RcmlserverApi rcmlServerApi = new RcmlserverApi(rcommConfiguration.getMain(), rcommConfiguration.getRcmlserver(), updatedAccount.getSid()); RcmlserverNotifications notifications = new RcmlserverNotifications(); notifications.add(rcmlServerApi.buildAccountStatusNotification(updatedAccount)); Account notifier = userIdentityContext.getEffectiveAccount(); rcmlServerApi.transmitNotifications(notifications, notifier.getSid().toString(), notifier.getAuthToken()); } } /** * Switches an account status at dao level. * * If status is CLSOED, Removes all resources belonging to an account. * * If rcmlServerApi is not null it will * also send account-removal notifications to the rcmlserver * * @param account */ private void switchAccountStatus(Account account, Account.Status status, UserIdentityContext userIdentityContext) { if (logger.isDebugEnabled()) { logger.debug("Switching status for account:" + account.getSid() + ",status:" + status); } switch (status) { case CLOSED: sendRVDStatusNotification(account,userIdentityContext); // then proceed to dependency removal removeAccoundDependencies(account.getSid()); break; default: break; } // finally, set and persist account status account = account.setStatus(status); accountsDao.updateAccount(account); } /** * Switches status of account along with all its children (the whole tree). * * @param parentAccount */ private void switchAccountStatusTree(Account parentAccount, UserIdentityContext userIdentityContext) { logger.debug("Status transition requested"); // transition child accounts List<String> subAccountsToSwitch = accountsDao.getSubAccountSidsRecursive(parentAccount.getSid()); if (subAccountsToSwitch != null && !subAccountsToSwitch.isEmpty()) { int i = subAccountsToSwitch.size(); // is is the count of accounts left to process // we iterate backwards to handle child accounts first, parent accounts next while (i > 0) { i --; String removedSid = subAccountsToSwitch.get(i); try { Account subAccount = accountsDao.getAccount(new Sid(removedSid)); switchAccountStatus(subAccount, parentAccount.getStatus(), userIdentityContext); } catch (Exception e) { // if anything bad happens, log the error and continue removing the rest of the accounts. logger.error("Failed switching status (child) account '" + removedSid + "'"); } } } // switch parent account too switchAccountStatus(parentAccount, parentAccount.getStatus(), userIdentityContext); } private void validate(final MultivaluedMap<String, String> data) throws NullPointerException { if (!data.containsKey("EmailAddress")) { throw new NullPointerException("Email address can not be null."); } else if (!data.containsKey("Password")) { throw new NullPointerException("Password can not be null."); } String emailAddress = data.getFirst("EmailAddress"); try { InternetAddress emailAddr = new InternetAddress(emailAddress); emailAddr.validate(); } catch (AddressException ex) { String msg = String.format("Provided email address %s is not valid",emailAddress); if (logger.isDebugEnabled()) { logger.debug(msg); } throw new IllegalArgumentException(msg); } String clientLogin = data.getFirst("EmailAddress").split("@")[0]; if (!ClientLoginConstrains.isValidClientLogin(clientLogin)) { String msg = String.format("Login %s contains invalid character(s) ",clientLogin); if (logger.isDebugEnabled()) { logger.debug(msg); } throw new IllegalArgumentException(msg); } } public LinkHeader composeLink(Sid targetSid, UriInfo info) { String sid = targetSid.toString(); URI uri = info.getBaseUriBuilder().path(ProfileEndpoint.class).path(sid).build(); LinkHeader.LinkHeaderBuilder link = LinkHeader.uri(uri).parameter(TITLE_PARAM, "Profiles"); return link.rel(PROFILE_REL_TYPE).build(); } @Path("/{accountSid}") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getAccountAsXml(@PathParam("accountSid") final String accountSid, @Context UriInfo info, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getAccount(accountSid, retrieveMediaType(accept), info, ContextUtil.convert(sec)); } @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getAccounts(@Context UriInfo info, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getAccounts(info, retrieveMediaType(accept), ContextUtil.convert(sec)); } @Consumes(APPLICATION_FORM_URLENCODED) @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response putAccount(final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return putAccount(data, retrieveMediaType(accept), ContextUtil.convert(sec)); } //The {accountSid} could be the email address of the account we need to update. Later we check if this is SID or EMAIL @Path("/{accountSid}") @Consumes(APPLICATION_FORM_URLENCODED) @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response updateAccountAsXmlPost(@PathParam("accountSid") final String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return updateAccount(accountSid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } //The {accountSid} could be the email address of the account we need to update. Later we check if this is SID or EMAIL @Path("/{accountSid}") @Consumes(APPLICATION_FORM_URLENCODED) @PUT @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response updateAccountAsXmlPut(@PathParam("accountSid") final String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return updateAccount(accountSid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } @Path("/migrate/{accountSid}") @Consumes(APPLICATION_FORM_URLENCODED) @POST @RolesAllowed(SUPER_ADMIN_ROLE) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response migrateAccount(@PathParam("accountSid") final String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return migrateAccountOrganization(accountSid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } }
45,657
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SmsMessagesEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/SmsMessagesEndpoint.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.restcomm.connect.http; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.UntypedActor; import akka.actor.UntypedActorContext; import akka.actor.UntypedActorFactory; import static akka.pattern.Patterns.ask; import akka.util.Timeout; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import java.math.BigDecimal; import java.net.URI; import java.text.ParseException; import java.util.Map; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.util.Currency; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.*; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.*; import static javax.ws.rs.core.Response.ok; import static javax.ws.rs.core.Response.status; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.commons.patterns.Observe; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.SmsMessagesDao; import org.restcomm.connect.dao.common.Sorting; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.dao.entities.SmsMessage; import org.restcomm.connect.dao.entities.SmsMessageFilter; import org.restcomm.connect.dao.entities.SmsMessageList; import org.restcomm.connect.http.converter.RestCommResponseConverter; import org.restcomm.connect.http.converter.SmsMessageConverter; import org.restcomm.connect.http.converter.SmsMessageListConverter; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.http.security.PermissionEvaluator.SecuredType; import org.restcomm.connect.identity.UserIdentityContext; import org.restcomm.connect.sms.api.CreateSmsSession; import org.restcomm.connect.sms.api.SmsServiceResponse; import org.restcomm.connect.sms.api.SmsSessionAttribute; import org.restcomm.connect.sms.api.SmsSessionInfo; import org.restcomm.connect.sms.api.SmsSessionRequest; import org.restcomm.connect.sms.api.SmsSessionResponse; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; /** * @author [email protected] (Thomas Quintana) */ @Path("/Accounts/{accountSid}/SMS/Messages") @ThreadSafe @Singleton public class SmsMessagesEndpoint extends AbstractEndpoint { private static final String SORTING_URL_PARAM_DATE_CREATED = "DateCreated"; private static final String SORTING_URL_PARAM_FROM = "From"; private static final String SORTING_URL_PARAM_TO = "To"; private static final String SORTING_URL_PARAM_DIRECTION = "Direction"; private static final String SORTING_URL_PARAM_STATUS = "Status"; private static final String SORTING_URL_PARAM_BODY = "Body"; private static final String SORTING_URL_PARAM_PRICE = "Price"; private static final String CALLBACK_PARAM = "StatusCallback"; private static final String FROM_PARAM = "From"; private static final String TO_PARAM = "To"; private static final String BODY_PARAM = "Body"; private static final String STATUS_PARAM = "Status"; @Context protected ServletContext context; protected ActorSystem system; protected Configuration configuration; protected ActorRef aggregator; protected SmsMessagesDao dao; protected Gson gson; protected XStream xstream; protected SmsMessageListConverter listConverter; protected String instanceId; private boolean normalizePhoneNumbers; public SmsMessagesEndpoint() { super(); } @PostConstruct public void init() { final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); configuration = (Configuration) context.getAttribute(Configuration.class.getName()); configuration = configuration.subset("runtime-settings"); dao = storage.getSmsMessagesDao(); aggregator = (ActorRef) context.getAttribute("org.restcomm.connect.sms.SmsService"); system = (ActorSystem) context.getAttribute(ActorSystem.class.getName()); super.init(configuration); final SmsMessageConverter converter = new SmsMessageConverter(configuration); listConverter = new SmsMessageListConverter(configuration); final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(SmsMessage.class, converter); builder.registerTypeAdapter(SmsMessageList.class, listConverter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(new SmsMessageListConverter(configuration)); xstream.registerConverter(new RestCommResponseConverter(configuration)); xstream.registerConverter(listConverter); instanceId = RestcommConfiguration.getInstance().getMain().getInstanceId(); normalizePhoneNumbers = configuration.getBoolean("normalize-numbers-for-outbound-calls"); } protected Response getSmsMessage(final String accountSid, final String sid, final MediaType responseType, UserIdentityContext userIdentityContext) { Account operatedAccount = accountsDao.getAccount(accountSid); permissionEvaluator.secure(operatedAccount, "RestComm:Read:SmsMessages", userIdentityContext); final SmsMessage smsMessage = dao.getSmsMessage(new Sid(sid)); if (smsMessage == null) { return status(NOT_FOUND).build(); } else { permissionEvaluator.secure(operatedAccount, smsMessage.getAccountSid(), SecuredType.SECURED_STANDARD, userIdentityContext); if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(smsMessage), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(smsMessage); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } } protected Response getSmsMessages(final String accountSid, UriInfo info, final MediaType responseType, UserIdentityContext userIdentityContext) { permissionEvaluator.secure(accountsDao.getAccount(accountSid), "RestComm:Read:SmsMessages", userIdentityContext); boolean localInstanceOnly = true; try { String localOnly = info.getQueryParameters().getFirst("localOnly"); if (localOnly != null && localOnly.equalsIgnoreCase("false")) localInstanceOnly = false; } catch (Exception e) { } // shall we include sub-accounts cdrs in our query ? boolean querySubAccounts = false; // be default we don't String querySubAccountsParam = info.getQueryParameters().getFirst("SubAccounts"); if (querySubAccountsParam != null && querySubAccountsParam.equalsIgnoreCase("true")) querySubAccounts = true; String pageSize = info.getQueryParameters().getFirst("PageSize"); String page = info.getQueryParameters().getFirst("Page"); // String afterSid = info.getQueryParameters().getFirst("AfterSid"); String recipient = info.getQueryParameters().getFirst(TO_PARAM); String sender = info.getQueryParameters().getFirst(FROM_PARAM); String startTime = info.getQueryParameters().getFirst("StartTime"); String endTime = info.getQueryParameters().getFirst("EndTime"); String body = info.getQueryParameters().getFirst(BODY_PARAM); String status = info.getQueryParameters().getFirst(STATUS_PARAM); String sortParameters = info.getQueryParameters().getFirst("SortBy"); SmsMessageFilter.Builder filterBuilder = SmsMessageFilter.Builder.builder(); String sortBy = null; String sortDirection = null; if (sortParameters != null && !sortParameters.isEmpty()) { try { Map<String, String> sortMap = Sorting.parseUrl(sortParameters); sortBy = sortMap.get(Sorting.SORT_BY_KEY); sortDirection = sortMap.get(Sorting.SORT_DIRECTION_KEY); } catch (Exception e) { return status(BAD_REQUEST).entity(buildErrorResponseBody(e.getMessage(), responseType)).build(); } } if (sortBy != null) { if (sortBy.equals(SORTING_URL_PARAM_DATE_CREATED)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByDate(Sorting.Direction.ASC); } else { filterBuilder.sortedByDate(Sorting.Direction.DESC); } } } if (sortBy.equals(SORTING_URL_PARAM_FROM)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByFrom(Sorting.Direction.ASC); } else { filterBuilder.sortedByFrom(Sorting.Direction.DESC); } } } if (sortBy.equals(SORTING_URL_PARAM_TO)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByTo(Sorting.Direction.ASC); } else { filterBuilder.sortedByTo(Sorting.Direction.DESC); } } } if (sortBy.equals(SORTING_URL_PARAM_DIRECTION)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByDirection(Sorting.Direction.ASC); } else { filterBuilder.sortedByDirection(Sorting.Direction.DESC); } } } if (sortBy.equals(SORTING_URL_PARAM_STATUS)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByStatus(Sorting.Direction.ASC); } else { filterBuilder.sortedByStatus(Sorting.Direction.DESC); } } } if (sortBy.equals(SORTING_URL_PARAM_BODY)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByBody(Sorting.Direction.ASC); } else { filterBuilder.sortedByBody(Sorting.Direction.DESC); } } } if (sortBy.equals(SORTING_URL_PARAM_PRICE)) { if (sortDirection != null) { if (sortDirection.equalsIgnoreCase(Sorting.Direction.ASC.name())) { filterBuilder.sortedByPrice(Sorting.Direction.ASC); } else { filterBuilder.sortedByPrice(Sorting.Direction.DESC); } } } } if (pageSize == null) { pageSize = "50"; } if (page == null) { page = "0"; } int limit = Integer.parseInt(pageSize); int offset = (page.equals("0")) ? 0 : (((Integer.parseInt(page) - 1) * Integer.parseInt(pageSize)) + Integer .parseInt(pageSize)); // Shall we query cdrs of sub-accounts too ? // if we do, we need to find the sub-accounts involved first List<String> ownerAccounts = null; if (querySubAccounts) { ownerAccounts = new ArrayList<String>(); ownerAccounts.add(accountSid); // we will also return parent account cdrs ownerAccounts.addAll(accountsDao.getSubAccountSidsRecursive(new Sid(accountSid))); } filterBuilder.byAccountSid(accountSid) .byAccountSidSet(ownerAccounts) .byRecipient(recipient) .bySender(sender) .byStatus(status) .byStartTime(startTime) .byEndTime(endTime) .byBody(body) .limited(limit, offset); if (!localInstanceOnly) { filterBuilder.byInstanceId(instanceId); } SmsMessageFilter filter; try { filter = filterBuilder.build(); } catch (ParseException e) { return status(BAD_REQUEST).build(); } final int total = dao.getTotalSmsMessage(filter); if (Integer.parseInt(page) > (total / limit)) { return status(Response.Status.BAD_REQUEST).build(); } final List<SmsMessage> cdrs = dao.getSmsMessages(filter); listConverter.setCount(total); listConverter.setPage(Integer.parseInt(page)); listConverter.setPageSize(Integer.parseInt(pageSize)); listConverter.setPathUri(info.getRequestUri().getPath()); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(new SmsMessageList(cdrs)); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(new SmsMessageList(cdrs)), APPLICATION_JSON).build(); } else { return null; } } private void normalize(final MultivaluedMap<String, String> data) throws IllegalArgumentException { final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance(); final String from = data.getFirst(FROM_PARAM); data.remove(FROM_PARAM); try { data.putSingle(FROM_PARAM, phoneNumberUtil.format(phoneNumberUtil.parse(from, "US"), PhoneNumberFormat.E164)); } catch (final NumberParseException exception) { throw new IllegalArgumentException(exception); } final String to = data.getFirst(TO_PARAM); data.remove(TO_PARAM); try { data.putSingle(TO_PARAM, phoneNumberUtil.format(phoneNumberUtil.parse(to, "US"), PhoneNumberFormat.E164)); } catch (final NumberParseException exception) { throw new IllegalArgumentException(exception); } final String body = data.getFirst(BODY_PARAM); if (body.getBytes().length > 160) { data.remove(BODY_PARAM); data.putSingle(BODY_PARAM, body.substring(0, 159)); } } @SuppressWarnings("unchecked") protected Response putSmsMessage(final String accountSid, final MultivaluedMap<String, String> data, final MediaType responseType, UserIdentityContext userIdentityContext) { permissionEvaluator.secure(accountsDao.getAccount(accountSid), "RestComm:Create:SmsMessages", userIdentityContext); try { validate(data); if(normalizePhoneNumbers) { normalize(data); } } catch (final RuntimeException exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } final String sender = data.getFirst(FROM_PARAM); final String recipient = data.getFirst(TO_PARAM); final String body = data.getFirst(BODY_PARAM); final SmsSessionRequest.Encoding encoding; if (!data.containsKey("Encoding")) { encoding = SmsSessionRequest.Encoding.GSM; } else { encoding = SmsSessionRequest.Encoding.valueOf(data.getFirst("Encoding").replace('-', '_')); } final URI statusCallback; if (!data.containsKey(CALLBACK_PARAM)) { statusCallback = null; } else { statusCallback = URI.create(data.getFirst(CALLBACK_PARAM)); } ConcurrentHashMap<String, String> customRestOutgoingHeaderMap = new ConcurrentHashMap<String, String>(); Iterator<String> iter = data.keySet().iterator(); while (iter.hasNext()) { String name = iter.next(); if (name.startsWith("X-")){ customRestOutgoingHeaderMap.put(name, data.getFirst(name)); } } final Timeout expires = new Timeout(Duration.create(60, TimeUnit.SECONDS)); try { Future<Object> future = (Future<Object>) ask(aggregator, new CreateSmsSession(sender, recipient, accountSid, true), expires); Object object = Await.result(future, Duration.create(10, TimeUnit.SECONDS)); Class<?> klass = object.getClass(); if (SmsServiceResponse.class.equals(klass)) { final SmsServiceResponse<ActorRef> smsServiceResponse = (SmsServiceResponse<ActorRef>) object; if (smsServiceResponse.succeeded()) { // Create an SMS record for the text message. final SmsMessage record = sms(new Sid(accountSid), getApiVersion(data), sender, recipient, body, SmsMessage.Status.SENDING, SmsMessage.Direction.OUTBOUND_API, statusCallback); dao.addSmsMessage(record); // Send the sms. final ActorRef session = smsServiceResponse.get(); final ActorRef observer = observer(); session.tell(new Observe(observer), observer); session.tell(new SmsSessionAttribute("record", record), null); final SmsSessionRequest request = new SmsSessionRequest(sender, recipient, body, encoding, customRestOutgoingHeaderMap); session.tell(request, null); if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(record), APPLICATION_JSON).build(); } else if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(record); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else { return null; } } else { String msg = smsServiceResponse.cause().getMessage(); String error = "SMS_LIMIT_EXCEEDED"; return status(Response.Status.FORBIDDEN).entity(buildErrorResponseBody(msg, error, responseType)).build(); } } return status(INTERNAL_SERVER_ERROR).build(); } catch (final Exception exception) { return status(INTERNAL_SERVER_ERROR).entity(exception.getMessage()).build(); } } private SmsMessage sms(final Sid accountSid, final String apiVersion, final String sender, final String recipient, final String body, final SmsMessage.Status status, final SmsMessage.Direction direction, URI callback) { final SmsMessage.Builder builder = SmsMessage.builder(); final Sid sid = Sid.generate(Sid.Type.SMS_MESSAGE); builder.setSid(sid); builder.setAccountSid(accountSid); builder.setSender(sender); builder.setRecipient(recipient); builder.setBody(body); builder.setStatus(status); builder.setDirection(direction); builder.setPrice(new BigDecimal(0.00)); // TODO - this needs to be added as property to Configuration somehow builder.setPriceUnit(Currency.getInstance("USD")); builder.setApiVersion(apiVersion); final StringBuilder buffer = new StringBuilder(); buffer.append("/").append(apiVersion).append("/Accounts/"); buffer.append(accountSid.toString()).append("/SMS/Messages/"); buffer.append(sid.toString()); final URI uri = URI.create(buffer.toString()); builder.setUri(uri); builder.setStatusCallback(callback); return builder.build(); } private void validate(final MultivaluedMap<String, String> data) throws NullPointerException { if (!data.containsKey(FROM_PARAM)) { throw new NullPointerException("From can not be null."); } else if (!data.containsKey(TO_PARAM)) { throw new NullPointerException("To can not be null."); } else if (!data.containsKey(BODY_PARAM)) { throw new NullPointerException("Body can not be null."); } } private ActorRef observer() { final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new SmsSessionObserver(); } }); return system.actorOf(props); } private final class SmsSessionObserver extends RestcommUntypedActor { public SmsSessionObserver() { super(); } @Override public void onReceive(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (SmsSessionResponse.class.equals(klass)) { final SmsSessionResponse response = (SmsSessionResponse) message; final SmsSessionInfo info = response.info(); SmsMessage record = (SmsMessage) info.attributes().get("record"); dao.updateSmsMessage(record); final UntypedActorContext context = getContext(); final ActorRef self = self(); context.stop(self); } } } @Path("/{sid}") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getSmsMessageAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getSmsMessage(accountSid, sid, retrieveMediaType(accept), ContextUtil.convert(sec)); } @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getSmsMessages(@PathParam("accountSid") final String accountSid, @Context UriInfo info, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getSmsMessages(accountSid, info, retrieveMediaType(accept), ContextUtil.convert(sec)); } @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response putSmsMessage(@PathParam("accountSid") final String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return putSmsMessage(accountSid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } }
25,318
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
GeolocationEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/GeolocationEndpoint.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2013, Telestax Inc and individual contributors * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.connect.http; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.sun.jersey.spi.resource.Singleton; import com.thoughtworks.xstream.XStream; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.net.URL; import java.util.Arrays; import java.util.List; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import static javax.ws.rs.core.MediaType.APPLICATION_JSON; import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE; import static javax.ws.rs.core.MediaType.APPLICATION_XML; import static javax.ws.rs.core.MediaType.APPLICATION_XML_TYPE; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import static javax.ws.rs.core.Response.Status.*; import static javax.ws.rs.core.Response.ok; import static javax.ws.rs.core.Response.status; import javax.ws.rs.core.SecurityContext; import org.apache.commons.configuration.Configuration; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.log4j.Logger; import org.joda.time.DateTime; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.commons.util.StringUtils; import org.restcomm.connect.dao.AccountsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.GeolocationDao; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.Geolocation; import org.restcomm.connect.dao.entities.Geolocation.GeolocationType; import org.restcomm.connect.dao.entities.GeolocationList; import org.restcomm.connect.dao.entities.RestCommResponse; import org.restcomm.connect.http.converter.ClientListConverter; import org.restcomm.connect.http.converter.GeolocationConverter; import org.restcomm.connect.http.converter.GeolocationListConverter; import org.restcomm.connect.http.converter.RestCommResponseConverter; import org.restcomm.connect.http.security.ContextUtil; import org.restcomm.connect.http.security.PermissionEvaluator.SecuredType; import org.restcomm.connect.identity.UserIdentityContext; /** * @author <a href="mailto:[email protected]"> Fernando Mendioroz </a> * */ @Path("/Accounts/{accountSid}/Geolocation") @ThreadSafe @Singleton public class GeolocationEndpoint extends AbstractEndpoint { @Context protected ServletContext context; protected Configuration configuration; protected GeolocationDao dao; protected Gson gson; protected XStream xstream; protected AccountsDao accountsDao; private static final Logger logger = Logger.getLogger(GeolocationEndpoint.class); private static final String ImmediateGT = Geolocation.GeolocationType.Immediate.toString(); private static final String NotificationGT = Geolocation.GeolocationType.Notification.toString(); private String cause; private String rStatus; private static enum responseStatus { Queued("queued"), Sent("sent"), Processing("processing"), Successful("successful"), PartiallySuccessful( "partially-successful"), LastKnown("last-known"), Failed("failed"), Unauthorized("unauthorized"), Rejected( "rejected"); private final String rs; private responseStatus(final String rs) { this.rs = rs; } @Override public String toString() { return rs; } } public GeolocationEndpoint() { super(); } @PostConstruct public void init() { final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); dao = storage.getGeolocationDao(); accountsDao = storage.getAccountsDao(); configuration = (Configuration) context.getAttribute(Configuration.class.getName()); configuration = configuration.subset("runtime-settings"); super.init(configuration); final GeolocationConverter converter = new GeolocationConverter(configuration); final GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Geolocation.class, converter); builder.setPrettyPrinting(); gson = builder.create(); xstream = new XStream(); xstream.alias("RestcommResponse", RestCommResponse.class); xstream.registerConverter(converter); xstream.registerConverter(new ClientListConverter(configuration)); xstream.registerConverter(new GeolocationListConverter(configuration)); xstream.registerConverter(new RestCommResponseConverter(configuration)); } protected Response getGeolocation(final String accountSid, final String sid, final MediaType responseType, UserIdentityContext userIdentityContext) { Account account; try { account = accountsDao.getAccount(accountSid); permissionEvaluator.secure(account, "RestComm:Read:Geolocation", userIdentityContext); } catch (final Exception exception) { return status(UNAUTHORIZED).build(); } // final Geolocation geolocation = dao.getGeolocation(new Sid(sid)); Geolocation geolocation = null; if (Sid.pattern.matcher(sid).matches()) { geolocation = dao.getGeolocation(new Sid(sid)); } if (geolocation == null) { return status(NOT_FOUND).build(); } else { try { permissionEvaluator.secure(account, geolocation.getAccountSid(), SecuredType.SECURED_APP, userIdentityContext); } catch (final Exception exception) { return status(UNAUTHORIZED).build(); } if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(geolocation); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(geolocation), APPLICATION_JSON).build(); } else { return null; } } } protected Response getGeolocations(final String accountSid, final MediaType responseType, UserIdentityContext userIdentityContext) { Account account; try { account = accountsDao.getAccount(accountSid); permissionEvaluator.secure(account, "RestComm:Read:Geolocation", SecuredType.SECURED_APP, userIdentityContext); } catch (final Exception exception) { return status(UNAUTHORIZED).build(); } final List<Geolocation> geolocations = dao.getGeolocations(new Sid(accountSid)); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(new GeolocationList(geolocations)); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(geolocations), APPLICATION_JSON).build(); } else { return null; } } protected Response deleteGeolocation(final String accountSid, final String sid, UserIdentityContext userIdentityContext) { Account account; try { account = accountsDao.getAccount(accountSid); permissionEvaluator.secure(account, "RestComm:Delete:Geolocation", userIdentityContext); Geolocation geolocation = dao.getGeolocation(new Sid(sid)); if (geolocation != null) { permissionEvaluator.secure(account, geolocation.getAccountSid(), SecuredType.SECURED_APP, userIdentityContext ); } } catch (final Exception exception) { return status(UNAUTHORIZED).build(); } dao.removeGeolocation(new Sid(sid)); return ok().build(); } public Response putGeolocation(final String accountSid, final MultivaluedMap<String, String> data, GeolocationType geolocationType, final MediaType responseType, UserIdentityContext userIdentityContext) { Account account; try { account = accountsDao.getAccount(accountSid); permissionEvaluator.secure(account, "RestComm:Create:Geolocation", SecuredType.SECURED_APP, userIdentityContext); } catch (final Exception exception) { return status(UNAUTHORIZED).build(); } try { validate(data, geolocationType); } catch (final NullPointerException nullPointerException) { // API compliance check regarding missing mandatory parameters return status(BAD_REQUEST).entity(nullPointerException.getMessage()).build(); } catch (final IllegalArgumentException illegalArgumentException) { // API compliance check regarding malformed parameters cause = illegalArgumentException.getMessage(); rStatus = responseStatus.Failed.toString(); } catch (final UnsupportedOperationException unsupportedOperationException) { // API compliance check regarding parameters not allowed for Immediate type of Geolocation return status(BAD_REQUEST).entity(unsupportedOperationException.getMessage()).build(); } /*********************************************/ /*** Query GMLC for Location Data, stage 1 ***/ /*********************************************/ try { String targetMSISDN = data.getFirst("DeviceIdentifier"); Configuration gmlcConf = configuration.subset("gmlc"); String gmlcURI = gmlcConf.getString("gmlc-uri"); // Authorization for further stage of the project String gmlcUser = gmlcConf.getString("gmlc-user"); String gmlcPassword = gmlcConf.getString("gmlc-password"); // Credentials credentials = new UsernamePasswordCredentials(gmlcUser, gmlcPassword); URL url = new URL(gmlcURI + targetMSISDN); HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(String.valueOf(url)); // Authorization for further stage of the project request.addHeader("User-Agent", gmlcUser); request.addHeader("User-Password", gmlcPassword); HttpResponse response = client.execute(request); final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream stream = entity.getContent(); try { BufferedReader br = new BufferedReader( new InputStreamReader(stream)); String gmlcResponse = null; while (null != (gmlcResponse = br.readLine())) { List<String> items = Arrays.asList(gmlcResponse.split("\\s*,\\s*")); if (logger.isInfoEnabled()) { logger.info("Data retrieved from GMLC: " + items.toString()); } for (String item : items) { for (int i = 0; i < items.size(); i++) { if (item.contains("mcc")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("MobileCountryCode", token); } if (item.contains("mnc")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("MobileNetworkCode", token); } if (item.contains("lac")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("LocationAreaCode", token); } if (item.contains("cellid")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("CellId", token); } if (item.contains("aol")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("LocationAge", token); } if (item.contains("vlrNumber")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("NetworkEntityAddress", token); } if (item.contains("latitude")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("DeviceLatitude", token); } if (item.contains("longitude")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("DeviceLongitude", token); } if (item.contains("civicAddress")) { String token = item.substring(item.lastIndexOf("=") + 1); data.putSingle("FormattedAddress", token); } } } if (gmlcURI != null && gmlcResponse != null) { // For debugging/logging purposes only if (logger.isDebugEnabled()) { logger.debug("Geolocation data of " + targetMSISDN + " retrieved from GMCL at: " + gmlcURI); logger.debug("MCC (Mobile Country Code) = " + getInteger("MobileCountryCode", data)); logger.debug("MNC (Mobile Network Code) = " + data.getFirst("MobileNetworkCode")); logger.debug("LAC (Location Area Code) = " + data.getFirst("LocationAreaCode")); logger.debug("CI (Cell ID) = " + data.getFirst("CellId")); logger.debug("AOL (Age of Location) = " + getInteger("LocationAge", data)); logger.debug("NNN (Network Node Number/Address) = " + +getLong("NetworkEntityAddress", data)); logger.debug("Devide Latitude = " + data.getFirst("DeviceLatitude")); logger.debug("Devide Longitude = " + data.getFirst("DeviceLongitude")); logger.debug("Civic Address = " + data.getFirst("FormattedAddress")); } } } } finally { stream.close(); } } } catch (Exception ex) { if (logger.isInfoEnabled()) { logger.info("Problem while trying to retrieve data from GMLC"); } return status(INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build(); } Geolocation geolocation = createFrom(new Sid(accountSid), data, geolocationType); if (geolocation.getResponseStatus() != null && geolocation.getResponseStatus().equals(responseStatus.Rejected.toString())) { if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(geolocation); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(geolocation), APPLICATION_JSON).build(); } else { return null; } } else { dao.addGeolocation(geolocation); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(geolocation); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(geolocation), APPLICATION_JSON).build(); } else { return null; } } } private void validate(final MultivaluedMap<String, String> data, Geolocation.GeolocationType glType) throws RuntimeException { // ** Validation of Geolocation POST requests with valid type **/ if (!glType.toString().equals(ImmediateGT) && !glType.toString().equals(NotificationGT)) { throw new NullPointerException("Geolocation Type can not be null, but either \"Immediate\" or \"Notification\"."); } // *** DeviceIdentifier can not be null ***/ if (!data.containsKey("DeviceIdentifier")) { throw new NullPointerException("DeviceIdentifier value can not be null"); } // *** StatusCallback can not be null ***/ if (!data.containsKey("StatusCallback")) { throw new NullPointerException("StatusCallback value can not be null"); } // *** DesiredAccuracy must be API compliant: High, Average or Low***/ if (data.containsKey("DesiredAccuracy")) { String desiredAccuracy = data.getFirst("DesiredAccuracy"); if (!desiredAccuracy.equalsIgnoreCase("High") && !desiredAccuracy.equalsIgnoreCase("Average") && !desiredAccuracy.equalsIgnoreCase("Low")) { throw new IllegalArgumentException("DesiredAccuracy value not API compliant"); } } // *** DeviceLatitude must be API compliant***/ if (data.containsKey("DeviceLatitude")) { String deviceLat = data.getFirst("DeviceLatitude"); Boolean devLatWGS84 = validateGeoCoordinatesFormat(deviceLat); if (!devLatWGS84) { throw new IllegalArgumentException("DeviceLatitude not API compliant"); } } // *** DeviceLongitude must be API compliant***/ if (data.containsKey("DeviceLongitude")) { String deviceLong = data.getFirst("DeviceLongitude"); Boolean devLongWGS84 = validateGeoCoordinatesFormat(deviceLong); if (!devLongWGS84) { throw new IllegalArgumentException("DeviceLongitude not API compliant"); } } // *** GeofenceEvent must belong to Notification type of Geolocation, not null and API compliant: in, out or in-out***/ if (!data.containsKey("GeofenceEvent") && glType.toString().equals(NotificationGT)) { throw new NullPointerException("GeofenceEvent value con not be null for Notification type of Geolocation"); } else if (data.containsKey("GeofenceEvent") && !glType.toString().equals(NotificationGT)) { throw new UnsupportedOperationException("GeofenceEvent only applies for Notification type of Geolocation"); } else if (data.containsKey("GeofenceEvent") && glType.toString().equals(NotificationGT)) { String geofenceEvent = data.getFirst("GeofenceEvent"); if (!geofenceEvent.equalsIgnoreCase("in") && !geofenceEvent.equalsIgnoreCase("out") && !geofenceEvent.equalsIgnoreCase("in-out")) { throw new IllegalArgumentException("GeofenceEvent value not API compliant"); } } // *** EventGeofenceLatitude must belong to Notification type of Geolocation, not null and API compliant ***/ if (!data.containsKey("EventGeofenceLatitude") && glType.toString().equals(NotificationGT)) { throw new NullPointerException("EventGeofenceLatitude value con not be null for Notification type of Geolocation"); } else if (data.containsKey("EventGeofenceLatitude") && !glType.toString().equals(NotificationGT)) { throw new UnsupportedOperationException("EventGeofenceLatitude only applies for Notification type of Geolocation"); } else if (data.containsKey("EventGeofenceLatitude") && glType.toString().equals(NotificationGT)) { String eventGeofenceLat = data.getFirst("EventGeofenceLatitude"); Boolean eventGeofenceLongWGS84 = validateGeoCoordinatesFormat(eventGeofenceLat); if (!eventGeofenceLongWGS84) { throw new IllegalArgumentException("EventGeofenceLatitude format not API compliant"); } } // *** EventGeofenceLongitude must belong to Notification type of Geolocation and must be API compliant ***/ if (!data.containsKey("EventGeofenceLongitude") && glType.toString().equals(NotificationGT)) { throw new NullPointerException("EventGeofenceLongitude value con not be null for Notification type of Geolocation"); } else if (data.containsKey("EventGeofenceLongitude") && !glType.toString().equals(NotificationGT)) { throw new UnsupportedOperationException("EventGeofenceLongitude only applies for Notification type of Geolocation"); } else if (data.containsKey("EventGeofenceLongitude") && glType.toString().equals(NotificationGT)) { String eventGeofenceLong = data.getFirst("EventGeofenceLongitude"); Boolean eventGeofenceLongWGS84 = validateGeoCoordinatesFormat(eventGeofenceLong); if (!eventGeofenceLongWGS84) { throw new IllegalArgumentException("EventGeofenceLongitude format not API compliant"); } } // *** GeofenceRange can not be null in Notification type of Geolocation***/ if (!data.containsKey("GeofenceRange") && glType.toString().equals(NotificationGT)) { throw new NullPointerException("GeofenceRange value con not be null for Notification type of Geolocation"); } else if (data.containsKey("GeofenceRange") && !glType.toString().equals(NotificationGT)) { throw new UnsupportedOperationException("GeofenceRange only applies for Notification type of Geolocation"); } // *** LocationTimestamp must be API compliant: DateTime format only***/ try { if (data.containsKey("LocationTimestamp")) { @SuppressWarnings("unused") DateTime locationTimestamp = getDateTime("LocationTimestamp", data); } } catch (IllegalArgumentException exception) { throw new IllegalArgumentException("LocationTimestamp value is not API compliant"); } } private Geolocation createFrom(final Sid accountSid, final MultivaluedMap<String, String> data, Geolocation.GeolocationType glType) { if (rStatus != null && rStatus.equals(responseStatus.Failed.toString())) { Geolocation gl = buildFailedGeolocation(accountSid, data, glType); return gl; } else { Geolocation gl = buildGeolocation(accountSid, data, glType); return gl; } } private Geolocation buildGeolocation(final Sid accountSid, final MultivaluedMap<String, String> data, Geolocation.GeolocationType glType) { final Geolocation.Builder builder = Geolocation.builder(); final Sid sid = Sid.generate(Sid.Type.GEOLOCATION); String geoloctype = glType.toString(); builder.setSid(sid); DateTime currentDateTime = DateTime.now(); builder.setDateUpdated(currentDateTime); builder.setAccountSid(accountSid); builder.setSource(data.getFirst("Source")); builder.setDeviceIdentifier(data.getFirst("DeviceIdentifier")); builder.setGeolocationType(glType); builder.setResponseStatus(data.getFirst("ResponseStatus")); builder.setCause(data.getFirst("Cause")); builder.setCellId(data.getFirst("CellId")); builder.setLocationAreaCode(data.getFirst("LocationAreaCode")); builder.setMobileCountryCode(getInteger("MobileCountryCode", data)); builder.setMobileNetworkCode(data.getFirst("MobileNetworkCode")); builder.setNetworkEntityAddress(getLong("NetworkEntityAddress", data)); builder.setAgeOfLocationInfo(getInteger("LocationAge", data)); builder.setDeviceLatitude(data.getFirst("DeviceLatitude")); builder.setDeviceLongitude(data.getFirst("DeviceLongitude")); builder.setAccuracy(getLong("Accuracy", data)); builder.setPhysicalAddress(data.getFirst("PhysicalAddress")); builder.setInternetAddress(data.getFirst("InternetAddress")); builder.setFormattedAddress(data.getFirst("FormattedAddress")); builder.setLocationTimestamp(getDateTime("LocationTimestamp", data)); builder.setEventGeofenceLatitude(data.getFirst("EventGeofenceLatitude")); builder.setEventGeofenceLongitude(data.getFirst("EventGeofenceLongitude")); builder.setRadius(getLong("Radius", data)); builder.setGeolocationPositioningType(data.getFirst("GeolocationPositioningType")); builder.setLastGeolocationResponse(data.getFirst("LastGeolocationResponse")); builder.setApiVersion(getApiVersion(data)); String rootUri = configuration.getString("root-uri"); rootUri = StringUtils.addSuffixIfNotPresent(rootUri, "/"); final StringBuilder buffer = new StringBuilder(); buffer.append(rootUri).append(getApiVersion(data)).append("/Accounts/").append(accountSid.toString()) .append("/Geolocation/" + geoloctype + "/").append(sid.toString()); builder.setUri(URI.create(buffer.toString())); return builder.build(); } private Geolocation buildFailedGeolocation(final Sid accountSid, final MultivaluedMap<String, String> data, Geolocation.GeolocationType glType) { final Geolocation.Builder builder = Geolocation.builder(); final Sid sid = Sid.generate(Sid.Type.GEOLOCATION); String geoloctype = glType.toString(); builder.setSid(sid); DateTime currentDateTime = DateTime.now(); builder.setDateUpdated(currentDateTime); builder.setAccountSid(accountSid); builder.setSource(data.getFirst("Source")); builder.setDeviceIdentifier(data.getFirst("DeviceIdentifier")); builder.setResponseStatus(rStatus); builder.setGeolocationType(glType); builder.setCause(cause); builder.setApiVersion(getApiVersion(data)); String rootUri = configuration.getString("root-uri"); rootUri = StringUtils.addSuffixIfNotPresent(rootUri, "/"); final StringBuilder buffer = new StringBuilder(); buffer.append(rootUri).append(getApiVersion(data)).append("/Accounts/").append(accountSid.toString()) .append("/Geolocation/" + geoloctype + "/").append(sid.toString()); builder.setUri(URI.create(buffer.toString())); return builder.build(); } protected Response updateGeolocation(final String accountSid, final String sid, final MultivaluedMap<String, String> data, final MediaType responseType, UserIdentityContext userIdentityContext) { Account account; try { account = accountsDao.getAccount(accountSid); permissionEvaluator.secure(account, "RestComm:Modify:Geolocation", userIdentityContext); } catch (final Exception exception) { return status(UNAUTHORIZED).build(); } Geolocation geolocation = dao.getGeolocation(new Sid(sid)); if (geolocation == null) { return status(NOT_FOUND).build(); } else { try { permissionEvaluator.secure(account, geolocation.getAccountSid(), SecuredType.SECURED_APP, userIdentityContext); } catch (final NullPointerException exception) { return status(BAD_REQUEST).entity(exception.getMessage()).build(); } catch (final Exception exception) { return status(UNAUTHORIZED).build(); } geolocation = update(geolocation, data); dao.updateGeolocation(geolocation); if (APPLICATION_XML_TYPE.equals(responseType)) { final RestCommResponse response = new RestCommResponse(geolocation); return ok(xstream.toXML(response), APPLICATION_XML).build(); } else if (APPLICATION_JSON_TYPE.equals(responseType)) { return ok(gson.toJson(geolocation), APPLICATION_JSON).build(); } else { return null; } } } private Geolocation update(final Geolocation geolocation, final MultivaluedMap<String, String> data) { Geolocation updatedGeolocation = geolocation; // *** Set of parameters with provided data for Geolocation update***// if (data.containsKey("Source")) { updatedGeolocation = updatedGeolocation.setSource(data.getFirst("Source")); } if (data.containsKey("DeviceIdentifier")) { updatedGeolocation = updatedGeolocation.setDeviceIdentifier(data.getFirst("DeviceIdentifier")); } if (data.containsKey("ResponseStatus")) { updatedGeolocation = updatedGeolocation.setResponseStatus(data.getFirst("ResponseStatus")); updatedGeolocation = updatedGeolocation.setDateUpdated(DateTime.now()); if (data.containsKey("Cause") && (updatedGeolocation.getResponseStatus().equals(responseStatus.Rejected.toString()) || updatedGeolocation.getResponseStatus().equals(responseStatus.Unauthorized.toString()) || updatedGeolocation.getResponseStatus().equals(responseStatus.Failed.toString()))) { updatedGeolocation = updatedGeolocation.setCause(data.getFirst("Cause")); // cause is set to null if responseStatus is not rejected, failed or unauthorized } if (!updatedGeolocation.getResponseStatus().equals(responseStatus.Rejected.toString()) || !updatedGeolocation.getResponseStatus().equals(responseStatus.Unauthorized.toString()) || !updatedGeolocation.getResponseStatus().equals(responseStatus.Failed.toString())) { updatedGeolocation = updatedGeolocation.setCause(null); // cause is set to null if responseStatus is not rejected, failed or unauthorized } } if (updatedGeolocation.getResponseStatus() != null && (!updatedGeolocation.getResponseStatus().equals(responseStatus.Unauthorized.toString()) || !updatedGeolocation.getResponseStatus().equals(responseStatus.Failed.toString()))) { updatedGeolocation = updatedGeolocation.setCause(null); // "Cause" is set to null if "ResponseStatus" is not null and is neither "rejected", "unauthorized" nor "failed" } if (data.containsKey("CellId")) { updatedGeolocation = updatedGeolocation.setCellId(data.getFirst("CellId")); } if (data.containsKey("LocationAreaCode")) { updatedGeolocation = updatedGeolocation.setLocationAreaCode(data.getFirst("LocationAreaCode")); } if (data.containsKey("MobileCountryCode")) { updatedGeolocation = updatedGeolocation.setMobileCountryCode(getInteger("MobileCountryCode", data)); } if (data.containsKey("MobileNetworkCode")) { updatedGeolocation = updatedGeolocation.setMobileNetworkCode(data.getFirst("MobileNetworkCode")); } if (data.containsKey("NetworkEntityAddress")) { updatedGeolocation = updatedGeolocation.setNetworkEntityAddress(getLong("NetworkEntityAddress", data)); } if (data.containsKey("LocationAge")) { updatedGeolocation = updatedGeolocation.setAgeOfLocationInfo(getInteger("LocationAge", data)); } if (data.containsKey("DeviceLatitude")) { String deviceLat = data.getFirst("DeviceLatitude"); Boolean deviceLatWGS84 = validateGeoCoordinatesFormat(deviceLat); if (!deviceLatWGS84) { return buildFailedGeolocationUpdate(geolocation, data, geolocation.getGeolocationType(), responseStatus.Failed.toString(), "DeviceLatitude format not API compliant"); } else { updatedGeolocation = updatedGeolocation.setDeviceLatitude(deviceLat); } } if (data.containsKey("DeviceLongitude")) { updatedGeolocation = updatedGeolocation.setDeviceLongitude(data.getFirst("DeviceLongitude")); String deviceLong = data.getFirst("DeviceLongitude"); Boolean deviceLongGS84 = validateGeoCoordinatesFormat(deviceLong); if (!deviceLongGS84) { return buildFailedGeolocationUpdate(geolocation, data, geolocation.getGeolocationType(), responseStatus.Failed.toString(), "DeviceLongitude format not API compliant"); } else { updatedGeolocation = updatedGeolocation.setDeviceLongitude(deviceLong); } } if (data.containsKey("Accuracy")) { updatedGeolocation = updatedGeolocation.setAccuracy(getLong("Accuracy", data)); } if (data.containsKey("PhysicalAddress")) { updatedGeolocation = updatedGeolocation.setPhysicalAddress(data.getFirst("PhysicalAddress")); } if (data.containsKey("InternetAddress")) { updatedGeolocation = updatedGeolocation.setInternetAddress(data.getFirst("InternetAddress")); } if (data.containsKey("FormattedAddress")) { updatedGeolocation = updatedGeolocation.setFormattedAddress(data.getFirst("FormattedAddress")); } if (data.containsKey("LocationTimestamp")) { updatedGeolocation = updatedGeolocation.setLocationTimestamp(getDateTime("LocationTimestamp", data)); } if (data.containsKey("EventGeofenceLatitude") && geolocation.getGeolocationType().toString().equals(NotificationGT)) { String eventGeofenceLat = data.getFirst("EventGeofenceLatitude"); Boolean eventGeofenceLatWGS84 = validateGeoCoordinatesFormat(eventGeofenceLat); if (!eventGeofenceLatWGS84) { return buildFailedGeolocationUpdate(geolocation, data, geolocation.getGeolocationType(), responseStatus.Failed.toString(), "EventGeofenceLatitude format not API compliant"); } else { updatedGeolocation = updatedGeolocation.setEventGeofenceLatitude(eventGeofenceLat); } } if (data.containsKey("EventGeofenceLongitude") && geolocation.getGeolocationType().toString().equals(NotificationGT)) { String eventGeofenceLong = data.getFirst("EventGeofenceLongitude"); Boolean eventGeofenceLongWGS84 = validateGeoCoordinatesFormat(eventGeofenceLong); if (!eventGeofenceLongWGS84) { return buildFailedGeolocationUpdate(geolocation, data, geolocation.getGeolocationType(), responseStatus.Failed.toString(), "EventGeofenceLongitude format not API compliant"); } else { updatedGeolocation = updatedGeolocation.setEventGeofenceLongitude(eventGeofenceLong); } } if (data.containsKey("Radius") && geolocation.getGeolocationType().toString().equals(NotificationGT)) { updatedGeolocation = updatedGeolocation.setRadius(getLong("Radius", data)); } if (data.containsKey("GeolocationPositioningType")) { updatedGeolocation = updatedGeolocation.setGeolocationPositioningType(data.getFirst("GeolocationPositioningType")); } if (data.containsKey("LastGeolocationResponse")) { updatedGeolocation = updatedGeolocation.setLastGeolocationResponse(data.getFirst("LastGeolocationResponse")); } DateTime thisDateTime = DateTime.now(); updatedGeolocation = updatedGeolocation.setDateUpdated(thisDateTime); return updatedGeolocation; } private Geolocation buildFailedGeolocationUpdate(Geolocation geolocation, final MultivaluedMap<String, String> data, Geolocation.GeolocationType glType, String responseStatus, String wrongUpdateCause) { final Sid accountSid = geolocation.getAccountSid(); final Sid sid = geolocation.getSid(); final Geolocation.Builder builder = Geolocation.builder(); String geoloctype = glType.toString(); DateTime currentDateTime = DateTime.now(); builder.setSid(sid); builder.setDateUpdated(currentDateTime); builder.setAccountSid(accountSid); builder.setResponseStatus(responseStatus); builder.setCause(wrongUpdateCause); builder.setSource(data.getFirst("Source")); builder.setDeviceIdentifier(data.getFirst("DeviceIdentifier")); builder.setGeolocationType(glType); builder.setApiVersion(getApiVersion(data)); String rootUri = configuration.getString("root-uri"); rootUri = StringUtils.addSuffixIfNotPresent(rootUri, "/"); final StringBuilder buffer = new StringBuilder(); buffer.append(rootUri).append(getApiVersion(data)).append("/Accounts/").append(accountSid.toString()) .append("/Geolocation/" + geoloctype + "/").append(sid.toString()); builder.setUri(URI.create(buffer.toString())); return builder.build(); } private boolean validateGeoCoordinatesFormat(String coordinates) { String degrees = "\\u00b0"; String minutes = "'"; Boolean WGS84_validation; Boolean pattern1 = coordinates.matches("[NWSE]{1}\\d{1,3}\\s\\d{1,2}\\s\\d{1,2}\\.\\d{1,2}$"); Boolean pattern2 = coordinates.matches("\\d{1,3}\\s\\d{1,2}\\s\\d{1,2}\\.\\d{1,2}[NWSE]{1}$"); Boolean pattern3 = coordinates.matches("\\d{1,3}[" + degrees + "]\\d{1,3}[" + minutes + "]\\d{1,2}\\.\\d{1,2}[" + minutes + "][" + minutes + "][NWSE]{1}$"); Boolean pattern4 = coordinates.matches("[NWSE]{1}\\d{1,3}[" + degrees + "]\\d{1,3}[" + minutes + "]\\d{1,2}\\.\\d{1,2}[" + minutes + "][" + minutes + "]$"); Boolean pattern5 = coordinates.matches("\\d{1,3}\\s\\d{1,2}\\s\\d{1,2}\\.\\d{1,2}$"); Boolean pattern6 = coordinates.matches("-?\\d{1,3}\\s\\d{1,2}\\s\\d{1,2}\\.\\d{1,2}$"); Boolean pattern7 = coordinates.matches("-?\\d+(\\.\\d+)?"); if (pattern1 || pattern2 || pattern3 || pattern4 || pattern5 || pattern6 || pattern7) { WGS84_validation = true; return WGS84_validation; } else { WGS84_validation = false; return WGS84_validation; } } @Path("/Immediate/{sid}") @DELETE public Response deleteImmediateGeolocationAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, @Context SecurityContext sec) { return deleteGeolocation(accountSid, sid, ContextUtil.convert(sec)); } @Path("/Immediate/{sid}") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getImmediateGeolocationAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getGeolocation(accountSid, sid, retrieveMediaType(accept), ContextUtil.convert(sec)); } @Path("/Immediate") @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response putImmediateGeolocationXmlPost(@PathParam("accountSid") final String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return putGeolocation(accountSid, data, Geolocation.GeolocationType.Immediate, retrieveMediaType(accept), ContextUtil.convert(sec)); } @Path("/Immediate/{sid}") @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response putImmediateGeolocationAsXmlPost(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return updateGeolocation(accountSid, sid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } @Path("/Immediate/{sid}") @PUT @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response updateImmediateGeolocationAsXmlPut(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return updateGeolocation(accountSid, sid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } /*******************************************/ // *** Notification type of Geolocation ***// /*******************************************/ @Path("/Notification/{sid}") @DELETE public Response deleteNotificationGeolocationAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, @Context SecurityContext sec) { return deleteGeolocation(accountSid, sid,ContextUtil.convert(sec)); } @Path("/Notification/{sid}") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getNotificationGeolocationAsXml(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getGeolocation(accountSid, sid, retrieveMediaType(accept), ContextUtil.convert(sec)); } @Path("/Notification") @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response putNotificationGeolocationXmlPost(@PathParam("accountSid") final String accountSid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return putGeolocation(accountSid, data, Geolocation.GeolocationType.Notification, retrieveMediaType(accept), ContextUtil.convert(sec)); } @Path("/Notification/{sid}") @POST @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response putNotificationGeolocationAsXmlPost(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return updateGeolocation(accountSid, sid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } @Path("/Notification/{sid}") @PUT @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response updateNotificationGeolocationAsXmlPut(@PathParam("accountSid") final String accountSid, @PathParam("sid") final String sid, final MultivaluedMap<String, String> data, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return updateGeolocation(accountSid, sid, data, retrieveMediaType(accept), ContextUtil.convert(sec)); } @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getGeolocationsAsXml(@PathParam("accountSid") final String accountSid, @HeaderParam("Accept") String accept, @Context SecurityContext sec) { return getGeolocations(accountSid, retrieveMediaType(accept), ContextUtil.convert(sec)); } }
48,047
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AbstractEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/AbstractEndpoint.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.restcomm.connect.http; import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber; import java.math.BigInteger; import java.net.URI; import java.util.List; import javax.servlet.ServletContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import org.apache.commons.configuration.Configuration; import org.apache.log4j.Logger; import org.joda.time.DateTime; import org.restcomm.connect.commons.annotations.concurrency.NotThreadSafe; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.commons.util.StringUtils; import org.restcomm.connect.dao.AccountsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.OrganizationsDao; import org.restcomm.connect.extension.api.ApiRequest; import org.restcomm.connect.extension.api.ExtensionType; import org.restcomm.connect.extension.api.RestcommExtensionGeneric; import org.restcomm.connect.extension.controller.ExtensionController; import org.restcomm.connect.http.security.PermissionEvaluator; /** * @author [email protected] (Thomas Quintana) * @author [email protected] */ @NotThreadSafe public abstract class AbstractEndpoint { protected Logger logger = Logger.getLogger(AbstractEndpoint.class); private String defaultApiVersion; protected Configuration configuration; protected String baseRecordingsPath; //List of extensions for RestAPI protected List<RestcommExtensionGeneric> extensions; @Context protected ServletContext context; protected AccountsDao accountsDao; protected OrganizationsDao organizationsDao; protected PermissionEvaluator permissionEvaluator; public AbstractEndpoint() { super(); } public AbstractEndpoint(ServletContext context) { this.context = context; } protected MediaType retrieveMediaType(String accept) { if (accept.contains("json")) { return MediaType.APPLICATION_JSON_TYPE; } return MediaType.APPLICATION_XML_TYPE; } protected void init(final Configuration configuration) { final String path = configuration.getString("recordings-path"); baseRecordingsPath = StringUtils.addSuffixIfNotPresent(path, "/"); defaultApiVersion = configuration.getString("api-version"); extensions = ExtensionController.getInstance().getExtensions(ExtensionType.RestApi); final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); this.accountsDao = storage.getAccountsDao(); this.organizationsDao = storage.getOrganizationsDao(); if (logger.isInfoEnabled()) { if (extensions != null) { logger.info("RestAPI extensions: "+(extensions != null ? extensions.size() : "0")); } } permissionEvaluator = new PermissionEvaluator(context); } protected String getApiVersion(final MultivaluedMap<String, String> data) { String apiVersion = defaultApiVersion; if (data != null && data.containsKey("ApiVersion")) { apiVersion = data.getFirst("ApiVersion"); } return apiVersion; } protected PhoneNumber getPhoneNumber(final MultivaluedMap<String, String> data) { final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance(); PhoneNumber phoneNumber = null; try { phoneNumber = phoneNumberUtil.parse(data.getFirst("PhoneNumber"), "US"); } catch (final NumberParseException ignored) { } return phoneNumber; } protected String getMethod(final String name, final MultivaluedMap<String, String> data) { String method = "POST"; if (data.containsKey(name)) { method = data.getFirst(name); } return method; } protected Sid getSid(final String name, final MultivaluedMap<String, String> data) { Sid sid = null; if (data.containsKey(name)) { sid = new Sid(data.getFirst(name)); } return sid; } protected URI getUrl(final String name, final MultivaluedMap<String, String> data) { URI uri = null; if (data.containsKey(name)) { uri = URI.create(data.getFirst(name)); } return uri; } protected Integer getInteger(final String name, final MultivaluedMap<String, String> data) { Integer integer = null; if (data.containsKey(name)) { integer = new Integer(data.getFirst(name)); } return integer; } protected BigInteger getBigInteger(final String name, final MultivaluedMap<String, String> data) { BigInteger bigInteger = null; if (data.containsKey(name)) { bigInteger = new BigInteger(data.getFirst(name)); } return bigInteger; } protected Long getLong(final String name, final MultivaluedMap<String, String> data) { Long l = null; if (data.containsKey(name)) { l = new Long(data.getFirst(name)); } return l; } protected DateTime getDateTime(final String name, final MultivaluedMap<String, String> data) { DateTime dateTime = null; if (data.containsKey(name)) { dateTime = new DateTime(data.getFirst(name)); } return dateTime; } protected Boolean getBoolean(final String name, final MultivaluedMap<String, String> data) { Boolean b = null; if (data.containsKey(name)) { b = new Boolean(data.getFirst(name)); } return b; } protected boolean getHasVoiceCallerIdLookup(final MultivaluedMap<String, String> data) { boolean hasVoiceCallerIdLookup = false; if (data.containsKey("VoiceCallerIdLookup")) { final String value = data.getFirst("VoiceCallerIdLookup"); if ("true".equalsIgnoreCase(value)) { return true; } } return hasVoiceCallerIdLookup; } // A general purpose method to test incoming parameters for meaningful data protected boolean isEmpty(Object value) { if (value == null) return true; if ( value.equals("") ) return true; return false; } // Quick'n'dirty error response building String buildErrorResponseBody(String message, MediaType type) { if (!type.equals(MediaType.APPLICATION_XML_TYPE)) { // fallback to JSON if not XML return "{\"message\":\""+message+"\"}"; } else { return "<RestcommResponse><Message>" + message + "</Message></RestcommResponse>"; } } String buildErrorResponseBody(String message, String error, MediaType type) { if (!type.equals(MediaType.APPLICATION_XML_TYPE)) { // fallback to JSON if not XML return "{\"message\":\""+message+"\",\n\"error\":\""+error+"\"}"; } else { return "<RestcommResponse><Message>" + message + "</Message><Error>"+ error +"</Error></RestcommResponse>"; } } protected boolean executePreApiAction(final ApiRequest apiRequest) { ExtensionController ec = ExtensionController.getInstance(); return ec.executePreApiAction(apiRequest, extensions).isAllowed(); } protected boolean executePostApiAction(final ApiRequest apiRequest) { ExtensionController ec = ExtensionController.getInstance(); return ec.executePostApiAction(apiRequest, extensions).isAllowed(); } }
8,471
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AccountAlreadyClosed.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/exceptions/AccountAlreadyClosed.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.restcomm.connect.http.exceptions; /** * When an operation on an Account fails because the account is in CLOSED state throw * this exception. * * @author [email protected] - Orestis Tsakiridis */ public class AccountAlreadyClosed extends Exception { }
1,095
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
PasswordTooWeak.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/exceptions/PasswordTooWeak.java
package org.restcomm.connect.http.exceptions; /** * Thrown when trying to persist a password that is too weak. * * @author [email protected] - Orestis Tsakiridis */ public class PasswordTooWeak extends Exception { }
220
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
NotAuthenticated.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/exceptions/NotAuthenticated.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2016, 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.restcomm.connect.http.exceptions; /** * @author [email protected] (Orestis Tsakiridis) */ public class NotAuthenticated extends AuthorizationException { }
996
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ResourceAccountMissmatch.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/exceptions/ResourceAccountMissmatch.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.restcomm.connect.http.exceptions; import org.restcomm.connect.commons.exceptions.RestcommRuntimeException; /** * Thrown when a resource (like Clients, Numbers etc.) is accessed under an account * that does not own them. * * @author [email protected] - Orestis Tsakiridis */ public class ResourceAccountMissmatch extends RestcommRuntimeException { public ResourceAccountMissmatch() { } public ResourceAccountMissmatch(String message) { super(message); } public ResourceAccountMissmatch(String message, Throwable cause) { super(message, cause); } public ResourceAccountMissmatch(Throwable cause) { super(cause); } public ResourceAccountMissmatch(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
1,713
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
OperatedAccountMissing.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/exceptions/OperatedAccountMissing.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.restcomm.connect.http.exceptions; import org.restcomm.connect.commons.exceptions.RestcommRuntimeException; /** * @author [email protected] - Orestis Tsakiridis */ public class OperatedAccountMissing extends RestcommRuntimeException { public OperatedAccountMissing() { } public OperatedAccountMissing(String message) { super(message); } public OperatedAccountMissing(String message, Throwable cause) { super(message, cause); } public OperatedAccountMissing(Throwable cause) { super(cause); } public OperatedAccountMissing(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
1,582
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RcmlserverNotifyError.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/exceptions/RcmlserverNotifyError.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.restcomm.connect.http.exceptions; /** * Thrown when notification submission to rcmlserver failed for some reason. * * @author [email protected] - Orestis Tsakiridis */ public class RcmlserverNotifyError extends Exception { public RcmlserverNotifyError(String message) { super(message); } public RcmlserverNotifyError() { } public RcmlserverNotifyError(String message, Throwable cause) { super(message, cause); } }
1,287
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AuthorizationException.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/exceptions/AuthorizationException.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2016, 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.restcomm.connect.http.exceptions; import org.restcomm.connect.commons.exceptions.RestcommRuntimeException; /** * General type of authorization exceptions. All security-related exceptions * in REST endpoints should extend this. * * @author [email protected] (Orestis Tsakiridis) */ public class AuthorizationException extends RestcommRuntimeException { }
1,199
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
InsufficientPermission.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/exceptions/InsufficientPermission.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2016, 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.restcomm.connect.http.exceptions; /** * @author [email protected] (Orestis Tsakiridis) */ public class InsufficientPermission extends AuthorizationException { }
1,002
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommRuntimeExceptionMapper.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/exceptionmappers/RestcommRuntimeExceptionMapper.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2016, 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.restcomm.connect.http.exceptionmappers; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import org.restcomm.connect.dao.exceptions.AccountHierarchyDepthCrossed; import org.restcomm.connect.http.exceptions.InsufficientPermission; import org.restcomm.connect.http.exceptions.NotAuthenticated; import org.restcomm.connect.http.exceptions.OperatedAccountMissing; import org.restcomm.connect.http.exceptions.ResourceAccountMissmatch; import org.restcomm.connect.commons.exceptions.RestcommRuntimeException; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; /** * Generates 401 for AuthorizationException instead of a 500 (and an exception * to the log). It helps to handle authorization errors when they occur in * *Endpoint.init() method where there is no explicit way of returning a * response (feature was needed after shiro removal). * * @author Orestis Tsakiridis */ @Provider public class RestcommRuntimeExceptionMapper implements ExceptionMapper<RestcommRuntimeException> { static final Logger logger = Logger.getLogger(RestcommRuntimeExceptionMapper.class.getName()); static final Map<Class, Response> exceptionMap = new HashMap(); static { exceptionMap.put(NotAuthenticated.class, Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic realm=\"Restcomm realm\"").build()); exceptionMap.put(InsufficientPermission.class, Response.status(Response.Status.FORBIDDEN).build()); exceptionMap.put(OperatedAccountMissing.class, Response.status(Response.Status.NOT_FOUND).build()); exceptionMap.put(ResourceAccountMissmatch.class, Response.status(Response.Status.BAD_REQUEST).build()); exceptionMap.put(AccountHierarchyDepthCrossed.class, Response.status(Response.Status.INTERNAL_SERVER_ERROR).build()); exceptionMap.put(NotAuthenticated.class, Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic realm=\"Restcomm realm\"").build()); } @Override public Response toResponse(RestcommRuntimeException e) { if (logger.isDebugEnabled()) { logger.debug("Converting response to a corresponding http status."); } Response res = null; if (exceptionMap.containsKey(e.getClass())) { res = exceptionMap.get(e.getClass()); } else { // map all other types of auth errors to 403 res = Response.status(Response.Status.FORBIDDEN).build(); } return res; } }
3,491
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CustomReasonPhraseType.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/exceptionmappers/CustomReasonPhraseType.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.restcomm.connect.http.exceptionmappers; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.Response.Status.Family; import javax.ws.rs.core.Response.StatusType; public class CustomReasonPhraseType implements StatusType { public CustomReasonPhraseType(final Family family, final int statusCode, final String reasonPhrase) { this.family = family; this.statusCode = statusCode; this.reasonPhrase = reasonPhrase; } public CustomReasonPhraseType(final Status status, final String reasonPhrase) { this(status.getFamily(), status.getStatusCode(), reasonPhrase); } @Override public Family getFamily() { return family; } @Override public String getReasonPhrase() { return reasonPhrase; } @Override public int getStatusCode() { return statusCode; } private final Family family; private final int statusCode; private final String reasonPhrase; }
1,825
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RcmlserverNotifications.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/client/rcmlserver/RcmlserverNotifications.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.restcomm.connect.http.client.rcmlserver; import com.google.gson.JsonObject; import java.util.ArrayList; /** * @author [email protected] - Orestis Tsakiridis */ public class RcmlserverNotifications extends ArrayList<JsonObject> { }
1,060
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RcmlserverApi.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/client/rcmlserver/RcmlserverApi.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.restcomm.connect.http.client.rcmlserver; import com.google.gson.Gson; import com.google.gson.JsonObject; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.log4j.Logger; import org.restcomm.connect.commons.common.http.CustomHttpClientBuilder; import org.restcomm.connect.commons.configuration.sets.MainConfigurationSet; import org.restcomm.connect.commons.configuration.sets.RcmlserverConfigurationSet; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.commons.util.SecurityUtils; import org.restcomm.connect.core.service.RestcommConnectServiceProvider; import org.restcomm.connect.core.service.util.UriUtils; import org.restcomm.connect.dao.entities.Account; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.concurrent.FutureCallback; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.restcomm.connect.dao.entities.Account.Status; /** * Utility class that handles notification submission to rcmlserver (typically * RVD) * * @author [email protected] - Orestis Tsakiridis */ public class RcmlserverApi { static final Logger logger = Logger.getLogger(RcmlserverApi.class.getName()); enum NotificationType { accountClosed, accountSuspended, accountActivated, accountUninitialized, accountInactivated } private static final Map<Status,NotificationType> status2NotMap = new HashMap(); static { status2NotMap.put(Status.CLOSED, NotificationType.accountClosed); status2NotMap.put(Status.ACTIVE, NotificationType.accountActivated); status2NotMap.put(Status.SUSPENDED, NotificationType.accountSuspended); status2NotMap.put(Status.INACTIVE, NotificationType.accountInactivated); status2NotMap.put(Status.UNINITIALIZED, NotificationType.accountUninitialized); } URI apiUrl; MainConfigurationSet mainConfig; RcmlserverConfigurationSet rcmlserverConfig; UriUtils uriUtils = RestcommConnectServiceProvider.getInstance().uriUtils(); public RcmlserverApi(MainConfigurationSet mainConfig, RcmlserverConfigurationSet rcmlserverConfig, Sid accountSid) { try { // if there is no baseUrl configured we use the resolver to guess the location of the rcml server and the path if (StringUtils.isEmpty(rcmlserverConfig.getBaseUrl())) { // resolveWithBase() should be run lazily to work. Make sure this constructor is invoked after the JBoss connectors have been set up. apiUrl = uriUtils.resolve(new URI(rcmlserverConfig.getApiPath()), accountSid); } // if baseUrl has been configured, concat baseUrl and path to find the location of rcml server. No resolving here. else { String path = rcmlserverConfig.getApiPath(); apiUrl = new URI(rcmlserverConfig.getBaseUrl() + (path != null ? path : "")); } } catch (URISyntaxException e) { throw new RuntimeException(e); } this.rcmlserverConfig = rcmlserverConfig; this.mainConfig = mainConfig; } class RCMLCallback implements FutureCallback<HttpResponse> { @Override public void completed(HttpResponse t) { logger.debug("RVD notification sent"); } @Override public void failed(Exception excptn) { logger.error("RVD notification failed", excptn); } @Override public void cancelled() { logger.debug("RVD notification cancelled"); } } public void transmitNotifications(List<JsonObject> notifications, String notifierUsername, String notifierPassword) { String notificationUrl = apiUrl + "/notifications"; HttpPost request = new HttpPost(notificationUrl); String authHeader; authHeader = SecurityUtils.buildBasicAuthHeader(notifierUsername, notifierPassword); request.setHeader("Authorization", authHeader); Gson gson = new Gson(); String json = gson.toJson(notifications); request.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON)); Integer totalTimeout = rcmlserverConfig.getTimeout() + notifications.size() * rcmlserverConfig.getTimeoutPerNotification(); CloseableHttpAsyncClient httpClient = CustomHttpClientBuilder.buildCloseableHttpAsyncClient(mainConfig); if (logger.isDebugEnabled()) { logger.debug("Will transmit a set of " + notifications.size() + " " + "notifications and wait at most for " + totalTimeout); } HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(HttpClientContext.REQUEST_CONFIG, RequestConfig.custom(). setConnectTimeout(totalTimeout). setSocketTimeout(totalTimeout). setConnectionRequestTimeout(totalTimeout).build()); httpClient.execute(request, httpContext, new RCMLCallback()); } public JsonObject buildAccountStatusNotification(Account account) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("type", status2NotMap.get(account.getStatus()).toString()); jsonObject.addProperty("accountSid", account.getSid().toString()); return jsonObject; } }
6,619
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CorsFilter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/cors/CorsFilter.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.restcomm.connect.http.cors; import com.sun.jersey.spi.container.ContainerRequest; import com.sun.jersey.spi.container.ContainerResponse; import com.sun.jersey.spi.container.ContainerResponseFilter; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.restcomm.connect.commons.configuration.sets.RcmlserverConfigurationSet; import org.restcomm.connect.commons.configuration.sets.impl.RcmlserverConfigurationSetImpl; import org.restcomm.connect.commons.configuration.sources.ApacheConfigurationSource; import org.restcomm.connect.commons.configuration.sources.ConfigurationSource; import javax.servlet.ServletContext; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Context; import javax.ws.rs.ext.Provider; import java.io.File; /** * @author [email protected] - Orestis Tsakiridis */ @Provider public class CorsFilter implements ContainerResponseFilter { private final Logger logger = Logger.getLogger(CorsFilter.class); @Context private HttpServletRequest servletRequest; // we initialize this lazily upon first request since it can't be injected through the @Context annotation (it didn't work) private ServletContext lazyServletContext; String allowedOrigin; // We return Access-* headers only in case allowedOrigin is present and equals to the 'Origin' header. @Override public ContainerResponse filter(ContainerRequest cres, ContainerResponse response) { initLazily(servletRequest); String requestOrigin = cres.getHeaderValue("Origin"); if (requestOrigin != null) { // is this is a cors request (ajax request that targets a different domain than the one the page was loaded from) if (allowedOrigin != null && allowedOrigin.startsWith(requestOrigin)) { // no cors allowances make are applied if allowedOrigins == null // only return the origin the client informed response.getHttpHeaders().add("Access-Control-Allow-Origin", requestOrigin); response.getHttpHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization"); response.getHttpHeaders().add("Access-Control-Allow-Credentials", "true"); response.getHttpHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD"); response.getHttpHeaders().add("Access-Control-Max-Age", "1209600"); } } return response; } private void initLazily(ServletRequest request) { if (lazyServletContext == null) { ServletContext context = request.getServletContext(); String rootPath = context.getRealPath("/"); rootPath = StringUtils.stripEnd(rootPath,"/"); // remove trailing "/" character String restcommXmlPath = rootPath + "/WEB-INF/conf/restcomm.xml"; // ok, found restcomm.xml. Now let's get rcmlserver/base-url configuration setting File restcommXmlFile = new File(restcommXmlPath); // Create apache configuration XMLConfiguration apacheConf = new XMLConfiguration(); apacheConf.setDelimiterParsingDisabled(true); apacheConf.setAttributeSplittingDisabled(true); try { apacheConf.load(restcommXmlPath); } catch (ConfigurationException e) { e.printStackTrace(); } // Create high-level configuration ConfigurationSource source = new ApacheConfigurationSource(apacheConf); RcmlserverConfigurationSet rcmlserverConfig = new RcmlserverConfigurationSetImpl(source); // initialize allowedOrigin String baseUrl = rcmlserverConfig.getBaseUrl(); if ( baseUrl != null && (! baseUrl.trim().equals(""))) { // baseUrl is set. We need to return CORS allow headers allowedOrigin = baseUrl; } lazyServletContext = context; logger.info("Initialized (lazily) CORS servlet response filter. allowedOrigin: " + allowedOrigin); } } }
5,118
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ContextUtil.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/security/ContextUtil.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.restcomm.connect.http.security; import javax.ws.rs.core.SecurityContext; import org.restcomm.connect.identity.UserIdentityContext; public class ContextUtil { public static UserIdentityContext convert(SecurityContext sec) { AccountPrincipal principal = (AccountPrincipal)sec.getUserPrincipal(); return principal.getIdentityContext(); } }
1,187
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AccountPrincipal.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/security/AccountPrincipal.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.restcomm.connect.http.security; import java.security.Principal; import java.util.Set; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.identity.UserIdentityContext; public class AccountPrincipal implements Principal { public static final String SUPER_ADMIN_ROLE = "SuperAdmin"; public static final String ADMIN_ROLE = "Administrator"; UserIdentityContext identityContext; public AccountPrincipal(UserIdentityContext identityContext) { this.identityContext = identityContext; } public boolean isSuperAdmin() { //SuperAdmin Account is the one the is //1. Has no parent, this is the top account //2. Is ACTIVE return (identityContext.getEffectiveAccount() != null && identityContext.getEffectiveAccount().getParentSid() == null) && (identityContext.getEffectiveAccount().getStatus().equals(Account.Status.ACTIVE)); } public Set<String> getRole() { Set<String> roles = identityContext.getEffectiveAccountRoles(); if (isSuperAdmin()) { roles.add(SUPER_ADMIN_ROLE); } return roles; } @Override public String getName() { if (identityContext.getEffectiveAccount() != null) { return identityContext.getAccountKey().getAccount().getSid().toString(); } else { return null; } } public UserIdentityContext getIdentityContext() { return identityContext; } }
2,332
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RCSecContext.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/security/RCSecContext.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.restcomm.connect.http.security; import javax.ws.rs.core.SecurityContext; import java.security.Principal; public class RCSecContext implements SecurityContext{ private AccountPrincipal user; private String scheme; public RCSecContext(AccountPrincipal user, String scheme) { this.user = user; this.scheme = scheme; } @Override public Principal getUserPrincipal() {return this.user;} @Override public boolean isUserInRole(String s) { if (user.getRole() != null) { return user.getRole().contains(s); } return false; } @Override public boolean isSecure() {return "https".equals(this.scheme);} @Override public String getAuthenticationScheme() { return SecurityContext.BASIC_AUTH; } }
1,628
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
PermissionEvaluator.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/security/PermissionEvaluator.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.restcomm.connect.http.security; import org.apache.commons.lang.NotImplementedException; import org.apache.log4j.Logger; import org.apache.shiro.authz.Permission; import org.apache.shiro.authz.SimpleRole; import org.apache.shiro.authz.permission.WildcardPermissionResolver; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.AccountsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.OrganizationsDao; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.Organization; import org.restcomm.connect.dao.exceptions.AccountHierarchyDepthCrossed; import org.restcomm.connect.http.exceptions.AuthorizationException; import org.restcomm.connect.http.exceptions.InsufficientPermission; import org.restcomm.connect.http.exceptions.OperatedAccountMissing; import org.restcomm.connect.identity.AuthOutcome; import org.restcomm.connect.identity.IdentityContext; import org.restcomm.connect.identity.UserIdentityContext; import org.restcomm.connect.identity.shiro.RestcommRoles; import javax.servlet.ServletContext; import java.util.Set; import static org.restcomm.connect.http.security.AccountPrincipal.ADMIN_ROLE; /** * PermissionEvaluator. * * How to use it: * - use checkAuthenticatedAccount() method to check that a user (any user) is authenticated. * - use checkAuthenticatedAccount(permission) method to check that an authenticated user has the required permission according to his roles * - use checkAuthenticatedAccount(account,permission) method to check that besides permission a user also has ownership over an account * * @author [email protected] (Orestis Tsakiridis) */ public class PermissionEvaluator { // types of secured resources used to apply different policies to applications, numbers etc. public enum SecuredType { SECURED_APP, SECURED_ACCOUNT, SECURED_STANDARD } private Logger logger = Logger.getLogger(PermissionEvaluator.class); private AccountsDao accountsDao; private OrganizationsDao organizationsDao; private IdentityContext identityContext; private ServletContext context; public PermissionEvaluator() { } public PermissionEvaluator(ServletContext context) { this.context = context; final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName()); this.accountsDao = storage.getAccountsDao(); this.organizationsDao = storage.getOrganizationsDao(); this.identityContext = (IdentityContext) context.getAttribute(IdentityContext.class.getName()); } /** * Checks if the effective account is a super account (top level account) * @param userIdentityContext * @return */ public boolean isSuperAdmin(UserIdentityContext userIdentityContext) { //SuperAdmin Account is the one the is //1. Has no parent, this is the top account //2. Is ACTIVE return (userIdentityContext.getEffectiveAccount().getParentSid() == null) && (userIdentityContext.getEffectiveAccount().getStatus().equals(Account.Status.ACTIVE)); } /** * Checks if the operated account is a direct child of effective account * @param operatedAccount * @return */ public boolean isDirectChildOfAccount(final Account effectiveAccount, final Account operatedAccount) { return operatedAccount.getParentSid().equals(effectiveAccount.getSid()); } /** * Checks if the effective account is a super account (top level account) * * @param userIdentityContext */ public void allowOnlySuperAdmin(UserIdentityContext userIdentityContext) { if (!isSuperAdmin(userIdentityContext)) { throw new InsufficientPermission(); } } /** * Grants access by permission. If the effective account has a role that resolves * to the specified permission (accoording to mappings of restcomm.xml) access is granted. * Administrator is granted access regardless of permissions. * * @param permission - e.g. 'RestComm:Create:Accounts' * @param userIdentityContext */ public void checkPermission(final String permission, UserIdentityContext userIdentityContext) { //checkAuthenticatedAccount(); // ok there is a valid authenticated account if ( checkPermission(permission, userIdentityContext.getEffectiveAccountRoles()) != AuthOutcome.OK ) throw new InsufficientPermission(); } // boolean overloaded form of checkAuthenticatedAccount(permission) public boolean isSecuredByPermission(final String permission, UserIdentityContext userIdentityContext) { try { checkPermission(permission,userIdentityContext); return true; } catch (AuthorizationException e) { return false; } } /** * Personalized type of grant. Besides checking 'permission' the effective account should have some sort of * ownership over the operatedAccount. The exact type of ownership is defined in secureAccount() * * @param operatedAccount * @param permission * @param userIdentityContext * @throws AuthorizationException */ public void secure(final Account operatedAccount, final String permission, UserIdentityContext userIdentityContext) throws AuthorizationException { secure(operatedAccount, permission, SecuredType.SECURED_STANDARD, userIdentityContext); } /** * @param operatedAccount * @param permission * @param type * @param userIdentityContext * @throws AuthorizationException */ public void secure(final Account operatedAccount, final String permission, SecuredType type, UserIdentityContext userIdentityContext) throws AuthorizationException { checkPermission(permission,userIdentityContext); // check an authenticated account allowed to do "permission" is available checkOrganization(operatedAccount,userIdentityContext); // check if valid organization is attached with this account. if (operatedAccount == null) { // if operatedAccount is NULL, we'll probably return a 404. But let's handle that in a central place. throw new OperatedAccountMissing(); } if (type == SecuredType.SECURED_STANDARD) { if (secureLevelControl(operatedAccount, null,userIdentityContext) != AuthOutcome.OK ) throw new InsufficientPermission(); } else if (type == SecuredType.SECURED_APP) { if (secureLevelControlApplications(operatedAccount,null,userIdentityContext) != AuthOutcome.OK) throw new InsufficientPermission(); } else if (type == SecuredType.SECURED_ACCOUNT) { if (secureLevelControlAccounts(operatedAccount,userIdentityContext) != AuthOutcome.OK) throw new InsufficientPermission(); } } /** * @param account * @throws IllegalStateException */ private void checkOrganization(Account account, UserIdentityContext userIdentityContext) throws IllegalStateException { Sid organizationSid = account.getOrganizationSid(); if(organizationSid == null){ String errorMsg = "there is no organization assosiate with this account: "+account.getSid(); logger.error(errorMsg); throw new IllegalStateException(errorMsg); } Organization organization = organizationsDao.getOrganization(organizationSid); if(organization == null || organization.getDomainName() == null || organization.getDomainName().trim().isEmpty()){ String errorMsg = "Invalid or Null Organization: "+organization +" for account: "+account.getSid(); logger.error(errorMsg); throw new IllegalStateException(errorMsg); } } /** * @param operatedAccount * @param resourceAccountSid * @param type * @param userIdentityContext * @throws AuthorizationException */ public void secure(final Account operatedAccount, final Sid resourceAccountSid, SecuredType type, UserIdentityContext userIdentityContext) throws AuthorizationException { if (operatedAccount == null) { // if operatedAccount is NULL, we'll probably return a 404. But let's handle that in a central place. throw new OperatedAccountMissing(); } String resourceAccountSidString = resourceAccountSid == null ? null : resourceAccountSid.toString(); if (type == SecuredType.SECURED_APP) { if (secureLevelControlApplications(operatedAccount, resourceAccountSidString,userIdentityContext) != AuthOutcome.OK) throw new InsufficientPermission(); } else if (type == SecuredType.SECURED_STANDARD){ if (secureLevelControl(operatedAccount, resourceAccountSidString,userIdentityContext) != AuthOutcome.OK) throw new InsufficientPermission(); } else if (type == SecuredType.SECURED_ACCOUNT) throw new IllegalStateException("Account security is not supported when using sub-resources"); else { throw new NotImplementedException(); } } // protected void secure(final Account operatedAccount, final Sid resourceAccountSid, final String permission) throws AuthorizationException { // secure(operatedAccount, resourceAccountSid, permission, SecuredType.SECURED_STANDARD); // } // // protected void secure(final Account operatedAccount, final Sid resourceAccountSid, final String permission, final SecuredType type ) { // secure(operatedAccount, resourceAccountSid, type); // checkPermission(permission); // check an authbenticated account allowed to do "permission" is available // } /** * Checks is the effective account has the specified role. Only role values contained in the Restcomm Account * are take into account. * * @param role * @return true if the role exists in the Account. Otherwise it returns false. */ public boolean hasAccountRole(final String role,UserIdentityContext userIdentityContext) { if (userIdentityContext.getEffectiveAccount() != null) { return userIdentityContext.getEffectiveAccountRoles().contains(role); } return false; } /** * Low level permission checking. roleNames are checked for neededPermissionString permission using permission * mappings contained in restcomm.xml. The permission mappings are stored in RestcommRoles. * * Note: Administrator is granted access with eyes closed * @param neededPermissionString * @param roleNames * @return */ private AuthOutcome checkPermission(String neededPermissionString, Set<String> roleNames) { // if this is an administrator ask no more questions if ( roleNames.contains(getAdministratorRole())) return AuthOutcome.OK; // normalize the permission string //neededPermissionString = "domain:" + neededPermissionString; WildcardPermissionResolver resolver = new WildcardPermissionResolver(); Permission neededPermission = resolver.resolvePermission(neededPermissionString); // check the neededPermission against all roles of the user RestcommRoles restcommRoles = identityContext.getRestcommRoles(); for (String roleName: roleNames) { SimpleRole simpleRole = restcommRoles.getRole(roleName); if ( simpleRole == null) { return AuthOutcome.FAILED; } else { Set<Permission> permissions = simpleRole.getPermissions(); // check the permissions one by one for (Permission permission: permissions) { if (permission.implies(neededPermission)) { if (logger.isDebugEnabled()) { logger.debug("Granted access by permission " + permission.toString()); } return AuthOutcome.OK; } } if (logger.isDebugEnabled()) { logger.debug("Role " + roleName + " does not allow " + neededPermissionString); } } } return AuthOutcome.FAILED; } /** * Applies the following access control rule: * If no sub-resources are involved (resourceAccountSid is null): * - If operatingAccount is the same or an ancestor of operatedAccount, access is granted * If there are sub-resources involved: * - If operatingAccount is the same or an ancestor of operatedAccount AND resource belongs to operatedAccount access is granted * @param operatedAccount the account specified in the URL * @param resourceAccountSid the account SID property of the operated resource e.g. the accountSid of a DID. * */ private AuthOutcome secureLevelControl(Account operatedAccount, String resourceAccountSid, UserIdentityContext userIdentityContext) { Account operatingAccount = userIdentityContext.getEffectiveAccount(); String operatingAccountSid = null; if (operatingAccount != null) operatingAccountSid = operatingAccount.getSid().toString(); String operatedAccountSid = null; if (operatedAccount != null) operatedAccountSid = operatedAccount.getSid().toString(); // in case we're dealing with resources, we first make sure that they are accessed under their owner account. if (resourceAccountSid != null) if (! resourceAccountSid.equals(operatedAccountSid)) return AuthOutcome.FAILED; // check parent/ancestor relationship between operatingAccount and operatedAccount if ( operatingAccountSid.equals(operatedAccountSid) ) return AuthOutcome.OK; if ( operatedAccount.getParentSid() != null ) { if (operatedAccount.getParentSid().toString().equals(operatingAccountSid)) return AuthOutcome.OK; else if (accountsDao.getAccountLineage(operatedAccount).contains(operatingAccountSid)) return AuthOutcome.OK; } return AuthOutcome.FAILED; } /** * Uses the security policy applied by secureLevelControl(). See there for details. * * DEPRECATED security policy: * * Applies the following access control rules * * If an application Account Sid is given: * - If operatingAccount is the same as the operated account and application resource belongs to operated account too * acces is granted. * If no application Account Sid is given: * - If operatingAccount is the same as the operated account access is granted. * * NOTE: Parent/ancestor relationships on accounts do not grant access here. * * @param operatedAccount * @param applicationAccountSid * @return */ private AuthOutcome secureLevelControlApplications(Account operatedAccount, String applicationAccountSid, UserIdentityContext userIdentityContext) { /* // disabled strict policy that prevented access to sub-account applications // operatingAccount and operatedAccount are not null at this point Account operatingAccount = userIdentityContext.getEffectiveAccount(); String operatingAccountSid = operatingAccount.getSid().toString(); String operatedAccountSid = operatedAccount.getSid().toString(); if (!operatingAccountSid.equals(String.valueOf(operatedAccountSid))) { return AuthOutcome.FAILED; } else if (applicationAccountSid != null && !operatingAccountSid.equals(applicationAccountSid)) { return AuthOutcome.FAILED; } return AuthOutcome.OK; */ // use the more liberal default policy that applies to other entities for applications too return secureLevelControl(operatedAccount, applicationAccountSid, userIdentityContext); } /** Applies the following access control rules: * * If the operating account is an administrator: * - If it is the same or parent/ancestor of the operated account access is granted. * If the operating accoutn is NOT an administrator: * - If it is the same as the operated account access is granted. * * @param operatedAccount * @return */ private AuthOutcome secureLevelControlAccounts(Account operatedAccount, UserIdentityContext userIdentityContext) throws AccountHierarchyDepthCrossed { // operatingAccount and operatedAccount are not null Account operatingAccount = userIdentityContext.getEffectiveAccount(); String operatingAccountSid = operatingAccount.getSid().toString(); String operatedAccountSid = operatedAccount.getSid().toString(); if (getAdministratorRole().equals(operatingAccount.getRole())) { // administrator can also operate on themselves, direct children, grand-children if (operatingAccountSid.equals(operatedAccountSid)) return AuthOutcome.OK; if (operatedAccount.getParentSid() != null ) { if (operatedAccount.getParentSid().toString().equals(operatingAccountSid )) return AuthOutcome.OK; else if (accountsDao.getAccountLineage(operatedAccount).contains(operatingAccountSid)) return AuthOutcome.OK; } return AuthOutcome.FAILED; } else { // non-administrators can only operate directly on themselves if ( operatingAccountSid.equals(operatedAccountSid) ) return AuthOutcome.OK; else return AuthOutcome.FAILED; } } /** * Returns the string literal for the administrator role. This role is granted implicitly access from checkAuthenticatedAccount() method. * No need to explicitly apply it at each protected resource * . * @return the administrator role as string */ public String getAdministratorRole() { return ADMIN_ROLE; } }
19,251
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SecurityFilter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/security/SecurityFilter.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.restcomm.connect.http.security; import com.sun.jersey.spi.container.ContainerRequest; import com.sun.jersey.spi.container.ContainerRequestFilter; import org.apache.log4j.Logger; import org.restcomm.connect.dao.AccountsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.Organization; import org.restcomm.connect.identity.UserIdentityContext; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.Provider; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; import static javax.ws.rs.core.Response.status; @Provider public class SecurityFilter implements ContainerRequestFilter { private final Logger logger = Logger.getLogger(SecurityFilter.class); private static final String PATTERN_FOR_RECORDING_FILE_PATH = ".*Accounts/.*/Recordings/RE.*[.mp4|.wav]"; private static final String PATTERN_FOR_LOGOUT_PATH = ".*Logout$"; private static final Set<Pattern> UNPROTECTED_PATHS = new HashSet(); static { UNPROTECTED_PATHS.add(Pattern.compile(PATTERN_FOR_RECORDING_FILE_PATH)); UNPROTECTED_PATHS.add(Pattern.compile(PATTERN_FOR_LOGOUT_PATH)); } @Context private HttpServletRequest servletRequest; // We return Access-* headers only in case allowedOrigin is present and equals to the 'Origin' header. @Override public ContainerRequest filter(ContainerRequest cr) { final DaoManager storage = (DaoManager) servletRequest.getServletContext().getAttribute(DaoManager.class.getName()); AccountsDao accountsDao = storage.getAccountsDao(); UserIdentityContext userIdentityContext = new UserIdentityContext(servletRequest, accountsDao); // exclude recording file https://telestax.atlassian.net/browse/RESTCOMM-1736 logger.info("cr.getPath(): " + cr.getPath()); if (!isUnprotected(cr)) { checkAuthenticatedAccount(userIdentityContext); filterClosedAccounts(userIdentityContext, cr.getPath()); //TODO temporarely disable organization domain validation - https://telestax.atlassian.net/browse/BS-408 // validateOrganizationAccess(userIdentityContext, storage, cr); } String scheme = cr.getAuthenticationScheme(); AccountPrincipal aPrincipal = new AccountPrincipal(userIdentityContext); cr.setSecurityContext(new RCSecContext(aPrincipal, scheme)); return cr; } private boolean isUnprotected(ContainerRequest cr) { boolean unprotected = false; for (Pattern pAux : UNPROTECTED_PATHS) { if (pAux.matcher(cr.getPath()).matches()) { unprotected = true; break; } } return unprotected; } /** * Grants general purpose access if any valid token exists in the request */ protected void checkAuthenticatedAccount(UserIdentityContext userIdentityContext) { if (userIdentityContext.getEffectiveAccount() == null) { throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic realm=\"Restcomm realm\"").build()); } } /** * filter out accounts that are not active * * @param userIdentityContext */ protected void filterClosedAccounts(UserIdentityContext userIdentityContext, String path) { if (userIdentityContext.getEffectiveAccount() != null && !userIdentityContext.getEffectiveAccount().getStatus().equals(Account.Status.ACTIVE)) { if (userIdentityContext.getEffectiveAccount().getStatus().equals(Account.Status.UNINITIALIZED) && path.startsWith("Accounts")) { return; } throw new WebApplicationException(status(Status.FORBIDDEN).entity("Provided Account is not active").build()); } } protected void validateOrganizationAccess(UserIdentityContext userIdentityContext, DaoManager daoManager, ContainerRequest cr) { Organization effectiveAccountOrg = daoManager.getOrganizationsDao().getOrganization(userIdentityContext.getEffectiveAccount().getOrganizationSid()); Organization requestOrg = daoManager.getOrganizationsDao().getOrganizationByDomainName(cr.getBaseUri().getHost()); //Organization SID discovered from the request host should match // Organization SID from the effective Account if (!requestOrg.getSid().equals(effectiveAccountOrg.getSid())) { throw new WebApplicationException(status(Status.FORBIDDEN).entity("Account is not allowed to access requested organization").build()); } return; } }
5,671
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ConferenceParticipantConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/ConferenceParticipantConverter.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.restcomm.connect.http.converter; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.entities.CallDetailRecord; import java.lang.reflect.Type; /** * @author [email protected] (Maria Farooq) */ @ThreadSafe public final class ConferenceParticipantConverter extends AbstractConverter implements JsonSerializer<CallDetailRecord> { private final String apiVersion; public ConferenceParticipantConverter(final Configuration configuration) { super(configuration); apiVersion = configuration.getString("api-version"); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return CallDetailRecord.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final CallDetailRecord cdr = (CallDetailRecord) object; writer.startNode("Call"); writeSid(cdr.getSid(), writer); writeConferenceSid(cdr.getConferenceSid(), writer); writeDateCreated(cdr.getDateCreated(), writer); writeDateUpdated(cdr.getDateUpdated(), writer); writeAccountSid(cdr.getAccountSid(), writer); writeMuted(cdr.isMuted(), writer); writeHold(cdr.isOnHold(), writer); writeStartConferenceOnEnter(cdr.isStartConferenceOnEnter(), writer); writeEndConferenceOnEnter(cdr.isEndConferenceOnExit(), writer); writeUri(cdr.getUri(), writer); writer.endNode(); } private String prefix(final CallDetailRecord cdr) { final StringBuilder buffer = new StringBuilder(); buffer.append("/").append(apiVersion).append("/Accounts/"); buffer.append(cdr.getAccountSid().toString()).append("/Calls/"); buffer.append(cdr.getSid()); return buffer.toString(); } @Override public JsonElement serialize(final CallDetailRecord cdr, Type type, final JsonSerializationContext context) { final JsonObject object = new JsonObject(); writeSid(cdr.getSid(), object); writeConferenceSid(cdr.getParentCallSid(), object); writeDateCreated(cdr.getDateCreated(), object); writeDateUpdated(cdr.getDateUpdated(), object); writeAccountSid(cdr.getAccountSid(), object); writeMuted(cdr.isMuted(), object); writeHold(cdr.isOnHold(), object); writeStartConferenceOnEnter(cdr.isStartConferenceOnEnter(), object); writeEndConferenceOnEnter(cdr.isEndConferenceOnExit(), object); writeUri(cdr.getUri(), object); return object; } private void writeMuted(final Boolean muted, final HierarchicalStreamWriter writer) { writer.startNode("Muted"); if (muted != null) { writer.setValue(muted.toString()); } writer.endNode(); } private void writeMuted(final Boolean muted, final JsonObject object) { object.addProperty("muted", muted); } private void writeHold(final Boolean hold, final HierarchicalStreamWriter writer) { writer.startNode("Hold"); if (hold != null) { writer.setValue(hold.toString()); } writer.endNode(); } private void writeHold(final Boolean hold, final JsonObject object) { object.addProperty("hold", hold); } private void writeStartConferenceOnEnter(final Boolean startConferenceOnEnter, final HierarchicalStreamWriter writer) { writer.startNode("StartConferenceOnEnter"); if (startConferenceOnEnter != null) { writer.setValue(startConferenceOnEnter.toString()); } writer.endNode(); } private void writeStartConferenceOnEnter(final Boolean startConferenceOnEnter, final JsonObject object) { object.addProperty("start_conference_on_enter", startConferenceOnEnter); } private void writeEndConferenceOnEnter(final Boolean endConferenceOnEnter, final HierarchicalStreamWriter writer) { writer.startNode("EndConferenceOnEnter"); if (endConferenceOnEnter != null) { writer.setValue(endConferenceOnEnter.toString()); } writer.endNode(); } private void writeEndConferenceOnEnter(final Boolean endConferenceOnEnter, final JsonObject object) { object.addProperty("end_conference_on_enter", endConferenceOnEnter); } private void writeConferenceSid(final Sid sid, final HierarchicalStreamWriter writer) { writer.startNode("ConferenceSid"); if (sid != null) { writer.setValue(sid.toString()); } writer.endNode(); } private void writeConferenceSid(final Sid sid, final JsonObject object) { if (sid != null) { object.addProperty("conference_sid", sid.toString()); } } }
6,070
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
NotificationListConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/NotificationListConverter.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.restcomm.connect.http.converter; import com.google.gson.JsonArray; import java.lang.reflect.Type; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.dao.entities.Notification; import org.restcomm.connect.dao.entities.NotificationList; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class NotificationListConverter extends AbstractConverter implements JsonSerializer<NotificationList> { Integer page, pageSize, total; String pathUri; public NotificationListConverter(final Configuration configuration) { super(configuration); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return NotificationList.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final NotificationList list = (NotificationList) object; writer.startNode("Notifications"); for (final Notification notification : list.getNotifications()) { context.convertAnother(notification); } writer.endNode(); } @Override public JsonObject serialize(NotificationList ntfList, Type type, JsonSerializationContext context) { JsonObject result = new JsonObject(); JsonArray array = new JsonArray(); for (Notification cdr : ntfList.getNotifications()) { array.add(context.serialize(cdr)); } if (total != null && pageSize != null && page != null) { result.addProperty("page", page); result.addProperty("num_pages", getTotalPages()); result.addProperty("page_size", pageSize); result.addProperty("total", total); result.addProperty("start", getFirstIndex()); result.addProperty("end", getLastIndex(ntfList)); result.addProperty("uri", pathUri); result.addProperty("first_page_uri", getFirstPageUri()); result.addProperty("previous_page_uri", getPreviousPageUri()); result.addProperty("next_page_uri", getNextPageUri(ntfList)); result.addProperty("last_page_uri", getLastPageUri()); } result.add("notifications", array); return result; } private int getTotalPages() { return total / pageSize; } private String getFirstIndex() { return String.valueOf(page * pageSize); } private String getLastIndex(NotificationList list) { return String.valueOf((page == getTotalPages()) ? (page * pageSize) + list.getNotifications().size() : (pageSize - 1) + (page * pageSize)); } private String getFirstPageUri() { return pathUri + "?Page=0&PageSize=" + pageSize; } private String getPreviousPageUri() { return ((page == 0) ? "null" : pathUri + "?Page=" + (page - 1) + "&PageSize=" + pageSize); } private String getNextPageUri(NotificationList list) { String lastSid = (page == getTotalPages()) ? "null" : list.getNotifications().get(pageSize - 1).getSid().toString(); return (page == getTotalPages()) ? "null" : pathUri + "?Page=" + (page + 1) + "&PageSize=" + pageSize + "&AfterSid=" + lastSid; } private String getLastPageUri() { return pathUri + "?Page=" + getTotalPages() + "&PageSize=" + pageSize; } public void setPage(Integer page) { this.page = page; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public void setCount(Integer count) { this.total = count; } public void setPathUri(String pathUri) { this.pathUri = pathUri; } }
4,921
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TranscriptionListConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/TranscriptionListConverter.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.restcomm.connect.http.converter; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.dao.entities.Transcription; import org.restcomm.connect.dao.entities.TranscriptionList; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import java.lang.reflect.Type; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class TranscriptionListConverter extends AbstractConverter implements JsonSerializer<TranscriptionList> { Integer page, pageSize, total; String pathUri; public TranscriptionListConverter(final Configuration configuration) { super(configuration); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return TranscriptionList.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final TranscriptionList list = (TranscriptionList) object; writer.startNode("Transcriptions"); for (final Transcription transcription : list.getTranscriptions()) { context.convertAnother(transcription); } writer.endNode(); } @Override public JsonObject serialize(TranscriptionList transList, Type type, JsonSerializationContext context) { JsonObject result = new JsonObject(); JsonArray array = new JsonArray(); for (Transcription cdr : transList.getTranscriptions()) { array.add(context.serialize(cdr)); } if (total != null && pageSize != null && page != null) { result.addProperty("page", page); result.addProperty("num_pages", getTotalPages()); result.addProperty("page_size", pageSize); result.addProperty("total", total); result.addProperty("start", getFirstIndex()); result.addProperty("end", getLastIndex(transList)); result.addProperty("uri", pathUri); result.addProperty("first_page_uri", getFirstPageUri()); result.addProperty("previous_page_uri", getPreviousPageUri()); result.addProperty("next_page_uri", getNextPageUri(transList)); result.addProperty("last_page_uri", getLastPageUri()); } result.add("transcriptions", array); return result; } private int getTotalPages() { return total / pageSize; } private String getFirstIndex() { return String.valueOf(page * pageSize); } private String getLastIndex(TranscriptionList list) { return String.valueOf((page == getTotalPages()) ? (page * pageSize) + list.getTranscriptions().size() : (pageSize - 1) + (page * pageSize)); } private String getFirstPageUri() { return pathUri + "?Page=0&PageSize=" + pageSize; } private String getPreviousPageUri() { return ((page == 0) ? "null" : pathUri + "?Page=" + (page - 1) + "&PageSize=" + pageSize); } private String getNextPageUri(TranscriptionList list) { String lastSid = (page == getTotalPages()) ? "null" : list.getTranscriptions().get(pageSize - 1).getSid().toString(); return (page == getTotalPages()) ? "null" : pathUri + "?Page=" + (page + 1) + "&PageSize=" + pageSize + "&AfterSid=" + lastSid; } private String getLastPageUri() { return pathUri + "?Page=" + getTotalPages() + "&PageSize=" + pageSize; } public void setPage(Integer page) { this.page = page; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public void setCount(Integer count) { this.total = count; } public void setPathUri(String pathUri) { this.pathUri = pathUri; } }
4,949
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
OutgoingCallerIdListConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/OutgoingCallerIdListConverter.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.restcomm.connect.http.converter; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.dao.entities.OutgoingCallerId; import org.restcomm.connect.dao.entities.OutgoingCallerIdList; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class OutgoingCallerIdListConverter extends AbstractConverter { public OutgoingCallerIdListConverter(final Configuration configuration) { super(configuration); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return OutgoingCallerIdList.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final OutgoingCallerIdList list = (OutgoingCallerIdList) object; writer.startNode("OutgoingCallerIds"); for (final OutgoingCallerId outgoingCallerId : list.getOutgoingCallerIds()) { context.convertAnother(outgoingCallerId); } writer.endNode(); } }
2,100
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ShortCodeConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/ShortCodeConverter.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.restcomm.connect.http.converter; import java.lang.reflect.Type; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.dao.entities.ShortCode; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class ShortCodeConverter extends AbstractConverter implements JsonSerializer<ShortCode> { public ShortCodeConverter(final Configuration configuration) { super(configuration); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return ShortCode.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final ShortCode shortCode = (ShortCode) object; writer.startNode("ShortCode"); writeSid(shortCode.getSid(), writer); writeDateCreated(shortCode.getDateCreated(), writer); writeDateUpdated(shortCode.getDateUpdated(), writer); writeFriendlyName(shortCode.getFriendlyName(), writer); writeAccountSid(shortCode.getAccountSid(), writer); writeShortCode(Integer.toString(shortCode.getShortCode()), writer); writeApiVersion(shortCode.getApiVersion(), writer); writeSmsUrl(shortCode.getSmsUrl(), writer); writeSmsMethod(shortCode.getSmsMethod(), writer); writeSmsFallbackUrl(shortCode.getSmsFallbackUrl(), writer); writeSmsFallbackMethod(shortCode.getSmsFallbackMethod(), writer); writeUri(shortCode.getUri(), writer); writer.endNode(); } @Override public JsonElement serialize(final ShortCode shortCode, final Type type, final JsonSerializationContext context) { final JsonObject object = new JsonObject(); writeSid(shortCode.getSid(), object); writeDateCreated(shortCode.getDateCreated(), object); writeDateUpdated(shortCode.getDateUpdated(), object); writeFriendlyName(shortCode.getFriendlyName(), object); writeAccountSid(shortCode.getAccountSid(), object); writeShortCode(Integer.toString(shortCode.getShortCode()), object); writeApiVersion(shortCode.getApiVersion(), object); writeSmsUrl(shortCode.getSmsUrl(), object); writeSmsMethod(shortCode.getSmsMethod(), object); writeSmsFallbackUrl(shortCode.getSmsFallbackUrl(), object); writeSmsFallbackMethod(shortCode.getSmsFallbackMethod(), object); writeUri(shortCode.getUri(), object); return object; } private void writeShortCode(final String shortCode, final HierarchicalStreamWriter writer) { writer.startNode("ShortCode"); writer.setValue(shortCode); writer.endNode(); } private void writeShortCode(final String shortCode, final JsonObject object) { object.addProperty("short_code", shortCode); } }
4,069
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AnnouncementConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/AnnouncementConverter.java
package org.restcomm.connect.http.converter; import java.lang.reflect.Type; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.dao.entities.Announcement; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * @author <a href="mailto:[email protected]">George Vagenas</a> */ @ThreadSafe public final class AnnouncementConverter extends AbstractConverter implements JsonSerializer<Announcement> { public AnnouncementConverter(final Configuration configuration) { super(configuration); } @Override public JsonElement serialize(final Announcement announcement, Type type, final JsonSerializationContext context) { final JsonObject object = new JsonObject(); writeSid(announcement.getSid(), object); writeDateCreated(announcement.getDateCreated(), object); writeAccountSid(announcement.getAccountSid(), object); writeGender(announcement.getGender(), object); writeLanguage(announcement.getLanguage(), object); writeText(announcement.getText(), object); if(announcement.getUri() != null) writeUri(announcement.getUri(), object); return object; } @Override public void marshal(Object object, HierarchicalStreamWriter writer, MarshallingContext context) { final Announcement announcement = (Announcement) object; writer.startNode("Announcement"); writeSid(announcement.getSid(), writer); writeDateCreated(announcement.getDateCreated(), writer); writeAccountSid(announcement.getAccountSid(), writer); writeGender(announcement.getGender(), writer); writeLanguage(announcement.getLanguage(), writer); writeText(announcement.getText(), writer); writeUri(announcement.getUri(), writer); writer.endNode(); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(Class klass) { return Announcement.class.equals(klass); } private void writeText(final String text, final JsonObject object) { object.addProperty("text", text); } private void writeLanguage(final String language, final JsonObject object) { object.addProperty("language", language); } private void writeGender(final String gender, final JsonObject object) { object.addProperty("gender", gender); } private void writeText(String text, HierarchicalStreamWriter writer) { writer.startNode("Text"); if (text != null) { writer.setValue(text); } writer.endNode(); } private void writeLanguage(String language, HierarchicalStreamWriter writer) { writer.startNode("Language"); if (language != null) { writer.setValue(language); } writer.endNode(); } private void writeGender(String gender, HierarchicalStreamWriter writer) { writer.startNode("Gender"); if (gender != null) { writer.setValue(gender); } writer.endNode(); } }
3,363
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
IncomingPhoneNumberConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/IncomingPhoneNumberConverter.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.restcomm.connect.http.converter; import java.lang.reflect.Type; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.dao.entities.IncomingPhoneNumber; import org.restcomm.connect.commons.dao.Sid; import com.google.gson.JsonElement; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class IncomingPhoneNumberConverter extends AbstractConverter implements JsonSerializer<IncomingPhoneNumber> { public IncomingPhoneNumberConverter(final Configuration configuration) { super(configuration); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return IncomingPhoneNumber.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final IncomingPhoneNumber incomingPhoneNumber = (IncomingPhoneNumber) object; writer.startNode("IncomingPhoneNumber"); writeSid(incomingPhoneNumber.getSid(), writer); writeAccountSid(incomingPhoneNumber.getAccountSid(), writer); writeFriendlyName(incomingPhoneNumber.getFriendlyName(), writer); writePhoneNumber(incomingPhoneNumber.getPhoneNumber(), writer); writeVoiceUrl(incomingPhoneNumber.getVoiceUrl(), writer); writeVoiceMethod(incomingPhoneNumber.getVoiceMethod(), writer); writeVoiceFallbackUrl(incomingPhoneNumber.getVoiceFallbackUrl(), writer); writeVoiceFallbackMethod(incomingPhoneNumber.getVoiceFallbackMethod(), writer); writeStatusCallback(incomingPhoneNumber.getStatusCallback(), writer); writeStatusCallbackMethod(incomingPhoneNumber.getStatusCallbackMethod(), writer); writeVoiceCallerIdLookup(incomingPhoneNumber.hasVoiceCallerIdLookup(), writer); writeVoiceApplicationSid(incomingPhoneNumber.getVoiceApplicationSid(), writer); if (incomingPhoneNumber.getVoiceApplicationSid() != null) writeVoiceApplicationName(incomingPhoneNumber.getVoiceApplicationName(), writer); writeDateCreated(incomingPhoneNumber.getDateCreated(), writer); writeDateUpdated(incomingPhoneNumber.getDateUpdated(), writer); writeSmsUrl(incomingPhoneNumber.getSmsUrl(), writer); writeSmsMethod(incomingPhoneNumber.getSmsMethod(), writer); writeSmsFallbackUrl(incomingPhoneNumber.getSmsFallbackUrl(), writer); writeSmsFallbackMethod(incomingPhoneNumber.getSmsFallbackMethod(), writer); writeSmsApplicationSid(incomingPhoneNumber.getSmsApplicationSid(), writer); if (incomingPhoneNumber.getSmsApplicationSid() != null) writeSmsApplicationName(incomingPhoneNumber.getSmsApplicationName(), writer); writeUssdUrl(incomingPhoneNumber.getUssdUrl(), writer); writeUssdMethod(incomingPhoneNumber.getUssdMethod(), writer); writeUssdFallbackUrl(incomingPhoneNumber.getUssdFallbackUrl(), writer); writeUssdFallbackMethod(incomingPhoneNumber.getUssdFallbackMethod(), writer); writeUssdApplicationSid(incomingPhoneNumber.getUssdApplicationSid(), writer); if (incomingPhoneNumber.getUssdApplicationSid() != null) writeUssdApplicationName(incomingPhoneNumber.getUssdApplicationName(), writer); writeReferUrl(incomingPhoneNumber.getReferUrl(), writer); writeReferMethod(incomingPhoneNumber.getReferMethod(), writer); writeReferApplicationSid(incomingPhoneNumber.getReferApplicationSid(), writer); if (incomingPhoneNumber.getReferApplicationSid() != null) writeReferApplicationName(incomingPhoneNumber.getReferApplicationName(), writer); writeCapabilities(incomingPhoneNumber.isVoiceCapable(), incomingPhoneNumber.isSmsCapable(), incomingPhoneNumber.isMmsCapable(), incomingPhoneNumber.isFaxCapable(), writer); writeApiVersion(incomingPhoneNumber.getApiVersion(), writer); writeUri(incomingPhoneNumber.getUri(), writer); writer.endNode(); } @Override public JsonElement serialize(final IncomingPhoneNumber incomingPhoneNumber, final Type type, final JsonSerializationContext context) { final JsonObject object = new JsonObject(); writeSid(incomingPhoneNumber.getSid(), object); writeAccountSid(incomingPhoneNumber.getAccountSid(), object); writeFriendlyName(incomingPhoneNumber.getFriendlyName(), object); writePhoneNumber(incomingPhoneNumber.getPhoneNumber(), object); writeVoiceUrl(incomingPhoneNumber.getVoiceUrl(), object); writeVoiceMethod(incomingPhoneNumber.getVoiceMethod(), object); writeVoiceFallbackUrl(incomingPhoneNumber.getVoiceFallbackUrl(), object); writeVoiceFallbackMethod(incomingPhoneNumber.getVoiceFallbackMethod(), object); writeStatusCallback(incomingPhoneNumber.getStatusCallback(), object); writeStatusCallbackMethod(incomingPhoneNumber.getStatusCallbackMethod(), object); writeVoiceCallerIdLookup(incomingPhoneNumber.hasVoiceCallerIdLookup(), object); writeVoiceApplicationSid(incomingPhoneNumber.getVoiceApplicationSid(), object); if (incomingPhoneNumber.getVoiceApplicationSid() != null) writeVoiceApplicationName(incomingPhoneNumber.getVoiceApplicationName(), object); writeDateCreated(incomingPhoneNumber.getDateCreated(), object); writeDateUpdated(incomingPhoneNumber.getDateUpdated(), object); writeSmsUrl(incomingPhoneNumber.getSmsUrl(), object); writeSmsMethod(incomingPhoneNumber.getSmsMethod(), object); writeSmsFallbackUrl(incomingPhoneNumber.getSmsFallbackUrl(), object); writeSmsFallbackMethod(incomingPhoneNumber.getSmsFallbackMethod(), object); writeSmsApplicationSid(incomingPhoneNumber.getSmsApplicationSid(), object); if (incomingPhoneNumber.getSmsApplicationSid() != null) writeSmsApplicationName(incomingPhoneNumber.getSmsApplicationName(), object); writeUssdUrl(incomingPhoneNumber.getUssdUrl(), object); writeUssdMethod(incomingPhoneNumber.getUssdMethod(), object); writeUssdFallbackUrl(incomingPhoneNumber.getUssdFallbackUrl(), object); writeUssdFallbackMethod(incomingPhoneNumber.getUssdFallbackMethod(), object); writeUssdApplicationSid(incomingPhoneNumber.getUssdApplicationSid(), object); if (incomingPhoneNumber.getUssdApplicationSid() != null) writeUssdApplicationName(incomingPhoneNumber.getUssdApplicationName(), object); writeReferUrl(incomingPhoneNumber.getReferUrl(), object); writeReferMethod(incomingPhoneNumber.getReferMethod(), object); writeReferApplicationSid(incomingPhoneNumber.getReferApplicationSid(), object); if (incomingPhoneNumber.getReferApplicationSid() != null) writeReferApplicationName(incomingPhoneNumber.getReferApplicationName(), object); writeCapabilities(incomingPhoneNumber.isVoiceCapable(), incomingPhoneNumber.isSmsCapable(), incomingPhoneNumber.isMmsCapable(), incomingPhoneNumber.isFaxCapable(), object); writeApiVersion(incomingPhoneNumber.getApiVersion(), object); writeUri(incomingPhoneNumber.getUri(), object); return object; } private void writeSmsApplicationSid(final Sid smsApplicationSid, final HierarchicalStreamWriter writer) { if (smsApplicationSid != null) { writer.startNode("SmsApplicationSid"); writer.setValue(smsApplicationSid.toString()); writer.endNode(); } } private void writeSmsApplicationSid(final Sid smsApplicationSid, final JsonObject object) { if (smsApplicationSid != null) { object.addProperty("sms_application_sid", smsApplicationSid.toString()); } else { object.add("sms_application_sid", JsonNull.INSTANCE); } } private void writeUssdApplicationSid(final Sid ussdApplicationSid, final HierarchicalStreamWriter writer) { if (ussdApplicationSid != null) { writer.startNode("UssdApplicationSid"); writer.setValue(ussdApplicationSid.toString()); writer.endNode(); } } private void writeUssdApplicationSid(final Sid ussdApplicationSid, final JsonObject object) { if (ussdApplicationSid != null) { object.addProperty("ussd_application_sid", ussdApplicationSid.toString()); } else { object.add("ussd_application_sid", JsonNull.INSTANCE); } } private void writeReferApplicationSid(final Sid referApplicationSid, final JsonObject object) { if (referApplicationSid != null) { object.addProperty("refer_application_sid", referApplicationSid.toString()); } else { object.add("refer_application_sid", JsonNull.INSTANCE); } } private void writeReferApplicationSid(final Sid referApplicationSid, final HierarchicalStreamWriter writer) { if (referApplicationSid != null) { writer.startNode("ReferApplicationSid"); writer.setValue(referApplicationSid.toString()); writer.endNode(); } } private void writeVoiceApplicationName(final String voiceApplicationName, final JsonObject object) { if (voiceApplicationName != null) object.addProperty("voice_application_name", voiceApplicationName); else object.add("voice_application_name", JsonNull.INSTANCE); } private void writeVoiceApplicationName(final String voiceApplicationName, final HierarchicalStreamWriter writer) { writer.startNode("VoiceApplicationName"); writer.setValue(voiceApplicationName); writer.endNode(); } private void writeSmsApplicationName(final String smsApplicationName, final JsonObject object) { if (smsApplicationName != null) object.addProperty("sms_application_name", smsApplicationName); else object.add("sms_application_name", JsonNull.INSTANCE); } private void writeSmsApplicationName(final String smsApplicationName, final HierarchicalStreamWriter writer) { writer.startNode("SmsApplicationName"); writer.setValue(smsApplicationName); writer.endNode(); } private void writeUssdApplicationName(final String ussdApplicationName, final JsonObject object) { if (ussdApplicationName != null) object.addProperty("ussd_application_name", ussdApplicationName); else object.add("ussd_application_name", JsonNull.INSTANCE); } private void writeUssdApplicationName(final String ussdApplicationName, final HierarchicalStreamWriter writer) { writer.startNode("UssdApplicationName"); writer.setValue(ussdApplicationName); writer.endNode(); } private void writeReferApplicationName(final String referApplicationName, final JsonObject object) { if (referApplicationName != null) object.addProperty("refer_application_name", referApplicationName); else object.add("refer_application_name", JsonNull.INSTANCE); } private void writeReferApplicationName(final String referApplicationName, final HierarchicalStreamWriter writer) { writer.startNode("ReferApplicationName"); writer.setValue(referApplicationName); writer.endNode(); } }
12,606
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AccountListConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/AccountListConverter.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.restcomm.connect.http.converter; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.AccountList; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * @author [email protected] (Thomas Quintana) */ public final class AccountListConverter extends AbstractConverter { public AccountListConverter(final Configuration configuration) { super(configuration); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return AccountList.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final AccountList list = (AccountList) object; writer.startNode("Accounts"); for (final Account account : list.getAccounts()) { context.convertAnother(account); } writer.endNode(); } }
1,908
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AvailableCountriesConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/AvailableCountriesConverter.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.restcomm.connect.http.converter; import org.apache.commons.configuration.Configuration; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * @author [email protected] */ public final class AvailableCountriesConverter extends AbstractConverter { public AvailableCountriesConverter(final Configuration configuration) { super(configuration); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return AvailableCountriesList.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final AvailableCountriesList list = (AvailableCountriesList) object; writer.startNode("AvailableCountries"); for (final String countryCode : list.getAvailableCountries()) { writer.startNode("AvailableCountry"); context.convertAnother(countryCode); writer.endNode(); } writer.endNode(); } }
1,941
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ApplicationNumberSummaryConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/ApplicationNumberSummaryConverter.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.restcomm.connect.http.converter; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import org.restcomm.connect.dao.entities.ApplicationNumberSummary; /** * @author [email protected] - Orestis Tsakiridis */ public class ApplicationNumberSummaryConverter implements Converter { @Override public void marshal(Object o, HierarchicalStreamWriter writer, MarshallingContext marshallingContext) { ApplicationNumberSummary number = (ApplicationNumberSummary) o; if (number.getSid() != null ) { writer.startNode("Sid"); writer.setValue(number.getSid()); writer.endNode(); } if (number.getFriendlyName() != null) { writer.startNode("FriendlyName"); writer.setValue(number.getFriendlyName()); writer.endNode(); } if (number.getPhoneNumber() != null) { writer.startNode("PhoneNumber"); writer.setValue(number.getPhoneNumber()); writer.endNode(); } if (number.getVoiceApplicationSid() != null) { writer.startNode("VoiceApplicationSid"); writer.setValue(number.getVoiceApplicationSid()); writer.endNode(); } if (number.getSmsApplicationSid() != null) { writer.startNode("SmsApplicationSid"); writer.setValue(number.getSmsApplicationSid()); writer.endNode(); } if (number.getUssdApplicationSid() != null) { writer.startNode("UssdApplicationSid"); writer.setValue(number.getUssdApplicationSid()); writer.endNode(); } } @Override public Object unmarshal(HierarchicalStreamReader hierarchicalStreamReader, UnmarshallingContext unmarshallingContext) { return null; } @Override public boolean canConvert(Class aClass) { return ApplicationNumberSummary.class.equals(aClass); } }
3,014
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MonitoringServiceConverterCallDetails.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/MonitoringServiceConverterCallDetails.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2013, Telestax Inc and individual contributors * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.connect.http.converter; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import org.apache.commons.configuration.Configuration; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.monitoringservice.LiveCallsDetails; import org.restcomm.connect.telephony.api.CallInfo; import java.lang.reflect.Type; import java.util.List; /** * @author <a href="mailto:[email protected]">gvagenas</a> * */ public class MonitoringServiceConverterCallDetails extends AbstractConverter implements JsonSerializer<LiveCallsDetails>{ private String dateTimeNow; public MonitoringServiceConverterCallDetails (Configuration configuration) { super(configuration); DateTime now = DateTime.now(); DateTimeFormatter fmt = DateTimeFormat.forPattern("EEE, dd MMM yyyy kk:mm:ss"); dateTimeNow = fmt.print(now); } @Override public boolean canConvert(final Class klass) { return (List.class.equals(klass)); } @Override public JsonElement serialize(LiveCallsDetails callDetails, Type typeOfSrc, JsonSerializationContext context) { JsonObject result = new JsonObject(); JsonArray callsArray = new JsonArray(); //First add InstanceId and Version details result.addProperty("DateTime", dateTimeNow); result.addProperty("InstanceId", RestcommConfiguration.getInstance().getMain().getInstanceId()); result.addProperty("Version", Version.getVersion()); result.addProperty("Revision", Version.getRevision()); List<CallInfo> liveCalls = callDetails.getCallDetails(); if (liveCalls.size() > 0) for (CallInfo callInfo: liveCalls) { callsArray.add(context.serialize(callInfo)); } result.add("LiveCallDetails", callsArray); return result; } @Override public void marshal(Object object, HierarchicalStreamWriter writer, MarshallingContext context) { final List<CallInfo> callDetails = (List<CallInfo>) object; writer.startNode("DateTime"); writer.setValue(dateTimeNow); writer.endNode(); writer.startNode("InstanceId"); writer.setValue(RestcommConfiguration.getInstance().getMain().getInstanceId()); writer.endNode(); writer.startNode("Version"); writer.setValue(Version.getVersion()); writer.endNode(); writer.startNode("Revision"); writer.setValue(Version.getRevision()); writer.endNode(); if (callDetails.size() > 0) { writer.startNode("LiveCallDetails"); for (final CallInfo callInfo : callDetails) { context.convertAnother(callInfo); } writer.endNode(); } } }
4,161
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
OrganizationListConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/OrganizationListConverter.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.restcomm.connect.http.converter; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.dao.entities.Organization; import org.restcomm.connect.dao.entities.OrganizationList; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * @author maria farooq */ public final class OrganizationListConverter extends AbstractConverter { public OrganizationListConverter(final Configuration configuration) { super(configuration); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return OrganizationList.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final OrganizationList list = (OrganizationList) object; writer.startNode("Organizations"); for (final Organization organization : list.getOrganizations()) { context.convertAnother(organization); } writer.endNode(); } }
1,937
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
OrganizationConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/OrganizationConverter.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.restcomm.connect.http.converter; import java.lang.reflect.Type; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.dao.entities.Organization; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * @author maria farooq */ @ThreadSafe public final class OrganizationConverter extends AbstractConverter implements JsonSerializer<Organization> { public OrganizationConverter(final Configuration configuration) { super(configuration); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return Organization.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final Organization organization = (Organization) object; writer.startNode("Organization"); writeSid(organization.getSid(), writer); writeDomainName(organization.getDomainName(), writer); writeStatus(organization.getStatus().toString(), writer); writeDateCreated(organization.getDateCreated(), writer); writeDateUpdated(organization.getDateUpdated(), writer); writer.endNode(); } @Override public JsonElement serialize(final Organization organization, final Type type, final JsonSerializationContext context) { final JsonObject object = new JsonObject(); writeSid(organization.getSid(), object); writeDomainName(organization.getDomainName(), object); writeStatus(organization.getStatus().toString(), object); writeDateCreated(organization.getDateCreated(), object); writeDateUpdated(organization.getDateUpdated(), object); return object; } }
2,885
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
GeolocationConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/GeolocationConverter.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2013, Telestax Inc and individual contributors * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.connect.http.converter; import java.lang.reflect.Type; import java.text.SimpleDateFormat; import java.util.Locale; import org.apache.commons.configuration.Configuration; import org.joda.time.DateTime; import org.restcomm.connect.dao.entities.Geolocation; import com.google.gson.JsonElement; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * @author <a href="mailto:[email protected]"> Fernando Mendioroz </a> * */ public class GeolocationConverter extends AbstractConverter implements JsonSerializer<Geolocation> { public GeolocationConverter(final Configuration configuration) { super(configuration); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return Geolocation.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final Geolocation geolocation = (Geolocation) object; writer.startNode("Geolocation"); writeSid(geolocation.getSid(), writer); writeDateCreated(geolocation.getDateCreated(), writer); writeDateUpdated(geolocation.getDateUpdated(), writer); writeDateExecuted(geolocation.getDateExecuted(), writer); writeAccountSid(geolocation.getAccountSid(), writer); writeSource(geolocation.getSource(), writer); writeDeviceIdentifier(geolocation.getDeviceIdentifier(), writer); writeGeolocationType(geolocation.getGeolocationType(), writer); writeResponseStatus(geolocation.getResponseStatus(), writer); writeGeolocationData(geolocation, writer); /*** GeolocationData XML ***/ writeGeolocationPositioningType(geolocation.getGeolocationPositioningType(), writer); writeLastGeolocationResponse(geolocation.getLastGeolocationResponse(), writer); writeCause(geolocation.getCause(), writer); writeApiVersion(geolocation.getApiVersion(), writer); writeUri(geolocation.getUri(), writer); writer.endNode(); } @Override public JsonElement serialize(final Geolocation geolocation, final Type type, final JsonSerializationContext context) { final JsonObject object = new JsonObject(); writeSid(geolocation.getSid(), object); writeDateCreated(geolocation.getDateCreated(), object); writeDateUpdated(geolocation.getDateUpdated(), object); writeDateExecuted(geolocation.getDateExecuted(), object); writeAccountSid(geolocation.getAccountSid(), object); writeSource(geolocation.getSource(), object); writeDeviceIdentifier(geolocation.getDeviceIdentifier(), object); writeGeolocationType(geolocation.getGeolocationType(), object); writeResponseStatus(geolocation.getResponseStatus(), object); writeGeolocationData(geolocation, object); /*** GeolocationData JSON ***/ writeGeolocationPositioningType(geolocation.getGeolocationPositioningType(), object); writeLastGeolocationResponse(geolocation.getLastGeolocationResponse(), object); writeCause(geolocation.getCause(), object); writeApiVersion(geolocation.getApiVersion(), object); writeUri(geolocation.getUri(), object); return object; } protected void writeDateExecuted(final DateTime dateExecuted, final HierarchicalStreamWriter writer) { writer.startNode("DateExecuted"); writer.setValue(new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US).format(dateExecuted.toDate())); writer.endNode(); } protected void writeDateExecuted(final DateTime dateExecuted, final JsonObject object) { object.addProperty("date_executed", new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US).format(dateExecuted.toDate())); } protected void writeSource(final String source, final HierarchicalStreamWriter writer) { if (source != null) { writer.startNode("Source"); writer.setValue(source); writer.endNode(); } } protected void writeSource(final String source, final JsonObject object) { if (source != null) { object.addProperty("source", source); } else { object.add("source", JsonNull.INSTANCE); } } protected void writeDeviceIdentifier(final String deviceIdentifier, final HierarchicalStreamWriter writer) { if (deviceIdentifier != null) { writer.startNode("DeviceIdentifier"); writer.setValue(deviceIdentifier); writer.endNode(); } } protected void writeDeviceIdentifier(final String deviceIdentifier, final JsonObject object) { if (deviceIdentifier != null) { object.addProperty("device_identifier", deviceIdentifier); } else { object.add("device_identifier", JsonNull.INSTANCE); } } protected void writeGeolocationType(final Geolocation.GeolocationType geolocationType, final HierarchicalStreamWriter writer) { if (geolocationType != null) { writer.startNode("GeolocationType"); writer.setValue(geolocationType.toString()); writer.endNode(); } } protected void writeGeolocationType(final Geolocation.GeolocationType geolocationType, final JsonObject object) { if (geolocationType != null) { object.addProperty("geolocation_type", geolocationType.toString()); } else { object.add("geolocation_type", JsonNull.INSTANCE); } } protected void writeResponseStatus(final String responseStatus, final HierarchicalStreamWriter writer) { if (responseStatus != null) { writer.startNode("ResponseStatus"); writer.setValue(responseStatus); writer.endNode(); } } protected void writeResponseStatus(final String responseStatus, final JsonObject object) { if (responseStatus != null) { object.addProperty("response_status", responseStatus); } else { object.add("response_status", JsonNull.INSTANCE); } } protected void writeGeolocationData(Geolocation geolocation, final HierarchicalStreamWriter writer) { writer.startNode("GeolocationData"); if (geolocation != null) { writeCellId(geolocation.getCellId(), writer); writeLocationAreaCode(geolocation.getLocationAreaCode(), writer); writeMobileCountryCode(geolocation.getMobileCountryCode(), writer); writeMobileNetworkCode(geolocation.getMobileNetworkCode(), writer); writeNetworkEntityAddress(geolocation.getNetworkEntityAddress(), writer); writeAgeOfLocationInfo(geolocation.getAgeOfLocationInfo(), writer); writeDeviceLatitude(geolocation.getDeviceLatitude(), writer); writeDeviceLongitude(geolocation.getDeviceLongitude(), writer); writeAccuracy(geolocation.getAccuracy(), writer); writeInternetAddress(geolocation.getInternetAddress(), writer); writePhysicalAddress(geolocation.getPhysicalAddress(), writer); writeFormattedAddress(geolocation.getFormattedAddress(), writer); writeLocationTimestamp(geolocation.getLocationTimestamp(), writer); writeEventGeofenceLatitude(geolocation.getEventGeofenceLatitude(), writer); writeEventGeofenceLongitude(geolocation.getEventGeofenceLongitude(), writer); writeRadius(geolocation.getRadius(), writer); } writer.endNode(); } protected void writeGeolocationData(Geolocation geolocation, final JsonObject object) { if (geolocation != null) { final JsonObject other = new JsonObject(); writeCellId(geolocation.getCellId(), other); writeLocationAreaCode(geolocation.getLocationAreaCode(), other); writeMobileCountryCode(geolocation.getMobileCountryCode(), other); writeMobileNetworkCode(geolocation.getMobileNetworkCode(), other); writeNetworkEntityAddress(geolocation.getNetworkEntityAddress(), other); writeAgeOfLocationInfo(geolocation.getAgeOfLocationInfo(), other); writeDeviceLatitude(geolocation.getDeviceLatitude(), other); writeDeviceLongitude(geolocation.getDeviceLongitude(), other); writeAccuracy(geolocation.getAccuracy(), other); writeInternetAddress(geolocation.getInternetAddress(), other); writePhysicalAddress(geolocation.getPhysicalAddress(), other); writeFormattedAddress(geolocation.getFormattedAddress(), other); writeLocationTimestamp(geolocation.getLocationTimestamp(), other); writeEventGeofenceLatitude(geolocation.getEventGeofenceLatitude(), other); writeEventGeofenceLongitude(geolocation.getEventGeofenceLongitude(), other); writeRadius(geolocation.getRadius(), other); object.add("geolocation_data", other); } else { object.add("geolocation_data", JsonNull.INSTANCE); } } protected void writeCellId(final String cellId, final HierarchicalStreamWriter writer) { if (cellId != null) { writer.startNode("CellId"); writer.setValue(cellId); writer.endNode(); } } protected void writeCellId(final String cellId, final JsonObject object) { if (cellId != null) { object.addProperty("cell_id", cellId); } else { object.add("cell_id", JsonNull.INSTANCE); } } protected void writeLocationAreaCode(final String locationAreaCode, final HierarchicalStreamWriter writer) { if (locationAreaCode != null) { writer.startNode("LocationAreaCode"); writer.setValue(locationAreaCode); writer.endNode(); } } protected void writeLocationAreaCode(final String locationAreaCode, final JsonObject object) { if (locationAreaCode != null) { object.addProperty("location_area_code", locationAreaCode); } else { object.add("location_area_code", JsonNull.INSTANCE); } } protected void writeMobileCountryCode(final Integer mobileCountryCode, final HierarchicalStreamWriter writer) { if (mobileCountryCode != null) { writer.startNode("MobileCountryCode"); writer.setValue(mobileCountryCode.toString()); writer.endNode(); } } protected void writeMobileCountryCode(final Integer mobileCountryCode, final JsonObject object) { if (mobileCountryCode != null) { object.addProperty("mobile_country_code", mobileCountryCode); } else { object.add("mobile_country_code", JsonNull.INSTANCE); } } protected void writeMobileNetworkCode(final String mobileNetworkCode, final HierarchicalStreamWriter writer) { if (mobileNetworkCode != null) { writer.startNode("MobileNetworkCode"); writer.setValue(mobileNetworkCode.toString()); writer.endNode(); } } protected void writeMobileNetworkCode(final String mobileNetworkCode, final JsonObject object) { if (mobileNetworkCode != null) { object.addProperty("mobile_network_code", mobileNetworkCode); } else { object.add("mobile_network_code", JsonNull.INSTANCE); } } protected void writeNetworkEntityAddress(final Long networkEntityAddress, final HierarchicalStreamWriter writer) { if (networkEntityAddress != null) { writer.startNode("NetworkEntityAddress"); writer.setValue(networkEntityAddress.toString()); writer.endNode(); } } protected void writeNetworkEntityAddress(final Long networkEntityAddress, final JsonObject object) { if (networkEntityAddress != null) { object.addProperty("network_entity_address", networkEntityAddress); } else { object.add("network_entity_address", JsonNull.INSTANCE); } } protected void writeAgeOfLocationInfo(final Integer ageOfLocationInfo, final HierarchicalStreamWriter writer) { if (ageOfLocationInfo != null) { writer.startNode("LocationAge"); writer.setValue(ageOfLocationInfo.toString()); writer.endNode(); } } protected void writeAgeOfLocationInfo(final Integer ageOfLocationInfo, final JsonObject object) { if (ageOfLocationInfo != null) { object.addProperty("location_age", ageOfLocationInfo); } else { object.add("location_age", JsonNull.INSTANCE); } } protected void writeDeviceLatitude(final String deviceLatitude, final HierarchicalStreamWriter writer) { if (deviceLatitude != null) { writer.startNode("DeviceLatitude"); writer.setValue(deviceLatitude); writer.endNode(); } } protected void writeDeviceLatitude(final String deviceLatitude, final JsonObject object) { if (deviceLatitude != null) { object.addProperty("device_latitude", deviceLatitude); } else { object.add("device_latitude", JsonNull.INSTANCE); } } protected void writeDeviceLongitude(final String deviceLongitude, final HierarchicalStreamWriter writer) { if (deviceLongitude != null) { writer.startNode("DeviceLongitude"); writer.setValue(deviceLongitude); writer.endNode(); } } protected void writeDeviceLongitude(final String deviceLongitude, final JsonObject object) { if (deviceLongitude != null) { object.addProperty("device_longitude", deviceLongitude); } else { object.add("device_longitude", JsonNull.INSTANCE); } } protected void writeAccuracy(final Long accuracy, final HierarchicalStreamWriter writer) { if (accuracy != null) { writer.startNode("Accuracy"); writer.setValue(accuracy.toString()); writer.endNode(); } } protected void writeAccuracy(final Long accuracy, final JsonObject object) { if (accuracy != null) { object.addProperty("accuracy", accuracy); } else { object.add("accuracy", JsonNull.INSTANCE); } } protected void writePhysicalAddress(final String physicalAddress, final HierarchicalStreamWriter writer) { if (physicalAddress != null) { writer.startNode("PhysicalAddress"); writer.setValue(physicalAddress); writer.endNode(); } } protected void writePhysicalAddress(final String physicalAddress, final JsonObject object) { if (physicalAddress != null) { object.addProperty("physical_address", physicalAddress); } else { object.add("physical_address", JsonNull.INSTANCE); } } protected void writeInternetAddress(final String internetAddress, final HierarchicalStreamWriter writer) { if (internetAddress != null) { writer.startNode("InternetAddress"); writer.setValue(internetAddress); writer.endNode(); } } protected void writeInternetAddress(final String internetAddress, final JsonObject object) { if (internetAddress != null) { object.addProperty("internet_address", internetAddress); } else { object.add("internet_address", JsonNull.INSTANCE); } } protected void writeFormattedAddress(final String formattedAddress, final HierarchicalStreamWriter writer) { if (formattedAddress != null) { writer.startNode("FormattedAddress"); writer.setValue(formattedAddress); writer.endNode(); } } protected void writeFormattedAddress(final String formattedAddress, final JsonObject object) { if (formattedAddress != null) { object.addProperty("formatted_address", formattedAddress); } else { object.add("formatted_address", JsonNull.INSTANCE); } } protected void writeLocationTimestamp(final DateTime locationTimestamp, final HierarchicalStreamWriter writer) { if (locationTimestamp != null) { writer.startNode("LocationTimestamp"); writer.setValue(new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US).format(locationTimestamp.toDate())); writer.endNode(); } } protected void writeLocationTimestamp(final DateTime locationTimestamp, final JsonObject object) { if (locationTimestamp != null) { object.addProperty("location_timestamp", new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US).format(locationTimestamp.toDate())); } else { object.add("location_timestamp", JsonNull.INSTANCE); } } protected void writeEventGeofenceLatitude(final String eventGeofenceLatitude, final HierarchicalStreamWriter writer) { if (eventGeofenceLatitude != null) { writer.startNode("EventGeofenceLatitude"); writer.setValue(eventGeofenceLatitude); writer.endNode(); } } protected void writeEventGeofenceLatitude(final String eventGeofenceLatitude, final JsonObject object) { if (eventGeofenceLatitude != null) { object.addProperty("event_geofence_latitude", eventGeofenceLatitude); } else { object.add("event_geofence_latitude", JsonNull.INSTANCE); } } protected void writeEventGeofenceLongitude(final String eventGeofenceLongitude, final HierarchicalStreamWriter writer) { if (eventGeofenceLongitude != null) { writer.startNode("EventGeofenceLongitude"); writer.setValue(eventGeofenceLongitude); writer.endNode(); } } protected void writeEventGeofenceLongitude(final String eventGeofenceLongitude, final JsonObject object) { if (eventGeofenceLongitude != null) { object.addProperty("event_geofence_longitude", eventGeofenceLongitude); } else { object.add("event_geofence_longitude", JsonNull.INSTANCE); } } protected void writeRadius(final Long radius, final HierarchicalStreamWriter writer) { if (radius != null) { writer.startNode("Radius"); writer.setValue(radius.toString()); writer.endNode(); } } protected void writeRadius(final Long radius, final JsonObject object) { if (radius != null) { object.addProperty("radius", radius); } else { object.add("radius", JsonNull.INSTANCE); } } protected void writeGeolocationPositioningType(final String geolocationPositioningType, final HierarchicalStreamWriter writer) { if (geolocationPositioningType != null) { writer.startNode("GeolocationPositioningType"); writer.setValue(geolocationPositioningType.toString()); writer.endNode(); } } protected void writeGeolocationPositioningType(final String geolocationPositioningType, final JsonObject object) { if (geolocationPositioningType != null) { object.addProperty("geolocation_positioning_type", geolocationPositioningType); } else { object.add("geolocation_positioning_type", JsonNull.INSTANCE); } } protected void writeLastGeolocationResponse(final String lastGeolocationResponse, final HierarchicalStreamWriter writer) { if (lastGeolocationResponse != null) { writer.startNode("LastGeolocationResponse"); writer.setValue(lastGeolocationResponse.toString()); writer.endNode(); } } protected void writeLastGeolocationResponse(final String lastGeolocationResponse, final JsonObject object) { if (lastGeolocationResponse != null) { object.addProperty("last_geolocation_response", lastGeolocationResponse); } else { object.add("last_geolocation_response", JsonNull.INSTANCE); } } protected void writeCause(final String cause, final HierarchicalStreamWriter writer) { if (cause != null) { writer.startNode("Cause"); writer.setValue(cause.toString()); writer.endNode(); } } protected void writeCause(final String cause, final JsonObject object) { if (cause != null) { object.addProperty("cause", cause); } else { object.add("cause", JsonNull.INSTANCE); } } }
22,097
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SmsMessageListConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/SmsMessageListConverter.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.restcomm.connect.http.converter; import com.google.gson.JsonArray; import java.lang.reflect.Type; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.dao.entities.SmsMessage; import org.restcomm.connect.dao.entities.SmsMessageList; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class SmsMessageListConverter extends AbstractConverter implements JsonSerializer<SmsMessageList> { Integer page, pageSize, total; String pathUri; public SmsMessageListConverter(final Configuration configuration) { super(configuration); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return SmsMessageList.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final SmsMessageList list = (SmsMessageList) object; writer.startNode("SMSMessages"); for (final SmsMessage sms : list.getSmsMessages()) { context.convertAnother(sms); } writer.endNode(); } @Override public JsonObject serialize(SmsMessageList smsList, Type type, JsonSerializationContext context) { JsonObject result = new JsonObject(); JsonArray array = new JsonArray(); for (SmsMessage cdr : smsList.getSmsMessages()) { array.add(context.serialize(cdr)); } if (total != null && pageSize != null && page != null) { result.addProperty("page", page); result.addProperty("num_pages", getTotalPages()); result.addProperty("page_size", pageSize); result.addProperty("total", total); result.addProperty("start", getFirstIndex()); result.addProperty("end", getLastIndex(smsList)); result.addProperty("uri", pathUri); result.addProperty("first_page_uri", getFirstPageUri()); result.addProperty("previous_page_uri", getPreviousPageUri()); result.addProperty("next_page_uri", getNextPageUri(smsList)); result.addProperty("last_page_uri", getLastPageUri()); } result.add("messages", array); return result; } private int getTotalPages() { return total / pageSize; } private String getFirstIndex() { return String.valueOf(page * pageSize); } private String getLastIndex(SmsMessageList list) { return String.valueOf((page == getTotalPages()) ? (page * pageSize) + list.getSmsMessages().size() : (pageSize - 1) + (page * pageSize)); } private String getFirstPageUri() { return pathUri + "?Page=0&PageSize=" + pageSize; } private String getPreviousPageUri() { return ((page == 0) ? "null" : pathUri + "?Page=" + (page - 1) + "&PageSize=" + pageSize); } private String getNextPageUri(SmsMessageList list) { String lastSid = (page == getTotalPages()) ? "null" : list.getSmsMessages().get(pageSize - 1).getSid().toString(); return (page == getTotalPages()) ? "null" : pathUri + "?Page=" + (page + 1) + "&PageSize=" + pageSize + "&AfterSid=" + lastSid; } private String getLastPageUri() { return pathUri + "?Page=" + getTotalPages() + "&PageSize=" + pageSize; } public void setPage(Integer page) { this.page = page; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public void setCount(Integer count) { this.total = count; } public void setPathUri(String pathUri) { this.pathUri = pathUri; } }
4,863
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
UsageConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/UsageConverter.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.restcomm.connect.http.converter; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import org.apache.commons.configuration.Configuration; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import org.joda.time.DateTime; import org.restcomm.connect.dao.entities.Usage; import java.lang.reflect.Type; import java.net.URI; /** * @author [email protected] (Alexandre Mendonca) */ public final class UsageConverter extends AbstractConverter implements JsonSerializer<Usage> { public UsageConverter(final Configuration configuration) { super(configuration); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return Usage.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final Usage number = (Usage) object; writer.startNode("UsageRecord"); writeCategory(number.getCategory(), writer); writeDescription(number.getDescription(), writer); writeAccountSid(number.getAccountSid(), writer); writeStartDate(number.getStartDate(), writer); writeEndDate(number.getEndDate(), writer); writeUsage(number.getUsage(), writer); writeUsageUnit(number.getUsageUnit(), writer); writeCount(number.getCount(), writer); writeCountUnit(number.getCountUnit(), writer); writePrice(number.getPrice(), writer); writePriceUnit(number.getPriceUnit(), writer); writeUri(number.getUri(), writer); writer.endNode(); } private void writeCategory(final Usage.Category category, final HierarchicalStreamWriter writer) { writer.startNode("Category"); if (category != null) { writer.setValue(category.toString()); } writer.endNode(); } private void writeCategory(final Usage.Category category, final JsonObject object) { object.addProperty("category", category.toString()); } private void writeDescription(final String description, final HierarchicalStreamWriter writer) { writer.startNode("Description"); if (description != null) { writer.setValue(description.toString()); } writer.endNode(); } private void writeDescription(final String description, final JsonObject object) { object.addProperty("description", description); } private void writeStartDate(final DateTime startDate, final HierarchicalStreamWriter writer) { writer.startNode("StartDate"); if (startDate != null) { writer.setValue(startDate.toString("yyyy-MM-dd")); } writer.endNode(); } private void writeStartDate(final DateTime startDate, final JsonObject object) { object.addProperty("start_date", startDate.toString("yyyy-MM-dd")); } private void writeEndDate(final DateTime endDate, final HierarchicalStreamWriter writer) { writer.startNode("EndDate"); if (endDate != null) { writer.setValue(endDate.toString("yyyy-MM-dd")); } writer.endNode(); } private void writeEndDate(final DateTime endDate, final JsonObject object) { object.addProperty("end_date", endDate.toString("yyyy-MM-dd")); } private void writeUsage(final Long usage, final HierarchicalStreamWriter writer) { writer.startNode("Usage"); if (usage != null) { writer.setValue(usage.toString()); } writer.endNode(); } private void writeUsage(final Long usage, final JsonObject object) { object.addProperty("usage", usage.toString()); } private void writeUsageUnit(final String usageUnit, final HierarchicalStreamWriter writer) { writer.startNode("UsageUnit"); if (usageUnit != null) { writer.setValue(usageUnit); } writer.endNode(); } private void writeUsageUnit(final String usageUnit, final JsonObject object) { object.addProperty("usage_unit", usageUnit); } private void writeCount(final Long count, final HierarchicalStreamWriter writer) { writer.startNode("Count"); if (count != null) { writer.setValue(count.toString()); } writer.endNode(); } private void writeCount(final Long count, final JsonObject object) { object.addProperty("count", count.toString()); } private void writeCountUnit(final String countUnit, final HierarchicalStreamWriter writer) { writer.startNode("CountUnit"); if (countUnit != null) { writer.setValue(countUnit.toString()); } writer.endNode(); } private void writeCountUnit(final String countUnit, final JsonObject object) { object.addProperty("count_unit", countUnit); } private void writePriceUnit(final String priceUnit, final HierarchicalStreamWriter writer) { writer.startNode("PriceUnit"); if (priceUnit != null) { writer.setValue(priceUnit.toString()); } writer.endNode(); } private void writePriceUnit(final String priceUnit, final JsonObject object) { object.addProperty("price_unit", priceUnit); } protected void writeUri(final URI uri, final JsonObject object) { object.addProperty("uri", uri.toString()); } @Override public JsonElement serialize(Usage usage, Type type, JsonSerializationContext jsonSerializationContext) { final JsonObject object = new JsonObject(); writeCategory(usage.getCategory(), object); writeDescription(usage.getDescription(), object); writeAccountSid(usage.getAccountSid(), object); writeStartDate(usage.getStartDate(), object); writeEndDate(usage.getEndDate(), object); writeUsage(usage.getUsage(), object); writeUsageUnit(usage.getUsageUnit(), object); writeCount(usage.getCount(), object); writeCountUnit(usage.getCountUnit(), object); writePrice(usage.getPrice(), object); writePriceUnit(usage.getPriceUnit(), object); writeUri(usage.getUri(), object); return object; } }
6,775
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ApplicationListConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/ApplicationListConverter.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.restcomm.connect.http.converter; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.dao.entities.Application; import org.restcomm.connect.dao.entities.ApplicationList; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class ApplicationListConverter extends AbstractConverter { public ApplicationListConverter(final Configuration configuration) { super(configuration); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return ApplicationList.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final ApplicationList list = (ApplicationList) object; writer.startNode("Applications"); for (final Application application : list.getApplications()) { context.convertAnother(application); } writer.endNode(); } }
2,040
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ApplicationConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/ApplicationConverter.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.restcomm.connect.http.converter; import java.lang.reflect.Type; import java.net.URI; import java.util.List; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.dao.entities.Application; import com.google.gson.JsonElement; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import org.restcomm.connect.dao.entities.ApplicationNumberSummary; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class ApplicationConverter extends AbstractConverter implements JsonSerializer<Application> { public ApplicationConverter(final Configuration configuration) { super(configuration); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return Application.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final Application application = (Application) object; writer.startNode("Application"); writeSid(application.getSid(), writer); writeDateCreated(application.getDateCreated(), writer); writeDateUpdated(application.getDateUpdated(), writer); writeFriendlyName(application.getFriendlyName(), writer); writeAccountSid(application.getAccountSid(), writer); writeApiVersion(application.getApiVersion(), writer); writeVoiceCallerIdLookup(application.hasVoiceCallerIdLookup(), writer); writeUri(application.getUri(), writer); writeRcmlUrl(application.getRcmlUrl(), writer); writeKind(application.getKind(), writer); writeNumbers(application.getNumbers(), writer, context); writer.endNode(); } @Override public JsonElement serialize(final Application application, final Type type, final JsonSerializationContext context) { final JsonObject object = new JsonObject(); writeSid(application.getSid(), object); writeDateCreated(application.getDateCreated(), object); writeDateUpdated(application.getDateUpdated(), object); writeFriendlyName(application.getFriendlyName(), object); writeAccountSid(application.getAccountSid(), object); writeApiVersion(application.getApiVersion(), object); writeVoiceCallerIdLookup(application.hasVoiceCallerIdLookup(), object); writeUri(application.getUri(), object); writeRcmlUrl(application.getRcmlUrl(), object); writeKind(application.getKind(), object); object.add("numbers",context.serialize(application.getNumbers())); return object; } private void writeRcmlUrl(final URI rcmlUrl, final HierarchicalStreamWriter writer) { if (rcmlUrl != null) { writer.startNode("RcmlUrl"); writer.setValue(rcmlUrl.toString()); writer.endNode(); } } private void writeRcmlUrl(final URI rcmlUrl, final JsonObject object) { if (rcmlUrl != null) { object.addProperty("rcml_url", rcmlUrl.toString()); } else { object.add("rcml_url", JsonNull.INSTANCE); } } private void writeKind(final Application.Kind kind, final HierarchicalStreamWriter writer) { if (kind != null) { writer.startNode("Kind"); writer.setValue(kind.toString()); writer.endNode(); } } private void writeKind(final Application.Kind kind, final JsonObject object) { if (kind != null) { object.addProperty("kind", kind.toString()); } else { object.add("kind", JsonNull.INSTANCE); } } private void writeNumbers(final List<ApplicationNumberSummary> numbers, final HierarchicalStreamWriter writer, final MarshallingContext context) { if (numbers != null) { writer.startNode("Numbers"); context.convertAnother(numbers); writer.endNode(); } } }
5,115
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CallDetailRecordConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/CallDetailRecordConverter.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.restcomm.connect.http.converter; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import org.apache.commons.configuration.Configuration; import org.joda.time.DateTime; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.entities.CallDetailRecord; import java.lang.reflect.Type; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class CallDetailRecordConverter extends AbstractConverter implements JsonSerializer<CallDetailRecord> { private final String apiVersion; public CallDetailRecordConverter(final Configuration configuration) { super(configuration); apiVersion = configuration.getString("api-version"); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return CallDetailRecord.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final CallDetailRecord cdr = (CallDetailRecord) object; writer.startNode("Call"); writeSid(cdr.getSid(), writer); writeInstanceId(cdr.getInstanceId(), writer); writeDateCreated(cdr.getDateCreated(), writer); writeDateUpdated(cdr.getDateUpdated(), writer); writeParentCallSid(cdr.getParentCallSid(), writer); writeAccountSid(cdr.getAccountSid(), writer); writeTo(cdr.getTo(), writer); writeFrom(cdr.getFrom(), writer); writePhoneNumberSid(cdr.getPhoneNumberSid(), writer); writeStatus(cdr.getStatus(), writer); writeStartTime(cdr.getStartTime(), writer); writeEndTime(cdr.getEndTime(), writer); writeDuration(cdr.getDuration(), writer); writePrice(cdr.getPrice(), writer); writePriceUnit(cdr.getPriceUnit(), writer); writeDirection(cdr.getDirection(), writer); writeAnsweredBy(cdr.getAnsweredBy(), writer); writeApiVersion(cdr.getApiVersion(), writer); writeForwardedFrom(cdr.getForwardedFrom(), writer); writeCallerName(cdr.getCallerName(), writer); writeUri(cdr.getUri(), writer); writeSubResources(cdr, writer); writeRingDuration(cdr.getRingDuration(), writer); writer.endNode(); } private String prefix(final CallDetailRecord cdr) { final StringBuilder buffer = new StringBuilder(); buffer.append("/").append(apiVersion).append("/Accounts/"); buffer.append(cdr.getAccountSid().toString()).append("/Calls/"); buffer.append(cdr.getSid()); return buffer.toString(); } @Override public JsonElement serialize(final CallDetailRecord cdr, Type type, final JsonSerializationContext context) { final JsonObject object = new JsonObject(); writeSid(cdr.getSid(), object); writeInstanceId(cdr.getInstanceId(), object); writeDateCreated(cdr.getDateCreated(), object); writeDateUpdated(cdr.getDateUpdated(), object); writeParentCallSid(cdr.getParentCallSid(), object); writeAccountSid(cdr.getAccountSid(), object); writeTo(cdr.getTo(), object); writeFrom(cdr.getFrom(), object); writePhoneNumberSid(cdr.getPhoneNumberSid(), object); writeStatus(cdr.getStatus(), object); writeStartTime(cdr.getStartTime(), object); writeEndTime(cdr.getEndTime(), object); writeDuration(cdr.getDuration(), object); writePriceUnit(cdr.getPriceUnit(), object); writeDirection(cdr.getDirection(), object); writeAnsweredBy(cdr.getAnsweredBy(), object); writeApiVersion(cdr.getApiVersion(), object); writeForwardedFrom(cdr.getForwardedFrom(), object); writeCallerName(cdr.getCallerName(), object); writeUri(cdr.getUri(), object); writeRingDuration(cdr.getRingDuration(), object); writeSubResources(cdr, object); return object; } private void writeAnsweredBy(final String answeredBy, final HierarchicalStreamWriter writer) { writer.startNode("AnsweredBy"); if (answeredBy != null) { writer.setValue(answeredBy); } writer.endNode(); } private void writeAnsweredBy(final String answeredBy, final JsonObject object) { object.addProperty("answered_by", answeredBy); } private void writeCallerName(final String callerName, final HierarchicalStreamWriter writer) { writer.startNode("CallerName"); if (callerName != null) { writer.setValue(callerName); } writer.endNode(); } private void writeCallerName(final String callerName, final JsonObject object) { object.addProperty("caller_name", callerName); } private void writeDirection(final String direction, final HierarchicalStreamWriter writer) { writer.startNode("Direction"); writer.setValue(direction); writer.endNode(); } private void writeDirection(final String direction, final JsonObject object) { object.addProperty("direction", direction); } private void writeDuration(final Integer duration, final HierarchicalStreamWriter writer) { writer.startNode("Duration"); if (duration != null) { writer.setValue(duration.toString()); } writer.endNode(); } private void writeDuration(final Integer duration, final JsonObject object) { object.addProperty("duration", duration); } private void writeRingDuration(final Integer ringDuration, final HierarchicalStreamWriter writer) { writer.startNode("Ring_duration"); if (ringDuration != null) { writer.setValue(ringDuration.toString()); } writer.endNode(); } private void writeRingDuration(final Integer ringDuration, final JsonObject object) { object.addProperty("ring_duration", ringDuration); } private void writeForwardedFrom(final String forwardedFrom, final HierarchicalStreamWriter writer) { writer.startNode("ForwardedFrom"); if (forwardedFrom != null) { writer.setValue(forwardedFrom); } writer.endNode(); } private void writeForwardedFrom(final String forwardedFrom, final JsonObject object) { object.addProperty("forwarded_from", forwardedFrom); } private void writeParentCallSid(final Sid sid, final HierarchicalStreamWriter writer) { writer.startNode("ParentCallSid"); if (sid != null) { writer.setValue(sid.toString()); } writer.endNode(); } private void writeParentCallSid(final Sid sid, final JsonObject object) { if (sid != null) { object.addProperty("parent_call_sid", sid.toString()); } } private void writePhoneNumberSid(final Sid sid, final HierarchicalStreamWriter writer) { writer.startNode("PhoneNumberSid"); if (sid != null) { writer.setValue(sid.toString()); } writer.endNode(); } private void writePhoneNumberSid(final Sid sid, final JsonObject object) { if (sid != null) { object.addProperty("phone_number_sid", sid.toString()); } } private void writeEndTime(final DateTime endTime, final HierarchicalStreamWriter writer) { writer.startNode("EndTime"); if (endTime != null) { writer.setValue(endTime.toString()); } writer.endNode(); } private void writeEndTime(final DateTime endTime, final JsonObject object) { if (endTime != null) { object.addProperty("end_time", endTime.toString()); } } private void writeStartTime(final DateTime startTime, final HierarchicalStreamWriter writer) { writer.startNode("StartTime"); if (startTime != null) { writer.setValue(startTime.toString()); } writer.endNode(); } private void writeStartTime(final DateTime startTime, final JsonObject object) { if (startTime != null) { object.addProperty("start_time", startTime.toString()); } } private void writeNotifications(final CallDetailRecord cdr, final HierarchicalStreamWriter writer) { writer.startNode("Notifications"); writer.setValue(prefix(cdr) + "/Notifications"); writer.endNode(); } private void writeNotifications(final CallDetailRecord cdr, final JsonObject object) { object.addProperty("notifications", prefix(cdr) + "/Notifications.json"); } private void writeRecordings(final CallDetailRecord cdr, final HierarchicalStreamWriter writer) { writer.startNode("Recordings"); writer.setValue(prefix(cdr) + "/Recordings"); writer.endNode(); } private void writeRecordings(final CallDetailRecord cdr, final JsonObject object) { object.addProperty("recordings", prefix(cdr) + "/Recordings.json"); } private void writeSubResources(final CallDetailRecord cdr, final HierarchicalStreamWriter writer) { writer.startNode("SubresourceUris"); writeNotifications(cdr, writer); writeRecordings(cdr, writer); writer.endNode(); } private void writeSubResources(final CallDetailRecord cdr, final JsonObject object) { final JsonObject other = new JsonObject(); writeNotifications(cdr, other); writeRecordings(cdr, other); object.add("subresource_uris", other); } private void writeInstanceId(final String instanceId, final HierarchicalStreamWriter writer) { if (instanceId != null && !instanceId.isEmpty()) { writer.startNode("InstanceId"); writer.setValue(instanceId); writer.endNode(); } } private void writeInstanceId(final String instanceId, final JsonObject object) { if (instanceId != null && !instanceId.isEmpty()) object.addProperty("InstanceId", instanceId); } }
11,159
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CallinfoConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/CallinfoConverter.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2013, Telestax Inc and individual contributors * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.connect.http.converter; import java.lang.reflect.Type; import javax.servlet.sip.URI; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.telephony.api.CallInfo; import org.restcomm.connect.commons.util.StringUtils; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * @author <a href="mailto:[email protected]">gvagenas</a> * */ public class CallinfoConverter extends AbstractConverter implements JsonSerializer<CallInfo>{ private final String apiVersion; private final String rootUri; @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return CallInfo.class.equals(klass); } /** * @param configuration */ public CallinfoConverter(Configuration configuration) { super(configuration); apiVersion = configuration.getString("api-version"); rootUri = StringUtils.addSuffixIfNotPresent(configuration.getString("root-uri"), "/"); } @Override public JsonElement serialize(CallInfo callInfo, Type typeOfSrc, JsonSerializationContext context) { final JsonObject object = new JsonObject(); writeSid(callInfo.sid(), object); writeState(callInfo.state().name(), object); if (callInfo.type() != null) writeType(callInfo.type().name(), object); writeDirection(callInfo.direction(), object); writeDateCreated(callInfo.dateCreated(), object); writeForwardedFrom(callInfo.forwardedFrom(), object); writeCallerName(callInfo.fromName(), object); writeFrom(callInfo.from(), object); writeTo(callInfo.to(), object); if (callInfo.invite() != null) { writeInviteUri(callInfo.invite().getRequestURI(), object); } if (callInfo.lastResponse() != null) writeLastResponseUri(callInfo.lastResponse().getStatus(), object); return object; } @Override public void marshal(Object object, HierarchicalStreamWriter writer, MarshallingContext context) { final CallInfo callInfo = (CallInfo) object; writer.startNode("CallInfo"); writeSid(callInfo.sid(), writer); writeState(callInfo.state().name(), writer); if (callInfo.type() != null) writeType(callInfo.type().name(), writer); writeDirection(callInfo.direction(), writer); writeDateCreated(callInfo.dateCreated(), writer); writeForwardedFrom(callInfo.forwardedFrom(), writer); writeCallerName(callInfo.fromName(), writer); writeFrom(callInfo.from(), writer); writeTo(callInfo.to(), writer); writeInviteUri(callInfo.invite().getRequestURI(), writer); if (callInfo.lastResponse() != null) writeLastResponseUri(callInfo.lastResponse().getStatus(), writer); writer.endNode(); } private void writeState(final String state, final HierarchicalStreamWriter writer) { writer.startNode("State"); writer.setValue(state); writer.endNode(); } private void writeState(final String state, final JsonObject object) { object.addProperty("State", state); } private void writeDirection(final String direction, final HierarchicalStreamWriter writer) { writer.startNode("Direction"); writer.setValue(direction); writer.endNode(); } private void writeDirection(final String direction, final JsonObject object) { object.addProperty("direction", direction); } private void writeForwardedFrom(final String forwardedFrom, final HierarchicalStreamWriter writer) { writer.startNode("ForwardedFrom"); if (forwardedFrom != null) { writer.setValue(forwardedFrom); } writer.endNode(); } private void writeForwardedFrom(final String forwardedFrom, final JsonObject object) { object.addProperty("ForwardedFrom", forwardedFrom); } private void writeCallerName(final String callerName, final HierarchicalStreamWriter writer) { writer.startNode("CallerName"); if (callerName != null) { writer.setValue(callerName); } writer.endNode(); } private void writeCallerName(final String callerName, final JsonObject object) { object.addProperty("CallerName", callerName); } private void writeInviteUri(final URI requestUri, final HierarchicalStreamWriter writer) { writer.startNode("Initial Invite"); if (requestUri != null) { writer.setValue(requestUri.toString()); } writer.endNode(); } private void writeInviteUri(final URI requestUri, final JsonObject object) { object.addProperty("Initial Invite", requestUri.toString()); } private void writeLastResponseUri(final int responseCode, final HierarchicalStreamWriter writer) { writer.startNode("Last Response"); if (responseCode > -1) { writer.setValue(String.valueOf(responseCode)); } writer.endNode(); } private void writeLastResponseUri(final int responseCode, final JsonObject object) { object.addProperty("Last Response", responseCode); } }
6,391
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
IncomingPhoneNumberListConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/IncomingPhoneNumberListConverter.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.restcomm.connect.http.converter; import java.lang.reflect.Type; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.dao.entities.IncomingPhoneNumber; import org.restcomm.connect.dao.entities.IncomingPhoneNumberList; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class IncomingPhoneNumberListConverter extends AbstractConverter implements JsonSerializer<IncomingPhoneNumberList> { Integer page, pageSize, total; String pathUri; public IncomingPhoneNumberListConverter(final Configuration configuration) { super(configuration); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return IncomingPhoneNumberList.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final IncomingPhoneNumberList list = (IncomingPhoneNumberList) object; writer.startNode("IncomingPhoneNumbers"); writer.addAttribute("page", String.valueOf(page)); writer.addAttribute("numpages", String.valueOf(getTotalPages())); writer.addAttribute("pagesize", String.valueOf(pageSize)); writer.addAttribute("total", String.valueOf(getTotalPages())); writer.addAttribute("start", getFirstIndex()); writer.addAttribute("end", getLastIndex(list)); writer.addAttribute("uri", pathUri); writer.addAttribute("firstpageuri", getFirstPageUri()); writer.addAttribute("previouspageuri", getPreviousPageUri()); writer.addAttribute("nextpageuri", getNextPageUri(list)); writer.addAttribute("lastpageuri", getLastPageUri()); for (final IncomingPhoneNumber incomingPhoneNumber : list.getIncomingPhoneNumbers()) { context.convertAnother(incomingPhoneNumber); } writer.endNode(); } @Override public JsonObject serialize(IncomingPhoneNumberList list, Type type, JsonSerializationContext context) { JsonObject result = new JsonObject(); JsonArray array = new JsonArray(); for (IncomingPhoneNumber phoneNumber : list.getIncomingPhoneNumbers()) { array.add(context.serialize(phoneNumber)); } if (total != null && pageSize != null && page != null) { result.addProperty("page", page); result.addProperty("num_pages", getTotalPages()); result.addProperty("page_size", pageSize); result.addProperty("total", total); result.addProperty("start", getFirstIndex()); result.addProperty("end", getLastIndex(list)); result.addProperty("uri", pathUri); result.addProperty("first_page_uri", getFirstPageUri()); result.addProperty("previous_page_uri", getPreviousPageUri()); result.addProperty("next_page_uri", getNextPageUri(list)); result.addProperty("last_page_uri", getLastPageUri()); } result.add("incomingPhoneNumbers", array); return result; } private int getTotalPages() { return total / pageSize; } private String getFirstIndex() { return String.valueOf(page * pageSize); } private String getLastIndex(IncomingPhoneNumberList list) { return String.valueOf((page == getTotalPages()) ? (page * pageSize) + list.getIncomingPhoneNumbers().size() : (pageSize - 1) + (page * pageSize)); } private String getFirstPageUri() { return pathUri + "?Page=0&PageSize=" + pageSize; } private String getPreviousPageUri() { return ((page == 0) ? "null" : pathUri + "?Page=" + (page - 1) + "&PageSize=" + pageSize); } private String getNextPageUri(IncomingPhoneNumberList list) { String lastSid = (page == getTotalPages()) ? "null" : list.getIncomingPhoneNumbers().get(pageSize - 1).getSid().toString(); return (page == getTotalPages()) ? "null" : pathUri + "?Page=" + (page + 1) + "&PageSize=" + pageSize + "&AfterSid=" + lastSid; } private String getLastPageUri() { return pathUri + "?Page=" + getTotalPages() + "&PageSize=" + pageSize; } public void setPage(Integer page) { this.page = page; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public void setCount(Integer count) { this.total = count; } public void setPathUri(String pathUri) { this.pathUri = pathUri; } }
5,786
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
NotificationConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/NotificationConverter.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.restcomm.connect.http.converter; import java.lang.reflect.Type; import java.net.URI; import org.apache.commons.configuration.Configuration; import org.joda.time.DateTime; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.dao.entities.Notification; import com.google.gson.JsonElement; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class NotificationConverter extends AbstractConverter implements JsonSerializer<Notification> { public NotificationConverter(final Configuration configuration) { super(configuration); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return Notification.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final Notification notification = (Notification) object; writer.startNode("Notification"); writeSid(notification.getSid(), writer); writeDateCreated(notification.getDateCreated(), writer); writeDateUpdated(notification.getDateUpdated(), writer); writeAccountSid(notification.getAccountSid(), writer); writeCallSid(notification.getCallSid(), writer); writeApiVersion(notification.getApiVersion(), writer); writeLog(notification.getLog(), writer); writeErrorCode(notification.getErrorCode(), writer); writeMoreInfo(notification.getMoreInfo(), writer); writeMessageText(notification.getMessageText(), writer); writeMessageDate(notification.getMessageDate(), writer); writeRequestUrl(notification.getRequestUrl(), writer); writeRequestMethod(notification.getRequestMethod(), writer); writeRequestVariables(notification.getRequestVariables(), writer); writeResponseHeaders(notification.getResponseHeaders(), writer); writeResponseBody(notification.getResponseBody(), writer); writeUri(notification.getUri(), writer); writer.endNode(); } @Override public JsonElement serialize(final Notification notification, final Type type, final JsonSerializationContext context) { final JsonObject object = new JsonObject(); writeSid(notification.getSid(), object); writeDateCreated(notification.getDateCreated(), object); writeDateUpdated(notification.getDateUpdated(), object); writeAccountSid(notification.getAccountSid(), object); writeCallSid(notification.getCallSid(), object); writeApiVersion(notification.getApiVersion(), object); writeLog(notification.getLog(), object); writeErrorCode(notification.getErrorCode(), object); writeMoreInfo(notification.getMoreInfo(), object); writeMessageText(notification.getMessageText(), object); writeMessageDate(notification.getMessageDate(), object); writeRequestUrl(notification.getRequestUrl(), object); writeRequestMethod(notification.getRequestMethod(), object); writeRequestVariables(notification.getRequestVariables(), object); writeResponseHeaders(notification.getResponseHeaders(), object); writeResponseBody(notification.getResponseBody(), object); writeUri(notification.getUri(), object); return object; } private void writeErrorCode(final int errorCode, final HierarchicalStreamWriter writer) { writer.startNode("ErrorCode"); writer.setValue(Integer.toString(errorCode)); writer.endNode(); } private void writeErrorCode(final int errorCode, final JsonObject object) { object.addProperty("error_code", errorCode); } private void writeLog(final int log, final HierarchicalStreamWriter writer) { writer.startNode("Log"); writer.setValue(Integer.toString(log)); writer.endNode(); } private void writeLog(final int log, final JsonObject object) { object.addProperty("log", log); } private void writeMessageDate(final DateTime messageDate, final HierarchicalStreamWriter writer) { writer.startNode("MessageDate"); writer.setValue(messageDate.toString()); writer.endNode(); } private void writeMessageDate(final DateTime messageDate, final JsonObject object) { object.addProperty("message_date", messageDate.toString()); } private void writeMessageText(final String messageText, final HierarchicalStreamWriter writer) { writer.startNode("MessageText"); if (messageText != null) { writer.setValue(messageText); } writer.endNode(); } private void writeMessageText(final String messageText, final JsonObject object) { if (messageText != null) { object.addProperty("message_text", messageText); } else { object.add("message_text", JsonNull.INSTANCE); } } private void writeMoreInfo(final URI moreInfo, final HierarchicalStreamWriter writer) { writer.startNode("MoreInfo"); writer.setValue(moreInfo.toString()); writer.endNode(); } private void writeMoreInfo(final URI moreInfo, final JsonObject object) { object.addProperty("more_info", moreInfo.toString()); } private void writeRequestUrl(final URI requestUrl, final HierarchicalStreamWriter writer) { writer.startNode("RequestUrl"); writer.setValue(requestUrl.toString()); writer.endNode(); } private void writeRequestUrl(final URI requestUrl, final JsonObject object) { object.addProperty("request_url", requestUrl.toString()); } private void writeRequestMethod(final String requestMethod, final HierarchicalStreamWriter writer) { writer.startNode("RequestMethod"); writer.setValue(requestMethod); writer.endNode(); } private void writeRequestMethod(final String requestMethod, final JsonObject object) { object.addProperty("request_method", requestMethod); } private void writeRequestVariables(final String requestVariables, final HierarchicalStreamWriter writer) { writer.startNode("RequestVariables"); if (requestVariables != null) { writer.setValue(requestVariables); } writer.endNode(); } private void writeRequestVariables(final String requestVariables, final JsonObject object) { if (requestVariables != null) { object.addProperty("request_variables", requestVariables); } else { object.add("request_variables", JsonNull.INSTANCE); } } private void writeResponseHeaders(final String responseHeaders, final HierarchicalStreamWriter writer) { writer.startNode("ResponseHeaders"); if (responseHeaders != null) { writer.setValue(responseHeaders); } writer.endNode(); } private void writeResponseHeaders(final String responseHeaders, final JsonObject object) { if (responseHeaders != null) { object.addProperty("response_headers", responseHeaders); } else { object.add("response_headers", JsonNull.INSTANCE); } } private void writeResponseBody(final String responseBody, final HierarchicalStreamWriter writer) { writer.startNode("ResponseBody"); if (responseBody != null) { writer.setValue(responseBody); } writer.endNode(); } private void writeResponseBody(final String responseBody, final JsonObject object) { if (responseBody != null) { object.addProperty("response_body", responseBody); } else { object.add("response_body", JsonNull.INSTANCE); } } }
8,928
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AvailablePhoneNumberListConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/AvailablePhoneNumberListConverter.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.restcomm.connect.http.converter; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.dao.entities.AvailablePhoneNumber; import org.restcomm.connect.dao.entities.AvailablePhoneNumberList; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * @author [email protected] (Thomas Quintana) */ public final class AvailablePhoneNumberListConverter extends AbstractConverter { public AvailablePhoneNumberListConverter(final Configuration configuration) { super(configuration); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return AvailablePhoneNumberList.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final AvailablePhoneNumberList list = (AvailablePhoneNumberList) object; writer.startNode("AvailablePhoneNumbers"); for (final AvailablePhoneNumber number : list.getAvailablePhoneNumbers()) { context.convertAnother(number); } writer.endNode(); } }
2,036
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AvailablePhoneNumberConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/AvailablePhoneNumberConverter.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.restcomm.connect.http.converter; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.dao.entities.AvailablePhoneNumber; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; /** * @author [email protected] (Thomas Quintana) */ public final class AvailablePhoneNumberConverter extends AbstractConverter { public AvailablePhoneNumberConverter(final Configuration configuration) { super(configuration); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return AvailablePhoneNumber.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final AvailablePhoneNumber number = (AvailablePhoneNumber) object; writer.startNode("AvailablePhoneNumber"); writeFriendlyName(number.getFriendlyName(), writer); writePhoneNumber(number.getPhoneNumber(), writer); writeLata(number.getLata(), writer); writeRateCenter(number.getRateCenter(), writer); writeLatitude(number.getLatitude(), writer); writeLongitude(number.getLongitude(), writer); writeRegion(number.getRegion(), writer); writePostalCode(number.getPostalCode(), writer); writeIsoCountry(number.getIsoCountry(), writer); writeCapabilities(number.isVoiceCapable(), number.isSmsCapable(), number.isMmsCapable(), number.isFaxCapable(), writer); writer.endNode(); } private void writeLata(final Integer lata, final HierarchicalStreamWriter writer) { writer.startNode("Lata"); if (lata != null) { writer.setValue(lata.toString()); } writer.endNode(); } private void writeRateCenter(final String center, final HierarchicalStreamWriter writer) { writer.startNode("RateCenter"); if (center != null) { writer.setValue(center); } writer.endNode(); } private void writeLatitude(final Double latitude, final HierarchicalStreamWriter writer) { writer.startNode("Latitude"); if (latitude != null) { writer.setValue(latitude.toString()); } writer.endNode(); } private void writeLongitude(final Double longitude, final HierarchicalStreamWriter writer) { writer.startNode("Longitude"); if (longitude != null) { writer.setValue(longitude.toString()); } writer.endNode(); } private void writeRegion(final String region, final HierarchicalStreamWriter writer) { writer.startNode("Region"); if (region != null) { writer.setValue(region); } writer.endNode(); } private void writePostalCode(final Integer postalCode, final HierarchicalStreamWriter writer) { writer.startNode("PostalCode"); if (postalCode != null) { writer.setValue(postalCode.toString()); } writer.endNode(); } private void writeIsoCountry(final String country, final HierarchicalStreamWriter writer) { writer.startNode("IsoCountry"); if (country != null) { writer.setValue(country); } writer.endNode(); } }
4,193
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ConferenceDetailRecordConverter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/converter/ConferenceDetailRecordConverter.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.restcomm.connect.http.converter; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.dao.entities.ConferenceDetailRecord; import java.lang.reflect.Type; /** * @author maria */ @ThreadSafe public final class ConferenceDetailRecordConverter extends AbstractConverter implements JsonSerializer<ConferenceDetailRecord> { private final String apiVersion; public ConferenceDetailRecordConverter(final Configuration configuration) { super(configuration); apiVersion = configuration.getString("api-version"); } @SuppressWarnings("rawtypes") @Override public boolean canConvert(final Class klass) { return ConferenceDetailRecord.class.equals(klass); } @Override public void marshal(final Object object, final HierarchicalStreamWriter writer, final MarshallingContext context) { final ConferenceDetailRecord cdr = (ConferenceDetailRecord) object; writer.startNode("Conference"); writeSid(cdr.getSid(), writer); writeDateCreated(cdr.getDateCreated(), writer); writeDateUpdated(cdr.getDateUpdated(), writer); writeAccountSid(cdr.getAccountSid(), writer); writeStatus(cdr.getStatus(), writer); writeApiVersion(cdr.getApiVersion(), writer); writeFriendlyName(cdr.getFriendlyName(), writer); writeUri(cdr.getUri(), writer); writeSubResources(cdr, writer); writer.endNode(); } @Override public JsonElement serialize(final ConferenceDetailRecord cdr, Type type, final JsonSerializationContext context) { final JsonObject object = new JsonObject(); writeSid(cdr.getSid(), object); writeDateCreated(cdr.getDateCreated(), object); writeDateUpdated(cdr.getDateUpdated(), object); writeAccountSid(cdr.getAccountSid(), object); writeStatus(cdr.getStatus(), object); writeApiVersion(cdr.getApiVersion(), object); writeFriendlyName(cdr.getFriendlyName(), object); writeUri(cdr.getUri(), object); writeSubResources(cdr, object); return object; } private void writeSubResources(final ConferenceDetailRecord cdr, final HierarchicalStreamWriter writer) { writer.startNode("SubresourceUris"); writeParticipants(cdr, writer); writer.endNode(); } private void writeSubResources(final ConferenceDetailRecord cdr, final JsonObject object) { final JsonObject other = new JsonObject(); writeParticipants(cdr, other); object.add("subresource_uris", other); } private void writeParticipants(final ConferenceDetailRecord cdr, final HierarchicalStreamWriter writer) { writer.startNode("Participants"); writer.setValue(prefix(cdr) + "/Participants"); writer.endNode(); } private void writeParticipants(final ConferenceDetailRecord cdr, final JsonObject object) { object.addProperty("participants", prefix(cdr) + "/Participants.json"); } private String prefix(final ConferenceDetailRecord cdr) { final StringBuilder buffer = new StringBuilder(); buffer.append("/").append(apiVersion).append("/Accounts/"); buffer.append(cdr.getAccountSid().toString()).append("/Conferences/"); buffer.append(cdr.getSid()); return buffer.toString(); } }
4,537
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z