signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class CmsXmlContainerPageFactory { /** * Create a new instance of a container page based on the given content definition ,
* that will have one language node for the given locale all initialized with default values . < p >
* The given encoding is used when marshalling the XML again later . < p >
* @ param cms the current users OpenCms content
* @ param locale the locale to generate the default content for
* @ param encoding the encoding to use when marshalling the XML content later
* @ param contentDefinition the content definition to create the content for
* @ return the created container page */
public static CmsXmlContainerPage createDocument ( CmsObject cms , Locale locale , String encoding , CmsXmlContentDefinition contentDefinition ) { } } | // create the XML content
CmsXmlContainerPage content = new CmsXmlContainerPage ( cms , locale , encoding , contentDefinition ) ; // call prepare for use content handler and return the result
return ( CmsXmlContainerPage ) content . getHandler ( ) . prepareForUse ( cms , content ) ; |
public class NIODirectorySocket { /** * Do the Socket connect .
* @ param addr
* the remote address .
* @ throws IOException
* the IOException . */
private void doSocketConnect ( InetSocketAddress addr ) throws IOException { } } | SocketChannel sock = createSock ( ) ; registerAndConnect ( sock , addr ) ; |
public class LDAPConnectionService { /** * Binds to the LDAP server using the provided user DN and password .
* @ param userDN
* The DN of the user to bind as , or null to bind anonymously .
* @ param password
* The password to use when binding as the specified user , or null to
* attempt to bind without a password .
* @ return
* A bound LDAP connection , or null if the connection could not be
* bound .
* @ throws GuacamoleException
* If an error occurs while binding to the LDAP server . */
public LDAPConnection bindAs ( String userDN , String password ) throws GuacamoleException { } } | // Obtain appropriately - configured LDAPConnection instance
LDAPConnection ldapConnection = createLDAPConnection ( ) ; // Configure LDAP connection constraints
LDAPConstraints ldapConstraints = ldapConnection . getConstraints ( ) ; if ( ldapConstraints == null ) ldapConstraints = new LDAPConstraints ( ) ; // Set whether or not we follow referrals
ldapConstraints . setReferralFollowing ( confService . getFollowReferrals ( ) ) ; // Set referral authentication to use the provided credentials .
if ( userDN != null && ! userDN . isEmpty ( ) ) ldapConstraints . setReferralHandler ( new ReferralAuthHandler ( userDN , password ) ) ; // Set the maximum number of referrals we follow
ldapConstraints . setHopLimit ( confService . getMaxReferralHops ( ) ) ; // Set timelimit to wait for LDAP operations , converting to ms
ldapConstraints . setTimeLimit ( confService . getOperationTimeout ( ) * 1000 ) ; // Apply the constraints to the connection
ldapConnection . setConstraints ( ldapConstraints ) ; try { // Connect to LDAP server
ldapConnection . connect ( confService . getServerHostname ( ) , confService . getServerPort ( ) ) ; // Explicitly start TLS if requested
if ( confService . getEncryptionMethod ( ) == EncryptionMethod . STARTTLS ) ldapConnection . startTLS ( ) ; } catch ( LDAPException e ) { logger . error ( "Unable to connect to LDAP server: {}" , e . getMessage ( ) ) ; logger . debug ( "Failed to connect to LDAP server." , e ) ; return null ; } // Bind using provided credentials
try { byte [ ] passwordBytes ; try { // Convert password into corresponding byte array
if ( password != null ) passwordBytes = password . getBytes ( "UTF-8" ) ; else passwordBytes = null ; } catch ( UnsupportedEncodingException e ) { logger . error ( "Unexpected lack of support for UTF-8: {}" , e . getMessage ( ) ) ; logger . debug ( "Support for UTF-8 (as required by Java spec) not found." , e ) ; disconnect ( ldapConnection ) ; return null ; } // Bind as user
ldapConnection . bind ( LDAPConnection . LDAP_V3 , userDN , passwordBytes ) ; } // Disconnect if an error occurs during bind
catch ( LDAPException e ) { logger . debug ( "LDAP bind failed." , e ) ; disconnect ( ldapConnection ) ; return null ; } return ldapConnection ; |
public class DefaultGroovyMethods { /** * Printf a value to the standard output stream using a format string .
* This method delegates to the owner to execute the method .
* @ param self a generated closure
* @ param format a format string
* @ param value value referenced by the format specifier in the format string
* @ since 3.0.0 */
public static void printf ( Closure self , String format , Object value ) { } } | Object owner = getClosureOwner ( self ) ; Object [ ] newValues = new Object [ 2 ] ; newValues [ 0 ] = format ; newValues [ 1 ] = value ; InvokerHelper . invokeMethod ( owner , "printf" , newValues ) ; |
public class FreemarkerSQLDataReportConnector { /** * Runs freemarker against the 3 sql queries , then executes them in order .
* { @ inheritDoc } */
@ Override public void runReport ( Map < String , Object > extra ) { } } | PreparedStatement prestatement = null ; PreparedStatement poststatement = null ; PreparedStatement statement = null ; try { getStartConnection ( ) ; if ( StringUtils . isNotBlank ( presql ) ) { FreemarkerSQLResult prefreemarkerSQLResult = freemakerParams ( extra , false , presql ) ; prestatement = connection . prepareStatement ( prefreemarkerSQLResult . getSql ( ) ) ; for ( int i = 0 ; i < prefreemarkerSQLResult . getParams ( ) . size ( ) ; i ++ ) { prestatement . setObject ( i + 1 , prefreemarkerSQLResult . getParams ( ) . get ( i ) ) ; } prestatement . setQueryTimeout ( queryTimeout ) ; prestatement . execute ( ) ; } FreemarkerSQLResult freemarkerSQLResult = freemakerParams ( extra , true , freemarkerSql ) ; statement = connection . prepareStatement ( freemarkerSQLResult . getSql ( ) ) ; for ( int i = 0 ; i < freemarkerSQLResult . getParams ( ) . size ( ) ; i ++ ) { statement . setObject ( i + 1 , freemarkerSQLResult . getParams ( ) . get ( i ) ) ; } statement . setQueryTimeout ( queryTimeout ) ; rows = resultSetToMap ( statement . executeQuery ( ) ) ; if ( StringUtils . isNotBlank ( postsql ) ) { FreemarkerSQLResult postfreemarkerSQLResult = freemakerParams ( extra , false , postsql ) ; poststatement = connection . prepareStatement ( postfreemarkerSQLResult . getSql ( ) ) ; for ( int i = 0 ; i < postfreemarkerSQLResult . getParams ( ) . size ( ) ; i ++ ) { poststatement . setObject ( i + 1 , postfreemarkerSQLResult . getParams ( ) . get ( i ) ) ; } poststatement . setQueryTimeout ( queryTimeout ) ; poststatement . execute ( ) ; } } catch ( Exception ex ) { errors . add ( ex . getMessage ( ) ) ; } finally { try { if ( statement != null && ! statement . isClosed ( ) ) { statement . close ( ) ; statement = null ; } if ( prestatement != null && ! prestatement . isClosed ( ) ) { prestatement . close ( ) ; prestatement = null ; } if ( poststatement != null && ! poststatement . isClosed ( ) ) { poststatement . close ( ) ; poststatement = null ; } if ( connection != null && ! connection . isClosed ( ) ) { connection . close ( ) ; connection = null ; } } catch ( SQLException e ) { errors . add ( e . getMessage ( ) ) ; e . printStackTrace ( ) ; } } |
public class ENU { /** * Converts WGS84 coordinates to Earth - Centered Earth - Fixed ( ECEF ) coordinates .
* @ param cLL the wgs84 coordinate .
* @ return the ecef coordinate . */
public Coordinate wgs84ToEcef ( Coordinate cLL ) { } } | double lambda = toRadians ( cLL . y ) ; double phi = toRadians ( cLL . x ) ; double sinLambda = sin ( lambda ) ; double cosLambda = cos ( lambda ) ; double cosPhi = cos ( phi ) ; double sinPhi = sin ( phi ) ; double N = semiMajorAxis / sqrt ( 1 - eccentricityP2 * pow ( sinLambda , 2.0 ) ) ; double h = cLL . z ; double x = ( h + N ) * cosLambda * cosPhi ; double y = ( h + N ) * cosLambda * sinPhi ; double z = ( h + ( 1 - eccentricityP2 ) * N ) * sinLambda ; return new Coordinate ( x , y , z ) ; |
public class LineSegment { /** * Intersection of this LineSegment with the Rectangle as another LineSegment .
* Algorithm is Cohen - Sutherland , see https : / / en . wikipedia . org / wiki / Cohen % E2%80%93Sutherland _ algorithm .
* @ param r the rectangle to clip to .
* @ return the LineSegment that falls into the Rectangle , null if there is no intersection . */
public LineSegment clipToRectangle ( Rectangle r ) { } } | Point a = this . start ; Point b = this . end ; int codeStart = code ( r , a ) ; int codeEnd = code ( r , b ) ; while ( true ) { if ( 0 == ( codeStart | codeEnd ) ) { // both points are inside , intersection is the computed line
return new LineSegment ( a , b ) ; } else if ( 0 != ( codeStart & codeEnd ) ) { // both points are either below , above , left or right of the box , no intersection
return null ; } else { double newX ; double newY ; // At least one endpoint is outside the clip rectangle ; pick it .
int outsideCode = ( 0 != codeStart ) ? codeStart : codeEnd ; if ( 0 != ( outsideCode & TOP ) ) { // point is above the clip rectangle
newX = a . x + ( b . x - a . x ) * ( r . top - a . y ) / ( b . y - a . y ) ; newY = r . top ; } else if ( 0 != ( outsideCode & BOTTOM ) ) { // point is below the clip rectangle
newX = a . x + ( b . x - a . x ) * ( r . bottom - a . y ) / ( b . y - a . y ) ; newY = r . bottom ; } else if ( 0 != ( outsideCode & RIGHT ) ) { // point is to the right of clip rectangle
newY = a . y + ( b . y - a . y ) * ( r . right - a . x ) / ( b . x - a . x ) ; newX = r . right ; } else if ( 0 != ( outsideCode & LEFT ) ) { // point is to the left of clip rectangle
newY = a . y + ( b . y - a . y ) * ( r . left - a . x ) / ( b . x - a . x ) ; newX = r . left ; } else { throw new IllegalStateException ( "Should not get here" ) ; } // Now we move outside point to intersection point to clip
// and get ready for next pass .
if ( outsideCode == codeStart ) { a = new Point ( newX , newY ) ; codeStart = code ( r , a ) ; } else { b = new Point ( newX , newY ) ; codeEnd = code ( r , b ) ; } } } |
public class BugChecker { /** * Returns a new builder for { @ link Description } s .
* @ param position the position of the error
* @ param checker the { @ code BugChecker } instance that is producing this { @ code Description } */
@ CheckReturnValue public static Description . Builder buildDescriptionFromChecker ( DiagnosticPosition position , BugChecker checker ) { } } | return Description . builder ( position , checker . canonicalName ( ) , checker . linkUrl ( ) , checker . defaultSeverity ( ) , checker . message ( ) ) ; |
public class LdiSrl { /** * Extract front sub - string from last - found delimiter ignoring case .
* < pre >
* substringLastFront ( " foo . bar / baz . qux " , " A " , " U " )
* returns " foo . bar / baz . q "
* < / pre >
* @ param str The target string . ( NotNull )
* @ param delimiters The array of delimiters . ( NotNull )
* @ return The part of string . ( NotNull : if delimiter not found , returns argument - plain string ) */
public static String substringLastFrontIgnoreCase ( String str , String ... delimiters ) { } } | assertStringNotNull ( str ) ; return doSubstringFirstRear ( true , false , true , str , delimiters ) ; |
public class FeatureSet { /** * Parses known strings into feature sets . */
public static FeatureSet valueOf ( String name ) { } } | switch ( name ) { case "es3" : return ES3 ; case "es5" : return ES5 ; case "es6-impl" : case "es6" : return ES6 ; case "typeCheckSupported" : return TYPE_CHECK_SUPPORTED ; case "es7" : return ES7 ; case "es8" : return ES8 ; case "es2018" : case "es9" : return ES2018 ; case "es_2019" : return ES2019 ; case "es_next" : return ES_NEXT ; case "ts" : return TYPESCRIPT ; default : throw new IllegalArgumentException ( "No such FeatureSet: " + name ) ; } |
public class BatchUnsuspendUserRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( BatchUnsuspendUserRequest batchUnsuspendUserRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( batchUnsuspendUserRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( batchUnsuspendUserRequest . getAccountId ( ) , ACCOUNTID_BINDING ) ; protocolMarshaller . marshall ( batchUnsuspendUserRequest . getUserIdList ( ) , USERIDLIST_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class PersistenceApi { /** * Bulk Save Managed Entities
* This is used to batch save entities in order to provide optimized throughput .
* @ param request Save Entities Request ( required )
* @ return ApiResponse & lt ; Void & gt ;
* @ throws ApiException If fail to call the API , e . g . server error or cannot deserialize the response body */
public ApiResponse < Void > saveEntitiesPostWithHttpInfo ( SaveEntitiesRequest request ) throws ApiException { } } | com . squareup . okhttp . Call call = saveEntitiesPostValidateBeforeCall ( request , null , null ) ; return apiClient . execute ( call ) ; |
public class ConsoleSink { /** * Gets the polling period .
* @ return the polling period set by properties . If it is not set , a default value 10 is
* returned . */
private int getPollPeriod ( ) { } } | String period = mProperties . getProperty ( CONSOLE_KEY_PERIOD ) ; return period != null ? Integer . parseInt ( period ) : CONSOLE_DEFAULT_PERIOD ; |
public class AbstractListBinder { /** * Applies any context or preset value .
* @ param binding
* the binding to apply the values
* @ param context
* contains context dependent values */
protected void applyContext ( AbstractListBinding binding , Map context ) { } } | if ( context . containsKey ( SELECTABLE_ITEMS_KEY ) ) { binding . setSelectableItems ( decorate ( context . get ( SELECTABLE_ITEMS_KEY ) , selectableItems ) ) ; } else if ( selectableItems != null ) { binding . setSelectableItems ( selectableItems ) ; } if ( context . containsKey ( COMPARATOR_KEY ) ) { binding . setComparator ( ( Comparator ) decorate ( context . get ( COMPARATOR_KEY ) , comparator ) ) ; } else if ( comparator != null ) { binding . setComparator ( comparator ) ; } if ( context . containsKey ( FILTER_KEY ) ) { binding . setFilter ( ( Constraint ) decorate ( context . get ( FILTER_KEY ) , filter ) ) ; } else if ( filter != null ) { binding . setFilter ( filter ) ; } |
public class SimpleRasterizer { /** * Renders all edges added so far , and removes them .
* Calls startAddingEdges after it ' s done .
* @ param fillMode Fill mode for the polygon fill can be one of two values : EVEN _ ODD or WINDING .
* Note , as any other graphics algorithm , the scan line rasterizer doesn ' t require polygons
* to be topologically simple , or have correct ring orientation . */
public final void renderEdges ( int fillMode ) { } } | evenOdd_ = fillMode == EVEN_ODD ; for ( int line = minY_ ; line <= maxY_ ; line ++ ) { advanceAET_ ( ) ; addNewEdgesToAET_ ( line ) ; emitScans_ ( ) ; } startAddingEdges ( ) ; // reset for new edges |
public class OptionsCheckForUpdatesPanel { /** * This method initializes chkProcessImages
* @ return javax . swing . JCheckBox */
private JCheckBox getChkCheckOnStart ( ) { } } | if ( chkCheckOnStart == null ) { chkCheckOnStart = new JCheckBox ( ) ; chkCheckOnStart . setText ( Constant . messages . getString ( "cfu.options.startUp" ) ) ; chkCheckOnStart . setVerticalAlignment ( javax . swing . SwingConstants . TOP ) ; chkCheckOnStart . setVerticalTextPosition ( javax . swing . SwingConstants . TOP ) ; chkCheckOnStart . addItemListener ( new ItemListener ( ) { @ Override public void itemStateChanged ( ItemEvent e ) { setCheckBoxStates ( ) ; } } ) ; } return chkCheckOnStart ; |
public class IndexingConfigurationImpl { /** * Gets the condition expression from the configuration .
* @ param config
* the config node .
* @ return the condition expression or < code > null < / code > if there is no
* condition set on the < code > config < / code > .
* @ throws MalformedPathException
* if the condition string is malformed .
* @ throws IllegalNameException
* if a name contains illegal characters .
* @ throws RepositoryException */
private PathExpression getCondition ( Node config ) throws IllegalNameException , RepositoryException { } } | Node conditionAttr = config . getAttributes ( ) . getNamedItem ( "condition" ) ; if ( conditionAttr == null ) { return null ; } String conditionString = conditionAttr . getNodeValue ( ) ; int idx ; int axis ; InternalQName elementTest = null ; InternalQName nameTest = null ; InternalQName propertyName ; String propertyValue ; // parse axis
if ( conditionString . startsWith ( "ancestor::" ) ) { axis = PathExpression . ANCESTOR ; idx = "ancestor::" . length ( ) ; } else if ( conditionString . startsWith ( "parent::" ) ) { axis = PathExpression . PARENT ; idx = "parent::" . length ( ) ; } else if ( conditionString . startsWith ( "@" ) ) { axis = PathExpression . SELF ; idx = "@" . length ( ) ; } else { axis = PathExpression . CHILD ; idx = 0 ; } try { if ( conditionString . startsWith ( "element(" , idx ) ) { int colon = conditionString . indexOf ( ',' , idx + "element(" . length ( ) ) ; String name = conditionString . substring ( idx + "element(" . length ( ) , colon ) . trim ( ) ; if ( ! name . equals ( "*" ) ) { nameTest = resolver . parseJCRName ( ISO9075 . decode ( name ) ) . getInternalName ( ) ; } idx = conditionString . indexOf ( ")/@" , colon ) ; String type = conditionString . substring ( colon + 1 , idx ) . trim ( ) ; elementTest = resolver . parseJCRName ( ISO9075 . decode ( type ) ) . getInternalName ( ) ; idx += ")/@" . length ( ) ; } else { if ( axis == PathExpression . ANCESTOR || axis == PathExpression . CHILD || axis == PathExpression . PARENT ) { // simple name test
String name = conditionString . substring ( idx , conditionString . indexOf ( '/' , idx ) ) ; if ( ! name . equals ( "*" ) ) { nameTest = resolver . parseJCRName ( ISO9075 . decode ( name ) ) . getInternalName ( ) ; } idx += name . length ( ) + "/@" . length ( ) ; } } // parse property name
int eq = conditionString . indexOf ( '=' , idx ) ; String name = conditionString . substring ( idx , eq ) . trim ( ) ; propertyName = resolver . parseJCRName ( ISO9075 . decode ( name ) ) . getInternalName ( ) ; // parse string value
int quote = conditionString . indexOf ( '\'' , eq ) + 1 ; propertyValue = conditionString . substring ( quote , conditionString . indexOf ( '\'' , quote ) ) ; } catch ( IndexOutOfBoundsException e ) { throw new RepositoryException ( conditionString ) ; } return new PathExpression ( axis , elementTest , nameTest , propertyName , propertyValue ) ; |
public class BlockInStream { /** * Creates a { @ link BlockInStream } to read from a gRPC data server .
* @ param context the file system context
* @ param address the address of the gRPC data server
* @ param blockSource the source location of the block
* @ param blockSize the block size
* @ param readRequestPartial the partial read request
* @ return the { @ link BlockInStream } created */
private static BlockInStream createGrpcBlockInStream ( FileSystemContext context , WorkerNetAddress address , BlockInStreamSource blockSource , ReadRequest readRequestPartial , long blockSize , InStreamOptions options ) { } } | ReadRequest . Builder readRequestBuilder = readRequestPartial . toBuilder ( ) ; long chunkSize = context . getClusterConf ( ) . getBytes ( PropertyKey . USER_NETWORK_READER_CHUNK_SIZE_BYTES ) ; readRequestBuilder . setChunkSize ( chunkSize ) ; DataReader . Factory factory = new GrpcDataReader . Factory ( context , address , readRequestBuilder . build ( ) ) ; return new BlockInStream ( factory , address , blockSource , readRequestPartial . getBlockId ( ) , blockSize ) ; |
public class DefaultGitHubClient { /** * Makes use of the graphQL endpoint , will not work for REST api */
private JSONObject getDataFromRestCallPost ( GitHubParsed gitHubParsed , GitHubRepo repo , String password , String personalAccessToken , JSONObject query ) throws MalformedURLException , HygieiaException { } } | ResponseEntity < String > response = makeRestCallPost ( gitHubParsed . getGraphQLUrl ( ) , repo . getUserId ( ) , password , personalAccessToken , query ) ; JSONObject data = ( JSONObject ) parseAsObject ( response ) . get ( "data" ) ; JSONArray errors = getArray ( parseAsObject ( response ) , "errors" ) ; if ( CollectionUtils . isEmpty ( errors ) ) { return data ; } JSONObject error = ( JSONObject ) errors . get ( 0 ) ; if ( ! error . containsKey ( "type" ) || ! error . get ( "type" ) . equals ( "NOT_FOUND" ) ) { throw new HygieiaException ( "Error in GraphQL query:" + errors . toJSONString ( ) , HygieiaException . JSON_FORMAT_ERROR ) ; } RedirectedStatus redirectedStatus = checkForRedirectedRepo ( repo ) ; if ( ! redirectedStatus . isRedirected ( ) ) { throw new HygieiaException ( "Error in GraphQL query:" + errors . toJSONString ( ) , HygieiaException . JSON_FORMAT_ERROR ) ; } String redirectedUrl = redirectedStatus . getRedirectedUrl ( ) ; LOG . debug ( "Repo was redirected from: " + repo . getRepoUrl ( ) + " to " + redirectedUrl ) ; repo . setRepoUrl ( redirectedUrl ) ; gitHubParsed . updateForRedirect ( redirectedUrl ) ; JSONParser parser = new JSONParser ( ) ; try { JSONObject variableJSON = ( JSONObject ) parser . parse ( str ( query , "variables" ) ) ; variableJSON . put ( "name" , gitHubParsed . getRepoName ( ) ) ; variableJSON . put ( "owner" , gitHubParsed . getOrgName ( ) ) ; query . put ( "variables" , variableJSON . toString ( ) ) ; } catch ( ParseException e ) { LOG . error ( "Could not parse JSON String" , e ) ; } return getDataFromRestCallPost ( gitHubParsed , repo , password , personalAccessToken , query ) ; |
public class GeneratedDUserDaoImpl { /** * query - by method for field phoneNumber1
* @ param phoneNumber1 the specified attribute
* @ return an Iterable of DUsers for the specified phoneNumber1 */
public Iterable < DUser > queryByPhoneNumber1 ( java . lang . String phoneNumber1 ) { } } | return queryByField ( null , DUserMapper . Field . PHONENUMBER1 . getFieldName ( ) , phoneNumber1 ) ; |
public class HashUtils { /** * Hashes data with the specified hashing algorithm . Returns a hexadecimal result .
* @ since 1.1
* @ param data the data to hash
* @ param alg the hashing algorithm to use
* @ return the hexadecimal hash of the data
* @ throws NoSuchAlgorithmException the algorithm is not supported by existing providers */
public static String hashHex ( byte [ ] data , HashAlgorithm alg ) throws NoSuchAlgorithmException { } } | return hashHex ( data , alg . toString ( ) ) ; |
public class CurationManager { /** * Look through all known related objects and assess their readiness . Can
* optionally send downstream curation requests if required , and update a
* relationship based on responses .
* @ param response
* The response currently being built
* @ param data
* The object ' s data
* @ param oid
* The object ' s ID
* @ param sendRequests
* True if curation requests should be sent out
* @ param childOid
* @ returns boolean True if all ' children ' have been curated .
* @ throws TransactionException
* If an error occurs */
private boolean checkChildren ( JsonSimple response , JsonSimple data , String thisOid , String thisPid , boolean sendRequests , String childOid , String childId , String curatedPid ) throws TransactionException { } } | boolean isReady = true ; boolean saveData = false ; log . debug ( "Checking Children of '{}'" , thisOid ) ; JSONArray relations = data . writeArray ( "relationships" ) ; for ( Object relation : relations ) { JsonSimple json = new JsonSimple ( ( JsonObject ) relation ) ; String broker = json . getString ( brokerUrl , "broker" ) ; boolean localRecord = broker . equals ( brokerUrl ) ; String relatedId = json . getString ( null , "identifier" ) ; // We need to find OIDs to match IDs ( only for local records )
String relatedOid = json . getString ( null , "oid" ) ; if ( relatedOid == null && localRecord ) { String identifier = json . getString ( null , "identifier" ) ; if ( identifier == null ) { throw new TransactionException ( "NULL identifer provided!" ) ; } relatedOid = idToOid ( identifier ) ; if ( relatedOid == null ) { throw new TransactionException ( "Cannot resolve identifer: " + identifier ) ; } ( ( JsonObject ) relation ) . put ( "oid" , relatedOid ) ; saveData = true ; } // Are we updating a relationship . . . and is it this one ?
boolean updatingById = ( childId != null && childId . equals ( relatedId ) ) ; boolean updatingByOid = ( childOid != null && childOid . equals ( relatedOid ) ) ; if ( curatedPid != null && ( updatingById || updatingByOid ) ) { log . debug ( "Updating..." ) ; ( ( JsonObject ) relation ) . put ( "isCurated" , true ) ; ( ( JsonObject ) relation ) . put ( "curatedPid" , curatedPid ) ; saveData = true ; } // Is this relationship using a curated ID ?
boolean isCurated = json . getBoolean ( false , "isCurated" ) ; if ( ! isCurated ) { log . debug ( " * Needs curation '{}'" , relatedId ) ; boolean optional = json . getBoolean ( false , "optional" ) ; if ( ! optional ) { isReady = false ; } // Only send out curation requests if asked to
if ( sendRequests ) { JsonObject task ; // It is a local object
if ( localRecord ) { task = createTask ( response , relatedOid , "curation-query" ) ; // Or remote
} else { task = createTask ( response , broker , relatedOid , "curation-query" ) ; // We won ' t know OIDs for remote systems
task . remove ( "oid" ) ; task . put ( "identifier" , relatedId ) ; } // If this record is the authority on the relationship
// make sure we tell the other object what its relationship
// back to us should be .
boolean authority = json . getBoolean ( false , "authority" ) ; if ( authority ) { // Send a full request rather then a query , we need it
// to propogate through children
task . put ( "task" , "curation-request" ) ; // Let the other object know its reverse relationship
// with us and that we ' ve already been curated .
String reverseRelationship = json . getString ( "hasAssociationWith" , "reverseRelationship" ) ; JsonObject relObject = new JsonObject ( ) ; relObject . put ( "identifier" , thisPid ) ; relObject . put ( "curatedPid" , thisPid ) ; relObject . put ( "broker" , brokerUrl ) ; relObject . put ( "isCurated" , true ) ; relObject . put ( "relationship" , reverseRelationship ) ; // Make sure we send OID to local records
if ( localRecord ) { relObject . put ( "oid" , thisOid ) ; } JSONArray newRelations = new JSONArray ( ) ; newRelations . add ( relObject ) ; task . put ( "relationships" , newRelations ) ; } // And make sure it knows how to send us curated PIDs
JsonObject msgResponse = new JsonObject ( ) ; msgResponse . put ( "broker" , brokerUrl ) ; msgResponse . put ( "oid" , thisOid ) ; msgResponse . put ( "task" , "curation-pending" ) ; task . put ( "respond" , msgResponse ) ; } } else { log . debug ( " * Already curated '{}'" , relatedId ) ; } } // Save our data if we changed it
if ( saveData ) { saveObjectData ( data , thisOid ) ; } return isReady ; |
public class IntTupleIterators { /** * Returns an iterator that returns { @ link MutableIntTuple } s in the
* given range , incremented in the given { @ link Order } . If the given
* { @ link Order } is < code > null < / code > , then < code > null < / code > will
* be returned . < br >
* < br >
* Also see < a href = " . . / . . / package - summary . html # IterationOrder " >
* Iteration Order < / a >
* @ param order The { @ link Order }
* @ param min The minimum values , inclusive
* @ param max The maximum values , exclusive
* @ return The iterator
* @ see # lexicographicalIterator ( IntTuple , IntTuple )
* @ see # colexicographicalIterator ( IntTuple , IntTuple ) */
public static Iterator < MutableIntTuple > iterator ( Order order , IntTuple min , IntTuple max ) { } } | if ( order == null ) { return null ; } IntTuple localMin = IntTuples . copy ( min ) ; IntTuple localMax = IntTuples . copy ( max ) ; return new IntTupleIterator ( localMin , localMax , IntTupleIncrementors . incrementor ( order ) ) ; |
public class ReplacedText { /** * Checks whether the layout is computed and recomputes it when necessary . */
private void checkLayout ( ) { } } | Dimension dim = getLayoutDimension ( ) ; if ( currentDimension == null || ! currentDimension . equals ( dim ) ) // the dimension has changed
{ createLayout ( dim ) ; // containing box for the new viewport
viewport . setContainingBlockBox ( owner ) ; if ( owner instanceof BlockBox ) viewport . clipByBlock ( ( BlockBox ) owner ) ; owner . removeAllSubBoxes ( ) ; owner . addSubBox ( viewport ) ; currentDimension = new Dimension ( dim ) ; } |
public class ServiceManager { /** * DS method for deactivating this component .
* @ param context */
protected synchronized void deactivate ( ComponentContext context ) { } } | cfwBundleRef . deactivate ( context ) ; scheduledExecSvcRef . deactivate ( context ) ; injectionServiceSRRef . deactivate ( context ) ; injectionService12SRRef . deactivate ( context ) ; executorServiceRef . deactivate ( context ) ; injectionEngineSRRef . deactivate ( context ) ; |
public class TransformerHandlerImpl { /** * Filter a start document event .
* @ throws SAXException The client may throw
* an exception during processing .
* @ see org . xml . sax . ContentHandler # startDocument */
public void startDocument ( ) throws SAXException { } } | if ( DEBUG ) System . out . println ( "TransformerHandlerImpl#startDocument" ) ; m_insideParse = true ; // Thread listener = new Thread ( m _ transformer ) ;
if ( m_contentHandler != null ) { // m _ transformer . setTransformThread ( listener ) ;
if ( m_incremental ) { m_transformer . setSourceTreeDocForThread ( m_dtm . getDocument ( ) ) ; int cpriority = Thread . currentThread ( ) . getPriority ( ) ; // runTransformThread is equivalent with the 2.0.1 code ,
// except that the Thread may come from a pool .
m_transformer . runTransformThread ( cpriority ) ; } // This is now done _ last _ , because IncrementalSAXSource _ Filter
// will immediately go into a " wait until events are requested "
// pause . I believe that will close our timing window .
// % REVIEW %
m_contentHandler . startDocument ( ) ; } // listener . setDaemon ( false ) ;
// listener . start ( ) ; |
public class Profiler { /** * Stop and obtain the self execution time of methods , each as a row in CSV
* format .
* @ return the execution time of methods in CSV format */
public String getMethodCsv ( ) { } } | stopCollecting ( ) ; StringBuilder buff = new StringBuilder ( ) ; buff . append ( "Method,Self" ) . append ( LINE_SEPARATOR ) ; for ( String k : new TreeSet < String > ( selfMethods . keySet ( ) ) ) { int percent = 100 * selfMethods . get ( k ) / Math . max ( total , 1 ) ; buff . append ( k ) . append ( "," ) . append ( percent ) . append ( LINE_SEPARATOR ) ; } return buff . toString ( ) ; |
public class ResourceIndexImpl { /** * { @ inheritDoc } */
public void add ( List < Triple > triples , boolean flush ) throws IOException , TrippiException { } } | _writer . add ( triples , flush ) ; |
public class SwiffyFallbackAsset { /** * Gets the asset value for this SwiffyFallbackAsset .
* @ return asset * The Swiffy asset . */
public com . google . api . ads . admanager . axis . v201808 . CreativeAsset getAsset ( ) { } } | return asset ; |
public class AbstractIncrementalGenerator { /** * Generates the the default constructor .
* @ param sourceWriter is the { @ link SourceWriter } .
* @ param simpleName is the { @ link Class # getSimpleName ( ) simple name } . */
protected void generateDefaultConstructor ( SourceWriter sourceWriter , String simpleName ) { } } | generateSourcePublicConstructorDeclaration ( sourceWriter , simpleName ) ; sourceWriter . println ( "super();" ) ; generateSourceCloseBlock ( sourceWriter ) ; |
public class Cooccurrence { /** * getter for firstIds - gets A list of string ids to identify the first occurrence
* @ generated
* @ return value of the feature */
public StringArray getFirstIds ( ) { } } | if ( Cooccurrence_Type . featOkTst && ( ( Cooccurrence_Type ) jcasType ) . casFeat_firstIds == null ) jcasType . jcas . throwFeatMissing ( "firstIds" , "ch.epfl.bbp.uima.types.Cooccurrence" ) ; return ( StringArray ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Cooccurrence_Type ) jcasType ) . casFeatCode_firstIds ) ) ) ; |
public class CommandLine { /** * Retrieves the array of values , if any , of an option .
* @ param opt string name of the option
* @ return Values of the argument if option is set , and has an argument ,
* otherwise null . */
public String [ ] getOptionValues ( String opt ) { } } | List < String > values = new ArrayList < String > ( ) ; for ( Option option : options ) { if ( opt . equals ( option . getOpt ( ) ) || opt . equals ( option . getLongOpt ( ) ) ) { values . addAll ( option . getValuesList ( ) ) ; } } return values . isEmpty ( ) ? null : values . toArray ( new String [ values . size ( ) ] ) ; |
public class MtasDataDoubleOperations { /** * ( non - Javadoc )
* @ see mtas . codec . util . DataCollector . MtasDataOperations # product11 ( java . lang .
* Number , java . lang . Number ) */
@ Override public Double product11 ( Double arg1 , Double arg2 ) { } } | if ( arg1 == null || arg2 == null ) { return Double . NaN ; } else { return arg1 * arg2 ; } |
public class CompressionUtils { /** * Copy inputStream to out while wrapping out in a GZIPOutputStream
* Closes both input and output
* @ param inputStream The input stream to copy data from . This stream is closed
* @ param out The output stream to wrap in a GZIPOutputStream before copying . This stream is closed
* @ return The size of the data copied
* @ throws IOException */
public static long gzip ( InputStream inputStream , OutputStream out ) throws IOException { } } | try ( GZIPOutputStream outputStream = new GZIPOutputStream ( out ) ) { final long result = ByteStreams . copy ( inputStream , outputStream ) ; out . flush ( ) ; return result ; } finally { inputStream . close ( ) ; } |
public class ExpressRouteCircuitConnectionsInner { /** * Creates or updates a Express Route Circuit Connection in the specified express route circuits .
* @ param resourceGroupName The name of the resource group .
* @ param circuitName The name of the express route circuit .
* @ param peeringName The name of the peering .
* @ param connectionName The name of the express route circuit connection .
* @ param expressRouteCircuitConnectionParameters Parameters supplied to the create or update express route circuit circuit connection operation .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable for the request */
public Observable < ExpressRouteCircuitConnectionInner > createOrUpdateAsync ( String resourceGroupName , String circuitName , String peeringName , String connectionName , ExpressRouteCircuitConnectionInner expressRouteCircuitConnectionParameters ) { } } | return createOrUpdateWithServiceResponseAsync ( resourceGroupName , circuitName , peeringName , connectionName , expressRouteCircuitConnectionParameters ) . map ( new Func1 < ServiceResponse < ExpressRouteCircuitConnectionInner > , ExpressRouteCircuitConnectionInner > ( ) { @ Override public ExpressRouteCircuitConnectionInner call ( ServiceResponse < ExpressRouteCircuitConnectionInner > response ) { return response . body ( ) ; } } ) ; |
public class WorkerPools { /** * region getInstances overloads */
public < T > List < T > getInstances ( Class < T > type ) { } } | return getInstances ( Key . get ( type ) ) ; |
public class ReflectionUtils { public static Object newInstance ( String className , Object ... parameters ) { } } | try { Class < ? > objClass = Class . forName ( className ) ; Constructor < ? > constructor = getConstructor ( objClass , parameters ) ; if ( constructor != null ) { return constructor . newInstance ( parameters ) ; } } catch ( Exception e ) { } return null ; |
public class DescribeEvaluationsResult { /** * A list of < code > Evaluation < / code > that meet the search criteria .
* < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use
* { @ link # setResults ( java . util . Collection ) } or { @ link # withResults ( java . util . Collection ) } if you want to override
* the existing values .
* @ param results
* A list of < code > Evaluation < / code > that meet the search criteria .
* @ return Returns a reference to this object so that method calls can be chained together . */
public DescribeEvaluationsResult withResults ( Evaluation ... results ) { } } | if ( this . results == null ) { setResults ( new com . amazonaws . internal . SdkInternalList < Evaluation > ( results . length ) ) ; } for ( Evaluation ele : results ) { this . results . add ( ele ) ; } return this ; |
public class AutoScalingPolicyStateChangeReasonMarshaller { /** * Marshall the given parameter object . */
public void marshall ( AutoScalingPolicyStateChangeReason autoScalingPolicyStateChangeReason , ProtocolMarshaller protocolMarshaller ) { } } | if ( autoScalingPolicyStateChangeReason == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( autoScalingPolicyStateChangeReason . getCode ( ) , CODE_BINDING ) ; protocolMarshaller . marshall ( autoScalingPolicyStateChangeReason . getMessage ( ) , MESSAGE_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class DBEngineVersion { /** * A list of features supported by the DB engine . Supported feature names include the following .
* < ul >
* < li >
* s3Import
* < / li >
* < / ul >
* @ param supportedFeatureNames
* A list of features supported by the DB engine . Supported feature names include the following . < / p >
* < ul >
* < li >
* s3Import
* < / li > */
public void setSupportedFeatureNames ( java . util . Collection < String > supportedFeatureNames ) { } } | if ( supportedFeatureNames == null ) { this . supportedFeatureNames = null ; return ; } this . supportedFeatureNames = new com . amazonaws . internal . SdkInternalList < String > ( supportedFeatureNames ) ; |
public class VDirectory { /** * * * * * * DIRECTORIES * * * * * / / */
public VDirectory getDirectoryCreate ( String name ) { } } | VDirectory child = new VDirectory ( this , name ) ; child . create ( ) ; return child ; |
public class BeliefPropagation { /** * Sends the message that is currently " pending " for this edge . This just
* copies the message in the " pending slot " to the " message slot " for this
* edge .
* @ param edge The edge over which the message should be sent .
* @ param iter The current iteration . */
private void forwardSendMessage ( int edge , int iter ) { } } | // Update the residual
double oldResidual = residuals [ edge ] ; residuals [ edge ] = smartResidual ( msgs [ edge ] , newMsgs [ edge ] , edge ) ; if ( oldResidual > prm . convergenceThreshold && residuals [ edge ] <= prm . convergenceThreshold ) { // This message has ( newly ) converged .
numConverged ++ ; } if ( oldResidual <= prm . convergenceThreshold && residuals [ edge ] > prm . convergenceThreshold ) { // This message was marked as converged , but is no longer converged .
numConverged -- ; } // Check for oscillation . Did the argmax change ?
if ( log . isTraceEnabled ( ) && iter > 0 ) { if ( msgs [ edge ] . getArgmaxConfigId ( ) != newMsgs [ edge ] . getArgmaxConfigId ( ) ) { oscillationCount . incrementAndGet ( ) ; } sendCount . incrementAndGet ( ) ; log . trace ( "Residual: {} {}" , fg . edgeToString ( edge ) , residuals [ edge ] ) ; } // Update the cached belief .
int child = bg . childE ( edge ) ; if ( ! bg . isT1T2 ( edge ) && bg . numNbsT1 ( child ) >= prm . minVarNbsForCache ) { varBeliefs [ child ] . elemDivBP ( msgs [ edge ] ) ; varBeliefs [ child ] . elemMultiply ( newMsgs [ edge ] ) ; assert ! varBeliefs [ child ] . containsBadValues ( ) : "varBeliefs[child] = " + varBeliefs [ child ] ; } else if ( bg . isT1T2 ( edge ) && bg . numNbsT2 ( child ) >= prm . minFacNbsForCache ) { Factor f = bg . t2E ( edge ) ; if ( ! ( f instanceof GlobalFactor ) ) { facBeliefs [ child ] . divBP ( msgs [ edge ] ) ; facBeliefs [ child ] . prod ( newMsgs [ edge ] ) ; assert ! facBeliefs [ child ] . containsBadValues ( ) : "facBeliefs[child] = " + facBeliefs [ child ] ; } } // Send message : Just swap the pointers to the current message and the new message , so
// that we don ' t have to create a new factor object .
VarTensor oldMessage = msgs [ edge ] ; msgs [ edge ] = newMsgs [ edge ] ; newMsgs [ edge ] = oldMessage ; assert ! msgs [ edge ] . containsBadValues ( ) : "msgs[edge] = " + msgs [ edge ] ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Message sent: {} {}" , fg . edgeToString ( edge ) , msgs [ edge ] ) ; } |
public class JmsSessionImpl { /** * This method is called by a JmsQueueBrowser in order to remove itself from
* the list of Browsers held by the Session .
* @ param JmsQueueBrowser The Browser which is calling this method . */
void removeBrowser ( JmsQueueBrowserImpl browser ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( this , tc , "removeBrowser" , browser ) ; browsers . remove ( browser ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( this , tc , "removeBrowser" ) ; |
public class Api { /** * List Streaming profiles
* @ param options additional options
* @ return a list of all streaming profiles defined for the current cloud
* @ throws Exception an exception */
public ApiResponse listStreamingProfiles ( Map options ) throws Exception { } } | if ( options == null ) options = ObjectUtils . emptyMap ( ) ; List < String > uri = Collections . singletonList ( "streaming_profiles" ) ; return callApi ( HttpMethod . GET , uri , ObjectUtils . emptyMap ( ) , options ) ; |
public class PooledObject { /** * Clear leak track */
public void clear ( ) { } } | Optional . ofNullable ( phantomReference ) . ifPresent ( ref -> pool . getLeakDetector ( ) . clear ( ref ) ) ; |
public class PolicyChecker { /** * Merges the specified inhibitAnyPolicy value with the
* SkipCerts value of the InhibitAnyPolicy
* extension obtained from the certificate .
* @ param inhibitAnyPolicy an integer which indicates whether
* " any - policy " is considered a match
* @ param currCert the Certificate to be processed
* @ return returns the new inhibitAnyPolicy value
* @ exception CertPathValidatorException Exception thrown if an error
* occurs */
static int mergeInhibitAnyPolicy ( int inhibitAnyPolicy , X509CertImpl currCert ) throws CertPathValidatorException { } } | if ( ( inhibitAnyPolicy > 0 ) && ! X509CertImpl . isSelfIssued ( currCert ) ) { inhibitAnyPolicy -- ; } try { InhibitAnyPolicyExtension inhAnyPolExt = ( InhibitAnyPolicyExtension ) currCert . getExtension ( InhibitAnyPolicy_Id ) ; if ( inhAnyPolExt == null ) return inhibitAnyPolicy ; int skipCerts = inhAnyPolExt . get ( InhibitAnyPolicyExtension . SKIP_CERTS ) . intValue ( ) ; if ( debug != null ) debug . println ( "PolicyChecker.mergeInhibitAnyPolicy() " + "skipCerts Index from cert = " + skipCerts ) ; if ( skipCerts != - 1 ) { if ( skipCerts < inhibitAnyPolicy ) { inhibitAnyPolicy = skipCerts ; } } } catch ( IOException e ) { if ( debug != null ) { debug . println ( "PolicyChecker.mergeInhibitAnyPolicy " + "unexpected exception" ) ; e . printStackTrace ( ) ; } throw new CertPathValidatorException ( e ) ; } return inhibitAnyPolicy ; |
public class JavacServer { /** * Log this message . */
public void log ( String msg ) { } } | if ( theLog != null ) { theLog . println ( msg ) ; } else { System . err . println ( msg ) ; } |
public class AbstractBigtableConnection { /** * { @ inheritDoc } */
@ Override public void abort ( final String msg , Throwable t ) { } } | if ( t != null ) { LOG . fatal ( msg , t ) ; } else { LOG . fatal ( msg ) ; } this . aborted = true ; try { close ( ) ; } catch ( IOException e ) { throw new RuntimeException ( "Could not close the connection" , e ) ; } |
public class JBBPOut { /** * Write each long value from a long value array into the session stream .
* @ param value a long value array which values will be written into
* @ return the DSL session
* @ throws IOException it will be thrown for transport errors */
public JBBPOut Long ( final long ... value ) throws IOException { } } | assertNotEnded ( ) ; assertArrayNotNull ( value ) ; if ( this . processCommands ) { for ( final long l : value ) { _writeLong ( l ) ; } } return this ; |
public class GeometryShapeConverter { /** * We ' re expecting a List that can be turned into a geometry using a series of factories */
@ SuppressWarnings ( "unchecked" ) // always have unchecked casts when dealing with raw classes
private Geometry decodeObject ( final List mongoDBGeometry , final List < GeometryFactory > geometryFactories ) { } } | GeometryFactory factory = geometryFactories . get ( 0 ) ; if ( geometryFactories . size ( ) == 1 ) { // This should be the last list , so no need to decode further
return factory . createGeometry ( mongoDBGeometry ) ; } else { List < Geometry > decodedObjects = new ArrayList < Geometry > ( ) ; for ( final Object objectThatNeedsDecoding : mongoDBGeometry ) { // MongoDB geometries are lists of lists of lists . . .
decodedObjects . add ( decodeObject ( ( List ) objectThatNeedsDecoding , geometryFactories . subList ( 1 , geometryFactories . size ( ) ) ) ) ; } return factory . createGeometry ( decodedObjects ) ; } |
public class GregorianCalendar { /** * Converts the time value ( millisecond offset from the < a
* href = " Calendar . html # Epoch " > Epoch < / a > ) to calendar field values .
* The time is < em > not < / em >
* recomputed first ; to recompute the time , then the fields , call the
* < code > complete < / code > method .
* @ see Calendar # complete */
@ Override protected void computeFields ( ) { } } | int mask ; if ( isPartiallyNormalized ( ) ) { // Determine which calendar fields need to be computed .
mask = getSetStateFields ( ) ; int fieldMask = ~ mask & ALL_FIELDS ; // We have to call computTime in case calsys = = null in
// order to set calsys and cdate . ( 6263644)
if ( fieldMask != 0 || calsys == null ) { mask |= computeFields ( fieldMask , mask & ( ZONE_OFFSET_MASK | DST_OFFSET_MASK ) ) ; assert mask == ALL_FIELDS ; } } else { mask = ALL_FIELDS ; computeFields ( mask , 0 ) ; } // After computing all the fields , set the field state to ` COMPUTED ' .
setFieldsComputed ( mask ) ; |
public class JDBC4ResultSet { /** * Reports whether the last column read had a value of SQL NULL . */
@ Override public boolean wasNull ( ) throws SQLException { } } | checkClosed ( ) ; try { return table . wasNull ( ) ; } catch ( Exception x ) { throw SQLError . get ( x ) ; } |
public class MatrixFeatures_ZDRM { /** * Unitary matrices have the following properties : < br > < br >
* Q * Q < sup > H < / sup > = I
* This is the complex equivalent of orthogonal matrix .
* @ param Q The matrix being tested . Not modified .
* @ param tol Tolerance .
* @ return True if it passes the test . */
public static boolean isUnitary ( ZMatrixRMaj Q , double tol ) { } } | if ( Q . numRows < Q . numCols ) { throw new IllegalArgumentException ( "The number of rows must be more than or equal to the number of columns" ) ; } Complex_F64 prod = new Complex_F64 ( ) ; ZMatrixRMaj u [ ] = CommonOps_ZDRM . columnsToVector ( Q , null ) ; for ( int i = 0 ; i < u . length ; i ++ ) { ZMatrixRMaj a = u [ i ] ; VectorVectorMult_ZDRM . innerProdH ( a , a , prod ) ; if ( Math . abs ( prod . real - 1 ) > tol ) return false ; if ( Math . abs ( prod . imaginary ) > tol ) return false ; for ( int j = i + 1 ; j < u . length ; j ++ ) { VectorVectorMult_ZDRM . innerProdH ( a , u [ j ] , prod ) ; if ( ! ( prod . getMagnitude2 ( ) <= tol * tol ) ) return false ; } } return true ; |
public class DRL6StrictParser { /** * lhsExpression : = lhsOr *
* @ param lhs
* @ throws org . antlr . runtime . RecognitionException */
private void lhsExpression ( CEDescrBuilder < ? , AndDescr > lhs ) throws RecognitionException { } } | helper . start ( lhs , CEDescrBuilder . class , null ) ; if ( state . backtracking == 0 ) { helper . emit ( Location . LOCATION_LHS_BEGIN_OF_CONDITION ) ; } try { while ( input . LA ( 1 ) != DRL6Lexer . EOF && ! helper . validateIdentifierKey ( DroolsSoftKeywords . THEN ) && ! helper . validateIdentifierKey ( DroolsSoftKeywords . END ) ) { if ( state . backtracking == 0 ) { helper . emit ( Location . LOCATION_LHS_BEGIN_OF_CONDITION ) ; } lhsOr ( lhs , true ) ; if ( lhs . getDescr ( ) != null && lhs . getDescr ( ) instanceof ConditionalElementDescr ) { ConditionalElementDescr root = ( ConditionalElementDescr ) lhs . getDescr ( ) ; BaseDescr [ ] descrs = root . getDescrs ( ) . toArray ( new BaseDescr [ root . getDescrs ( ) . size ( ) ] ) ; root . getDescrs ( ) . clear ( ) ; for ( int i = 0 ; i < descrs . length ; i ++ ) { root . addOrMerge ( descrs [ i ] ) ; } } if ( state . failed ) return ; } } finally { helper . end ( CEDescrBuilder . class , lhs ) ; } |
public class FineUploader5Request { /** * The endpoint to send upload requests to .
* @ param aRequestEndpoint
* The new action URL . May not be < code > null < / code > .
* @ return this */
@ Nonnull public FineUploader5Request setEndpoint ( @ Nonnull final ISimpleURL aRequestEndpoint ) { } } | ValueEnforcer . notNull ( aRequestEndpoint , "RequestEndpoint" ) ; m_aRequestEndpoint = aRequestEndpoint ; return this ; |
public class FileNameUtils { /** * Returns the directory of the URL .
* @ param urlString URL of the file .
* @ return The directory string .
* @ throws IllegalArgumentException if URL is malformed */
public static String getURLParentDirectory ( String urlString ) throws IllegalArgumentException { } } | URL url = null ; try { url = new URL ( urlString ) ; } catch ( MalformedURLException e ) { throw Exceptions . IllegalArgument ( "Malformed URL: %s" , url ) ; } String path = url . getPath ( ) ; int lastSlashIndex = path . lastIndexOf ( "/" ) ; String directory = lastSlashIndex == - 1 ? "" : path . substring ( 0 , lastSlashIndex ) ; return String . format ( "%s://%s%s%s%s" , url . getProtocol ( ) , url . getUserInfo ( ) == null ? "" : url . getUserInfo ( ) + "@" , url . getHost ( ) , url . getPort ( ) == - 1 ? "" : ":" + Integer . toString ( url . getPort ( ) ) , directory ) ; |
public class SizeValidator { /** * { @ inheritDoc } */
@ Override public boolean isValid ( T value ) { } } | int length = 0 ; if ( value instanceof Map < ? , ? > ) { length = ( ( Map < ? , ? > ) value ) . size ( ) ; } else if ( value instanceof Collection < ? > ) { length = ( ( Collection < ? > ) value ) . size ( ) ; } else if ( value instanceof Object [ ] ) { length = ( ( Object [ ] ) value ) . length ; } else if ( value != null ) { length = value . toString ( ) . length ( ) ; } return length >= minValue && length <= maxValue ; |
public class PlatformLevel { /** * Add a component to container only if this is a standalone instance , without clustering .
* @ throws IllegalStateException if called from PlatformLevel1 , when cluster settings are not loaded */
AddIfStandalone addIfStandalone ( Object ... objects ) { } } | if ( addIfStandalone == null ) { addIfStandalone = new AddIfStandalone ( getWebServer ( ) . isStandalone ( ) ) ; } addIfStandalone . ifAdd ( objects ) ; return addIfStandalone ; |
public class CurrentState { /** * Returns the current state and updates the status as being read .
* @ return the current state and updates the status as being read . */
public State get ( ) { } } | InternalState internalState = currentInternalState . get ( ) ; while ( ! internalState . isRead ) { // Slow path , the state is first time read . Change the state only if no other changes
// happened between the moment initialState is read and this moment . This ensures that this
// method only changes the isRead part of the internal state .
currentInternalState . compareAndSet ( internalState , internalState . state == State . ENABLED ? InternalState . ENABLED_READ : InternalState . DISABLED_READ ) ; internalState = currentInternalState . get ( ) ; } return internalState . state ; |
public class OidcAccessTokenAuthenticator { /** * Validate id token if any .
* @ param accessToken the access token
* @ param profile the profile
* @ throws MalformedClaimException the malformed claim exception */
protected void validateIdTokenIfAny ( final AccessToken accessToken , final CommonProfile profile ) throws MalformedClaimException { } } | if ( StringUtils . isNotBlank ( accessToken . getIdToken ( ) ) ) { val idTokenResult = idTokenSigningAndEncryptionService . validate ( accessToken . getIdToken ( ) ) ; profile . setId ( idTokenResult . getSubject ( ) ) ; profile . addAttributes ( idTokenResult . getClaimsMap ( ) ) ; } |
public class MaterialSpinner { /** * Set the custom adapter for the dropdown items
* @ param adapter The adapter
* @ param < T > The type */
public < T > void setAdapter ( MaterialSpinnerAdapter < T > adapter ) { } } | this . adapter = adapter ; this . adapter . setTextColor ( textColor ) ; this . adapter . setBackgroundSelector ( backgroundSelector ) ; this . adapter . setPopupPadding ( popupPaddingLeft , popupPaddingTop , popupPaddingRight , popupPaddingBottom ) ; setAdapterInternal ( adapter ) ; |
public class AppcastManager { /** * Download the file from the given URL to the specified target
* @ param appcast The appcast content
* @ param targetDir The target download dir ( update directory )
* @ return Path to the downloaded update file
* @ throws IOException in case of an error */
public Path download ( Appcast appcast , Path targetDir ) throws IOException , Exception { } } | Path downloaded = null ; Enclosure enclosure = appcast . getLatestEnclosure ( ) ; if ( enclosure != null ) { String url = enclosure . getUrl ( ) ; if ( url != null && ! url . isEmpty ( ) ) { URL enclosureUrl = new URL ( url ) ; String targetName = url . substring ( url . lastIndexOf ( '/' ) + 1 , url . length ( ) ) ; long length = enclosure . getLength ( ) ; File tmpFile = null ; ReadableByteChannel rbc = null ; FileOutputStream fos = null ; try { tmpFile = File . createTempFile ( "ac-" , ".part" ) ; rbc = Channels . newChannel ( enclosureUrl . openStream ( ) ) ; fos = new FileOutputStream ( tmpFile ) ; fos . getChannel ( ) . transferFrom ( rbc , 0 , Long . MAX_VALUE ) ; // Verify if file is ok
// Check size
if ( length > 0 ) { long size = Files . size ( tmpFile . toPath ( ) ) ; if ( length != size ) { throw new Exception ( "Downloaded file has wrong size! Expected: " + length + " -- Actual: " + size ) ; } } // Check MD5 / DSA Signature
String md5 = enclosure . getMd5 ( ) ; if ( md5 != null ) { MessageDigest md = MessageDigest . getInstance ( "MD5" ) ; md . reset ( ) ; byte [ ] bytes = new byte [ 2048 ] ; int numBytes ; try ( FileInputStream is = new FileInputStream ( tmpFile ) ) { while ( ( numBytes = is . read ( bytes ) ) != - 1 ) { md . update ( bytes , 0 , numBytes ) ; } } String hash = toHex ( md . digest ( ) ) ; if ( ! md5 . equalsIgnoreCase ( hash ) ) { throw new Exception ( "Downloaded file has wrong MD5 hash! Expected: " + md5 + " -- Actual: " + hash ) ; } } // Copy file to target dir
downloaded = Files . copy ( tmpFile . toPath ( ) , targetDir . resolve ( targetName ) , StandardCopyOption . REPLACE_EXISTING ) ; } finally { try { if ( fos != null ) fos . close ( ) ; } catch ( IOException e ) { /* ignore */
} try { if ( rbc != null ) rbc . close ( ) ; } catch ( IOException e ) { /* ignore */
} if ( tmpFile != null ) { Files . deleteIfExists ( tmpFile . toPath ( ) ) ; } } } } return downloaded ; |
public class ReteooBuilder { /** * Add a < code > Rule < / code > to the network .
* @ param rule
* The rule to add .
* @ throws InvalidPatternException */
public synchronized void addRule ( final RuleImpl rule ) throws InvalidPatternException { } } | final List < TerminalNode > terminals = this . ruleBuilder . addRule ( rule , this . kBase ) ; BaseNode [ ] nodes = terminals . toArray ( new BaseNode [ terminals . size ( ) ] ) ; this . rules . put ( rule . getFullyQualifiedName ( ) , nodes ) ; if ( rule . isQuery ( ) ) { this . queries . put ( rule . getName ( ) , nodes ) ; } |
public class SeleniumSpec { /** * Verifies that a webelement previously found { @ code isDisplayed }
* @ param index
* @ param isDisplayed */
@ Then ( "^the element on index '(\\d+?)' (IS|IS NOT) displayed$" ) public void assertSeleniumIsDisplayed ( Integer index , Boolean isDisplayed ) { } } | assertThat ( this . commonspec , commonspec . getPreviousWebElements ( ) ) . as ( "There are less found elements than required" ) . hasAtLeast ( index ) ; assertThat ( this . commonspec , commonspec . getPreviousWebElements ( ) . getPreviousWebElements ( ) . get ( index ) . isDisplayed ( ) ) . as ( "Unexpected element display property" ) . isEqualTo ( isDisplayed ) ; |
public class ConsumerDispatcher { /** * Updates to state that the subscription is in the MatchSpace . */
public void setIsInMatchSpace ( boolean inMatchSpace ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "setIsInMatchSpace" , Boolean . valueOf ( inMatchSpace ) ) ; isInMatchSpace = inMatchSpace ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "setIsInMatchSpace" ) ; |
public class HttpSupport { /** * Redirects to referrer if one exists . If a referrer does not exist , it will be redirected to
* the < code > defaultReference < / code > .
* @ param defaultReference where to redirect - can be absolute or relative ; this will be used in case
* the request does not provide a " Referrer " header .
* @ return { @ link HttpSupport . HttpBuilder } , to accept additional information . */
protected HttpBuilder redirectToReferrer ( String defaultReference ) { } } | String referrer = RequestContext . getHttpRequest ( ) . getHeader ( "Referer" ) ; referrer = referrer == null ? defaultReference : referrer ; RedirectResponse resp = new RedirectResponse ( referrer ) ; RequestContext . setControllerResponse ( resp ) ; return new HttpBuilder ( resp ) ; |
public class SqlBuilder { /** * The IN expression .
* @ param e1 The first expression .
* @ param e2 The second expression .
* @ return The expression . */
public static Expression in ( final Expression e1 , final Expression e2 ) { } } | return new RepeatDelimiter ( IN , e1 . isEnclosed ( ) ? e1 : e1 . enclose ( ) , e2 . isEnclosed ( ) ? e2 : e2 . enclose ( ) ) ; |
public class P6LogQuery { /** * this is an internal method called by logElapsed */
protected static void doLogElapsed ( int connectionId , long timeElapsedNanos , Category category , String prepared , String sql , String url ) { } } | doLog ( connectionId , timeElapsedNanos , category , prepared , sql , url ) ; |
public class IOUtils { /** * Pack some binary data .
* @ param data data to be packed
* @ return packed data as byte array
* @ since 1.0 */
@ Nonnull @ Weight ( Weight . Unit . VARIABLE ) public static byte [ ] packData ( @ Nonnull final byte [ ] data ) { } } | final Deflater compressor = new Deflater ( Deflater . BEST_COMPRESSION ) ; compressor . setInput ( Assertions . assertNotNull ( data ) ) ; compressor . finish ( ) ; final ByteArrayOutputStream resultData = new ByteArrayOutputStream ( data . length + 100 ) ; final byte [ ] buffer = new byte [ 1024 ] ; while ( ! compressor . finished ( ) ) { resultData . write ( buffer , 0 , compressor . deflate ( buffer ) ) ; } return resultData . toByteArray ( ) ; |
public class SelectClauseVisitors { /** * TODO move this to writer package . */
public static SelectClauseVisitor clauseVisitor ( final Appendable appendable ) { } } | final SafeAppendable sb = new SafeAppendable ( appendable ) ; SimpleClauseVisitor cv = new SimpleClauseVisitor ( ) { AtomicBoolean first = new AtomicBoolean ( true ) ; /* * TODO take care of multiples and order . */
@ Override protected void doVisit ( SqlSelectClause < ? > clause ) { if ( ! appendStart ( clause ) ) return ; sb . append ( clause . getSql ( ) ) ; } @ Override public void visit ( SelectWhereClauseBuilder < ? > whereClauseBuilder ) { if ( ! appendStart ( whereClauseBuilder ) ) return ; whereClauseBuilder . getCondition ( ) . accept ( ConditionVisitors . conditionVisitor ( sb . getAppendable ( ) ) ) ; } @ Override public void visit ( OrderByClauseBuilder < ? > orderClauseBuilder ) { if ( ! appendStart ( orderClauseBuilder ) ) return ; if ( nullToEmpty ( orderClauseBuilder . getSql ( ) ) . trim ( ) . isEmpty ( ) ) OrderByPartialVisitors . visitor ( sb . getAppendable ( ) ) . visit ( orderClauseBuilder . getOrderByPartial ( ) ) ; else sb . append ( orderClauseBuilder . getSql ( ) ) ; } private boolean appendStart ( SelectClause < ? > k ) { if ( k . isNoOp ( ) ) return false ; if ( first . get ( ) ) { first . set ( false ) ; } else { sb . append ( " " ) ; } if ( k . getType ( ) != SelectClauseType . CUSTOM ) { sb . append ( k . getType ( ) . getSql ( ) ) ; if ( k . getType ( ) != SelectClauseType . FORUPDATE && k . getType ( ) != SelectClauseType . FORSHARE ) sb . append ( " " ) ; } return true ; } } ; return cv ; |
public class AbstractEncoding { /** * onigenc _ minimum _ property _ name _ to _ ctype
* notably overridden by unicode encodings */
@ Override public int propertyNameToCType ( byte [ ] bytes , int p , int end ) { } } | Integer ctype = PosixBracket . PBSTableUpper . get ( bytes , p , end ) ; if ( ctype != null ) return ctype ; throw new CharacterPropertyException ( EncodingError . ERR_INVALID_CHAR_PROPERTY_NAME , bytes , p , end - p ) ; |
public class IOUtil { /** * copy a reader to a writer
* @ param reader
* @ param writer
* @ param closeReader
* @ param closeWriter
* @ throws IOException */
public static final void copy ( Reader reader , Writer writer , boolean closeReader , boolean closeWriter ) throws IOException { } } | try { copy ( reader , writer , 0xffff , - 1 ) ; } finally { if ( closeReader ) closeEL ( reader ) ; if ( closeWriter ) closeEL ( writer ) ; } |
public class JsonWebKey { /** * Get the RSA public key value .
* @ param provider
* the Java security provider .
* @ return the RSA public key value */
private PublicKey getRSAPublicKey ( Provider provider ) { } } | try { RSAPublicKeySpec publicKeySpec = getRSAPublicKeySpec ( ) ; KeyFactory factory = provider != null ? KeyFactory . getInstance ( "RSA" , provider ) : KeyFactory . getInstance ( "RSA" ) ; return factory . generatePublic ( publicKeySpec ) ; } catch ( GeneralSecurityException e ) { throw new IllegalStateException ( e ) ; } |
public class RotationAxisAligner { /** * Returns the default reference vector for the alignment of Cn structures
* @ return */
private Vector3d getReferenceAxisCylic ( ) { } } | if ( rotationGroup . getPointGroup ( ) . equals ( "C2" ) ) { Vector3d vr = new Vector3d ( subunits . getOriginalCenters ( ) . get ( 0 ) ) ; vr . sub ( subunits . getCentroid ( ) ) ; vr . normalize ( ) ; return vr ; } // get principal axis vector that is perpendicular to the principal
// rotation vector
Vector3d vmin = null ; double dotMin = 1.0 ; for ( Vector3d v : principalAxesOfInertia ) { if ( Math . abs ( principalRotationVector . dot ( v ) ) < dotMin ) { dotMin = Math . abs ( principalRotationVector . dot ( v ) ) ; vmin = new Vector3d ( v ) ; } } if ( principalRotationVector . dot ( vmin ) < 0 ) { vmin . negate ( ) ; } return vmin ; |
public class ReceiveMessageAction { /** * Receives the message with the respective message receiver implementation
* also using a message selector .
* @ param context the test context .
* @ param selectorString the message selector string .
* @ return */
private Message receiveSelected ( TestContext context , String selectorString ) { } } | if ( log . isDebugEnabled ( ) ) { log . debug ( "Setting message selector: '" + selectorString + "'" ) ; } Endpoint messageEndpoint = getOrCreateEndpoint ( context ) ; Consumer consumer = messageEndpoint . createConsumer ( ) ; if ( consumer instanceof SelectiveConsumer ) { if ( receiveTimeout > 0 ) { return ( ( SelectiveConsumer ) messageEndpoint . createConsumer ( ) ) . receive ( context . replaceDynamicContentInString ( selectorString ) , context , receiveTimeout ) ; } else { return ( ( SelectiveConsumer ) messageEndpoint . createConsumer ( ) ) . receive ( context . replaceDynamicContentInString ( selectorString ) , context , messageEndpoint . getEndpointConfiguration ( ) . getTimeout ( ) ) ; } } else { log . warn ( String . format ( "Unable to receive selective with consumer implementation: '%s'" , consumer . getClass ( ) ) ) ; return receive ( context ) ; } |
public class CmsSecurityManager { /** * Reads all resources below the given path matching the filter criteria ,
* including the full tree below the path only in case the < code > readTree < / code >
* parameter is < code > true < / code > . < p >
* @ param context the current request context
* @ param parent the parent path to read the resources from
* @ param filter the filter
* @ param readTree < code > true < / code > to read all subresources
* @ return a list of < code > { @ link CmsResource } < / code > objects matching the filter criteria
* @ throws CmsSecurityException if the user has insufficient permission for the given resource ( read is required )
* @ throws CmsException if something goes wrong */
public List < CmsResource > readResources ( CmsRequestContext context , CmsResource parent , CmsResourceFilter filter , boolean readTree ) throws CmsException , CmsSecurityException { } } | List < CmsResource > result = null ; CmsDbContext dbc = m_dbContextFactory . getDbContext ( context ) ; try { // check the access permissions
checkPermissions ( dbc , parent , CmsPermissionSet . ACCESS_READ , true , CmsResourceFilter . ALL ) ; result = m_driverManager . readResources ( dbc , parent , filter , readTree ) ; } catch ( Exception e ) { dbc . report ( null , Messages . get ( ) . container ( Messages . ERR_READ_RESOURCES_1 , context . removeSiteRoot ( parent . getRootPath ( ) ) ) , e ) ; } finally { dbc . clear ( ) ; } return result ; |
public class CmsVfsDiskCache { /** * Returns the RFS name to use for caching the given VFS resource with parameters in the disk cache . < p >
* @ param online if true , the online disk cache is used , the offline disk cache otherwise
* @ param rootPath the VFS resource root path to get the RFS cache name for
* @ param parameters the parameters of the request to the VFS resource
* @ return the RFS name to use for caching the given VFS resource with parameters */
public String getCacheName ( boolean online , String rootPath , String parameters ) { } } | String rfsName = CmsFileUtil . getRepositoryName ( m_rfsRepository , rootPath , online ) ; if ( CmsStringUtil . isNotEmpty ( parameters ) ) { String extension = CmsFileUtil . getExtension ( rfsName ) ; // build the RFS name for the VFS name with parameters
rfsName = CmsFileUtil . getRfsPath ( rfsName , extension , parameters ) ; } return rfsName ; |
public class OrderedSet { /** * remove will be slow */
@ Override public boolean remove ( Object o ) { } } | if ( elements . remove ( o ) ) { ordered . remove ( o ) ; return true ; } else { return false ; } |
public class StatisticsJDBCStorageConnection { /** * { @ inheritDoc } */
public void delete ( PropertyData data , ChangedSizeHandler sizeHandler ) throws RepositoryException , UnsupportedOperationException , InvalidItemStateException , IllegalStateException { } } | Statistics s = ALL_STATISTICS . get ( DELETE_PROPERTY_DATA_DESCR ) ; try { s . begin ( ) ; wcs . delete ( data , sizeHandler ) ; } finally { s . end ( ) ; } |
public class TabbedPanel { /** * Puts widget at first free index
* @ param widget Widget to put
* @ param name Name of tab
* @ return index of element in container */
public int put ( Widget widget , String name ) { } } | if ( widget == null ) return - 1 ; attach ( widget ) ; for ( int i = 0 ; i < content . length ; ++ i ) if ( content [ i ] == null ) { content [ i ] = new Tab ( widget , name ) ; this . sendElement ( ) ; return i ; } throw new IndexOutOfBoundsException ( ) ; // return - 1; |
public class RequestCollapser { /** * Submit a request to a batch . If the batch maxSize is hit trigger the batch immediately .
* @ param arg argument to a { @ link RequestCollapser }
* @ return Observable < ResponseType >
* @ throws IllegalStateException
* if submitting after shutdown */
public Observable < ResponseType > submitRequest ( final RequestArgumentType arg ) { } } | /* * We only want the timer ticking if there are actually things to do so we register it the first time something is added . */
if ( ! timerListenerRegistered . get ( ) && timerListenerRegistered . compareAndSet ( false , true ) ) { /* schedule the collapsing task to be executed every x milliseconds ( x defined inside CollapsedTask ) */
timerListenerReference . set ( timer . addListener ( new CollapsedTask ( ) ) ) ; } // loop until succeed ( compare - and - set spin - loop )
while ( true ) { final RequestBatch < BatchReturnType , ResponseType , RequestArgumentType > b = batch . get ( ) ; if ( b == null ) { return Observable . error ( new IllegalStateException ( "Submitting requests after collapser is shutdown" ) ) ; } final Observable < ResponseType > response ; if ( arg != null ) { response = b . offer ( arg ) ; } else { response = b . offer ( ( RequestArgumentType ) NULL_SENTINEL ) ; } // it will always get an Observable unless we hit the max batch size
if ( response != null ) { return response ; } else { // this batch can ' t accept requests so create a new one and set it if another thread doesn ' t beat us
createNewBatchAndExecutePreviousIfNeeded ( b ) ; } } |
public class Engine { /** * exactly one thread will invoke this method for one path */
private Content doComputeUnlimited ( String path , CountDownLatch gate ) throws IOException { } } | long startContent ; long endContent ; ByteArrayOutputStream result ; References references ; byte [ ] bytes ; String hash ; Content content ; if ( gate . getCount ( ) != 1 ) { throw new IllegalStateException ( path + " " + gate . getCount ( ) ) ; } startContent = System . currentTimeMillis ( ) ; try { try { references = repository . resolve ( Request . parse ( path ) ) ; } catch ( CyclicDependency e ) { throw new RuntimeException ( e . toString ( ) , e ) ; } catch ( IOException e ) { throw new IOException ( path + ": " + e . getMessage ( ) , e ) ; } result = new ByteArrayOutputStream ( ) ; try ( OutputStream dest = new GZIPOutputStream ( result ) ; Writer writer = new OutputStreamWriter ( dest , ENCODING ) ) { references . writeTo ( writer ) ; } bytes = result . toByteArray ( ) ; endContent = System . currentTimeMillis ( ) ; hash = hash ( bytes ) ; content = new Content ( references . type . getMime ( ) , references . getLastModified ( ) , bytes ) ; hashCache . add ( path , hash , endContent /* that ' s where hash computation starts */
, 0 /* too small for meaningful measures */
) ; contentCache . add ( hash , content , startContent , endContent - startContent ) ; } finally { synchronized ( pending ) { if ( gate . getCount ( ) != 1 ) { throw new IllegalStateException ( path + " " + gate . getCount ( ) ) ; } if ( pending . remove ( path ) != gate ) { throw new IllegalStateException ( ) ; } gate . countDown ( ) ; } } return content ; |
public class AssociationExecutionFilterMarshaller { /** * Marshall the given parameter object . */
public void marshall ( AssociationExecutionFilter associationExecutionFilter , ProtocolMarshaller protocolMarshaller ) { } } | if ( associationExecutionFilter == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( associationExecutionFilter . getKey ( ) , KEY_BINDING ) ; protocolMarshaller . marshall ( associationExecutionFilter . getValue ( ) , VALUE_BINDING ) ; protocolMarshaller . marshall ( associationExecutionFilter . getType ( ) , TYPE_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class DeleteLayerRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( DeleteLayerRequest deleteLayerRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( deleteLayerRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( deleteLayerRequest . getLayerId ( ) , LAYERID_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class Model { /** * Remove attributes if it is null .
* @ return this model */
public M removeNullValueAttrs ( ) { } } | for ( Iterator < Entry < String , Object > > it = attrs . entrySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Entry < String , Object > e = it . next ( ) ; if ( e . getValue ( ) == null ) { it . remove ( ) ; _getModifyFlag ( ) . remove ( e . getKey ( ) ) ; } } return ( M ) this ; |
public class tunneltrafficpolicy { /** * Use this API to fetch tunneltrafficpolicy resource of given name . */
public static tunneltrafficpolicy get ( nitro_service service , String name ) throws Exception { } } | tunneltrafficpolicy obj = new tunneltrafficpolicy ( ) ; obj . set_name ( name ) ; tunneltrafficpolicy response = ( tunneltrafficpolicy ) obj . get_resource ( service ) ; return response ; |
public class IntegrationAuthenticationFilter { /** * public void setAuthenticationSuccessHandler ( AuthenticationSuccessHandler successHandler ) {
* Assert . notNull ( successHandler , " successHandler cannot be null " ) ;
* this . successHandler = successHandler ;
* public void setAuthenticationFailureHandler ( AuthenticationFailureHandler failureHandler ) {
* Assert . notNull ( failureHandler , " failureHandler cannot be null " ) ;
* this . failureHandler = failureHandler ; */
protected boolean requiresAuthentication ( HttpServletRequest request , HttpServletResponse response ) { } } | String uri = request . getRequestURI ( ) ; int pathParamIndex = uri . indexOf ( ';' ) ; if ( pathParamIndex > 0 ) { // strip everything after the first semi - colon
uri = uri . substring ( 0 , pathParamIndex ) ; } if ( "" . equals ( request . getContextPath ( ) ) ) { return uri . endsWith ( filterProcessesUrl ) ; } return uri . endsWith ( request . getContextPath ( ) + filterProcessesUrl ) ; |
public class PolicyToPath { /** * List of policy objects .
* < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use
* { @ link # setPolicies ( java . util . Collection ) } or { @ link # withPolicies ( java . util . Collection ) } if you want to override
* the existing values .
* @ param policies
* List of policy objects .
* @ return Returns a reference to this object so that method calls can be chained together . */
public PolicyToPath withPolicies ( PolicyAttachment ... policies ) { } } | if ( this . policies == null ) { setPolicies ( new java . util . ArrayList < PolicyAttachment > ( policies . length ) ) ; } for ( PolicyAttachment ele : policies ) { this . policies . add ( ele ) ; } return this ; |
public class PathUtils { /** * Answer the last file name of a path , using the forward slash ( ' / ' ) as the
* path separator character . Answer the path element which follows the last
* forward slash of the path .
* Answer the entire path if the path contains no path separator .
* For example :
* For " / parent / child " answer " child " .
* For " child " answer " child " .
* An exception will be thrown if the path ends with a trailing slash .
* @ param path The path from which to answer the last file name .
* @ return The last file name of the path . */
public static String getName ( String pathAndName ) { } } | int i = pathAndName . lastIndexOf ( '/' ) ; int l = pathAndName . length ( ) ; if ( i == - 1 ) { return pathAndName ; } else if ( l == i ) { return "/" ; } else { return pathAndName . substring ( i + 1 ) ; } |
public class RunCommandParameters { /** * Currently , we support including only one RunCommandTarget block , which specifies either an array of InstanceIds
* or a tag .
* @ param runCommandTargets
* Currently , we support including only one RunCommandTarget block , which specifies either an array of
* InstanceIds or a tag . */
public void setRunCommandTargets ( java . util . Collection < RunCommandTarget > runCommandTargets ) { } } | if ( runCommandTargets == null ) { this . runCommandTargets = null ; return ; } this . runCommandTargets = new java . util . ArrayList < RunCommandTarget > ( runCommandTargets ) ; |
public class CudaZeroHandler { /** * Copies specific chunk of memory from one storage to another
* Possible directions : HOST - > DEVICE , DEVICE - > HOST
* @ param currentStatus
* @ param targetStatus
* @ param point */
@ Override public void relocate ( AllocationStatus currentStatus , AllocationStatus targetStatus , AllocationPoint point , AllocationShape shape , CudaContext context ) { } } | // log . info ( " RELOCATE CALLED : [ " + currentStatus + " ] - > [ " + targetStatus + " ] " ) ;
if ( currentStatus == AllocationStatus . DEVICE && targetStatus == AllocationStatus . HOST ) { // DEVICE - > HOST
DataBuffer targetBuffer = point . getBuffer ( ) ; if ( targetBuffer == null ) throw new IllegalStateException ( "Target buffer is NULL!" ) ; Pointer devicePointer = new CudaPointer ( point . getPointers ( ) . getDevicePointer ( ) . address ( ) ) ; } else if ( currentStatus == AllocationStatus . HOST && targetStatus == AllocationStatus . DEVICE ) { // HOST - > DEVICE
// TODO : this probably should be removed
if ( point . isConstant ( ) ) { // log . info ( " Skipping relocation for constant " ) ;
return ; } if ( point . getPointers ( ) . getDevicePointer ( ) == null ) { throw new IllegalStateException ( "devicePointer is NULL!" ) ; } val profD = PerformanceTracker . getInstance ( ) . helperStartTransaction ( ) ; if ( nativeOps . memcpyAsync ( point . getPointers ( ) . getDevicePointer ( ) , point . getPointers ( ) . getHostPointer ( ) , AllocationUtils . getRequiredMemory ( shape ) , CudaConstants . cudaMemcpyHostToDevice , context . getSpecialStream ( ) ) == 0 ) throw new IllegalStateException ( "MemcpyAsync relocate H2D failed: [" + point . getHostPointer ( ) . address ( ) + "] -> [" + point . getDevicePointer ( ) . address ( ) + "]" ) ; flowController . commitTransfer ( context . getSpecialStream ( ) ) ; PerformanceTracker . getInstance ( ) . helperRegisterTransaction ( point . getDeviceId ( ) , profD , point . getNumberOfBytes ( ) , MemcpyDirection . HOST_TO_DEVICE ) ; // context . syncOldStream ( ) ;
} else throw new UnsupportedOperationException ( "Can't relocate data in requested direction: [" + currentStatus + "] -> [" + targetStatus + "]" ) ; |
public class AccountsImpl { /** * Gets the number of nodes in each state , grouped by pool .
* @ param nextPageLink The NextLink from the previous successful call to List operation .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the PagedList & lt ; PoolNodeCounts & gt ; object wrapped in { @ link ServiceResponseWithHeaders } if successful . */
public Observable < ServiceResponseWithHeaders < Page < PoolNodeCounts > , AccountListPoolNodeCountsHeaders > > listPoolNodeCountsNextSinglePageAsync ( final String nextPageLink ) { } } | if ( nextPageLink == null ) { throw new IllegalArgumentException ( "Parameter nextPageLink is required and cannot be null." ) ; } final AccountListPoolNodeCountsNextOptions accountListPoolNodeCountsNextOptions = null ; UUID clientRequestId = null ; Boolean returnClientRequestId = null ; DateTime ocpDate = null ; DateTimeRfc1123 ocpDateConverted = null ; if ( ocpDate != null ) { ocpDateConverted = new DateTimeRfc1123 ( ocpDate ) ; } String nextUrl = String . format ( "%s" , nextPageLink ) ; return service . listPoolNodeCountsNext ( nextUrl , this . client . acceptLanguage ( ) , clientRequestId , returnClientRequestId , ocpDateConverted , this . client . userAgent ( ) ) . flatMap ( new Func1 < Response < ResponseBody > , Observable < ServiceResponseWithHeaders < Page < PoolNodeCounts > , AccountListPoolNodeCountsHeaders > > > ( ) { @ Override public Observable < ServiceResponseWithHeaders < Page < PoolNodeCounts > , AccountListPoolNodeCountsHeaders > > call ( Response < ResponseBody > response ) { try { ServiceResponseWithHeaders < PageImpl < PoolNodeCounts > , AccountListPoolNodeCountsHeaders > result = listPoolNodeCountsNextDelegate ( response ) ; return Observable . just ( new ServiceResponseWithHeaders < Page < PoolNodeCounts > , AccountListPoolNodeCountsHeaders > ( result . body ( ) , result . headers ( ) , result . response ( ) ) ) ; } catch ( Throwable t ) { return Observable . error ( t ) ; } } } ) ; |
public class NoCompTreeMap { /** * BinTreeNode that should replace node in the tree . */
private final V finish_removal ( BinTreeNode < K , V > node , BinTreeNode < K , V > prev , int son , BinTreeNode < K , V > m ) { } } | if ( m != null ) { // set up the links for m
m . left = node . left ; m . right = node . right ; } if ( prev == null ) root = m ; else { if ( son == 0 ) prev . left = m ; else prev . right = m ; } return node . value ; |
public class RaftAgent { /** * { @ inheritDoc }
* @ throws IllegalStateException if this method is called before { @ code RaftAgent } is initialized */
@ Override public @ Nullable Committed getNextCommitted ( long indexToSearchFrom ) { } } | checkState ( setupConversion ) ; checkState ( initialized ) ; return raftAlgorithm . getNextCommitted ( indexToSearchFrom ) ; |
public class FileSystemHeartbeatPRequest { /** * < code > optional . alluxio . grpc . file . FileSystemHeartbeatPOptions options = 3 ; < / code > */
public alluxio . grpc . FileSystemHeartbeatPOptionsOrBuilder getOptionsOrBuilder ( ) { } } | return options_ == null ? alluxio . grpc . FileSystemHeartbeatPOptions . getDefaultInstance ( ) : options_ ; |
public class MethodAttribUtils { /** * getAnnotationCMTTransactions fill the TransactionAttribute array with data from
* Annotations . / / d366845.8 */
public static final void getAnnotationCMTransactions ( TransactionAttribute [ ] tranAttrs , int methodInterfaceType , Method [ ] beanMethods , BeanMetaData bmd ) { } } | final boolean isTraceOn = TraceComponent . isAnyTracingEnabled ( ) ; if ( isTraceOn && tc . isEntryEnabled ( ) ) Tr . entry ( tc , "getAnnotationCMTransactions" ) ; for ( int i = 0 ; i < beanMethods . length ; i ++ ) { // Only get the value from annotations if it is not already set by WCCM
if ( tranAttrs [ i ] == null ) { javax . ejb . TransactionAttribute methTranAttr = null ; // Don ' t bother looking for annotations , if we ' re told there are none .
if ( ! bmd . metadataComplete ) { methTranAttr = beanMethods [ i ] . getAnnotation ( javax . ejb . TransactionAttribute . class ) ; if ( methTranAttr == null && // EJB 3.2 , section 4.3.14:
// " A stateful session bean ' s PostConstruct , PreDestroy ,
// PrePassivate or PostActivate lifecycle callback
// interceptor method is invoked in the scope of a
// transaction determined by the transaction attribute
// specified in the lifecycle callback method ' s metadata
// annotations or deployment descriptor "
( bmd . type != InternalConstants . TYPE_STATEFUL_SESSION || methodInterfaceType != InternalConstants . METHOD_INTF_LIFECYCLE_INTERCEPTOR ) ) { methTranAttr = beanMethods [ i ] . getDeclaringClass ( ) . getAnnotation ( javax . ejb . TransactionAttribute . class ) ; if ( isTraceOn && tc . isDebugEnabled ( ) && methTranAttr != null ) Tr . debug ( tc , beanMethods [ i ] . getName ( ) + " from class " + beanMethods [ i ] . getDeclaringClass ( ) . getName ( ) ) ; } } if ( methTranAttr == null ) { // set the default value
if ( methodInterfaceType == InternalConstants . METHOD_INTF_LIFECYCLE_INTERCEPTOR && bmd . type == InternalConstants . TYPE_STATEFUL_SESSION ) { // " By default a stateful session bean ' s PostConstruct ,
// PreDestroy , PrePassivate and PostActivate methods are
// executed in an unspecified transactional context . "
// WebSphere implements an unspecified transactional
// context as TX _ NOT _ SUPPORTED .
tranAttrs [ i ] = TransactionAttribute . TX_NOT_SUPPORTED ; } else { tranAttrs [ i ] = TransactionAttribute . TX_REQUIRED ; } if ( isTraceOn && tc . isDebugEnabled ( ) ) Tr . debug ( tc , beanMethods [ i ] . getName ( ) + " = REQUIRED (defaulted)" ) ; } else { // Switch the javax . ejb . TransactionAttribute to com . ibm . websphere . csi . TransactionAttribute
int tranType = methTranAttr . value ( ) . ordinal ( ) ; tranAttrs [ i ] = txAttrFromJEE15Map [ tranType ] ; if ( isTraceOn && tc . isDebugEnabled ( ) ) Tr . debug ( tc , beanMethods [ i ] . getName ( ) + " = " + methTranAttr . value ( ) ) ; } } } if ( isTraceOn && tc . isEntryEnabled ( ) ) { Tr . exit ( tc , "getAnnotationsCMTransactions" , Arrays . toString ( tranAttrs ) ) ; } |
public class CompositeClassLoader { /** * This ClassLoader never has classes of it ' s own , so only search the child ClassLoaders
* and the parent ClassLoader if one is provided */
public Class < ? > loadClass ( final String name , final boolean resolve ) throws ClassNotFoundException { } } | Class cls = loader . get ( ) . load ( this , name , resolve ) ; if ( cls == null ) { throw new ClassNotFoundException ( "Unable to load class: " + name ) ; } return cls ; |
public class CPDAvailabilityEstimateUtil { /** * Returns the first cpd availability estimate in the ordered set where uuid = & # 63 ; .
* @ param uuid the uuid
* @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > )
* @ return the first matching cpd availability estimate , or < code > null < / code > if a matching cpd availability estimate could not be found */
public static CPDAvailabilityEstimate fetchByUuid_First ( String uuid , OrderByComparator < CPDAvailabilityEstimate > orderByComparator ) { } } | return getPersistence ( ) . fetchByUuid_First ( uuid , orderByComparator ) ; |
public class CmsCmisResourceHelper { /** * Collects renditions for a resource . < p >
* @ param cms the CMS context
* @ param resource the resource for which we want the renditions
* @ param renditionFilterString the filter string for the renditions
* @ param objectInfo the object info in which the renditions should be saved
* @ return the rendition data for the given resource */
protected List < RenditionData > collectRenditions ( CmsObject cms , CmsResource resource , String renditionFilterString , ObjectInfoImpl objectInfo ) { } } | List < I_CmsCmisRenditionProvider > providers = m_repository . getRenditionProviders ( new CmsCmisRenditionFilter ( renditionFilterString ) ) ; List < RenditionData > result = new ArrayList < RenditionData > ( ) ; List < RenditionInfo > renditionInfos = new ArrayList < RenditionInfo > ( ) ; for ( I_CmsCmisRenditionProvider provider : providers ) { RenditionData renditionData = provider . getRendition ( cms , resource ) ; if ( renditionData != null ) { RenditionInfoImpl renditionInfo = new RenditionInfoImpl ( ) ; renditionInfo . setContentType ( renditionData . getMimeType ( ) ) ; renditionInfo . setKind ( renditionData . getKind ( ) ) ; renditionInfo . setId ( renditionData . getStreamId ( ) ) ; result . add ( renditionData ) ; renditionInfos . add ( renditionInfo ) ; } } if ( objectInfo != null ) { objectInfo . setRenditionInfos ( renditionInfos ) ; } return result ; |
public class BodyContentImpl { /** * Write a single character . */
public void write ( int c ) throws IOException { } } | if ( writer != null ) { writer . write ( c ) ; } else { ensureOpen ( ) ; // PK33136
strBuffer . append ( ( char ) c ) ; ++ nextChar ; // PK33136
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.