idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
38,700
private static CSSParser createParser ( Object source , NetworkProcessor network , String encoding , SourceType type , URL base ) throws IOException , CSSException { CSSInputStream input = getInput ( source , network , encoding , type ) ; input . setBase ( base ) ; return createParserForInput ( input ) ; }
creates the parser
38,701
protected static CSSException encapsulateException ( Throwable t , String msg ) { log . error ( "THROWN:" , t ) ; return new CSSException ( msg , t ) ; }
Creates new CSSException which encapsulates cause
38,702
public boolean repeat ( Map < String , CSSProperty > properties , Map < String , Term < ? > > values ) { for ( int i = 0 ; i < times ; i ++ ) { if ( ! operation ( i , properties , values ) ) return false ; } return true ; }
Repeats operations on terms
38,703
public void assignPropertyNames ( String ... propertyNames ) throws IllegalArgumentException { if ( propertyNames . length != times ) throw new IllegalArgumentException ( "Invalid length of propertyNames in Repeater." ) ; this . names = Arrays . asList ( propertyNames ) ; }
Assigns property names
38,704
public void assignTerms ( Term < ? > ... terms ) throws IllegalArgumentException { if ( terms . length != times ) throw new IllegalArgumentException ( "Invalid length of terms in Repeater." ) ; this . terms = Arrays . asList ( terms ) ; }
Assigns terms to repeater
38,705
public boolean parseDeclaration ( Declaration d , Map < String , CSSProperty > properties , Map < String , Term < ? > > values ) { final String propertyName = d . getProperty ( ) ; if ( ! css . isSupportedCSSProperty ( propertyName ) || d . isEmpty ( ) ) return false ; try { Method m = methods . get ( propertyName ) ; if ( m != null ) { boolean result = ( Boolean ) m . invoke ( this , d , properties , values ) ; log . debug ( "Parsing /{}/ {}" , result , d ) ; return result ; } else { boolean result = processAdditionalCSSGenericProperty ( d , properties , values ) ; log . debug ( "Parsing with proxy /{}/ {}" , result , d ) ; return result ; } } catch ( IllegalArgumentException e ) { log . warn ( "Illegal argument" , e ) ; } catch ( IllegalAccessException e ) { log . warn ( "Illegal access" , e ) ; } catch ( InvocationTargetException e ) { log . warn ( "Invocation target" , e ) ; log . warn ( "Invotation target cause" , e . getCause ( ) ) ; } return false ; }
Core function . Parses CSS declaration into structure applicable to DataNodeImpl
38,706
public < T extends CSSProperty > T genericPropertyRaw ( Class < T > type , Set < T > intersection , TermIdent term ) { try { String name = term . getValue ( ) . replace ( "-" , "_" ) . toUpperCase ( ) ; T property = CSSProperty . Translator . valueOf ( type , name ) ; if ( intersection != null && intersection . contains ( property ) ) return property ; return property ; } catch ( Exception e ) { return null ; } }
Converts TermIdent into CSSProperty using intersection set . CSSProperty . Translator is used .
38,707
protected < T extends CSSProperty > boolean genericProperty ( Class < T > type , TermIdent term , boolean avoidInherit , Map < String , CSSProperty > properties , String propertyName ) { T property = genericPropertyRaw ( type , null , term ) ; if ( property == null || ( avoidInherit && property . equalsInherit ( ) ) ) return false ; properties . put ( propertyName , property ) ; return true ; }
Converts TermIdent into value of enum of given class and stores it into properties map under key property
38,708
protected < T extends CSSProperty > boolean genericTermIdent ( Class < T > type , Term < ? > term , boolean avoidInherit , String propertyName , Map < String , CSSProperty > properties ) { if ( term instanceof TermIdent ) { return genericProperty ( type , ( TermIdent ) term , avoidInherit , properties , propertyName ) ; } return false ; }
Converts TermIdent into value of CSSProperty for given class
38,709
protected < T extends CSSProperty > boolean genericTermColor ( Term < ? > term , String propertyName , T colorIdentification , Map < String , CSSProperty > properties , Map < String , Term < ? > > values ) { if ( term instanceof TermColor ) { properties . put ( propertyName , colorIdentification ) ; values . put ( propertyName , term ) ; return true ; } return false ; }
Converts term into Color and stored values and types in maps
38,710
protected < T extends CSSProperty > boolean genericTermLength ( Term < ? > term , String propertyName , T lengthIdentification , ValueRange range , Map < String , CSSProperty > properties , Map < String , Term < ? > > values ) { if ( term instanceof TermInteger && ( ( TermInteger ) term ) . getUnit ( ) . equals ( TermNumber . Unit . none ) ) { if ( CSSFactory . getImplyPixelLength ( ) || ( ( TermInteger ) term ) . getValue ( ) == 0 ) { TermLength tl = tf . createLength ( ( ( TermInteger ) term ) . getValue ( ) , TermNumber . Unit . px ) ; return genericTerm ( TermLength . class , tl , propertyName , lengthIdentification , range , properties , values ) ; } else { return false ; } } else if ( term instanceof TermLength ) { return genericTerm ( TermLength . class , term , propertyName , lengthIdentification , range , properties , values ) ; } return false ; }
Converts term into TermLength and stores values and types in maps
38,711
protected < T extends CSSProperty > boolean genericTerm ( Class < ? extends Term < ? > > termType , Term < ? > term , String propertyName , T typeIdentification , ValueRange range , Map < String , CSSProperty > properties , Map < String , Term < ? > > values ) { if ( termType . isInstance ( term ) ) { if ( range != ValueRange . ALLOW_ALL ) { if ( term . getValue ( ) instanceof Integer ) { final Integer zero = 0 ; int result = zero . compareTo ( ( Integer ) term . getValue ( ) ) ; if ( result > 0 ) { if ( range == ValueRange . TRUNCATE_NEGATIVE ) ( ( TermInteger ) term ) . setZero ( ) ; else return false ; } else if ( result == 0 ) { if ( range == ValueRange . DISALLOW_ZERO ) { return false ; } } } else if ( term . getValue ( ) instanceof java . lang . Float ) { final java . lang . Float zero = 0f ; int result = zero . compareTo ( ( java . lang . Float ) term . getValue ( ) ) ; if ( result > 0 ) { if ( range == ValueRange . TRUNCATE_NEGATIVE ) ( ( TermFloatValue ) term ) . setZero ( ) ; else return false ; } else if ( result == 0 ) { if ( range == ValueRange . DISALLOW_ZERO ) { return false ; } } } } properties . put ( propertyName , typeIdentification ) ; values . put ( propertyName , term ) ; return true ; } return false ; }
Check whether given declaration contains one term of given type . It is able to check even whether is above zero for numeric values
38,712
protected < T extends CSSProperty > boolean genericOneIdent ( Class < T > type , Declaration d , Map < String , CSSProperty > properties ) { if ( d . size ( ) != 1 ) return false ; return genericTermIdent ( type , d . get ( 0 ) , ALLOW_INH , d . getProperty ( ) , properties ) ; }
Processes declaration which is supposed to contain one identification term
38,713
protected < T extends CSSProperty > boolean genericOneIdentOrColor ( Class < T > type , T colorIdentification , Declaration d , Map < String , CSSProperty > properties , Map < String , Term < ? > > values ) { if ( d . size ( ) != 1 ) return false ; return genericTermIdent ( type , d . get ( 0 ) , ALLOW_INH , d . getProperty ( ) , properties ) || genericTermColor ( d . get ( 0 ) , d . getProperty ( ) , colorIdentification , properties , values ) ; }
Processes declaration which is supposed to contain one identification term or one TermColor
38,714
@ SuppressWarnings ( "unchecked" ) protected < R > R service ( ServiceRequest < R > request ) throws WssServiceException { R result ; String response = "" ; try { HttpRequestBase httpRequest = createHttpRequest ( request ) ; RequestConfig requestConfig = RequestConfig . custom ( ) . setCookieSpec ( CookieSpecs . STANDARD ) . build ( ) ; httpRequest . setConfig ( requestConfig ) ; logger . trace ( "Calling White Source service: " + request ) ; response = httpClient . execute ( httpRequest , new BasicResponseHandler ( ) ) ; String data = extractResultData ( response ) ; logger . trace ( "Result data is: " + data ) ; switch ( request . type ( ) ) { case UPDATE : result = ( R ) gson . fromJson ( data , UpdateInventoryResult . class ) ; break ; case CHECK_POLICIES : result = ( R ) gson . fromJson ( data , CheckPoliciesResult . class ) ; break ; case CHECK_POLICY_COMPLIANCE : result = ( R ) gson . fromJson ( data , CheckPolicyComplianceResult . class ) ; break ; case CHECK_VULNERABILITIES : result = ( R ) gson . fromJson ( data , CheckVulnerabilitiesResult . class ) ; break ; case GET_DEPENDENCY_DATA : result = ( R ) gson . fromJson ( data , GetDependencyDataResult . class ) ; break ; case SUMMARY_SCAN : result = ( R ) gson . fromJson ( data , SummaryScanResult . class ) ; break ; case GET_CONFIGURATION : result = ( R ) gson . fromJson ( data , ConfigurationResult . class ) ; break ; default : throw new IllegalStateException ( "Unsupported request type." ) ; } } catch ( JsonSyntaxException e ) { throw new WssServiceException ( "JsonSyntax exception. Response data is: " + response + e . getMessage ( ) , e ) ; } catch ( IOException e ) { throw new WssServiceException ( "Unexpected error. Response data is: " + response + e . getMessage ( ) , e ) ; } return result ; }
The method service the given request .
38,715
public static void copyResource ( String resource , File destination ) throws IOException { InputStream is = null ; FileOutputStream fos = null ; try { is = FileUtils . class . getResourceAsStream ( "/" + resource ) ; fos = new FileOutputStream ( destination ) ; final byte [ ] buffer = new byte [ 10 * 1024 ] ; int len ; while ( ( len = is . read ( buffer ) ) > 0 ) { fos . write ( buffer , 0 , len ) ; } } finally { close ( is ) ; close ( fos ) ; } }
Copy a classpath resource to a destination file .
38,716
public static boolean deleteRecursive ( File path ) throws FileNotFoundException { if ( ! path . exists ( ) ) { throw new FileNotFoundException ( path . getAbsolutePath ( ) ) ; } boolean success = true ; if ( path . isDirectory ( ) ) { for ( File f : path . listFiles ( ) ) { success = success && FileUtils . deleteRecursive ( f ) ; } } return success && path . delete ( ) ; }
Delete all files rooted in the given path .
38,717
public UpdateInventoryRequest offlineUpdate ( String orgToken , String product , Boolean removeBeforeAdd , String productVersion , Collection < AgentProjectInfo > projectInfos , String userKey , String requesterEmail , String scanComment , String productToken ) { return requestFactory . newUpdateInventoryRequest ( orgToken , requesterEmail , product , productVersion , projectInfos , userKey , scanComment , productToken ) ; }
Generates a file with json representation of the update request .
38,718
public GetDependencyDataResult getDependencyData ( String orgToken , String product , String productVersion , Collection < AgentProjectInfo > projectInfos , String userKey , String requesterEmail , String productToken ) throws WssServiceException { return client . getDependencyData ( requestFactory . newDependencyDataRequest ( orgToken , product , productVersion , projectInfos , userKey , requesterEmail , productToken ) ) ; }
Gets additional data for given dependencies .
38,719
public CheckVulnerabilitiesResult checkVulnerabilities ( String orgToken , String product , String productVersion , Collection < AgentProjectInfo > projectInfos , String userKey , String requesterEmail , String productToken ) throws WssServiceException { return client . checkVulnerabilities ( requestFactory . newCheckVulnerabilitiesRequest ( orgToken , product , productVersion , projectInfos , userKey , requesterEmail , productToken ) ) ; }
Gets vulnerabilities data for given dependencies .
38,720
public File generate ( File outputDir , boolean zip , boolean prettyJson ) throws IOException { if ( request == null ) { throw new IllegalStateException ( "Update inventory request is null" ) ; } File workDir = new File ( outputDir , "whitesource" ) ; if ( ! workDir . exists ( ) && ! workDir . mkdir ( ) ) { throw new IOException ( "Unable to make output directory: " + workDir ) ; } String json ; if ( zip ) { json = new Gson ( ) . toJson ( request ) ; json = ZipUtils . compressString ( json ) ; } else if ( prettyJson ) { Gson gson = new GsonBuilder ( ) . setPrettyPrinting ( ) . create ( ) ; json = gson . toJson ( request ) ; } else { json = new Gson ( ) . toJson ( request ) ; } File requestFile = new File ( workDir , "update-request.txt" ) ; FileUtils . writeStringToFile ( requestFile , json , UTF_8 ) ; return requestFile ; }
The method generates the update request file .
38,721
public Map < ChecksumType , String > calculateJavaScriptHashes ( File file ) throws WssHashException { Map < ChecksumType , String > checksums = new EnumMap < > ( ChecksumType . class ) ; try { long fileLength = file . length ( ) ; if ( fileLength >= FILE_MAX_SIZE_THRESHOLD ) { logger . debug ( "Ignore file {}, ({}): maximum file size is 2GB" , file . getName ( ) , FileUtils . byteCountToDisplaySize ( fileLength ) ) ; return checksums ; } checksums = calculateJavaScriptHashes ( FileUtils . readFileToByteArray ( file ) ) ; } catch ( Exception e ) { throw new WssHashException ( "Error calculating JavaScript hash: " + e . getMessage ( ) ) ; } return checksums ; }
Removes all JavaScript comments from the file and calculates SHA - 1 checksum .
38,722
public Map < ChecksumType , String > calculateJavaScriptHashes ( byte [ ] byteArray ) throws WssHashException { Map < ChecksumType , String > checksums = new EnumMap < > ( ChecksumType . class ) ; try { String fileContent = IOUtils . toString ( byteArray , UTF_8 ) ; ParseResult parseResult = new JavaScriptParser ( ) . parse ( fileContent ) ; if ( parseResult != null ) { String contentWithoutComments = parseResult . getContentWithoutComments ( ) ; if ( StringUtils . isNotBlank ( contentWithoutComments ) ) { HashCalculationResult noCommentsSha1 = calculateSuperHash ( contentWithoutComments . getBytes ( ) ) ; if ( noCommentsSha1 != null ) { checksums . put ( ChecksumType . SHA1_NO_COMMENTS_SUPER_HASH , noCommentsSha1 . getFullHash ( ) ) ; } } String headerlessContent = parseResult . getContentWithoutHeaderComments ( ) ; if ( StringUtils . isNotBlank ( headerlessContent ) ) { String headerlessChecksum = calculateByteArrayHash ( headerlessContent . getBytes ( ) , HashAlgorithm . SHA1 ) ; checksums . put ( ChecksumType . SHA1_NO_HEADER , headerlessChecksum ) ; } } } catch ( Exception e ) { throw new WssHashException ( "Error calculating JavaScript hash: " + e . getMessage ( ) ) ; } return checksums ; }
Removes all JavaScript header comments from the file and calculates SHA - 1 checksum .
38,723
public String calculateSha1ByNameVersionAndType ( String name , String version , DependencyType dependencyType ) throws IOException { String sha1ToCalc = name + UNDERSCORE + version + UNDERSCORE + dependencyType . toString ( ) ; return calculateByteArraySHA1 ( sha1ToCalc . getBytes ( StandardCharsets . UTF_8 ) ) ; }
Calculates SHA - 1 for library by name version and dependencyType
38,724
private byte [ ] stripWhiteSpaces ( byte [ ] data ) { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; for ( byte b : data ) { if ( ! WHITESPACES . contains ( b ) ) { bos . write ( b ) ; } } return bos . toByteArray ( ) ; }
Removes all whitespaces from the text - the same way that Shir is doing for source files .
38,725
public static String compress ( String text ) throws IOException { String result ; if ( text != null && text . length ( ) > 0 ) { try ( ByteArrayOutputStream baos = new ByteArrayOutputStream ( text . length ( ) ) ; GZIPOutputStream gzipos = new GZIPOutputStream ( baos ) ; ) { gzipos . write ( text . getBytes ( UTF_8 ) ) ; gzipos . close ( ) ; baos . close ( ) ; result = Base64 . encodeBase64String ( baos . toByteArray ( ) ) ; } } else { result = text ; } return result ; }
The method compresses the string using gzip .
38,726
public static String decompress ( String text ) throws IOException { if ( text == null || text . length ( ) == 0 ) { return text ; } byte [ ] bytes = Base64 . decodeBase64 ( text ) ; try ( GZIPInputStream gis = new GZIPInputStream ( new ByteArrayInputStream ( bytes ) ) ; BufferedReader bf = new BufferedReader ( new InputStreamReader ( gis , UTF_8 ) ) ; ) { StringBuilder outStr = new StringBuilder ( ) ; String line ; while ( ( line = bf . readLine ( ) ) != null ) { outStr . append ( line ) ; } return outStr . toString ( ) ; } }
The method decompresses the string using gzip .
38,727
public static void compressString ( InputStream inputStream , OutputStream outputStream ) throws IOException { try ( ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ( ) ) { fillExportStreamCompress ( inputStream , byteArrayOutputStream ) ; String result = getStringFromEncode ( byteArrayOutputStream . toByteArray ( ) ) ; try ( PrintWriter printWriter = new PrintWriter ( outputStream ) ) { printWriter . write ( result ) ; } } }
The method compresses the big strings using gzip - low memory via Streams
38,728
public static void decompressString ( InputStream inputStream , OutputStream outputStream ) throws IOException { try ( InputStream bufferedInputStream = new BufferedInputStream ( inputStream ) ; PrintWriter printWriter = new PrintWriter ( outputStream ) ; ) { byte [ ] buffer = new byte [ BYTES_BUFFER_SIZE ] ; int len ; while ( ( len = bufferedInputStream . read ( buffer ) ) > 0 ) { String val = new String ( buffer , StandardCharsets . UTF_8 ) ; String str = decompressString ( val ) ; printWriter . write ( str ) ; } } }
The method decompresses the big strings using gzip - low memory via Streams
38,729
public static String compressChunks ( String text ) throws IOException { Path tempFolder = Paths . get ( JAVA_TEMP_DIR , ZIP_UTILS ) ; File tempFileIn = File . createTempFile ( TMP_IN_ , ZIP_UTILS_SUFFIX , tempFolder . toFile ( ) ) ; File tempFileOut = File . createTempFile ( TMP_OUT_ , ZIP_UTILS_SUFFIX , tempFolder . toFile ( ) ) ; writeChunkBytes ( text , tempFileIn ) ; String result ; if ( text != null && text . length ( ) > 0 ) { try ( InputStream in = new FileInputStream ( tempFileIn ) ; FileOutputStream fileOutputStream = new FileOutputStream ( tempFileOut ) ; BufferedOutputStream bufferedOutputStream = new BufferedOutputStream ( fileOutputStream ) ; OutputStream out = new GZIPOutputStream ( bufferedOutputStream ) ; ) { byte [ ] bytes = new byte [ BYTES_BUFFER_SIZE ] ; int len ; while ( ( len = in . read ( bytes ) ) > 0 ) { out . write ( bytes , 0 , len ) ; } in . close ( ) ; out . flush ( ) ; out . close ( ) ; result = Base64 . encodeBase64String ( Files . readAllBytes ( tempFileOut . toPath ( ) ) ) ; } } else { result = text ; } Files . deleteIfExists ( tempFileIn . toPath ( ) ) ; Files . deleteIfExists ( tempFileOut . toPath ( ) ) ; return result ; }
The method compresses the big strings using gzip - low memory via the File system
38,730
private static void writeChunkBytes ( String text , File tempFileIn ) throws IOException { try ( FileOutputStream writer = new FileOutputStream ( tempFileIn ) ) { int chunk = text . length ( ) ; if ( text . length ( ) > STRING_MAX_SIZE ) { chunk = text . length ( ) / STRING_MAX_SIZE ; } int startString = 0 ; while ( startString < text . length ( ) ) { int endString = startString + chunk ; if ( endString > text . length ( ) ) { endString = text . length ( ) ; } byte [ ] bytes = text . substring ( startString , endString ) . getBytes ( StandardCharsets . UTF_8 ) ; writer . write ( bytes ) ; startString = endString ; } } }
Writes a string piece by piece to file
38,731
protected VelocityEngine createTemplateEngine ( Properties properties ) { Properties actualProperties = properties ; if ( actualProperties == null ) { actualProperties = new Properties ( ) ; } String resourceLoader = actualProperties . getProperty ( VelocityEngine . RESOURCE_LOADER ) ; if ( StringUtils . isBlank ( resourceLoader ) ) { actualProperties . setProperty ( VelocityEngine . RESOURCE_LOADER , "classpath" ) ; actualProperties . setProperty ( "classpath.resource.loader.class" , ClasspathResourceLoader . class . getName ( ) ) ; } String loggerClass = actualProperties . getProperty ( VelocityEngine . RUNTIME_LOG_LOGSYSTEM_CLASS ) ; if ( StringUtils . isBlank ( loggerClass ) ) { actualProperties . setProperty ( VelocityEngine . RUNTIME_LOG_LOGSYSTEM_CLASS , "org.apache.velocity.runtime.log.NullLogChute" ) ; } VelocityEngine velocity = new VelocityEngine ( actualProperties ) ; velocity . init ( ) ; return velocity ; }
Create and initialize a template engine to use for generating reports .
38,732
protected VelocityContext createTemplateContext ( ) { VelocityContext context = new VelocityContext ( ) ; context . put ( "result" , result ) ; context . put ( "hasRejections" , result . hasRejections ( ) ) ; context . put ( "licenses" , createLicenseHistogram ( result ) ) ; context . put ( "creationTime" , new SimpleDateFormat ( DATE_FORMAT ) . format ( new Date ( ) ) ) ; if ( StringUtils . isNotBlank ( buildName ) ) { context . put ( "buildName" , buildName ) ; } if ( StringUtils . isNotBlank ( buildNumber ) ) { context . put ( "buildNumber" , buildNumber ) ; } return context ; }
Create the context holding all the information of the report .
38,733
protected void copyReportResources ( File workDir ) throws IOException { FileUtils . copyResource ( TEMPLATE_FOLDER + CSS_FILE , new File ( workDir , CSS_FILE ) ) ; }
Copy required resources for the report .
38,734
public ParseResult parse ( String fileContent ) { ParseResult result = null ; CompilerEnvirons environment = new CompilerEnvirons ( ) ; environment . setLanguageVersion ( 180 ) ; environment . setStrictMode ( false ) ; environment . setRecordingComments ( true ) ; environment . setAllowSharpComments ( true ) ; environment . setRecordingLocalJsDocComments ( true ) ; Parser parser = new Parser ( environment ) ; try { AstRoot root = parser . parse ( new StringReader ( fileContent ) , null , 1 ) ; result = new ParseResult ( ) ; result . setContentWithoutComments ( root . toSource ( ) ) ; SortedSet < Comment > comments = root . getComments ( ) ; if ( comments != null && ! comments . isEmpty ( ) ) { String headerlessFileContent = removeHeaderComments ( fileContent , comments ) ; result . setContentWithoutHeaderComments ( headerlessFileContent ) ; } } catch ( Exception e ) { logger . debug ( "Error parsing JavaScript file: {}" , e . getMessage ( ) ) ; } return result ; }
Parse the file content and return variants of the file .
38,735
private String removeHeaderComments ( String fileContent , SortedSet < Comment > comments ) { String headerlessFileContent = fileContent ; for ( Comment comment : comments ) { String commentValue = comment . getValue ( ) ; if ( headerlessFileContent . startsWith ( commentValue ) ) { headerlessFileContent = headerlessFileContent . replace ( commentValue , EMPTY_STRING ) ; while ( StringUtils . isNotBlank ( headerlessFileContent ) && Character . isWhitespace ( headerlessFileContent . charAt ( 0 ) ) ) { headerlessFileContent = headerlessFileContent . substring ( 1 ) ; } } else { break ; } } return headerlessFileContent ; }
Go over each comment and remove from content until reaching the beginning of the actual code .
38,736
private static String executePowerShellCommand ( String command ) { try { String [ ] commandList = { POWER_SHELL , POWER_SHELL_COMMAND , command } ; ProcessBuilder pb = new ProcessBuilder ( commandList ) ; Process process = pb . start ( ) ; InputStream is = process . getInputStream ( ) ; InputStreamReader isr = new InputStreamReader ( is ) ; BufferedReader br = new BufferedReader ( isr ) ; String line ; while ( ( line = br . readLine ( ) ) != null ) { if ( line . startsWith ( COMMON_NAME_PARAMETER ) ) { String [ ] values = line . split ( COMMA_SPLIT ) ; return values [ 0 ] . substring ( values [ 0 ] . indexOf ( EQUAL_SPLIT ) + 1 ) ; } } } catch ( Exception e ) { } return null ; }
Get the signature from file by execute process from power shell
38,737
private static List < String > getGenericTypeParameters ( String parameters ) { List < String > paramList = new ArrayList < String > ( ) ; int balanced = 0 ; StringBuilder current = new StringBuilder ( ) ; for ( int i = 0 ; i < parameters . length ( ) ; i ++ ) { char c = parameters . charAt ( i ) ; if ( balanced == 0 && c == ',' ) { paramList . add ( current . toString ( ) . trim ( ) ) ; current = new StringBuilder ( ) ; continue ; } else if ( c == '<' ) { balanced ++ ; } else if ( c == '>' ) { balanced -- ; } current . append ( c ) ; } paramList . add ( current . toString ( ) ) ; return paramList ; }
parse generic type parameters making sure nested generics are taken into account
38,738
public < A extends Annotation > A findAnnotationOnBean ( Class < A > annotationType ) { return applicationContext . findAnnotationOnBean ( beanName , annotationType ) ; }
Attempts to find and return an annotation of the specified type declared on this side bar item .
38,739
public void destroy ( ) { if ( executorService != null ) { LOGGER . info ( "Shutting down message provider cache cleanup thread" ) ; cleanupJob . cancel ( true ) ; executorService . shutdown ( ) ; } }
Shuts down the cleanup thread .
38,740
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 .
38,741
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 .
38,742
@ 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
38,743
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 .
38,744
public Collection < SideBarSectionDescriptor > getSideBarSections ( Class < ? extends UI > uiClass ) { List < SideBarSectionDescriptor > supportedSections = new ArrayList < SideBarSectionDescriptor > ( ) ; for ( SideBarSectionDescriptor section : sections ) { if ( section . isAvailableFor ( uiClass ) ) { supportedSections . add ( section ) ; } } return supportedSections ; }
Gets all side bar sections for the specified UI class .
38,745
public Collection < SideBarItemDescriptor > getSideBarItems ( SideBarSectionDescriptor descriptor ) { List < SideBarItemDescriptor > supportedItems = new ArrayList < SideBarItemDescriptor > ( ) ; for ( SideBarItemDescriptor item : items ) { if ( item . isMemberOfSection ( descriptor ) ) { supportedItems . add ( item ) ; } } return supportedItems ; }
Gets all side bar items for the specified side bar section .
38,746
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 ( transport ) || Transport . WEBSOCKET_XHR . equals ( transport ) ) { LOGGER . warn ( "Clearing and reinitializing the session is currently not supported when using Websocket Push." ) ; return ; } } if ( currentRequest != null ) { LOGGER . debug ( "Clearing the session" ) ; final WrappedSession session = currentRequest . getWrappedSession ( ) ; final String serviceName = VaadinService . getCurrent ( ) . getServiceName ( ) ; final Set < String > attributesToSpare = new HashSet < String > ( ) ; attributesToSpare . add ( serviceName + ".lock" ) ; attributesToSpare . add ( VaadinSession . class . getName ( ) + "." + serviceName ) ; for ( String s : currentRequest . getWrappedSession ( ) . getAttributeNames ( ) ) { if ( ! attributesToSpare . contains ( s ) ) { LOGGER . trace ( "Removing attribute {} from session" , s ) ; session . removeAttribute ( s ) ; } } LOGGER . debug ( "Reinitializing the session {}" , session . getId ( ) ) ; VaadinService . reinitializeSession ( currentRequest ) ; LOGGER . debug ( "Session reinitialized, new ID is {}" , VaadinService . getCurrentRequest ( ) . getWrappedSession ( ) . getId ( ) ) ; } else { LOGGER . warn ( "No VaadinRequest bound to current thread, could NOT clear/reinitialize the session after login" ) ; } }
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 .
38,747
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 .
38,748
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 .
38,749
public File getJarDirectory ( ) { if ( jarDirectory == null ) { this . jarDirectory = new File ( jarPath ) . getAbsoluteFile ( ) . getParentFile ( ) ; } return jarDirectory ; }
Gets the directory of the jar - file
38,750
public static ApiResponseObjectDoc buildResponse ( Method method ) { ApiResponseObjectDoc apiResponseObjectDoc = new ApiResponseObjectDoc ( JSONDocTypeBuilder . build ( new JSONDocType ( ) , method . getReturnType ( ) , method . getGenericReturnType ( ) ) ) ; if ( method . getReturnType ( ) . isAssignableFrom ( ResponseEntity . class ) ) { apiResponseObjectDoc . getJsondocType ( ) . getType ( ) . remove ( 0 ) ; } return apiResponseObjectDoc ; }
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 .
38,751
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 .
38,752
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_PARAM_NAME = "Missing documentation data: query parameter name" ; final String ERROR_MISSING_HEADER_NAME = "Missing documentation data: header name" ; final String WARN_MISSING_METHOD_PRODUCES = "Missing documentation data: produces" ; final String WARN_MISSING_METHOD_CONSUMES = "Missing documentation data: consumes" ; final String HINT_MISSING_PATH_PARAM_DESCRIPTION = "Add description to ApiPathParam" ; final String HINT_MISSING_QUERY_PARAM_DESCRIPTION = "Add description to ApiQueryParam" ; final String HINT_MISSING_METHOD_DESCRIPTION = "Add description to ApiMethod" ; final String HINT_MISSING_METHOD_RESPONSE_OBJECT = "Add annotation ApiResponseObject to document the returned object" ; final String HINT_MISSING_METHOD_SUMMARY = "Method display set to SUMMARY, but summary info has not been specified" ; final String MESSAGE_MISSING_METHOD_SUMMARY = "Missing documentation data: summary" ; if ( apiMethodDoc . getPath ( ) . isEmpty ( ) ) { apiMethodDoc . setPath ( Sets . newHashSet ( ERROR_MISSING_METHOD_PATH ) ) ; apiMethodDoc . addJsondocerror ( ERROR_MISSING_METHOD_PATH ) ; } if ( apiMethodDoc . getSummary ( ) . trim ( ) . isEmpty ( ) && displayMethodAs . equals ( MethodDisplay . SUMMARY ) ) { apiMethodDoc . setSummary ( MESSAGE_MISSING_METHOD_SUMMARY ) ; apiMethodDoc . addJsondochint ( HINT_MISSING_METHOD_SUMMARY ) ; } for ( ApiParamDoc apiParamDoc : apiMethodDoc . getPathparameters ( ) ) { if ( apiParamDoc . getName ( ) . trim ( ) . isEmpty ( ) ) { apiMethodDoc . addJsondocerror ( ERROR_MISSING_PATH_PARAM_NAME ) ; } if ( apiParamDoc . getDescription ( ) . trim ( ) . isEmpty ( ) ) { apiMethodDoc . addJsondochint ( HINT_MISSING_PATH_PARAM_DESCRIPTION ) ; } } for ( ApiParamDoc apiParamDoc : apiMethodDoc . getQueryparameters ( ) ) { if ( apiParamDoc . getName ( ) . trim ( ) . isEmpty ( ) ) { apiMethodDoc . addJsondocerror ( ERROR_MISSING_QUERY_PARAM_NAME ) ; } if ( apiParamDoc . getDescription ( ) . trim ( ) . isEmpty ( ) ) { apiMethodDoc . addJsondochint ( HINT_MISSING_QUERY_PARAM_DESCRIPTION ) ; } } for ( ApiHeaderDoc apiHeaderDoc : apiMethodDoc . getHeaders ( ) ) { if ( apiHeaderDoc . getName ( ) . trim ( ) . isEmpty ( ) ) { apiMethodDoc . addJsondocerror ( ERROR_MISSING_HEADER_NAME ) ; } } if ( apiMethodDoc . getProduces ( ) . isEmpty ( ) ) { apiMethodDoc . addJsondocwarning ( WARN_MISSING_METHOD_PRODUCES ) ; } if ( ( apiMethodDoc . getVerb ( ) . contains ( ApiVerb . POST ) || apiMethodDoc . getVerb ( ) . contains ( ApiVerb . PUT ) ) && apiMethodDoc . getConsumes ( ) . isEmpty ( ) ) { apiMethodDoc . addJsondocwarning ( WARN_MISSING_METHOD_CONSUMES ) ; } if ( apiMethodDoc . getDescription ( ) . trim ( ) . isEmpty ( ) ) { apiMethodDoc . addJsondochint ( HINT_MISSING_METHOD_DESCRIPTION ) ; } if ( apiMethodDoc . getResponse ( ) == null ) { apiMethodDoc . addJsondochint ( HINT_MISSING_METHOD_RESPONSE_OBJECT ) ; } return apiMethodDoc ; }
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 does not happen an error string is added to the jsondocwarnings list in ApiMethodDoc .
38,753
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
38,754
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 ( JSONDocApiAuthDocBuilder . getApiAuthDocForController ( controller ) ) ; apiDoc . setMethods ( getApiMethodDocs ( controller , displayMethodAs ) ) ; if ( controller . isAnnotationPresent ( Api . class ) ) { apiDoc = mergeApiDoc ( controller , apiDoc ) ; } return apiDoc ; }
Gets the API documentation for a single class annotated with
38,755
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 . getMethods ( ) ; for ( Method method : methods ) { if ( method . isAnnotationPresent ( ApiFlow . class ) ) { ApiFlowDoc apiFlowDoc = getApiFlowDoc ( method , apiMethodDocs ) ; apiFlowDocs . add ( apiFlowDoc ) ; } } } return apiFlowDocs ; }
Gets the API flow documentation for the set of classes passed as argument
38,756
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 ( new ApiParamDoc ( splitParam [ 0 ] , "" , JSONDocTypeBuilder . build ( new JSONDocType ( ) , String . class , null ) , "true" , new String [ ] { splitParam [ 1 ] } , null , null ) ) ; } else { apiParamDocs . add ( new ApiParamDoc ( param , "" , JSONDocTypeBuilder . build ( new JSONDocType ( ) , String . class , null ) , "true" , new String [ ] { } , null , null ) ) ; } } } }
Checks the request mapping annotation value and adds the resulting
38,757
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 = buildFromAnnotation ( typeAnnotation ) ; } if ( methodAnnotation != null ) { apiVersionDoc = buildFromAnnotation ( method . getAnnotation ( ApiVersion . class ) ) ; } return apiVersionDoc ; }
In case this annotation is present at type and method level then the method annotation will override the type one .
38,758
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 false ; }
if 200 ok delay is enabled we need to answer only the calls which are having any further call enabler verbs in their RCML .
38,759
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
38,760
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
38,761
private void removeAccoundDependencies ( Sid sid ) { logger . debug ( "removing accoutn dependencies" ) ; DaoManager daoManager = ( DaoManager ) context . getAttribute ( DaoManager . class . getName ( ) ) ; daoManager . getAnnouncementsDao ( ) . removeAnnouncements ( sid ) ; daoManager . getNotificationsDao ( ) . removeNotifications ( sid ) ; daoManager . getShortCodesDao ( ) . removeShortCodes ( sid ) ; daoManager . getOutgoingCallerIdsDao ( ) . removeOutgoingCallerIds ( sid ) ; daoManager . getTranscriptionsDao ( ) . removeTranscriptions ( sid ) ; daoManager . getRecordingsDao ( ) . removeRecordings ( sid ) ; daoManager . getApplicationsDao ( ) . removeApplications ( sid ) ; removeIncomingPhoneNumbers ( sid , daoManager . getIncomingPhoneNumbersDao ( ) ) ; daoManager . getClientsDao ( ) . removeClients ( sid ) ; profileAssociationsDao . deleteProfileAssociationByTargetSid ( sid . toString ( ) ) ; }
Removes all dependent resources of an account . Some resources like CDRs are excluded .
38,762
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 ( IncomingPhoneNumber number : numbers ) { if ( number . isPureSip ( ) == null || ! number . isPureSip ( ) ) { if ( ! managerQueried ) manager = new PhoneNumberProvisioningManagerProvider ( rootConfiguration , context ) . get ( ) ; if ( manager != null ) { try { if ( ! manager . cancelNumber ( IncomingPhoneNumbersEndpoint . convertIncomingPhoneNumbertoPhoneNumber ( number ) ) ) { logger . error ( "Number cancelation failed for provided number '" + number . getPhoneNumber ( ) + "'. Number entity " + number . getSid ( ) + " will stay in database" ) ; } else { dao . removeIncomingPhoneNumber ( number . getSid ( ) ) ; } } catch ( Exception e ) { logger . error ( "Number cancelation failed for provided number '" + number . getPhoneNumber ( ) + "'" , e ) ; } } else logger . error ( "Number cancelation failed for provided number '" + number . getPhoneNumber ( ) + "'. Provisioning Manager was null. " + "Number entity " + number . getSid ( ) + " will stay in database" ) ; } else { dao . removeIncomingPhoneNumber ( number . getSid ( ) ) ; } } } }
Removes incoming phone numbers that belong to an account from the database . For provided numbers the provider is also contacted to get them released .
38,763
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 = Account . Status . getValueOf ( data . getFirst ( "Status" ) . toLowerCase ( ) ) ; accBuilder . setStatus ( newStatus ) ; } if ( data . containsKey ( "FriendlyName" ) ) { accBuilder . setFriendlyName ( data . getFirst ( "FriendlyName" ) ) ; } if ( data . containsKey ( "Password" ) ) { if ( account . getStatus ( ) == Account . Status . UNINITIALIZED ) { accBuilder . setStatus ( Account . Status . ACTIVE ) ; } String password = data . getFirst ( "Password" ) ; PasswordValidator validator = PasswordValidatorFactory . createDefault ( ) ; if ( ! validator . isStrongEnough ( password ) ) { CustomReasonPhraseType stat = new CustomReasonPhraseType ( Response . Status . BAD_REQUEST , "Password too weak" ) ; throw new WebApplicationException ( status ( stat ) . build ( ) ) ; } final String hash = new Md5Hash ( data . getFirst ( "Password" ) ) . toString ( ) ; accBuilder . setAuthToken ( hash ) ; } if ( data . containsKey ( "Role" ) ) { if ( userIdentityContext . getEffectiveAccountRoles ( ) . contains ( permissionEvaluator . getAdministratorRole ( ) ) ) { accBuilder . setRole ( data . getFirst ( "Role" ) ) ; } else { CustomReasonPhraseType stat = new CustomReasonPhraseType ( Response . Status . FORBIDDEN , "Only Administrator allowed" ) ; throw new WebApplicationException ( status ( stat ) . build ( ) ) ; } } return accBuilder . build ( ) ; }
Fills an account entity object with values supplied from an http request
38,764
private void updateLinkedClient ( Account account , MultivaluedMap < String , String > data ) { logger . debug ( "checking linked client" ) ; String email = account . getEmailAddress ( ) ; if ( email != null && ! email . equals ( "" ) ) { logger . debug ( "account email is valid" ) ; String username = email . split ( "@" ) [ 0 ] ; Client client = clientDao . getClient ( username , account . getOrganizationSid ( ) ) ; if ( client != null ) { logger . debug ( "client found" ) ; if ( data . containsKey ( "Password" ) ) { logger . debug ( "password changed" ) ; String password = data . getFirst ( "Password" ) ; client = client . setPassword ( client . getLogin ( ) , password , organizationsDao . getOrganization ( account . getOrganizationSid ( ) ) . getDomainName ( ) ) ; } if ( data . containsKey ( "FriendlyName" ) ) { logger . debug ( "friendlyname changed" ) ; client = client . setFriendlyName ( data . getFirst ( "FriendlyName" ) ) ; } logger . debug ( "updating linked client" ) ; clientDao . updateClient ( client ) ; } } }
update SIP client of the corresponding Account . Password and FriendlyName fields are synched .
38,765
private void switchAccountStatus ( Account account , Account . Status status , UserIdentityContext userIdentityContext ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Switching status for account:" + account . getSid ( ) + ",status:" + status ) ; } switch ( status ) { case CLOSED : sendRVDStatusNotification ( account , userIdentityContext ) ; removeAccoundDependencies ( account . getSid ( ) ) ; break ; default : break ; } account = account . setStatus ( status ) ; accountsDao . updateAccount ( account ) ; }
Switches an account status at dao level .
38,766
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 . matcher ( extensionId ) . matches ( ) ) { extensionSid = new Sid ( extensionId ) ; } else { extensionName = extensionId ; } if ( Sid . pattern . matcher ( extensionId ) . matches ( ) ) { try { extensionConfiguration = extensionsConfigurationDao . getConfigurationBySid ( extensionSid ) ; } catch ( Exception e ) { return status ( NOT_FOUND ) . build ( ) ; } } else { try { extensionConfiguration = extensionsConfigurationDao . getConfigurationByName ( extensionName ) ; } catch ( Exception e ) { return status ( NOT_FOUND ) . build ( ) ; } } if ( accountSid != null ) { if ( extensionSid == null ) { extensionSid = extensionConfiguration . getSid ( ) ; } try { extensionAccountConfiguration = extensionsConfigurationDao . getAccountExtensionConfiguration ( accountSid . toString ( ) , extensionSid . toString ( ) ) ; extensionConfiguration . setConfigurationData ( extensionAccountConfiguration . getConfigurationData ( ) , extensionAccountConfiguration . getConfigurationType ( ) ) ; } catch ( Exception e ) { return status ( NOT_FOUND ) . build ( ) ; } } if ( extensionConfiguration == null ) { return status ( NOT_FOUND ) . build ( ) ; } else { if ( APPLICATION_XML_TYPE . equals ( responseType ) ) { final RestCommResponse response = new RestCommResponse ( extensionConfiguration ) ; return ok ( xstream . toXML ( response ) , APPLICATION_XML ) . build ( ) ; } else if ( APPLICATION_JSON_TYPE . equals ( responseType ) ) { return ok ( gson . toJson ( extensionConfiguration ) , APPLICATION_JSON ) . build ( ) ; } else { return null ; } } }
Will be used to get configuration for extension
38,767
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 Application application = applications . getApplication ( applicationSid ) ; RcmlserverConfigurationSet rcmlserverConfig = RestcommConfiguration . getInstance ( ) . getRcmlserver ( ) ; RcmlserverResolver resolver = RcmlserverResolver . getInstance ( rcmlserverConfig . getBaseUrl ( ) , rcmlserverConfig . getApiPath ( ) ) ; clientAppVoiceUrl = uriUtils . resolve ( resolver . resolveRelative ( application . getRcmlUrl ( ) ) , client . getAccountSid ( ) ) ; } if ( clientAppVoiceUrl == null ) { clientAppVoiceUrl = client . getVoiceUrl ( ) ; } boolean isClientManaged = ( ( applicationSid != null && ! applicationSid . toString ( ) . isEmpty ( ) && ! applicationSid . toString ( ) . equals ( "" ) ) || ( clientAppVoiceUrl != null && ! clientAppVoiceUrl . toString ( ) . isEmpty ( ) && ! clientAppVoiceUrl . toString ( ) . equals ( "" ) ) ) ; if ( isClientManaged ) { final VoiceInterpreterParams . Builder builder = new VoiceInterpreterParams . Builder ( ) ; builder . setConfiguration ( configuration ) ; builder . setStorage ( storage ) ; builder . setCallManager ( self ) ; builder . setConferenceCenter ( conferences ) ; builder . setBridgeManager ( bridges ) ; builder . setSmsService ( sms ) ; builder . setAccount ( client . getAccountSid ( ) ) ; builder . setVersion ( client . getApiVersion ( ) ) ; final Account account = accounts . getAccount ( client . getAccountSid ( ) ) ; builder . setEmailAddress ( account . getEmailAddress ( ) ) ; final Sid sid = client . getVoiceApplicationSid ( ) ; builder . setUrl ( clientAppVoiceUrl ) ; builder . setMethod ( client . getVoiceMethod ( ) ) ; URI uri = client . getVoiceFallbackUrl ( ) ; if ( uri != null ) builder . setFallbackUrl ( uriUtils . resolve ( uri , client . getAccountSid ( ) ) ) ; else builder . setFallbackUrl ( null ) ; builder . setFallbackMethod ( client . getVoiceFallbackMethod ( ) ) ; builder . setMonitoring ( monitoring ) ; final Props props = VoiceInterpreter . props ( builder . build ( ) ) ; final ActorRef interpreter = getContext ( ) . actorOf ( props ) ; final ActorRef call = call ( client . getAccountSid ( ) , null ) ; final SipApplicationSession application = request . getApplicationSession ( ) ; application . setAttribute ( Call . class . getName ( ) , call ) ; call . tell ( request , self ) ; interpreter . tell ( new StartInterpreter ( call ) , self ) ; } return isClientManaged ; }
If there is VoiceUrl provided for a Client configuration try to begin execution of the RCML app otherwise return false .
38,768
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 .
38,769
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 ( SORT_DIRECTION_KEY , values [ 1 ] ) ; if ( sortParameters . get ( SORT_BY_KEY ) . isEmpty ( ) ) { throw new Exception ( "Error parsing the SortBy parameter: missing field to sort by" ) ; } if ( ! sortParameters . get ( SORT_DIRECTION_KEY ) . equalsIgnoreCase ( Direction . ASC . name ( ) ) && ! sortParameters . get ( SORT_DIRECTION_KEY ) . equalsIgnoreCase ( Direction . DESC . name ( ) ) ) { throw new Exception ( "Error parsing the SortBy parameter: sort direction needs to be either " + Direction . ASC + " or " + Direction . DESC ) ; } } else if ( values . length == 1 ) { sortParameters . put ( SORT_DIRECTION_KEY , Direction . ASC . name ( ) ) ; } return sortParameters ; }
Parse the sorting part of the URI and return sortBy and sortDirection counterparts
38,770
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
38,771
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 ( URISyntaxException e ) { logger . error ( "Cannot resolve uri: " + uri . toString ( ) + ". Ignoring..." , e ) ; } } return uri ; }
if rvdOrigin is null no point in trying to resolve RVD location . We will return passed uri instead
38,772
private HttpConnectorList getHttpConnectors ( ) throws Exception { logger . info ( "Searching HTTP connectors." ) ; HttpConnectorList httpConnectorList = null ; httpConnectorList = jBossConnectorDiscover . findConnectors ( ) ; if ( httpConnectorList == null || httpConnectorList . getConnectors ( ) . isEmpty ( ) ) { httpConnectorList = new TomcatConnectorDiscover ( ) . findConnectors ( ) ; } return httpConnectorList ; }
Will query different JMX MBeans for a list of runtime connectors .
38,773
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 . getOrganizationsDao ( ) . getOrganization ( organizationSid ) . getDomainName ( ) ; } if ( restcommAddress == null || restcommAddress . isEmpty ( ) ) { if ( useHostnameToResolve ) { restcommAddress = RestcommConfiguration . getInstance ( ) . getMain ( ) . getHostname ( ) ; if ( restcommAddress == null || restcommAddress . isEmpty ( ) ) { try { InetAddress addr = DNSUtils . getByName ( selectedConnector . getAddress ( ) ) ; restcommAddress = addr . getCanonicalHostName ( ) ; } catch ( UnknownHostException e ) { logger . error ( "Unable to resolveWithBase: " + selectedConnector + " to hostname: " + e ) ; restcommAddress = selectedConnector . getAddress ( ) ; } } } else { restcommAddress = selectedConnector . getAddress ( ) ; } } String base = selectedConnector . getScheme ( ) + "://" + restcommAddress + ":" + selectedConnector . getPort ( ) ; try { return resolveWithBase ( new URI ( base ) , uri ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( "Badly formed URI: " + base , e ) ; } }
Use to resolve a relative URI using the domain name of the Organization that the provided AccountSid belongs
38,774
public HttpConnector getHttpConnector ( ) throws RuntimeException { if ( selectedConnector == null ) { try { HttpConnectorList httpConnectorList = getHttpConnectors ( ) ; if ( httpConnectorList != null && ! httpConnectorList . getConnectors ( ) . isEmpty ( ) ) { List < HttpConnector > connectors = httpConnectorList . getConnectors ( ) ; Iterator < HttpConnector > iterator = connectors . iterator ( ) ; while ( iterator . hasNext ( ) ) { HttpConnector connector = iterator . next ( ) ; if ( connector . isSecure ( ) ) { selectedConnector = connector ; } } if ( selectedConnector == null ) { selectedConnector = connectors . get ( 0 ) ; } } if ( selectedConnector == null ) { throw new RuntimeException ( "No HttpConnector found" ) ; } } catch ( Exception e ) { throw new RuntimeException ( "Exception during HTTP Connectors discovery: " , e ) ; } } return selectedConnector ; }
For historical reasons this method never returns null and instead throws a RuntimeException .
38,775
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 ) ; } } for ( IncomingPhoneNumber nAux : toBeRemoved ) { numbers . remove ( nAux ) ; } } }
SMPP is not supporting organizations at the moment disable regexes to prevent an organization to capture all cloud traffic with a single regex .
38,776
public HttpConnectorList findConnectors ( ) throws MalformedObjectNameException , NullPointerException , UnknownHostException , AttributeNotFoundException , InstanceNotFoundException , MBeanException , ReflectionException { LOG . info ( "Searching JBoss HTTP connectors." ) ; HttpConnectorList httpConnectorList = null ; MBeanServer mbs = ManagementFactory . getPlatformMBeanServer ( ) ; Set < ObjectName > jbossObjs = mbs . queryNames ( new ObjectName ( "jboss.as:socket-binding-group=standard-sockets,socket-binding=http*" ) , null ) ; LOG . info ( "JBoss Mbean found." ) ; ArrayList < HttpConnector > endPoints = new ArrayList < HttpConnector > ( ) ; if ( jbossObjs != null && jbossObjs . size ( ) > 0 ) { LOG . info ( "JBoss Connectors found:" + jbossObjs . size ( ) ) ; for ( ObjectName obj : jbossObjs ) { Boolean bound = ( Boolean ) mbs . getAttribute ( obj , "bound" ) ; if ( bound ) { String scheme = mbs . getAttribute ( obj , "name" ) . toString ( ) . replaceAll ( "\"" , "" ) ; Integer port = ( Integer ) mbs . getAttribute ( obj , "boundPort" ) ; String address = ( ( String ) mbs . getAttribute ( obj , "boundAddress" ) ) . replaceAll ( "\"" , "" ) ; if ( LOG . isInfoEnabled ( ) ) { LOG . info ( "Jboss Http Connector: " + scheme + "://" + address + ":" + port ) ; } HttpConnector httpConnector = new HttpConnector ( scheme , address , port , scheme . equalsIgnoreCase ( "https" ) ) ; endPoints . add ( httpConnector ) ; } else { LOG . info ( "JBoss Connector not bound,discarding." ) ; } } } if ( endPoints . isEmpty ( ) ) { LOG . warn ( "Coundn't discover any Http Interfaces." ) ; } httpConnectorList = new HttpConnectorList ( endPoints ) ; return httpConnectorList ; }
A list of connectors . Not bound connectors will be discarded .
38,777
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
38,778
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 .
38,779
private AuthOutcome checkPermission ( String neededPermissionString , Set < String > roleNames ) { if ( roleNames . contains ( getAdministratorRole ( ) ) ) return AuthOutcome . OK ; WildcardPermissionResolver resolver = new WildcardPermissionResolver ( ) ; Permission neededPermission = resolver . resolvePermission ( neededPermissionString ) ; RestcommRoles restcommRoles = identityContext . getRestcommRoles ( ) ; for ( String roleName : roleNames ) { SimpleRole simpleRole = restcommRoles . getRole ( roleName ) ; if ( simpleRole == null ) { return AuthOutcome . FAILED ; } else { Set < Permission > permissions = simpleRole . getPermissions ( ) ; for ( Permission permission : permissions ) { if ( permission . implies ( neededPermission ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Granted access by permission " + permission . toString ( ) ) ; } return AuthOutcome . OK ; } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Role " + roleName + " does not allow " + neededPermissionString ) ; } } } return AuthOutcome . FAILED ; }
Low level permission checking . roleNames are checked for neededPermissionString permission using permission mappings contained in restcomm . xml . The permission mappings are stored in RestcommRoles .
38,780
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 ( map . get ( field_prefix + "phone_number" ) ) , readString ( map . get ( field_prefix + "voice_application_sid" ) ) , readString ( map . get ( field_prefix + "sms_application_sid" ) ) , readString ( map . get ( field_prefix + "ussd_application_sid" ) ) , readString ( map . get ( field_prefix + "refer_application_sid" ) ) ) ; List < ApplicationNumberSummary > numbers = application . getNumbers ( ) ; if ( numbers == null ) { numbers = new ArrayList < ApplicationNumberSummary > ( ) ; application . setNumbers ( numbers ) ; } numbers . add ( number ) ; }
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 .
38,781
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 .
38,782
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 ( method ) && ! org . apache . http . client . methods . HttpPost . METHOD_NAME . equalsIgnoreCase ( method ) ) { final Notification notification = notification ( WARNING_NOTIFICATION , 14104 , method + " is not a valid HTTP method for <Sms>" ) ; storage . getNotificationsDao ( ) . addNotification ( notification ) ; method = org . apache . http . client . methods . HttpPost . METHOD_NAME ; } } else { method = org . apache . http . client . methods . HttpPost . METHOD_NAME ; } List < NameValuePair > parameters = populateReqParams ( message ) ; HttpRequestDescriptor request = new HttpRequestDescriptor ( callback , method , parameters ) ; downloader ( ) . tell ( request , self ( ) ) ; } }
The storage engine .
38,783
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
38,784
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
38,785
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 . permitted ( authorization , method , storage , organizationSid ) ) { if ( logger . isDebugEnabled ( ) ) { String msg = String . format ( "Either authorization header is null [if(authorization==null) evaluates %s], or CallControlHelper.permitted() method failed, will send \"407 Proxy Authentication required\"" , authorization == null ) ; logger . debug ( msg ) ; } authenticate ( request , storage . getOrganizationsDao ( ) . getOrganization ( organizationSid ) . getDomainName ( ) ) ; return false ; } else { return true ; } }
Check if a client is authenticated . If so return true . Otherwise request authentication and return false ;
38,786
private NumberSelectionResult findSingleNumber ( String number , Sid sourceOrganizationSid , Sid destinationOrganizationSid , Set < SearchModifier > modifiers ) { NumberSelectionResult matchedNumber = new NumberSelectionResult ( null , false , null ) ; IncomingPhoneNumberFilter . Builder filterBuilder = IncomingPhoneNumberFilter . Builder . builder ( ) ; filterBuilder . byPhoneNumber ( number ) ; int unfilteredCount = numbersDao . getTotalIncomingPhoneNumbers ( filterBuilder . build ( ) ) ; if ( unfilteredCount > 0 ) { if ( destinationOrganizationSid != null ) { filterBuilder . byOrgSid ( destinationOrganizationSid . toString ( ) ) ; } else if ( ( modifiers != null ) && ( modifiers . contains ( SearchModifier . ORG_COMPLIANT ) ) ) { logger . debug ( "Organizations are null, restrict PureSIP numbers." ) ; filterBuilder . byPureSIP ( Boolean . FALSE ) ; } if ( sourceOrganizationSid != null && ! sourceOrganizationSid . equals ( destinationOrganizationSid ) ) { filterBuilder . byPureSIP ( Boolean . FALSE ) ; } IncomingPhoneNumberFilter numFilter = filterBuilder . build ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Searching with filter:" + numFilter ) ; } List < IncomingPhoneNumber > matchedNumbers = numbersDao . getIncomingPhoneNumbersByFilter ( numFilter ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Num of results:" + matchedNumbers . size ( ) + ".unfilteredCount:" + unfilteredCount ) ; } if ( matchedNumbers != null && matchedNumbers . size ( ) > 0 ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Matched number with filter:" + matchedNumbers . get ( 0 ) . toString ( ) ) ; } matchedNumber = new NumberSelectionResult ( matchedNumbers . get ( 0 ) , Boolean . FALSE , ResultType . REGULAR ) ; } else { matchedNumber . setOrganizationFiltered ( Boolean . TRUE ) ; } } return matchedNumber ; }
Here we expect a perfect match in DB .
38,787
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 ( matchedNumber . getNumber ( ) == null && i < numberQueries . size ( ) ) { matchedNumber = findSingleNumber ( numberQueries . get ( i ) , sourceOrganizationSid , destinationOrganizationSid , modifiers ) ; if ( matchedNumber . getOrganizationFiltered ( ) ) { orgFiltered = true ; } i = i + 1 ; } matchedNumber . setOrganizationFiltered ( orgFiltered ) ; return matchedNumber ; }
Iterates over the list of given numbers and returns the first matching .
38,788
private NumberSelectionResult findByRegex ( List < String > numberQueries , Sid sourceOrganizationSid , Sid destOrg ) { NumberSelectionResult numberFound = new NumberSelectionResult ( null , false , null ) ; IncomingPhoneNumberFilter . Builder filterBuilder = IncomingPhoneNumberFilter . Builder . builder ( ) ; filterBuilder . byOrgSid ( destOrg . toString ( ) ) ; filterBuilder . byPureSIP ( Boolean . TRUE ) ; List < IncomingPhoneNumber > regexList = numbersDao . getIncomingPhoneNumbersRegex ( filterBuilder . build ( ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( String . format ( "Found %d Regex IncomingPhone numbers." , regexList . size ( ) ) ) ; } Set < IncomingPhoneNumber > regexSet = new TreeSet < IncomingPhoneNumber > ( new NumberLengthComparator ( ) ) ; regexSet . addAll ( regexList ) ; if ( regexList != null && regexList . size ( ) > 0 ) { NumberSelectionResult matchingRegex = findFirstMatchingRegex ( numberQueries , regexSet ) ; if ( matchingRegex . getNumber ( ) != null ) { numberFound = matchingRegex ; } } return numberFound ; }
This will take the regexes available in given organization and evalute them agsint the given list of numbers returning the first match .
38,789
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 ( MSG_INVALID_DOMAIN_NAME_PATTERN ) . build ( ) ; } Organization organization ; if ( dnsProvisioningManager == null ) { organization = organizationsDao . getOrganizationByDomainName ( domainName ) ; if ( organization != null ) { return status ( CONFLICT ) . entity ( MSG_DOMAIN_NAME_NOT_AVAILABLE ) . build ( ) ; } logger . warn ( "No DNS provisioning Manager is configured, restcomm will not make any queries to DNS server." ) ; organization = new Organization ( Sid . generate ( Sid . Type . ORGANIZATION ) , domainName , DateTime . now ( ) , DateTime . now ( ) , Organization . Status . ACTIVE ) ; organizationsDao . addOrganization ( organization ) ; } else { String hostedZoneId = info . getQueryParameters ( ) . getFirst ( "HostedZoneId" ) ; String completeDomainName = dnsProvisioningManager . getCompleteDomainName ( domainName , hostedZoneId ) ; organization = organizationsDao . getOrganizationByDomainName ( completeDomainName ) ; if ( organization != null ) { return status ( CONFLICT ) . entity ( MSG_DOMAIN_NAME_NOT_AVAILABLE ) . build ( ) ; } if ( dnsProvisioningManager . doesResourceRecordAlreadyExists ( domainName , hostedZoneId ) ) { return status ( CONFLICT ) . entity ( MSG_DOMAIN_NAME_NOT_AVAILABLE ) . build ( ) ; } if ( ! dnsProvisioningManager . createResourceRecord ( domainName , hostedZoneId ) ) { logger . error ( "could not create resource record on dns server" ) ; return status ( INTERNAL_SERVER_ERROR ) . build ( ) ; } else { organization = new Organization ( Sid . generate ( Sid . Type . ORGANIZATION ) , completeDomainName , DateTime . now ( ) , DateTime . now ( ) , Organization . Status . ACTIVE ) ; organizationsDao . addOrganization ( organization ) ; } } if ( APPLICATION_XML_TYPE . equals ( responseType ) ) { final RestCommResponse response = new RestCommResponse ( organization ) ; return ok ( xstream . toXML ( response ) , APPLICATION_XML ) . build ( ) ; } else if ( APPLICATION_JSON_TYPE . equals ( responseType ) ) { return ok ( gson . toJson ( organization ) , APPLICATION_JSON ) . build ( ) ; } else { return null ; } } }
putOrganization create new organization
38,790
protected Response migrateClientsOrganization ( final String organizationSid , UriInfo info , MediaType responseType , UserIdentityContext userIdentityContext ) { permissionEvaluator . checkPermission ( "RestComm:Read:Organizations" , userIdentityContext ) ; Organization organization = null ; if ( ! Sid . pattern . matcher ( organizationSid ) . matches ( ) ) { return status ( BAD_REQUEST ) . build ( ) ; } else { try { if ( ! permissionEvaluator . isSuperAdmin ( userIdentityContext ) ) { return status ( FORBIDDEN ) . build ( ) ; } else { organization = organizationsDao . getOrganization ( new Sid ( organizationSid ) ) ; } } catch ( Exception e ) { return status ( NOT_FOUND ) . build ( ) ; } } if ( organization == null ) { return status ( NOT_FOUND ) . build ( ) ; } else { Response . ResponseBuilder ok = Response . ok ( ) ; List < Client > clients = clientsDao . getClientsByOrg ( organization . getSid ( ) ) ; Map < String , String > migratedClients = clientPasswordHashingService . hashClientPassword ( clients , organization . getDomainName ( ) ) ; if ( APPLICATION_XML_TYPE . equals ( responseType ) ) { final RestCommResponse response = new RestCommResponse ( migratedClients ) ; return ok . type ( APPLICATION_XML ) . entity ( xstream . toXML ( response ) ) . build ( ) ; } else if ( APPLICATION_JSON_TYPE . equals ( responseType ) ) { return ok . type ( APPLICATION_JSON ) . entity ( gson . toJson ( migratedClients ) ) . build ( ) ; } else { return null ; } } }
Hash password for clients of the given organization
38,791
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
38,792
protected void filterClosedAccounts ( UserIdentityContext userIdentityContext , String path ) { if ( userIdentityContext . getEffectiveAccount ( ) != null && ! userIdentityContext . getEffectiveAccount ( ) . getStatus ( ) . equals ( Account . Status . ACTIVE ) ) { if ( userIdentityContext . getEffectiveAccount ( ) . getStatus ( ) . equals ( Account . Status . UNINITIALIZED ) && path . startsWith ( "Accounts" ) ) { return ; } throw new WebApplicationException ( status ( Status . FORBIDDEN ) . entity ( "Provided Account is not active" ) . build ( ) ) ; } }
filter out accounts that are not active
38,793
private int getGlobalNoOfParticipants ( ) throws Exception { if ( sid == null ) { globalNoOfParticipants = calls . size ( ) ; } else { CallDetailRecordsDao dao = storage . getCallDetailRecordsDao ( ) ; globalNoOfParticipants = dao . getTotalRunningCallDetailRecordsByConferenceSid ( sid ) ; } if ( logger . isDebugEnabled ( ) ) logger . debug ( "sid: " + sid + "globalNoOfParticipants: " + globalNoOfParticipants ) ; return globalNoOfParticipants ; }
get global total no of participants from db
38,794
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 not exist, will create one from default Plan" ) ; } JsonNode jsonNode = JsonLoader . fromPath ( profileSourcePath ) ; profile = new Profile ( DEFAULT_PROFILE_SID , jsonNode . toString ( ) , new Date ( ) , new Date ( ) ) ; storage . getProfilesDao ( ) . addProfile ( profile ) ; } else { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "default profile already exists, will not override it." ) ; } } }
generateDefaultProfile if does not already exists
38,795
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 .
38,796
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 ( "/.*$" , "/*" ) ) > - 1 || Arrays . binarySearch ( acceptValues , "*/*" ) > - 1 ; }
Returns true if the given accept header accepts the given value .
38,797
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 .
38,798
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 > simIDs = simLaunchd . getLaunchdIDs ( ) ; if ( simIDs . size ( ) > 0 ) { if ( log . isLoggable ( Level . FINE ) ) { log . log ( Level . FINE , "Removing stale iphonesimulator launchds: " + simIDs ) ; } String iphoneSimulatorPrefix = "com.apple.iphonesimulator.launchd." ; for ( String id : simIDs ) { launchctlCmd = Arrays . asList ( "launchctl" , "remove" , iphoneSimulatorPrefix + id ) ; cmd = new Command ( launchctlCmd , false ) ; cmd . executeAndWait ( true ) ; } } }
Removes stale iphonesimulator launchds hanging in the system
38,799
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 new WebDriverException ( e ) ; } }
sends the message to the AUT .