idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
32,300
public int getNumberOfResults ( ) { final String numberOfResults = agiReply . getAttribute ( "results" ) ; return numberOfResults == null ? 0 : Integer . parseInt ( numberOfResults ) ; }
Returns how many results have been recoginized . Usually there is only one result but if multiple rules in the grammar match multiple results may be returned .
47
31
32,301
void performPostCreationTasks ( ) { StatusAction statusAction = new StatusAction ( ) ; try { ResponseEvents events = CoherentManagerConnection . sendEventGeneratingAction ( statusAction , 1000 ) ; for ( ResponseEvent event : events . getEvents ( ) ) { if ( event instanceof StatusEvent ) { // do nothing. Creating the events will register the // channels, which is after all what we are trying to do. } } } catch ( IllegalArgumentException | IllegalStateException | IOException | TimeoutException e ) { logger . error ( e , e ) ; } }
Find all the channels that came into existence before startup . This can t be done during the Constructor call because it requires calls back to AsteriskPBX which isn t finished constructing until after the Constructor returns .
125
43
32,302
void mergeCalls ( CallTracker rhs ) { synchronized ( this . _associatedChannels ) { this . _associatedChannels . addAll ( rhs . _associatedChannels ) ; // not certain this is necessary but lets just tidy up a bit. rhs . _associatedChannels . clear ( ) ; } }
Used to merge two calls into a single call . This is required as during a masquerade a new channel is created an initially we will create a CallTracker for it . When the masquerade event finally turns up we will realise it belongs to an existing CallTracker and as such we need to merge the two CallTrackers .
68
65
32,303
public void remove ( Channel channel ) { synchronized ( this . _associatedChannels ) { int index = findChannel ( channel ) ; if ( index != - 1 ) { if ( logger . isDebugEnabled ( ) ) logger . debug ( "CallTracker removing channel: " + this . toString ( ) + " " + channel . getExtendedChannelName ( ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ this . _associatedChannels . remove ( index ) ; } } }
Remove a channel from the call .
113
7
32,304
ManagerEvent addMember ( BridgeEnterEvent event ) { List < BridgeEnterEvent > remaining = null ; synchronized ( members ) { if ( members . put ( event . getChannel ( ) , event ) == null && members . size ( ) == 2 ) { remaining = new ArrayList <> ( members . values ( ) ) ; } } if ( remaining == null ) { return null ; } logger . info ( "Members size " + remaining . size ( ) + " " + event ) ; BridgeEvent bridgeEvent = buildBridgeEvent ( BridgeEvent . BRIDGE_STATE_LINK , remaining ) ; logger . info ( "Bridge " + bridgeEvent . getChannel1 ( ) + " " + bridgeEvent . getChannel2 ( ) ) ; return bridgeEvent ; }
if there are exactly 2 members in the bridge return a BridgeEvent
161
13
32,305
ManagerEvent removeMember ( BridgeLeaveEvent event ) { List < BridgeEnterEvent > remaining = null ; synchronized ( members ) { if ( members . remove ( event . getChannel ( ) ) != null && members . size ( ) == 2 ) { remaining = new ArrayList <> ( members . values ( ) ) ; } } // If we didn't remove anything, or we aren't at exactly 2 members, // there's nothing else for us to do if ( remaining == null ) { return null ; } return buildBridgeEvent ( BridgeEvent . BRIDGE_STATE_UNLINK , remaining ) ; }
If there are exactly 2 members in the bridge return a BridgeEvent
127
13
32,306
public synchronized static Log getLog ( Class < ? > clazz ) { if ( slf4jLoggingAvailable == null ) { try { classLoader . loadClass ( "org.slf4j.Logger" ) ; slf4jLoggingAvailable = Boolean . TRUE ; } catch ( Exception e ) { slf4jLoggingAvailable = Boolean . FALSE ; } } if ( slf4jLoggingAvailable ) { try { return new Slf4JLogger ( clazz ) ; } catch ( Throwable e ) { slf4jLoggingAvailable = Boolean . FALSE ; } } if ( log4jLoggingAvailable == null ) { try { classLoader . loadClass ( "org.apache.log4j.Logger" ) ; log4jLoggingAvailable = Boolean . TRUE ; } catch ( Exception e ) { log4jLoggingAvailable = Boolean . FALSE ; } } if ( log4jLoggingAvailable ) { return new Log4JLogger ( clazz ) ; } if ( javaLoggingAvailable == null ) { try { classLoader . loadClass ( "java.util.logging.Logger" ) ; javaLoggingAvailable = Boolean . TRUE ; } catch ( Exception e ) { javaLoggingAvailable = Boolean . FALSE ; } } if ( javaLoggingAvailable ) { return new JavaLoggingLog ( clazz ) ; } return new NullLog ( ) ; }
Returns an instance of Log suitable for logging from the given class .
304
13
32,307
public void handleEvent ( final MasqueradeEvent b ) { if ( this . isConnectedToSelf ( b . getClone ( ) ) ) { // At this point we will actually have two CallTrackers // which we now need to merge into a single CallTracker. CallTracker original = findCall ( b . getOriginal ( ) ) ; CallTracker clone = findCall ( b . getClone ( ) ) ; if ( original != null && clone != null ) { clone . mergeCalls ( original ) ; clone . setState ( b . getCloneState ( ) ) ; this . evaluateState ( ) ; } else logger . warn ( "When processing masquradeEvent we could not find the expected calls. event=" //$NON-NLS-1$ + b . toString ( ) + " original=" + original + " clone=" + clone ) ; //$NON-NLS-1$ //$NON-NLS-2$ } }
We handle the masqurade event is it contains channel state information . During a masquerade we will have two channels for the one peer the original and the clone . As the clone is taking over from the original peer we now need to use that as true indicator of state .
206
56
32,308
public void handleEvent ( final NewChannelEvent b ) { // Very occasionally we get a null channel which we can't do anything // with so just throw the event away. // If we get a Console/dsp channel name it means that someone has // dialled from the asterisk // console. We just ignore these. if ( ( b . getChannel ( ) == null ) || ( b . getChannel ( ) . isConsole ( ) ) ) { return ; } if ( this . isConnectedToSelf ( b . getChannel ( ) ) ) { CallTracker call = this . registerChannel ( b . getChannel ( ) ) ; if ( call != null ) { call . setState ( b . getChannelState ( ) ) ; this . evaluateState ( ) ; } } }
When a new channel comes up associated it with the peer . Be warned a peer can have multiple calls associated with it .
164
24
32,309
private void evaluateState ( ) { synchronized ( this . callList ) { // Get the highest prioirty state from the set of calls. PeerState newState = PeerState . NOTSET ; for ( CallTracker call : this . callList ) { if ( call . getState ( ) . getPriority ( ) > newState . getPriority ( ) ) newState = call . getState ( ) ; } this . _state = newState ; } }
Called each time the state of a call changes to determine the Peers overall state .
97
18
32,310
public final void registerEventClass ( String eventType , Class < ? extends ManagerEvent > clazz ) throws IllegalArgumentException { Constructor < ? > defaultConstructor ; if ( ! ManagerEvent . class . isAssignableFrom ( clazz ) ) { throw new IllegalArgumentException ( clazz + " is not a ManagerEvent" ) ; } if ( ( clazz . getModifiers ( ) & Modifier . ABSTRACT ) != 0 ) { throw new IllegalArgumentException ( clazz + " is abstract" ) ; } try { defaultConstructor = clazz . getConstructor ( Object . class ) ; } catch ( NoSuchMethodException ex ) { throw new IllegalArgumentException ( clazz + " has no usable constructor" ) ; } if ( ( defaultConstructor . getModifiers ( ) & Modifier . PUBLIC ) == 0 ) { throw new IllegalArgumentException ( clazz + " has no public default constructor" ) ; } registeredEventClasses . put ( eventType . toLowerCase ( Locale . US ) , clazz ) ; logger . debug ( "Registered event type '" + eventType + "' (" + clazz + ")" ) ; }
Registers a new event class for the event given by eventType .
253
14
32,311
public void masquerade ( Channel channel ) { // If the channel doesn't have a caller id // preserve the existing one (as given this is a clone they should be // identical). // Asterisk doesn't always pass the caller ID on the channel hence this // protects us from Asterisk accidentally clearing the caller id. if ( channel . hasCallerID ( ) ) { this . _callerID = channel . getCallerID ( ) ; } else if ( this . _callerID != null && ( ( ChannelImpl ) channel ) . _callerID != null ) { // Force the caller id back into the channel so it has one as well. PBX pbx = PBXFactory . getActivePBX ( ) ; if ( this . _callerID != null ) { ( ( ChannelImpl ) channel ) . _callerID = pbx . buildCallerID ( this . _callerID . getNumber ( ) , this . _callerID . getName ( ) ) ; } } this . _muted = channel . isMute ( ) ; this . _parked = channel . isParked ( ) ; // just in case the original channel is part way through a sweep by the // PeerMonitor // marking the sweep as true will stop the new clone being hungup as it // may not have been around when the sweep started. this . _marked = true ; this . _sweepStartTime = null ; }
designed for use by the ChannelProxy when a channel is being cloned as a result of Asterisk undertaking an Masquerade . This is not intended to be a complete clone just the key elements that we generally track on our side rather than getting directly from asterisk .
306
52
32,312
private void validateChannelName ( final String channelName ) throws InvalidChannelName { if ( ! this . _isConsole ) { if ( ! TechType . hasValidTech ( channelName ) ) { throw new InvalidChannelName ( "Invalid channelName: " + channelName + ". Unknown tech." ) ; //$NON-NLS-1$ //$NON-NLS-2$ } // Check we have the expected hypen final int hypen = channelName . indexOf ( "-" ) ; //$NON-NLS-1$ if ( hypen == - 1 ) { throw new InvalidChannelName ( "Invalid channelName: " + channelName + ". Missing hypen." ) ; //$NON-NLS-1$ //$NON-NLS-2$ } // Check we have the expected slash final int slash = channelName . indexOf ( "/" ) ; //$NON-NLS-1$ if ( slash == - 1 ) { throw new InvalidChannelName ( "Invalid channelName: " + channelName + ". Missing slash." ) ; //$NON-NLS-1$ //$NON-NLS-2$ } // Check that the hypen is after the slash. if ( hypen < slash ) { throw new InvalidChannelName ( "Invalid channelName: " + channelName + ". Hypen must be after the slash." ) ; //$NON-NLS-1$ //$NON-NLS-2$ } // Check that there is at least one characters between the hypen and // the // slash if ( ( hypen - slash ) < 2 ) { throw new InvalidChannelName ( "Invalid channelName: " + channelName //$NON-NLS-1$ + ". Must be one character between the hypen and the slash." ) ; //$NON-NLS-1$ } // Check that the channel sequence number is at least 1 character // long. if ( ( channelName . length ( ) - hypen ) < 2 ) { throw new InvalidChannelName ( "Invalid channelName: " + channelName //$NON-NLS-1$ + ". The channel sequence number must be at least 1 character." ) ; //$NON-NLS-1$ } } }
validates the channel name . Validate is to be called after the channel has been cleaned .
486
19
32,313
public boolean sameUniqueID ( String uniqueID ) { boolean equals = false ; if ( ( this . _uniqueID . compareTo ( ChannelImpl . UNKNOWN_UNIQUE_ID ) != 0 ) && ( uniqueID . compareTo ( ChannelImpl . UNKNOWN_UNIQUE_ID ) != 0 ) ) { if ( this . _uniqueID . compareTo ( uniqueID ) == 0 ) { equals = true ; } } return equals ; }
Try to match a channel based solely on its unique ID
96
11
32,314
@ Override public void notifyHangupListeners ( Integer cause , String causeText ) { this . _isLive = false ; if ( this . hangupListener != null ) { this . hangupListener . channelHangup ( this , cause , causeText ) ; } else { logger . warn ( "Hangup listener is null" ) ; } }
Called by Peer when we have been hungup . This can happen when Peer receives a HangupEvent or during a periodic sweep done by PeerMonitor to find the status of all channels . Notify any listeners that this channel has been hung up .
77
50
32,315
@ Override public String getExtendedChannelName ( ) { final StringBuilder name = new StringBuilder ( ) ; if ( this . _isInAction ) { name . append ( this . _actionPrefix ) ; name . append ( "/" ) ; //$NON-NLS-1$ } name . append ( this . _channelName ) ; if ( this . _isMasqueraded ) { name . append ( ChannelImpl . MASQ ) ; } if ( this . _isZombie ) { name . append ( ChannelImpl . ZOMBIE ) ; } return name . toString ( ) ; }
Returns the full channel name including the masquerade prefix and the zombie suffix .
132
15
32,316
@ SuppressWarnings ( "unchecked" ) protected AgiScript createAgiScriptInstance ( String className ) { Class < ? > tmpClass ; Class < AgiScript > agiScriptClass ; Constructor < AgiScript > constructor ; AgiScript agiScript ; agiScript = null ; try { tmpClass = getClassLoader ( ) . loadClass ( className ) ; } catch ( ClassNotFoundException e1 ) { logger . debug ( "Unable to create AgiScript instance of type " + className + ": Class not found, make sure the class exists and is available on the CLASSPATH" ) ; return null ; } if ( ! AgiScript . class . isAssignableFrom ( tmpClass ) ) { logger . warn ( "Unable to create AgiScript instance of type " + className + ": Class does not implement the AgiScript interface" ) ; return null ; } agiScriptClass = ( Class < AgiScript > ) tmpClass ; try { constructor = agiScriptClass . getConstructor ( ) ; agiScript = constructor . newInstance ( ) ; } catch ( Exception e ) { logger . warn ( "Unable to create AgiScript instance of type " + className , e ) ; } return agiScript ; }
Creates a new instance of an AGI script .
280
11
32,317
protected String escapeAndQuote ( String s ) { String tmp ; if ( s == null ) { return "\"\"" ; } tmp = s ; tmp = tmp . replaceAll ( "\\\\" , "\\\\\\\\" ) ; tmp = tmp . replaceAll ( "\\\"" , "\\\\\"" ) ; tmp = tmp . replaceAll ( "\\\n" , "" ) ; // filter newline return "\"" + tmp + "\"" ; // add quotes }
Escapes and quotes a given String according to the rules set by Asterisk s AGI .
100
19
32,318
public void setVariables ( Map < String , String > variables ) { if ( this . variables != null ) { this . variables . putAll ( variables ) ; } else { this . variables = variables ; } }
Sets the variables to set on the originated call .
45
11
32,319
public void setControlDigits ( String forwardDigit , String rewindDigit , String pauseDigit ) { this . forwardDigit = forwardDigit ; this . rewindDigit = rewindDigit ; this . pauseDigit = pauseDigit ; }
Sets the control digits for fast forward rewind and pause .
57
13
32,320
Collection < AsteriskChannel > getChannels ( ) { Collection < AsteriskChannel > copy ; synchronized ( channels ) { copy = new ArrayList <> ( channels . size ( ) + 2 ) ; for ( AsteriskChannel channel : channels . values ( ) ) { if ( channel . getState ( ) != ChannelState . HUNGUP ) { copy . add ( channel ) ; } } } return copy ; }
Returns a collection of all active AsteriskChannels .
87
11
32,321
AsteriskChannelImpl getChannelImplByName ( String name ) { Date dateOfCreation = null ; AsteriskChannelImpl channel = null ; if ( name == null ) { return null ; } synchronized ( channels ) { for ( AsteriskChannelImpl tmp : channels . values ( ) ) { if ( name . equals ( tmp . getName ( ) ) ) { // return the most recent channel or when dates are similar, // the active one if ( dateOfCreation == null || tmp . getDateOfCreation ( ) . after ( dateOfCreation ) || ( tmp . getDateOfCreation ( ) . equals ( dateOfCreation ) && tmp . getState ( ) != ChannelState . HUNGUP ) ) { channel = tmp ; dateOfCreation = channel . getDateOfCreation ( ) ; } } } } return channel ; }
Returns a channel from the ChannelManager s cache with the given name If multiple channels are found returns the most recently CREATED one . If two channels with the very same date exist avoid HUNGUP ones .
182
41
32,322
AsteriskChannelImpl getChannelImplByNameAndActive ( String name ) { // In non bristuffed AST 1.2, we don't have uniqueid header to match the // channel // So we must use the channel name // Channel name is unique at any give moment in the * server // But asterisk-java keeps Hungup channels for a while. // We don't want to retrieve hungup channels. AsteriskChannelImpl channel = null ; if ( name == null ) { return null ; } synchronized ( channels ) { for ( AsteriskChannelImpl tmp : channels . values ( ) ) { if ( name . equals ( tmp . getName ( ) ) && tmp . getState ( ) != ChannelState . HUNGUP ) { channel = tmp ; } } } return channel ; }
Returns a NON - HUNGUP channel from the ChannelManager s cache with the given name .
164
19
32,323
static private void syncDial ( ) { try { PBX pbx = PBXFactory . getActivePBX ( ) ; // The trunk MUST match the section header (e.g. [default]) that // appears // in your /etc/asterisk/sip.d file (assuming you are using a SIP // trunk). // The trunk is used to select which SIP trunk to dial through. Trunk trunk = pbx . buildTrunk ( "default" ) ; // We are going to dial from extension 100 EndPoint from = pbx . buildEndPoint ( TechType . SIP , "100" ) ; // The caller ID to show on extension 100. CallerID fromCallerID = pbx . buildCallerID ( "100" , "My Phone" ) ; // The caller ID to display on the called parties phone CallerID toCallerID = pbx . buildCallerID ( "83208100" , "Asterisk Java is calling" ) ; // The party we are going to call. EndPoint to = pbx . buildEndPoint ( TechType . SIP , trunk , "5551234" ) ; // Trunk is currently ignored so set to null // The call is dialed and only returns when the call comes up (it // doesn't wait for the remote end to answer). DialActivity dial = pbx . dial ( from , fromCallerID , to , toCallerID ) ; Call call = dial . getNewCall ( ) ; Thread . sleep ( 20000 ) ; logger . warn ( "Hanging up" ) ; pbx . hangup ( call ) ; } catch ( PBXException | InterruptedException e ) { System . out . println ( e ) ; } }
Simple synchronous dial . The dial method won t return until the dial starts . Using this method will lockup your UI until the dial starts . For better control use the async Dial method below .
376
39
32,324
public final Logger getLogger ( ) { if ( logger == null ) { logger = LoggerFactory . getLogger ( clazz ) ; } if ( logger instanceof LocationAwareLogger ) { return new LocationAwareWrapper ( FQCN , ( LocationAwareLogger ) logger ) ; } return this . logger ; }
Return the native Logger instance we are using .
73
10
32,325
void initialize ( ) throws ManagerCommunicationException { ResponseEvents re ; re = server . sendEventGeneratingAction ( new AgentsAction ( ) ) ; for ( ManagerEvent event : re . getEvents ( ) ) { if ( event instanceof AgentsEvent ) { logger . info ( event ) ; handleAgentsEvent ( ( AgentsEvent ) event ) ; } } }
Retrieves all agents registered at Asterisk server by sending an AgentsAction .
76
16
32,326
void handleAgentsEvent ( AgentsEvent event ) { AsteriskAgentImpl agent = new AsteriskAgentImpl ( server , event . getName ( ) , "Agent/" + event . getAgent ( ) , AgentState . valueOf ( event . getStatus ( ) ) ) ; logger . info ( "Adding agent " + agent . getName ( ) + "(" + agent . getAgentId ( ) + ")" ) ; addAgent ( agent ) ; }
On AgentsEvent create a new Agent .
96
8
32,327
private void addAgent ( AsteriskAgentImpl agent ) { synchronized ( agents ) { agents . put ( agent . getAgentId ( ) , agent ) ; } server . fireNewAgent ( agent ) ; }
Add a new agent to the manager .
43
8
32,328
void handleAgentCalledEvent ( AgentCalledEvent event ) { AsteriskAgentImpl agent = getAgentByAgentId ( event . getAgentCalled ( ) ) ; if ( agent == null ) { logger . error ( "Ignored AgentCalledEvent for unknown agent " + event . getAgentCalled ( ) ) ; return ; } updateRingingAgents ( event . getChannelCalling ( ) , agent ) ; updateAgentState ( agent , AgentState . AGENT_RINGING ) ; }
Update state if agent was called .
107
7
32,329
private void updateAgentState ( AsteriskAgentImpl agent , AgentState newState ) { logger . info ( "Set state of agent " + agent . getAgentId ( ) + " to " + newState ) ; synchronized ( agent ) { agent . updateState ( newState ) ; } }
Set state of agent .
61
5
32,330
private void updateRingingAgents ( String channelCalling , AsteriskAgentImpl agent ) { synchronized ( ringingAgents ) { if ( ringingAgents . containsKey ( channelCalling ) ) { updateAgentState ( ringingAgents . get ( channelCalling ) , AgentState . AGENT_IDLE ) ; } ringingAgents . put ( channelCalling , agent ) ; } }
Updates state of agent if the call in a queue was redirect to the next agent because the ringed agent doesn t answer the call . After reset state put the next agent in charge .
79
38
32,331
void handleAgentConnectEvent ( AgentConnectEvent event ) { AsteriskAgentImpl agent = getAgentByAgentId ( event . getChannel ( ) ) ; if ( agent == null ) { logger . error ( "Ignored AgentConnectEvent for unknown agent " + event . getChannel ( ) ) ; return ; } agent . updateState ( AgentState . AGENT_ONCALL ) ; }
Update state if agent was connected to channel .
82
9
32,332
Collection < AsteriskAgent > getAgents ( ) { Collection < AsteriskAgent > copy ; synchronized ( agents ) { copy = new ArrayList < AsteriskAgent > ( agents . values ( ) ) ; } return copy ; }
Return all agents registered at Asterisk server .
48
9
32,333
void handleAgentCompleteEvent ( AgentCompleteEvent event ) { AsteriskAgentImpl agent = getAgentByAgentId ( event . getChannel ( ) ) ; if ( agent == null ) { logger . error ( "Ignored AgentCompleteEvent for unknown agent " + event . getChannel ( ) ) ; return ; } agent . updateState ( AgentState . AGENT_IDLE ) ; }
Change state if connected call was terminated .
81
8
32,334
public void setReason ( String s ) { int spaceIdx ; if ( s == null ) { return ; } spaceIdx = s . indexOf ( ' ' ) ; if ( spaceIdx <= 0 ) { spaceIdx = s . length ( ) ; } try { this . reason = Integer . valueOf ( s . substring ( 0 , spaceIdx ) ) ; } catch ( NumberFormatException e ) { return ; } if ( s . length ( ) > spaceIdx + 3 ) { this . reasonTxt = s . substring ( spaceIdx + 3 , s . length ( ) ) ; } }
Sets the reason for disabling logging .
134
8
32,335
private void fireChainListeners ( ManagerEvent event ) { synchronized ( this . chainListeners ) { for ( ManagerEventListener listener : this . chainListeners ) listener . onManagerEvent ( event ) ; } }
dispatch the event to the chainListener if they exist .
45
12
32,336
public static String getInternalActionId ( String actionId ) { final int delimiterIndex ; if ( actionId == null ) { return null ; } delimiterIndex = actionId . indexOf ( INTERNAL_ACTION_ID_DELIMITER ) ; if ( delimiterIndex > 0 ) { return actionId . substring ( 0 , delimiterIndex ) ; } return null ; }
Returns the internal action id contained in the given action id .
84
12
32,337
public static String stripInternalActionId ( String actionId ) { int delimiterIndex ; delimiterIndex = actionId . indexOf ( INTERNAL_ACTION_ID_DELIMITER ) ; if ( delimiterIndex > 0 ) { if ( actionId . length ( ) > delimiterIndex + 1 ) { return actionId . substring ( delimiterIndex + 1 ) ; } return null ; } return null ; }
Strips the internal action id from the given action id .
91
13
32,338
public static String addInternalActionId ( String actionId , String internalActionId ) { if ( actionId == null ) { return internalActionId + INTERNAL_ACTION_ID_DELIMITER ; } return internalActionId + INTERNAL_ACTION_ID_DELIMITER + actionId ; }
Adds the internal action id to the given action id .
69
11
32,339
@ Deprecated public static void main ( String [ ] args ) throws Exception { final AgiServer server ; server = new DefaultAgiServer ( ) ; server . startup ( ) ; }
Creates a new DefaultAgiServer and starts it .
39
12
32,340
public String getVariable ( final Channel channel , final String variableName ) { String value = "" ; final GetVarAction var = new GetVarAction ( channel , variableName ) ; try { PBX pbx = PBXFactory . getActivePBX ( ) ; if ( ! pbx . waitForChannelToQuiescent ( channel , 3000 ) ) throw new PBXException ( "Channel: " + channel + " cannot be retrieved as it is still in transition." ) ; ManagerResponse convertedResponse = sendAction ( var , 500 ) ; if ( convertedResponse != null ) { value = convertedResponse . getAttribute ( "value" ) ; //$NON-NLS-1$ if ( value == null ) value = "" ; CoherentManagerConnection . logger . debug ( "getVarAction returned name:" + variableName + " value:" + value ) ; //$NON-NLS-1$ //$NON-NLS-2$ } } catch ( final Exception e ) { CoherentManagerConnection . logger . debug ( e , e ) ; CoherentManagerConnection . logger . error ( "getVariable: " + e ) ; //$NON-NLS-1$ } return value ; }
Retrieves and returns the value of a variable associated with a channel . If the variable is empty or null then an empty string is returned .
259
29
32,341
public static void sendActionNoWait ( final ManagerAction action ) { final Thread background = new Thread ( ) { @ Override public void run ( ) { try { CoherentManagerConnection . sendAction ( action , 5000 ) ; } catch ( final Exception e ) { CoherentManagerConnection . logger . error ( e , e ) ; } } } ; background . setName ( "sendActionNoWait" ) ; //$NON-NLS-1$ background . setDaemon ( true ) ; background . start ( ) ; }
Allows the caller to send an action to asterisk without waiting for the response . You should only use this if you don t care whether the action actually succeeds .
112
32
32,342
public static ManagerResponse sendAction ( final ManagerAction action , final int timeout ) throws IllegalArgumentException , IllegalStateException , IOException , TimeoutException { if ( logger . isDebugEnabled ( ) ) CoherentManagerConnection . logger . debug ( "Sending Action: " + action . toString ( ) ) ; //$NON-NLS-1$ CoherentManagerConnection . getInstance ( ) ; if ( ( CoherentManagerConnection . managerConnection != null ) && ( CoherentManagerConnection . managerConnection . getState ( ) == ManagerConnectionState . CONNECTED ) ) { final org . asteriskjava . manager . action . ManagerAction ajAction = action . getAJAction ( ) ; org . asteriskjava . manager . response . ManagerResponse response = CoherentManagerConnection . managerConnection . sendAction ( ajAction , timeout ) ; ManagerResponse convertedResponse = null ; // UserEventActions always return a null if ( response != null ) convertedResponse = CoherentEventFactory . build ( response ) ; if ( ( convertedResponse != null ) && ( convertedResponse . getResponse ( ) . compareToIgnoreCase ( "Error" ) == 0 ) ) //$NON-NLS-1$ { CoherentManagerConnection . logger . warn ( "Action '" + ajAction + "' failed, Response: " //$NON-NLS-1$ //$NON-NLS-2$ + convertedResponse . getResponse ( ) + " Message: " + convertedResponse . getMessage ( ) ) ; //$NON-NLS-1$ } return convertedResponse ; } throw new IllegalStateException ( "not connected." ) ; //$NON-NLS-1$ }
Sends an Asterisk action and waits for a ManagerRespose .
367
14
32,343
public Map < Integer , String > getCategories ( ) { if ( categories == null ) { categories = new TreeMap <> ( ) ; } Map < String , Object > responseMap = super . getAttributes ( ) ; for ( Entry < String , Object > response : responseMap . entrySet ( ) ) { String key = response . getKey ( ) ; if ( key . toLowerCase ( Locale . US ) . contains ( "category" ) ) { String [ ] keyParts = key . split ( "-" ) ; // if it doesn't have at least category-XXXXXX, skip if ( keyParts . length < 2 ) continue ; // try to get the number of this category, skip if we mess up Integer categoryNumber ; try { categoryNumber = Integer . parseInt ( keyParts [ 1 ] ) ; } catch ( Exception exception ) { continue ; } categories . put ( categoryNumber , ( String ) response . getValue ( ) ) ; } } return categories ; }
Returns the map of category numbers to category names .
207
10
32,344
public Map < Integer , String > getLines ( int categoryNumber ) { if ( lines == null ) { lines = new TreeMap <> ( ) ; } Map < String , Object > responseMap = super . getAttributes ( ) ; for ( Entry < String , Object > response : responseMap . entrySet ( ) ) { String key = response . getKey ( ) ; if ( key . toLowerCase ( Locale . US ) . contains ( "line" ) ) { String [ ] keyParts = key . split ( "-" ) ; // if it doesn't have at least line-XXXXXX-XXXXXX, skip if ( keyParts . length < 3 ) { continue ; } // try to get the number of this category, skip if we mess up Integer potentialCategoryNumber ; try { potentialCategoryNumber = Integer . parseInt ( keyParts [ 1 ] ) ; } catch ( Exception exception ) { continue ; } // try to get the number of this line, skip if we mess up Integer potentialLineNumber ; try { potentialLineNumber = Integer . parseInt ( keyParts [ 2 ] ) ; } catch ( Exception exception ) { continue ; } // get the List out for placing stuff in Map < Integer , String > linesForCategory = lines . get ( potentialCategoryNumber ) ; if ( linesForCategory == null ) { linesForCategory = new TreeMap <> ( ) ; } // put the line we just parsed into the line map for this category linesForCategory . put ( potentialLineNumber , ( String ) response . getValue ( ) ) ; if ( ! lines . containsKey ( potentialCategoryNumber ) ) { lines . put ( potentialCategoryNumber , linesForCategory ) ; } } } return lines . get ( categoryNumber ) ; }
Returns the map of line number to line value for a given category .
366
14
32,345
protected void ping ( ManagerConnection c ) { try { if ( timeout <= 0 ) { c . sendAction ( new PingAction ( ) , null ) ; } else { final ManagerResponse response ; response = c . sendAction ( new PingAction ( ) , timeout ) ; logger . debug ( "Ping response '" + response + "' for " + c . toString ( ) ) ; } } catch ( Exception e ) { logger . warn ( "Exception on sending Ping to " + c . toString ( ) , e ) ; } }
Sends a ping to Asterisk and logs any errors that may occur .
112
15
32,346
public void addCommand ( String action , String cat , String var , String value , String match ) { // for convienence of reference, shorter! final String stringCounter = String . format ( "%06d" , this . actionCounter ) ; if ( action != null ) { actions . put ( "Action-" + stringCounter , action ) ; } if ( cat != null ) { actions . put ( "Cat-" + stringCounter , cat ) ; } if ( var != null ) { actions . put ( "Var-" + stringCounter , var ) ; } if ( value != null ) { actions . put ( "Value-" + stringCounter , value ) ; } if ( match != null ) { actions . put ( "Match-" + stringCounter , match ) ; } this . actionCounter ++ ; }
Adds a command to update a config file while sparing you the details of the Manager s required syntax . If you want to omit one of the command s sections provide a null value to this method . The command index will be incremented even if you supply a null for all parameters though the map will be unaffected .
168
62
32,347
public void setAttributes ( Map < String , String > actions ) { this . actions = actions ; this . actionCounter = actions . keySet ( ) . size ( ) ; }
You may use this field to directly programmatically add your own Map of key value pairs that you would like to send for this command . Setting your own map will reset the command index to the number of keys in the Map
37
44
32,348
public void publish ( ) { /* * Some care is required here to correctly swap the DataBuffers, * but not hold the synchronization object while compiling stats * (a potentially long computation). This ensures that continued * data collection (calls to noteValue()) will not be blocked for any * significant period. */ DataBuffer tmp = null ; Lock l = null ; synchronized ( swapLock ) { // Swap buffers tmp = current ; current = previous ; previous = tmp ; // Start collection in the new "current" buffer l = current . getLock ( ) ; l . lock ( ) ; try { current . startCollection ( ) ; } finally { l . unlock ( ) ; } // Grab lock on new "previous" buffer l = tmp . getLock ( ) ; l . lock ( ) ; } // Release synchronizaton *before* publishing data try { tmp . endCollection ( ) ; publish ( tmp ) ; } finally { l . unlock ( ) ; } }
Swaps the data collection buffers and computes statistics about the data collected up til now .
200
18
32,349
public double [ ] getPercentiles ( double [ ] percents , double [ ] percentiles ) { for ( int i = 0 ; i < percents . length ; i ++ ) { percentiles [ i ] = computePercentile ( percents [ i ] ) ; } return percentiles ; }
Gets the requested percentile statistics .
65
7
32,350
public static boolean applyFilters ( Object event , Set < EventFilter > filters , StatsTimer filterStats , String invokerDesc , Logger logger ) { if ( filters . isEmpty ( ) ) { return true ; } Stopwatch filterStart = filterStats . start ( ) ; try { for ( EventFilter filter : filters ) { if ( ! filter . apply ( event ) ) { logger . debug ( "Event: " + event + " filtered out for : " + invokerDesc + " due to the filter: " + filter ) ; return false ; } } return true ; } finally { filterStart . stop ( ) ; } }
Utility method to apply filters for an event this can be used both by publisher & subscriber code .
133
20
32,351
protected Predicate < Object > getEqualFilter ( ) { String xpath = getXPath ( getChild ( 0 ) ) ; Tree valueNode = getChild ( 1 ) ; switch ( valueNode . getType ( ) ) { case NUMBER : Number value = ( Number ) ( ( ValueTreeNode ) valueNode ) . getValue ( ) ; return new PathValueEventFilter ( xpath , new NumericValuePredicate ( value , "=" ) ) ; case STRING : String sValue = ( String ) ( ( ValueTreeNode ) valueNode ) . getValue ( ) ; return new PathValueEventFilter ( xpath , new StringValuePredicate ( sValue ) ) ; case TRUE : return new PathValueEventFilter ( xpath , BooleanValuePredicate . TRUE ) ; case FALSE : return new PathValueEventFilter ( xpath , BooleanValuePredicate . FALSE ) ; case NULL : return new PathValueEventFilter ( xpath , NullValuePredicate . INSTANCE ) ; case XPATH_FUN_NAME : String aPath = ( String ) ( ( ValueTreeNode ) valueNode ) . getValue ( ) ; return new PathValueEventFilter ( xpath , new XPathValuePredicate ( aPath , xpath ) ) ; case TIME_MILLIS_FUN_NAME : TimeMillisValueTreeNode timeNode = ( TimeMillisValueTreeNode ) valueNode ; return new PathValueEventFilter ( xpath , new TimeMillisValuePredicate ( timeNode . getValueFormat ( ) , timeNode . getValue ( ) , "=" ) ) ; case TIME_STRING_FUN_NAME : TimeStringValueTreeNode timeStringNode = ( TimeStringValueTreeNode ) valueNode ; return new PathValueEventFilter ( xpath , new TimeStringValuePredicate ( timeStringNode . getValueTimeFormat ( ) , timeStringNode . getInputTimeFormat ( ) , timeStringNode . getValue ( ) , "=" ) ) ; default : throw new UnexpectedTokenException ( valueNode , "Number" , "String" , "TRUE" , "FALSE" ) ; } }
but I can t get ANTLR to generated nested tree with added node .
450
16
32,352
public static boolean equalObjects ( Object o1 , Object o2 ) { if ( o1 == null ) { return ( o2 == null ) ; } else if ( o2 == null ) { return false ; } else { return o1 . equals ( o2 ) ; } }
Utility function to make it easy to compare two possibly null objects .
60
14
32,353
@ SuppressWarnings ( "deprecation" ) @ Override public < S extends T > S save ( final S entity ) { if ( arangoOperations . getVersion ( ) . getVersion ( ) . compareTo ( "3.4.0" ) < 0 ) { arangoOperations . upsert ( entity , UpsertStrategy . REPLACE ) ; } else { arangoOperations . repsert ( entity ) ; } return entity ; }
Saves the passed entity to the database using upsert from the template
100
14
32,354
@ SuppressWarnings ( "deprecation" ) @ Override public < S extends T > Iterable < S > saveAll ( final Iterable < S > entities ) { if ( arangoOperations . getVersion ( ) . getVersion ( ) . compareTo ( "3.4.0" ) < 0 ) { arangoOperations . upsert ( entities , UpsertStrategy . UPDATE ) ; } else { final S first = StreamSupport . stream ( entities . spliterator ( ) , false ) . findFirst ( ) . get ( ) ; arangoOperations . repsert ( entities , ( Class < S > ) first . getClass ( ) ) ; } return entities ; }
Saves the given iterable of entities to the database
149
11
32,355
@ Override public Optional < T > findById ( final ID id ) { return arangoOperations . find ( id , domainClass ) ; }
Finds if a document with the given id exists in the database
31
13
32,356
@ Override public Iterable < T > findAllById ( final Iterable < ID > ids ) { return arangoOperations . find ( ids , domainClass ) ; }
Finds all documents with the an id or key in the argument
39
13
32,357
@ Override public void delete ( final T entity ) { String id = null ; try { id = ( String ) arangoOperations . getConverter ( ) . getMappingContext ( ) . getPersistentEntity ( domainClass ) . getIdProperty ( ) . getField ( ) . get ( entity ) ; } catch ( final IllegalAccessException e ) { e . printStackTrace ( ) ; } arangoOperations . delete ( id , domainClass ) ; }
Deletes document in the database representing the given object by getting it s id
102
15
32,358
@ Override public Iterable < T > findAll ( final Sort sort ) { return new Iterable < T > ( ) { @ Override public Iterator < T > iterator ( ) { return findAllInternal ( sort , null , new HashMap <> ( ) ) ; } } ; }
Gets all documents in the collection for the class type of this repository with the given sort applied
62
19
32,359
@ Override public Page < T > findAll ( final Pageable pageable ) { if ( pageable == null ) { LOGGER . debug ( "Pageable in findAll(Pageable) is null" ) ; } final ArangoCursor < T > result = findAllInternal ( pageable , null , new HashMap <> ( ) ) ; final List < T > content = result . asListRemaining ( ) ; return new PageImpl <> ( content , pageable , result . getStats ( ) . getFullCount ( ) ) ; }
Gets all documents in the collection for the class type of this repository with pagination
118
17
32,360
@ Override public < S extends T > Optional < S > findOne ( final Example < S > example ) { final ArangoCursor cursor = findAllInternal ( ( Pageable ) null , example , new HashMap ( ) ) ; return cursor . hasNext ( ) ? Optional . ofNullable ( ( S ) cursor . next ( ) ) : Optional . empty ( ) ; }
Finds one document which matches the given example object
81
10
32,361
@ Override public < S extends T > Iterable < S > findAll ( final Example < S > example ) { final ArangoCursor cursor = findAllInternal ( ( Pageable ) null , example , new HashMap <> ( ) ) ; return cursor ; }
Finds all documents which match with the given example
57
10
32,362
@ Override public < S extends T > Iterable < S > findAll ( final Example < S > example , final Sort sort ) { final ArangoCursor cursor = findAllInternal ( sort , example , new HashMap ( ) ) ; return cursor ; }
Finds all documents which match with the given example then apply the given sort to results
55
17
32,363
@ Override public < S extends T > Page < S > findAll ( final Example < S > example , final Pageable pageable ) { final ArangoCursor cursor = findAllInternal ( pageable , example , new HashMap ( ) ) ; final List < T > content = cursor . asListRemaining ( ) ; return new PageImpl <> ( ( List < S > ) content , pageable , cursor . getStats ( ) . getFullCount ( ) ) ; }
Finds all documents which match with the given example with pagination
102
13
32,364
@ Override public < S extends T > long count ( final Example < S > example ) { final Map < String , Object > bindVars = new HashMap <> ( ) ; final String predicate = exampleConverter . convertExampleToPredicate ( example , bindVars ) ; final String filter = predicate . length ( ) == 0 ? "" : " FILTER " + predicate ; final String query = String . format ( "FOR e IN %s%s COLLECT WITH COUNT INTO length RETURN length" , getCollectionName ( ) , filter ) ; final ArangoCursor < Long > cursor = arangoOperations . query ( query , bindVars , null , Long . class ) ; return cursor . next ( ) ; }
Counts the number of documents in the collection which match with the given example
157
15
32,365
private String escapeSpecialCharacters ( final String string ) { final StringBuilder escaped = new StringBuilder ( ) ; for ( final char character : string . toCharArray ( ) ) { if ( character == ' ' || character == ' ' || character == ' ' ) { escaped . append ( ' ' ) ; } escaped . append ( character ) ; } return escaped . toString ( ) ; }
Escapes special characters which could be used in an operand of LIKE operator
81
15
32,366
public static String determineDocumentKeyFromId ( final String id ) { final int lastSlash = id . lastIndexOf ( KEY_DELIMITER ) ; return id . substring ( lastSlash + 1 ) ; }
Provides a substring with _key .
49
9
32,367
public static String determineCollectionFromId ( final String id ) { final int delimiter = id . indexOf ( KEY_DELIMITER ) ; return delimiter == - 1 ? null : id . substring ( 0 , delimiter ) ; }
Provides a substring with collection name .
53
9
32,368
private boolean shouldIgnoreCase ( final Part part ) { final Class < ? > propertyClass = part . getProperty ( ) . getLeafProperty ( ) . getType ( ) ; final boolean isLowerable = String . class . isAssignableFrom ( propertyClass ) ; final boolean shouldIgnoreCase = part . shouldIgnoreCase ( ) != Part . IgnoreCaseType . NEVER && isLowerable && ! UNSUPPORTED_IGNORE_CASE . contains ( part . getType ( ) ) ; if ( part . shouldIgnoreCase ( ) == Part . IgnoreCaseType . ALWAYS && ( ! isLowerable || UNSUPPORTED_IGNORE_CASE . contains ( part . getType ( ) ) ) ) { LOGGER . debug ( "Ignoring case for \"{}\" type is meaningless" , propertyClass ) ; } return shouldIgnoreCase ; }
Determines whether the case for a Part should be ignored based on property type and IgnoreCase keywords in the method name
188
24
32,369
private void checkUniquePoint ( final Point point ) { final boolean isStillUnique = ( uniquePoint == null || uniquePoint . equals ( point ) ) ; if ( ! isStillUnique ) { isUnique = false ; } if ( ! geoFields . isEmpty ( ) ) { Assert . isTrue ( uniquePoint == null || uniquePoint . equals ( point ) , "Different Points are used - Distance is ambiguous" ) ; uniquePoint = point ; } }
Ensures that Points used in geospatial parts of non - nested properties are the same in case geospatial return type is expected
97
28
32,370
private void checkUniqueLocation ( final Part part ) { isUnique = isUnique == null ? true : isUnique ; isUnique = ( uniqueLocation == null || uniqueLocation . equals ( ignorePropertyCase ( part ) ) ) ? isUnique : false ; if ( ! geoFields . isEmpty ( ) ) { Assert . isTrue ( isUnique , "Different location fields are used - Distance is ambiguous" ) ; } uniqueLocation = ignorePropertyCase ( part ) ; }
Ensures that the same geo fields are used in geospatial parts of non - nested properties are the same in case geospatial return type is expected
99
32
32,371
public Object convertResult ( final Class < ? > type ) { try { if ( type . isArray ( ) ) { return TYPE_MAP . get ( "array" ) . invoke ( this ) ; } if ( ! TYPE_MAP . containsKey ( type ) ) { return getNext ( result ) ; } return TYPE_MAP . get ( type ) . invoke ( this ) ; } catch ( final Exception e ) { e . printStackTrace ( ) ; return null ; } }
Called to convert result from ArangoCursor to given type by invoking the appropriate converter method
102
19
32,372
private Set < ? > buildSet ( final ArangoCursor < ? > cursor ) { return StreamSupport . stream ( Spliterators . spliteratorUnknownSize ( cursor , 0 ) , false ) . collect ( Collectors . toSet ( ) ) ; }
Creates a Set return type from the given cursor
54
10
32,373
private GeoResult < ? > buildGeoResult ( final ArangoCursor < ? > cursor ) { GeoResult < ? > geoResult = null ; while ( cursor . hasNext ( ) && geoResult == null ) { final Object object = cursor . next ( ) ; if ( ! ( object instanceof VPackSlice ) ) { continue ; } final VPackSlice slice = ( VPackSlice ) object ; final VPackSlice distSlice = slice . get ( "_distance" ) ; final Double distanceInMeters = distSlice . isDouble ( ) ? distSlice . getAsDouble ( ) : null ; if ( distanceInMeters == null ) { continue ; } final Object entity = operations . getConverter ( ) . read ( domainClass , slice ) ; final Distance distance = new Distance ( distanceInMeters / 1000 , Metrics . KILOMETERS ) ; geoResult = new GeoResult <> ( entity , distance ) ; } return geoResult ; }
Build a GeoResult from the given ArangoCursor
213
11
32,374
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) private GeoResults < ? > buildGeoResults ( final ArangoCursor < ? > cursor ) { final List < GeoResult < ? > > list = new LinkedList <> ( ) ; cursor . forEachRemaining ( o -> { final GeoResult < ? > geoResult = buildGeoResult ( o ) ; if ( geoResult != null ) { list . add ( geoResult ) ; } } ) ; return new GeoResults ( list ) ; }
Build a GeoResults object with the ArangoCursor returned by query execution
117
15
32,375
@ Deprecated public static Zone create ( String name , String id ) { return new Zone ( id , name , 86400 , "nil@" + name ) ; }
Represent a zone with a fake email and a TTL of 86400 .
36
15
32,376
public StringRecordBuilder < D > addAll ( String ... records ) { return addAll ( Arrays . asList ( checkNotNull ( records , "records" ) ) ) ; }
adds values to the builder
40
6
32,377
private Zone zipWithSOA ( Zone next ) { Record soa = api . recordsByNameAndType ( Integer . parseInt ( next . id ( ) ) , next . name ( ) , "SOA" ) . get ( 0 ) ; return Zone . create ( next . id ( ) , next . name ( ) , soa . ttl , next . email ( ) ) ; }
CloudDNS doesn t expose the domain s ttl in the list api .
83
16
32,378
private Integer getPriority ( Map < String , Object > mutableRData ) { Integer priority = null ; if ( mutableRData . containsKey ( "priority" ) ) { // SRVData priority = Integer . class . cast ( mutableRData . remove ( "priority" ) ) ; } else if ( mutableRData . containsKey ( "preference" ) ) { // MXData priority = Integer . class . cast ( mutableRData . remove ( "preference" ) ) ; } return priority ; }
Has the side effect of removing the priority from the mutableRData .
113
15
32,379
public static Filter < ResourceRecordSet < ? > > alwaysVisible ( ) { return new Filter < ResourceRecordSet < ? > > ( ) { @ Override public boolean apply ( ResourceRecordSet < ? > in ) { return in != null && in . qualifier ( ) == null ; } @ Override public String toString ( ) { return "alwaysVisible()" ; } } ; }
Returns true if the input has no visibility qualifier . Typically indicates a basic record set .
83
17
32,380
public static ResourceRecordSet < SOAData > soa ( ResourceRecordSet < ? > soa , String email , int ttl ) { SOAData soaData = ( SOAData ) soa . records ( ) . get ( 0 ) ; soaData = soaData . toBuilder ( ) . serial ( soaData . serial ( ) + 1 ) . rname ( email ) . build ( ) ; return ResourceRecordSet . < SOAData > builder ( ) . name ( soa . name ( ) ) . type ( "SOA" ) . ttl ( ttl ) . add ( soaData ) . build ( ) ; }
Returns an updated SOA rrset with an incremented serial number and the specified parameters .
141
19
32,381
public static List < String > split ( char delim , String toSplit ) { checkNotNull ( toSplit , "toSplit" ) ; if ( toSplit . indexOf ( delim ) == - 1 ) { return Arrays . asList ( toSplit ) ; // sortable in JRE 7 and 8 } List < String > out = new LinkedList < String > ( ) ; StringBuilder currentString = new StringBuilder ( ) ; for ( char c : toSplit . toCharArray ( ) ) { if ( c == delim ) { out . add ( emptyToNull ( currentString . toString ( ) ) ) ; currentString . setLength ( 0 ) ; } else { currentString . append ( c ) ; } } out . add ( emptyToNull ( currentString . toString ( ) ) ) ; return out ; }
empty fields will result in null elements in the result .
176
11
32,382
@ Override public Iterator < Zone > iterator ( ) { final Iterator < String > delegate = api . getZonesOfAccount ( account . get ( ) ) . iterator ( ) ; return new Iterator < Zone > ( ) { @ Override public boolean hasNext ( ) { return delegate . hasNext ( ) ; } @ Override public Zone next ( ) { return fromSOA ( delegate . next ( ) ) ; } @ Override public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; }
in UltraDNS zones are scoped to an account .
113
12
32,383
@ Override public Object put ( String key , Object val ) { val = val != null && val instanceof Number ? Number . class . cast ( val ) . intValue ( ) : val ; return super . put ( key , val ) ; }
a ctor that allows passing a map .
52
9
32,384
static Map < String , String > parseJson ( String in ) { if ( in == null ) { return Collections . emptyMap ( ) ; } String noBraces = in . replace ( ' ' , ' ' ) . replace ( ' ' , ' ' ) . trim ( ) ; Map < String , String > builder = new LinkedHashMap < String , String > ( ) ; Matcher matcher = JSON_FIELDS . matcher ( noBraces ) ; while ( matcher . find ( ) ) { String key = keyMap . get ( matcher . group ( 1 ) ) ; if ( key != null ) { builder . put ( key , matcher . group ( 2 ) ) ; } } return builder ; }
IAM Instance Profile format is simple non - nested json .
155
13
32,385
public static List < String > list ( URI metadataService , String path ) { checkArgument ( checkNotNull ( path , "path" ) . endsWith ( "/" ) , "path must end with '/'; %s provided" , path ) ; String content = get ( metadataService , path ) ; if ( content != null ) { return split ( ' ' , content ) ; } return Collections . < String > emptyList ( ) ; }
Retrieves a list of resources at a path if present .
93
13
32,386
public static String get ( URI metadataService , String path ) { checkNotNull ( metadataService , "metadataService" ) ; checkArgument ( metadataService . getPath ( ) . endsWith ( "/" ) , "metadataService must end with '/'; %s provided" , metadataService ) ; checkNotNull ( path , "path" ) ; InputStream stream = null ; try { stream = openStream ( metadataService + path ) ; String content = slurp ( new InputStreamReader ( stream ) ) ; if ( content . isEmpty ( ) ) { return null ; } return content ; } catch ( IOException e ) { return null ; } finally { try { if ( stream != null ) { stream . close ( ) ; } } catch ( IOException e ) { } } }
Retrieves content at a path if present .
165
10
32,387
@ Override public Iterator < ResourceRecordSet < ? > > iterateByName ( String name ) { Filter < ResourceRecordSet < ? > > filter = andNotAlias ( nameEqualTo ( name ) ) ; return lazyIterateRRSets ( api . listResourceRecordSets ( zoneId , name ) , filter ) ; }
lists and lazily transforms all record sets for a name which are not aliases into denominator format .
73
20
32,388
@ Override public boolean onKeyDown ( int keyCode , KeyEvent event ) { if ( keyCode == KeyEvent . KEYCODE_MENU ) { startActivity ( new Intent ( this , PreferencesActivity . class ) ) ; return true ; } return super . onKeyDown ( keyCode , event ) ; }
wire up preferences screen when menu button is pressed .
67
10
32,389
@ Subscribe public void onZones ( ZoneList . SuccessEvent event ) { String durationEvent = getString ( R . string . list_duration , event . duration ) ; Toast . makeText ( this , durationEvent , LENGTH_SHORT ) . show ( ) ; }
flash the response time of doing the list .
58
9
32,390
@ Subscribe public void onFailure ( Throwable t ) { Toast . makeText ( this , t . getMessage ( ) , LENGTH_LONG ) . show ( ) ; }
show any error messages posted to the bus .
38
9
32,391
@ Override public Iterator < Zone > iterateByName ( final String name ) { final Iterator < HostedZone > delegate = api . listHostedZonesByName ( name ) . iterator ( ) ; return new PeekingIterator < Zone > ( ) { @ Override protected Zone computeNext ( ) { if ( delegate . hasNext ( ) ) { HostedZone next = delegate . next ( ) ; if ( next . name . equals ( name ) ) { return zipWithSOA ( next ) ; } } return endOfData ( ) ; } } ; }
This implementation assumes that there isn t more than one page of zones with the same name .
122
18
32,392
private void deleteEverythingExceptNSAndSOA ( String id , String name ) { List < ActionOnResourceRecordSet > deletes = new ArrayList < ActionOnResourceRecordSet > ( ) ; ResourceRecordSetList page = api . listResourceRecordSets ( id ) ; while ( ! page . isEmpty ( ) ) { for ( ResourceRecordSet < ? > rrset : page ) { if ( rrset . type ( ) . equals ( "SOA" ) || rrset . type ( ) . equals ( "NS" ) && rrset . name ( ) . equals ( name ) ) { continue ; } deletes . add ( ActionOnResourceRecordSet . delete ( rrset ) ) ; } if ( ! deletes . isEmpty ( ) ) { api . changeResourceRecordSets ( id , deletes ) ; } if ( page . next == null ) { page . clear ( ) ; } else { deletes . clear ( ) ; page = api . listResourceRecordSets ( id , page . next . name , page . next . type , page . next . identifier ) ; } } }
Works through the zone deleting each page of rrsets except the zone s SOA and the NS rrsets . Once the zone is cleared it can be deleted .
240
34
32,393
static Object logModule ( boolean quiet , boolean verbose ) { checkArgument ( ! ( quiet && verbose ) , "quiet and verbose flags cannot be used at the same time!" ) ; Logger . Level logLevel ; if ( quiet ) { return null ; } else if ( verbose ) { logLevel = Logger . Level . FULL ; } else { logLevel = Logger . Level . BASIC ; } return new LogModule ( logLevel ) ; }
Returns a log configuration module or null if none is needed .
99
12
32,394
@ Override public boolean hasNext ( ) { if ( ! peekingIterator . hasNext ( ) ) { return false ; } DirectionalRecord record = peekingIterator . peek ( ) ; if ( record . noResponseRecord ) { // TODO: log as this is unsupported peekingIterator . next ( ) ; } return true ; }
skips no response records as they aren t portable
71
10
32,395
static String awaitComplete ( CloudDNS api , Job job ) { RetryableException retryableException = new RetryableException ( format ( "Job %s did not complete. Check your logs." , job . id ) , null ) ; Retryer retryer = new Retryer . Default ( 500 , 1000 , 30 ) ; while ( true ) { job = api . getStatus ( job . id ) ; if ( "COMPLETED" . equals ( job . status ) ) { return job . resultId ; } else if ( "ERROR" . equals ( job . status ) ) { throw new IllegalStateException ( format ( "Job %s failed with error: %s" , job . id , job . errorDetails ) ) ; } retryer . continueOrPropagate ( retryableException ) ; } }
Returns the ID of the object created or null .
176
10
32,396
static Map < String , Object > toRDataMap ( Record record ) { if ( "MX" . equals ( record . type ) ) { return MXData . create ( record . priority , record . data ( ) ) ; } else if ( "TXT" . equals ( record . type ) ) { return TXTData . create ( record . data ( ) ) ; } else if ( "SRV" . equals ( record . type ) ) { List < String > rdata = split ( ' ' , record . data ( ) ) ; return SRVData . builder ( ) . priority ( record . priority ) . weight ( Integer . valueOf ( rdata . get ( 0 ) ) ) . port ( Integer . valueOf ( rdata . get ( 1 ) ) ) . target ( rdata . get ( 2 ) ) . build ( ) ; } else if ( "SOA" . equals ( record . type ) ) { List < String > threeParts = split ( ' ' , record . data ( ) ) ; return SOAData . builder ( ) . mname ( threeParts . get ( 0 ) ) . rname ( threeParts . get ( 1 ) ) . serial ( Integer . valueOf ( threeParts . get ( 2 ) ) ) . refresh ( record . ttl ) . retry ( record . ttl ) . expire ( record . ttl ) . minimum ( record . ttl ) . build ( ) ; } else { return Util . toMap ( record . type , record . data ( ) ) ; } }
Special - cases priority field and the strange and incomplete SOA record .
325
14
32,397
public void stop ( ) { MessageBatcher batcher = null ; for ( String originalAppenderName : originalAsyncAppenderNameMap . keySet ( ) ) { String batcherName = AsyncAppender . class . getName ( ) + "." + originalAppenderName ; batcher = BatcherFactory . getBatcher ( batcherName ) ; if ( batcher == null ) { continue ; } batcher . stop ( ) ; } for ( String originalAppenderName : originalAsyncAppenderNameMap . keySet ( ) ) { String batcherName = AsyncAppender . class . getName ( ) + "." + originalAppenderName ; batcher = BatcherFactory . getBatcher ( batcherName ) ; if ( batcher == null ) { continue ; } BatcherFactory . removeBatcher ( batcherName ) ; } }
Shuts down blitz4j cleanly by flushing out all the async related messages .
183
18
32,398
public synchronized void reconfigure ( Properties props ) { // First isolate any property that is different from the immutable // set of original initialization properties Properties newOverrideProps = new Properties ( ) ; for ( Entry < Object , Object > prop : props . entrySet ( ) ) { if ( isLog4JProperty ( prop . getKey ( ) . toString ( ) ) ) { Object initialValue = initialProps . get ( prop . getKey ( ) ) ; if ( initialValue == null || ! initialValue . equals ( prop . getValue ( ) ) ) { newOverrideProps . put ( prop . getKey ( ) , prop . getValue ( ) ) ; } } } // Compare against our cached set of override if ( ! overrideProps . equals ( newOverrideProps ) ) { this . overrideProps . clear ( ) ; this . overrideProps . putAll ( newOverrideProps ) ; reConfigureAsynchronously ( ) ; } }
Set a snapshot of all LOG4J properties and reconfigure if properties have been changed .
203
18
32,399
private void reConfigureAsynchronously ( ) { refreshCount . incrementAndGet ( ) ; if ( pendingRefreshes . incrementAndGet ( ) == 1 ) { executorPool . submit ( new Runnable ( ) { @ Override public void run ( ) { do { try { Thread . sleep ( MIN_DELAY_BETWEEN_REFRESHES ) ; logger . info ( "Configuring log4j dynamically" ) ; reconfigure ( ) ; } catch ( Exception th ) { logger . error ( "Cannot dynamically configure log4j :" , th ) ; } } while ( 0 != pendingRefreshes . getAndSet ( 0 ) ) ; } } ) ; } }
Refresh the configuration asynchronously
152
7