signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class ComponentEnhancer { /** * Manage unique { @ link WaveType } subscription ( from value field of { @ link OnWave } annotation ) .
* @ param component the wave ready
* @ param waveActionName the { @ link WaveType } unique name
* @ param method the wave handler method */
private static void manageUniqueWaveTypeAction ( final Component < ? > component , final String waveActionName , final Method method ) { } } | // Get the WaveType from the WaveType registry
final WaveType wt = WaveTypeRegistry . getWaveType ( waveActionName ) ; if ( wt == null ) { throw new CoreRuntimeException ( "WaveType '" + waveActionName + "' not found into WaveTypeRegistry." ) ; } else { // Method is not defined or is the default fallback one
if ( method == null || AbstractComponent . PROCESS_WAVE_METHOD_NAME . equals ( method . getName ( ) ) ) { // Just listen the WaveType
component . listen ( wt ) ; } else { // Listen the WaveType and specify the right method handler
component . listen ( null , method , wt ) ; } } |
public class ProjectManager { /** * DEPRECATED . use membership . delete ( ) instead . */
@ Deprecated public void deleteProjectMembership ( int membershipId ) throws RedmineException { } } | transport . deleteObject ( Membership . class , Integer . toString ( membershipId ) ) ; |
public class OperatorSimplifyLocalHelper { /** * Simplifies geometries for storing in OGC format :
* MultiPoint : check that no points coincide . tolerance is ignored .
* Polyline : ensure there no segments degenerate segments . Polygon : cracks and
* clusters using cluster tolerance and resolves all self intersections ,
* orients rings properly and arranges the rings in the OGC order .
* Returns simplified geometry . */
static Geometry simplifyOGC ( /* const */
Geometry geometry , /* const */
SpatialReference spatialReference , boolean bForce , ProgressTracker progressTracker ) { } } | if ( geometry . isEmpty ( ) ) return geometry ; Geometry . Type gt = geometry . getType ( ) ; if ( gt == Geometry . Type . Point ) return geometry ; double tolerance = InternalUtils . calculateToleranceFromGeometry ( spatialReference , geometry , false ) ; if ( gt == Geometry . Type . Envelope ) { Envelope env = ( Envelope ) geometry ; Envelope2D env2D = new Envelope2D ( ) ; env . queryEnvelope2D ( env2D ) ; if ( env2D . isDegenerate ( tolerance ) ) { return ( Geometry ) ( env . createInstance ( ) ) ; // return empty
// geometry
} return geometry ; } else if ( Geometry . isSegment ( gt . value ( ) ) ) { Segment seg = ( Segment ) geometry ; Polyline polyline = new Polyline ( seg . getDescription ( ) ) ; polyline . addSegment ( seg , true ) ; return simplifyOGC ( polyline , spatialReference , bForce , progressTracker ) ; } if ( ! Geometry . isMultiVertex ( gt . value ( ) ) ) { throw new GeometryException ( "OGC simplify is not implemented for this geometry type" + gt ) ; } MultiVertexGeometry result = TopologicalOperations . simplifyOGC ( ( MultiVertexGeometry ) geometry , tolerance , false , progressTracker ) ; return result ; |
public class AbstractInjectAnnotationProcessor { /** * Produce a compile warning for the given element and message .
* @ param e The element
* @ param msg The message
* @ param args The string format args */
protected final void warning ( Element e , String msg , Object ... args ) { } } | if ( messager == null ) { illegalState ( ) ; } messager . printMessage ( Diagnostic . Kind . WARNING , String . format ( msg , args ) , e ) ; |
public class DefaultJsonWriter { /** * { @ inheritDoc } */
@ Override public DefaultJsonWriter value ( Number value ) { } } | if ( value == null ) { return nullValue ( ) ; } writeDeferredName ( ) ; String string = value . toString ( ) ; if ( ! lenient && ( string . equals ( "-Infinity" ) || string . equals ( "Infinity" ) || string . equals ( "NaN" ) ) ) { throw new IllegalArgumentException ( "Numeric values must be finite, but was " + value ) ; } beforeValue ( false ) ; out . append ( string ) ; return this ; |
public class ArrayUtility { /** * Returns the total number of non array items held in the specified array ,
* recursively descending in every array item .
* @ param items
* comma separated sequence of { @ link Object } items
* @ return integer specifying the total number of itemsnew */
public static int getFlattenedItemsCount ( final Object ... items ) { } } | return stream ( items ) . map ( item -> item . getClass ( ) . isArray ( ) ? getFlattenedItemsCount ( ( Object [ ] ) item ) : 1 ) . reduce ( 0 , Integer :: sum ) ; |
public class CPSpecificationOptionUtil { /** * Returns the first cp specification option in the ordered set where groupId = & # 63 ; .
* @ param groupId the group ID
* @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > )
* @ return the first matching cp specification option
* @ throws NoSuchCPSpecificationOptionException if a matching cp specification option could not be found */
public static CPSpecificationOption findByGroupId_First ( long groupId , OrderByComparator < CPSpecificationOption > orderByComparator ) throws com . liferay . commerce . product . exception . NoSuchCPSpecificationOptionException { } } | return getPersistence ( ) . findByGroupId_First ( groupId , orderByComparator ) ; |
public class InternationalizedRuntimeException { /** * Gets the arguments to this exception ' s message . Arguments allow a
* < code > InternationalizedRuntimeException < / code > to have a compound message , made up of
* multiple parts that are concatenated in a language - neutral way .
* @ return the arguments to this exception ' s message . */
public Object [ ] getArguments ( ) { } } | if ( mArguments == null ) return new Object [ 0 ] ; Object [ ] result = new Object [ mArguments . length ] ; System . arraycopy ( mArguments , 0 , result , 0 , mArguments . length ) ; return result ; |
public class S3TaskClientImpl { /** * { @ inheritDoc } */
@ Override public DisableStreamingTaskResult disableStreaming ( String spaceId ) throws ContentStoreException { } } | DisableStreamingTaskParameters taskParams = new DisableStreamingTaskParameters ( ) ; taskParams . setSpaceId ( spaceId ) ; return DisableStreamingTaskResult . deserialize ( contentStore . performTask ( StorageTaskConstants . DISABLE_STREAMING_TASK_NAME , taskParams . serialize ( ) ) ) ; |
public class Options { /** * Puts an IModel & lt ; Double & gt ; value for the given option name .
* @ param key
* the option name .
* @ param value
* the float value . */
public Options putDouble ( String key , IModel < Double > value ) { } } | putOption ( key , new DoubleOption ( value ) ) ; return this ; |
public class Keyword { /** * setter for source - sets Tthe keyword source ( terminology ) , O
* @ generated
* @ param v value to set into the feature */
public void setSource ( String v ) { } } | if ( Keyword_Type . featOkTst && ( ( Keyword_Type ) jcasType ) . casFeat_source == null ) jcasType . jcas . throwFeatMissing ( "source" , "de.julielab.jules.types.Keyword" ) ; jcasType . ll_cas . ll_setStringValue ( addr , ( ( Keyword_Type ) jcasType ) . casFeatCode_source , v ) ; |
public class QueueService { /** * A static factory method that returns an instance implementing
* { @ link com . microsoft . windowsazure . services . queue . QueueContract } using the specified { @ link Configuration } instance
* and profile prefix for service settings . The { @ link Configuration }
* instance must have storage account information and credentials set with
* the specified profile prefix before this method is called for the
* returned interface to work .
* @ param profile
* A string prefix for the account name and credentials settings
* in the { @ link Configuration } instance .
* @ param config
* A { @ link Configuration } instance configured with storage
* account information and credentials .
* @ return An instance implementing { @ link com . microsoft . windowsazure . services . queue . QueueContract } for interacting
* with the queue service . */
public static QueueContract create ( String profile , Configuration config ) { } } | return config . create ( profile , QueueContract . class ) ; |
public class EgressFilterMarshaller { /** * Marshall the given parameter object . */
public void marshall ( EgressFilter egressFilter , ProtocolMarshaller protocolMarshaller ) { } } | if ( egressFilter == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( egressFilter . getType ( ) , TYPE_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class CmsScrollPanelImpl { /** * Set the scrollbar used for vertical scrolling .
* @ param scrollbar the scrollbar , or null to clear it
* @ param width the width of the scrollbar in pixels */
private void setVerticalScrollbar ( final CmsScrollBar scrollbar , int width ) { } } | // Validate .
if ( ( scrollbar == m_scrollbar ) || ( scrollbar == null ) ) { return ; } // Detach new child .
scrollbar . asWidget ( ) . removeFromParent ( ) ; // Remove old child .
if ( m_scrollbar != null ) { if ( m_verticalScrollbarHandlerRegistration != null ) { m_verticalScrollbarHandlerRegistration . removeHandler ( ) ; m_verticalScrollbarHandlerRegistration = null ; } remove ( m_scrollbar ) ; } m_scrollLayer . appendChild ( scrollbar . asWidget ( ) . getElement ( ) ) ; adopt ( scrollbar . asWidget ( ) ) ; // Logical attach .
m_scrollbar = scrollbar ; m_verticalScrollbarWidth = width ; // Initialize the new scrollbar .
m_verticalScrollbarHandlerRegistration = scrollbar . addValueChangeHandler ( new ValueChangeHandler < Integer > ( ) { public void onValueChange ( ValueChangeEvent < Integer > event ) { int vPos = scrollbar . getVerticalScrollPosition ( ) ; int v = getVerticalScrollPosition ( ) ; if ( v != vPos ) { setVerticalScrollPosition ( vPos ) ; } } } ) ; maybeUpdateScrollbars ( ) ; |
public class HyphenationAuto { /** * Hyphenates a word and returns the first part of it . To get
* the second part of the hyphenated word call < CODE > getHyphenatedWordPost ( ) < / CODE > .
* @ param word the word to hyphenate
* @ param font the font used by this word
* @ param fontSize the font size used by this word
* @ param remainingWidth the width available to fit this word in
* @ return the first part of the hyphenated word including
* the hyphen symbol , if any */
public String getHyphenatedWordPre ( String word , BaseFont font , float fontSize , float remainingWidth ) { } } | post = word ; String hyphen = getHyphenSymbol ( ) ; float hyphenWidth = font . getWidthPoint ( hyphen , fontSize ) ; if ( hyphenWidth > remainingWidth ) return "" ; Hyphenation hyphenation = hyphenator . hyphenate ( word ) ; if ( hyphenation == null ) { return "" ; } int len = hyphenation . length ( ) ; int k ; for ( k = 0 ; k < len ; ++ k ) { if ( font . getWidthPoint ( hyphenation . getPreHyphenText ( k ) , fontSize ) + hyphenWidth > remainingWidth ) break ; } -- k ; if ( k < 0 ) return "" ; post = hyphenation . getPostHyphenText ( k ) ; return hyphenation . getPreHyphenText ( k ) + hyphen ; |
public class Library { /** * Return the build string of this instance of finmath - lib .
* Currently this is the Git commit hash .
* @ return The build string of this instance of finmath - lib . */
public static String getBuildString ( ) { } } | String versionString = "UNKNOWN" ; Properties propeties = getProperites ( ) ; if ( propeties != null ) { versionString = propeties . getProperty ( "finmath-lib.build" ) ; } return versionString ; |
public class PoolResizeOptions { /** * Set a timestamp indicating the last modified time of the resource known to the client . The operation will be performed only if the resource on the service has not been modified since the specified time .
* @ param ifUnmodifiedSince the ifUnmodifiedSince value to set
* @ return the PoolResizeOptions object itself . */
public PoolResizeOptions withIfUnmodifiedSince ( DateTime ifUnmodifiedSince ) { } } | if ( ifUnmodifiedSince == null ) { this . ifUnmodifiedSince = null ; } else { this . ifUnmodifiedSince = new DateTimeRfc1123 ( ifUnmodifiedSince ) ; } return this ; |
public class DistributedFileSystem { /** * { @ inheritDoc } */
public void setTimes ( Path p , long mtime , long atime ) throws IOException { } } | dfs . setTimes ( getPathName ( p ) , mtime , atime ) ; |
public class JmsConnectionFactoryImpl { /** * ( non - Javadoc )
* @ see com . ibm . websphere . sib . api . jms . JmsConnectionFactory # setReadAhead ( java . lang . String ) */
@ Override public void setDurableSubscriptionHome ( String value ) throws JMSException { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( this , tc , "setDurableSubscriptionHome" , value ) ; jcaManagedConnectionFactory . setDurableSubscriptionHome ( value ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( this , tc , "setDurableSubscriptionHome" ) ; |
public class CacheProxy { /** * Associates the specified value with the specified key in the cache if there is no existing
* mapping .
* @ param key key with which the specified value is to be associated
* @ param value value to be associated with the specified key
* @ param publishToWriter if the writer should be notified
* @ return if the mapping was successful */
private boolean putIfAbsentNoAwait ( K key , V value , boolean publishToWriter ) { } } | boolean [ ] absent = { false } ; cache . asMap ( ) . compute ( copyOf ( key ) , ( k , expirable ) -> { if ( ( expirable != null ) && ! expirable . isEternal ( ) && expirable . hasExpired ( currentTimeMillis ( ) ) ) { dispatcher . publishExpired ( this , key , expirable . get ( ) ) ; statistics . recordEvictions ( 1L ) ; expirable = null ; } if ( expirable != null ) { return expirable ; } absent [ 0 ] = true ; long expireTimeMS = getWriteExpireTimeMS ( /* created */
true ) ; if ( expireTimeMS == 0 ) { return null ; } if ( publishToWriter ) { publishToCacheWriter ( writer :: write , ( ) -> new EntryProxy < > ( key , value ) ) ; } V copy = copyOf ( value ) ; dispatcher . publishCreated ( this , key , copy ) ; return new Expirable < > ( copy , expireTimeMS ) ; } ) ; return absent [ 0 ] ; |
public class SystemViewContentExporter { /** * ( non - Javadoc )
* @ see
* org . exoplatform . services . jcr . dataflow . ItemDataTraversingVisitor # entering ( org . exoplatform . services
* . jcr . datamodel . PropertyData , int ) */
@ Override protected void entering ( PropertyData property , int level ) throws RepositoryException { } } | try { // set name and type of property
AttributesImpl atts = new AttributesImpl ( ) ; atts . addAttribute ( getSvNamespaceUri ( ) , "name" , "sv:name" , "CDATA" , getExportName ( property , false ) ) ; atts . addAttribute ( getSvNamespaceUri ( ) , "type" , "sv:type" , "CDATA" , ExtendedPropertyType . nameFromValue ( property . getType ( ) ) ) ; contentHandler . startElement ( getSvNamespaceUri ( ) , "property" , "sv:property" , atts ) ; List < ValueData > values = property . getValues ( ) ; for ( ValueData valueData : values ) { writeValueData ( valueData , property . getType ( ) ) ; contentHandler . endElement ( getSvNamespaceUri ( ) , "value" , "sv:value" ) ; } } catch ( SAXException e ) { throw new RepositoryException ( "Can't export value to string: " + e . getMessage ( ) , e ) ; } catch ( IllegalStateException e ) { throw new RepositoryException ( "Can't export value to string: " + e . getMessage ( ) , e ) ; } catch ( IOException e ) { throw new RepositoryException ( "Can't export value to string: " + e . getMessage ( ) , e ) ; } |
public class HessenbergSimilarDecomposition_ZDRM { /** * Computes the decomposition of the provided matrix . If no errors are detected then true is returned ,
* false otherwise .
* @ param A The matrix that is being decomposed . Not modified .
* @ return If it detects any errors or not . */
@ Override public boolean decompose ( ZMatrixRMaj A ) { } } | if ( A . numRows != A . numCols ) throw new IllegalArgumentException ( "A must be square." ) ; if ( A . numRows <= 0 ) return false ; QH = A ; N = A . numCols ; if ( b . length < N * 2 ) { b = new double [ N * 2 ] ; gammas = new double [ N ] ; u = new double [ N * 2 ] ; } return _decompose ( ) ; |
public class Repository { /** * < p > asDocumentRepository . < / p >
* @ param env a { @ link com . greenpepper . server . domain . EnvironmentType } object .
* @ param user a { @ link java . lang . String } object .
* @ param pwd a { @ link java . lang . String } object .
* @ return a { @ link com . greenpepper . repository . DocumentRepository } object .
* @ throws java . lang . Exception if any . */
public DocumentRepository asDocumentRepository ( EnvironmentType env , String user , String pwd ) throws Exception { } } | return ( DocumentRepository ) new FactoryConverter ( ) . convert ( type . asFactoryArguments ( this , env , true , user , pwd ) ) ; |
public class Cluster { /** * Check if the cluster health status is not { @ literal RED } and that the
* { @ link IndexSetRegistry # isUp ( ) deflector is up } .
* @ return { @ code true } if the the cluster is healthy and the deflector is up , { @ code false } otherwise */
public boolean isHealthy ( ) { } } | return health ( ) . map ( health -> ! "red" . equals ( health . path ( "status" ) . asText ( ) ) && indexSetRegistry . isUp ( ) ) . orElse ( false ) ; |
public class HTMLFileWriter { /** * Prints summary of Test API methods , excluding old - style verbs , in HTML format .
* @ param classDoc the classDoc of the Test API component */
public void printMethodsSummary ( ClassDoc classDoc ) { } } | MethodDoc [ ] methodDocs = TestAPIDoclet . getTestAPIComponentMethods ( classDoc ) ; if ( methodDocs . length > 0 ) { mOut . println ( "<P>" ) ; mOut . println ( "<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" CELLSPACING=\"0\" SUMMARY=\"\">" ) ; mOut . println ( "<TR BGCOLOR=\"#CCCCFF\"><TH ALIGN=\"left\" COLSPAN=\"2\"><FONT SIZE=\"+2\"><B>Methods " + "Summary</B></FONT></TH></TR>" ) ; for ( MethodDoc methodDoc : methodDocs ) { String methodName = methodDoc . name ( ) ; mOut . print ( "<TR><TD WIDTH=\"1%\"><CODE><B><A HREF=\"#" + methodName + methodDoc . flatSignature ( ) + "\">" + methodName + "</A></B></CODE></TD><TD>" ) ; Tag [ ] firstSentenceTags = methodDoc . firstSentenceTags ( ) ; if ( firstSentenceTags . length == 0 ) { System . err . println ( "Warning: method " + methodName + " of " + methodDoc . containingClass ( ) . simpleTypeName ( ) + " has no description" ) ; } printInlineTags ( firstSentenceTags , classDoc ) ; mOut . println ( "</TD>" ) ; } mOut . println ( "</TABLE>" ) ; } |
public class OsClientV3Factory { /** * This method tries to determine if the authentication should happen by using the user provided
* information as domain ID or domain name resp . project ID or project name .
* It does so by brute forcing the four different possible combinations .
* Returns early on success .
* @ param domainIdOrName the domain id or name
* @ param projectIdOrName the project id or name
* @ param endpoint the endpoint
* @ param userId the user
* @ param password the password of the user
* @ return The valid identifiers if a valid combination exists or null if all combinations failed . */
@ Nullable private static Identifiers handleIdentifiers ( String domainIdOrName , String projectIdOrName , String endpoint , String userId , String password ) { } } | // we try all four cases and return the one that works
Set < Identifiers > possibleIdentifiers = new HashSet < Identifiers > ( ) { { add ( new Identifiers ( Identifier . byName ( domainIdOrName ) , Identifier . byName ( projectIdOrName ) ) ) ; add ( new Identifiers ( Identifier . byId ( domainIdOrName ) , Identifier . byId ( projectIdOrName ) ) ) ; add ( new Identifiers ( Identifier . byId ( domainIdOrName ) , Identifier . byName ( projectIdOrName ) ) ) ; add ( new Identifiers ( Identifier . byName ( domainIdOrName ) , Identifier . byId ( projectIdOrName ) ) ) ; } } ; for ( Identifiers candidate : possibleIdentifiers ) { try { authenticate ( endpoint , userId , password , candidate . getDomain ( ) , candidate . getProject ( ) ) ; } catch ( AuthenticationException | ClientResponseException e ) { continue ; } return candidate ; } return null ; |
public class HDFSUtil { /** * Recover the lease from HDFS , retrying multiple times . */
public void recoverFileLease ( final FileSystem fs , final Path p , Configuration conf ) throws IOException { } } | // lease recovery not needed for local file system case .
if ( ! ( fs instanceof DistributedFileSystem ) ) { return ; } recoverDFSFileLease ( ( DistributedFileSystem ) fs , p , conf ) ; |
public class Node { /** * Add or override a named attribute . < br / >
* @ param name
* The attribute name
* @ param value
* The given value
* @ return This { @ link Node } */
public Node attribute ( final String name , final String value ) { } } | this . attributes . put ( name , value ) ; return this ; |
public class JSONWriter { /** * Pop an array or object scope . < p >
* @ param c the scope to close
* @ throws JSONException zf nesting is wrong */
private void pop ( char c ) throws JSONException { } } | if ( ( m_top <= 0 ) || ( m_stack [ m_top - 1 ] != c ) ) { throw new JSONException ( "Nesting error." ) ; } m_top -= 1 ; m_mode = m_top == 0 ? 'd' : m_stack [ m_top - 1 ] ; |
public class AbstractDefinitionComparator { /** * Compare definitions
* @ param ancestorDefinition
* @ param recipientDefinition
* @ param sameDefinitionData
* @ param changedDefinitionData
* @ param newDefinitionData
* @ param removedDefinitionData */
protected void init ( T [ ] ancestorDefinition , T [ ] recipientDefinition , List < T > sameDefinitionData , List < RelatedDefinition < T > > changedDefinitionData , List < T > newDefinitionData , List < T > removedDefinitionData ) { } } | for ( int i = 0 ; i < recipientDefinition . length ; i ++ ) { boolean isNew = true ; for ( int j = 0 ; j < ancestorDefinition . length ; j ++ ) { if ( recipientDefinition [ i ] . getName ( ) . equals ( ancestorDefinition [ j ] . getName ( ) ) ) { isNew = false ; if ( recipientDefinition [ i ] . equals ( ancestorDefinition [ j ] ) ) sameDefinitionData . add ( recipientDefinition [ i ] ) ; else { RelatedDefinition < T > relatedDefinition = new RelatedDefinition < T > ( ancestorDefinition [ j ] , recipientDefinition [ i ] ) ; changedDefinitionData . add ( relatedDefinition ) ; } } } if ( isNew ) newDefinitionData . add ( recipientDefinition [ i ] ) ; } for ( int i = 0 ; i < ancestorDefinition . length ; i ++ ) { boolean isRemoved = true ; for ( int j = 0 ; j < recipientDefinition . length && isRemoved ; j ++ ) { if ( recipientDefinition [ j ] . getName ( ) . equals ( ancestorDefinition [ i ] . getName ( ) ) ) { isRemoved = false ; break ; } } if ( isRemoved ) removedDefinitionData . add ( ancestorDefinition [ i ] ) ; } |
public class AnimatedImageResult { /** * Gets a decoded frame . This will only return non - null if the { @ code ImageDecodeOptions }
* were configured to decode all frames at decode time .
* @ param index the index of the frame to get
* @ return a reference to the preview bitmap which must be released by the caller when done or
* null if there is no preview bitmap set */
public synchronized @ Nullable CloseableReference < Bitmap > getDecodedFrame ( int index ) { } } | if ( mDecodedFrames != null ) { return CloseableReference . cloneOrNull ( mDecodedFrames . get ( index ) ) ; } return null ; |
public class RelatedTablesCoreExtension { /** * Adds a media relationship between the base table and user media related
* table . Creates a default user mapping table and the media table if
* needed .
* @ param baseTableName
* base table name
* @ param mediaTable
* user media table
* @ param mappingTableName
* user mapping table name
* @ return The relationship that was added */
public ExtendedRelation addMediaRelationship ( String baseTableName , MediaTable mediaTable , String mappingTableName ) { } } | return addRelationship ( baseTableName , mediaTable , mappingTableName ) ; |
public class IOHelper { /** * Reads the data from the stream .
* @ param inputStream
* The inputStream
* @ return The data read from the provided stream
* @ throws IOException
* Any IO exception */
public static byte [ ] readStream ( InputStream inputStream ) throws IOException { } } | // create output stream
ByteArrayOutputStream outputStream = new ByteArrayOutputStream ( 5000 ) ; // read / write
IOHelper . readAndWriteStreams ( inputStream , outputStream ) ; // get data
byte [ ] data = outputStream . toByteArray ( ) ; return data ; |
public class SimpleDateFormat { /** * check whether the i - th item ' s level is lower than the input ' level '
* It is supposed to be used only by CLDR survey tool .
* It is used by intervalFormatByAlgorithm ( ) .
* @ param items the pattern items
* @ param i the i - th item in pattern items
* @ param level the level with which the i - th pattern item compared to
* @ exception IllegalArgumentException when there is non - recognized
* pattern letter
* @ return true if i - th pattern item is lower than ' level ' ,
* false otherwise */
private boolean lowerLevel ( Object [ ] items , int i , int level ) throws IllegalArgumentException { } } | if ( items [ i ] instanceof String ) { return false ; } PatternItem item = ( PatternItem ) items [ i ] ; char ch = item . type ; int patternCharIndex = getLevelFromChar ( ch ) ; if ( patternCharIndex == - 1 ) { throw new IllegalArgumentException ( "Illegal pattern character " + "'" + ch + "' in \"" + pattern + '"' ) ; } if ( patternCharIndex >= level ) { return true ; } return false ; |
public class CmsXMLSearchConfigurationParser { /** * Helper to read an optional Boolean value .
* @ param path The XML path of the element to read .
* @ return The Boolean value stored in the XML , or < code > null < / code > if the value could not be read . */
protected Boolean parseOptionalBooleanValue ( final String path ) { } } | final I_CmsXmlContentValue value = m_xml . getValue ( path , m_locale ) ; if ( value == null ) { return null ; } else { final String stringValue = value . getStringValue ( null ) ; try { final Boolean boolValue = Boolean . valueOf ( stringValue ) ; return boolValue ; } catch ( final NumberFormatException e ) { LOG . info ( Messages . get ( ) . getBundle ( ) . key ( Messages . LOG_OPTIONAL_BOOLEAN_MISSING_1 , path ) , e ) ; return null ; } } |
public class PluginRepositoryUtil { /** * Parse an XML plugin definition .
* @ param cl
* The classloader to be used to load classes
* @ param plugin
* The plugin XML element
* @ return the parsed plugin definition * @ throws PluginConfigurationException */
@ SuppressWarnings ( "rawtypes" ) private static PluginDefinition parsePluginDefinition ( final ClassLoader cl , final Element plugin ) throws PluginConfigurationException { } } | // Check if the plugin definition is inside its own file
if ( getAttributeValue ( plugin , "definedIn" , false ) != null ) { StreamManager sm = new StreamManager ( ) ; String sFileName = getAttributeValue ( plugin , "definedIn" , false ) ; try { InputStream in = sm . handle ( cl . getResourceAsStream ( sFileName ) ) ; return parseXmlPluginDefinition ( cl , in ) ; } finally { sm . closeAll ( ) ; } } String pluginClass = getAttributeValue ( plugin , "class" , true ) ; Class clazz ; try { clazz = LoadedClassCache . getClass ( cl , pluginClass ) ; if ( ! IPluginInterface . class . isAssignableFrom ( clazz ) ) { throw new PluginConfigurationException ( "Specified class '" + clazz . getName ( ) + "' in the plugin.xml file does not implement " + "the IPluginInterface interface" ) ; } if ( isAnnotated ( clazz ) ) { return loadFromPluginAnnotation ( clazz ) ; } } catch ( ClassNotFoundException e ) { throw new PluginConfigurationException ( e . getMessage ( ) , e ) ; } // The class is not annotated not has an external definition file . . .
// Loading from current xml file . . .
String sDescription = getAttributeValue ( plugin , "description" , false ) ; @ SuppressWarnings ( "unchecked" ) PluginDefinition pluginDef = new PluginDefinition ( getAttributeValue ( plugin , "name" , true ) , sDescription , clazz ) ; parseCommandLine ( pluginDef , plugin ) ; return pluginDef ; |
public class LocationMarshaller { /** * Marshall the given parameter object . */
public void marshall ( Location location , ProtocolMarshaller protocolMarshaller ) { } } | if ( location == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( location . getJdbc ( ) , JDBC_BINDING ) ; protocolMarshaller . marshall ( location . getS3 ( ) , S3_BINDING ) ; protocolMarshaller . marshall ( location . getDynamoDB ( ) , DYNAMODB_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class UiCompat { /** * Returns a themed color state list associated with a particular resource
* ID . The resource may contain either a single raw color value or a
* complex { @ link ColorStateList } holding multiple possible colors .
* @ param resources Resources
* @ param id The desired resource identifier of a { @ link ColorStateList } ,
* as generated by the aapt tool . This integer encodes the
* package , type , and resource entry . The value 0 is an invalid
* identifier .
* @ return A themed ColorStateList object containing either a single solid
* color or multiple colors that can be selected based on a state . */
public static ColorStateList getColorStateList ( Resources resources , int id ) { } } | if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . M ) { return resources . getColorStateList ( id , null ) ; } else { return resources . getColorStateList ( id ) ; } |
public class ProtoBufJSonProcessor { /** * Deserialise a JSon string representation for a protobuf message given the class of the type .
* @ param jsonStringRep the string representation of the rst value
* @ param messageClass the message class of the type .
* @ return the deserialized message .
* @ throws org . openbase . jul . exception . CouldNotPerformException is thrown in case the deserialization fails . */
public < M extends Message > M deserialize ( String jsonStringRep , Class < M > messageClass ) throws CouldNotPerformException { } } | try { try { Message . Builder builder = ( Message . Builder ) messageClass . getMethod ( "newBuilder" ) . invoke ( null ) ; jsonFormat . merge ( new ByteArrayInputStream ( jsonStringRep . getBytes ( Charset . forName ( UTF8 ) ) ) , builder ) ; return ( M ) builder . build ( ) ; } catch ( IOException ex ) { throw new CouldNotPerformException ( "Could not merge [" + jsonStringRep + "] into builder" , ex ) ; } catch ( NoSuchMethodException | SecurityException ex ) { throw new CouldNotPerformException ( "Could not find or access newBuilder method of type [" + messageClass + "]" , ex ) ; } catch ( IllegalAccessException | IllegalArgumentException | InvocationTargetException ex ) { throw new CouldNotPerformException ( "Could not invoke newBuilder method of type [" + messageClass + "]" , ex ) ; } } catch ( CouldNotPerformException | NullPointerException ex ) { throw new CouldNotPerformException ( "Could not deserialize json String[" + jsonStringRep + "] into protobuf type of Class[" + messageClass + "]!" , ex ) ; } |
public class CreateIssueParams { /** * Sets the single list type custom field with Map .
* @ param customFieldMap set of the custom field identifiers and custom field item identifiers
* @ return CreateIssueParams instance */
public CreateIssueParams singleListCustomFieldMap ( Map < Long , Long > customFieldMap ) { } } | Set < Long > keySet = customFieldMap . keySet ( ) ; for ( Long key : keySet ) { parameters . add ( new NameValuePair ( "customField_" + key . toString ( ) , customFieldMap . get ( key ) . toString ( ) ) ) ; } return this ; |
public class Matchers { /** * Returns a matcher that matches attribute maps that include the given
* attribute entry .
* @ param key attribute name
* @ param value attribute value
* @ return a { @ code Map < String , Object > } matcher */
public static Matcher < Map < String , Object > > hasAttribute ( final String key , final Object value ) { } } | return new Matcher < Map < String , Object > > ( ) { @ Override protected boolean matchesSafely ( Map < String , Object > object ) { return object . containsKey ( key ) && value . equals ( object . get ( key ) ) ; } } ; |
public class PerServerConnectionPool { /** * function to run when a connection is acquired before returning it to caller . */
private void onAcquire ( final PooledConnection conn , String httpMethod , String uriStr , int attemptNum , CurrentPassport passport ) { } } | passport . setOnChannel ( conn . getChannel ( ) ) ; removeIdleStateHandler ( conn ) ; conn . setInUse ( ) ; if ( LOG . isDebugEnabled ( ) ) LOG . debug ( "PooledConnection acquired: " + conn . toString ( ) ) ; |
public class ObservableDataBuilder { /** * Defines the function for evaluating whether two objects have the same contents , for the purpose of determining
* notifications .
* By default , content equality is evaluated using { @ link Object # equals ( Object ) } . */
@ NonNull public ObservableDataBuilder < T > contentEquality ( @ Nullable EqualityFunction < ? super T > contentEqualityFunction ) { } } | mContentEqualityFunction = contentEqualityFunction ; return this ; |
public class Activator { /** * { @ inheritDoc } */
@ Override public void stop ( BundleContext context ) throws Exception { } } | if ( hpelConfigService != null ) { for ( AbstractHPELConfigService service : hpelConfigService ) { service . stop ( ) ; } hpelConfigService = null ; } |
public class Request { /** * Creates a new Request that is configured to perform a search for places near a specified location via the Graph
* API . At least one of location or searchText must be specified .
* @ param session
* the Session to use , or null ; if non - null , the session must be in an opened state
* @ param location
* the location around which to search ; only the latitude and longitude components of the location are
* meaningful
* @ param radiusInMeters
* the radius around the location to search , specified in meters ; this is ignored if
* no location is specified
* @ param resultsLimit
* the maximum number of results to return
* @ param searchText
* optional text to search for as part of the name or type of an object
* @ param callback
* a callback that will be called when the request is completed to handle success or error conditions
* @ return a Request that is ready to execute
* @ throws FacebookException If neither location nor searchText is specified */
public static Request newPlacesSearchRequest ( Session session , Location location , int radiusInMeters , int resultsLimit , String searchText , final GraphPlaceListCallback callback ) { } } | if ( location == null && Utility . isNullOrEmpty ( searchText ) ) { throw new FacebookException ( "Either location or searchText must be specified." ) ; } Bundle parameters = new Bundle ( 5 ) ; parameters . putString ( "type" , "place" ) ; parameters . putInt ( "limit" , resultsLimit ) ; if ( location != null ) { parameters . putString ( "center" , String . format ( Locale . US , "%f,%f" , location . getLatitude ( ) , location . getLongitude ( ) ) ) ; parameters . putInt ( "distance" , radiusInMeters ) ; } if ( ! Utility . isNullOrEmpty ( searchText ) ) { parameters . putString ( "q" , searchText ) ; } Callback wrapper = new Callback ( ) { @ Override public void onCompleted ( Response response ) { if ( callback != null ) { callback . onCompleted ( typedListFromResponse ( response , GraphPlace . class ) , response ) ; } } } ; return new Request ( session , SEARCH , parameters , HttpMethod . GET , wrapper ) ; |
public class Bzip2HuffmanStageEncoder { /** * Encodes and writes the block data . */
void encode ( ByteBuf out ) { } } | // Create optimised selector list and Huffman tables
generateHuffmanOptimisationSeeds ( ) ; for ( int i = 3 ; i >= 0 ; i -- ) { optimiseSelectorsAndHuffmanTables ( i == 0 ) ; } assignHuffmanCodeSymbols ( ) ; // Write out the tables and the block data encoded with them
writeSelectorsAndHuffmanTables ( out ) ; writeBlockData ( out ) ; |
public class WalkerFactory { /** * Tell if the pattern can be ' walked ' with the iteration steps in natural
* document order , without duplicates .
* @ param compiler non - null reference to compiler object that has processed
* the XPath operations into an opcode map .
* @ param stepOpCodePos The opcode position for the step .
* @ param stepIndex The top - level step index withing the iterator .
* @ param analysis The general analysis of the pattern .
* @ return true if the walk can be done in natural order .
* @ throws javax . xml . transform . TransformerException */
private static boolean isNaturalDocOrder ( Compiler compiler , int stepOpCodePos , int stepIndex , int analysis ) throws javax . xml . transform . TransformerException { } } | if ( canCrissCross ( analysis ) ) return false ; // Namespaces can present some problems , so just punt if we ' re looking for
// these .
if ( isSet ( analysis , BIT_NAMESPACE ) ) return false ; // The following , preceding , following - sibling , and preceding sibling can
// be found in doc order if we get to this point , but if they occur
// together , they produce
// duplicates , so it ' s better for us to eliminate this case so we don ' t
// have to check for duplicates during runtime if we ' re using a
// WalkingIterator .
if ( isSet ( analysis , BIT_FOLLOWING | BIT_FOLLOWING_SIBLING ) && isSet ( analysis , BIT_PRECEDING | BIT_PRECEDING_SIBLING ) ) return false ; // OK , now we have to check for select = " @ * / axis : : * " patterns , which
// can also cause duplicates to happen . But select = " axis * / @ : : * " patterns
// are OK , as are select = " @ foo / axis : : * " patterns .
// Unfortunately , we can ' t do this just via the analysis bits .
int stepType ; int stepCount = 0 ; boolean foundWildAttribute = false ; // Steps that can traverse anything other than down a
// subtree or that can produce duplicates when used in
// combonation are counted with this variable .
int potentialDuplicateMakingStepCount = 0 ; while ( OpCodes . ENDOP != ( stepType = compiler . getOp ( stepOpCodePos ) ) ) { stepCount ++ ; switch ( stepType ) { case OpCodes . FROM_ATTRIBUTES : case OpCodes . MATCH_ATTRIBUTE : if ( foundWildAttribute ) // Maybe not needed , but be safe .
return false ; // This doesn ' t seem to work as a test for wild card . Hmph .
// int nodeTestType = compiler . getStepTestType ( stepOpCodePos ) ;
String localName = compiler . getStepLocalName ( stepOpCodePos ) ; // System . err . println ( " localName : " + localName ) ;
if ( localName . equals ( "*" ) ) { foundWildAttribute = true ; } break ; case OpCodes . FROM_FOLLOWING : case OpCodes . FROM_FOLLOWING_SIBLINGS : case OpCodes . FROM_PRECEDING : case OpCodes . FROM_PRECEDING_SIBLINGS : case OpCodes . FROM_PARENT : case OpCodes . OP_VARIABLE : case OpCodes . OP_EXTFUNCTION : case OpCodes . OP_FUNCTION : case OpCodes . OP_GROUP : case OpCodes . FROM_NAMESPACE : case OpCodes . FROM_ANCESTORS : case OpCodes . FROM_ANCESTORS_OR_SELF : case OpCodes . MATCH_ANY_ANCESTOR : case OpCodes . MATCH_IMMEDIATE_ANCESTOR : case OpCodes . FROM_DESCENDANTS_OR_SELF : case OpCodes . FROM_DESCENDANTS : if ( potentialDuplicateMakingStepCount > 0 ) return false ; potentialDuplicateMakingStepCount ++ ; case OpCodes . FROM_ROOT : case OpCodes . FROM_CHILDREN : case OpCodes . FROM_SELF : if ( foundWildAttribute ) return false ; break ; default : throw new RuntimeException ( XSLMessages . createXPATHMessage ( XPATHErrorResources . ER_NULL_ERROR_HANDLER , new Object [ ] { Integer . toString ( stepType ) } ) ) ; // " Programmer ' s assertion : unknown opcode : "
// + stepType ) ;
} int nextStepOpCodePos = compiler . getNextStepPos ( stepOpCodePos ) ; if ( nextStepOpCodePos < 0 ) break ; stepOpCodePos = nextStepOpCodePos ; } return true ; |
public class JKSecurityManager { /** * Check allowed privilige .
* @ param privilige the privilige
* @ throws SecurityException the security exception */
public static void checkAllowedPrivilige ( final JKPrivilige privilige ) { } } | logger . debug ( "checkAllowedPrivilige() : " , privilige ) ; final JKAuthorizer auth = getAuthorizer ( ) ; auth . checkAllowed ( privilige ) ; |
public class NodeTypeClient { /** * Returns the specified node type . Gets a list of available node types by making a list ( )
* request .
* < p > Sample code :
* < pre > < code >
* try ( NodeTypeClient nodeTypeClient = NodeTypeClient . create ( ) ) {
* ProjectZoneNodeTypeName nodeType = ProjectZoneNodeTypeName . of ( " [ PROJECT ] " , " [ ZONE ] " , " [ NODE _ TYPE ] " ) ;
* NodeType response = nodeTypeClient . getNodeType ( nodeType . toString ( ) ) ;
* < / code > < / pre >
* @ param nodeType Name of the node type to return .
* @ throws com . google . api . gax . rpc . ApiException if the remote call fails */
@ BetaApi public final NodeType getNodeType ( String nodeType ) { } } | GetNodeTypeHttpRequest request = GetNodeTypeHttpRequest . newBuilder ( ) . setNodeType ( nodeType ) . build ( ) ; return getNodeType ( request ) ; |
public class GoogleCloudStorageReadChannel { /** * When an IOException is thrown , depending on if the exception is caused by non - existent object
* generation , and depending on the generation read consistency setting , either retry the read ( of
* the latest generation ) , or handle the exception directly .
* @ param e IOException thrown while reading from GCS .
* @ param getObject the Get request to GCS .
* @ param retryWithLiveVersion flag indicating whether we should strip the generation ( thus read
* from the latest generation ) and retry .
* @ return the HttpResponse of reading from GCS from possible retry .
* @ throws IOException either error on retry , or thrown because the original read encounters
* error . */
private HttpResponse handleExecuteMediaException ( IOException e , Get getObject , boolean retryWithLiveVersion ) throws IOException { } } | if ( errorExtractor . itemNotFound ( e ) ) { if ( retryWithLiveVersion ) { generation = null ; footerContent = null ; getObject . setGeneration ( null ) ; try { return getObject . executeMedia ( ) ; } catch ( IOException e1 ) { return handleExecuteMediaException ( e1 , getObject , /* retryWithLiveVersion = */
false ) ; } } throw GoogleCloudStorageExceptions . getFileNotFoundException ( bucketName , objectName ) ; } String msg = String . format ( "Error reading '%s' at position %d" , resourceIdString , currentPosition ) ; if ( errorExtractor . rangeNotSatisfiable ( e ) ) { throw ( EOFException ) new EOFException ( msg ) . initCause ( e ) ; } throw new IOException ( msg , e ) ; |
public class CommandLineApplication { /** * Invokes { @ link # exit ( ExitCode ) exit } with the provided status code .
* @ param e Exit code */
protected final void bail ( final ExitCode e ) { } } | if ( e . isFailure ( ) ) { final StringBuilder bldr = new StringBuilder ( ) ; bldr . append ( "\n" ) ; bldr . append ( getApplicationShortName ( ) ) ; bldr . append ( " failed with error " ) ; bldr . append ( e ) ; bldr . append ( "." ) ; err . println ( bldr . toString ( ) ) ; } systemExit ( e ) ; |
public class CmsExportpointsList { /** * Deletes a module exportpoint from a module . < p >
* @ param module the module to delete the dependency from
* @ param exportpoint the name of the exportpoint to delete */
private void deleteExportpoint ( CmsModule module , String exportpoint ) { } } | List oldExportpoints = module . getExportPoints ( ) ; List newExportpoints = new ArrayList ( ) ; Iterator i = oldExportpoints . iterator ( ) ; while ( i . hasNext ( ) ) { CmsExportPoint exp = ( CmsExportPoint ) i . next ( ) ; if ( ! exp . getUri ( ) . equals ( exportpoint ) ) { newExportpoints . add ( exp ) ; } } module . setExportPoints ( newExportpoints ) ; // update the module information
try { OpenCms . getModuleManager ( ) . updateModule ( getCms ( ) , module ) ; } catch ( CmsConfigurationException ce ) { // should never happen
throw new CmsRuntimeException ( Messages . get ( ) . container ( Messages . ERR_ACTION_EXPORTPOINTS_DELETE_2 , exportpoint , module . getName ( ) ) , ce ) ; } catch ( CmsRoleViolationException re ) { throw new CmsRuntimeException ( Messages . get ( ) . container ( Messages . ERR_ACTION_EXPORTPOINTS_DELETE_2 , exportpoint , module . getName ( ) ) , re ) ; } |
public class WriterFactoryImpl { /** * { @ inheritDoc } */
public AnnotationTypeWriter getAnnotationTypeWriter ( AnnotationTypeDoc annotationType , Type prevType , Type nextType ) throws Exception { } } | return new AnnotationTypeWriterImpl ( configuration , annotationType , prevType , nextType ) ; |
public class TopologyBuilder { /** * Creates a platform specific stream .
* @ param sourcePi
* source processing item .
* @ return */
private Stream createStream ( IProcessingItem sourcePi ) { } } | Stream stream = this . componentFactory . createStream ( sourcePi ) ; this . topology . addStream ( stream ) ; return stream ; |
public class Initiator { /** * Invokes a write operation for the session < code > targetName < / code > and transmits the bytes in the buffer
* < code > dst < / code > . Start writing at the logical block address and transmit < code > transferLength < / code > blocks .
* @ param targetName The name of the session to invoke this write operation .
* @ param src The buffer to transmit .
* @ param logicalBlockAddress The logical block address of the beginning .
* @ param transferLength Number of bytes to write .
* @ throws TaskExecutionException if execution fails
* @ throws NoSuchSessionException if session is not found */
public final void write ( final String targetName , final ByteBuffer src , final int logicalBlockAddress , final long transferLength ) throws NoSuchSessionException , TaskExecutionException { } } | try { multiThreadedWrite ( targetName , src , logicalBlockAddress , transferLength ) . get ( ) ; } catch ( final InterruptedException exc ) { throw new TaskExecutionException ( exc ) ; } catch ( final ExecutionException exc ) { throw new TaskExecutionException ( exc ) ; } |
public class TemplateSourceImpl { /** * provides a default class injector using the contextType ' s ClassLoader
* as a parent . */
protected ClassInjector createClassInjector ( ) throws Exception { } } | return new ResolvingInjector ( mConfig . getContextSource ( ) . getContextType ( ) . getClassLoader ( ) , new File [ ] { mCompiledDir } , mConfig . getPackagePrefix ( ) , false ) ; |
public class HttpURI { public void decodeQueryTo ( MultiMap < String > parameters , String encoding ) throws UnsupportedEncodingException { } } | decodeQueryTo ( parameters , Charset . forName ( encoding ) ) ; |
public class SipResourceAdaptor { /** * ( non - Javadoc )
* @ see javax . slee . resource . ResourceAdaptor # activityEnded ( javax . slee . resource . ActivityHandle ) */
public void activityEnded ( ActivityHandle activityHandle ) { } } | final Wrapper activity = activityManagement . remove ( ( SipActivityHandle ) activityHandle ) ; if ( activity != null ) { activity . clear ( ) ; } |
public class Input { /** * Reads the length and string of UTF8 characters , or null . This can read strings written by
* { @ link Output # writeString ( String ) } and { @ link Output # writeAscii ( String ) } .
* @ return May be null . */
public String readString ( ) { } } | if ( ! readVarIntFlag ( ) ) return readAsciiString ( ) ; // ASCII .
// Null , empty , or UTF8.
int charCount = readVarIntFlag ( true ) ; switch ( charCount ) { case 0 : return null ; case 1 : return "" ; } charCount -- ; readUtf8Chars ( charCount ) ; return new String ( chars , 0 , charCount ) ; |
public class FailureDetailsMarshaller { /** * Marshall the given parameter object . */
public void marshall ( FailureDetails failureDetails , ProtocolMarshaller protocolMarshaller ) { } } | if ( failureDetails == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( failureDetails . getType ( ) , TYPE_BINDING ) ; protocolMarshaller . marshall ( failureDetails . getMessage ( ) , MESSAGE_BINDING ) ; protocolMarshaller . marshall ( failureDetails . getExternalExecutionId ( ) , EXTERNALEXECUTIONID_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class MtasFunctionParserFunctionDefault { /** * ( non - Javadoc )
* @ see
* mtas . parser . function . util . MtasFunctionParserFunction # getValueDouble ( long [ ] ,
* long ) */
@ Override public double getValueDouble ( long [ ] args , long n ) throws IOException { } } | double value = 0 ; if ( args != null ) { for ( long a : args ) { value += a ; } } return value ; |
public class TTripleInt21ObjectHashMap { /** * Removes the mapping for a key from this map if it is present ( optional operation ) . More formally , if this map contains a mapping from key < code > k < / code > to value < code > v < / code > such that
* < code > key . equals ( k ) < / code > , that mapping is removed . ( The map can contain at most one such mapping . ) < br > Returns the value to which this map previously associated the key , or < code > null < / code >
* if the map contained no mapping for the key . < br > If this map permits null values , then a return value of < code > null < / code > does not < i > necessarily < / i > indicate that the map contained no
* mapping for the key ; it ' s also possible that the map explicitly mapped the key to < code > null < / code > . < br > The map will not contain a mapping for the specified key once the call returns .
* @ param x an < code > int < / code > value
* @ param y an < code > int < / code > value
* @ param z an < code > int < / code > value
* @ return the previous < code > long < / code > value associated with < code > key ( x , y , z ) < / code > , or < code > null < / code > if there was no mapping for key . */
@ Override public T remove ( int x , int y , int z ) { } } | long key = Int21TripleHashed . key ( x , y , z ) ; return map . remove ( key ) ; |
public class CmsFlexRequest { /** * Sets the specified Map as attribute map of the request . < p >
* The map should be immutable .
* This will completely replace the attribute map .
* Use this in combination with { @ link # getAttributeMap ( ) } and
* { @ link # addAttributeMap ( Map ) } in case you want to set the old status
* of the attribute map after you have modified it for
* a specific operation . < p >
* @ param map the map to set */
public void setAttributeMap ( Map < String , Object > map ) { } } | m_attributes = new HashMap < String , Object > ( map ) ; |
public class GenericStyledArea { /** * Private methods * */
private Cell < Paragraph < PS , SEG , S > , ParagraphBox < PS , SEG , S > > createCell ( Paragraph < PS , SEG , S > paragraph , BiConsumer < TextFlow , PS > applyParagraphStyle , Function < StyledSegment < SEG , S > , Node > nodeFactory ) { } } | ParagraphBox < PS , SEG , S > box = new ParagraphBox < > ( paragraph , applyParagraphStyle , nodeFactory ) ; box . highlightTextFillProperty ( ) . bind ( highlightTextFill ) ; box . wrapTextProperty ( ) . bind ( wrapTextProperty ( ) ) ; box . graphicFactoryProperty ( ) . bind ( paragraphGraphicFactoryProperty ( ) ) ; box . graphicOffset . bind ( virtualFlow . breadthOffsetProperty ( ) ) ; EventStream < Integer > boxIndexValues = box . indexProperty ( ) . values ( ) . filter ( i -> i != - 1 ) ; Subscription firstParPseudoClass = boxIndexValues . subscribe ( idx -> box . pseudoClassStateChanged ( FIRST_PAR , idx == 0 ) ) ; Subscription lastParPseudoClass = EventStreams . combine ( boxIndexValues , getParagraphs ( ) . sizeProperty ( ) . values ( ) ) . subscribe ( in -> in . exec ( ( i , n ) -> box . pseudoClassStateChanged ( LAST_PAR , i == n - 1 ) ) ) ; // set up caret
Function < CaretNode , Subscription > subscribeToCaret = caret -> { EventStream < Integer > caretIndexStream = EventStreams . nonNullValuesOf ( caret . paragraphIndexProperty ( ) ) ; // a new event stream needs to be created for each caret added , so that it will immediately
// fire the box ' s current index value as an event , thereby running the code in the subscribe block
// Reusing boxIndexValues will not fire its most recent event , leading to a caret not being added
// Thus , we ' ll call the new event stream " fresh " box index values
EventStream < Integer > freshBoxIndexValues = box . indexProperty ( ) . values ( ) . filter ( i -> i != - 1 ) ; return EventStreams . combine ( caretIndexStream , freshBoxIndexValues ) . subscribe ( t -> { int caretParagraphIndex = t . get1 ( ) ; int boxIndex = t . get2 ( ) ; if ( caretParagraphIndex == boxIndex ) { box . caretsProperty ( ) . add ( caret ) ; } else { box . caretsProperty ( ) . remove ( caret ) ; } } ) ; } ; Subscription caretSubscription = caretSet . addSubscriber ( subscribeToCaret ) ; // TODO : how should ' hasCaret ' be handled now ?
Subscription hasCaretPseudoClass = EventStreams . combine ( boxIndexValues , Val . wrap ( currentParagraphProperty ( ) ) . values ( ) ) // box index ( t1 ) = = caret paragraph index ( t2)
. map ( t -> t . get1 ( ) . equals ( t . get2 ( ) ) ) . subscribe ( value -> box . pseudoClassStateChanged ( HAS_CARET , value ) ) ; Function < Selection < PS , SEG , S > , Subscription > subscribeToSelection = selection -> { EventStream < Integer > startParagraphValues = EventStreams . nonNullValuesOf ( selection . startParagraphIndexProperty ( ) ) ; EventStream < Integer > endParagraphValues = EventStreams . nonNullValuesOf ( selection . endParagraphIndexProperty ( ) ) ; // see comment in caret section about why a new box index EventStream is needed
EventStream < Integer > freshBoxIndexValues = box . indexProperty ( ) . values ( ) . filter ( i -> i != - 1 ) ; return EventStreams . combine ( startParagraphValues , endParagraphValues , freshBoxIndexValues ) . subscribe ( t -> { int startPar = t . get1 ( ) ; int endPar = t . get2 ( ) ; int boxIndex = t . get3 ( ) ; if ( startPar <= boxIndex && boxIndex <= endPar ) { // So that we don ' t add multiple paths for the same selection ,
// which leads to not removing the additional paths when selection is removed ,
// this is a ` Map # putIfAbsent ( Key , Value ) ` implementation that creates the path lazily
SelectionPath p = box . selectionsProperty ( ) . get ( selection ) ; if ( p == null ) { // create & configure path
Val < IndexRange > range = Val . create ( ( ) -> boxIndex != - 1 ? getParagraphSelection ( selection , boxIndex ) : EMPTY_RANGE , selection . rangeProperty ( ) ) ; SelectionPath path = new SelectionPath ( range ) ; selection . configureSelectionPath ( path ) ; box . selectionsProperty ( ) . put ( selection , path ) ; } } else { box . selectionsProperty ( ) . remove ( selection ) ; } } ) ; } ; Subscription selectionSubscription = selectionSet . addSubscriber ( subscribeToSelection ) ; return new Cell < Paragraph < PS , SEG , S > , ParagraphBox < PS , SEG , S > > ( ) { @ Override public ParagraphBox < PS , SEG , S > getNode ( ) { return box ; } @ Override public void updateIndex ( int index ) { box . setIndex ( index ) ; } @ Override public void dispose ( ) { box . highlightTextFillProperty ( ) . unbind ( ) ; box . wrapTextProperty ( ) . unbind ( ) ; box . graphicFactoryProperty ( ) . unbind ( ) ; box . graphicOffset . unbind ( ) ; box . dispose ( ) ; firstParPseudoClass . unsubscribe ( ) ; lastParPseudoClass . unsubscribe ( ) ; caretSubscription . unsubscribe ( ) ; hasCaretPseudoClass . unsubscribe ( ) ; selectionSubscription . unsubscribe ( ) ; } } ; |
public class SchemeUtils { /** * Resolves model class hierarchy ( types recognized by orient ) .
* @ param type model class
* @ return class hierarchy */
public static List < Class < ? > > resolveHierarchy ( final Class < ? > type ) { } } | final List < Class < ? > > res = Lists . newArrayList ( ) ; Class < ? > current = type ; while ( ! Object . class . equals ( current ) && current != null ) { res . add ( current ) ; current = current . getSuperclass ( ) ; } return res ; |
public class GzipOutputHandler { /** * Write the gzip header onto the output list .
* @ param list
* @ return List < WsByteBuffer > */
private List < WsByteBuffer > writeHeader ( List < WsByteBuffer > list ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) { Tr . debug ( tc , "Writing gzip header information" ) ; } WsByteBuffer hdr = HttpDispatcher . getBufferManager ( ) . allocateDirect ( GZIP_Header . length ) ; hdr . put ( GZIP_Header ) ; hdr . flip ( ) ; list . add ( hdr ) ; this . haveWrittenHeader = true ; return list ; |
public class SharedObjectService { /** * { @ inheritDoc } */
public ISharedObject getSharedObject ( IScope scope , String name , boolean persistent ) { } } | if ( ! hasSharedObject ( scope , name ) ) { createSharedObject ( scope , name , persistent ) ; } return getSharedObject ( scope , name ) ; |
public class UniqueId { /** * Attempts to convert the given string to a type enumerator
* @ param type The string to convert
* @ return a valid UniqueIdType if matched
* @ throws IllegalArgumentException if the string did not match a type
* @ since 2.0 */
public static UniqueIdType stringToUniqueIdType ( final String type ) { } } | if ( type . toLowerCase ( ) . equals ( "metric" ) || type . toLowerCase ( ) . equals ( "metrics" ) ) { return UniqueIdType . METRIC ; } else if ( type . toLowerCase ( ) . equals ( "tagk" ) ) { return UniqueIdType . TAGK ; } else if ( type . toLowerCase ( ) . equals ( "tagv" ) ) { return UniqueIdType . TAGV ; } else { throw new IllegalArgumentException ( "Invalid type requested: " + type ) ; } |
public class BaseTableLayout { /** * Padding at the right edge of the table . */
public BaseTableLayout < C , T > padRight ( float padRight ) { } } | this . padRight = new FixedValue < C , T > ( toolkit , padRight ) ; sizeInvalid = true ; return this ; |
public class FLVReader { /** * Load enough bytes from channel to buffer . After the loading process , the caller can make sure the amount in buffer is of size
* ' amount ' if we haven ' t reached the end of channel .
* @ param amount
* The amount of bytes in buffer after returning , no larger than bufferSize
* @ param reload
* Whether to reload or append */
private void fillBuffer ( long amount , boolean reload ) { } } | try { if ( amount > bufferSize ) { amount = bufferSize ; } log . debug ( "Buffering amount: {} buffer size: {}" , amount , bufferSize ) ; // Read all remaining bytes if the requested amount reach the end of channel
if ( channelSize - channel . position ( ) < amount ) { amount = channelSize - channel . position ( ) ; } if ( in == null ) { switch ( bufferType ) { case HEAP : in = IoBuffer . allocate ( bufferSize , false ) ; break ; case DIRECT : in = IoBuffer . allocate ( bufferSize , true ) ; break ; default : in = IoBuffer . allocate ( bufferSize ) ; } channel . read ( in . buf ( ) ) ; in . flip ( ) ; useLoadBuf = true ; } if ( ! useLoadBuf ) { return ; } if ( reload || in . remaining ( ) < amount ) { if ( ! reload ) { in . compact ( ) ; } else { in . clear ( ) ; } channel . read ( in . buf ( ) ) ; in . flip ( ) ; } } catch ( Exception e ) { log . error ( "Error fillBuffer" , e ) ; } |
public class CertificateReader { /** * Make the request to the Twilio API to perform the read .
* @ param client TwilioRestClient with which to make the request
* @ return Certificate ResourceSet */
@ Override public ResourceSet < Certificate > read ( final TwilioRestClient client ) { } } | return new ResourceSet < > ( this , client , firstPage ( client ) ) ; |
public class CommerceNotificationTemplatePersistenceImpl { /** * Returns an ordered range of all the commerce notification templates where groupId = & # 63 ; and enabled = & # 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 CommerceNotificationTemplateModelImpl } . 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 groupId the group ID
* @ param enabled the enabled
* @ param start the lower bound of the range of commerce notification templates
* @ param end the upper bound of the range of commerce notification templates ( not inclusive )
* @ param orderByComparator the comparator to order the results by ( optionally < code > null < / code > )
* @ return the ordered range of matching commerce notification templates */
@ Override public List < CommerceNotificationTemplate > findByG_E ( long groupId , boolean enabled , int start , int end , OrderByComparator < CommerceNotificationTemplate > orderByComparator ) { } } | return findByG_E ( groupId , enabled , start , end , orderByComparator , true ) ; |
public class GenIncrementalDomCodeVisitor { /** * Visit an { @ link PrintNode } , with special cases for a variable being printed within an attribute
* declaration or as HTML content .
* < p > For attributes , if the variable is of kind attributes , it is invoked . Any other kind of
* variable is an error .
* < p > For HTML , if the variable is of kind HTML , it is invoked . Any other kind of variable gets
* wrapped in a call to { @ code incrementalDom . text } , resulting in a Text node . */
@ Override protected void visitPrintNode ( PrintNode node ) { } } | List < Expression > chunks = genJsExprsVisitor . exec ( node ) ; switch ( node . getHtmlContext ( ) ) { case HTML_TAG : getJsCodeBuilder ( ) . append ( SOY_IDOM_PRINT_DYNAMIC_ATTR . call ( INCREMENTAL_DOM , CodeChunkUtils . concatChunks ( chunks ) ) ) ; break ; case JS : // fall through
case CSS : // fall through
case HTML_PCDATA : if ( node . numChildren ( ) > 0 && node . getChild ( node . numChildren ( ) - 1 ) . getPrintDirective ( ) instanceof SanitizedContentOperator && ( ( SanitizedContentOperator ) node . getChild ( node . numChildren ( ) - 1 ) . getPrintDirective ( ) ) . getContentKind ( ) == SanitizedContent . ContentKind . HTML ) { getJsCodeBuilder ( ) . append ( SOY_IDOM_PRINT . call ( INCREMENTAL_DOM , CodeChunkUtils . concatChunks ( chunks ) , Expression . LITERAL_TRUE ) ) ; } else { getJsCodeBuilder ( ) . append ( SOY_IDOM_PRINT . call ( INCREMENTAL_DOM , CodeChunkUtils . concatChunks ( chunks ) ) ) ; } break ; case HTML_RCDATA : getJsCodeBuilder ( ) . append ( INCREMENTAL_DOM_TEXT . call ( id ( "String" ) . call ( CodeChunkUtils . concatChunks ( chunks ) ) ) ) ; break ; default : super . visitPrintNode ( node ) ; break ; } |
public class StreamEx { /** * Creates a stream from the given input sequence around matches of the
* given pattern represented as String .
* This method is equivalent to
* { @ code StreamEx . split ( str , Pattern . compile ( regex ) ) } .
* @ param str The character sequence to be split
* @ param regex The regular expression String to use for splitting
* @ return The stream of strings computed by splitting the input around
* matches of this pattern
* @ see Pattern # splitAsStream ( CharSequence )
* @ see # split ( CharSequence , char ) */
public static StreamEx < String > split ( CharSequence str , String regex ) { } } | if ( str . length ( ) == 0 ) return of ( "" ) ; if ( regex . isEmpty ( ) ) { return IntStreamEx . ofChars ( str ) . mapToObj ( ch -> new String ( new char [ ] { ( char ) ch } ) ) ; } char ch = regex . charAt ( 0 ) ; if ( regex . length ( ) == 1 && ".$|()[{^?*+\\" . indexOf ( ch ) == - 1 ) { return split ( str , ch ) ; } else if ( regex . length ( ) == 2 && ch == '\\' ) { ch = regex . charAt ( 1 ) ; if ( ( ch < '0' || ch > '9' ) && ( ch < 'A' || ch > 'Z' ) && ( ch < 'a' || ch > 'z' ) && ( ch < Character . MIN_HIGH_SURROGATE || ch > Character . MAX_LOW_SURROGATE ) ) { return split ( str , ch ) ; } } return new StreamEx < > ( Pattern . compile ( regex ) . splitAsStream ( str ) , StreamContext . SEQUENTIAL ) ; |
public class Languages { /** * Returns the default language as derived from PippoSettings .
* @ param applicationLanguages
* @ return the default language */
private String getDefaultLanguage ( List < String > applicationLanguages ) { } } | if ( applicationLanguages . isEmpty ( ) ) { String NO_LANGUAGES_TEXT = "Please specify the supported languages in 'application.properties'." + " For example 'application.languages=en, ro, de, pt-BR' makes 'en' your default language." ; log . error ( NO_LANGUAGES_TEXT ) ; return "en" ; } // the first language specified is the default language
return applicationLanguages . get ( 0 ) ; |
public class UriUtils { /** * Returns a string that encodes a collection of key / value parameters for
* URL use .
* @ param parameters The collection of key / value parameters .
* @ return A string that encodes the collection of key / value parameters for
* URL use . */
private static String getUrlParameters ( final Collection < Pair < String , String > > parameters , final boolean formEncoding ) { } } | final StringBuilder sb = new StringBuilder ( ) ; final Iterator < Pair < String , String > > i = parameters . iterator ( ) ; if ( i . hasNext ( ) ) { final Pair < String , String > first = i . next ( ) ; sb . append ( '?' ) ; sb . append ( getKeyValuePair ( first , formEncoding ) ) ; while ( i . hasNext ( ) ) { final Pair < String , String > current = i . next ( ) ; sb . append ( '&' ) ; sb . append ( getKeyValuePair ( current , formEncoding ) ) ; } return sb . toString ( ) ; } else { return sb . toString ( ) ; } |
public class EdgeIntensityPolygon { /** * Checks to see if its a valid polygon or a false positive by looking at edge intensity
* @ param polygon The polygon being tested
* @ param ccw True if the polygon is counter clockwise
* @ return true if it could compute the edge intensity , otherwise false */
public boolean computeEdge ( Polygon2D_F64 polygon , boolean ccw ) { } } | averageInside = 0 ; averageOutside = 0 ; double tangentSign = ccw ? 1 : - 1 ; int totalSides = 0 ; for ( int i = polygon . size ( ) - 1 , j = 0 ; j < polygon . size ( ) ; i = j , j ++ ) { Point2D_F64 a = polygon . get ( i ) ; Point2D_F64 b = polygon . get ( j ) ; double dx = b . x - a . x ; double dy = b . y - a . y ; double t = Math . sqrt ( dx * dx + dy * dy ) ; dx /= t ; dy /= t ; // see if the side is too small
if ( t < 3 * cornerOffset ) { offsetA . set ( a ) ; offsetB . set ( b ) ; } else { offsetA . x = a . x + cornerOffset * dx ; offsetA . y = a . y + cornerOffset * dy ; offsetB . x = b . x - cornerOffset * dx ; offsetB . y = b . y - cornerOffset * dy ; } double tanX = - dy * tangentDistance * tangentSign ; double tanY = dx * tangentDistance * tangentSign ; scorer . computeAverageDerivative ( offsetA , offsetB , tanX , tanY ) ; if ( scorer . getSamplesInside ( ) > 0 ) { totalSides ++ ; averageInside += scorer . getAverageUp ( ) / tangentDistance ; averageOutside += scorer . getAverageDown ( ) / tangentDistance ; } } if ( totalSides > 0 ) { averageInside /= totalSides ; averageOutside /= totalSides ; } else { averageInside = averageOutside = 0 ; return false ; } return true ; |
public class ElasticIP { /** * Identify if the string is an IP address , e . g . x . x . x . x or x : x : x : x : x : x : x : x
* @ param address IP address to test
* @ return true if parameter is a normal IPv4 or IPv6 address */
private boolean isIPAddress ( @ Nonnull String address ) { } } | return ( InetAddressUtils . isIPv4Address ( address ) || InetAddressUtils . isIPv6Address ( address ) ) ; |
public class UniqueClassNameValidator { /** * Marks a type as already defined .
* @ param type - the type to mark already defined .
* @ param fileName - a file where the type is already defined .
* If fileName is null this information will not be part of the message . */
protected void addIssue ( final JvmDeclaredType type , final String fileName ) { } } | StringConcatenation _builder = new StringConcatenation ( ) ; _builder . append ( "The type " ) ; String _simpleName = type . getSimpleName ( ) ; _builder . append ( _simpleName ) ; _builder . append ( " is already defined" ) ; { if ( ( fileName != null ) ) { _builder . append ( " in " ) ; _builder . append ( fileName ) ; } } _builder . append ( "." ) ; final String message = _builder . toString ( ) ; final EObject sourceElement = this . associations . getPrimarySourceElement ( type ) ; if ( ( sourceElement == null ) ) { this . addIssue ( message , type , IssueCodes . DUPLICATE_TYPE ) ; } else { final EStructuralFeature feature = sourceElement . eClass ( ) . getEStructuralFeature ( "name" ) ; this . addIssue ( message , sourceElement , feature , IssueCodes . DUPLICATE_TYPE ) ; } |
public class UIComponentBase { /** * < p class = " changed _ added _ 2_0 " > This is a default implementation of
* { @ link javax . faces . component . behavior . ClientBehaviorHolder # getClientBehaviors } .
* < code > UIComponent < / code > does not implement the
* { @ link javax . faces . component . behavior . ClientBehaviorHolder } interface ,
* but provides default implementations for the methods defined by
* { @ link javax . faces . component . behavior . ClientBehaviorHolder } to simplify
* subclass implementations . Subclasses that wish to support the
* { @ link javax . faces . component . behavior . ClientBehaviorHolder } contract
* must declare that the subclass implements
* { @ link javax . faces . component . behavior . ClientBehaviorHolder } , and must add
* an implementation of
* { @ link javax . faces . component . behavior . ClientBehaviorHolder # getEventNames } . < / p >
* @ since 2.0 */
public Map < String , List < ClientBehavior > > getClientBehaviors ( ) { } } | if ( null == behaviors ) { return Collections . emptyMap ( ) ; } return behaviors ; |
public class SequentialEvent { /** * Adds a { @ linkplain SuppressedEvent } to the set of suppressed events of
* this Event . If a capable EventProvider determines that a certain event
* has been prevented because its listener class has been registered on this
* event using { @ link # preventCascade ( Class ) } , then the prevented event is
* registered here using this method .
* @ param e The event to add .
* @ throws IllegalArgumentException If the event is < code > null < / code > . */
public void addSuppressedEvent ( SuppressedEvent e ) { } } | if ( e == null ) { throw new IllegalArgumentException ( "e is null" ) ; } else if ( this . suppressedEvents == null ) { this . suppressedEvents = new HashSet < > ( ) ; } this . suppressedEvents . add ( e ) ; |
public class TypeChecker { /** * Creates a recursing type checker for a { @ link java . util . List } .
* @ param elementChecker The typechecker to check the elements with
* @ return a typechecker for a List containing elements passing the specified type checker */
public static < T > TypeChecker < List < ? extends T > > tList ( TypeChecker < ? extends T > elementChecker ) { } } | return new CollectionTypeChecker < > ( List . class , elementChecker ) ; |
public class Prober { /** * Start probing , waiting for { @ code condition } to become true .
* < p > This method is blocking : It returns when condition becomes true or throws an exception if timeout is reached . < / p >
* @ param timeoutInMs wait time in milliseconds */
public void probe ( long timeoutInMs ) { } } | long start = System . nanoTime ( ) ; try { while ( ! condition . call ( ) && ( elapsedMs ( start ) < timeoutInMs ) ) { Thread . yield ( ) ; } if ( ! condition . call ( ) ) { throw new IllegalStateException ( "probe condition not true after " + timeoutInMs ) ; } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } |
public class LogManager { /** * we return the given default value . */
int getIntProperty ( String name , int defaultValue ) { } } | String val = getProperty ( name ) ; if ( val == null ) { return defaultValue ; } try { return Integer . parseInt ( val . trim ( ) ) ; } catch ( Exception ex ) { return defaultValue ; } |
public class CompactDecimalDataCache { /** * Fetch data for a particular locale . Clients must not modify any part of the returned data . Portions of returned
* data may be shared so modifying it will have unpredictable results . */
DataBundle get ( ULocale locale ) { } } | DataBundle result = cache . get ( locale ) ; if ( result == null ) { result = load ( locale ) ; cache . put ( locale , result ) ; } return result ; |
public class AwsSecurityFinding { /** * A list of malware related to a finding .
* < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use
* { @ link # setMalware ( java . util . Collection ) } or { @ link # withMalware ( java . util . Collection ) } if you want to override
* the existing values .
* @ param malware
* A list of malware related to a finding .
* @ return Returns a reference to this object so that method calls can be chained together . */
public AwsSecurityFinding withMalware ( Malware ... malware ) { } } | if ( this . malware == null ) { setMalware ( new java . util . ArrayList < Malware > ( malware . length ) ) ; } for ( Malware ele : malware ) { this . malware . add ( ele ) ; } return this ; |
public class SelectAlgorithmAndInputPanel { /** * Enables / disables the ability to interact with the algorithms GUI . */
private void setActiveGUI ( final boolean isEnabled ) { } } | SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { toolbar . setEnabled ( isEnabled ) ; for ( JComboBox b : algBoxes ) { b . setEnabled ( isEnabled ) ; } for ( JComponent b : addedComponents ) { b . setEnabled ( isEnabled ) ; } imageBox . setEnabled ( isEnabled ) ; } } ) ; |
public class ChangesListener { /** * What to do if data size exceeded quota limit . Throwing exception or logging only .
* Depends on preconfigured parameter .
* @ param message
* the detail message for exception or log operation
* @ throws ExceededQuotaLimitException
* if current behavior is { @ link ExceededQuotaBehavior # EXCEPTION } */
private void behaveWhenQuotaExceeded ( String message ) throws ExceededQuotaLimitException { } } | switch ( exceededQuotaBehavior ) { case EXCEPTION : throw new ExceededQuotaLimitException ( message ) ; case WARNING : LOG . warn ( message ) ; break ; } |
public class Reflect { /** * Class new instance or null , wrap exception handling and
* instance cache . */
public static Object getNewInstance ( Class < ? > type ) { } } | if ( instanceCache . containsKey ( type ) ) return instanceCache . get ( type ) ; try { instanceCache . put ( type , type . getConstructor ( ) . newInstance ( ) ) ; } catch ( IllegalArgumentException | ReflectiveOperationException | SecurityException e ) { instanceCache . put ( type , null ) ; } return instanceCache . get ( type ) ; |
public class BootstrapSocketConnector { /** * Connects to an OOo server using the specified host and port for the
* socket and returns a component context for using the connection to the
* OOo server .
* @ param host The host
* @ param port The port
* @ return The component context */
public XComponentContext connect ( String host , int port ) throws BootstrapException { } } | String unoConnectString = "uno:socket,host=" + host + ",port=" + port + ";urp;StarOffice.ComponentContext" ; return connect ( unoConnectString ) ; |
public class MMapBuffer { /** * this is not particularly useful , the syscall takes forever */
public void advise ( long position , long length ) throws IOException { } } | final long ap = address + position ; final long a = ( ap ) / PAGE_SIZE * PAGE_SIZE ; final long l = Math . min ( length + ( ap - a ) , address + memory . length ( ) - ap ) ; final int err = madvise ( a , l ) ; if ( err != 0 ) { throw new IOException ( "madvise failed with error code: " + err ) ; } |
public class CipherSupplier { /** * visible for testing */
Cipher forMode ( int ciphermode , SecretKey key , AlgorithmParameterSpec params ) { } } | final Cipher cipher = threadLocal . get ( ) ; try { cipher . init ( ciphermode , key , params ) ; return cipher ; } catch ( InvalidKeyException e ) { throw new IllegalArgumentException ( "Invalid key." , e ) ; } catch ( InvalidAlgorithmParameterException e ) { throw new IllegalArgumentException ( "Algorithm parameter not appropriate for " + cipher . getAlgorithm ( ) + "." , e ) ; } |
public class ResponseSetCookieDissector { @ Override public void dissect ( final Parsable < ? > parsable , final String inputname ) throws DissectionFailure { } } | final ParsedField field = parsable . getParsableField ( INPUT_TYPE , inputname ) ; final String fieldValue = field . getValue ( ) . getString ( ) ; if ( fieldValue == null || fieldValue . isEmpty ( ) ) { return ; // Nothing to do here
} String [ ] parts = fieldValue . split ( ";" ) ; for ( int i = 0 ; i < parts . length ; i ++ ) { String part = parts [ i ] . trim ( ) ; String [ ] keyValue = part . split ( "=" , 2 ) ; String key = keyValue [ 0 ] . trim ( ) ; String value = "" ; if ( keyValue . length == 2 ) { value = keyValue [ 1 ] . trim ( ) ; } if ( i == 0 ) { parsable . addDissection ( inputname , "STRING" , "value" , value ) ; } else { switch ( key ) { // We ignore the max - age field because that is unsupported by IE anyway .
case "expires" : Long expires = parseExpire ( value ) ; // Backwards compatibility : STRING version is in seconds
parsable . addDissection ( inputname , "STRING" , "expires" , expires / 1000 ) ; parsable . addDissection ( inputname , "TIME.EPOCH" , "expires" , expires ) ; break ; case "domain" : parsable . addDissection ( inputname , "STRING" , "domain" , value ) ; break ; case "comment" : parsable . addDissection ( inputname , "STRING" , "comment" , value ) ; break ; case "path" : parsable . addDissection ( inputname , "STRING" , "path" , value ) ; break ; default : // Ignore anything else
} } } |
public class MethodValidator { /** * Returns the internacionalized message for this constraint violation . */
protected String extractInternacionalizedMessage ( ConstraintViolation < Object > v ) { } } | return interpolator . interpolate ( v . getMessageTemplate ( ) , new BeanValidatorContext ( v ) , locale . get ( ) ) ; |
public class CommitsApi { /** * Get a list of repository commits in a project .
* < pre > < code > GitLab Endpoint : GET / projects / : id / repository / commits < / code > < / pre >
* @ param projectIdOrPath the project in the form of an Integer ( ID ) , String ( path ) , or Project instance
* @ param ref the name of a repository branch or tag or if not given the default branch
* @ param since only commits after or on this date will be returned
* @ param until only commits before or on this date will be returned
* @ param path the path to file of a project
* @ param page the page to get
* @ param perPage the number of commits per page
* @ return a list containing the commits for the specified project ID
* @ throws GitLabApiException GitLabApiException if any exception occurs during execution */
public List < Commit > getCommits ( Object projectIdOrPath , String ref , Date since , Date until , String path , int page , int perPage ) throws GitLabApiException { } } | Form formData = new GitLabApiForm ( ) . withParam ( "ref_name" , ref ) . withParam ( "since" , ISO8601 . toString ( since , false ) ) . withParam ( "until" , ISO8601 . toString ( until , false ) ) . withParam ( "path" , ( path == null ? null : urlEncode ( path ) ) ) . withParam ( PAGE_PARAM , page ) . withParam ( PER_PAGE_PARAM , perPage ) ; Response response = get ( Response . Status . OK , formData . asMap ( ) , "projects" , getProjectIdOrPath ( projectIdOrPath ) , "repository" , "commits" ) ; return ( response . readEntity ( new GenericType < List < Commit > > ( ) { } ) ) ; |
public class DirectoryCodeBase { /** * ( non - Javadoc )
* @ see
* edu . umd . cs . findbugs . classfile . ICodeBase # lookupResource ( java . lang . String ) */
@ Override public ICodeBaseEntry lookupResource ( String resourceName ) { } } | // Translate resource name , in case a resource name
// has been overridden and the resource is being accessed
// using the overridden name .
resourceName = translateResourceName ( resourceName ) ; File file = getFullPathOfResource ( resourceName ) ; if ( ! file . exists ( ) ) { return null ; } return new DirectoryCodeBaseEntry ( this , resourceName ) ; |
public class ManagementResource { /** * ( non - Javadoc )
* @ see net . roboconf . dm . rest . services . internal . resources . IManagementResource
* # loadUploadedZippedApplicationTemplate ( java . io . InputStream , com . sun . jersey . core . header . FormDataContentDisposition ) */
@ Override public Response loadUploadedZippedApplicationTemplate ( InputStream uploadedInputStream , FormDataContentDisposition fileDetail ) { } } | this . logger . fine ( "Request: load application from an uploaded ZIP file (" + fileDetail . getFileName ( ) + ")." ) ; File tempZipFile = new File ( System . getProperty ( "java.io.tmpdir" ) , fileDetail . getFileName ( ) ) ; Response response ; try { // Copy the uploaded ZIP file on the disk
Utils . copyStream ( uploadedInputStream , tempZipFile ) ; // Load the application
response = loadZippedApplicationTemplate ( tempZipFile . toURI ( ) . toURL ( ) . toString ( ) ) ; } catch ( IOException e ) { response = handleError ( Status . NOT_ACCEPTABLE , new RestError ( REST_MNGMT_ZIP_ERROR , e ) , lang ( this . manager ) ) . build ( ) ; } finally { Utils . closeQuietly ( uploadedInputStream ) ; // We do not need the uploaded file anymore .
// In case of success , it was copied in the DM ' s configuration .
Utils . deleteFilesRecursivelyAndQuietly ( tempZipFile ) ; } return response ; |
public class BaseUpdateProvider { /** * 通过主键更新全部字段
* @ param ms */
public String updateByPrimaryKey ( MappedStatement ms ) { } } | Class < ? > entityClass = getEntityClass ( ms ) ; StringBuilder sql = new StringBuilder ( ) ; sql . append ( SqlHelper . updateTable ( entityClass , tableName ( entityClass ) ) ) ; sql . append ( SqlHelper . updateSetColumns ( entityClass , null , false , false ) ) ; sql . append ( SqlHelper . wherePKColumns ( entityClass , true ) ) ; return sql . toString ( ) ; |
public class BytecodeUtils { /** * Returns an { @ link Expression } that evaluates to the { @ link ContentKind } value that is
* equivalent to the given { @ link SanitizedContentKind } , or null . */
public static Expression constantSanitizedContentKindAsContentKind ( @ Nullable SanitizedContentKind kind ) { } } | return ( kind == null ) ? BytecodeUtils . constantNull ( CONTENT_KIND_TYPE ) : FieldRef . enumReference ( ContentKind . valueOf ( kind . name ( ) ) ) . accessor ( ) ; |
public class AndroidVariantEndpoint { /** * Update Android Variant
* @ param id id of { @ link PushApplication }
* @ param androidID id of { @ link AndroidVariant }
* @ param updatedAndroidApplication new info of { @ link AndroidVariant }
* @ return updated { @ link AndroidVariant }
* @ statuscode 200 The Android Variant updated successfully
* @ statuscode 400 The format of the client request was incorrect
* @ statuscode 404 The requested Android Variant resource does not exist */
@ PUT @ Path ( "/{androidID}" ) @ Consumes ( MediaType . APPLICATION_JSON ) @ Produces ( MediaType . APPLICATION_JSON ) public Response updateAndroidVariant ( @ PathParam ( "pushAppID" ) String id , @ PathParam ( "androidID" ) String androidID , AndroidVariant updatedAndroidApplication ) { } } | AndroidVariant androidVariant = ( AndroidVariant ) variantService . findByVariantID ( androidID ) ; if ( androidVariant != null ) { // some validation
try { validateModelClass ( updatedAndroidApplication ) ; } catch ( ConstraintViolationException cve ) { logger . info ( "Unable to update Android Variant '{}'" , androidVariant . getVariantID ( ) ) ; logger . debug ( "Details: {}" , cve ) ; // Build and return the 400 ( Bad Request ) response
ResponseBuilder builder = createBadRequestResponse ( cve . getConstraintViolations ( ) ) ; return builder . build ( ) ; } // apply updated data :
androidVariant . setGoogleKey ( updatedAndroidApplication . getGoogleKey ( ) ) ; androidVariant . setProjectNumber ( updatedAndroidApplication . getProjectNumber ( ) ) ; androidVariant . setName ( updatedAndroidApplication . getName ( ) ) ; androidVariant . setDescription ( updatedAndroidApplication . getDescription ( ) ) ; logger . trace ( "Updating Android Variant '{}'" , androidID ) ; variantService . updateVariant ( androidVariant ) ; return Response . ok ( androidVariant ) . build ( ) ; } return Response . status ( Status . NOT_FOUND ) . entity ( "Could not find requested Variant" ) . build ( ) ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.