idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
121,200
protected final void clearAuthenticationAttributes ( ) { HttpSession session = http . getCurrentRequest ( ) . getSession ( false ) ; if ( session == null ) { return ; } session . removeAttribute ( WebAttributes . AUTHENTICATION_EXCEPTION ) ; }
Removes temporary authentication - related data which may have been stored in the session during the authentication process .
121,201
public void setLargeIcons ( boolean largeIcons ) { this . largeIcons = largeIcons ; if ( getCompositionRoot ( ) != null ) { if ( largeIcons ) { getCompositionRoot ( ) . addStyleName ( ValoTheme . MENU_PART_LARGE_ICONS ) ; } else { getCompositionRoot ( ) . removeStyleName ( ValoTheme . MENU_PART_LARGE_ICONS ) ; } } }
Specifies whether the side bar should use large icons or not .
121,202
@ SuppressWarnings ( "unchecked" ) public V getView ( ) { V result = null ; if ( viewName != null ) { result = ( V ) viewProvider . getView ( viewName ) ; } return result ; }
Hands back the View that this Presenter works with A match is made if the ViewProvider finds a VaadinView annotated View whose name matches Presenter s viewName
121,203
public Locale getLocale ( ) { UI currentUI = UI . getCurrent ( ) ; Locale locale = currentUI == null ? null : currentUI . getLocale ( ) ; if ( locale == null ) { locale = Locale . getDefault ( ) ; } return locale ; }
Gets the locale of the current Vaadin UI . If the locale can not be determinted the default locale is returned instead .
121,204
public Collection < SideBarSectionDescriptor > getSideBarSections ( Class < ? extends UI > uiClass ) { List < SideBarSectionDescriptor > supportedSections = new ArrayList < SideBarSectionDescriptor > ( ) ; for ( SideBarSectionDescriptor section : sections ) { if ( section . isAvailableFor ( uiClass ) ) { supportedSecti...
Gets all side bar sections for the specified UI class .
121,205
public Collection < SideBarItemDescriptor > getSideBarItems ( SideBarSectionDescriptor descriptor ) { List < SideBarItemDescriptor > supportedItems = new ArrayList < SideBarItemDescriptor > ( ) ; for ( SideBarItemDescriptor item : items ) { if ( item . isMemberOfSection ( descriptor ) ) { supportedItems . add ( item ) ...
Gets all side bar items for the specified side bar section .
121,206
protected void clearAndReinitializeSession ( ) { final VaadinRequest currentRequest = VaadinService . getCurrentRequest ( ) ; final UI currentUI = UI . getCurrent ( ) ; if ( currentUI != null ) { final Transport transport = currentUI . getPushConfiguration ( ) . getTransport ( ) ; if ( Transport . WEBSOCKET . equals ( ...
Clears the session of all attributes except some internal Vaadin attributes and reinitializes it . If Websocket Push is used the session will never be reinitialized since this throws errors on at least Tomcat 8 .
121,207
protected HttpServletRequest getCurrentRequest ( ) { final HttpServletRequest request = httpService . getCurrentRequest ( ) ; if ( request == null ) { throw new IllegalStateException ( "No HttpServletRequest bound to current thread" ) ; } return request ; }
Returns the HTTP request bound to the current thread .
121,208
protected HttpServletResponse getCurrentResponse ( ) { final HttpServletResponse response = httpService . getCurrentResponse ( ) ; if ( response == null ) { throw new IllegalStateException ( "No HttpServletResponse bound to current thread" ) ; } return response ; }
Returns the HTTP response bound to the current thread .
121,209
public File getJarDirectory ( ) { if ( jarDirectory == null ) { this . jarDirectory = new File ( jarPath ) . getAbsoluteFile ( ) . getParentFile ( ) ; } return jarDirectory ; }
Gets the directory of the jar - file
121,210
public static ApiResponseObjectDoc buildResponse ( Method method ) { ApiResponseObjectDoc apiResponseObjectDoc = new ApiResponseObjectDoc ( JSONDocTypeBuilder . build ( new JSONDocType ( ) , method . getReturnType ( ) , method . getGenericReturnType ( ) ) ) ; if ( method . getReturnType ( ) . isAssignableFrom ( Respons...
Builds the ApiResponseObjectDoc from the method s return type and checks if the first type corresponds to a ResponseEntity class . In that case removes the responseentity string from the final list because it s not important to the documentation user .
121,211
public ApiDoc initApiDoc ( Class < ? > controller ) { ApiDoc apiDoc = new ApiDoc ( ) ; apiDoc . setName ( controller . getSimpleName ( ) ) ; apiDoc . setDescription ( controller . getSimpleName ( ) ) ; return apiDoc ; }
ApiDoc is initialized with the Controller s simple class name .
121,212
public static ApiMethodDoc validateApiMethodDoc ( ApiMethodDoc apiMethodDoc , MethodDisplay displayMethodAs ) { final String ERROR_MISSING_METHOD_PATH = "Missing documentation data: path" ; final String ERROR_MISSING_PATH_PARAM_NAME = "Missing documentation data: path parameter name" ; final String ERROR_MISSING_QUERY_...
This checks that some of the properties are correctly set to produce a meaningful documentation and a working playground . In case this does not happen an error string is added to the jsondocerrors list in ApiMethodDoc . It also checks that some properties are be set to produce a meaningful documentation . In case this...
121,213
public Set < ApiDoc > getApiDocs ( Set < Class < ? > > classes , MethodDisplay displayMethodAs ) { Set < ApiDoc > apiDocs = new TreeSet < ApiDoc > ( ) ; for ( Class < ? > controller : classes ) { ApiDoc apiDoc = getApiDoc ( controller , displayMethodAs ) ; apiDocs . add ( apiDoc ) ; } return apiDocs ; }
Gets the API documentation for the set of classes passed as argument
121,214
private ApiDoc getApiDoc ( Class < ? > controller , MethodDisplay displayMethodAs ) { log . debug ( "Getting JSONDoc for class: " + controller . getName ( ) ) ; ApiDoc apiDoc = initApiDoc ( controller ) ; apiDoc . setSupportedversions ( JSONDocApiVersionDocBuilder . build ( controller ) ) ; apiDoc . setAuth ( JSONDocAp...
Gets the API documentation for a single class annotated with
121,215
public Set < ApiFlowDoc > getApiFlowDocs ( Set < Class < ? > > classes , List < ApiMethodDoc > apiMethodDocs ) { Set < ApiFlowDoc > apiFlowDocs = new TreeSet < ApiFlowDoc > ( ) ; for ( Class < ? > clazz : classes ) { log . debug ( "Getting JSONDoc for class: " + clazz . getName ( ) ) ; Method [ ] methods = clazz . getM...
Gets the API flow documentation for the set of classes passed as argument
121,216
private static void addRequestMappingParamDoc ( Set < ApiParamDoc > apiParamDocs , RequestMapping requestMapping ) { if ( requestMapping . params ( ) . length > 0 ) { for ( String param : requestMapping . params ( ) ) { String [ ] splitParam = param . split ( "=" ) ; if ( splitParam . length > 1 ) { apiParamDocs . add ...
Checks the request mapping annotation value and adds the resulting
121,217
public static ApiVersionDoc build ( Method method ) { ApiVersionDoc apiVersionDoc = null ; ApiVersion methodAnnotation = method . getAnnotation ( ApiVersion . class ) ; ApiVersion typeAnnotation = method . getDeclaringClass ( ) . getAnnotation ( ApiVersion . class ) ; if ( typeAnnotation != null ) { apiVersionDoc = bui...
In case this annotation is present at type and method level then the method annotation will override the type one .
121,218
public static boolean isThisVerbCallEnabler ( Tag verb ) { if ( Verbs . play . equals ( verb . name ( ) ) || Verbs . say . equals ( verb . name ( ) ) || Verbs . gather . equals ( verb . name ( ) ) || Verbs . record . equals ( verb . name ( ) ) || Verbs . redirect . equals ( verb . name ( ) ) ) return true ; return fals...
if 200 ok delay is enabled we need to answer only the calls which are having any further call enabler verbs in their RCML .
121,219
private static void addHeadersToMessage ( SipServletMessage message , Map < String , String > customHeaders ) { for ( Map . Entry < String , String > entry : customHeaders . entrySet ( ) ) { String headerName = entry . getKey ( ) ; String headerVal = entry . getValue ( ) ; message . addHeader ( headerName , headerVal )...
Method adds custom headers to a SipServlet message
121,220
public DiskCache getDiskCache ( final String cachePath , final String cacheUri ) { return new DiskCache ( downloader , cachePath , cacheUri , true , cfg . isNoWavCache ( ) ) ; }
constructor for compatibility with existing cache implementation
121,221
private void removeAccoundDependencies ( Sid sid ) { logger . debug ( "removing accoutn dependencies" ) ; DaoManager daoManager = ( DaoManager ) context . getAttribute ( DaoManager . class . getName ( ) ) ; daoManager . getAnnouncementsDao ( ) . removeAnnouncements ( sid ) ; daoManager . getNotificationsDao ( ) . remov...
Removes all dependent resources of an account . Some resources like CDRs are excluded .
121,222
private void removeIncomingPhoneNumbers ( Sid accountSid , IncomingPhoneNumbersDao dao ) { List < IncomingPhoneNumber > numbers = dao . getIncomingPhoneNumbers ( accountSid ) ; if ( numbers != null && numbers . size ( ) > 0 ) { boolean managerQueried = false ; PhoneNumberProvisioningManager manager = null ; for ( Incom...
Removes incoming phone numbers that belong to an account from the database . For provided numbers the provider is also contacted to get them released .
121,223
private Account prepareAccountForUpdate ( final Account account , final MultivaluedMap < String , String > data , UserIdentityContext userIdentityContext ) { Account . Builder accBuilder = Account . builder ( ) ; accBuilder . copy ( account ) ; if ( data . containsKey ( "Status" ) ) { Account . Status newStatus = Accou...
Fills an account entity object with values supplied from an http request
121,224
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 ( "...
update SIP client of the corresponding Account . Password and FriendlyName fields are synched .
121,225
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 ...
Switches an account status at dao level .
121,226
protected Response getConfiguration ( final String extensionId , final Sid accountSid , final MediaType responseType ) { ExtensionConfiguration extensionConfiguration = null ; ExtensionConfiguration extensionAccountConfiguration = null ; Sid extensionSid = null ; String extensionName = null ; if ( Sid . pattern . match...
Will be used to get configuration for extension
121,227
private boolean redirectToClientVoiceApp ( final ActorRef self , final SipServletRequest request , final AccountsDao accounts , final ApplicationsDao applications , final Client client ) { Sid applicationSid = client . getVoiceApplicationSid ( ) ; URI clientAppVoiceUrl = null ; if ( applicationSid != null ) { final App...
If there is VoiceUrl provided for a Client configuration try to begin execution of the RCML app otherwise return false .
121,228
private boolean isWebRTC ( String transport , String userAgent ) { return "ws" . equalsIgnoreCase ( transport ) || "wss" . equalsIgnoreCase ( transport ) || userAgent . toLowerCase ( ) . contains ( "restcomm" ) ; }
Checks whether the client is WebRTC or not .
121,229
public static Map < String , String > parseUrl ( String url ) throws Exception { final String [ ] values = url . split ( ":" , 2 ) ; HashMap < String , String > sortParameters = new HashMap < String , String > ( ) ; sortParameters . put ( SORT_BY_KEY , values [ 0 ] ) ; if ( values . length > 1 ) { sortParameters . put ...
Parse the sorting part of the URI and return sortBy and sortDirection counterparts
121,230
public static RcmlserverResolver getInstance ( String rvdOrigin , String apiPath , boolean reinit ) { if ( singleton == null || reinit ) { singleton = new RcmlserverResolver ( rvdOrigin , apiPath ) ; } return singleton ; }
not really a clean singleton pattern but a way to init once and use many . Only the first time this method is called the parameters are used in the initialization
121,231
public URI resolveRelative ( URI uri ) { if ( uri != null && rvdOrigin != null && filterPrefix != null ) { if ( uri . isAbsolute ( ) ) return uri ; try { String uriString = uri . toString ( ) ; if ( uriString . startsWith ( filterPrefix ) ) return new URI ( rvdOrigin + uri . toString ( ) ) ; } catch ( URISyntaxExceptio...
if rvdOrigin is null no point in trying to resolve RVD location . We will return passed uri instead
121,232
private HttpConnectorList getHttpConnectors ( ) throws Exception { logger . info ( "Searching HTTP connectors." ) ; HttpConnectorList httpConnectorList = null ; httpConnectorList = jBossConnectorDiscover . findConnectors ( ) ; if ( httpConnectorList == null || httpConnectorList . getConnectors ( ) . isEmpty ( ) ) { htt...
Will query different JMX MBeans for a list of runtime connectors .
121,233
public URI resolve ( final URI uri , final Sid accountSid ) { getHttpConnector ( ) ; String restcommAddress = null ; if ( accountSid != null && daoManager != null ) { Sid organizationSid = daoManager . getAccountsDao ( ) . getAccount ( accountSid ) . getOrganizationSid ( ) ; restcommAddress = daoManager . getOrganizati...
Use to resolve a relative URI using the domain name of the Organization that the provided AccountSid belongs
121,234
public HttpConnector getHttpConnector ( ) throws RuntimeException { if ( selectedConnector == null ) { try { HttpConnectorList httpConnectorList = getHttpConnectors ( ) ; if ( httpConnectorList != null && ! httpConnectorList . getConnectors ( ) . isEmpty ( ) ) { List < HttpConnector > connectors = httpConnectorList . g...
For historical reasons this method never returns null and instead throws a RuntimeException .
121,235
static void removeRegexes ( List < IncomingPhoneNumber > numbers ) { List < IncomingPhoneNumber > toBeRemoved = new ArrayList ( ) ; if ( numbers != null ) { for ( IncomingPhoneNumber nAux : numbers ) { if ( StringUtils . containsAny ( nAux . getPhoneNumber ( ) , REGEX_SPECIAL_CHARS ) ) { toBeRemoved . add ( nAux ) ; } ...
SMPP is not supporting organizations at the moment disable regexes to prevent an organization to capture all cloud traffic with a single regex .
121,236
public HttpConnectorList findConnectors ( ) throws MalformedObjectNameException , NullPointerException , UnknownHostException , AttributeNotFoundException , InstanceNotFoundException , MBeanException , ReflectionException { LOG . info ( "Searching JBoss HTTP connectors." ) ; HttpConnectorList httpConnectorList = null ;...
A list of connectors . Not bound connectors will be discarded .
121,237
public boolean isDirectChildOfAccount ( final Account effectiveAccount , final Account operatedAccount ) { return operatedAccount . getParentSid ( ) . equals ( effectiveAccount . getSid ( ) ) ; }
Checks if the operated account is a direct child of effective account
121,238
public boolean hasAccountRole ( final String role , UserIdentityContext userIdentityContext ) { if ( userIdentityContext . getEffectiveAccount ( ) != null ) { return userIdentityContext . getEffectiveAccountRoles ( ) . contains ( role ) ; } return false ; }
Checks is the effective account has the specified role . Only role values contained in the Restcomm Account are take into account .
121,239
private AuthOutcome checkPermission ( String neededPermissionString , Set < String > roleNames ) { if ( roleNames . contains ( getAdministratorRole ( ) ) ) return AuthOutcome . OK ; WildcardPermissionResolver resolver = new WildcardPermissionResolver ( ) ; Permission neededPermission = resolver . resolvePermission ( ne...
Low level permission checking . roleNames are checked for neededPermissionString permission using permission mappings contained in restcomm . xml . The permission mappings are stored in RestcommRoles .
121,240
private void populateApplicationWithNumber ( Application application , final Map < String , Object > map , String field_prefix ) { ApplicationNumberSummary number = new ApplicationNumberSummary ( readString ( map . get ( field_prefix + "sid" ) ) , readString ( map . get ( field_prefix + "friendly_name" ) ) , readString...
Populates application . numbers field with information of one or more numbers . The numbers list is created if already null and an IncomingPhoneNumber is added into it based on information from the map . Invoking the same method several times to add more numbers to the same list is possible .
121,241
public static String endWithNewLine ( String sdpDescription ) { if ( sdpDescription == null || sdpDescription . isEmpty ( ) ) { throw new IllegalArgumentException ( "The SDP description cannot be null or empty" ) ; } return sdpDescription . trim ( ) . concat ( "\n" ) ; }
Patches an SDP description by trimming and making sure it ends with a new line .
121,242
private void notifyStatus ( SmsMessage message ) { URI callback = message . getStatusCallback ( ) ; if ( callback != null ) { String method = message . getStatusCallbackMethod ( ) ; if ( method != null && ! method . isEmpty ( ) ) { if ( ! org . apache . http . client . methods . HttpGet . METHOD_NAME . equalsIgnoreCase...
The storage engine .
121,243
public static String HA1 ( String username , String realm , String password , String algorithm ) { String ha1 = "" ; ha1 = DigestAuthentication . H ( username + ":" + realm + ":" + password , algorithm ) ; return ha1 ; }
USed for unit testing
121,244
protected boolean isEmpty ( Object value ) { if ( value == null ) return true ; if ( value . equals ( "" ) ) return true ; return false ; }
A general purpose method to test incoming parameters for meaningful data
121,245
public static boolean checkAuthentication ( SipServletRequest request , DaoManager storage , Sid organizationSid ) throws IOException { final String authorization = request . getHeader ( "Proxy-Authorization" ) ; final String method = request . getMethod ( ) ; if ( authorization == null || ! CallControlHelper . permitt...
Check if a client is authenticated . If so return true . Otherwise request authentication and return false ;
121,246
private NumberSelectionResult findSingleNumber ( String number , Sid sourceOrganizationSid , Sid destinationOrganizationSid , Set < SearchModifier > modifiers ) { NumberSelectionResult matchedNumber = new NumberSelectionResult ( null , false , null ) ; IncomingPhoneNumberFilter . Builder filterBuilder = IncomingPhoneNu...
Here we expect a perfect match in DB .
121,247
private NumberSelectionResult findByNumber ( List < String > numberQueries , Sid sourceOrganizationSid , Sid destinationOrganizationSid , Set < SearchModifier > modifiers ) { Boolean orgFiltered = false ; NumberSelectionResult matchedNumber = new NumberSelectionResult ( null , orgFiltered , null ) ; int i = 0 ; while (...
Iterates over the list of given numbers and returns the first matching .
121,248
private NumberSelectionResult findByRegex ( List < String > numberQueries , Sid sourceOrganizationSid , Sid destOrg ) { NumberSelectionResult numberFound = new NumberSelectionResult ( null , false , null ) ; IncomingPhoneNumberFilter . Builder filterBuilder = IncomingPhoneNumberFilter . Builder . builder ( ) ; filterBu...
This will take the regexes available in given organization and evalute them agsint the given list of numbers returning the first match .
121,249
protected Response putOrganization ( String domainName , final UriInfo info , MediaType responseType ) { if ( domainName == null ) { return status ( BAD_REQUEST ) . entity ( MSG_EMPTY_DOMAIN_NAME ) . build ( ) ; } else { if ( ! pattern . matcher ( domainName ) . matches ( ) ) { return status ( BAD_REQUEST ) . entity ( ...
putOrganization create new organization
121,250
protected Response migrateClientsOrganization ( final String organizationSid , UriInfo info , MediaType responseType , UserIdentityContext userIdentityContext ) { permissionEvaluator . checkPermission ( "RestComm:Read:Organizations" , userIdentityContext ) ; Organization organization = null ; if ( ! Sid . pattern . mat...
Hash password for clients of the given organization
121,251
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 ( ) ...
Grants general purpose access if any valid token exists in the request
121,252
protected void filterClosedAccounts ( UserIdentityContext userIdentityContext , String path ) { if ( userIdentityContext . getEffectiveAccount ( ) != null && ! userIdentityContext . getEffectiveAccount ( ) . getStatus ( ) . equals ( Account . Status . ACTIVE ) ) { if ( userIdentityContext . getEffectiveAccount ( ) . ge...
filter out accounts that are not active
121,253
private int getGlobalNoOfParticipants ( ) throws Exception { if ( sid == null ) { globalNoOfParticipants = calls . size ( ) ; } else { CallDetailRecordsDao dao = storage . getCallDetailRecordsDao ( ) ; globalNoOfParticipants = dao . getTotalRunningCallDetailRecordsByConferenceSid ( sid ) ; } if ( logger . isDebugEnable...
get global total no of participants from db
121,254
private void generateDefaultProfile ( final DaoManager storage , final String profileSourcePath ) throws SQLException , IOException { Profile profile = storage . getProfilesDao ( ) . getProfile ( DEFAULT_PROFILE_SID ) ; if ( profile == null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "default profile does...
generateDefaultProfile if does not already exists
121,255
protected void doHead ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { processRequest ( request , response , false ) ; }
Process HEAD request . This returns the same headers as GET request but without content .
121,256
private static boolean accepts ( String acceptHeader , String toAccept ) { String [ ] acceptValues = acceptHeader . split ( "\\s*(,|;)\\s*" ) ; Arrays . sort ( acceptValues ) ; return Arrays . binarySearch ( acceptValues , toAccept ) > - 1 || Arrays . binarySearch ( acceptValues , toAccept . replaceAll ( "/.*$" , "/*" ...
Returns true if the given accept header accepts the given value .
121,257
private static boolean matches ( String matchHeader , String toMatch ) { String [ ] matchValues = matchHeader . split ( "\\s*,\\s*" ) ; Arrays . sort ( matchValues ) ; return Arrays . binarySearch ( matchValues , toMatch ) > - 1 || Arrays . binarySearch ( matchValues , "*" ) > - 1 ; }
Returns true if the given match header matches the given value .
121,258
public void removeStaleSimulatorLaunchds ( ) { List < String > launchctlCmd = Arrays . asList ( "launchctl" , "list" ) ; Command cmd = new Command ( launchctlCmd , false ) ; SimulatorLaunchd simLaunchd = new SimulatorLaunchd ( ) ; cmd . registerListener ( simLaunchd ) ; cmd . executeAndWait ( true ) ; Set < String > si...
Removes stale iphonesimulator launchds hanging in the system
121,259
protected void sendMessage ( String xml ) { byte [ ] bytes = null ; try { bytes = xml . getBytes ( "UTF-8" ) ; writeBytes ( bytes ) ; } catch ( SocketException se ) { stop ( ) ; start ( ) ; try { writeBytes ( bytes ) ; } catch ( IOException e ) { throw new WebDriverException ( e ) ; } } catch ( IOException e ) { throw ...
sends the message to the AUT .
121,260
private void pushInput ( byte [ ] inputBytes ) throws Exception { buf . write ( inputBytes ) ; while ( buf . size ( ) >= 4 ) { byte [ ] bytes = buf . toByteArray ( ) ; int size = 0 ; size = ( size << 8 ) + byteToInt ( bytes [ 0 ] ) ; size = ( size << 8 ) + byteToInt ( bytes [ 1 ] ) ; size = ( size << 8 ) + byteToInt ( ...
reads the messages from the AUT .
121,261
protected void read ( ) throws Exception { InputStream is = socket . getInputStream ( ) ; while ( is . available ( ) > 0 ) { byte [ ] bytes = new byte [ 1024 * 1024 ] ; int read = is . read ( bytes ) ; byte [ ] actuallyRead = new byte [ read ] ; System . arraycopy ( bytes , 0 , actuallyRead , 0 , read ) ; pushInput ( a...
listen for a complete message .
121,262
public static String extractMessage ( Throwable e ) { String msg = e . getMessage ( ) ; return msg == null ? "" : ( e instanceof WebDriverException ) ? msg . split ( "\n" ) [ 0 ] : msg ; }
Webdriver exception have debug info for the client . polluting server side .
121,263
public void setKeyboardOptions ( ) { File folder = new File ( contentAndSettingsFolder + "/Library/Preferences/" ) ; File preferenceFile = new File ( folder , "com.apple.Preferences.plist" ) ; try { JSONObject preferences = new JSONObject ( ) ; preferences . put ( "KeyboardAutocapitalization" , false ) ; preferences . ...
the default keyboard options aren t good for automation . For instance it automatically capitalize the first letter of sentences etc . Getting rid of all that to have the keyboard execute requests without changing them .
121,264
public void setAccessibilityOptions ( ) { File folder = new File ( contentAndSettingsFolder + "/Library/Preferences/" ) ; File preferenceFile = new File ( folder , "com.apple.Accessibility.plist" ) ; try { JSONObject preferences = new JSONObject ( ) ; if ( instrumentsVersion . getMajor ( ) < 6 ) { preferences . put ( "...
Set the Accessibility preferences . Overrides the values in com . apple . Accessibility . plist file .
121,265
public void resetContentAndSettings ( ) { if ( instrumentsVersion . getMajor ( ) < 6 ) { if ( hasContentAndSettingsFolder ( ) ) { boolean ok = deleteRecursive ( getContentAndSettingsFolder ( ) ) ; if ( ! ok ) { System . err . println ( "cannot delete content and settings folder " + contentAndSettingsFolder ) ; } } Stri...
Does what IOS Simulator - Reset content and settings menu does by deleting the files on disk . The simulator shouldn t be running when that is done .
121,266
private File extract ( InstrumentsVersion version ) { if ( version . getBuild ( ) == null ) { throw new WebDriverException ( "you are running a version of XCode that is too old " + version ) ; } extractFromJar ( "instruments" ) ; extractFromJar ( "InstrumentsShim.dylib" ) ; extractFromJar ( "ScriptAgentShim.dylib" ) ; ...
extract the binaries for the specified version of instruments .
121,267
private void processVersionLine ( String log ) { log = log . replace ( start , "" ) ; String [ ] pieces = log . split ( " \\(" ) ; if ( pieces . length == 2 ) { version = pieces [ 0 ] ; build = pieces [ 1 ] . replace ( ")" , "" ) ; } else { version = pieces [ 0 ] ; build = null ; } }
string parsing to get the version out .
121,268
public static < T > T augment ( WebDriver driver ) { Augmenter augmenter = new Augmenter ( ) ; augmenter . addDriverAugmentation ( IOSCapabilities . CONFIGURABLE , new AddConfigurable ( ) ) ; augmenter . addDriverAugmentation ( IOSCapabilities . ELEMENT_TREE , new AddLogElementTree ( ) ) ; augmenter . addDriverAugmenta...
Add all the IOS specific interfaces ios - driver supports .
121,269
public static File extractAppFromURL ( URL url ) throws IOException { String fileName = url . toExternalForm ( ) . substring ( url . toExternalForm ( ) . lastIndexOf ( '/' ) + 1 ) ; File tmpDir = createTmpDir ( "iosd" ) ; log . fine ( "tmpDir: " + tmpDir . getAbsolutePath ( ) ) ; File downloadedFile = new File ( tmpDir...
Downloads zip from from url extracts it into tmp dir and returns path to extracted directory
121,270
private void forceWebViewToReloadManually ( int retry ) { boolean ok = false ; setMode ( WorkingMode . Native ) ; for ( int i = 0 ; i < retry ; i ++ ) { try { WebElement b = getNativeDriver ( ) . findElement ( By . xpath ( "//UIAWindow/UIAScrollView/UIAButton" ) ) ; b . click ( ) ; ok = true ; } catch ( WebDriverExcept...
the webview doesn t refresh correctly if it hasn t been loaded at lease once .
121,271
public static WebElement createObject ( RemoteWebDriver driver , Map < String , Object > ro ) { String ref = ro . get ( "ELEMENT" ) . toString ( ) ; String type = ( String ) ro . get ( "type" ) ; if ( type != null ) { String remoteObjectName = "org.uiautomation.ios.client.uiamodels.impl.Remote" + type ; if ( "UIAElemen...
Uses reflection to instanciate a remote object implementing the correct interface .
121,272
public Response handle ( ) throws Exception { Object p = getRequest ( ) . getPayload ( ) . get ( "id" ) ; if ( JSONObject . NULL . equals ( p ) ) { getWebDriver ( ) . getContext ( ) . setCurrentFrame ( null , null , null ) ; } else { RemoteWebElement iframe ; if ( p instanceof String ) { iframe = getIframe ( ( String )...
NoSuchFrame - If the frame specified by id cannot be found .
121,273
private ImmutableList < LanguageDictionary > loadDictionaries ( ) { Map < String , LanguageDictionary > languageNameMap = new HashMap < > ( ) ; for ( File f : LanguageDictionary . getL10NFiles ( app ) ) { String name = LanguageDictionary . extractLanguageName ( f ) ; LanguageDictionary res = languageNameMap . get ( nam...
Load all the dictionaries for the application .
121,274
public Map < String , String > getResources ( ) { Map < String , String > resourceByResourceName = new HashMap < > ( ) ; String metadata = getMetadata ( ICON ) ; if ( metadata . equals ( "" ) ) { metadata = getFirstIconFile ( BUNDLE_ICONS ) ; } resourceByResourceName . put ( ICON , metadata ) ; return resourceByResourc...
the list of resources to publish via http .
121,275
public JSONObject readContentFromBinaryFile ( File binaryFile ) throws Exception { PlistFileUtils util = new PlistFileUtils ( binaryFile ) ; return util . toJSON ( ) ; }
load the content of the binary file and returns it as a json object .
121,276
private JSONObject getCriteria ( JSONObject payload ) throws JSONException { if ( payload . has ( "criteria" ) ) { JSONObject json = payload . getJSONObject ( "criteria" ) ; return json ; } else if ( payload . has ( "using" ) ) { return getCriteriaFromWebDriverSelector ( payload ) ; } else { throw new InvalidSelectorEx...
create the criteria for the request . If the request follows the webdriver protocol maps it to a criteria ios - driver understands .
121,277
private JSONObject getCriteriaFromWebDriverSelector ( JSONObject payload ) throws JSONException { String using = payload . getString ( "using" ) ; String value = payload . getString ( "value" ) ; if ( "tag name" . equals ( using ) || "class name" . equals ( using ) ) { try { Package p = UIAElement . class . getPackage ...
handles the mapping from the webdriver using to a criteria .
121,278
public void setCurrentFrame ( RemoteWebElement iframe , RemoteWebElement document , RemoteWebElement window ) { this . iframe = iframe ; this . document = document ; this . window = window ; if ( iframe != null ) { isOnMainFrame = false ; } else { isOnMainFrame = true ; } if ( iframe == null && document == null ) { thi...
breaks the nodeId reference .
121,279
public void start ( ) { if ( log . isLoggable ( Level . FINE ) ) { log . fine ( String . format ( "Starting command: %s" , commandString ( ) ) ) ; } ProcessBuilder builder = new ProcessBuilder ( args ) ; if ( workingDir != null ) { builder . directory ( workingDir ) ; } if ( ! environment . isEmpty ( ) ) { Map < String...
Starts the command . Doesn t wait for it to finish . Doesn t wait for stdout and stderr either .
121,280
public < T > T execute ( WebDriverLikeRequest request ) { Response response = null ; long total = 0 ; try { HttpClient client = newHttpClientWithTimeout ( ) ; String url = remoteURL + request . getPath ( ) ; BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest ( request . getMethod ( ) , url ) ; if (...
send the request to the remote server for execution .
121,281
public Subscription subscribe ( String applicationName , String eventName , String consumerGroup ) throws IOException { return subscription ( applicationName , eventName ) . withConsumerGroup ( consumerGroup ) . subscribe ( ) ; }
Create a subscription for a single event type .
121,282
public SubscriptionBuilder subscription ( String applicationName , String eventName ) throws IOException { return new SubscriptionBuilder ( this , applicationName , Collections . singleton ( eventName ) ) ; }
Build a subscription for a single event type .
121,283
public SubscriptionBuilder subscription ( String applicationName , Set < String > eventNames ) throws IOException { return new SubscriptionBuilder ( this , applicationName , eventNames ) ; }
Build a subscription for multiple event types .
121,284
public void deleteSubscription ( String subscriptionId ) throws IOException { checkArgument ( ! subscriptionId . isEmpty ( ) , "Subscription ID cannot be empty." ) ; final URI uri = baseUri . resolve ( String . format ( "/subscriptions/%s" , subscriptionId ) ) ; final Request request = clientHttpRequestFactory . create...
Delete subscription based on subscription ID .
121,285
private HttpURLConnection openConnection ( URL url ) throws IOException { URLConnection urlConnection = url . openConnection ( ) ; if ( ! ( urlConnection instanceof HttpURLConnection ) ) { throw new IllegalStateException ( "Connection should be an HttpURLConnection" ) ; } return ( HttpURLConnection ) urlConnection ; }
Opens and returns a connection to the given URL .
121,286
public StreamParameters withCommitTimeout ( int commitTimeout ) { return new StreamParameters ( batchLimit , streamLimit , batchFlushTimeout , streamTimeout , streamKeepAliveLimit , maxUncommittedEvents , commitTimeout ) ; }
Maximum amount of seconds that nakadi will be waiting for commit after sending a batch to a client . If the commit does not come within this timeout nakadi will initialize stream termination no new data will be sent . Partitions from this stream will be assigned to other streams .
121,287
private void initializeProcessor ( JsonProcessor processor ) throws ODataUnmarshallingException { LOG . info ( "Trying to initialize processor: {}" , processor . getClass ( ) . getSimpleName ( ) ) ; processor . initialize ( ) ; fields = processor . getValues ( ) ; odataValues = processor . getODataValues ( ) ; links = ...
Initialize processor ready for for unmarshalling entity .
121,288
private String getEntityName ( ) throws ODataUnmarshallingException { String odataType = odataValues . get ( JsonConstants . TYPE ) ; if ( isNullOrEmpty ( odataType ) ) { TargetType targetType = getTargetType ( ) ; if ( targetType == null ) { throw new ODataUnmarshallingException ( "Could not find entity name" ) ; } re...
Gets the entity type name .
121,289
protected void setEntityNavigationProperties ( Object entity , StructuredType entityType ) throws ODataException { for ( Map . Entry < String , Object > entry : links . entrySet ( ) ) { String propertyName = entry . getKey ( ) ; Object entryLinks = entry . getValue ( ) ; LOG . debug ( "Found link for navigation propert...
Sets the given entity with navigation links .
121,290
public void writeStartFeed ( String requestContextURL , Map < String , Object > meta ) throws ODataRenderException { this . contextURL = checkNotNull ( requestContextURL ) ; try { startFeed ( false ) ; if ( ODataUriUtil . hasCountOption ( oDataUri ) && meta != null && meta . containsKey ( "count" ) ) { metadataWriter ....
Write start feed to the XML stream .
121,291
public void writeBodyFeed ( List < ? > entities ) throws ODataRenderException { checkNotNull ( entities ) ; try { for ( Object entity : entities ) { writeEntry ( entity , true ) ; } } catch ( XMLStreamException | IllegalAccessException | NoSuchFieldException | ODataEdmException e ) { LOG . error ( "Not possible to mars...
Write feed body .
121,292
public String getXml ( ) { try { return ( ( ByteArrayOutputStream ) outputStream ) . toString ( StandardCharsets . UTF_8 . name ( ) ) ; } catch ( UnsupportedEncodingException e ) { return outputStream . toString ( ) ; } }
Get the generated XML .
121,293
public static void closeIfNecessary ( Closeable closeable ) throws ODataClientException { if ( closeable != null ) { try { closeable . close ( ) ; } catch ( IOException e ) { throw new ODataClientException ( "Could not close '" + closeable . getClass ( ) . getSimpleName ( ) + "'" , e ) ; } } }
Close closable objects if it is necessary . Mostly used to close connections .
121,294
public static Map < String , String > populateRequestProperties ( Map < String , String > requestProperties , int bodyLength , MediaType contentType , MediaType acceptType ) { Map < String , String > properties ; if ( requestProperties == null || requestProperties . isEmpty ( ) ) { properties = new HashMap < > ( ) ; } ...
Util method for first populating request properties before execution .
121,295
public Object getAction ( ) throws ODataException { Option < String > actionNameOption = ODataUriUtil . getActionCallName ( odataUri ) ; if ( actionNameOption . isDefined ( ) ) { LOG . debug ( "The operation is supposed to be an action" ) ; String actionName = actionNameOption . get ( ) ; return parseAction ( actionNam...
Returns the instance of Action with all parameters provided by request .
121,296
public void addActionImport ( Class < ? > cls ) { EdmActionImport actionImportAnnotation = cls . getAnnotation ( EdmActionImport . class ) ; ActionImportImpl . Builder actionImportBuilder = new ActionImportImpl . Builder ( ) . setEntitySetName ( actionImportAnnotation . entitySet ( ) ) . setActionName ( actionImportAnn...
Adds an action import to factory .
121,297
public Iterable < ActionImport > build ( FactoryLookup lookup ) { List < ActionImport > actionImports = new ArrayList < > ( ) ; for ( ActionImportImpl . Builder actionImportBuilder : actionImportBuilders ) { actionImportBuilder . setEntitySet ( lookup . getEntitySet ( actionImportBuilder . getEntitySetName ( ) ) ) ; ac...
Builds action import objects based on registered classes .
121,298
public String getJsonError ( ODataException exception ) throws ODataRenderException { checkNotNull ( exception ) ; LOG . debug ( "Start building Json error document" ) ; ByteArrayOutputStream outputStream = new ByteArrayOutputStream ( ) ; try { JsonGenerator jsonGenerator = JSON_FACTORY . createGenerator ( outputStream...
Gets the json error output according to ODataException .
121,299
public void writeData ( Object entity , EntityType entityType ) throws XMLStreamException , ODataRenderException { xmlWriter . writeStartElement ( ODATA_CONTENT ) ; xmlWriter . writeAttribute ( TYPE , XML . toString ( ) ) ; xmlWriter . writeStartElement ( METADATA , ODATA_PROPERTIES , "" ) ; marshall ( entity , entityT...
Write the data for a given entity .