signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class Mailer { /** * Fills the { @ link Message } instance with the embedded images from the { @ link Email } .
* @ param email The message in which the embedded images are defined .
* @ param multipartRelated The branch in the email structure in which we ' ll stuff the embedded images .
* @ throws MessagingException See { @ link MimeMultipart # addBodyPart ( BodyPart ) } and
* { @ link # getBodyPartFromDatasource ( AttachmentResource , String ) } */
private void setEmbeddedImages ( final Email email , final MimeMultipart multipartRelated ) throws MessagingException { } } | for ( final AttachmentResource embeddedImage : email . getEmbeddedImages ( ) ) { multipartRelated . addBodyPart ( getBodyPartFromDatasource ( embeddedImage , Part . INLINE ) ) ; } |
public class Email { /** * Adds an embedded image ( attachment type ) to the email message and generates the necessary { @ link DataSource } with
* the given byte data . Then delegates to { @ link # addEmbeddedImage ( String , DataSource ) } . At this point the
* datasource is actually a { @ link ByteArrayDataSource } .
* @ param name The name of the image as being referred to from the message content body ( eg .
* ' & lt ; cid : signature & gt ; ' ) .
* @ param data The byte data of the image to be embedded .
* @ param mimetype The content type of the given data ( eg . " image / gif " or " image / jpeg " ) .
* @ see ByteArrayDataSource
* @ see # addEmbeddedImage ( String , DataSource ) */
public void addEmbeddedImage ( final String name , final byte [ ] data , final String mimetype ) { } } | final ByteArrayDataSource dataSource = new ByteArrayDataSource ( data , mimetype ) ; dataSource . setName ( name ) ; addEmbeddedImage ( name , dataSource ) ; |
public class Javalin { /** * Adds an exception mapper to the instance .
* @ see < a href = " https : / / javalin . io / documentation # exception - mapping " > Exception mapping in docs < / a > */
public < T extends Exception > Javalin exception ( @ NotNull Class < T > exceptionClass , @ NotNull ExceptionHandler < ? super T > exceptionHandler ) { } } | servlet . getExceptionMapper ( ) . getHandlers ( ) . put ( exceptionClass , ( ExceptionHandler < Exception > ) exceptionHandler ) ; return this ; |
public class MisoScenePanel { /** * Renders the base and fringe layer tiles that intersect the
* specified clipping rectangle . */
protected void paintTiles ( Graphics2D gfx , Rectangle clip ) { } } | // go through rendering our tiles
_paintOp . setGraphics ( gfx ) ; _applicator . applyToTiles ( clip , _paintOp ) ; _paintOp . setGraphics ( null ) ; |
public class ReadFileExtensions { /** * Reads every line from the File and puts them to the List .
* @ param input
* The File from where the input comes .
* @ return The List with all lines from the file .
* @ throws FileNotFoundException
* is thrown if the given file is not found .
* @ throws IOException
* Signals that an I / O exception has occurred . */
public static List < String > readLinesInList ( final File input ) throws FileNotFoundException , IOException { } } | return readLinesInList ( input , false ) ; |
public class ExtensionRESTService { /** * Returns the arbitrary REST resource exposed by the AuthenticationProvider
* having the given identifier .
* @ param identifier
* The identifier of the AuthenticationProvider whose REST resource
* should be retrieved .
* @ return
* The arbitrary REST resource exposed by the AuthenticationProvider
* having the given identifier .
* @ throws GuacamoleException
* If no such resource could be found , or if an error occurs while
* retrieving that resource . */
@ Path ( "{identifier}" ) public Object getExtensionResource ( @ PathParam ( "identifier" ) String identifier ) throws GuacamoleException { } } | // Retrieve authentication provider having given identifier
AuthenticationProvider authProvider = getAuthenticationProvider ( identifier ) ; if ( authProvider != null ) { // Pull resource from authentication provider
Object resource = authProvider . getResource ( ) ; if ( resource != null ) return resource ; } // AuthenticationProvider - specific resource could not be found
throw new GuacamoleResourceNotFoundException ( "No such resource." ) ; |
public class GatewayManagementBeanImpl { /** * This must run ON the IO thread */
@ Override public void doSessionCreated ( final long sessionId , final ManagementSessionType managementSessionType ) throws Exception { } } | ThreadGatewayStats stats = gatewayStats . get ( ) ; stats . doSessionCreated ( ) ; |
public class TileBoundingBoxUtils { /** * Get the Web Mercator tile bounding box from the Google Maps API tile grid
* and zoom level
* @ param tileGrid
* tile grid
* @ param zoom
* zoom level
* @ return bounding box */
public static BoundingBox getWebMercatorBoundingBox ( TileGrid tileGrid , int zoom ) { } } | double tileSize = tileSizeWithZoom ( zoom ) ; double minLon = ( - 1 * ProjectionConstants . WEB_MERCATOR_HALF_WORLD_WIDTH ) + ( tileGrid . getMinX ( ) * tileSize ) ; double maxLon = ( - 1 * ProjectionConstants . WEB_MERCATOR_HALF_WORLD_WIDTH ) + ( ( tileGrid . getMaxX ( ) + 1 ) * tileSize ) ; double minLat = ProjectionConstants . WEB_MERCATOR_HALF_WORLD_WIDTH - ( ( tileGrid . getMaxY ( ) + 1 ) * tileSize ) ; double maxLat = ProjectionConstants . WEB_MERCATOR_HALF_WORLD_WIDTH - ( tileGrid . getMinY ( ) * tileSize ) ; BoundingBox box = new BoundingBox ( minLon , minLat , maxLon , maxLat ) ; return box ; |
public class CmsUserSettings { /** * Initializes the user settings with the given users setting parameters . < p >
* @ param user the current CmsUser */
public void init ( CmsUser user ) { } } | m_user = user ; // try to initialize the User Settings with the values stored in the user object .
// if no values are found , the default user settings will be used .
// workplace button style
try { m_workplaceButtonStyle = ( ( Integer ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_WORKPLACEGENERALOPTIONS + CmsWorkplaceConfiguration . N_BUTTONSTYLE ) ) . intValue ( ) ; } catch ( Throwable t ) { m_workplaceButtonStyle = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getWorkplaceButtonStyle ( ) ; } // workplace time warp setting
Object timeWarpObj = m_user . getAdditionalInfo ( ADDITIONAL_INFO_TIMEWARP ) ; try { m_timeWarp = ( ( Long ) timeWarpObj ) . longValue ( ) ; } catch ( ClassCastException e ) { try { m_timeWarp = Long . parseLong ( ( String ) timeWarpObj ) ; if ( m_timeWarp < 0 ) { m_timeWarp = CmsContextInfo . CURRENT_TIME ; } } catch ( Throwable t ) { m_timeWarp = CmsContextInfo . CURRENT_TIME ; } } catch ( Throwable t ) { m_timeWarp = CmsContextInfo . CURRENT_TIME ; } // workplace report type
m_workplaceReportType = ( String ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_WORKPLACEGENERALOPTIONS + CmsWorkplaceConfiguration . N_REPORTTYPE ) ; if ( m_workplaceReportType == null ) { m_workplaceReportType = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getWorkplaceReportType ( ) ; } // workplace list all projects
try { m_listAllProjects = ( ( Boolean ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_WORKPLACEGENERALOPTIONS + CmsWorkplaceConfiguration . N_LISTALLPROJECTS ) ) . booleanValue ( ) ; } catch ( Throwable t ) { m_listAllProjects = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getListAllProjects ( ) ; } // workplace show publish notification
try { m_showPublishNotification = ( ( Boolean ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_WORKPLACEGENERALOPTIONS + CmsWorkplaceConfiguration . N_PUBLISHNOTIFICATION ) ) . booleanValue ( ) ; } catch ( Throwable t ) { m_showPublishNotification = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getShowPublishNotification ( ) ; } // workplace upload applet mode
setUploadVariant ( String . valueOf ( m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_WORKPLACEGENERALOPTIONS + CmsWorkplaceConfiguration . N_UPLOADAPPLET ) ) ) ; // locale
Object obj = m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_WORKPLACESTARTUPSETTINGS + CmsWorkplaceConfiguration . N_LOCALE ) ; if ( obj == null ) { m_locale = null ; } else { m_locale = CmsLocaleManager . getLocale ( String . valueOf ( obj ) ) ; } if ( m_locale == null ) { m_locale = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getLocale ( ) ; } // start project
try { m_project = ( String ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_WORKPLACESTARTUPSETTINGS + CmsWorkplaceConfiguration . N_PROJECT ) ; } catch ( Throwable t ) { m_project = null ; } if ( m_project == null ) { m_project = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getStartProject ( ) ; String ou = user . getOuFqn ( ) ; if ( ou == null ) { ou = "" ; } m_project = user . getOuFqn ( ) + m_project ; } // start view
m_view = ( String ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_WORKPLACESTARTUPSETTINGS + CmsWorkplaceConfiguration . N_WORKPLACEVIEW ) ; if ( m_view == null ) { m_view = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getStartView ( ) ; } // explorer button style
try { m_explorerButtonStyle = ( ( Integer ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_EXPLORERGENERALOPTIONS + CmsWorkplaceConfiguration . N_BUTTONSTYLE ) ) . intValue ( ) ; } catch ( Throwable t ) { m_explorerButtonStyle = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getExplorerButtonStyle ( ) ; } // explorer file entries
try { m_explorerFileEntries = ( ( Integer ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_EXPLORERGENERALOPTIONS + CmsWorkplaceConfiguration . N_ENTRIES ) ) . intValue ( ) ; } catch ( Throwable t ) { m_explorerFileEntries = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getExplorerFileEntries ( ) ; } // explorer settings
try { m_explorerSettings = ( ( Integer ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_EXPLORERGENERALOPTIONS + CmsWorkplaceConfiguration . N_EXPLORERDISPLAYOPTIONS ) ) . intValue ( ) ; } catch ( Throwable t ) { m_explorerSettings = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getExplorerSettings ( ) ; } // dialog file copy mode
try { m_dialogFileCopy = CmsResourceCopyMode . valueOf ( ( ( Integer ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_DIALOGSDEFAULTSETTINGS + CmsWorkplaceConfiguration . N_FILECOPY ) ) . intValue ( ) ) ; } catch ( Throwable t ) { m_dialogFileCopy = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getDialogCopyFileMode ( ) ; } // dialog folder copy mode
try { m_dialogFolderCopy = CmsResourceCopyMode . valueOf ( ( ( Integer ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_DIALOGSDEFAULTSETTINGS + CmsWorkplaceConfiguration . N_FOLDERCOPY ) ) . intValue ( ) ) ; } catch ( Throwable t ) { m_dialogFolderCopy = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getDialogCopyFolderMode ( ) ; } // dialog file delete mode
try { m_dialogFileDelete = CmsResourceDeleteMode . valueOf ( ( ( Integer ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_DIALOGSDEFAULTSETTINGS + CmsWorkplaceConfiguration . N_FILEDELETION ) ) . intValue ( ) ) ; } catch ( Throwable t ) { m_dialogFileDelete = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getDialogDeleteFileMode ( ) ; } // dialog direct publish mode
try { m_dialogDirectpublish = ( ( Boolean ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_DIALOGSDEFAULTSETTINGS + CmsWorkplaceConfiguration . N_DIRECTPUBLISH ) ) . booleanValue ( ) ; } catch ( Throwable t ) { m_dialogDirectpublish = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getDialogPublishSiblings ( ) ; } // dialog show lock mode
try { m_showLock = ( ( Boolean ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_DIALOGSDEFAULTSETTINGS + CmsWorkplaceConfiguration . N_SHOWLOCK ) ) . booleanValue ( ) ; } catch ( Throwable t ) { m_showLock = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getDialogShowLock ( ) ; } // dialog show export settings mode
try { m_showExportSettings = ( ( Boolean ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_DIALOGSDEFAULTSETTINGS + CmsWorkplaceConfiguration . N_SHOWEXPORTSETTINGS ) ) . booleanValue ( ) ; } catch ( Throwable t ) { m_showExportSettings = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getDialogShowExportSettings ( ) ; } // dialog permissions inheriting mode
try { m_dialogPermissionsInheritOnFolder = ( ( Boolean ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_DIALOGSDEFAULTSETTINGS + CmsWorkplaceConfiguration . N_PERMISSIONSINHERITONFOLDER ) ) . booleanValue ( ) ; } catch ( Throwable t ) { m_dialogPermissionsInheritOnFolder = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getDialogPermissionsInheritOnFolder ( ) ; } // dialog expand inherited permissions mode
try { m_dialogExpandInheritedPermissions = ( ( Boolean ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_DIALOGSDEFAULTSETTINGS + CmsWorkplaceConfiguration . N_EXPANDPERMISSIONSINHERITED ) ) . booleanValue ( ) ; } catch ( Throwable t ) { m_dialogExpandInheritedPermissions = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getDialogExpandInheritedPermissions ( ) ; } // dialog expand users permissions mode
try { m_dialogExpandUserPermissions = ( ( Boolean ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_DIALOGSDEFAULTSETTINGS + CmsWorkplaceConfiguration . N_EXPANDPERMISSIONSUSER ) ) . booleanValue ( ) ; } catch ( Throwable t ) { m_dialogExpandUserPermissions = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getDialogExpandUserPermissions ( ) ; } // editor button style
try { m_editorButtonStyle = ( ( Integer ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_EDITORGENERALOPTIONS + CmsWorkplaceConfiguration . N_BUTTONSTYLE ) ) . intValue ( ) ; } catch ( Throwable t ) { m_editorButtonStyle = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getEditorButtonStyle ( ) ; } // direct edit button style
try { m_directeditButtonStyle = ( ( Integer ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_EDITORGENERALOPTIONS + CmsWorkplaceConfiguration . N_DIRECTEDITSTYLE ) ) . intValue ( ) ; } catch ( Throwable t ) { m_directeditButtonStyle = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getDirectEditButtonStyle ( ) ; } // editor settings
m_editorSettings = new TreeMap < String , String > ( ) ; Iterator < String > itKeys = m_user . getAdditionalInfo ( ) . keySet ( ) . iterator ( ) ; while ( itKeys . hasNext ( ) ) { String key = itKeys . next ( ) ; if ( key . startsWith ( PREFERENCES + CmsWorkplaceConfiguration . N_EDITORPREFERREDEDITORS ) ) { String editKey = key . substring ( ( PREFERENCES + CmsWorkplaceConfiguration . N_EDITORPREFERREDEDITORS ) . length ( ) ) ; m_editorSettings . put ( editKey , m_user . getAdditionalInfo ( key ) . toString ( ) ) ; } } if ( m_editorSettings . isEmpty ( ) ) { m_editorSettings = new TreeMap < String , String > ( OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getEditorSettings ( ) ) ; } // start gallery settings
m_startGalleriesSettings = new TreeMap < String , String > ( ) ; Iterator < String > gKeys = m_user . getAdditionalInfo ( ) . keySet ( ) . iterator ( ) ; while ( gKeys . hasNext ( ) ) { String key = gKeys . next ( ) ; if ( key . startsWith ( PREFERENCES + CmsWorkplaceConfiguration . N_STARTGALLERIES ) ) { String editKey = key . substring ( ( PREFERENCES + CmsWorkplaceConfiguration . N_STARTGALLERIES ) . length ( ) ) ; m_startGalleriesSettings . put ( editKey , m_user . getAdditionalInfo ( key ) . toString ( ) ) ; } } if ( m_startGalleriesSettings . isEmpty ( ) ) { m_startGalleriesSettings = new TreeMap < String , String > ( OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getStartGalleriesSettings ( ) ) ; } // start site
m_startSite = ( String ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_WORKPLACESTARTUPSETTINGS + I_CmsXmlConfiguration . N_SITE ) ; if ( m_startSite == null ) { m_startSite = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getStartSite ( ) ; } // start folder , we use the setter here for default logic in case of illegal folder string :
String startFolder = ( String ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_WORKPLACESTARTUPSETTINGS + CmsWorkplaceConfiguration . N_FOLDER ) ; if ( startFolder == null ) { startFolder = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getStartFolder ( ) ; } setStartFolder ( startFolder ) ; // restrict explorer folder view
try { m_restrictExplorerView = ( ( Boolean ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_WORKPLACESTARTUPSETTINGS + CmsWorkplaceConfiguration . N_RESTRICTEXPLORERVIEW ) ) . booleanValue ( ) ; } catch ( Throwable t ) { m_restrictExplorerView = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getRestrictExplorerView ( ) ; } // workplace search
m_workplaceSearchIndexName = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getWorkplaceSearchIndexName ( ) ; m_workplaceSearchViewStyle = CmsSearchResultStyle . valueOf ( ( String ) m_user . getAdditionalInfo ( PREFERENCES + CmsWorkplaceConfiguration . N_WORKPLACESEARCH + CmsWorkplaceConfiguration . N_SEARCHVIEWSTYLE ) ) ; if ( m_workplaceSearchViewStyle == null ) { m_workplaceSearchViewStyle = OpenCms . getWorkplaceManager ( ) . getDefaultUserSettings ( ) . getWorkplaceSearchViewStyle ( ) ; } // synchronize settings
try { boolean enabled = ( ( Boolean ) m_user . getAdditionalInfo ( PREFERENCES + SYNC_SETTINGS + SYNC_ENABLED ) ) . booleanValue ( ) ; String destination = ( String ) m_user . getAdditionalInfo ( PREFERENCES + SYNC_SETTINGS + SYNC_DESTINATION ) ; List < String > vfsList = CmsStringUtil . splitAsList ( ( String ) m_user . getAdditionalInfo ( PREFERENCES + SYNC_SETTINGS + SYNC_VFS_LIST ) , '|' ) ; m_synchronizeSettings = new CmsSynchronizeSettings ( ) ; m_synchronizeSettings . setEnabled ( enabled ) ; m_synchronizeSettings . setDestinationPathInRfs ( destination ) ; m_synchronizeSettings . setSourceListInVfs ( vfsList ) ; } catch ( Throwable t ) { // default is to disable the synchronize settings
m_synchronizeSettings = null ; } // upload applet client folder path
m_uploadAppletClientFolder = ( String ) m_user . getAdditionalInfo ( ADDITIONAL_INFO_UPLOADAPPLET_CLIENTFOLDER ) ; for ( Map . Entry < String , Object > entry : m_user . getAdditionalInfo ( ) . entrySet ( ) ) { String key = entry . getKey ( ) ; if ( key . startsWith ( CmsUserSettings . PREFERENCES_ADDITIONAL_PREFIX ) ) { try { String value = ( String ) entry . getValue ( ) ; m_additionalPreferences . put ( key . substring ( CmsUserSettings . PREFERENCES_ADDITIONAL_PREFIX . length ( ) ) , value ) ; } catch ( ClassCastException e ) { LOG . warn ( e . getLocalizedMessage ( ) , e ) ; } } } try { save ( null ) ; } catch ( CmsException e ) { // ignore
if ( LOG . isWarnEnabled ( ) ) { LOG . warn ( e . getLocalizedMessage ( ) , e ) ; } } |
public class CommerceTierPriceEntryLocalServiceWrapper { /** * Returns the commerce tier price entry matching the UUID and group .
* @ param uuid the commerce tier price entry ' s UUID
* @ param groupId the primary key of the group
* @ return the matching commerce tier price entry , or < code > null < / code > if a matching commerce tier price entry could not be found */
@ Override public com . liferay . commerce . price . list . model . CommerceTierPriceEntry fetchCommerceTierPriceEntryByUuidAndGroupId ( String uuid , long groupId ) { } } | return _commerceTierPriceEntryLocalService . fetchCommerceTierPriceEntryByUuidAndGroupId ( uuid , groupId ) ; |
public class DynamicCompositeAgent { /** * Try and remove an { @ link Agent } from the composite . The agent is removed during the next { @ link # doWork ( ) }
* duty cycle if this operation is successful . This method does not block and will return false if another
* concurrent attempt to remove is in progress . .
* The { @ link Agent } is removed by identity . Only the first found is removed .
* @ param agent to be removed .
* @ return true is a successful remove request is pending otherwise false if another concurrent remove request
* is in progress .
* @ see # hasRemoveAgentCompleted ( ) */
public boolean tryRemove ( final Agent agent ) { } } | Objects . requireNonNull ( agent , "agent cannot be null" ) ; if ( Status . ACTIVE != status ) { throw new IllegalStateException ( "remove called when not active" ) ; } return removeAgent . compareAndSet ( null , agent ) ; |
public class ChangesListener { /** * { @ inheritDoc }
* Checks if new changes can exceeds some limits . It either can be node , workspace ,
* repository or global JCR instance .
* @ throws IllegalStateException if data size exceeded quota limit */
public void onSaveItems ( ItemStateChangesLog itemStates ) { } } | try { ChangesItem changesItem = new ChangesItem ( ) ; for ( ItemState state : itemStates . getAllStates ( ) ) { if ( ! state . getData ( ) . isNode ( ) ) { String nodePath = getPath ( state . getData ( ) . getQPath ( ) . makeParentPath ( ) ) ; Set < String > parentsWithQuota = quotaPersister . getAllParentNodesWithQuota ( rName , wsName , nodePath ) ; for ( String parent : parentsWithQuota ) { changesItem . updateNodeChangedSize ( parent , state . getChangedSize ( ) ) ; addPathsWithAsyncUpdate ( changesItem , parent ) ; } changesItem . updateWorkspaceChangedSize ( state . getChangedSize ( ) ) ; } else { addPathsWithUnknownChangedSize ( changesItem , state ) ; } } validatePendingChanges ( changesItem ) ; pendingChanges . set ( changesItem ) ; } catch ( ExceededQuotaLimitException e ) { throw new IllegalStateException ( e . getMessage ( ) , e ) ; } |
public class BaseDAO { /** * Clear all entries in internal shared preferences file .
* @ return Returns true if the new values were successfully written */
boolean clearAll ( ) { } } | SharedPreferences . Editor editor = sharedPreferences . edit ( ) ; Map < String , ? > all = sharedPreferences . getAll ( ) ; // noinspection Convert2streamapi
for ( String key : all . keySet ( ) ) { editor . remove ( key ) ; } return editor . commit ( ) ; |
public class StaticTypeCheckingSupport { /** * Tells if a class is one of the " accept all " classes as the left hand side of an
* assignment .
* @ param node the classnode to test
* @ return true if it ' s an Object , String , boolean , Boolean or Class . */
public static boolean isWildcardLeftHandSide ( final ClassNode node ) { } } | if ( OBJECT_TYPE . equals ( node ) || STRING_TYPE . equals ( node ) || boolean_TYPE . equals ( node ) || Boolean_TYPE . equals ( node ) || CLASS_Type . equals ( node ) ) { return true ; } return false ; |
public class ZeroCodePackageRunner { /** * Returns a list of objects that define the children of this Runner . */
@ Override protected List < ScenarioSpec > getChildren ( ) { } } | TestPackageRoot rootPackageAnnotation = testClass . getAnnotation ( TestPackageRoot . class ) ; JsonTestCases jsonTestCasesAnnotation = testClass . getAnnotation ( JsonTestCases . class ) ; validateSuiteAnnotationPresent ( rootPackageAnnotation , jsonTestCasesAnnotation ) ; if ( rootPackageAnnotation != null ) { /* * Different scenarios with same name - or - Same scenarios with same name more than once is prevented */
smartUtils . checkDuplicateScenarios ( rootPackageAnnotation . value ( ) ) ; return smartUtils . getScenarioSpecListByPackage ( rootPackageAnnotation . value ( ) ) ; } else { List < JsonTestCase > jsonTestCases = Arrays . asList ( testClass . getAnnotationsByType ( JsonTestCase . class ) ) ; List < String > allEndPointFiles = jsonTestCases . stream ( ) . map ( thisTestCase -> thisTestCase . value ( ) ) . collect ( Collectors . toList ( ) ) ; return allEndPointFiles . stream ( ) . map ( testResource -> { try { return smartUtils . jsonFileToJava ( testResource , ScenarioSpec . class ) ; } catch ( IOException e ) { throw new RuntimeException ( "Exception while deserializing to Spec. Details: " + e ) ; } } ) . collect ( Collectors . toList ( ) ) ; } |
public class Optimum { /** * Sets to indicate three LZMA symbols of which the second one
* is a literal . */
void set3 ( int newPrice , int optCur , int back2 , int len2 , int back ) { } } | price = newPrice ; optPrev = optCur + len2 + 1 ; backPrev = back ; prev1IsLiteral = true ; hasPrev2 = true ; optPrev2 = optCur ; backPrev2 = back2 ; |
public class PortletDefinitionImporterExporter { /** * Save a portlet definition .
* @ param definition the portlet definition
* @ param categories the list of categories for the portlet
* @ param permissionMap a map of permission name - > list of groups who are granted that
* permission ( Note : for now , only grant is supported and only for the FRAMEWORK _ OWNER perm
* manager ) */
private IPortletDefinition savePortletDefinition ( IPortletDefinition definition , List < PortletCategory > categories , Map < ExternalPermissionDefinition , Set < IGroupMember > > permissionMap ) { } } | boolean newChannel = ( definition . getPortletDefinitionId ( ) == null ) ; // save the channel
definition = portletDefinitionDao . savePortletDefinition ( definition ) ; definition = portletDefinitionDao . getPortletDefinitionByFname ( definition . getFName ( ) ) ; final String defId = definition . getPortletDefinitionId ( ) . getStringId ( ) ; final IEntity portletDefEntity = GroupService . getEntity ( defId , IPortletDefinition . class ) ; // Sync on groups during update . This really should be a portal wide thread - safety check or
// The groups service needs to deal with concurrent modification better .
synchronized ( this . groupUpdateLock ) { // Delete existing category memberships for this channel
if ( ! newChannel ) { for ( IEntityGroup group : portletDefEntity . getAncestorGroups ( ) ) { group . removeChild ( portletDefEntity ) ; group . update ( ) ; } } // For each category ID , add channel to category
for ( PortletCategory category : categories ) { final IEntityGroup categoryGroup = GroupService . findGroup ( category . getId ( ) ) ; categoryGroup . addChild ( portletDefEntity ) ; categoryGroup . updateMembers ( ) ; } // Set groups
final AuthorizationServiceFacade authService = AuthorizationServiceFacade . instance ( ) ; final String target = PermissionHelper . permissionTargetIdForPortletDefinition ( definition ) ; // Loop over the affected permission managers . . .
Map < String , Collection < ExternalPermissionDefinition > > permissionsBySystem = getPermissionsBySystem ( permissionMap . keySet ( ) ) ; for ( String system : permissionsBySystem . keySet ( ) ) { Collection < ExternalPermissionDefinition > systemPerms = permissionsBySystem . get ( system ) ; // get the permission manager for this system . . .
final IUpdatingPermissionManager upm = authService . newUpdatingPermissionManager ( system ) ; final List < IPermission > permissions = new ArrayList < > ( ) ; // add activity grants for each permission . .
for ( ExternalPermissionDefinition permissionDef : systemPerms ) { Set < IGroupMember > members = permissionMap . get ( permissionDef ) ; for ( final IGroupMember member : members ) { final IAuthorizationPrincipal authPrincipal = authService . newPrincipal ( member ) ; final IPermission permEntity = upm . newPermission ( authPrincipal ) ; permEntity . setType ( IPermission . PERMISSION_TYPE_GRANT ) ; permEntity . setActivity ( permissionDef . getActivity ( ) ) ; permEntity . setTarget ( target ) ; permissions . add ( permEntity ) ; } } // If modifying the channel , remove the existing permissions before adding the new
// ones
if ( ! newChannel ) { for ( ExternalPermissionDefinition permissionName : permissionMap . keySet ( ) ) { IPermission [ ] oldPermissions = upm . getPermissions ( permissionName . getActivity ( ) , target ) ; upm . removePermissions ( oldPermissions ) ; } } upm . addPermissions ( permissions . toArray ( new IPermission [ permissions . size ( ) ] ) ) ; } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Portlet " + defId + " has been " + ( newChannel ? "published" : "modified" ) + "." ) ; } return definition ; |
public class JacksonWrapperParser { /** * / * ( non - Javadoc )
* @ see com . abubusoft . kripton . persistence . ParserWrapper # close ( ) */
@ Override public void close ( ) { } } | try { if ( ! jacksonParser . isClosed ( ) ) jacksonParser . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; throw ( new KriptonRuntimeException ( e ) ) ; } |
public class AttributeMarshaller { /** * Marshall the given parameter object . */
public void marshall ( Attribute attribute , ProtocolMarshaller protocolMarshaller ) { } } | if ( attribute == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( attribute . getName ( ) , NAME_BINDING ) ; protocolMarshaller . marshall ( attribute . getValue ( ) , VALUE_BINDING ) ; protocolMarshaller . marshall ( attribute . getTargetType ( ) , TARGETTYPE_BINDING ) ; protocolMarshaller . marshall ( attribute . getTargetId ( ) , TARGETID_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class VarOptItemsSketch { /** * Resets this sketch to the empty state , but retains the original value of k . */
public void reset ( ) { } } | final int ceilingLgK = Util . toLog2 ( Util . ceilingPowerOf2 ( k_ ) , "VarOptItemsSketch" ) ; final int initialLgSize = SamplingUtil . startingSubMultiple ( ceilingLgK , rf_ . lg ( ) , MIN_LG_ARR_ITEMS ) ; currItemsAlloc_ = SamplingUtil . getAdjustedSize ( k_ , 1 << initialLgSize ) ; data_ = new ArrayList < > ( currItemsAlloc_ ) ; weights_ = new ArrayList < > ( currItemsAlloc_ ) ; if ( marks_ != null ) { marks_ = new ArrayList < > ( currItemsAlloc_ ) ; } n_ = 0 ; h_ = 0 ; m_ = 0 ; r_ = 0 ; numMarksInH_ = 0 ; totalWtR_ = 0.0 ; |
public class EnvironmentStream { /** * Sets path as the backing stream for System . err */
public static synchronized void setStderr ( OutputStream os ) { } } | if ( _stderrStream == null ) { initStderr ( ) ; } if ( os == _systemErr || os == _systemOut ) { return ; } if ( os instanceof WriteStream ) { WriteStream out = ( WriteStream ) os ; /* if ( out . getSource ( ) = = StdoutStream . create ( )
| | out . getSource ( ) = = StderrStream . create ( ) ) {
return ; */
} _stderrStream . setStream ( os ) ; |
public class AmazonIdentityManagementClient { /** * Retrieves the status of your service - linked role deletion . After you use the < a > DeleteServiceLinkedRole < / a > API
* operation to submit a service - linked role for deletion , you can use the < code > DeletionTaskId < / code > parameter in
* < code > GetServiceLinkedRoleDeletionStatus < / code > to check the status of the deletion . If the deletion fails , this
* operation returns the reason that it failed , if that information is returned by the service .
* @ param getServiceLinkedRoleDeletionStatusRequest
* @ return Result of the GetServiceLinkedRoleDeletionStatus operation returned by the service .
* @ throws NoSuchEntityException
* The request was rejected because it referenced a resource entity that does not exist . The error message
* describes the resource .
* @ throws InvalidInputException
* The request was rejected because an invalid or out - of - range value was supplied for an input parameter .
* @ throws ServiceFailureException
* The request processing has failed because of an unknown error , exception or failure .
* @ sample AmazonIdentityManagement . GetServiceLinkedRoleDeletionStatus
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / iam - 2010-05-08 / GetServiceLinkedRoleDeletionStatus "
* target = " _ top " > AWS API Documentation < / a > */
@ Override public GetServiceLinkedRoleDeletionStatusResult getServiceLinkedRoleDeletionStatus ( GetServiceLinkedRoleDeletionStatusRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeGetServiceLinkedRoleDeletionStatus ( request ) ; |
public class SortedProperties { /** * To be compatible with version control systems , we need to sort properties
* before storing them to disk . Otherwise each change may lead to problems
* by diff against previous version - because Property entries are randomly
* distributed ( it ' s a map ) .
* @ param keySet
* non null set instance to sort
* @ return non null list which contains all given keys , sorted
* lexicographically . The list may be empty if given set was empty */
static public Enumeration < ? > sortKeys ( Set < String > keySet ) { } } | List < String > sortedList = new ArrayList < > ( ) ; sortedList . addAll ( keySet ) ; Collections . sort ( sortedList ) ; return Collections . enumeration ( sortedList ) ; |
public class TermsByQueryShardResponse { /** * Deserialize */
@ Override public void readFrom ( StreamInput in ) throws IOException { } } | super . readFrom ( in ) ; TermsByQueryRequest . TermsEncoding termsEncoding = TermsByQueryRequest . TermsEncoding . values ( ) [ in . readVInt ( ) ] ; switch ( termsEncoding ) { case LONG : termsSet = new LongTermsSet ( breaker ) ; termsSet . readFrom ( in ) ; return ; case INTEGER : termsSet = new IntegerTermsSet ( breaker ) ; termsSet . readFrom ( in ) ; return ; case BLOOM : termsSet = new BloomFilterTermsSet ( breaker ) ; termsSet . readFrom ( in ) ; return ; case BYTES : termsSet = new BytesRefTermsSet ( breaker ) ; termsSet . readFrom ( in ) ; return ; default : throw new IOException ( "[termsByQuery] Invalid type of terms encoding: " + termsEncoding . name ( ) ) ; } |
public class DynamicReportBuilder { /** * Set a colspan in a group of columns . First add the cols to the report
* @ param colNumber the index of the col
* @ param colQuantity the number of cols how i will take
* @ param colspanTitle colspan title
* @ return a Dynamic Report Builder
* @ throws ColumnBuilderException When the index of the cols is out of
* bounds . */
public DynamicReportBuilder setColspan ( int colNumber , int colQuantity , String colspanTitle ) { } } | this . setColspan ( colNumber , colQuantity , colspanTitle , null ) ; return this ; |
public class BplusTree { /** * Return the first / low or last / high LeafNode in the Tree
* @ param lowORhigh true first / low node , false last / high node
* @ return the LeafNoder head / first / lower or tail / last / higher */
private final LeafNode < K , V > findSideLeafNode ( final boolean lowORhigh ) { } } | if ( _isEmpty ( ) ) { return null ; } try { int nodeIdx = ( lowORhigh ? lowIdx : highIdx ) ; // rootIdx ;
Node < K , V > nodeFind = getNode ( ( nodeIdx == 0 ) ? rootIdx : nodeIdx ) ; while ( ! nodeFind . isLeaf ( ) ) { nodeIdx = ( ( InternalNode < K , V > ) nodeFind ) . childs [ ( lowORhigh ? 0 : nodeFind . allocated ) ] ; nodeFind = getNode ( nodeIdx ) ; } return ( nodeFind . isLeaf ( ) ? ( LeafNode < K , V > ) nodeFind : null ) ; } finally { releaseNodes ( ) ; } |
public class JbcSrcRuntime { /** * Helper function to translate null - > NullData when calling SoyJavaPrintDirectives that may
* expect it . */
public static SoyValue applyPrintDirective ( SoyJavaPrintDirective directive , SoyValue value , List < SoyValue > args ) { } } | value = value == null ? NullData . INSTANCE : value ; for ( int i = 0 ; i < args . size ( ) ; i ++ ) { if ( args . get ( i ) == null ) { args . set ( i , NullData . INSTANCE ) ; } } return directive . applyForJava ( value , args ) ; |
public class CssScanner { /** * Check if a forward scan will equal given match string
* @ param match The string to match
* @ param ignoreCase Whether case should be ignored
* @ param resetOnTrue Whether the reader should be reset on found match
* @ throws IOException */
private boolean forwardMatch ( String match , boolean ignoreCase , boolean resetOnTrue ) throws IOException { } } | Mark mark = reader . mark ( ) ; List < Integer > cbuf = Lists . newArrayList ( ) ; StringBuilder builder = new StringBuilder ( ) ; boolean result = true ; boolean seenChar = false ; while ( true ) { cbuf . add ( reader . next ( ) ) ; char ch = ( char ) reader . curChar ; if ( reader . curChar == - 1 ) { result = false ; break ; } else if ( WHITESPACE . matches ( ch ) ) { if ( seenChar ) { builder . append ( ch ) ; } } else { if ( builder . length ( ) == 0 ) { seenChar = true ; } builder . append ( ch ) ; int index = builder . length ( ) - 1 ; if ( ! ignoreCase && ( builder . charAt ( index ) == match . charAt ( index ) ) ) { result = false ; break ; } if ( ignoreCase && ( Ascii . toLowerCase ( builder . charAt ( index ) ) != Ascii . toLowerCase ( match . charAt ( index ) ) ) ) { result = false ; break ; } } if ( builder . length ( ) == match . length ( ) ) { if ( ! match . equalsIgnoreCase ( builder . toString ( ) ) ) { result = false ; } break ; } } if ( ! result || resetOnTrue ) { reader . unread ( cbuf , mark ) ; } return result ; |
public class QueryParserBase { /** * Create the plain query string representation of the given node using mapping information derived from the domain
* type .
* @ param node
* @ param domainType can be { @ literal null } .
* @ return
* @ since 4.0 */
public String createQueryStringFromNode ( Node node , @ Nullable Class < ? > domainType ) { } } | return createQueryStringFromNode ( node , 0 , domainType ) ; |
public class DualPivotQuicksort { /** * Sorts the specified range of the array using the given
* workspace array slice if possible for merging
* @ param a the array to be sorted
* @ param left the index of the first element , inclusive , to be sorted
* @ param right the index of the last element , inclusive , to be sorted
* @ param work a workspace array ( slice )
* @ param workBase origin of usable space in work array
* @ param workLen usable size of work array */
static void sort ( double [ ] a , int left , int right , double [ ] work , int workBase , int workLen ) { } } | /* * Phase 1 : Move NaNs to the end of the array . */
while ( left <= right && Double . isNaN ( a [ right ] ) ) { -- right ; } for ( int k = right ; -- k >= left ; ) { double ak = a [ k ] ; if ( ak != ak ) { // a [ k ] is NaN
a [ k ] = a [ right ] ; a [ right ] = ak ; -- right ; } } /* * Phase 2 : Sort everything except NaNs ( which are already in place ) . */
doSort ( a , left , right , work , workBase , workLen ) ; /* * Phase 3 : Place negative zeros before positive zeros . */
int hi = right ; /* * Find the first zero , or first positive , or last negative element . */
while ( left < hi ) { int middle = ( left + hi ) >>> 1 ; double middleValue = a [ middle ] ; if ( middleValue < 0.0d ) { left = middle + 1 ; } else { hi = middle ; } } /* * Skip the last negative value ( if any ) or all leading negative zeros . */
while ( left <= right && Double . doubleToRawLongBits ( a [ left ] ) < 0 ) { ++ left ; } /* * Move negative zeros to the beginning of the sub - range .
* Partitioning :
* | < 0.0 | - 0.0 | 0.0 | ? ( > = 0.0 ) |
* left p k
* Invariants :
* all in ( * , left ) < 0.0
* all in [ left , p ) = = - 0.0
* all in [ p , k ) = = 0.0
* all in [ k , right ] > = 0.0
* Pointer k is the first index of ? - part . */
for ( int k = left , p = left - 1 ; ++ k <= right ; ) { double ak = a [ k ] ; if ( ak != 0.0d ) { break ; } if ( Double . doubleToRawLongBits ( ak ) < 0 ) { // ak is - 0.0d
a [ k ] = 0.0d ; a [ ++ p ] = - 0.0d ; } } |
public class SiteNode { /** * Tells whether or not the given alert is the alert with highest risk than the current highest alert .
* { @ link Alert # CONFIDENCE _ FALSE _ POSITIVE False positive alerts } are ignored .
* @ param alert the alert to check
* @ return { @ code true } if it ' s the alert with highest risk , { @ code false } otherwise . */
private boolean isHighestAlert ( Alert alert ) { } } | if ( alert . getConfidence ( ) == Alert . CONFIDENCE_FALSE_POSITIVE ) { return false ; } if ( highestAlert == null ) { return true ; } return alert . getRisk ( ) > highestAlert . getRisk ( ) ; |
public class ShellFactory { /** * Facade method facilitating the creation of subshell .
* Subshell is created and run inside Command method and shares the same IO and naming strtategy .
* Run the obtained Shell with commandLoop ( ) .
* @ param pathElement sub - prompt
* @ param parent Shell to be subshell ' d
* @ param appName The app name string
* @ param mainHandler Command handler
* @ return subshell */
public static Shell createSubshell ( String pathElement , Shell parent , String appName , Object mainHandler ) { } } | return createSubshell ( pathElement , parent , appName , mainHandler , new EmptyMultiMap < String , Object > ( ) ) ; |
public class AuditReaderTask { /** * Convert the properties for encoding from the command line parameters . */
protected Map < String , String > convertToProperties ( Map < String , String > argMap ) { } } | HashMap < String , String > props = new HashMap < String , String > ( ) ; String value = argMap . get ( ARG_AUDIT_FILE_LOCATION ) ; if ( value != null ) { props . put ( "auditFileLocation" , value ) ; } value = argMap . get ( ARG_OUTPUT_FILE_LOCATION ) ; if ( value != null ) { props . put ( "outputFileLocation" , value ) ; } value = argMap . get ( ARG_ENCRYPTED ) ; if ( value != null ) { props . put ( "encrypted" , value ) ; } value = argMap . get ( ARG_SIGNED ) ; if ( value != null ) { props . put ( "signed" , value ) ; } value = argMap . get ( ARG_ENCRYPTION_KEYSTORE_LOCATION ) ; if ( value != null ) { props . put ( "encKeyStoreLocation" , value ) ; } value = argMap . get ( ARG_ENCRYPTION_KEYSTORE_PASSWORD ) ; if ( value != null ) { props . put ( "encKeyStorePassword" , value ) ; } value = argMap . get ( ARG_SIGNING_KEYSTORE_LOCATION ) ; if ( value != null ) { props . put ( "signingKeyStoreLocation" , value ) ; } value = argMap . get ( ARG_SIGNING_KEYSTORE_PASSWORD ) ; if ( value != null ) { props . put ( "signingKeyStorePassword" , value ) ; } value = argMap . get ( ARG_ENCRYPTION_KEYSTORE_TYPE ) ; if ( value != null ) { props . put ( "encKeyStoreType" , value ) ; } value = argMap . get ( ARG_SIGNING_KEYSTORE_TYPE ) ; if ( value != null ) { props . put ( "signingKeyStoreType" , value ) ; } value = argMap . get ( DEBUG ) ; if ( value != null ) { props . put ( "debug" , value ) ; if ( value . equals ( "true" ) ) isDebug = true ; else isDebug = false ; } else { props . put ( "debug" , "false" ) ; isDebug = false ; } return props ; |
public class MeterRegistry { /** * Measures the distribution of samples .
* @ param name The base metric name
* @ param tags MUST be an even number of arguments representing key / value pairs of tags .
* @ return A new or existing distribution summary . */
public DistributionSummary summary ( String name , String ... tags ) { } } | return summary ( name , Tags . of ( tags ) ) ; |
public class FrameScreen { /** * Utility to get the sub - screen ( applet ) .
* @ return The applet ( sub ) screen . */
public AppletScreen getAppletScreen ( ) { } } | AppletScreen appletScreen = null ; if ( this . getSFieldCount ( ) > 0 ) appletScreen = ( AppletScreen ) this . getSField ( 0 ) ; return appletScreen ; |
public class DefaultThemeController { /** * ( non - Javadoc )
* @ see fr . putnami . pwt . core . theme . client . ThemeController # installTheme (
* fr . putnami . pwt . core . theme . client * . Theme ) */
@ Override public void installTheme ( Theme theme ) { } } | this . removeCssLinks ( ) ; if ( this . currentTheme != null ) { for ( CssLink link : this . currentTheme . getLinks ( ) ) { link . getLink ( ) . removeFromParent ( ) ; } } this . currentTheme = theme ; this . resetTheme ( ) ; |
public class ListUtils { /** * Obtains a random sample without replacement from a source list and places
* it in the destination list . This is done without modifying the source list .
* @ param < T > the list content type involved
* @ param source the source of values to randomly sample from
* @ param dest the list to store the random samples in . The list does not
* need to be empty for the sampling to work correctly
* @ param samples the number of samples to select from the source
* @ param rand the source of randomness for the sampling
* @ throws IllegalArgumentException if the sample size is not positive or l
* arger than the source population . */
public static < T > void randomSample ( List < T > source , List < T > dest , int samples , Random rand ) { } } | randomSample ( ( Collection < T > ) source , dest , samples , rand ) ; |
public class MessageFormat { /** * Both arguments cannot be null . */
private Format createAppropriateFormat ( String type , String style ) { } } | Format newFormat = null ; int subformatType = findKeyword ( type , typeList ) ; switch ( subformatType ) { case TYPE_NUMBER : switch ( findKeyword ( style , modifierList ) ) { case MODIFIER_EMPTY : newFormat = NumberFormat . getInstance ( ulocale ) ; break ; case MODIFIER_CURRENCY : newFormat = NumberFormat . getCurrencyInstance ( ulocale ) ; break ; case MODIFIER_PERCENT : newFormat = NumberFormat . getPercentInstance ( ulocale ) ; break ; case MODIFIER_INTEGER : newFormat = NumberFormat . getIntegerInstance ( ulocale ) ; break ; default : // pattern
newFormat = new DecimalFormat ( style , new DecimalFormatSymbols ( ulocale ) ) ; break ; } break ; case TYPE_DATE : switch ( findKeyword ( style , dateModifierList ) ) { case DATE_MODIFIER_EMPTY : newFormat = DateFormat . getDateInstance ( DateFormat . DEFAULT , ulocale ) ; break ; case DATE_MODIFIER_SHORT : newFormat = DateFormat . getDateInstance ( DateFormat . SHORT , ulocale ) ; break ; case DATE_MODIFIER_MEDIUM : newFormat = DateFormat . getDateInstance ( DateFormat . DEFAULT , ulocale ) ; break ; case DATE_MODIFIER_LONG : newFormat = DateFormat . getDateInstance ( DateFormat . LONG , ulocale ) ; break ; case DATE_MODIFIER_FULL : newFormat = DateFormat . getDateInstance ( DateFormat . FULL , ulocale ) ; break ; default : newFormat = new SimpleDateFormat ( style , ulocale ) ; break ; } break ; case TYPE_TIME : switch ( findKeyword ( style , dateModifierList ) ) { case DATE_MODIFIER_EMPTY : newFormat = DateFormat . getTimeInstance ( DateFormat . DEFAULT , ulocale ) ; break ; case DATE_MODIFIER_SHORT : newFormat = DateFormat . getTimeInstance ( DateFormat . SHORT , ulocale ) ; break ; case DATE_MODIFIER_MEDIUM : newFormat = DateFormat . getTimeInstance ( DateFormat . DEFAULT , ulocale ) ; break ; case DATE_MODIFIER_LONG : newFormat = DateFormat . getTimeInstance ( DateFormat . LONG , ulocale ) ; break ; case DATE_MODIFIER_FULL : newFormat = DateFormat . getTimeInstance ( DateFormat . FULL , ulocale ) ; break ; default : newFormat = new SimpleDateFormat ( style , ulocale ) ; break ; } break ; case TYPE_SPELLOUT : { RuleBasedNumberFormat rbnf = new RuleBasedNumberFormat ( ulocale , RuleBasedNumberFormat . SPELLOUT ) ; String ruleset = style . trim ( ) ; if ( ruleset . length ( ) != 0 ) { try { rbnf . setDefaultRuleSet ( ruleset ) ; } catch ( Exception e ) { // warn invalid ruleset
} } newFormat = rbnf ; } break ; case TYPE_ORDINAL : { RuleBasedNumberFormat rbnf = new RuleBasedNumberFormat ( ulocale , RuleBasedNumberFormat . ORDINAL ) ; String ruleset = style . trim ( ) ; if ( ruleset . length ( ) != 0 ) { try { rbnf . setDefaultRuleSet ( ruleset ) ; } catch ( Exception e ) { // warn invalid ruleset
} } newFormat = rbnf ; } break ; case TYPE_DURATION : { RuleBasedNumberFormat rbnf = new RuleBasedNumberFormat ( ulocale , RuleBasedNumberFormat . DURATION ) ; String ruleset = style . trim ( ) ; if ( ruleset . length ( ) != 0 ) { try { rbnf . setDefaultRuleSet ( ruleset ) ; } catch ( Exception e ) { // warn invalid ruleset
} } newFormat = rbnf ; } break ; default : throw new IllegalArgumentException ( "Unknown format type \"" + type + "\"" ) ; } return newFormat ; |
public class CommerceDiscountUserSegmentRelPersistenceImpl { /** * Returns an ordered range of all the commerce discount user segment rels where commerceUserSegmentEntryId = & # 63 ; .
* Useful when paginating results . Returns a maximum of < code > end - start < / code > instances . < code > start < / code > and < code > end < / code > are not primary keys , they are indexes in the result set . Thus , < code > 0 < / code > refers to the first result in the set . Setting both < code > start < / code > and < code > end < / code > to { @ link QueryUtil # ALL _ POS } will return the full result set . If < code > orderByComparator < / code > is specified , then the query will include the given ORDER BY logic . If < code > orderByComparator < / code > is absent and pagination is required ( < code > start < / code > and < code > end < / code > are not { @ link QueryUtil # ALL _ POS } ) , then the query will include the default ORDER BY logic from { @ link CommerceDiscountUserSegmentRelModelImpl } . If both < code > orderByComparator < / code > and pagination are absent , for performance reasons , the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order .
* @ param commerceUserSegmentEntryId the commerce user segment entry ID
* @ param start the lower bound of the range of commerce discount user segment rels
* @ param end the upper bound of the range of commerce discount user segment rels ( not inclusive )
* @ param orderByComparator the comparator to order the results by ( optionally < code > null < / code > )
* @ return the ordered range of matching commerce discount user segment rels */
@ Override public List < CommerceDiscountUserSegmentRel > findByCommerceUserSegmentEntryId ( long commerceUserSegmentEntryId , int start , int end , OrderByComparator < CommerceDiscountUserSegmentRel > orderByComparator ) { } } | return findByCommerceUserSegmentEntryId ( commerceUserSegmentEntryId , start , end , orderByComparator , true ) ; |
public class ObjNameFlagRight { /** * { @ inheritDoc } */
@ Override public void infoSeeFromEast ( ControllerPlayer c , double distance , double direction , double distChange , double dirChange , double bodyFacingDirection , double headFacingDirection ) { } } | switch ( qualifier ) { case 't' : switch ( number ) { case 30 : c . infoSeeFlagOwn ( Flag . RIGHT_30 , distance , direction , distChange , dirChange , bodyFacingDirection , headFacingDirection ) ; break ; case 20 : c . infoSeeFlagOwn ( Flag . RIGHT_20 , distance , direction , distChange , dirChange , bodyFacingDirection , headFacingDirection ) ; break ; case 10 : c . infoSeeFlagOwn ( Flag . RIGHT_10 , distance , direction , distChange , dirChange , bodyFacingDirection , headFacingDirection ) ; break ; } ; break ; case 'b' : switch ( number ) { case 30 : c . infoSeeFlagOwn ( Flag . LEFT_30 , distance , direction , distChange , dirChange , bodyFacingDirection , headFacingDirection ) ; break ; case 20 : c . infoSeeFlagOwn ( Flag . LEFT_20 , distance , direction , distChange , dirChange , bodyFacingDirection , headFacingDirection ) ; break ; case 10 : c . infoSeeFlagOwn ( Flag . LEFT_10 , distance , direction , distChange , dirChange , bodyFacingDirection , headFacingDirection ) ; break ; } ; break ; case '0' : c . infoSeeFlagOwn ( Flag . CENTER , distance , direction , distChange , dirChange , bodyFacingDirection , headFacingDirection ) ; break ; } |
public class RemoveAliasCommand { /** * Remove an alias from a LIST ModelNode of existing aliases .
* @ param list LIST ModelNode of aliases
* @ param alias
* @ return LIST ModelNode with the alias removed */
private ModelNode removeAliasFromList ( ModelNode list , String alias ) throws OperationFailedException { } } | // check for empty string
if ( alias == null || alias . equals ( "" ) ) return list ; // check for undefined list ( AS7-3476)
if ( ! list . isDefined ( ) ) { throw InfinispanMessages . MESSAGES . cannotRemoveAliasFromEmptyList ( alias ) ; } ModelNode newList = new ModelNode ( ) ; List < ModelNode > listElements = list . asList ( ) ; for ( ModelNode listElement : listElements ) { if ( ! listElement . asString ( ) . equals ( alias ) ) { newList . add ( ) . set ( listElement ) ; } } return newList ; |
public class AbstractResources { /** * Post an object to Smartsheet REST API and receive a CopyOrMoveRowResult object from response .
* Parameters : - path : the relative path of the resource collections - objectToPost : the object to post -
* Returns : the object
* Exceptions :
* IllegalArgumentException : if any argument is null , or path is empty string
* InvalidRequestException : if there is any problem with the REST API request
* AuthorizationException : if there is any problem with the REST API authorization ( access token )
* ServiceUnavailableException : if the REST API service is not available ( possibly due to rate limiting )
* SmartsheetRestException : if there is any other REST API related error occurred during the operation
* SmartsheetException : if there is any other error occurred during the operation
* @ param path the path
* @ param objectToPost the object to post
* @ return the result object
* @ throws SmartsheetException the smartsheet exception */
protected CopyOrMoveRowResult postAndReceiveRowObject ( String path , CopyOrMoveRowDirective objectToPost ) throws SmartsheetException { } } | Util . throwIfNull ( path , objectToPost ) ; Util . throwIfEmpty ( path ) ; HttpRequest request = createHttpRequest ( smartsheet . getBaseURI ( ) . resolve ( path ) , HttpMethod . POST ) ; ByteArrayOutputStream objectBytesStream = new ByteArrayOutputStream ( ) ; this . smartsheet . getJsonSerializer ( ) . serialize ( objectToPost , objectBytesStream ) ; HttpEntity entity = new HttpEntity ( ) ; entity . setContentType ( "application/json" ) ; entity . setContent ( new ByteArrayInputStream ( objectBytesStream . toByteArray ( ) ) ) ; entity . setContentLength ( objectBytesStream . size ( ) ) ; request . setEntity ( entity ) ; CopyOrMoveRowResult obj = null ; try { HttpResponse response = this . smartsheet . getHttpClient ( ) . request ( request ) ; switch ( response . getStatusCode ( ) ) { case 200 : obj = this . smartsheet . getJsonSerializer ( ) . deserializeCopyOrMoveRow ( response . getEntity ( ) . getContent ( ) ) ; break ; default : handleError ( response ) ; } } finally { smartsheet . getHttpClient ( ) . releaseConnection ( ) ; } return obj ; |
public class CommerceOrderItemPersistenceImpl { /** * Removes all the commerce order items where commerceOrderId = & # 63 ; and CPInstanceId = & # 63 ; from the database .
* @ param commerceOrderId the commerce order ID
* @ param CPInstanceId the cp instance ID */
@ Override public void removeByC_I ( long commerceOrderId , long CPInstanceId ) { } } | for ( CommerceOrderItem commerceOrderItem : findByC_I ( commerceOrderId , CPInstanceId , QueryUtil . ALL_POS , QueryUtil . ALL_POS , null ) ) { remove ( commerceOrderItem ) ; } |
public class FilterBasedTriggeringPolicy { /** * { @ inheritDoc } */
public boolean isTriggeringEvent ( final Appender appender , final LoggingEvent event , final String file , final long fileLength ) { } } | return isTriggeringEvent ( event ) ; |
public class ValoSideBar { /** * Adds a logo to the very top of the side bar , above the header . The logo ' s primary style is automatically
* set to { @ link ValoTheme # MENU _ LOGO } ands its size to undefined .
* @ param logo a { @ link com . vaadin . ui . Label } or { @ link com . vaadin . ui . Button } to use as the logo , or { @ code null } to remove the logo completely . */
public void setLogo ( Component logo ) { } } | if ( getCompositionRoot ( ) != null && this . logo != null ) { getCompositionRoot ( ) . removeComponent ( this . logo ) ; } this . logo = logo ; if ( logo != null ) { logo . setPrimaryStyleName ( ValoTheme . MENU_LOGO ) ; logo . setSizeUndefined ( ) ; if ( getCompositionRoot ( ) != null ) { getCompositionRoot ( ) . addComponentAsFirst ( logo ) ; } } |
public class DukeController { /** * Runs the record linkage process . */
public void process ( ) { } } | // are we ready to process yet , or have we had an error , and are
// waiting a bit longer in the hope that it will resolve itself ?
if ( error_skips > 0 ) { error_skips -- ; return ; } try { if ( logger != null ) logger . debug ( "Starting processing" ) ; status = "Processing" ; lastCheck = System . currentTimeMillis ( ) ; // FIXME : how to break off processing if we don ' t want to keep going ?
processor . deduplicate ( batch_size ) ; status = "Sleeping" ; if ( logger != null ) logger . debug ( "Finished processing" ) ; } catch ( Throwable e ) { status = "Thread blocked on error: " + e ; if ( logger != null ) logger . error ( "Error in processing; waiting" , e ) ; error_skips = error_factor ; } |
public class AbstractTemplateEngine { /** * Performs common initialization for template engines .
* Implementations must override this method to do their own template engine specific initialization .
* To use the convenience of this class , implementations must invoke this class ' s implementation before
* performing their own initialization .
* @ param application reference to the Pippo { @ link Application } that can be used to retrieve settings
* and other settings for the initialization */
@ Override public void init ( Application application ) { } } | languages = application . getLanguages ( ) ; messages = application . getMessages ( ) ; router = application . getRouter ( ) ; pippoSettings = application . getPippoSettings ( ) ; fileExtension = pippoSettings . getString ( PippoConstants . SETTING_TEMPLATE_EXTENSION , getDefaultFileExtension ( ) ) ; templatePathPrefix = pippoSettings . getString ( PippoConstants . SETTING_TEMPLATE_PATH_PREFIX , TemplateEngine . DEFAULT_PATH_PREFIX ) ; |
public class OWLClassImpl_CustomFieldSerializer { /** * Deserializes the content of the object from the
* { @ link com . google . gwt . user . client . rpc . SerializationStreamReader } .
* @ param streamReader the { @ link com . google . gwt . user . client . rpc . SerializationStreamReader } to read the
* object ' s content from
* @ param instance the object instance to deserialize
* @ throws com . google . gwt . user . client . rpc . SerializationException
* if the deserialization operation is not
* successful */
@ Override public void deserializeInstance ( SerializationStreamReader streamReader , OWLClass instance ) throws SerializationException { } } | deserialize ( streamReader , instance ) ; |
public class Word2Vec { /** * This method defines TokenizerFactory instance to be using during model building
* @ param tokenizerFactory TokenizerFactory instance */
public void setTokenizerFactory ( @ NonNull TokenizerFactory tokenizerFactory ) { } } | this . tokenizerFactory = tokenizerFactory ; if ( sentenceIter != null ) { SentenceTransformer transformer = new SentenceTransformer . Builder ( ) . iterator ( sentenceIter ) . tokenizerFactory ( this . tokenizerFactory ) . build ( ) ; this . iterator = new AbstractSequenceIterator . Builder < > ( transformer ) . build ( ) ; } |
public class SnorocketReasoner { /** * Prints a concept given its internal id . Useful for debugging .
* @ param id
* @ return */
protected String printConcept ( int id ) { } } | Object oid = factory . lookupConceptId ( id ) ; if ( factory . isVirtualConcept ( id ) ) { if ( oid instanceof AbstractConcept ) { return printAbstractConcept ( ( AbstractConcept ) oid ) ; } else { return oid . toString ( ) ; } } else { return ( String ) oid ; } |
public class AlertPolicyService { /** * Returns the set of alert policies with the given name .
* @ param name The name of the alert policy to return
* @ return The set of alert policies */
public Collection < AlertPolicy > list ( String name ) { } } | return list ( filters ( ) . name ( name ) . build ( ) ) ; |
public class Enum { /** * Returns a list of all enum constant names . */
public Set < String > getConstantNames ( ) { } } | return constants . stream ( ) . map ( EnumConstant :: getName ) . collect ( Collectors . toSet ( ) ) ; |
public class MessageBuilder { /** * 构建rpc错误结果
* @ param errorMsg 错误消息
* @ return rpc结果 */
public static SofaResponse buildSofaErrorResponse ( String errorMsg ) { } } | SofaResponse sofaResponse = new SofaResponse ( ) ; sofaResponse . setErrorMsg ( errorMsg ) ; return sofaResponse ; |
public class JobMetrics { /** * Get a new { @ link GobblinMetrics } instance for a given job .
* @ param jobName job name
* @ param jobId job ID
* @ return a new { @ link GobblinMetrics } instance for the given job */
public static JobMetrics get ( String jobName , String jobId ) { } } | return get ( new JobState ( jobName , jobId ) ) ; |
public class ImmutableRoaringBitmap { /** * Checks whether the parameter is a subset of this RoaringBitmap or not
* @ param subset the potential subset
* @ return true if the parameter is a subset of this RoaringBitmap */
public boolean contains ( ImmutableRoaringBitmap subset ) { } } | if ( subset . getCardinality ( ) > getCardinality ( ) ) { return false ; } final int length1 = this . highLowContainer . size ( ) ; final int length2 = subset . highLowContainer . size ( ) ; int pos1 = 0 , pos2 = 0 ; while ( pos1 < length1 && pos2 < length2 ) { final short s1 = this . highLowContainer . getKeyAtIndex ( pos1 ) ; final short s2 = subset . highLowContainer . getKeyAtIndex ( pos2 ) ; if ( s1 == s2 ) { MappeableContainer c1 = this . highLowContainer . getContainerAtIndex ( pos1 ) ; MappeableContainer c2 = subset . highLowContainer . getContainerAtIndex ( pos2 ) ; if ( ! c1 . contains ( c2 ) ) { return false ; } ++ pos1 ; ++ pos2 ; } else if ( compareUnsigned ( s1 , s2 ) > 0 ) { return false ; } else { pos1 = subset . highLowContainer . advanceUntil ( s2 , pos1 ) ; } } return pos2 == length2 ; |
public class FileIndex { /** * Reads index from input stream .
* @ param stream input stream
* @ return { @ code FileIndex }
* @ throws IOException */
public static FileIndex read ( InputStream stream ) throws IOException { } } | // Creating raw input stream
DataInputStream raw = new DataInputStream ( stream ) ; // Reading magic number
int magic = raw . readInt ( ) ; if ( magic != MAGIC ) throw new IOException ( "Wrong magic number" ) ; // Reading length
int length = raw . readInt ( ) ; // Reading whole index
byte [ ] buffer = new byte [ length ] ; raw . read ( buffer ) ; // Creating uncompressed stream
InflaterInputStream inflater = new InflaterInputStream ( new ByteArrayInputStream ( buffer ) ) ; DataInputStream dataStream = new DataInputStream ( inflater ) ; // Reading step
long step = dataStream . readLong ( ) ; long startingRecordNumner = dataStream . readLong ( ) ; long lastRecordNumber = dataStream . readLong ( ) ; // Reading meta record count
int metaRecordsCount = dataStream . readInt ( ) ; // Reading meta records
Map < String , String > metadata = new HashMap < > ( ) ; String key , value ; while ( -- metaRecordsCount >= 0 ) { key = dataStream . readUTF ( ) ; value = dataStream . readUTF ( ) ; metadata . put ( key , value ) ; } // Reading entries number
int size = dataStream . readInt ( ) ; // Creating array for index
TLongArrayList index = new TLongArrayList ( size ) ; // Reading index
long last = 0 , val ; for ( int i = 0 ; i < size ; ++ i ) { val = IOUtil . readRawVarint64 ( dataStream , - 1 ) ; if ( val == - 1 ) throw new IOException ( "Wrong file format" ) ; last += val ; index . add ( last ) ; } return new FileIndex ( step , metadata , index , startingRecordNumner , lastRecordNumber ) ; |
public class TypeMapper { /** * only for change appenders */
public MapContentType getMapContentType ( ContainerType containerType ) { } } | JaversType keyType = getJaversType ( Integer . class ) ; JaversType valueType = getJaversType ( containerType . getItemType ( ) ) ; return new MapContentType ( keyType , valueType ) ; |
public class ExtensionController { /** * Gets the list of extensions . */
@ RequestMapping ( value = "" , method = RequestMethod . GET ) public Resource < ExtensionList > getExtensions ( ) { } } | return Resource . of ( extensionManager . getExtensionList ( ) , uri ( MvcUriComponentsBuilder . on ( getClass ( ) ) . getExtensions ( ) ) ) ; |
public class PersistenceUnitMetadata { /** * Sets the jar files .
* @ param jarFiles
* the new jar files */
public void addJarFile ( String jarFile ) { } } | if ( jarFiles == null ) { jarFiles = new HashSet < String > ( ) ; } this . jarFiles . add ( jarFile ) ; addJarFileUrl ( jarFile ) ; |
public class _SharedRendererUtils { /** * Gets a Class object from a given component attribute . The attribute can
* be a ValueExpression ( that evaluates to a String or a Class ) or a
* String ( that is a fully qualified Java class name ) or a Class object .
* @ param facesContext
* @ param attribute
* @ return
* @ throws FacesException if the value is a String and the represented
* class cannot be found */
static Class < ? > getClassFromAttribute ( FacesContext facesContext , Object attribute ) throws FacesException { } } | // Attention !
// This code is duplicated in shared renderkit package .
// If you change something here please do the same in the other class !
Class < ? > type = null ; // if there is a value , it must be a . . .
// . . . a ValueExpression that evaluates to a String or a Class
if ( attribute instanceof ValueExpression ) { // get the value of the ValueExpression
attribute = ( ( ValueExpression ) attribute ) . getValue ( facesContext . getELContext ( ) ) ; } // . . . String that is a fully qualified Java class name
if ( attribute instanceof String ) { try { type = Class . forName ( ( String ) attribute ) ; } catch ( ClassNotFoundException cnfe ) { throw new FacesException ( "Unable to find class " + attribute + " on the classpath." , cnfe ) ; } } // . . . a Class object
else if ( attribute instanceof Class ) { type = ( Class < ? > ) attribute ; } return type ; |
public class SslRefInfoImpl { /** * { @ inheritDoc } */
@ FFDCIgnore ( { } } | SocialLoginException . class } ) @ Override public PublicKey getPublicKey ( ) throws SocialLoginException { if ( this . jsseHelper == null ) { init ( ) ; } if ( sslKeyStoreName != null ) { if ( keyAliasName != null && keyAliasName . trim ( ) . isEmpty ( ) == false ) { KeyStoreService keyStoreService = keyStoreServiceRef . getService ( ) ; if ( keyStoreService == null ) { throw new SocialLoginException ( "KEYSTORE_SERVICE_NOT_FOUND" , null , new Object [ 0 ] ) ; } // TODO : Determine if the first public key should be used if a public key is not found for the key alias .
try { return keyStoreService . getCertificateFromKeyStore ( sslKeyStoreName , keyAliasName ) . getPublicKey ( ) ; } catch ( GeneralSecurityException e ) { throw new SocialLoginException ( "ERROR_LOADING_CERTIFICATE" , e , new Object [ ] { keyAliasName , sslTrustStoreName , e . getLocalizedMessage ( ) } ) ; } } else { Iterator < Entry < String , PublicKey > > publicKeysIterator = null ; try { // Get first public key
publicKeysIterator = getPublicKeys ( ) . entrySet ( ) . iterator ( ) ; } catch ( SocialLoginException e ) { throw new SocialLoginException ( "ERROR_LOADING_GETTING_PUBLIC_KEYS" , e , new Object [ ] { keyAliasName , sslTrustStoreName , e . getLocalizedMessage ( ) } ) ; } if ( publicKeysIterator . hasNext ( ) ) { return publicKeysIterator . next ( ) . getValue ( ) ; } } } return null ; |
public class SelectListUtil { /** * Check for legacy matching , which supported setSelected using String representations .
* @ param option the option to test for a match
* @ param data the test data value
* @ return true if the option is a legacy match
* @ deprecated Support for legacy matching will be removed */
@ Deprecated private static boolean isLegacyMatch ( final Object option , final Object data ) { } } | // Support legacy matching , which supported setSelected using String representations . . .
String optionAsString = String . valueOf ( option ) ; String matchAsString = String . valueOf ( data ) ; boolean equal = Util . equals ( optionAsString , matchAsString ) ; return equal ; |
public class JKServerDownException { /** * ( non - Javadoc )
* @ see java . lang . Throwable # getMessage ( ) */
@ Override public String getMessage ( ) { } } | if ( getCause ( ) instanceof UnknownHostException ) { return "Host (" + getHost ( ) + ") is unreachable !!!!" ; } if ( getCause ( ) instanceof ConnectException ) { return "Host (" + getHost ( ) + ") is unreachable at Port (" + getPort ( ) + ")!!!!" ; } return getCause ( ) . getMessage ( ) ; |
public class MsgCompiler { /** * Handles a complex message with placeholders . */
private Statement handleTranslationWithPlaceholders ( MsgNode msg , ImmutableList < SoyPrintDirective > escapingDirectives , Expression soyMsgParts , Expression locale , MsgPartsAndIds partsAndId ) { } } | // We need to render placeholders into a buffer and then pack them into a map to pass to
// Runtime . renderSoyMsgWithPlaceholders .
Map < String , Function < Expression , Statement > > placeholderNameToPutStatement = new LinkedHashMap < > ( ) ; putPlaceholdersIntoMap ( msg , partsAndId . parts , placeholderNameToPutStatement ) ; // sanity check
checkState ( ! placeholderNameToPutStatement . isEmpty ( ) ) ; ConstructorRef cstruct = msg . isPlrselMsg ( ) ? ConstructorRef . PLRSEL_MSG_RENDERER : ConstructorRef . MSG_RENDERER ; Statement initRendererStatement = variables . getCurrentRenderee ( ) . putInstanceField ( thisVar , cstruct . construct ( constant ( partsAndId . id ) , soyMsgParts , locale , constant ( placeholderNameToPutStatement . size ( ) ) ) ) ; List < Statement > initializationStatements = new ArrayList < > ( ) ; initializationStatements . add ( initRendererStatement ) ; for ( Function < Expression , Statement > fn : placeholderNameToPutStatement . values ( ) ) { initializationStatements . add ( fn . apply ( variables . getCurrentRenderee ( ) . accessor ( thisVar ) ) ) ; } Statement initMsgRenderer = Statement . concat ( initializationStatements ) ; Statement render ; if ( areAllPrintDirectivesStreamable ( escapingDirectives ) ) { AppendableAndOptions wrappedAppendable = applyStreamingEscapingDirectives ( escapingDirectives , appendableExpression , parameterLookup . getPluginContext ( ) , variables ) ; FieldRef currentAppendableField = variables . getCurrentAppendable ( ) ; Statement initAppendable = currentAppendableField . putInstanceField ( thisVar , wrappedAppendable . appendable ( ) ) ; Expression appendableExpression = currentAppendableField . accessor ( thisVar ) ; Statement clearAppendable = currentAppendableField . putInstanceField ( thisVar , constantNull ( LOGGING_ADVISING_APPENDABLE_TYPE ) ) ; if ( wrappedAppendable . closeable ( ) ) { clearAppendable = Statement . concat ( appendableExpression . checkedCast ( BytecodeUtils . CLOSEABLE_TYPE ) . invokeVoid ( MethodRef . CLOSEABLE_CLOSE ) , clearAppendable ) ; } render = Statement . concat ( initAppendable , detachState . detachForRender ( variables . getCurrentRenderee ( ) . accessor ( thisVar ) . invoke ( MethodRef . SOY_VALUE_PROVIDER_RENDER_AND_RESOLVE , appendableExpression , // set the isLast field to true since we know this will only be rendered
// once .
/* isLast = */
constant ( true ) ) ) , clearAppendable ) ; } else { Label start = new Label ( ) ; SoyExpression value = SoyExpression . forSoyValue ( StringType . getInstance ( ) , detachState . createExpressionDetacher ( start ) . resolveSoyValueProvider ( variables . getCurrentRenderee ( ) . accessor ( thisVar ) ) . checkedCast ( SOY_STRING_TYPE ) ) ; for ( SoyPrintDirective directive : escapingDirectives ) { value = parameterLookup . getRenderContext ( ) . applyPrintDirective ( directive , value ) ; } render = appendableExpression . appendString ( value . unboxAsString ( ) ) . toStatement ( ) . labelStart ( start ) ; } return Statement . concat ( initMsgRenderer , render , // clear the field
variables . getCurrentRenderee ( ) . putInstanceField ( thisVar , BytecodeUtils . constantNull ( ConstructorRef . MSG_RENDERER . instanceClass ( ) . type ( ) ) ) ) ; |
public class InstrumentedResourceLeakDetector { /** * This private field in the superclass needs to be reset so that we can continue reporting leaks even
* if they ' re duplicates . This is ugly but ideally should not be called frequently ( or at all ) . */
private void resetReportedLeaks ( ) { } } | try { Field reportedLeaks = ResourceLeakDetector . class . getDeclaredField ( "reportedLeaks" ) ; reportedLeaks . setAccessible ( true ) ; Object f = reportedLeaks . get ( this ) ; if ( f instanceof Map ) { ( ( Map ) f ) . clear ( ) ; } } catch ( Throwable t ) { // do nothing
} |
public class MKeyArea { /** * Read the record that matches this record ' s temp key area . < p >
* WARNING - This method changes the current record ' s buffer .
* @ param strSeekSign - Seek sign : < p >
* < pre >
* " = " - Look for the first match .
* " = = " - Look for an exact match ( On non - unique keys , must match primary key also ) .
* " > " - Look for the first record greater than this .
* " > = " - Look for the first record greater than or equal to this .
* " < " - Look for the first record less than or equal to this .
* " < = " - Look for the first record less than or equal to this .
* < / pre >
* returns : success / failure ( true / false ) .
* @ param table The basetable .
* @ param keyArea The key area .
* @ exception DBException File exception . */
public BaseBuffer doSeek ( String strSeekSign , FieldTable vectorTable , KeyAreaInfo keyArea ) throws DBException { } } | BaseBuffer buffer = null ; int iLowestMatch = - 1 ; // For non - exact matches
keyArea . setupKeyBuffer ( null , Constants . TEMP_KEY_AREA ) ; if ( keyArea . getUniqueKeyCode ( ) != Constants . UNIQUE ) // The main key is part of the comparison
vectorTable . getRecord ( ) . getKeyArea ( Constants . MAIN_KEY_AREA ) . setupKeyBuffer ( null , Constants . TEMP_KEY_AREA ) ; int iLowKey = 0 ; int iHighKey = this . getRecordCount ( ) - 1 ; while ( iLowKey <= iHighKey ) { m_iIndex = ( iLowKey + iHighKey ) / 2 ; buffer = ( BaseBuffer ) m_VectorObjects . elementAt ( m_iIndex ) ; buffer . resetPosition ( ) ; // Being careful
buffer . bufferToFields ( vectorTable . getRecord ( ) , Constants . DONT_DISPLAY , Constants . READ_MOVE ) ; int iCompare = this . compareKeys ( Constants . TEMP_KEY_AREA , strSeekSign , vectorTable , keyArea ) ; if ( iCompare < 0 ) iLowKey = m_iIndex + 1 ; // target key is smaller than this key
else if ( iCompare > 0 ) iHighKey = m_iIndex - 1 ; // target key is larger than this key
else // if ( iCompare = = 0)
{ if ( strSeekSign . equals ( ">" ) ) { iLowKey = m_iIndex + 1 ; // target key is larger than this key
iLowestMatch = iLowKey ; // Not looking for an exact match ( lowest so far )
} else if ( strSeekSign . equals ( "<" ) ) { iHighKey = m_iIndex - 1 ; // target key is larger than this key
iLowestMatch = iHighKey ; // Not looking for an exact match ( lowest so far )
} else { if ( keyArea . getUniqueKeyCode ( ) == Constants . UNIQUE ) { return buffer ; // Found a matching record
} else { if ( ( strSeekSign == null ) || ( strSeekSign . equals ( "==" ) ) ) { // Found an exact matching record
return buffer ; } else { // Not looking for an exact match
iLowestMatch = m_iIndex ; // lowest so far .
iHighKey = m_iIndex - 1 ; // target key is larger than this key
} } } } } m_iIndex = iHighKey ; // Point to next lower key
if ( keyArea . getKeyOrder ( Constants . MAIN_KEY_FIELD ) == Constants . DESCENDING ) // Rarely
m_iIndex = iLowKey ; // Point to next higher key
if ( iLowestMatch == - 1 ) { // For non - exact searches , return the next / previous
if ( ( strSeekSign . equals ( ">=" ) ) || ( strSeekSign . equals ( ">" ) ) ) iLowestMatch = m_iIndex + 1 ; if ( ( strSeekSign . equals ( "<=" ) ) || ( strSeekSign . equals ( "<" ) ) ) iLowestMatch = m_iIndex ; } if ( iLowestMatch != - 1 ) if ( iLowestMatch < m_VectorObjects . size ( ) ) { // There was a non - exact match to this seek
m_iIndex = iLowestMatch ; buffer = ( BaseBuffer ) m_VectorObjects . elementAt ( m_iIndex ) ; buffer . bufferToFields ( vectorTable . getRecord ( ) , Constants . DONT_DISPLAY , Constants . READ_MOVE ) ; return buffer ; // Match ( for a non - exact search )
} return null ; // No match |
public class CommerceOrderItemUtil { /** * Returns the first commerce order item in the ordered set where commerceOrderId = & # 63 ; and CPInstanceId = & # 63 ; .
* @ param commerceOrderId the commerce order ID
* @ param CPInstanceId the cp instance ID
* @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > )
* @ return the first matching commerce order item
* @ throws NoSuchOrderItemException if a matching commerce order item could not be found */
public static CommerceOrderItem findByC_I_First ( long commerceOrderId , long CPInstanceId , OrderByComparator < CommerceOrderItem > orderByComparator ) throws com . liferay . commerce . exception . NoSuchOrderItemException { } } | return getPersistence ( ) . findByC_I_First ( commerceOrderId , CPInstanceId , orderByComparator ) ; |
public class GHUtility { /** * TODO very similar to createSortedGraph - > use a ' int map ( int ) ' interface */
public static Graph copyTo ( Graph fromGraph , Graph toGraph ) { } } | AllEdgesIterator eIter = fromGraph . getAllEdges ( ) ; while ( eIter . next ( ) ) { int base = eIter . getBaseNode ( ) ; int adj = eIter . getAdjNode ( ) ; toGraph . edge ( base , adj ) . copyPropertiesFrom ( eIter ) ; } NodeAccess fna = fromGraph . getNodeAccess ( ) ; NodeAccess tna = toGraph . getNodeAccess ( ) ; int nodes = fromGraph . getNodes ( ) ; for ( int node = 0 ; node < nodes ; node ++ ) { if ( tna . is3D ( ) ) tna . setNode ( node , fna . getLatitude ( node ) , fna . getLongitude ( node ) , fna . getElevation ( node ) ) ; else tna . setNode ( node , fna . getLatitude ( node ) , fna . getLongitude ( node ) ) ; } return toGraph ; |
public class UnXARMojo { /** * Unpack xar dependencies of the provided artifact .
* @ throws MojoExecutionException error when unpack dependencies . */
protected void unpackDependentXars ( Artifact artifact ) throws MojoExecutionException { } } | try { Set < Artifact > dependencies = resolveArtifactDependencies ( artifact ) ; for ( Artifact dependency : dependencies ) { unpack ( dependency . getFile ( ) , this . outputDirectory , "XAR Plugin" , false , getIncludes ( ) , getExcludes ( ) ) ; } } catch ( Exception e ) { throw new MojoExecutionException ( String . format ( "Failed to unpack artifact [%s] dependencies" , artifact ) , e ) ; } |
public class Reporter { /** * Records the performed step to the output file . This includes the action taken if any , the
* expected result , and the actual result . If a screenshot is desired , indicate as such . If
* a ' real ' browser is not being used ( not NONE or HTMLUNIT ) , then no screenshot will be taken
* @ param action - the step that was performed
* @ param expectedResult - the result that was expected to occur
* @ param actualResult - the result that actually occurred
* @ param screenshot - should a screenshot be taken
* @ param success - the result of the action */
private void recordStep ( String action , String expectedResult , String actualResult , Boolean screenshot , Success success ) { } } | stepNum ++ ; String imageLink = "" ; if ( screenshot && isRealBrowser ( ) ) { // get a screen shot of the action
imageLink = captureEntirePageScreenshot ( ) ; } // determine time differences
Date currentTime = new Date ( ) ; long dTime = currentTime . getTime ( ) - lastTime ; long tTime = currentTime . getTime ( ) - startTime ; lastTime = currentTime . getTime ( ) ; try ( // Reopen file
FileWriter fw = new FileWriter ( file , true ) ; BufferedWriter out = new BufferedWriter ( fw ) ) { // record the action
out . write ( START_ROW ) ; out . write ( " <td align='center'>" + stepNum + ".</td>\n" ) ; out . write ( START_CELL + action + END_CELL ) ; out . write ( START_CELL + expectedResult + END_CELL ) ; out . write ( START_CELL + actualResult + imageLink + END_CELL ) ; out . write ( START_CELL + dTime + "ms / " + tTime + "ms</td>\n" ) ; out . write ( " <td class='" + success . toString ( ) . toLowerCase ( ) + "'>" + success + END_CELL ) ; out . write ( END_ROW ) ; } catch ( IOException e ) { log . error ( e ) ; } |
public class PeerAwareInstanceRegistryImpl { /** * ( non - Javadoc )
* @ see com . netflix . eureka . registry . InstanceRegistry # cancel ( java . lang . String ,
* java . lang . String , long , boolean ) */
@ Override public boolean cancel ( final String appName , final String id , final boolean isReplication ) { } } | if ( super . cancel ( appName , id , isReplication ) ) { replicateToPeers ( Action . Cancel , appName , id , null , null , isReplication ) ; synchronized ( lock ) { if ( this . expectedNumberOfClientsSendingRenews > 0 ) { // Since the client wants to cancel it , reduce the number of clients to send renews
this . expectedNumberOfClientsSendingRenews = this . expectedNumberOfClientsSendingRenews - 1 ; updateRenewsPerMinThreshold ( ) ; } } return true ; } return false ; |
public class AbstractBigtableAdmin { /** * { @ inheritDoc } */
@ Override public boolean tableExists ( TableName tableName ) throws IOException { } } | for ( TableName existingTableName : listTableNames ( tableName . getNameAsString ( ) ) ) { if ( existingTableName . equals ( tableName ) ) { return true ; } } return false ; |
public class DefaultPDUSender { /** * ( non - Javadoc )
* @ see org . jsmpp . PDUSender # sendEnquireLinkResp ( java . io . OutputStream , int ) */
public byte [ ] sendEnquireLinkResp ( OutputStream os , int sequenceNumber ) throws IOException { } } | byte [ ] b = pduComposer . enquireLinkResp ( sequenceNumber ) ; writeAndFlush ( os , b ) ; return b ; |
public class MemberEnter { /** * Create a fresh environment for a variable ' s initializer .
* If the variable is a field , the owner of the environment ' s scope
* is be the variable itself , otherwise the owner is the method
* enclosing the variable definition .
* @ param tree The variable definition .
* @ param env The environment current outside of the variable definition . */
Env < AttrContext > initEnv ( JCVariableDecl tree , Env < AttrContext > env ) { } } | Env < AttrContext > localEnv = env . dupto ( new AttrContextEnv ( tree , env . info . dup ( ) ) ) ; if ( tree . sym . owner . kind == TYP ) { localEnv . info . scope = env . info . scope . dupUnshared ( tree . sym ) ; } if ( ( tree . mods . flags & STATIC ) != 0 || ( ( env . enclClass . sym . flags ( ) & INTERFACE ) != 0 && env . enclMethod == null ) ) localEnv . info . staticLevel ++ ; return localEnv ; |
public class UrlOperations { /** * Extract userinfo from the absolute URL argument , that is , " username @ " , or
* " username : password @ " if present .
* @ param url the URL from which to extract the userinfo
* @ return the userinfo found , not including the " @ " , or null if no userinfo
* is found */
public static String urlToUserInfo ( String url ) { } } | String lcUrl = url . toLowerCase ( ) ; if ( lcUrl . startsWith ( DNS_SCHEME ) ) { return null ; } for ( String scheme : ALL_SCHEMES ) { if ( lcUrl . startsWith ( scheme ) ) { int authorityIdx = scheme . length ( ) ; Matcher m = USERINFO_REGEX_SIMPLE . matcher ( lcUrl . substring ( authorityIdx ) ) ; if ( m . find ( ) ) { return m . group ( 1 ) ; } } } return null ; |
public class Billing { /** * < pre >
* Billing configurations for sending metrics to the consumer project .
* There can be multiple consumer destinations per service , each one must have
* a different monitored resource type . A metric can be used in at most
* one consumer destination .
* < / pre >
* < code > repeated . google . api . Billing . BillingDestination consumer _ destinations = 8 ; < / code > */
public com . google . api . Billing . BillingDestinationOrBuilder getConsumerDestinationsOrBuilder ( int index ) { } } | return consumerDestinations_ . get ( index ) ; |
public class FormulaFactory { /** * Creates a new literal instance with a given name and phase .
* Literal names should not start with { @ code @ RESERVED } - these are reserved for internal literals .
* @ param name the literal name
* @ param phase the literal phase
* @ return a new literal with the given name and phase */
public Literal literal ( final String name , final boolean phase ) { } } | if ( phase ) return this . variable ( name ) ; else { Literal lit = this . negLiterals . get ( name ) ; if ( lit == null ) { lit = new Literal ( name , false , this ) ; this . negLiterals . put ( name , lit ) ; } return lit ; } |
public class Block { /** * A list of child blocks of the current block . For example a LINE object has child blocks for each WORD block
* that ' s part of the line of text . There aren ' t Relationship objects in the list for relationships that don ' t
* exist , such as when the current block has no child blocks . The list size can be the following :
* < ul >
* < li >
* 0 - The block has no child blocks .
* < / li >
* < li >
* 1 - The block has child blocks .
* < / li >
* < / ul >
* @ param relationships
* A list of child blocks of the current block . For example a LINE object has child blocks for each WORD
* block that ' s part of the line of text . There aren ' t Relationship objects in the list for relationships
* that don ' t exist , such as when the current block has no child blocks . The list size can be the
* following : < / p >
* < ul >
* < li >
* 0 - The block has no child blocks .
* < / li >
* < li >
* 1 - The block has child blocks .
* < / li > */
public void setRelationships ( java . util . Collection < Relationship > relationships ) { } } | if ( relationships == null ) { this . relationships = null ; return ; } this . relationships = new java . util . ArrayList < Relationship > ( relationships ) ; |
public class DevicesInner { /** * Downloads the updates on a data box edge / gateway device .
* @ param deviceName The device name .
* @ param resourceGroupName The resource group name .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the { @ link ServiceResponse } object if successful . */
public Observable < Void > beginDownloadUpdatesAsync ( String deviceName , String resourceGroupName ) { } } | return beginDownloadUpdatesWithServiceResponseAsync ( deviceName , resourceGroupName ) . map ( new Func1 < ServiceResponse < Void > , Void > ( ) { @ Override public Void call ( ServiceResponse < Void > response ) { return response . body ( ) ; } } ) ; |
public class KAMStoreSchemaServiceImpl { /** * { @ inheritDoc } */
@ Override public void deleteFromKAMCatalog ( final String kamName ) throws SQLException { } } | KAMCatalogDao catalogDAO = null ; try { catalogDAO = createCatalogDao ( ) ; catalogDAO . deleteFromCatalog ( kamName ) ; } finally { if ( catalogDAO != null ) { closeCatalogDao ( catalogDAO ) ; } } |
public class UpdateAppProfileRequest { /** * Creates the request protobuf . This method is considered an internal implementation detail and
* not meant to be used by applications . */
@ InternalApi public com . google . bigtable . admin . v2 . UpdateAppProfileRequest toProto ( String projectId ) { } } | String name = NameUtil . formatAppProfileName ( projectId , instanceId , appProfileId ) ; proto . getAppProfileBuilder ( ) . setName ( name ) ; return proto . build ( ) ; |
public class PopupMenuItemHttpMessageContainer { /** * Tells whether or not the button should be enabled for the state of the given message container . Called from
* { @ code isEnableForMessageContainer ( MessageContainer ) } .
* By default , is only enabled if both methods { @ code isButtonEnabledForNumberOfSelectedMessages ( HttpMessageContainer ) } and
* { @ code isButtonEnabledForSelectedMessages ( HttpMessageContainer ) } ( called only if the former method returns { @ code true } )
* return { @ code true } . < br >
* Not normally overridden .
* @ param httpMessageContainer the message container that will be evaluated
* @ return { @ code true } if the button should be enabled for the message container , { @ code false } otherwise .
* @ see # isEnableForMessageContainer ( MessageContainer )
* @ see # isButtonEnabledForNumberOfSelectedMessages ( HttpMessageContainer )
* @ see # isButtonEnabledForSelectedMessages ( HttpMessageContainer ) */
protected boolean isButtonEnabledForHttpMessageContainerState ( HttpMessageContainer httpMessageContainer ) { } } | boolean enabled = isButtonEnabledForNumberOfSelectedMessages ( httpMessageContainer ) ; if ( enabled ) { enabled = isButtonEnabledForSelectedMessages ( httpMessageContainer ) ; } return enabled ; |
public class GDLLoader { /** * Adds a list of predicates to the current predicates using AND conjunctions
* @ param newPredicates predicates to be added */
private void addPredicates ( List < Predicate > newPredicates ) { } } | for ( Predicate newPredicate : newPredicates ) { if ( this . predicates == null ) { this . predicates = newPredicate ; } else { this . predicates = new And ( this . predicates , newPredicate ) ; } } |
public class XCARespondingGatewayAuditor { /** * Audits an ITI - 39 Cross Gateway Retrieve event for XCA Responding Gateway actors .
* @ param eventOutcome The event outcome indicator
* @ param initiatingGatewayUserId The Active Participant UserID for the document consumer ( if using WS - Addressing )
* @ param initiatingGatewayUserName The Active Participant UserName for the document consumer ( if using WS - Security / XUA )
* @ param initiatingGatewayIpAddress The IP address of the document consumer that initiated the transaction
* @ param respondingGatewayEndpointUri The Web service endpoint URI for this document repository
* @ param documentUniqueIds The list of Document Entry UniqueId ( s ) for the document ( s ) retrieved
* @ param repositoryUniqueIds The list of XDS . b Repository Unique Ids involved in this transaction ( aligned with Document Unique Ids array )
* @ param homeCommunityIds The list of home community ids used in the transaction
* @ param purposesOfUse purpose of use codes ( may be taken from XUA token )
* @ param userRoles roles of the human user ( may be taken from XUA token ) */
public void auditCrossGatewayRetrieveEvent ( RFC3881EventOutcomeCodes eventOutcome , String initiatingGatewayUserId , String initiatingGatewayIpAddress , String respondingGatewayEndpointUri , String initiatingGatewayUserName , String [ ] documentUniqueIds , String [ ] repositoryUniqueIds , String homeCommunityIds [ ] , List < CodedValueType > purposesOfUse , List < CodedValueType > userRoles ) { } } | if ( ! isAuditorEnabled ( ) ) { return ; } ExportEvent exportEvent = new ExportEvent ( true , eventOutcome , new IHETransactionEventTypeCodes . CrossGatewayRetrieve ( ) , purposesOfUse ) ; exportEvent . setAuditSourceId ( getAuditSourceId ( ) , getAuditEnterpriseSiteId ( ) ) ; exportEvent . addSourceActiveParticipant ( respondingGatewayEndpointUri , getSystemAltUserId ( ) , null , EventUtils . getAddressForUrl ( respondingGatewayEndpointUri , false ) , false ) ; if ( ! EventUtils . isEmptyOrNull ( initiatingGatewayUserName ) ) { exportEvent . addHumanRequestorActiveParticipant ( initiatingGatewayUserName , null , initiatingGatewayUserName , userRoles ) ; } exportEvent . addDestinationActiveParticipant ( initiatingGatewayUserId , null , null , initiatingGatewayIpAddress , true ) ; // exportEvent . addPatientParticipantObject ( patientId ) ;
if ( ! EventUtils . isEmptyOrNull ( documentUniqueIds ) ) { for ( int i = 0 ; i < documentUniqueIds . length ; i ++ ) { exportEvent . addDocumentParticipantObject ( documentUniqueIds [ i ] , repositoryUniqueIds [ i ] , homeCommunityIds [ i ] ) ; } } audit ( exportEvent ) ; |
public class ConnectionWatcher { /** * @ param hosts
* @ return void
* @ throws IOException
* @ throws InterruptedException
* @ Description : 连接ZK
* @ author liaoqiqi
* @ date 2013-6-14 */
public void connect ( String hosts ) throws IOException , InterruptedException { } } | internalHost = hosts ; zk = new ZooKeeper ( internalHost , SESSION_TIMEOUT , this ) ; // 连接有超时哦
connectedSignal . await ( CONNECT_TIMEOUT , TimeUnit . MILLISECONDS ) ; LOGGER . info ( "zookeeper: " + hosts + " , connected." ) ; |
public class NewChunk { /** * Compute a sparse float buffer */
private byte [ ] bufD ( final int valsz ) { } } | int log = 0 ; while ( ( 1 << log ) < valsz ) ++ log ; assert ( 1 << log ) == valsz ; final int ridsz = _len >= 65535 ? 4 : 2 ; final int elmsz = ridsz + valsz ; int off = CXDChunk . OFF ; byte [ ] buf = MemoryManager . malloc1 ( off + _sparseLen * elmsz , true ) ; for ( int i = 0 ; i < _sparseLen ; i ++ , off += elmsz ) { if ( ridsz == 2 ) UDP . set2 ( buf , off , ( short ) _id [ i ] ) ; else UDP . set4 ( buf , off , _id [ i ] ) ; final double dval = _ds == null ? isNA2 ( i ) ? Double . NaN : _ls [ i ] * PrettyPrint . pow10 ( _xs [ i ] ) : _ds [ i ] ; switch ( valsz ) { case 4 : UDP . set4f ( buf , off + ridsz , ( float ) dval ) ; break ; case 8 : UDP . set8d ( buf , off + ridsz , dval ) ; break ; default : throw H2O . unimpl ( ) ; } } assert off == buf . length ; return buf ; |
public class GenerateEsas { /** * This method will find the appropriate JAR ( s ) to the supplied set of file paths .
* @ param content The file paths to add the JAR ( s ) to
* @ param fd The feature definition containing this JAR
* @ param br The bundle repository to be queried to find the JAR
* @ param fr The feature resource defining the JAR */
public void addJarResource ( final Set < String > content , final ProvisioningFeatureDefinition fd , final ContentBasedLocalBundleRepository br , FeatureResource fr ) { } } | // type = bundle , need to query the bundle repository for
// this feature def , to find which files are being used
// ( could be in a different location or an iFix ) .
// type = jar , basically same as type = bundle here
// type = boot . jar , basically same as type = bundle here
File b = br . selectBundle ( fr . getLocation ( ) , fr . getSymbolicName ( ) , fr . getVersionRange ( ) ) ; // bb is the bundle if no iFix were installed
File bb = br . selectBaseBundle ( fr . getLocation ( ) , fr . getSymbolicName ( ) , fr . getVersionRange ( ) ) ; // b & bb will be the same bundle if the base was the
// selected . .
if ( b != null && bb != null ) { // ESAs don ' t ( and can ' t ) install iFix content so just include the base bundle
content . add ( bb . getAbsolutePath ( ) ) ; } else { /* * As we have a built version we should have everything
* so if it is missing then that is bad */
log ( "Missing JAR for resource " + fr . getSymbolicName ( ) + " in feature " + fd . getSymbolicName ( ) , Project . MSG_ERR ) ; } |
public class TargetFullFeatureStage { /** * Creates a PDU with { @ link FixedFormatSenseData } that must be sent to the initiator after receiving a
* Command
* Descriptor Block with an illegal field .
* @ param senseKeySpecificData
* contains a list of all illegal fields
* @ param additionalSenseCodeAndQualifier
* provides more specific information about the cause of the check condition
* @ param initiatorTaskTag
* used by the initiator to identify the task
* @ param expectedDataTransferLength
* the amount of payload data expected by the initiator ( i . e . allocated buffer
* space )
* @ return the error PDU */
protected static final ProtocolDataUnit createFixedFormatErrorPdu ( final FieldPointerSenseKeySpecificData [ ] senseKeySpecificData , final AdditionalSenseCodeAndQualifier additionalSenseCodeAndQualifier , final int initiatorTaskTag , final int expectedDataTransferLength ) { } } | // create the whole sense data
FixedFormatSenseData senseData = new FixedFormatSenseData ( false , // valid
ErrorType . CURRENT , // error type
false , // file mark
false , // end of medium
false , // incorrect length indicator
SenseKey . ILLEGAL_REQUEST , // sense key
new FourByteInformation ( ) , // information
new FourByteInformation ( ) , // command specific information
additionalSenseCodeAndQualifier , // additional sense code and
// qualifier
( byte ) 0 , // field replaceable unit code
senseKeySpecificData [ 0 ] , // sense key specific data , only report
// first problem
new AdditionalSenseBytes ( ) ) ; // additional sense bytes
// keep only the part of the sense data that will be sent
final ScsiResponseDataSegment dataSegment = new ScsiResponseDataSegment ( senseData , expectedDataTransferLength ) ; final int senseDataSize = senseData . size ( ) ; // calculate residuals and flags
final int residualCount = Math . abs ( expectedDataTransferLength - senseDataSize ) ; final boolean residualOverflow = expectedDataTransferLength < senseDataSize ; final boolean residualUnderflow = expectedDataTransferLength > senseDataSize ; // create and return PDU
return TargetPduFactory . createSCSIResponsePdu ( false , // bidirectionalReadResidualOverflow
false , // bidirectionalReadResidualUnderflow
residualOverflow , // residualOverflow
residualUnderflow , // residualUnderflow ,
SCSIResponseParser . ServiceResponse . COMMAND_COMPLETED_AT_TARGET , // response ,
SCSIStatus . CHECK_CONDITION , // status ,
initiatorTaskTag , // initiatorTaskTag ,
0 , // snackTag
0 , // expectedDataSequenceNumber
0 , // bidirectionalReadResidualCount
residualCount , // residualCount
dataSegment ) ; // data segment |
public class StateAssignmentOperation { /** * TODO rewrite based on operator id */
private Tuple2 < List < KeyedStateHandle > , List < KeyedStateHandle > > reAssignSubKeyedStates ( OperatorState operatorState , List < KeyGroupRange > keyGroupPartitions , int subTaskIndex , int newParallelism , int oldParallelism ) { } } | List < KeyedStateHandle > subManagedKeyedState ; List < KeyedStateHandle > subRawKeyedState ; if ( newParallelism == oldParallelism ) { if ( operatorState . getState ( subTaskIndex ) != null ) { subManagedKeyedState = operatorState . getState ( subTaskIndex ) . getManagedKeyedState ( ) . asList ( ) ; subRawKeyedState = operatorState . getState ( subTaskIndex ) . getRawKeyedState ( ) . asList ( ) ; } else { subManagedKeyedState = Collections . emptyList ( ) ; subRawKeyedState = Collections . emptyList ( ) ; } } else { subManagedKeyedState = getManagedKeyedStateHandles ( operatorState , keyGroupPartitions . get ( subTaskIndex ) ) ; subRawKeyedState = getRawKeyedStateHandles ( operatorState , keyGroupPartitions . get ( subTaskIndex ) ) ; } if ( subManagedKeyedState . isEmpty ( ) && subRawKeyedState . isEmpty ( ) ) { return new Tuple2 < > ( Collections . emptyList ( ) , Collections . emptyList ( ) ) ; } else { return new Tuple2 < > ( subManagedKeyedState , subRawKeyedState ) ; } |
public class ZooCheckDb { /** * private static final String DB _ NAME = " StackServerFault " ; */
public static void main ( String [ ] args ) { } } | String dbName ; if ( args . length == 0 ) { dbName = DB_NAME ; } else { dbName = args [ 0 ] ; } if ( ! ZooHelper . getDataStoreManager ( ) . dbExists ( dbName ) ) { err . println ( "ERROR Database not found: " + dbName ) ; return ; } out . println ( "Checking database: " + dbName ) ; ZooJdoProperties props = new ZooJdoProperties ( dbName ) ; PersistenceManagerFactory pmf = JDOHelper . getPersistenceManagerFactory ( props ) ; PersistenceManager pm = pmf . getPersistenceManager ( ) ; Session s = ( Session ) pm . getDataStoreConnection ( ) . getNativeConnection ( ) ; String report = s . getPrimaryNode ( ) . checkDb ( ) ; out . println ( ) ; out . println ( "Report" ) ; out . println ( "======" ) ; out . println ( report ) ; out . println ( "======" ) ; pm . close ( ) ; pmf . close ( ) ; out . println ( "Checking database done." ) ; |
public class PausablePriorityBlockingQueue { /** * makes findbugs happy , but unused */
private void readObject ( ObjectInputStream ois ) { } } | try { ois . defaultReadObject ( ) ; pauseLock = new ReentrantLock ( ) ; pauseLock . newCondition ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } |
public class ConfigurationMarshaller { /** * Marshall the given parameter object . */
public void marshall ( Configuration configuration , ProtocolMarshaller protocolMarshaller ) { } } | if ( configuration == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( configuration . getArn ( ) , ARN_BINDING ) ; protocolMarshaller . marshall ( configuration . getCreated ( ) , CREATED_BINDING ) ; protocolMarshaller . marshall ( configuration . getDescription ( ) , DESCRIPTION_BINDING ) ; protocolMarshaller . marshall ( configuration . getEngineType ( ) , ENGINETYPE_BINDING ) ; protocolMarshaller . marshall ( configuration . getEngineVersion ( ) , ENGINEVERSION_BINDING ) ; protocolMarshaller . marshall ( configuration . getId ( ) , ID_BINDING ) ; protocolMarshaller . marshall ( configuration . getLatestRevision ( ) , LATESTREVISION_BINDING ) ; protocolMarshaller . marshall ( configuration . getName ( ) , NAME_BINDING ) ; protocolMarshaller . marshall ( configuration . getTags ( ) , TAGS_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class TransmittableThreadLocal { /** * see { @ link InheritableThreadLocal # set } */
@ Override public final void set ( T value ) { } } | super . set ( value ) ; // may set null to remove value
if ( null == value ) removeValue ( ) ; else addValue ( ) ; |
public class BaseMessageTransport { /** * Using this transport , process this internal message and convert to the external format .
* ( I ' m getting this message ready to send externally )
* @ param messageOut The message to send .
* @ param messageOutProcessor The message out processor .
* @ return Error code */
public int convertToExternal ( BaseMessage messageOut , BaseInternalMessageProcessor messageOutProcessor ) { } } | String strMessageInfoType = MessageInfoTypeModel . REQUEST ; String strMessageProcessType = MessageTypeModel . MESSAGE_OUT ; if ( messageOut . getMessageHeader ( ) != null ) { strMessageInfoType = ( String ) messageOut . getMessageHeader ( ) . get ( TrxMessageHeader . MESSAGE_INFO_TYPE ) ; strMessageProcessType = ( String ) messageOut . getMessageHeader ( ) . get ( TrxMessageHeader . MESSAGE_PROCESS_TYPE ) ; } if ( messageOutProcessor == null ) { String strDefaultProcessorClass = MessageTypeModel . MESSAGE_OUT . equals ( strMessageProcessType ) ? BaseMessageOutProcessor . class . getName ( ) : BaseMessageReplyOutProcessor . class . getName ( ) ; messageOutProcessor = ( BaseInternalMessageProcessor ) BaseMessageProcessor . getMessageProcessor ( this . getTask ( ) , messageOut , strDefaultProcessorClass ) ; } messageOut . createMessageDataDesc ( ) ; messageOutProcessor . processMessage ( messageOut ) ; String strMessageStatus = MessageTypeModel . MESSAGE_OUT . equals ( strMessageProcessType ) ? MessageStatusModel . SENT : MessageStatusModel . SENTOK ; // Reply does not wait for a reply
ExternalMessage externalTrxMessage = this . createExternalMessage ( messageOut , null ) ; Utility . getLogger ( ) . info ( "sendMessage externalTrxMessage = " + externalTrxMessage ) ; String strTrxID = this . logMessage ( null , messageOut , strMessageInfoType , strMessageProcessType , strMessageStatus , null , null ) ; if ( messageOut . getMessageHeader ( ) instanceof TrxMessageHeader ) ( ( TrxMessageHeader ) messageOut . getMessageHeader ( ) ) . put ( TrxMessageHeader . LOG_TRX_ID , strTrxID ) ; int iErrorCode = DBConstants . ERROR_RETURN ; if ( externalTrxMessage != null ) iErrorCode = externalTrxMessage . convertInternalToExternal ( this ) ; // Convert my standard message to the OTA EC message
String strMessageDescription = null ; if ( iErrorCode != DBConstants . NORMAL_RETURN ) { strMessageDescription = this . getTask ( ) . getLastError ( iErrorCode ) ; if ( ( strMessageDescription == null ) || ( strMessageDescription . length ( ) == 0 ) ) strMessageDescription = "Error converting to external format" ; iErrorCode = this . getTask ( ) . setLastError ( strMessageDescription ) ; strMessageStatus = MessageStatusModel . ERROR ; } this . logMessage ( strTrxID , messageOut , strMessageInfoType , strMessageProcessType , strMessageStatus , strMessageDescription , null ) ; // Log it with the external info
return iErrorCode ; |
public class PlatformDetector { /** * Parses the { @ code / etc / redhat - release } and returns a { @ link LinuxRelease } containing the
* ID and like [ " rhel " , " fedora " , ID ] . Currently only supported for CentOS , Fedora , and RHEL .
* Other variants will return { @ code null } . */
private static LinuxRelease parseLinuxRedhatReleaseFile ( File file ) { } } | BufferedReader reader = null ; try { reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( file ) , "utf-8" ) ) ; // There is only a single line in this file .
String line = reader . readLine ( ) ; if ( line != null ) { line = line . toLowerCase ( Locale . US ) ; String id ; String version = null ; if ( line . contains ( "centos" ) ) { id = "centos" ; } else if ( line . contains ( "fedora" ) ) { id = "fedora" ; } else if ( line . contains ( "red hat enterprise linux" ) ) { id = "rhel" ; } else { // Other variants are not currently supported .
return null ; } Matcher versionMatcher = REDHAT_MAJOR_VERSION_REGEX . matcher ( line ) ; if ( versionMatcher . find ( ) ) { version = versionMatcher . group ( 1 ) ; } Set < String > likeSet = new LinkedHashSet < String > ( ) ; likeSet . addAll ( Arrays . asList ( DEFAULT_REDHAT_VARIANTS ) ) ; likeSet . add ( id ) ; return new LinuxRelease ( id , version , likeSet ) ; } } catch ( IOException ignored ) { // Just absorb . Don ' t treat failure to read / etc / os - release as an error .
} finally { closeQuietly ( reader ) ; } return null ; |
public class RidUtils { /** * Resolve rid from almost all possible objects .
* Even if simple string provided , value will be checked for correctness .
* Note : not saved object proxy , document or vertex will contain fake id and will be accepted
* ( but query result against such id will be empty ) .
* @ param value value may be a mapped object ( proxy or raw ) , document , vertex , ORID or simple string
* @ return correct rid string
* @ throws ru . vyarus . guice . persist . orient . db . PersistException if rid couldn ' t be resolved
* @ throws NullPointerException if value is null */
public static String getRid ( final Object value ) { } } | Preconditions . checkNotNull ( value , "Not null value required" ) ; final String res ; if ( value instanceof ORID ) { res = value . toString ( ) ; } else if ( value instanceof OIdentifiable ) { // ODocument , Vertex support
res = ( ( OIdentifiable ) value ) . getIdentity ( ) . toString ( ) ; } else if ( value instanceof String ) { res = checkRid ( value ) ; } else if ( value instanceof Proxy ) { // object proxy
res = OObjectEntitySerializer . getRid ( ( Proxy ) value ) . toString ( ) ; } else { // raw ( non proxy ) object
res = resolveIdFromObject ( value ) ; } return res ; |
public class JobLeaderService { /** * Start the job leader service with the given services .
* @ param initialOwnerAddress to be used for establishing connections ( source address )
* @ param initialRpcService to be used to create rpc connections
* @ param initialHighAvailabilityServices to create leader retrieval services for the different jobs
* @ param initialJobLeaderListener listening for job leader changes */
public void start ( final String initialOwnerAddress , final RpcService initialRpcService , final HighAvailabilityServices initialHighAvailabilityServices , final JobLeaderListener initialJobLeaderListener ) { } } | if ( JobLeaderService . State . CREATED != state ) { throw new IllegalStateException ( "The service has already been started." ) ; } else { LOG . info ( "Start job leader service." ) ; this . ownerAddress = Preconditions . checkNotNull ( initialOwnerAddress ) ; this . rpcService = Preconditions . checkNotNull ( initialRpcService ) ; this . highAvailabilityServices = Preconditions . checkNotNull ( initialHighAvailabilityServices ) ; this . jobLeaderListener = Preconditions . checkNotNull ( initialJobLeaderListener ) ; state = JobLeaderService . State . STARTED ; } |
public class LocalPDBDirectory { /** * Gets the directory in which the file for a given MMCIF file would live ,
* creating it if necessary .
* The obsolete parameter is necessary to avoid additional server queries .
* @ param pdbId
* @ param obsolete Whether the pdbId is obsolete or not
* @ return File pointing to the directory , */
protected File getDir ( String pdbId , boolean obsolete ) { } } | File dir = null ; if ( obsolete ) { // obsolete is always split
String middle = pdbId . substring ( 1 , 3 ) . toLowerCase ( ) ; dir = new File ( obsoleteDirPath , middle ) ; } else { String middle = pdbId . substring ( 1 , 3 ) . toLowerCase ( ) ; dir = new File ( splitDirPath , middle ) ; } if ( ! dir . exists ( ) ) { boolean success = dir . mkdirs ( ) ; if ( ! success ) logger . error ( "Could not create mmCIF dir {}" , dir . toString ( ) ) ; } return dir ; |
public class GateioTradeService { /** * Submits a Limit Order to be executed on the Gateio Exchange for the desired market defined by
* { @ code CurrencyPair } . WARNING - Gateio will return true regardless of whether or not an order
* actually gets created . The reason for this is that orders are simply submitted to a queue in
* their back - end . One example for why an order might not get created is because there are
* insufficient funds . The best attempt you can make to confirm that the order was created is to
* poll { @ link # getOpenOrders } . However , if the order is created and executed before it is caught
* in its open state from calling { @ link # getOpenOrders } then the only way to confirm would be
* confirm the expected difference in funds available for your account .
* @ return String " true " / " false " Used to determine if the order request was submitted
* successfully . */
@ Override public String placeLimitOrder ( LimitOrder limitOrder ) throws IOException { } } | return String . valueOf ( super . placeGateioLimitOrder ( limitOrder ) ) ; |
public class AzkabanExecutorServer { /** * Configure Metric Reporting as per azkaban . properties settings */
private void configureMetricReports ( ) throws MetricException { } } | final Props props = getAzkabanProps ( ) ; if ( props != null && props . getBoolean ( "executor.metric.reports" , false ) ) { logger . info ( "Starting to configure Metric Reports" ) ; final MetricReportManager metricManager = MetricReportManager . getInstance ( ) ; final IMetricEmitter metricEmitter = new InMemoryMetricEmitter ( props ) ; metricManager . addMetricEmitter ( metricEmitter ) ; logger . info ( "Adding number of failed flow metric" ) ; metricManager . addMetric ( new NumFailedFlowMetric ( metricManager , props . getInt ( METRIC_INTERVAL + NumFailedFlowMetric . NUM_FAILED_FLOW_METRIC_NAME , props . getInt ( METRIC_INTERVAL + "default" ) ) ) ) ; logger . info ( "Adding number of failed jobs metric" ) ; metricManager . addMetric ( new NumFailedJobMetric ( metricManager , props . getInt ( METRIC_INTERVAL + NumFailedJobMetric . NUM_FAILED_JOB_METRIC_NAME , props . getInt ( METRIC_INTERVAL + "default" ) ) ) ) ; logger . info ( "Adding number of running Jobs metric" ) ; metricManager . addMetric ( new NumRunningJobMetric ( metricManager , props . getInt ( METRIC_INTERVAL + NumRunningJobMetric . NUM_RUNNING_JOB_METRIC_NAME , props . getInt ( METRIC_INTERVAL + "default" ) ) ) ) ; logger . info ( "Adding number of running flows metric" ) ; metricManager . addMetric ( new NumRunningFlowMetric ( this . runnerManager , metricManager , props . getInt ( METRIC_INTERVAL + NumRunningFlowMetric . NUM_RUNNING_FLOW_METRIC_NAME , props . getInt ( METRIC_INTERVAL + "default" ) ) ) ) ; logger . info ( "Adding number of queued flows metric" ) ; metricManager . addMetric ( new NumQueuedFlowMetric ( this . runnerManager , metricManager , props . getInt ( METRIC_INTERVAL + NumQueuedFlowMetric . NUM_QUEUED_FLOW_METRIC_NAME , props . getInt ( METRIC_INTERVAL + "default" ) ) ) ) ; logger . info ( "Completed configuring Metric Reports" ) ; } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.