idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
38,600
public Map < String , String > getEnvProperty ( ) { Map < String , String > res = new TreeMap < String , String > ( ) ; MutablePropertySources mps = env . getPropertySources ( ) ; Iterator < PropertySource < ? > > iter = mps . iterator ( ) ; while ( iter . hasNext ( ) ) { PropertySource < ? > ps = iter . next ( ) ; if ( ps instanceof EnumerablePropertySource < ? > ) { for ( String propName : ( ( EnumerablePropertySource < ? > ) ps ) . getPropertyNames ( ) ) { try { res . put ( propName , env . getProperty ( propName ) ) ; } catch ( Exception e ) { LOGGER . warn ( "unresolveable property: " + propName ) ; res . put ( propName , "UNRESOLVEABLE" ) ; } } } } return res ; }
returns the spring environment properties
38,601
public boolean adminToolMbeansExported ( MBeanServer server , BeanFactory beanFactory , List < AdminToolConfig > configs ) throws MalformedObjectNameException { MBeanExporter mbeanExporter = new MBeanExporter ( ) ; mbeanExporter . setServer ( server ) ; mbeanExporter . setBeanFactory ( beanFactory ) ; SimpleReflectiveMBeanInfoAssembler assembler = new SimpleReflectiveMBeanInfoAssembler ( ) ; mbeanExporter . setAssembler ( assembler ) ; mbeanExporter . setAutodetect ( true ) ; LOGGER . info ( "registering %s managed admintool config resources" , configs . size ( ) ) ; for ( AdminToolConfig adminToolConfig : configs ) { LOGGER . info ( "registering managed resource: %s" , adminToolConfig . getClass ( ) . getName ( ) ) ; ObjectName name = new ObjectName ( String . format ( "de.chandre.admintool:type=Config,name=%s" , adminToolConfig . getClass ( ) . getSimpleName ( ) ) ) ; mbeanExporter . registerManagedResource ( adminToolConfig , name ) ; } return true ; }
maybe not reasonable to export all configuration beans as mbeans especially configurations like fileBrowser or dbBrowser
38,602
public void setSubmenu ( List < MenuEntry > submenu ) { submenu . stream ( ) . forEach ( entry -> entry . setParent ( this ) ) ; this . submenu = submenu ; }
list of sub menu entries .
38,603
public Map < String , Boolean > getAdditionalJSReverse ( ) { Map < String , Boolean > result = new LinkedHashMap < > ( ) ; List < MenuEntry > parents = reverseFlattened ( ) . collect ( AdminToolMenuUtils . toListReversed ( ) ) ; parents . forEach ( menuEntry -> { if ( null != menuEntry . getAdditionalJS ( ) ) { result . putAll ( menuEntry . getAdditionalJS ( ) ) ; } } ) ; return result ; }
returns all additional js from this to upper menu item hierarchy beginning with the root .
38,604
protected void addUsersMenu ( ) { LOGGER . info ( "adding Authentication component" ) ; MenuEntry mainMenu = new MenuEntry ( "users" , "Users" , "security/content/users" , securityRolesConfig ) ; mainMenu . addAdditionalJS ( "/static/admintool/security/users.js" , true ) ; mainMenu . addAdditionalJS ( "/static/admintool/security/validator.min.js" , true ) ; mainMenu . setResouceMessageKey ( AdminTool . RESOURCE_MESSAGE_KEY_PREFIX + "security.users.displayName" ) ; String adminLtePrefix = getAdminLTEPrefixUri ( ) ; boolean relative = ! shouldCDNsUsed ( ) ; component . addAdditionalJS ( adminLtePrefix + "plugins/select2/select2.min.js" , relative ) ; component . addAdditionalCSS ( adminLtePrefix + "plugins/select2/select2.min.css" , relative ) ; component . addAdditionalJS ( getWebjarsPrefixUri ( ) + "mustache/" + mustacheVersion + "/mustache.min.js" , relative ) ; component . setMainMenu ( mainMenu ) ; component . setPosition ( componentPosition ) ; component . getSecurityRoles ( ) . addAll ( securityRolesConfig ) ; component . setDisplayName ( "Authentication" ) ; adminTool . addComponent ( component ) ; }
adds the users view to admin tool
38,605
protected Collection < GrantedAuthority > transformToSimpleAuthorities ( Set < String > strAuthorities , boolean appendRolePrefix ) { if ( null != strAuthorities ) { Collection < GrantedAuthority > authorities = new HashSet < > ( strAuthorities . size ( ) ) ; for ( String authority : strAuthorities ) { if ( ! StringUtils . isEmpty ( authority ) ) { String role = authority . trim ( ) . toUpperCase ( Locale . ENGLISH ) ; if ( appendRolePrefix ) { authorities . add ( new SimpleGrantedAuthority ( getRolePrefix ( ) + role ) ) ; } else { authorities . add ( new SimpleGrantedAuthority ( role ) ) ; } } } return authorities ; } return Collections . emptyList ( ) ; }
transforms all authorities to upper case and append the prefix if appendRolePrefix = true
38,606
protected void iterateResult ( ResultSet resSet , QueryResultTO resultTO , StatementTO statementTO ) { try { if ( resSet != null && ! resSet . isClosed ( ) ) { ResultSetMetaData metaData = resSet . getMetaData ( ) ; int cols = metaData . getColumnCount ( ) ; Map < Integer , Integer > type = new HashMap < Integer , Integer > ( ) ; List < String > columnsNames = new ArrayList < > ( ) ; for ( int i = 1 ; i < ( cols + 1 ) ; i ++ ) { String colName = metaData . getColumnName ( i ) ; columnsNames . add ( colName ) ; type . put ( i , metaData . getColumnType ( i ) ) ; } List < List < String > > tableResult = new ArrayList < > ( ) ; String clobEncoding = statementTO . getClobEncoding ( ) != null ? statementTO . getClobEncoding ( ) : DEFAULT_CLOB_ENCODING ; while ( resSet . next ( ) ) { List < String > row = new ArrayList < > ( ) ; for ( int i = 1 ; i < ( cols + 1 ) ; i ++ ) { if ( type . get ( i ) != null && type . get ( i ) == Types . BLOB ) { if ( statementTO . isShowBlobs ( ) ) { row . add ( String . valueOf ( new String ( resSet . getBytes ( i ) ) ) ) ; } else { row . add ( String . valueOf ( resSet . getObject ( i ) ) ) ; } } else if ( type . get ( i ) != null && type . get ( i ) == Types . CLOB ) { if ( statementTO . isShowClobs ( ) ) { row . add ( getClobString ( resSet . getClob ( i ) , clobEncoding ) ) ; } else { row . add ( "CLOB content" ) ; } } else { row . add ( String . valueOf ( resSet . getObject ( i ) ) ) ; } } tableResult . add ( row ) ; } resultTO . setSqlWarnings ( null != resSet . getWarnings ( ) ? resSet . getWarnings ( ) . toString ( ) : null ) ; resultTO . setAffectedRows ( tableResult . size ( ) ) ; resultTO . setColumnsNames ( columnsNames ) ; resultTO . setTableResult ( tableResult ) ; } else { resultTO . setSqlWarnings ( "resultSet was " + ( null != resSet ? "closed already" : "null" ) ) ; } resultTO . setSelect ( true ) ; } catch ( Exception e ) { resultTO . setExceptionMessage ( e . getMessage ( ) ) ; resultTO . setExceptionCause ( null != e . getCause ( ) ? e . getCause ( ) . toString ( ) : null ) ; resultTO . setExceptionTrace ( printException ( e ) ) ; } }
iterates the resultSet and fills resultTO
38,607
protected String getClobString ( Clob clobObject , String encoding ) throws IOException , SQLException , UnsupportedEncodingException { if ( null == clobObject ) { return "" ; } InputStream in = clobObject . getAsciiStream ( ) ; Reader read = new InputStreamReader ( in , encoding ) ; StringWriter write = new StringWriter ( ) ; String result = null ; try { int c = - 1 ; while ( ( c = read . read ( ) ) != - 1 ) { write . write ( c ) ; } write . flush ( ) ; result = write . toString ( ) ; } finally { closeStream ( write ) ; closeStream ( read ) ; } return result ; }
turns clob into a string
38,608
protected static String printException ( final Throwable throwable ) { if ( null == throwable ) { return null ; } final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; final PrintStream printStream = new PrintStream ( baos ) ; throwable . printStackTrace ( printStream ) ; String exceptionStr = "" ; try { exceptionStr = baos . toString ( "UTF-8" ) ; } catch ( Exception ex ) { exceptionStr = "Unavailable" ; } finally { closeStream ( printStream ) ; closeStream ( baos ) ; } return exceptionStr ; }
prints a exception into a string
38,609
public String getExtension ( String fileName ) { if ( fileName . lastIndexOf ( '.' ) > - 1 ) { return ( fileName . substring ( fileName . lastIndexOf ( '.' ) + 1 , fileName . length ( ) ) ) . toLowerCase ( ) ; } return null ; }
returns the file extension by filename separated by last dot
38,610
protected InputStream getResourceAsStream ( String paramString ) throws MalformedURLException { URL localURL = new URL ( paramString ) ; try { if ( null != localURL ) { URLConnection localURLConnection = localURL . openConnection ( ) ; return localURLConnection . getInputStream ( ) ; } } catch ( IOException localIOException ) { } return null ; }
loads the input stream of an url
38,611
public List < MenuIntegrityError > checkMenuIntegrity ( ) { List < MenuIntegrityError > errorList = new ArrayList < > ( ) ; Map < String , MenuEntry > links = new HashMap < > ( ) ; Map < String , MenuEntry > templates = new HashMap < > ( ) ; for ( AdminComponent comp : adminTool . getComponents ( ) ) { if ( null != comp . getMainMenu ( ) ) { comp . getMainMenu ( ) . flattened ( ) . forEach ( menu -> { if ( links . containsKey ( menu . getName ( ) ) && CollectionUtils . isEmpty ( menu . getSubmenu ( ) ) ) { findErrorAndAddEntry ( "duplicate link name on menu item" , MSG_KEY_DUPLICATE_LINK , errorList , menu , links . get ( menu . getName ( ) ) ) ; } else { links . put ( menu . getName ( ) , menu ) ; } if ( templates . containsKey ( menu . getTarget ( ) ) && CollectionUtils . isEmpty ( menu . getSubmenu ( ) ) ) { findErrorAndAddEntry ( "duplicate template reference on menu item" , MSG_KEY_DUPLICATE_TPL_REF , errorList , menu , templates . get ( menu . getTarget ( ) ) ) ; } else { templates . put ( menu . getTarget ( ) , menu ) ; } if ( config . isInternationalizationEnabled ( ) && StringUtils . isEmpty ( menu . getResouceMessageKey ( ) ) ) { findErrorAndAddEntry ( "missing message resource key on menu item" , MSG_KEY_MISSING_RESOURCE_KEY , errorList , menu , templates . get ( menu . getTarget ( ) ) ) ; } } ) ; } else { findErrorAndAddEntry ( String . format ( "the component '%s' has no main menu" , comp . getDisplayName ( ) ) , MSG_KEY_COMPONENT_NO_MAINMENU , errorList , null , null ) ; } } links . clear ( ) ; templates . clear ( ) ; return errorList ; }
checks for integrity errors
38,612
public static String toSetter ( final String fieldName ) { return "set" + fieldName . substring ( 0 , 1 ) . toUpperCase ( Locale . ENGLISH ) + fieldName . substring ( 1 , fieldName . length ( ) ) ; }
creates setter out of field name
38,613
public static void copy ( Object object , Object clone , String fieldName , boolean ignoreNonExisting ) { invokeSetter ( clone , fieldName , invokeGetter ( object , fieldName ) , ignoreNonExisting ) ; }
copys a value from one to another object with same field name!
38,614
public static void copy ( Object object , Field field , Object clone , Field cloneField , boolean ignoreNonExisting ) { invokeSetter ( clone , cloneField , invokeGetter ( object , field ) , ignoreNonExisting ) ; }
copys a value from one to another object !
38,615
public static AuditorAware < String > auditorProvider ( ATUser systemUser , ATUser anonymousUser ) { return new AuditorAware < String > ( ) { private final Log LOGGER = LogFactory . getLog ( AuditorAware . class ) ; public String getCurrentAuditor ( ) { SecurityContext secCtx = SecurityContextHolder . getContext ( ) ; if ( null == secCtx ) { return systemUser . getUsername ( ) ; } Authentication authentication = secCtx . getAuthentication ( ) ; if ( authentication == null || ! authentication . isAuthenticated ( ) ) { LOGGER . debug ( String . format ( "using %s user for auditing" , systemUser . getUsername ( ) ) ) ; return systemUser . getUsername ( ) ; } else if ( authentication . isAuthenticated ( ) && ! ATUser . class . isAssignableFrom ( authentication . getPrincipal ( ) . getClass ( ) ) ) { LOGGER . debug ( String . format ( "using %s user for auditing" , anonymousUser . getUsername ( ) ) ) ; return anonymousUser . getUsername ( ) ; } return ( ( ATUser ) authentication . getPrincipal ( ) ) . getUsername ( ) ; } } ; }
creates a auditor provider
38,616
public static List < PushedNotification > findSuccessfulNotifications ( List < PushedNotification > notifications ) { List < PushedNotification > filteredList = new Vector < PushedNotification > ( ) ; for ( PushedNotification notification : notifications ) { if ( notification . isSuccessful ( ) ) filteredList . add ( notification ) ; } return filteredList ; }
Filters a list of pushed notifications and returns only the ones that were successful .
38,617
public static PushedNotifications alert ( String message , Object keystore , String password , boolean production , Object devices ) throws CommunicationException , KeystoreException { return sendPayload ( PushNotificationPayload . alert ( message ) , keystore , password , production , devices ) ; }
Push a simple alert to one or more devices .
38,618
public static PushedNotifications sound ( String sound , Object keystore , String password , boolean production , Object devices ) throws CommunicationException , KeystoreException { return sendPayload ( PushNotificationPayload . sound ( sound ) , keystore , password , production , devices ) ; }
Push a simple sound name to one or more devices .
38,619
public static PushedNotifications combined ( String message , int badge , String sound , Object keystore , String password , boolean production , Object devices ) throws CommunicationException , KeystoreException { return sendPayload ( PushNotificationPayload . combined ( message , badge , sound ) , keystore , password , production , devices ) ; }
Push a notification combining an alert a badge and a sound .
38,620
public static PushedNotifications contentAvailable ( Object keystore , String password , boolean production , Object devices ) throws CommunicationException , KeystoreException { return sendPayload ( NewsstandNotificationPayload . contentAvailable ( ) , keystore , password , production , devices ) ; }
Push a content - available notification for Newsstand .
38,621
public static NewsstandNotificationPayload contentAvailable ( ) { NewsstandNotificationPayload payload = complex ( ) ; try { payload . addContentAvailable ( ) ; } catch ( JSONException e ) { } return payload ; }
Create a pre - defined payload with a content - available property set to 1 .
38,622
protected SSLSocketFactory createSSLSocketFactoryWithTrustManagers ( TrustManager [ ] trustManagers ) throws KeystoreException { logger . debug ( "Creating SSLSocketFactory" ) ; try { KeyStore keystore = getKeystore ( ) ; KeyManagerFactory kmf = KeyManagerFactory . getInstance ( ALGORITHM ) ; try { char [ ] password = KeystoreManager . getKeystorePasswordForSSL ( server ) ; kmf . init ( keystore , password ) ; } catch ( Exception e ) { e = KeystoreManager . wrapKeystoreException ( e ) ; throw e ; } SSLContext sslc = SSLContext . getInstance ( PROTOCOL ) ; sslc . init ( kmf . getKeyManagers ( ) , trustManagers , null ) ; return sslc . getSocketFactory ( ) ; } catch ( Exception e ) { throw new KeystoreException ( "Keystore exception: " + e . getMessage ( ) , e ) ; } }
Generic SSLSocketFactory builder
38,623
public SSLSocket getSSLSocket ( ) throws KeystoreException , CommunicationException { SSLSocketFactory socketFactory = getSSLSocketFactory ( ) ; logger . debug ( "Creating SSLSocket to " + getServerHost ( ) + ":" + getServerPort ( ) ) ; try { if ( ProxyManager . isUsingProxy ( server ) ) { return tunnelThroughProxy ( socketFactory ) ; } else { return ( SSLSocket ) socketFactory . createSocket ( getServerHost ( ) , getServerPort ( ) ) ; } } catch ( Exception e ) { throw new CommunicationException ( "Communication exception: " + e , e ) ; } }
Create a SSLSocket which will be used to send data to Apple
38,624
public static void setProxy ( String host , String port ) { System . setProperty ( LOCAL_PROXY_HOST_PROPERTY , host ) ; System . setProperty ( LOCAL_PROXY_PORT_PROPERTY , port ) ; }
Configure a proxy to use for HTTPS connections created by JavaPNS .
38,625
public static String getProxyHost ( AppleServer server ) { String host = server != null ? server . getProxyHost ( ) : null ; if ( host != null && host . length ( ) > 0 ) { return host ; } else { host = System . getProperty ( LOCAL_PROXY_HOST_PROPERTY ) ; if ( host != null && host . length ( ) > 0 ) { return host ; } else { host = System . getProperty ( JVM_PROXY_HOST_PROPERTY ) ; if ( host != null && host . length ( ) > 0 ) { return host ; } else { return null ; } } } }
Get the proxy host address currently configured . This method checks if a server - specific proxy has been configured then checks if a proxy has been configured for the entire library and finally checks if a JVM - wide proxy setting is available for HTTPS .
38,626
public static int getProxyPort ( AppleServer server ) { String host = server != null ? server . getProxyHost ( ) : null ; if ( host != null && host . length ( ) > 0 ) { return server . getProxyPort ( ) ; } else { host = System . getProperty ( LOCAL_PROXY_HOST_PROPERTY ) ; if ( host != null && host . length ( ) > 0 ) { return Integer . parseInt ( System . getProperty ( LOCAL_PROXY_PORT_PROPERTY ) ) ; } else { host = System . getProperty ( JVM_PROXY_HOST_PROPERTY ) ; if ( host != null && host . length ( ) > 0 ) { return Integer . parseInt ( System . getProperty ( JVM_PROXY_PORT_PROPERTY ) ) ; } else { return 0 ; } } } }
Get the proxy port currently configured . This method first locates a proxy host setting then returns the proxy port from the same location .
38,627
public static boolean isUsingProxy ( AppleServer server ) { String proxyHost = getProxyHost ( server ) ; boolean proxyConfigured = proxyHost != null && proxyHost . length ( ) > 0 ; return proxyConfigured ; }
Determine if a proxy is currently configured .
38,628
public String nextCDATA ( ) throws JSONException { char c ; int i ; StringBuffer sb = new StringBuffer ( ) ; for ( ; ; ) { c = next ( ) ; if ( c == 0 ) { throw syntaxError ( "Unclosed CDATA" ) ; } sb . append ( c ) ; i = sb . length ( ) - 3 ; if ( i >= 0 && sb . charAt ( i ) == ']' && sb . charAt ( i + 1 ) == ']' && sb . charAt ( i + 2 ) == '>' ) { sb . setLength ( i ) ; return sb . toString ( ) ; } } }
Get the text in the CDATA block .
38,629
public PushedNotifications getSuccessfulNotifications ( ) { PushedNotifications filteredList = new PushedNotifications ( this ) ; for ( PushedNotification notification : this ) { if ( notification . isSuccessful ( ) ) filteredList . add ( notification ) ; } return filteredList ; }
Filter a list of pushed notifications and return only the ones that were successful .
38,630
public PushedNotifications getFailedNotifications ( ) { PushedNotifications filteredList = new PushedNotifications ( this ) ; for ( PushedNotification notification : this ) { if ( ! notification . isSuccessful ( ) ) { filteredList . add ( notification ) ; } } return filteredList ; }
Filter a list of pushed notifications and return only the ones that failed .
38,631
public Device addDevice ( String id , String token ) throws DuplicateDeviceException , NullIdException , NullDeviceTokenException , Exception { if ( ( id == null ) || ( id . trim ( ) . equals ( "" ) ) ) { throw new NullIdException ( ) ; } else if ( ( token == null ) || ( token . trim ( ) . equals ( "" ) ) ) { throw new NullDeviceTokenException ( ) ; } else { if ( ! this . devices . containsKey ( id ) ) { token = token . trim ( ) . replace ( " " , "" ) ; BasicDevice device = new BasicDevice ( id , token , new Timestamp ( Calendar . getInstance ( ) . getTime ( ) . getTime ( ) ) ) ; this . devices . put ( id , device ) ; return device ; } else { throw new DuplicateDeviceException ( ) ; } } }
Add a device to the map
38,632
public Device getDevice ( String id ) throws UnknownDeviceException , NullIdException { if ( ( id == null ) || ( id . trim ( ) . equals ( "" ) ) ) { throw new NullIdException ( ) ; } else { if ( this . devices . containsKey ( id ) ) { return this . devices . get ( id ) ; } else { throw new UnknownDeviceException ( ) ; } } }
Get a device according to his id
38,633
public void removeDevice ( String id ) throws UnknownDeviceException , NullIdException { if ( ( id == null ) || ( id . trim ( ) . equals ( "" ) ) ) { throw new NullIdException ( ) ; } if ( this . devices . containsKey ( id ) ) { this . devices . remove ( id ) ; } else { throw new UnknownDeviceException ( ) ; } }
Remove a device
38,634
static Object ensureReusableKeystore ( AppleServer server , Object keystore ) throws KeystoreException { if ( keystore instanceof InputStream ) keystore = loadKeystore ( server , keystore , false ) ; return keystore ; }
Make sure that the provided keystore will be reusable .
38,635
public static void verifyKeystoreContent ( AppleServer server , Object keystore ) throws KeystoreException { KeyStore keystoreToValidate = null ; if ( keystore instanceof KeyStore ) keystoreToValidate = ( KeyStore ) keystore ; else keystoreToValidate = loadKeystore ( server , keystore ) ; verifyKeystoreContent ( keystoreToValidate ) ; }
Perform basic tests on a keystore to detect common user mistakes . If a problem is found a KeystoreException is thrown . If no problem is found this method simply returns without exceptions .
38,636
public static void validateKeystoreParameter ( Object keystore ) throws InvalidKeystoreReferenceException { if ( keystore == null ) throw new InvalidKeystoreReferenceException ( ( Object ) null ) ; if ( keystore instanceof KeyStore ) return ; if ( keystore instanceof InputStream ) return ; if ( keystore instanceof String ) keystore = new File ( ( String ) keystore ) ; if ( keystore instanceof File ) { File file = ( File ) keystore ; if ( ! file . exists ( ) ) throw new InvalidKeystoreReferenceException ( "Invalid keystore reference. File does not exist: " + file . getAbsolutePath ( ) ) ; if ( ! file . isFile ( ) ) throw new InvalidKeystoreReferenceException ( "Invalid keystore reference. Path does not refer to a valid file: " + file . getAbsolutePath ( ) ) ; if ( file . length ( ) <= 0 ) throw new InvalidKeystoreReferenceException ( "Invalid keystore reference. File is empty: " + file . getAbsolutePath ( ) ) ; return ; } if ( keystore instanceof byte [ ] ) { byte [ ] bytes = ( byte [ ] ) keystore ; if ( bytes . length == 0 ) throw new InvalidKeystoreReferenceException ( "Invalid keystore reference. Byte array is empty" ) ; return ; } }
Ensures that a keystore parameter is actually supported by the KeystoreManager .
38,637
public void addCustomDictionary ( String name , String value ) throws JSONException { logger . debug ( "Adding custom Dictionary [" + name + "] = [" + value + "]" ) ; put ( name , value , payload , false ) ; }
Add a custom dictionnary with a string value
38,638
public void addCustomDictionary ( String name , List values ) throws JSONException { logger . debug ( "Adding custom Dictionary [" + name + "] = (list)" ) ; put ( name , values , payload , false ) ; }
Add a custom dictionnary with multiple values
38,639
private byte [ ] getPayloadAsBytesUnchecked ( ) throws Exception { byte [ ] bytes = null ; try { bytes = toString ( ) . getBytes ( characterEncoding ) ; } catch ( Exception ex ) { bytes = toString ( ) . getBytes ( ) ; } return bytes ; }
Get this payload as a byte array using the preconfigured character encoding . This method does NOT check if the payload exceeds the maximum payload length .
38,640
public int estimatePayloadSizeAfterAdding ( String propertyName , Object propertyValue ) { try { int maximumPayloadSize = getMaximumPayloadSize ( ) ; int currentPayloadSize = getPayloadAsBytesUnchecked ( ) . length ; int estimatedSize = currentPayloadSize ; if ( propertyName != null && propertyValue != null ) { estimatedSize += 5 ; estimatedSize += propertyName . getBytes ( getCharacterEncoding ( ) ) . length ; int estimatedValueSize = 0 ; if ( propertyValue instanceof String || propertyValue instanceof Number ) estimatedValueSize = propertyValue . toString ( ) . getBytes ( getCharacterEncoding ( ) ) . length ; estimatedSize += estimatedValueSize ; } return estimatedSize ; } catch ( Exception e ) { try { return getPayloadSize ( ) ; } catch ( Exception e1 ) { return 0 ; } } }
Estimate the size that this payload will take after adding a given property . For performance reasons this estimate is not as reliable as actually adding the property and checking the payload size afterwards .
38,641
public boolean isEstimatedPayloadSizeAllowedAfterAdding ( String propertyName , Object propertyValue ) { int maximumPayloadSize = getMaximumPayloadSize ( ) ; int estimatedPayloadSize = estimatePayloadSizeAfterAdding ( propertyName , propertyValue ) ; boolean estimatedToBeAllowed = estimatedPayloadSize <= maximumPayloadSize ; return estimatedToBeAllowed ; }
Validate if the estimated payload size after adding a given property will be allowed . For performance reasons this estimate is not as reliable as actually adding the property and checking the payload size afterwards .
38,642
private void validateMaximumPayloadSize ( int currentPayloadSize ) throws PayloadMaxSizeExceededException { int maximumPayloadSize = getMaximumPayloadSize ( ) ; if ( currentPayloadSize > maximumPayloadSize ) { throw new PayloadMaxSizeExceededException ( maximumPayloadSize , currentPayloadSize ) ; } }
Validate that the payload does not exceed the maximum size allowed . If the limit is exceeded a PayloadMaxSizeExceededException is thrown .
38,643
protected void put ( String propertyName , Object propertyValue , JSONObject object , boolean opt ) throws JSONException { try { if ( isPayloadSizeEstimatedWhenAdding ( ) ) { int maximumPayloadSize = getMaximumPayloadSize ( ) ; int estimatedPayloadSize = estimatePayloadSizeAfterAdding ( propertyName , propertyValue ) ; boolean estimatedToExceed = estimatedPayloadSize > maximumPayloadSize ; if ( estimatedToExceed ) throw new PayloadMaxSizeProbablyExceededException ( maximumPayloadSize , estimatedPayloadSize ) ; } } catch ( PayloadMaxSizeProbablyExceededException e ) { throw e ; } catch ( Exception e ) { } if ( opt ) object . putOpt ( propertyName , propertyValue ) ; else object . put ( propertyName , propertyValue ) ; }
Puts a property in a JSONObject while possibly checking for estimated payload size violation .
38,644
public static PushNotificationPayload alert ( String message ) { if ( message == null ) throw new IllegalArgumentException ( "Alert cannot be null" ) ; PushNotificationPayload payload = complex ( ) ; try { payload . addAlert ( message ) ; } catch ( JSONException e ) { } return payload ; }
Create a pre - defined payload with a simple alert message .
38,645
public static PushNotificationPayload badge ( int badge ) { PushNotificationPayload payload = complex ( ) ; try { payload . addBadge ( badge ) ; } catch ( JSONException e ) { } return payload ; }
Create a pre - defined payload with a badge .
38,646
public static PushNotificationPayload sound ( String sound ) { if ( sound == null ) throw new IllegalArgumentException ( "Sound name cannot be null" ) ; PushNotificationPayload payload = complex ( ) ; try { payload . addSound ( sound ) ; } catch ( JSONException e ) { } return payload ; }
Create a pre - defined payload with a sound name .
38,647
public static PushNotificationPayload combined ( String message , int badge , String sound ) { if ( message == null && badge < 0 && sound == null ) throw new IllegalArgumentException ( "Must provide at least one non-null argument" ) ; PushNotificationPayload payload = complex ( ) ; try { if ( message != null ) payload . addAlert ( message ) ; if ( badge >= 0 ) payload . addBadge ( badge ) ; if ( sound != null ) payload . addSound ( sound ) ; } catch ( JSONException e ) { } return payload ; }
Create a pre - defined payload with a simple alert message a badge and a sound .
38,648
public static PushNotificationPayload fromJSON ( String rawJSON ) throws JSONException { PushNotificationPayload payload = new PushNotificationPayload ( rawJSON ) ; return payload ; }
Create a PushNotificationPayload object from a preformatted JSON payload .
38,649
public void addBadge ( int badge ) throws JSONException { logger . debug ( "Adding badge [" + badge + "]" ) ; put ( "badge" , badge , this . apsDictionary , true ) ; }
Add a badge .
38,650
public void addSound ( String sound ) throws JSONException { logger . debug ( "Adding sound [" + sound + "]" ) ; put ( "sound" , sound , this . apsDictionary , true ) ; }
Add a sound .
38,651
private JSONObject getOrAddCustomAlert ( ) throws JSONException { JSONObject alert = getCompatibleProperty ( "alert" , JSONObject . class , "A simple alert (\"%s\") was already added to this payload" ) ; if ( alert == null ) { alert = new JSONObject ( ) ; put ( "alert" , alert , this . apsDictionary , false ) ; } return alert ; }
Get the custom alert object creating it if it does not yet exist .
38,652
public void setContentAvailable ( boolean available ) throws JSONException { if ( available == true ) { logger . debug ( "Setting content available" ) ; put ( "content-available" , 1 , this . apsDictionary , false ) ; } else { logger . debug ( "Removing content available" ) ; remove ( "content-available" , this . apsDictionary ) ; } }
Sets the content available .
38,653
public void addCategory ( String category ) throws JSONException { logger . debug ( "Adding category [" + category + "]" ) ; put ( "category" , category , this . apsDictionary , true ) ; }
Add a category .
38,654
public void setMutableContent ( boolean mutable ) throws JSONException { if ( mutable == true ) { logger . debug ( "Setting mutable content" ) ; put ( "mutable-content" , 1 , this . apsDictionary , false ) ; } else { logger . debug ( "Removing mutable content" ) ; remove ( "mutable-content" , this . apsDictionary ) ; } }
Sets the mutable content .
38,655
public String getMessage ( ) { if ( command == 8 ) { String prefix = "APNS: [" + identifier + "] " ; if ( status == 0 ) return prefix + "No errors encountered" ; if ( status == 1 ) return prefix + "Processing error" ; if ( status == 2 ) return prefix + "Missing device token" ; if ( status == 3 ) return prefix + "Missing topic" ; if ( status == 4 ) return prefix + "Missing payload" ; if ( status == 5 ) return prefix + "Invalid token size" ; if ( status == 6 ) return prefix + "Invalid topic size" ; if ( status == 7 ) return prefix + "Invalid payload size" ; if ( status == 8 ) return prefix + "Invalid token" ; if ( status == 255 ) return prefix + "None (unknown)" ; return prefix + "Undocumented status code: " + status ; } return "APNS: Undocumented response command: " + command ; }
Returns a humand - friendly error message as documented by Apple .
38,656
public SwipeViewGroup addBackground ( View background , SwipeDirection direction ) { if ( mBackgroundMap . get ( direction ) != null ) removeView ( mBackgroundMap . get ( direction ) ) ; background . setVisibility ( View . INVISIBLE ) ; mBackgroundMap . put ( direction , background ) ; addView ( background ) ; return this ; }
Add a View to the background of the Layout . The background should have the same height as the contentView
38,657
public void showBackground ( SwipeDirection direction , boolean dimBackground ) { if ( SwipeDirection . DIRECTION_NEUTRAL != direction && mBackgroundMap . get ( direction ) == null ) return ; if ( SwipeDirection . DIRECTION_NEUTRAL != visibleView ) mBackgroundMap . get ( visibleView ) . setVisibility ( View . INVISIBLE ) ; if ( SwipeDirection . DIRECTION_NEUTRAL != direction ) { mBackgroundMap . get ( direction ) . setVisibility ( View . VISIBLE ) ; mBackgroundMap . get ( direction ) . setAlpha ( dimBackground ? 0.4f : 1 ) ; } visibleView = direction ; }
Show the View linked to a key . Don t do anything if the key is not found
38,658
public SwipeViewGroup setContentView ( View contentView ) { if ( this . contentView != null ) removeView ( contentView ) ; addView ( contentView ) ; this . contentView = contentView ; return this ; }
Add a contentView to the Layout
38,659
public void translateBackgrounds ( ) { this . setClipChildren ( false ) ; for ( Map . Entry < SwipeDirection , View > entry : mBackgroundMap . entrySet ( ) ) { int signum = entry . getKey ( ) . isLeft ( ) ? 1 : - 1 ; entry . getValue ( ) . setTranslationX ( signum * entry . getValue ( ) . getWidth ( ) ) ; } }
Move all backgrounds to the edge of the Layout so they can be swiped in
38,660
public void onSwipeStarted ( ListView listView , int position , SwipeDirection direction ) { if ( mSwipeActionListener != null ) mSwipeActionListener . onSwipeStarted ( listView , position , direction ) ; }
Called once the user touches the screen and starts swiping in any direction
38,661
@ SuppressWarnings ( "unused" ) public SwipeActionAdapter setFadeOut ( boolean mFadeOut ) { this . mFadeOut = mFadeOut ; if ( mListView != null ) mTouchListener . setFadeOut ( mFadeOut ) ; return this ; }
Set whether items should have a fadeOut animation
38,662
@ SuppressWarnings ( "unused" ) public SwipeActionAdapter setFarSwipeFraction ( float farSwipeFraction ) { if ( farSwipeFraction < 0 || farSwipeFraction > 1 ) { throw new IllegalArgumentException ( "Must be a float between 0 and 1" ) ; } this . mFarSwipeFraction = farSwipeFraction ; if ( mListView != null ) mTouchListener . setFarSwipeFraction ( farSwipeFraction ) ; return this ; }
Set the fraction of the View Width that needs to be swiped before it is counted as a far swipe
38,663
@ SuppressWarnings ( "unused" ) public SwipeActionAdapter setNormalSwipeFraction ( float normalSwipeFraction ) { if ( normalSwipeFraction < 0 || normalSwipeFraction > 1 ) { throw new IllegalArgumentException ( "Must be a float between 0 and 1" ) ; } this . mNormalSwipeFraction = normalSwipeFraction ; if ( mListView != null ) mTouchListener . setNormalSwipeFraction ( normalSwipeFraction ) ; return this ; }
Set the fraction of the View Width that needs to be swiped before it is counted as a normal swipe
38,664
public SwipeActionAdapter setListView ( ListView listView ) { this . mListView = listView ; mTouchListener = new SwipeActionTouchListener ( listView , this ) ; this . mListView . setOnTouchListener ( mTouchListener ) ; this . mListView . setOnScrollListener ( mTouchListener . makeScrollListener ( ) ) ; this . mListView . setClipChildren ( false ) ; mTouchListener . setFadeOut ( mFadeOut ) ; mTouchListener . setDimBackgrounds ( mDimBackgrounds ) ; mTouchListener . setFixedBackgrounds ( mFixedBackgrounds ) ; mTouchListener . setNormalSwipeFraction ( mNormalSwipeFraction ) ; mTouchListener . setFarSwipeFraction ( mFarSwipeFraction ) ; return this ; }
We need the ListView to be able to modify it s OnTouchListener
38,665
public SwipeActionAdapter addBackground ( SwipeDirection key , int resId ) { if ( SwipeDirection . getAllDirections ( ) . contains ( key ) ) mBackgroundResIds . put ( key , resId ) ; return this ; }
Add a background image for a certain callback . The key for the background must be one of the directions from the SwipeDirections class .
38,666
public void setShadowPadding ( int left , int top , int right , int bottom ) { mShadowBounds . set ( left , top , right , bottom ) ; super . setPadding ( left + mContentPadding . left , top + mContentPadding . top , right + mContentPadding . right , bottom + mContentPadding . bottom ) ; }
Internal method used by CardView implementations to update the padding .
38,667
public void showCorner ( boolean leftTop , boolean rightTop , boolean leftBottom , boolean rightBottom ) { if ( SDK_LOLLIPOP ) { ( ( OptRoundRectDrawable ) getBackground ( ) ) . showCorner ( leftTop , rightTop , leftBottom , rightBottom ) ; } else { ( ( OptRoundRectDrawableWithShadow ) getBackground ( ) ) . showCorner ( leftTop , rightTop , leftBottom , rightBottom ) ; } }
show corner or rect
38,668
public void showEdgeShadow ( boolean left , boolean top , boolean right , boolean bottom ) { if ( SDK_LOLLIPOP ) { } else { ( ( OptRoundRectDrawableWithShadow ) getBackground ( ) ) . showEdgeShadow ( left , top , right , bottom ) ; } }
show Edge Shadow
38,669
public boolean addObjectFactoryForClass ( JDefinedClass clazz ) { JDefinedClass valueObjectFactoryClass = clazz . _package ( ) . _getClass ( FACTORY_CLASS_NAME ) ; if ( objectFactoryClasses . containsKey ( valueObjectFactoryClass . fullName ( ) ) ) { return false ; } objectFactoryClasses . put ( valueObjectFactoryClass . fullName ( ) , valueObjectFactoryClass ) ; JDefinedClass objectFactoryClass = null ; for ( Iterator < JClass > iter = clazz . _implements ( ) ; iter . hasNext ( ) ; ) { JClass interfaceClass = iter . next ( ) ; if ( ! isHiddenClass ( interfaceClass ) ) { objectFactoryClass = interfaceClass . _package ( ) . _getClass ( FACTORY_CLASS_NAME ) ; if ( objectFactoryClass != null ) { objectFactoryClasses . put ( objectFactoryClass . fullName ( ) , objectFactoryClass ) ; } } } return objectFactoryClass != null ; }
For the given class locate and add Object Factory classes to the map .
38,670
public int parseArgument ( Options opts , String [ ] args , int i ) throws BadCommandLineException { initLoggerIfNecessary ( opts ) ; int recognized = 0 ; String arg = args [ i ] ; logger . trace ( "Argument[" + i + "] = " + arg ) ; if ( arg . equals ( getArgumentName ( ConfigurationOption . APPLY_PLURAL_FORM . optionName ( ) ) ) ) { globalConfiguration . setApplyPluralForm ( true ) ; return 1 ; } else if ( ( recognized = parseArgument ( args , i , ConfigurationOption . CONTROL ) ) == 0 && ( recognized = parseArgument ( args , i , ConfigurationOption . SUMMARY ) ) == 0 && ( recognized = parseArgument ( args , i , ConfigurationOption . COLLECTION_INTERFACE ) ) == 0 && ( recognized = parseArgument ( args , i , ConfigurationOption . COLLECTION_IMPLEMENTATION ) ) == 0 && ( recognized = parseArgument ( args , i , ConfigurationOption . INSTANTIATION_MODE ) ) == 0 ) { if ( arg . startsWith ( getArgumentName ( "" ) ) ) { throw new BadCommandLineException ( "Invalid argument " + arg ) ; } } return recognized ; }
Parse and apply plugin configuration options .
38,671
public boolean run ( Outline outline , Options opt , ErrorHandler errorHandler ) throws SAXException { try { runInternal ( outline ) ; return true ; } catch ( IOException e ) { logger . error ( "Failed to read the file" , e ) ; throw new SAXException ( e ) ; } catch ( ClassNotFoundException e ) { logger . error ( "Invalid class" , e ) ; throw new SAXException ( e ) ; } }
Implements exception handling .
38,672
public static final String generableToString ( JGenerable generable ) { Writer w = new StringWriter ( ) ; generable . generate ( new JFormatter ( w ) ) ; return w . toString ( ) . replace ( "\"" , "" ) ; }
Returns the string value of passed argument .
38,673
public static XSDeclaration getXsdDeclaration ( CPropertyInfo propertyInfo ) { XSComponent schemaComponent = propertyInfo . getSchemaComponent ( ) ; if ( ! ( schemaComponent instanceof XSParticle ) ) { return null ; } XSTerm term = ( ( XSParticle ) schemaComponent ) . getTerm ( ) ; if ( ! ( term instanceof XSDeclaration ) ) { return null ; } return ( XSDeclaration ) term ; }
Returns XSD declaration of given property .
38,674
void readControlFile ( String fileName ) throws IOException { BufferedReader reader = new BufferedReader ( new FileReader ( fileName ) ) ; try { controlList . clear ( ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { line = line . trim ( ) ; if ( line . isEmpty ( ) || line . startsWith ( "#" ) ) { continue ; } int separatorIndex = line . indexOf ( '=' ) ; if ( separatorIndex <= 0 ) { logger . warn ( "Control file line \"" + line + "\" is invalid as does not have '=' separator." ) ; continue ; } String className = line . substring ( 0 , separatorIndex ) ; ControlMode controlMode ; try { controlMode = ControlMode . valueOf ( line . substring ( separatorIndex + 1 ) . trim ( ) . toUpperCase ( ) ) ; } catch ( IllegalArgumentException e ) { logger . warn ( "Control file line \"" + line + "\" is invalid as control mode is unknown." ) ; continue ; } controlList . add ( new ControlEntry ( className . startsWith ( "/" ) && className . endsWith ( "/" ) && className . length ( ) > 2 ? Pattern . compile ( className . substring ( 1 , className . length ( ) - 1 ) ) : Pattern . compile ( className , Pattern . LITERAL ) , controlMode ) ) ; } configurationValues . put ( ConfigurationOption . CONTROL , fileName ) ; } finally { reader . close ( ) ; } }
Parse the given control file and initialize this config appropriately .
38,675
private int createScopedFactoryMethods ( JCodeModel codeModel , JDefinedClass factoryClass , Collection < ScopedElementInfo > scopedElementInfos , JDefinedClass targetClass , JClass xmlElementDeclModelClass , JClass jaxbElementModelClass , JClass qNameModelClass ) { int createdMethods = 0 ; NEXT : for ( ScopedElementInfo info : scopedElementInfos ) { String dotClazz = targetClass . fullName ( ) + ".class" ; for ( JMethod method : factoryClass . methods ( ) ) { JAnnotationUse xmlElementDeclAnnotation = getAnnotation ( method , xmlElementDeclModelClass ) ; JExpression scope = getAnnotationMemberExpression ( xmlElementDeclAnnotation , "scope" ) ; JExpression name = getAnnotationMemberExpression ( xmlElementDeclAnnotation , "name" ) ; if ( scope != null && dotClazz . equals ( generableToString ( scope ) ) && generableToString ( info . name ) . equals ( generableToString ( name ) ) ) { continue NEXT ; } } StringBuilder methodName = new StringBuilder ( ) ; JDefinedClass container = targetClass ; while ( true ) { methodName . insert ( 0 , container . name ( ) ) ; if ( container . parentContainer ( ) . isClass ( ) ) { container = ( JDefinedClass ) container . parentContainer ( ) ; } else { break ; } } methodName . insert ( 0 , "create" ) . append ( NameConverter . standard . toPropertyName ( generableToString ( info . name ) ) ) ; JClass jaxbElementType = jaxbElementModelClass . narrow ( info . type ) ; JMethod method = factoryClass . method ( JMod . PUBLIC , jaxbElementType , methodName . toString ( ) ) ; method . annotate ( xmlElementDeclModelClass ) . param ( "namespace" , info . namespace ) . param ( "name" , info . name ) . param ( "scope" , targetClass ) ; JInvocation qname = JExpr . _new ( qNameModelClass ) . arg ( info . namespace ) . arg ( info . name ) ; JClass declaredType = info . type . boxify ( ) ; method . body ( ) . _return ( JExpr . _new ( jaxbElementType ) . arg ( qname ) . arg ( declaredType . erasure ( ) == declaredType ? declaredType . dotclass ( ) : JExpr . cast ( codeModel . ref ( Class . class ) , declaredType . dotclass ( ) ) ) . arg ( targetClass . dotclass ( ) ) . arg ( method . param ( info . type , "value" ) ) ) ; createdMethods ++ ; } return createdMethods ; }
Create additional factory methods with a new scope for elements that should be scoped .
38,676
private void deleteClass ( Outline outline , JDefinedClass clazz ) { if ( clazz . parentContainer ( ) . isClass ( ) ) { JDefinedClass parentClass = ( JDefinedClass ) clazz . parentContainer ( ) ; writeSummary ( "\tRemoving class " + clazz . fullName ( ) + " from class " + parentClass . fullName ( ) ) ; for ( Iterator < JDefinedClass > iter = parentClass . classes ( ) ; iter . hasNext ( ) ; ) { if ( iter . next ( ) . equals ( clazz ) ) { iter . remove ( ) ; break ; } } } else { JPackage parentPackage = ( JPackage ) clazz . parentContainer ( ) ; writeSummary ( "\tRemoving class " + clazz . fullName ( ) + " from package " + parentPackage . name ( ) ) ; parentPackage . remove ( clazz ) ; for ( Iterator < ? extends ClassOutline > iter = outline . getClasses ( ) . iterator ( ) ; iter . hasNext ( ) ; ) { ClassOutline classOutline = iter . next ( ) ; if ( classOutline . implClass == clazz ) { outline . getModel ( ) . beans ( ) . remove ( classOutline . target ) ; Set < Object > packageClasses = getPrivateField ( classOutline . _package ( ) , "classes" ) ; packageClasses . remove ( classOutline ) ; iter . remove ( ) ; break ; } } } }
Remove the given class from it s parent class or package it is defined in .
38,677
public String render ( ) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder docBuilder = docFactory . newDocumentBuilder ( ) ; doc = docBuilder . newDocument ( ) ; rootElement = doc . createElement ( "application" ) ; Element element ; rootElement . setAttribute ( "xmlns" , "http://java.sun.com/xml/ns/javaee" ) ; rootElement . setAttribute ( "xmlns:xsi" , "http://www.w3.org/2001/XMLSchema-instance" ) ; rootElement . setAttribute ( "xsi:schemaLocation" , "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_6.xsd" ) ; rootElement . setAttribute ( "version" , "6" ) ; doc . appendChild ( rootElement ) ; element = doc . createElement ( "description" ) ; element . setTextContent ( "Autogenerated deployment for " + basename ) ; rootElement . appendChild ( element ) ; element = doc . createElement ( "display-name" ) ; element . setTextContent ( basename + "-full" ) ; rootElement . appendChild ( element ) ; for ( String filename : ejbs ) { writeEjbModule ( filename ) ; } for ( Map . Entry < String , String > entry : webs ) { writeWebModule ( entry . getKey ( ) , entry . getValue ( ) ) ; } element = doc . createElement ( "library-directory" ) ; element . setTextContent ( "lib" ) ; rootElement . appendChild ( element ) ; TransformerFactory transformerFactory = TransformerFactory . newInstance ( ) ; Transformer transformer = transformerFactory . newTransformer ( ) ; DOMSource source = new DOMSource ( doc ) ; ByteArrayOutputStream bytes = new ByteArrayOutputStream ( ) ; StreamResult result = new StreamResult ( bytes ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; transformer . setOutputProperty ( "{http://xml.apache.org/xslt}indent-amount" , "4" ) ; transformer . transform ( source , result ) ; return bytes . toString ( ) ; } catch ( TransformerException ex ) { throw new IllegalStateException ( ex ) ; } catch ( ParserConfigurationException ex ) { throw new IllegalStateException ( ex ) ; } }
Renders application . xml filr for application .
38,678
static Class < ? > getDeploymentClass ( ArquillianDescriptor descriptor ) { Class < ? > deploymentClass = getDeploymentClassFromConfig ( descriptor ) ; if ( deploymentClass == null ) { deploymentClass = getDeploymentClassFromAnnotation ( ) ; } if ( deploymentClass == null ) { log . warning ( "arquillian-suite-deployment: Cannot find configuration in arquillian.xml, nor class annotated with @ArquillianSuiteDeployment, will try standard way.." ) ; } return deploymentClass ; }
Finds class to be used as global deployment .
38,679
public void startup ( @ Observes ( precedence = - 100 ) final BeforeSuite event ) { if ( extensionEnabled ( ) ) { debug ( "Catching BeforeSuite event {0}" , event . toString ( ) ) ; executeInClassScope ( new Callable < Void > ( ) { public Void call ( ) { generateDeploymentEvent . fire ( new GenerateDeployment ( new TestClass ( deploymentClass ) ) ) ; suiteDeploymentScenario = classDeploymentScenario . get ( ) ; return null ; } } ) ; deployDeployments = true ; extendedSuiteContext . get ( ) . activate ( ) ; suiteDeploymentScenarioInstanceProducer . set ( suiteDeploymentScenario ) ; } }
Startup event .
38,680
public void undeploy ( final BeforeStop event ) { if ( extensionEnabled ( ) ) { debug ( "Catching BeforeStop event {0}" , event . toString ( ) ) ; undeployDeployments = true ; undeployEvent . fire ( new UnDeployManagedDeployments ( ) ) ; } }
Undeploy event .
38,681
private void executeInClassScope ( Callable < Void > call ) { try { classContext . get ( ) . activate ( deploymentClass ) ; call . call ( ) ; } catch ( Exception e ) { throw new RuntimeException ( "Could not invoke operation" , e ) ; } finally { classContext . get ( ) . deactivate ( ) ; } }
Calls operation in deployment class scope .
38,682
private void debug ( String format , Object ... message ) { Boolean DEBUG = Boolean . valueOf ( System . getProperty ( "arquillian.debug" ) ) ; if ( DEBUG ) { log . log ( Level . WARNING , format , message ) ; } }
Prints debug message .
38,683
public static GsonBuilder registerAll ( GsonBuilder builder ) { if ( builder == null ) { throw new NullPointerException ( "builder cannot be null" ) ; } registerLocalDate ( builder ) ; registerLocalDateTime ( builder ) ; registerLocalTime ( builder ) ; registerOffsetDateTime ( builder ) ; registerOffsetTime ( builder ) ; registerZonedDateTime ( builder ) ; registerInstant ( builder ) ; return builder ; }
Registers all the Java Time converters .
38,684
public static < T > Publisher < T > toPublisher ( Completable completable ) { if ( completable == null ) { throw new NullPointerException ( "completable" ) ; } return new CompletableAsPublisher < T > ( completable ) ; }
Converts an RxJava Completable into a Publisher that emits only onError or onComplete .
38,685
public static Completable toCompletable ( Publisher < ? > publisher ) { if ( publisher == null ) { throw new NullPointerException ( "publisher" ) ; } return Completable . create ( new PublisherAsCompletable ( publisher ) ) ; }
Converst a Publisher into a Completable by ignoring all onNext values and emitting onError or onComplete only .
38,686
public boolean undoPendingDismiss ( ) { boolean existPendingDismisses = existPendingDismisses ( ) ; if ( existPendingDismisses ) { mPendingDismiss . rowContainer . undoContainer . setVisibility ( View . GONE ) ; mPendingDismiss . rowContainer . dataContainer . animate ( ) . translationX ( 0 ) . alpha ( 1 ) . setDuration ( mAnimationTime ) . setListener ( null ) ; mPendingDismiss = null ; } return existPendingDismisses ; }
If a view was dismissed and the undo container is showing it will undo and make the data container reappear .
38,687
private void generateDummyGroupUsages ( final Options opts ) throws BadCommandLineException { try { final Transformer transformer = GroupInterfacePlugin . TRANSFORMER_FACTORY . newTransformer ( ) ; final XPath xPath = GroupInterfacePlugin . X_PATH_FACTORY . newXPath ( ) ; final MappingNamespaceContext namespaceContext = new MappingNamespaceContext ( ) . add ( "xs" , Namespaces . XS_NS ) . add ( "kscs" , Namespaces . KSCS_BINDINGS_NS ) . add ( "jxb" , Namespaces . JAXB_NS ) ; xPath . setNamespaceContext ( namespaceContext ) ; final XPathExpression attGroupExpression = xPath . compile ( "/xs:schema/xs:attributeGroup" ) ; final XPathExpression modelGroupExpression = xPath . compile ( "/xs:schema/xs:group" ) ; final XPathExpression targetNamespaceExpression = xPath . compile ( "/xs:schema/@targetNamespace" ) ; final Map < String , List < String > > includeMappings = findIncludeMappings ( xPath , opts . getGrammars ( ) ) ; final List < InputSource > newGrammars = new ArrayList < > ( ) ; for ( final InputSource grammarSource : opts . getGrammars ( ) ) { final Document grammar = copyInputSource ( grammarSource ) ; final String declaredTargetNamespaceUri = targetNamespaceExpression . evaluate ( grammar ) ; for ( final String targetNamespaceUri : declaredTargetNamespaceUri == null ? includeMappings . get ( grammarSource . getSystemId ( ) ) : Collections . singletonList ( declaredTargetNamespaceUri ) ) { final NodeList attGroupNodes = ( NodeList ) attGroupExpression . evaluate ( grammar , XPathConstants . NODESET ) ; final NodeList modelGroupNodes = ( NodeList ) modelGroupExpression . evaluate ( grammar , XPathConstants . NODESET ) ; final Groups currentGroups = new Groups ( targetNamespaceUri ) ; for ( int i = 0 ; i < attGroupNodes . getLength ( ) ; i ++ ) { final Element node = ( Element ) attGroupNodes . item ( i ) ; currentGroups . attGroupNames . add ( node . getAttribute ( "name" ) ) ; } for ( int i = 0 ; i < modelGroupNodes . getLength ( ) ; i ++ ) { final Element node = ( Element ) modelGroupNodes . item ( i ) ; currentGroups . modelGroupNames . add ( node . getAttribute ( "name" ) ) ; } final InputSource newSchema = generateImplementationSchema ( opts , transformer , currentGroups , grammarSource . getSystemId ( ) ) ; if ( newSchema != null ) { newGrammars . add ( newSchema ) ; } } } for ( final InputSource newGrammar : newGrammars ) { opts . addGrammar ( newGrammar ) ; } } catch ( final Exception e ) { throw new BadCommandLineException ( getMessage ( "error.plugin-setup" , e ) ) ; } }
Generates dummy complexTypes that implement the interface generated from group decls . These complexTypes will be transformed into classes by the default code generator . Later this plugin will transform the classes into interface declarations . This approach avoids tedious re - implementation of the property generation code with all the effects of settings options and customizations in this plugin .
38,688
public boolean start ( ) { Intent emailIntent = build ( ) ; try { startActivity ( emailIntent ) ; } catch ( ActivityNotFoundException e ) { return false ; } return true ; }
Launch the email intent .
38,689
@ Support ( { SQLDialect . POSTGRES } ) public static Field < String > stringAgg ( Field < String > field , String delimiter ) { return DSL . field ( "string_agg({0}, {1})" , field . getDataType ( ) , field , DSL . val ( delimiter ) ) ; }
Joins a set of string values using the given delimiter .
38,690
public static synchronized void configure ( final String options , final Instrumentation instrumentation ) throws Exception { if ( SigarAgent . instrumentation != null ) { logger . severe ( "Duplicate agent setup attempt." ) ; return ; } SigarAgent . options = options ; SigarAgent . instrumentation = instrumentation ; logger . info ( "Sigar loader options: " + options ) ; final File folder = new File ( SigarProvisioner . discoverLocation ( options ) ) ; SigarProvisioner . provision ( folder ) ; }
Agent mode configuration .
38,691
public static synchronized boolean isNativeLoaded ( ) { try { return isSigarAlreadyLoaded ( ) ; } catch ( final Throwable e ) { try { final Sigar sigar = new Sigar ( ) ; sigar . getPid ( ) ; sigar . close ( ) ; return true ; } catch ( final Throwable ex ) { return false ; } } }
Verify if sigar native library is loaded and operational .
38,692
public static synchronized void provision ( final File folder ) throws Exception { if ( isNativeLoaded ( ) ) { logger . warning ( "Sigar library is already provisioned." ) ; return ; } if ( ! folder . exists ( ) ) { folder . mkdirs ( ) ; } final SigarLoader sigarLoader = new SigarLoader ( Sigar . class ) ; final String libraryName = sigarLoader . getLibraryName ( ) ; final String sourcePath = "/" + LIB_DIR + "/" + libraryName ; final File targetPath = new File ( folder , libraryName ) . getAbsoluteFile ( ) ; final InputStream sourceStream = SigarProvisioner . class . getResourceAsStream ( sourcePath ) ; final OutputStream targetStream = new FileOutputStream ( targetPath ) ; transfer ( sourceStream , targetStream ) ; sourceStream . close ( ) ; targetStream . close ( ) ; final String libraryPath = targetPath . getAbsolutePath ( ) ; System . load ( libraryPath ) ; System . setProperty ( "org.hyperic.sigar.path" , "-" ) ; sigarLoader . load ( ) ; logger . info ( "Sigar library provisioned: " + libraryPath ) ; }
Extract and load native sigar library in the provided folder .
38,693
public static void transfer ( final InputStream input , final OutputStream output ) throws Exception { final byte [ ] data = new byte [ SIZE ] ; while ( true ) { final int count = input . read ( data , 0 , SIZE ) ; if ( count == EOF ) { break ; } output . write ( data , 0 , count ) ; } }
Perform stream copy .
38,694
public void addPattern ( Pattern pattern ) { if ( patterns == null ) { patterns = new ArrayList < Pattern > ( ) ; } patterns . add ( pattern ) ; }
Add a pattern to the list of patterns .
38,695
public Pattern getPattern ( ) { if ( patterns != null && ! patterns . isEmpty ( ) ) { return patterns . get ( 0 ) ; } else { return null ; } }
Get pattern for text parsing
38,696
public void setPattern ( Pattern pattern ) { patterns = new ArrayList < Pattern > ( 1 ) ; patterns . add ( pattern ) ; }
Set pattern for text parsing
38,697
public int findIn ( Source source ) { if ( source . hasNext ( ) ) { if ( onBol ( source ) ) { return source . getOffset ( ) ; } int index = findLineBreak ( source ) ; if ( index < 0 ) { return - 1 ; } index = skipLineBreak ( source , index ) ; if ( index < source . length ( ) ) { return index ; } else { return - 1 ; } } else { return - 1 ; } }
I strongly don t recommend to use tag bol as a terminator .
38,698
private boolean onBol ( Source source ) { int offset = source . getOffset ( ) ; if ( offset == 0 ) { return true ; } else { char c = source . charAt ( offset ) ; char p = source . charAt ( offset - 1 ) ; return c != '\n' && c != '\r' && ( p == '\n' || p == '\r' ) ; } }
Check we are on the beginning of line
38,699
private int findLineBreak ( Source source ) { int index ; int n = source . find ( AbstractEol . AN , false ) ; int r = source . find ( AbstractEol . AR , false ) ; if ( n >= 0 && r >= 0 ) { index = Math . min ( n , r ) ; } else if ( n >= 0 ) { index = n ; } else if ( r >= 0 ) { index = r ; } else { index = - 1 ; } return index ; }
Find first input of line break