signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class Injector { /** * Add time info to a generated gaming event . */
private static String addTimeInfoToEvent ( String message , Long currTime , int delayInMillis ) { } } | String eventTimeString = Long . toString ( ( currTime - delayInMillis ) / 1000 * 1000 ) ; // Add a ( redundant ) ' human - readable ' date string to make the data semantics more clear .
String dateString = GameConstants . DATE_TIME_FORMATTER . print ( currTime ) ; message = message + "," + eventTimeString + "," + dateString ; return message ; |
public class MarshallUtil { /** * Marshall the { @ code map } to the { @ code ObjectOutput } .
* { @ code null } maps are supported .
* @ param map { @ link Map } to marshall .
* @ param out { @ link ObjectOutput } to write . It must be non - null .
* @ param < K > Key type of the map .
* @ param < V > Value type of the map .
* @ param < T > Type of the { @ link Map } .
* @ throws IOException If any of the usual Input / Output related exceptions occur . */
public static < K , V , T extends Map < K , V > > void marshallMap ( T map , ObjectOutput out ) throws IOException { } } | final int mapSize = map == null ? NULL_VALUE : map . size ( ) ; marshallSize ( out , mapSize ) ; if ( mapSize <= 0 ) return ; for ( Map . Entry < K , V > me : map . entrySet ( ) ) { out . writeObject ( me . getKey ( ) ) ; out . writeObject ( me . getValue ( ) ) ; } |
public class Actions { /** * Converts an { @ link Action3 } to a function that calls the action and returns a specified value .
* @ param action the { @ link Action3 } to convert
* @ param result the value to return from the function call
* @ return a { @ link Func3 } that calls { @ code action } and returns { @ code result } */
public static < T1 , T2 , T3 , R > Func3 < T1 , T2 , T3 , R > toFunc ( final Action3 < T1 , T2 , T3 > action , final R result ) { } } | return new Func3 < T1 , T2 , T3 , R > ( ) { @ Override public R call ( T1 t1 , T2 t2 , T3 t3 ) { action . call ( t1 , t2 , t3 ) ; return result ; } } ; |
public class ClientIOHandler { /** * ( non - Javadoc )
* @ see
* org . jboss . netty . channel . SimpleChannelHandler # channelConnected ( org . jboss .
* netty . channel . ChannelHandlerContext ,
* org . jboss . netty . channel . ChannelStateEvent ) */
public void channelConnected ( ChannelHandlerContext ctx , ChannelStateEvent e ) throws Exception { } } | if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Connected to: {}" , getRemoteAddress ( ) ) ; } |
public class MutableClock { /** * Returns a { @ code MutableClock } that uses the specified time - zone and that
* has shared updates with this clock .
* Two clocks with shared updates always have the same instant , and all
* updates applied to either clock affect both clocks .
* @ param zone the time - zone to use for the returned clock , not null
* @ return a view of this clock in the specified time - zone , not null */
@ Override public MutableClock withZone ( ZoneId zone ) { } } | Objects . requireNonNull ( zone , "zone" ) ; if ( zone . equals ( this . zone ) ) { return this ; } return new MutableClock ( instantHolder , zone ) ; |
public class RespokeCall { /** * Attach the call ' s video renderers to the specified GLSurfaceView
* @ param glView The GLSurfaceView on which to render video */
public void attachVideoRenderer ( GLSurfaceView glView ) { } } | if ( null != glView ) { VideoRendererGui . setView ( glView , new Runnable ( ) { @ Override public void run ( ) { Log . d ( TAG , "VideoRendererGui GL Context ready" ) ; } } ) ; remoteRender = VideoRendererGui . create ( 0 , 0 , 100 , 100 , VideoRendererGui . ScalingType . SCALE_ASPECT_FILL , false ) ; localRender = VideoRendererGui . create ( 70 , 5 , 25 , 25 , VideoRendererGui . ScalingType . SCALE_ASPECT_FILL , false ) ; } |
public class AttributesImpl { /** * Look up an attribute ' s index by Namespace name .
* < p > In many cases , it will be more efficient to look up the name once and
* use the index query methods rather than using the name query methods
* repeatedly . < / p >
* @ param uri The attribute ' s Namespace URI , or the empty
* string if none is available .
* @ param localName The attribute ' s local name .
* @ return The attribute ' s index , or - 1 if none matches .
* @ see org . xml . sax . Attributes # getIndex ( java . lang . String , java . lang . String ) */
public int getIndex ( String uri , String localName ) { } } | int max = length * 5 ; for ( int i = 0 ; i < max ; i += 5 ) { if ( data [ i ] . equals ( uri ) && data [ i + 1 ] . equals ( localName ) ) { return i / 5 ; } } return - 1 ; |
public class VirtualNetworkGatewaysInner { /** * This operation retrieves a list of routes the virtual network gateway has learned , including routes learned from BGP peers .
* @ param resourceGroupName The name of the resource group .
* @ param virtualNetworkGatewayName The name of the virtual network gateway .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ throws CloudException thrown if the request is rejected by server
* @ throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @ return the GatewayRouteListResultInner object if successful . */
public GatewayRouteListResultInner beginGetLearnedRoutes ( String resourceGroupName , String virtualNetworkGatewayName ) { } } | return beginGetLearnedRoutesWithServiceResponseAsync ( resourceGroupName , virtualNetworkGatewayName ) . toBlocking ( ) . single ( ) . body ( ) ; |
public class StructurePairAligner { /** * Calculate the alignment between the two full structures with user
* provided parameters
* @ param s1
* @ param s2
* @ param params
* @ throws StructureException */
public void align ( Structure s1 , Structure s2 , StrucAligParameters params ) throws StructureException { } } | // step 1 convert the structures to Atom Arrays
Atom [ ] ca1 = getAlignmentAtoms ( s1 ) ; Atom [ ] ca2 = getAlignmentAtoms ( s2 ) ; notifyStartingAlignment ( s1 . getName ( ) , ca1 , s2 . getName ( ) , ca2 ) ; align ( ca1 , ca2 , params ) ; |
public class SortScan { /** * Positions the scan before the first record in sorted order . Internally ,
* it moves to the first record of each underlying scan . The variable
* currentScan is set to null , indicating that there is no current scan .
* @ see Scan # beforeFirst ( ) */
@ Override public void beforeFirst ( ) { } } | currentScan = null ; s1 . beforeFirst ( ) ; hasMore1 = s1 . next ( ) ; if ( s2 != null ) { s2 . beforeFirst ( ) ; hasMore2 = s2 . next ( ) ; } |
public class Http2Ping { /** * Completes this operation successfully . The stopwatch given during construction is used to
* measure the elapsed time . Registered callbacks are invoked and provided the measured elapsed
* time .
* @ return true if the operation is marked as complete ; false if it was already complete */
public boolean complete ( ) { } } | Map < ClientTransport . PingCallback , Executor > callbacks ; long roundTripTimeNanos ; synchronized ( this ) { if ( completed ) { return false ; } completed = true ; roundTripTimeNanos = this . roundTripTimeNanos = stopwatch . elapsed ( TimeUnit . NANOSECONDS ) ; callbacks = this . callbacks ; this . callbacks = null ; } for ( Map . Entry < ClientTransport . PingCallback , Executor > entry : callbacks . entrySet ( ) ) { doExecute ( entry . getValue ( ) , asRunnable ( entry . getKey ( ) , roundTripTimeNanos ) ) ; } return true ; |
public class Readability { /** * Initialize a node with the readability object . Also checks the
* className / id for special names to add to its score .
* @ param node */
private static void initializeNode ( Element node ) { } } | node . attr ( CONTENT_SCORE , Integer . toString ( 0 ) ) ; String tagName = node . tagName ( ) ; if ( "div" . equalsIgnoreCase ( tagName ) ) { incrementContentScore ( node , 5 ) ; } else if ( "pre" . equalsIgnoreCase ( tagName ) || "td" . equalsIgnoreCase ( tagName ) || "blockquote" . equalsIgnoreCase ( tagName ) ) { incrementContentScore ( node , 3 ) ; } else if ( "address" . equalsIgnoreCase ( tagName ) || "ol" . equalsIgnoreCase ( tagName ) || "ul" . equalsIgnoreCase ( tagName ) || "dl" . equalsIgnoreCase ( tagName ) || "dd" . equalsIgnoreCase ( tagName ) || "dt" . equalsIgnoreCase ( tagName ) || "li" . equalsIgnoreCase ( tagName ) || "form" . equalsIgnoreCase ( tagName ) ) { incrementContentScore ( node , - 3 ) ; } else if ( "h1" . equalsIgnoreCase ( tagName ) || "h2" . equalsIgnoreCase ( tagName ) || "h3" . equalsIgnoreCase ( tagName ) || "h4" . equalsIgnoreCase ( tagName ) || "h5" . equalsIgnoreCase ( tagName ) || "h6" . equalsIgnoreCase ( tagName ) || "th" . equalsIgnoreCase ( tagName ) ) { incrementContentScore ( node , - 5 ) ; } incrementContentScore ( node , getClassWeight ( node ) ) ; |
public class DeleteResourceRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( DeleteResourceRequest deleteResourceRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( deleteResourceRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( deleteResourceRequest . getOrganizationId ( ) , ORGANIZATIONID_BINDING ) ; protocolMarshaller . marshall ( deleteResourceRequest . getResourceId ( ) , RESOURCEID_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class DirectedGraphAdaptor { /** * { @ inheritDoc } */
public int inDegree ( int vertex ) { } } | int degree = 0 ; Set < T > edges = getAdjacencyList ( vertex ) ; if ( edges == null ) return 0 ; for ( T e : edges ) { if ( e . to ( ) == vertex ) degree ++ ; } return degree ; |
public class XMLDatabase { /** * Notifies the registered listeners that some text nodes have been
* removed .
* @ param textNodes the text nodes that have been removed
* @ param index the position of the topmost text node that has been
* removed */
protected void fireTextNodesRemoved ( ITextNode [ ] textNodes , int index ) { } } | for ( IDatabaseListener iDatabaseListener : listeners ) { iDatabaseListener . textNodesRemoved ( this , textNodes , index ) ; } |
public class MenuAPI { /** * 创建个性化菜单
* @ param access _ token access _ token
* @ param menuButtons menuButtons
* @ return BaseResult */
public static BaseResult menuAddconditional ( String access_token , MenuButtons menuButtons ) { } } | String menuJson = JsonUtil . toJSONString ( menuButtons ) ; return menuAddconditional ( access_token , menuJson ) ; |
public class CommerceNotificationTemplateUserSegmentRelLocalServiceBaseImpl { /** * Updates the commerce notification template user segment rel in the database or adds it if it does not yet exist . Also notifies the appropriate model listeners .
* @ param commerceNotificationTemplateUserSegmentRel the commerce notification template user segment rel
* @ return the commerce notification template user segment rel that was updated */
@ Indexable ( type = IndexableType . REINDEX ) @ Override public CommerceNotificationTemplateUserSegmentRel updateCommerceNotificationTemplateUserSegmentRel ( CommerceNotificationTemplateUserSegmentRel commerceNotificationTemplateUserSegmentRel ) { } } | return commerceNotificationTemplateUserSegmentRelPersistence . update ( commerceNotificationTemplateUserSegmentRel ) ; |
public class Compiler { /** * Gets the DOT graph of the AST generated at the end of compilation . */
public String getAstDotGraph ( ) throws IOException { } } | if ( jsRoot != null ) { ControlFlowAnalysis cfa = new ControlFlowAnalysis ( this , true , false ) ; cfa . process ( null , jsRoot ) ; return DotFormatter . toDot ( jsRoot , cfa . getCfg ( ) ) ; } else { return "" ; } |
public class JavaRuntimeInformation { /** * Grab a snapshot of the current system properties .
* @ param out the output stream to write diagnostics to */
@ Override public void introspect ( PrintWriter writer ) { } } | RuntimeMXBean runtime = ManagementFactory . getRuntimeMXBean ( ) ; introspectUptime ( runtime , writer ) ; introspectVendorVersion ( runtime , writer ) ; introspectInputArguments ( runtime , writer ) ; Map < String , String > props = introspectSystemProperties ( runtime , writer ) ; // introspectPaths ( runtime , writer ) ;
introspectDirsFromSystemProperties ( runtime , writer , "java.ext.dirs" , props ) ; introspectDirsFromSystemProperties ( runtime , writer , "java.endorsed.dirs" , props ) ; |
public class AbstractStub { /** * Returns a new stub with an absolute deadline .
* < p > This is mostly used for propagating an existing deadline . { @ link # withDeadlineAfter } is the
* recommended way of setting a new deadline ,
* @ since 1.0.0
* @ param deadline the deadline or { @ code null } for unsetting the deadline . */
public final S withDeadline ( @ Nullable Deadline deadline ) { } } | return build ( channel , callOptions . withDeadline ( deadline ) ) ; |
public class GetProductsRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( GetProductsRequest getProductsRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( getProductsRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( getProductsRequest . getServiceCode ( ) , SERVICECODE_BINDING ) ; protocolMarshaller . marshall ( getProductsRequest . getFilters ( ) , FILTERS_BINDING ) ; protocolMarshaller . marshall ( getProductsRequest . getFormatVersion ( ) , FORMATVERSION_BINDING ) ; protocolMarshaller . marshall ( getProductsRequest . getNextToken ( ) , NEXTTOKEN_BINDING ) ; protocolMarshaller . marshall ( getProductsRequest . getMaxResults ( ) , MAXRESULTS_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class RewriteAppender { /** * { @ inheritDoc } */
public boolean parseUnrecognizedElement ( final Element element , final Properties props ) throws Exception { } } | final String nodeName = element . getNodeName ( ) ; if ( "rewritePolicy" . equals ( nodeName ) ) { Object rewritePolicy = org . apache . log4j . xml . DOMConfigurator . parseElement ( element , props , RewritePolicy . class ) ; if ( rewritePolicy != null ) { if ( rewritePolicy instanceof OptionHandler ) { ( ( OptionHandler ) rewritePolicy ) . activateOptions ( ) ; } this . setRewritePolicy ( ( RewritePolicy ) rewritePolicy ) ; } return true ; } return false ; |
public class KNXNetworkLinkIP { /** * / * ( non - Javadoc )
* @ see tuwien . auto . calimero . link . KNXNetworkLink # setKNXMedium
* ( tuwien . auto . calimero . link . medium . KNXMediumSettings ) */
public void setKNXMedium ( KNXMediumSettings settings ) { } } | if ( settings == null ) throw new KNXIllegalArgumentException ( "medium settings are mandatory" ) ; if ( medium != null && ! settings . getClass ( ) . isAssignableFrom ( medium . getClass ( ) ) && ! medium . getClass ( ) . isAssignableFrom ( settings . getClass ( ) ) ) throw new KNXIllegalArgumentException ( "medium differs" ) ; medium = settings ; |
public class DualInputOperator { /** * Sets the second input to the union of the given operators .
* @ param inputs The operator ( s ) that form the second inputs .
* @ deprecated This method will be removed in future versions . Use the { @ link Union } operator instead . */
@ Deprecated public void setSecondInputs ( List < Operator < IN2 > > inputs ) { } } | this . input2 = Operator . createUnionCascade ( inputs ) ; |
public class KiteTicker { /** * Performs reconnection after a particular interval if count is less than maximum retries . */
public void doReconnect ( ) { } } | if ( ! tryReconnection ) return ; if ( nextReconnectInterval == 0 ) { nextReconnectInterval = ( int ) ( 2000 * Math . pow ( 2 , count ) ) ; } else { nextReconnectInterval = ( int ) ( nextReconnectInterval * Math . pow ( 2 , count ) ) ; } if ( nextReconnectInterval > maxRetryInterval ) { nextReconnectInterval = maxRetryInterval ; } if ( count <= maxRetries ) { if ( canReconnect ) { count ++ ; reconnect ( new ArrayList < > ( subscribedTokens ) ) ; canReconnect = false ; canReconnectTimer = new Timer ( ) ; canReconnectTimer . schedule ( new TimerTask ( ) { @ Override public void run ( ) { canReconnect = true ; } } , nextReconnectInterval ) ; } } else if ( count > maxRetries ) { // if number of tries exceeds maximum number of retries then stop timer .
if ( timer != null ) { timer . cancel ( ) ; timer = null ; } } |
public class Loader { /** * Loads a class from a { @ code ClassLoader } - specific cache if it ' s already there , or
* loads it from the given { @ code ClassLoader } and caching it for future requests . Failures
* to load are also cached using the Void . class type . A null { @ code ClassLoader } is assumed
* to be the system classloader . */
protected Class < ? > loadClass ( ClassLoader classLoader , String name ) { } } | // A null classloader is the system classloader .
classLoader = ( classLoader != null ) ? classLoader : ClassLoader . getSystemClassLoader ( ) ; return caches . get ( classLoader ) . get ( name ) ; |
public class SerializerBuilder { /** * Constructs buffer serializer for type , described by the given { @ code SerializerGen } .
* @ param serializerGen { @ code SerializerGen } that describes the type that is to serialize
* @ return buffer serializer for the given { @ code SerializerGen } */
private < T > BinarySerializer < T > buildBufferSerializer ( SerializerGen serializerGen ) { } } | return buildBufferSerializer ( serializerGen , Integer . MAX_VALUE ) ; |
public class MaxSATSolver { /** * Returns a new MaxSAT solver using weighted MSU3 as algorithm with the default configuration .
* @ return the MaxSAT solver */
public static MaxSATSolver wmsu3 ( ) { } } | return new MaxSATSolver ( new MaxSATConfig . Builder ( ) . incremental ( MaxSATConfig . IncrementalStrategy . ITERATIVE ) . build ( ) , Algorithm . WMSU3 ) ; |
public class AtomContainer { /** * { @ inheritDoc } */
@ Override public Iterable < ISingleElectron > singleElectrons ( ) { } } | return new Iterable < ISingleElectron > ( ) { @ Override public Iterator < ISingleElectron > iterator ( ) { return new SingleElectronIterator ( ) ; } } ; |
public class IOSDriverAugmenter { /** * Most actions can be performed using the normal augmented driver , but for findElement , the
* findElement ( s ) must be override , so need to create a new object from scratch . */
public static RemoteIOSDriver getIOSDriver ( RemoteWebDriver driver ) { } } | if ( ! ( driver . getCommandExecutor ( ) instanceof HttpCommandExecutor ) ) { throw new WebDriverException ( "ios only supports http commandExecutor." ) ; } HttpCommandExecutor e = ( HttpCommandExecutor ) driver . getCommandExecutor ( ) ; RemoteIOSDriver attach = new AttachRemoteIOSDriver ( e . getAddressOfRemoteServer ( ) , driver . getSessionId ( ) ) ; return attach ; |
public class AwsSecurityFindingFilters { /** * The canonical AWS partition name to which the region is assigned .
* @ param resourcePartition
* The canonical AWS partition name to which the region is assigned . */
public void setResourcePartition ( java . util . Collection < StringFilter > resourcePartition ) { } } | if ( resourcePartition == null ) { this . resourcePartition = null ; return ; } this . resourcePartition = new java . util . ArrayList < StringFilter > ( resourcePartition ) ; |
public class TemplateBase { /** * Get layout content as { @ link org . rythmengine . utils . RawData } . Not to be used in user application or template
* @ return layout content */
protected RawData __getSection ( ) { } } | return S . raw ( S . isEmpty ( layoutContent ) ? layoutSections . get ( "__CONTENT__" ) : layoutContent ) ; |
public class ZWaveController { /** * Handles an incoming request message .
* An incoming request message is a message initiated by a node or the controller .
* @ param incomingMessage the incoming message to process . */
private void handleIncomingRequestMessage ( SerialMessage incomingMessage ) { } } | logger . debug ( "Message type = REQUEST" ) ; switch ( incomingMessage . getMessageClass ( ) ) { case ApplicationCommandHandler : handleApplicationCommandRequest ( incomingMessage ) ; break ; case SendData : handleSendDataRequest ( incomingMessage ) ; break ; case ApplicationUpdate : handleApplicationUpdateRequest ( incomingMessage ) ; break ; default : logger . warn ( String . format ( "TODO: Implement processing of Request Message = %s (0x%02X)" , incomingMessage . getMessageClass ( ) . getLabel ( ) , incomingMessage . getMessageClass ( ) . getKey ( ) ) ) ; break ; } |
public class ObjectGraphFieldInvocation { /** * < p > invoke . < / p >
* @ param target a { @ link java . lang . Object } object .
* @ param args a { @ link java . lang . String } object .
* @ return a { @ link java . lang . Object } object .
* @ throws java . lang . Exception if any . */
public Object invoke ( Object target , String ... args ) throws Exception { } } | if ( getter ) { return field . get ( target ) ; } else { field . set ( target , TypeConversion . parse ( args [ 0 ] , field . getType ( ) ) ) ; return null ; } |
public class GCLINEImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ SuppressWarnings ( "unchecked" ) @ Override public void eSet ( int featureID , Object newValue ) { } } | switch ( featureID ) { case AfplibPackage . GCLINE__RG : getRg ( ) . clear ( ) ; getRg ( ) . addAll ( ( Collection < ? extends GCLINERG > ) newValue ) ; return ; } super . eSet ( featureID , newValue ) ; |
public class Selector { /** * Find elements matching selector .
* @ param query CSS selector
* @ param root root element to descend into
* @ return matching elements , empty if none
* @ throws Selector . SelectorParseException ( unchecked ) on an invalid CSS query . */
public static Elements select ( String query , Element root ) { } } | Validate . notEmpty ( query ) ; return select ( QueryParser . parse ( query ) , root ) ; |
public class DescribeDBEngineVersionsResult { /** * A list of < code > DBEngineVersion < / code > elements .
* @ return A list of < code > DBEngineVersion < / code > elements . */
public java . util . List < DBEngineVersion > getDBEngineVersions ( ) { } } | if ( dBEngineVersions == null ) { dBEngineVersions = new com . amazonaws . internal . SdkInternalList < DBEngineVersion > ( ) ; } return dBEngineVersions ; |
public class Preset { /** * Authenticate a Maestrano request using the appId and apiKey
* @ param marketplace
* @ param appId
* @ param apiKey
* @ return authenticated or not
* @ throws MnoException */
public boolean authenticate ( String appId , String apiKey ) throws MnoConfigurationException { } } | return appId != null && apiKey != null && appId . equals ( api . getId ( ) ) && apiKey . equals ( api . getKey ( ) ) ; |
public class WordShapeClassifier { /** * A fairly basic 5 - way classifier , that notes digits , and upper
* and lower case , mixed , and non - alphanumeric .
* @ param s String to find word shape of
* @ return Its word shape : a 5 way classification */
private static String wordShapeDan1 ( String s ) { } } | boolean digit = true ; boolean upper = true ; boolean lower = true ; boolean mixed = true ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( ! Character . isDigit ( c ) ) { digit = false ; } if ( ! Character . isLowerCase ( c ) ) { lower = false ; } if ( ! Character . isUpperCase ( c ) ) { upper = false ; } if ( ( i == 0 && ! Character . isUpperCase ( c ) ) || ( i >= 1 && ! Character . isLowerCase ( c ) ) ) { mixed = false ; } } if ( digit ) { return "ALL-DIGITS" ; } if ( upper ) { return "ALL-UPPER" ; } if ( lower ) { return "ALL-LOWER" ; } if ( mixed ) { return "MIXED-CASE" ; } return "OTHER" ; |
public class ConditionalCheck { /** * Ensures that a passed { @ code Comparable } is less than another { @ code Comparable } . The comparison is made using
* { @ code expected . compareTo ( check ) < = 0 } .
* @ param condition
* condition must be { @ code true } ^ so that the check will be performed
* @ param expected
* Expected value
* @ param check
* Comparable to be checked
* @ param message
* an error message describing why the comparables must be less than a value ( will be passed to
* { @ code IllegalNotLessThanException } )
* @ throws IllegalNotLesserThanException
* if the argument value { @ code check } is not lesser than value { @ code expected } when using method
* { @ code compareTo } */
@ ArgumentsChecked @ Throws ( { } } | IllegalNullArgumentException . class , IllegalNotLesserThanException . class } ) public static < T extends Comparable < T > > void lesserThan ( final boolean condition , @ Nonnull final T expected , @ Nonnull final T check , final String message ) { Check . notNull ( expected , "expected" ) ; Check . notNull ( check , "check" ) ; if ( condition ) { Check . lesserThan ( expected , check , message ) ; } |
public class SlackWebhooks { /** * Make a POST call to the incoming webhook url . */
@ PostConstruct public void invokeSlackWebhook ( ) { } } | RestTemplate restTemplate = new RestTemplate ( ) ; RichMessage richMessage = new RichMessage ( "Just to test Slack's incoming webhooks." ) ; // set attachments
Attachment [ ] attachments = new Attachment [ 1 ] ; attachments [ 0 ] = new Attachment ( ) ; attachments [ 0 ] . setText ( "Some data relevant to your users." ) ; richMessage . setAttachments ( attachments ) ; // For debugging purpose only
try { logger . debug ( "Reply (RichMessage): {}" , new ObjectMapper ( ) . writeValueAsString ( richMessage ) ) ; } catch ( JsonProcessingException e ) { logger . debug ( "Error parsing RichMessage: " , e ) ; } // Always remember to send the encoded message to Slack
try { restTemplate . postForEntity ( slackIncomingWebhookUrl , richMessage . encodedMessage ( ) , String . class ) ; } catch ( RestClientException e ) { logger . error ( "Error posting to Slack Incoming Webhook: " , e ) ; } |
public class XdsLoadReportStore { /** * Record that a request has been dropped by drop overload policy with the provided category
* instructed by the remote balancer . */
void recordDroppedRequest ( String category ) { } } | AtomicLong counter = dropCounters . get ( category ) ; if ( counter == null ) { counter = dropCounters . putIfAbsent ( category , new AtomicLong ( ) ) ; if ( counter == null ) { counter = dropCounters . get ( category ) ; } } counter . getAndIncrement ( ) ; |
public class PorterStemmer { /** * m ( ) measures the number of consonant sequences between 0 and j . if c is
* a consonant sequence and v a vowel sequence , and < . . > indicates
* arbitrary presence ,
* < c > < v > gives 0
* < c > vc < v > gives 1
* < c > vcvc < v > gives 2
* < c > vcvcvc < v > gives 3 */
private final int m ( ) { } } | int n = 0 ; int i = 0 ; for ( ; cons ( i ) ; ++ i ) { if ( i > j ) return n ; } i ++ ; while ( i <= j ) { for ( ; ! cons ( i ) ; ++ i ) { if ( i > j ) return n ; } i ++ ; n ++ ; if ( i > j ) return n ; for ( ; cons ( i ) ; ++ i ) { if ( i > j ) return n ; } i ++ ; } return n ; |
public class Ifc2x3tc1FactoryImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public String convertIfcFilterTypeEnumToString ( EDataType eDataType , Object instanceValue ) { } } | return instanceValue == null ? null : instanceValue . toString ( ) ; |
public class RemoteExceptionMappingStrategy { /** * This method is used for EJB 2.1 ( and earlier ) component remote interfaces
* as well as EJB 3.0 business remote interfaces that implement java . rmi . Remote .
* Generally , the exception mapping for the component and java . rmi . Remote
* business interfaces is the same , but for those differences that do exist ,
* the code should run conditionally based on the wrapper interface type . < p > */
@ Override public Exception mapCSITransactionRolledBackException ( EJSDeployedSupport s , CSITransactionRolledbackException ex ) throws CSIException { } } | // d180095
// Ensure root is set before doing the mapping .
if ( s . rootEx == null ) { s . rootEx = ExceptionUtil . findRootCause ( ex ) ; } Exception mappedEx = mapCSIException ( s , ex ) ; // set the stack trace in CORBA exception to the exception stack for
// the root cause of the exception .
mappedEx . setStackTrace ( s . rootEx . getStackTrace ( ) ) ; return mappedEx ; |
public class DataGenerator { /** * Read directory structure file under the input directory . Create each
* directory under the specified root . The directory names are relative to
* the specified root . */
@ SuppressWarnings ( "unused" ) private void genDirStructure ( ) throws IOException { } } | BufferedReader in = new BufferedReader ( new FileReader ( new File ( inDir , StructureGenerator . DIR_STRUCTURE_FILE_NAME ) ) ) ; String line ; while ( ( line = in . readLine ( ) ) != null ) { fs . mkdirs ( new Path ( root + line ) ) ; } |
public class FileValueStorage { /** * { @ inheritDoc } */
public void init ( Properties props , ValueDataResourceHolder resources ) throws IOException , RepositoryConfigurationException { } } | this . resources = resources ; prepareRootDir ( props . getProperty ( PATH ) ) ; |
public class SourceWriteUtil { /** * Write the Javadoc for the binding of a particular key , showing the context
* of the binding .
* @ param key The bound key .
* @ param writer The writer to use to write this comment .
* @ param bindingContext The context of the binding . */
public void writeBindingContextJavadoc ( SourceWriter writer , Context bindingContext , Key < ? > key ) { } } | writeBindingContextJavadoc ( writer , bindingContext , "Binding for " + key . getTypeLiteral ( ) + " declared at:" ) ; |
public class Ifc2x3tc1FactoryImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public String convertIfcWasteTerminalTypeEnumToString ( EDataType eDataType , Object instanceValue ) { } } | return instanceValue == null ? null : instanceValue . toString ( ) ; |
public class ICalPropertyScribe { /** * Unmarshals a property from a plain - text iCalendar data stream .
* @ param value the value as read off the wire
* @ param dataType the data type of the property value . The property ' s VALUE
* parameter is used to determine the data type . If the property has no
* VALUE parameter , then this parameter will be set to the property ' s
* default datatype . Note that the VALUE parameter is removed from the
* property ' s parameter list after it has been read .
* @ param parameters the parsed parameters
* @ param context the parse context
* @ return the unmarshalled property
* @ throws CannotParseException if the scribe could not parse the property ' s
* value
* @ throws SkipMeException if the property should not be added to the final
* { @ link ICalendar } object
* @ throws DataModelConversionException if the property should be converted
* to something different in order to adhere to the 2.0 data model ( only
* thrown when parsing 1.0 vCals ) */
public final T parseText ( String value , ICalDataType dataType , ICalParameters parameters , ParseContext context ) { } } | T property = _parseText ( value , dataType , parameters , context ) ; property . setParameters ( parameters ) ; return property ; |
public class DistributedAnalysisResultReducer { /** * Reduces all the analyzer results of an analysis
* @ param results
* @ param resultMap
* @ param reductionErrors */
private void reduceResults ( final List < AnalysisResultFuture > results , final Map < ComponentJob , AnalyzerResult > resultMap , final List < AnalysisResultReductionException > reductionErrors ) { } } | if ( _hasRun . get ( ) ) { // already reduced
return ; } _hasRun . set ( true ) ; for ( AnalysisResultFuture result : results ) { if ( result . isErrornous ( ) ) { logger . error ( "Encountered errorneous slave result. Result reduction will stop. Result={}" , result ) ; final List < Throwable > errors = result . getErrors ( ) ; if ( ! errors . isEmpty ( ) ) { final Throwable firstError = errors . get ( 0 ) ; logger . error ( "Encountered error before reducing results (showing stack trace of invoking the reducer): " + firstError . getMessage ( ) , new Throwable ( ) ) ; _analysisListener . errorUknown ( _masterJob , firstError ) ; } // error occurred !
return ; } } final Collection < AnalyzerJob > analyzerJobs = _masterJob . getAnalyzerJobs ( ) ; for ( AnalyzerJob masterAnalyzerJob : analyzerJobs ) { final Collection < AnalyzerResult > slaveResults = new ArrayList < AnalyzerResult > ( ) ; logger . info ( "Reducing {} slave results for component: {}" , results . size ( ) , masterAnalyzerJob ) ; for ( AnalysisResultFuture result : results ) { final Map < ComponentJob , AnalyzerResult > slaveResultMap = result . getResultMap ( ) ; final List < AnalyzerJob > slaveAnalyzerJobs = CollectionUtils2 . filterOnClass ( slaveResultMap . keySet ( ) , AnalyzerJob . class ) ; final AnalyzerJobHelper analyzerJobHelper = new AnalyzerJobHelper ( slaveAnalyzerJobs ) ; final AnalyzerJob slaveAnalyzerJob = analyzerJobHelper . getAnalyzerJob ( masterAnalyzerJob ) ; if ( slaveAnalyzerJob == null ) { throw new IllegalStateException ( "Could not resolve slave component matching [" + masterAnalyzerJob + "] in slave result: " + result ) ; } final AnalyzerResult analyzerResult = result . getResult ( slaveAnalyzerJob ) ; slaveResults . add ( analyzerResult ) ; } reduce ( masterAnalyzerJob , slaveResults , resultMap , reductionErrors ) ; } |
public class ThrowableMessageMatcher { /** * ( non - Javadoc )
* @ see org . hamcrest . Matcher # matches ( java . lang . Object ) */
public boolean matches ( Object obj ) { } } | if ( ! ( obj instanceof Throwable ) ) return false ; Throwable throwable = ( Throwable ) obj ; String foundMessage = throwable . getMessage ( ) ; return expectedMessageMatcher . matches ( foundMessage ) ; |
public class FieldAnalyzer { /** * Analyze the given String value and return the set of terms that should be indexed .
* @ param value Field value to be indexed as a binary value .
* @ return Set of terms that should be indexed . */
public Set < String > extractTerms ( String value ) { } } | try { Set < String > result = new HashSet < String > ( ) ; Set < String > split = Utils . split ( value . toLowerCase ( ) , CommonDefs . MV_SCALAR_SEP_CHAR ) ; for ( String s : split ) { String [ ] tokens = tokenize ( s ) ; for ( String token : tokens ) { if ( token . length ( ) == 0 ) continue ; result . add ( token ) ; } } return result ; } catch ( Exception e ) { // Turn into an IllegalArgumentException
throw new IllegalArgumentException ( "Error parsing field value: " + e . getLocalizedMessage ( ) ) ; } |
public class FloatPoint { /** * Adds values of two points .
* @ param point1 FloatPoint .
* @ param point2 FloatPoint .
* @ return A new FloatPoint with the add operation . */
public FloatPoint Add ( FloatPoint point1 , FloatPoint point2 ) { } } | FloatPoint result = new FloatPoint ( point1 ) ; result . Add ( point2 ) ; return result ; |
public class SignatureConverter { /** * Convenience method for generating a method signature in human readable
* form .
* @ param className
* name of the class containing the method
* @ param methodName
* the name of the method
* @ param methodSig
* the signature of the method
* @ param pkgName
* the name of the package the method is in ( used to shorten
* class names ) */
public static String convertMethodSignature ( String className , String methodName , String methodSig , String pkgName ) { } } | StringBuilder args = new StringBuilder ( ) ; SignatureConverter converter = new SignatureConverter ( methodSig ) ; converter . skip ( ) ; args . append ( '(' ) ; while ( converter . getFirst ( ) != ')' ) { if ( args . length ( ) > 1 ) { args . append ( ", " ) ; } args . append ( shorten ( pkgName , converter . parseNext ( ) ) ) ; } converter . skip ( ) ; args . append ( ')' ) ; // Ignore return type
StringBuilder result = new StringBuilder ( ) ; result . append ( className ) ; result . append ( '.' ) ; result . append ( methodName ) ; result . append ( args . toString ( ) ) ; return result . toString ( ) ; |
public class AnimaQuery { /** * query model by primary key
* @ param id primary key value
* @ return model instance */
public T byId ( Object id ) { } } | this . beforeCheck ( ) ; this . where ( primaryKeyColumn , id ) ; String sql = this . buildSelectSQL ( false ) ; T model = this . queryOne ( modelClass , sql , paramValues ) ; ifNotNullThen ( model , ( ) -> this . setJoin ( Collections . singletonList ( model ) ) ) ; return model ; |
public class AgentFilterMarshaller { /** * Marshall the given parameter object . */
public void marshall ( AgentFilter agentFilter , ProtocolMarshaller protocolMarshaller ) { } } | if ( agentFilter == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( agentFilter . getAgentHealths ( ) , AGENTHEALTHS_BINDING ) ; protocolMarshaller . marshall ( agentFilter . getAgentHealthCodes ( ) , AGENTHEALTHCODES_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class Gauge { /** * Sets the ticklabel sections to the given list of Section objects .
* @ param SECTIONS */
public void setTickLabelSections ( final List < Section > SECTIONS ) { } } | tickLabelSections . setAll ( SECTIONS ) ; Collections . sort ( tickLabelSections , new SectionComparator ( ) ) ; fireUpdateEvent ( REDRAW_EVENT ) ; |
public class ShardedCounterServiceImpl { /** * Helper method to create the { @ link CounterData } associated with the supplied counter information .
* @ param counterName
* @ return
* @ throws IllegalArgumentException If the { @ code counterName } is invalid .
* @ throws CounterExistsException If the counter with { @ code counterName } already exists in the Datastore . */
@ VisibleForTesting protected CounterData createCounterData ( final String counterName ) { } } | this . counterNameValidator . validateCounterName ( counterName ) ; final Key < CounterData > counterKey = CounterData . key ( counterName ) ; // Perform a transactional GET to see if the counter exists . If it does , throw an exception . Otherwise , create
// the counter in the same TX .
return ObjectifyService . ofy ( ) . transact ( new Work < CounterData > ( ) { @ Override public CounterData run ( ) { final CounterData loadedCounterData = ObjectifyService . ofy ( ) . load ( ) . key ( counterKey ) . now ( ) ; if ( loadedCounterData == null ) { final CounterData counterData = new CounterData ( counterName , config . getNumInitialShards ( ) ) ; ObjectifyService . ofy ( ) . save ( ) . entity ( counterData ) . now ( ) ; return counterData ; } else { throw new CounterExistsException ( counterName ) ; } } } ) ; |
public class ClassDocImpl { /** * Return interfaces implemented by this class or interfaces
* extended by this interface .
* @ return An array of ClassDocImpl representing the interfaces .
* Return an empty array if there are no interfaces . */
public ClassDoc [ ] interfaces ( ) { } } | ListBuffer < ClassDocImpl > ta = new ListBuffer < > ( ) ; for ( Type t : env . types . interfaces ( type ) ) { ta . append ( env . getClassDoc ( ( ClassSymbol ) t . tsym ) ) ; } // # # # Cache ta here ?
return ta . toArray ( new ClassDocImpl [ ta . length ( ) ] ) ; |
public class StartPersonTrackingRequestMarshaller { /** * Marshall the given parameter object . */
public void marshall ( StartPersonTrackingRequest startPersonTrackingRequest , ProtocolMarshaller protocolMarshaller ) { } } | if ( startPersonTrackingRequest == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( startPersonTrackingRequest . getVideo ( ) , VIDEO_BINDING ) ; protocolMarshaller . marshall ( startPersonTrackingRequest . getClientRequestToken ( ) , CLIENTREQUESTTOKEN_BINDING ) ; protocolMarshaller . marshall ( startPersonTrackingRequest . getNotificationChannel ( ) , NOTIFICATIONCHANNEL_BINDING ) ; protocolMarshaller . marshall ( startPersonTrackingRequest . getJobTag ( ) , JOBTAG_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class DomUtils { /** * < p > Returns the text value of a child element . Returns
* < code > null < / code > if there is no child element found . < / p >
* @ param element element
* @ return text value */
static String getElementText ( Element element ) { } } | StringBuffer buf = new StringBuffer ( ) ; NodeList children = element . getChildNodes ( ) ; for ( int i = 0 ; i < children . getLength ( ) ; i ++ ) { Node node = children . item ( i ) ; if ( node . getNodeType ( ) == Node . TEXT_NODE || node . getNodeType ( ) == Node . CDATA_SECTION_NODE ) { Text text = ( Text ) node ; buf . append ( text . getData ( ) . trim ( ) ) ; } } return buf . toString ( ) ; |
public class CoreServiceImpl { /** * Retrieve the location service using the component context .
* The location service is a required service ( the component will
* not be activated without it ) . The component context caches the
* returned service ( subsequent calls to locate are cheap ) . */
@ Override public WsLocationAdmin getLocationService ( ) { } } | WsLocationAdmin sRef = locServiceRef . get ( ) ; if ( sRef == null ) { throw new IllegalStateException ( "WsLocationAdmin service is unavailable" ) ; } return sRef ; |
public class ApplicationTenancyRepository { /** * region > findByName */
@ Programmatic public ApplicationTenancy findByNameCached ( final String name ) { } } | return queryResultsCache . execute ( new Callable < ApplicationTenancy > ( ) { @ Override public ApplicationTenancy call ( ) throws Exception { return findByName ( name ) ; } } , ApplicationTenancyRepository . class , "findByNameCached" , name ) ; |
public class AppliedTerminologyMarshaller { /** * Marshall the given parameter object . */
public void marshall ( AppliedTerminology appliedTerminology , ProtocolMarshaller protocolMarshaller ) { } } | if ( appliedTerminology == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( appliedTerminology . getName ( ) , NAME_BINDING ) ; protocolMarshaller . marshall ( appliedTerminology . getTerms ( ) , TERMS_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class NvdCveUpdater { /** * Downloads the NVD CVE Meta file properties .
* @ param url the URL to the NVD CVE JSON file
* @ return the meta file properties
* @ throws UpdateException thrown if the meta file could not be downloaded */
protected final MetaProperties getMetaFile ( String url ) throws UpdateException { } } | try { final String metaUrl = url . substring ( 0 , url . length ( ) - 7 ) + "meta" ; final URL u = new URL ( metaUrl ) ; final Downloader d = new Downloader ( settings ) ; final String content = d . fetchContent ( u , true ) ; return new MetaProperties ( content ) ; } catch ( MalformedURLException ex ) { throw new UpdateException ( "Meta file url is invalid: " + url , ex ) ; } catch ( InvalidDataException ex ) { throw new UpdateException ( "Meta file content is invalid: " + url , ex ) ; } catch ( DownloadFailedException ex ) { throw new UpdateException ( "Unable to download meta file: " + url , ex ) ; } |
public class MBeans { /** * ( non - Javadoc )
* @ see com . ibm . websphere . cache . CacheAdminMBean # getCacheIDsInMemory ( java . lang . String , java . lang . String ) */
@ Override public String [ ] getCacheIDsInMemory ( String cacheInstance , String pattern ) throws javax . management . AttributeNotFoundException { } } | // Get the cache for this cacheInstance
DCache cache1 = getCache ( cacheInstance ) ; // Check that the input pattern is a valid regular expression
Pattern cpattern = checkPattern ( pattern ) ; List < String > matchSet = new ArrayList < String > ( 10 ) ; int i = 0 ; Enumeration vEnum = cache1 . getAllIds ( ) ; while ( vEnum . hasMoreElements ( ) ) { Object key = vEnum . nextElement ( ) ; String skey = key . toString ( ) ; boolean matches = checkMatch ( cpattern , skey ) ; if ( matches ) { matchSet . add ( skey ) ; i ++ ; // if ( tc . isDebugEnabled ( ) ) {
// Tr . debug ( tc , " getCacheIDsInMemory : Cache element # " + i + " = " + skey + " matches the pattern " + pattern + " for cacheInstance = " + cacheInstance ) ;
} } if ( tc . isDebugEnabled ( ) ) Tr . debug ( tc , "getCacheIDsInMemory" + "/" + cacheInstance + "/" + "Exiting. Number of matches found = " + i ) ; // Allocate output String array # entries matched and return
// Convert to string array and return
String [ ] cids = matchSet . toArray ( new String [ matchSet . size ( ) ] ) ; return cids ; |
public class InternalXbaseWithAnnotationsParser { /** * InternalXbaseWithAnnotations . g : 532:1 : entryRuleXAnnotationOrExpression returns [ EObject current = null ] : iv _ ruleXAnnotationOrExpression = ruleXAnnotationOrExpression EOF ; */
public final EObject entryRuleXAnnotationOrExpression ( ) throws RecognitionException { } } | EObject current = null ; EObject iv_ruleXAnnotationOrExpression = null ; try { // InternalXbaseWithAnnotations . g : 532:64 : ( iv _ ruleXAnnotationOrExpression = ruleXAnnotationOrExpression EOF )
// InternalXbaseWithAnnotations . g : 533:2 : iv _ ruleXAnnotationOrExpression = ruleXAnnotationOrExpression EOF
{ if ( state . backtracking == 0 ) { newCompositeNode ( grammarAccess . getXAnnotationOrExpressionRule ( ) ) ; } pushFollow ( FOLLOW_1 ) ; iv_ruleXAnnotationOrExpression = ruleXAnnotationOrExpression ( ) ; state . _fsp -- ; if ( state . failed ) return current ; if ( state . backtracking == 0 ) { current = iv_ruleXAnnotationOrExpression ; } match ( input , EOF , FOLLOW_2 ) ; if ( state . failed ) return current ; } } catch ( RecognitionException re ) { recover ( input , re ) ; appendSkippedTokens ( ) ; } finally { } return current ; |
public class InternalXbaseParser { /** * $ ANTLR start synpred27 _ InternalXbase */
public final void synpred27_InternalXbase_fragment ( ) throws RecognitionException { } } | // InternalXbase . g : 3050:6 : ( ( ( ( ruleJvmFormalParameter ) ) ' : ' ) )
// InternalXbase . g : 3050:7 : ( ( ( ruleJvmFormalParameter ) ) ' : ' )
{ // InternalXbase . g : 3050:7 : ( ( ( ruleJvmFormalParameter ) ) ' : ' )
// InternalXbase . g : 3051:7 : ( ( ruleJvmFormalParameter ) ) ' : '
{ // InternalXbase . g : 3051:7 : ( ( ruleJvmFormalParameter ) )
// InternalXbase . g : 3052:8 : ( ruleJvmFormalParameter )
{ // InternalXbase . g : 3052:8 : ( ruleJvmFormalParameter )
// InternalXbase . g : 3053:9 : ruleJvmFormalParameter
{ pushFollow ( FOLLOW_47 ) ; ruleJvmFormalParameter ( ) ; state . _fsp -- ; if ( state . failed ) return ; } } match ( input , 61 , FOLLOW_2 ) ; if ( state . failed ) return ; } } |
public class ParquetTypeUtils { /** * / * For backward - compatibility , the type of elements in LIST - annotated structures should always be determined by the following rules :
* 1 . If the repeated field is not a group , then its type is the element type and elements are required .
* 2 . If the repeated field is a group with multiple fields , then its type is the element type and elements are required .
* 3 . If the repeated field is a group with one field and is named either array or uses the LIST - annotated group ' s name with _ tuple appended then the repeated type is the element type and elements are required .
* 4 . Otherwise , the repeated field ' s type is the element type with the repeated field ' s repetition .
* https : / / github . com / apache / parquet - format / blob / master / LogicalTypes . md # lists */
public static ColumnIO getArrayElementColumn ( ColumnIO columnIO ) { } } | while ( columnIO instanceof GroupColumnIO && ! columnIO . getType ( ) . isRepetition ( REPEATED ) ) { columnIO = ( ( GroupColumnIO ) columnIO ) . getChild ( 0 ) ; } /* If array has a standard 3 - level structure with middle level repeated group with a single field :
* optional group my _ list ( LIST ) {
* repeated group element {
* required binary str ( UTF8 ) ; */
if ( columnIO instanceof GroupColumnIO && columnIO . getType ( ) . getOriginalType ( ) == null && ( ( GroupColumnIO ) columnIO ) . getChildrenCount ( ) == 1 && ! columnIO . getName ( ) . equals ( "array" ) && ! columnIO . getName ( ) . equals ( columnIO . getParent ( ) . getName ( ) + "_tuple" ) ) { return ( ( GroupColumnIO ) columnIO ) . getChild ( 0 ) ; } /* Backward - compatibility support for 2 - level arrays where a repeated field is not a group :
* optional group my _ list ( LIST ) {
* repeated int32 element ; */
return columnIO ; |
public class PrLog { /** * < p > Makes free buyer and moving its cart by fast updates . < / p >
* @ param pRqVs request scoped vars
* @ param pRqDt Request Data
* @ param pBuTmp buyer unregistered
* @ param pBuyr buyer registered
* @ throws Exception - an exception */
public final void mkFreBuyr ( final Map < String , Object > pRqVs , final IRequestData pRqDt , final OnlineBuyer pBuTmp , final OnlineBuyer pBuyr ) throws Exception { } } | long now = new Date ( ) . getTime ( ) ; if ( ! pBuTmp . getIsNew ( ) ) { pBuTmp . setFre ( true ) ; pBuTmp . setRegEmail ( null ) ; pBuTmp . setRegisteredPassword ( null ) ; pBuTmp . setLsTm ( 0L ) ; this . srvOrm . updateEntity ( pRqVs , pBuTmp ) ; } pBuyr . setLsTm ( now ) ; UUID buseid = UUID . randomUUID ( ) ; pBuyr . setBuSeId ( buseid . toString ( ) ) ; this . srvOrm . updateEntity ( pRqVs , pBuyr ) ; pRqDt . setCookieValue ( "buSeId" , pBuyr . getBuSeId ( ) ) ; pRqDt . setCookieValue ( "cBuyerId" , pBuyr . getItsId ( ) . toString ( ) ) ; pRqDt . setAttribute ( "buyr" , pBuyr ) ; Cart oldCrt = this . srvOrm . retrieveEntityById ( pRqVs , Cart . class , pBuTmp ) ; if ( oldCrt != null && oldCrt . getTot ( ) . compareTo ( BigDecimal . ZERO ) == 1 ) { Long obid = pBuTmp . getItsId ( ) ; ColumnsValues cvs = new ColumnsValues ( ) ; cvs . setIdColumnsNames ( new String [ ] { "itsId" } ) ; cvs . put ( "itsOwner" , pBuyr . getItsId ( ) ) ; this . srvDb . executeUpdate ( "CARTLN" , cvs , "ITSOWNER=" + obid ) ; this . srvDb . executeUpdate ( "CARTTXLN" , cvs , "ITSOWNER=" + obid ) ; this . srvDb . executeUpdate ( "CARTTOT" , cvs , "ITSOWNER=" + obid ) ; Cart cart = this . srvCart . getShoppingCart ( pRqVs , pRqDt , true , false ) ; TradingSettings ts = ( TradingSettings ) pRqVs . get ( "tradSet" ) ; AccSettings as = ( AccSettings ) pRqVs . get ( "accSet" ) ; TaxDestination txRules = this . srvCart . revealTaxRules ( pRqVs , cart , as ) ; if ( txRules != null ) { pRqDt . setAttribute ( "txRules" , txRules ) ; } cart . setDeliv ( oldCrt . getDeliv ( ) ) ; cart . setPayMeth ( oldCrt . getPayMeth ( ) ) ; // redo prices and taxes :
CartLn frCl = null ; for ( CartLn cl : cart . getItems ( ) ) { if ( ! cl . getDisab ( ) ) { if ( cl . getForc ( ) ) { frCl = cl ; this . srvCart . delLine ( pRqVs , cl , txRules ) ; } else { this . srvCart . makeCartLine ( pRqVs , cl , as , ts , txRules , true , true ) ; this . srvCart . makeCartTotals ( pRqVs , ts , cl , as , txRules ) ; } } } if ( frCl != null ) { this . srvCart . hndCartChan ( pRqVs , cart , txRules ) ; } } |
public class Functions { /** * Validates an { @ link EntityID } annotation is correctly formed .
* @ param id
* ID to check . */
public static void validateEntityID ( final EntityID id ) { } } | int changes = 0 ; // Changed new UUID ( m , l )
if ( id . mostSigBits ( ) != EntityID . DEFAULT_MOST_SIG_BITS || id . leastSigBits ( ) != EntityID . DEFAULT_LEAST_SIG_BITS ) { changes ++ ; } // Changed fromString ( n )
if ( ! EntityID . DEFAULT_NAME . equals ( id . name ( ) ) ) { changes ++ ; } // Changed random
if ( id . random ( ) != EntityID . DEFAULT_RANDOM ) { changes ++ ; } // Check changed more than once
if ( changes > 1 ) { throw new IllegalArgumentException ( String . format ( "%s annotation provides multiple ID source info" , EntityID . class ) ) ; } |
public class MonitorController { /** * Uses Crafter Commons Memory Monitor POJO to get current JVM Memory stats .
* @ return { link { @ link MemoryMonitor } } */
@ RequestMapping ( value = MEMORY_URL , method = RequestMethod . GET ) public ResponseEntity < List < MemoryMonitor > > memoryStats ( ) { } } | return new ResponseEntity < > ( MemoryMonitor . getMemoryStats ( ) , HttpStatus . OK ) ; |
public class AgentInternalEventsDispatcher { /** * Execute every single Behaviors runnable , a dedicated thread will created by the executor local to this class and be used to
* execute each runnable in parallel .
* < p > This function never fails . Errors in the event handlers are logged by the executor service .
* @ param behaviorsMethodsToExecute the collection of Behaviors runnable that must be executed . */
private void executeAsynchronouslyBehaviorMethods ( Collection < Runnable > behaviorsMethodsToExecute ) { } } | for ( final Runnable runnable : behaviorsMethodsToExecute ) { this . executor . execute ( runnable ) ; } |
public class CalendarUtil { /** * Create a XMLGregorianCalendar Without Time Component .
* @ param cal a XMLGregorianCalendar , possibly with time information .
* @ return An XMLGregorianCalendar */
public XMLGregorianCalendar buildXMLGregorianCalendarDate ( XMLGregorianCalendar cal ) { } } | XMLGregorianCalendar result = null ; if ( cal != null ) { result = newXMLGregorianCalendar ( cal . getDay ( ) , cal . getMonth ( ) , cal . getYear ( ) ) ; } return result ; |
public class MultiUserChat { /** * Returns a list of < code > Occupant < / code > with the room participants .
* @ return a list of < code > Occupant < / code > with the room participants .
* @ throws XMPPErrorException if you don ' t have enough privileges to get this information .
* @ throws NoResponseException if there was no response from the server .
* @ throws NotConnectedException
* @ throws InterruptedException */
public List < Occupant > getParticipants ( ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { } } | return getOccupants ( MUCRole . participant ) ; |
public class JarBimServer { /** * Add a file appender to every logger we can find ( the loggers should already have been configured via logback . xml )
* @ throws IOException */
private void fixLogging ( BimServerConfig config ) throws IOException { } } | Path logFolder = config . getHomeDir ( ) . resolve ( "logs" ) ; if ( ! Files . isDirectory ( logFolder ) ) { Files . createDirectories ( logFolder ) ; } Path file = logFolder . resolve ( "bimserver.log" ) ; LoggerContext lc = ( LoggerContext ) LoggerFactory . getILoggerFactory ( ) ; PatternLayoutEncoder ple = new PatternLayoutEncoder ( ) ; ple . setPattern ( "%date %level [%thread] %logger{10} [%file:%line] %msg%n" ) ; ple . setContext ( lc ) ; ple . start ( ) ; FileAppender < ILoggingEvent > fileAppender = new FileAppender < ILoggingEvent > ( ) ; String filename = file . toAbsolutePath ( ) . toString ( ) ; if ( lc instanceof LoggerContext ) { if ( ! lc . isStarted ( ) ) { lc . start ( ) ; } } System . out . println ( "Logging to " + filename ) ; fileAppender . setFile ( filename ) ; fileAppender . setEncoder ( ple ) ; fileAppender . setContext ( lc ) ; fileAppender . start ( ) ; for ( ch . qos . logback . classic . Logger log : lc . getLoggerList ( ) ) { if ( log . getLevel ( ) != null ) { log . addAppender ( fileAppender ) ; } } |
public class DialogRootView { /** * Creates and returns a listener , which allows to observe the list view , which is contained by
* the dialog , is scrolled .
* @ return The listener , which has been created , as an instance of the type { @ link
* android . widget . AbsListView . OnScrollListener } . The listener may not be null */
@ NonNull private AbsListView . OnScrollListener createListViewScrollListener ( ) { } } | return new AbsListView . OnScrollListener ( ) { @ Override public void onScrollStateChanged ( final AbsListView view , final int scrollState ) { } @ Override public void onScroll ( final AbsListView view , final int firstVisibleItem , final int visibleItemCount , final int totalItemCount ) { adaptDividerVisibilities ( isListViewScrolledToTop ( view ) , isListViewScrolledToBottom ( view ) , true ) ; } } ; |
public class KeyVaultClientBaseImpl { /** * Lists the policy for a certificate .
* The GetCertificatePolicy operation returns the specified certificate policy resources in the specified key vault . This operation requires the certificates / get permission .
* @ param vaultBaseUrl The vault name , for example https : / / myvault . vault . azure . net .
* @ param certificateName The name of the certificate in a given key vault .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the CertificatePolicy object */
public Observable < CertificatePolicy > getCertificatePolicyAsync ( String vaultBaseUrl , String certificateName ) { } } | return getCertificatePolicyWithServiceResponseAsync ( vaultBaseUrl , certificateName ) . map ( new Func1 < ServiceResponse < CertificatePolicy > , CertificatePolicy > ( ) { @ Override public CertificatePolicy call ( ServiceResponse < CertificatePolicy > response ) { return response . body ( ) ; } } ) ; |
public class DbUtil { /** * Runs a SQL query that returns a single < code > String < / code > value .
* @ param con The < code > Connection < / code > against which to run the query .
* @ param def The default value to return if the query returns no results .
* @ param query The SQL query to run .
* @ param param The parameters to the SQL query .
* @ return The value returned by the query , or < code > def < / code > if the
* query returns no results . It is assumed that the query
* returns a result set consisting of a single row and column , and
* that this value is a < code > String < / code > . Any additional rows or
* columns returned will be ignored .
* @ throws SQLException If an error occurs while attempting to communicate
* with the database . */
public static String queryString ( Connection con , String def , String query , Object ... param ) throws SQLException { } } | PreparedStatement stmt = null ; try { stmt = con . prepareStatement ( query ) ; stmt . setMaxRows ( 1 ) ; for ( int i = 0 ; i < param . length ; i ++ ) { stmt . setObject ( i + 1 , param [ i ] ) ; } return queryString ( stmt , def ) ; } finally { close ( stmt ) ; } |
public class PrimitiveObjects { public static Character getCharacter ( char pValue ) { } } | if ( pValue >= CHARACTER_LOWER_BOUND && pValue <= CHARACTER_UPPER_BOUND ) { return mCharacters [ ( ( int ) pValue ) - CHARACTER_LOWER_BOUND ] ; } else { return new Character ( pValue ) ; } |
public class CommerceWishListItemPersistenceImpl { /** * Removes all the commerce wish list items where CProductId = & # 63 ; from the database .
* @ param CProductId the c product ID */
@ Override public void removeByCProductId ( long CProductId ) { } } | for ( CommerceWishListItem commerceWishListItem : findByCProductId ( CProductId , QueryUtil . ALL_POS , QueryUtil . ALL_POS , null ) ) { remove ( commerceWishListItem ) ; } |
public class CmsModuleXmlHandler { /** * Adds the digester rules for OpenCms version 5 modules . < p >
* @ param digester the digester to add the rules to */
private static void addXmlDigesterRulesForVersion5Modules ( Digester digester ) { } } | // mark method
digester . addCallMethod ( "*/" + N_MODULE + "/author" , "setOldModule" ) ; // base module information
digester . addCallParam ( "*/" + N_MODULE + "/author" , 10 ) ; digester . addCallParam ( "*/" + N_MODULE + "/email" , 11 ) ; digester . addCallParam ( "*/" + N_MODULE + "/creationdate" , 12 ) ; // dependencies
digester . addCallParam ( "*/" + N_MODULE + "/dependencies/dependency/name" , 0 ) ; digester . addCallParam ( "*/" + N_MODULE + "/dependencies/dependency/minversion" , 1 ) ; // export points
digester . addCallMethod ( "*/" + N_MODULE + "/exportpoint" , "addExportPoint" , 2 ) ; digester . addCallParam ( "*/" + N_MODULE + "/exportpoint/source" , 0 ) ; digester . addCallParam ( "*/" + N_MODULE + "/exportpoint/destination" , 1 ) ; // parameters
digester . addCallMethod ( "*/" + N_MODULE + "/parameters/para" , "addParameter" , 2 ) ; digester . addCallParam ( "*/" + N_MODULE + "/parameters/para/name" , 0 ) ; digester . addCallParam ( "*/" + N_MODULE + "/parameters/para/value" , 1 ) ; |
public class ExtendedListeningPoint { /** * Create a Record Route URI based on the host , port and transport of this listening point
* @ param usePublicAddress if true , the host will be the global ip address found by STUN otherwise
* it will be the local network interface ipaddress
* @ return the record route uri */
public javax . sip . address . SipURI createRecordRouteURI ( boolean usePublicAddress ) { } } | try { String host = getIpAddress ( usePublicAddress ) ; SipURI sipUri = SipFactoryImpl . addressFactory . createSipURI ( null , host ) ; sipUri . setPort ( port ) ; sipUri . setTransportParam ( transport ) ; // Do we want to add an ID here ?
return sipUri ; } catch ( ParseException ex ) { logger . error ( "Unexpected error while creating a record route URI" , ex ) ; throw new IllegalArgumentException ( "Unexpected exception when creating a record route URI" , ex ) ; } |
public class JobsImpl { /** * Lists the execution status of the Job Preparation and Job Release task for the specified job across the compute nodes where the job has run .
* This API returns the Job Preparation and Job Release task status on all compute nodes that have run the Job Preparation or Job Release task . This includes nodes which have since been removed from the pool . If this API is invoked on a job which has no Job Preparation or Job Release task , the Batch service returns HTTP status code 409 ( Conflict ) with an error code of JobPreparationTaskNotSpecified .
* ServiceResponseWithHeaders < PageImpl < JobPreparationAndReleaseTaskExecutionInformation > , JobListPreparationAndReleaseTaskStatusHeaders > * @ param jobId The ID of the job .
* ServiceResponseWithHeaders < PageImpl < JobPreparationAndReleaseTaskExecutionInformation > , JobListPreparationAndReleaseTaskStatusHeaders > * @ param jobListPreparationAndReleaseTaskStatusOptions Additional parameters for the operation
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the PagedList & lt ; JobPreparationAndReleaseTaskExecutionInformation & gt ; object wrapped in { @ link ServiceResponseWithHeaders } if successful . */
public Observable < ServiceResponseWithHeaders < Page < JobPreparationAndReleaseTaskExecutionInformation > , JobListPreparationAndReleaseTaskStatusHeaders > > listPreparationAndReleaseTaskStatusSinglePageAsync ( final String jobId , final JobListPreparationAndReleaseTaskStatusOptions jobListPreparationAndReleaseTaskStatusOptions ) { } } | if ( this . client . batchUrl ( ) == null ) { throw new IllegalArgumentException ( "Parameter this.client.batchUrl() is required and cannot be null." ) ; } if ( jobId == null ) { throw new IllegalArgumentException ( "Parameter jobId is required and cannot be null." ) ; } if ( this . client . apiVersion ( ) == null ) { throw new IllegalArgumentException ( "Parameter this.client.apiVersion() is required and cannot be null." ) ; } Validator . validate ( jobListPreparationAndReleaseTaskStatusOptions ) ; String filter = null ; if ( jobListPreparationAndReleaseTaskStatusOptions != null ) { filter = jobListPreparationAndReleaseTaskStatusOptions . filter ( ) ; } String select = null ; if ( jobListPreparationAndReleaseTaskStatusOptions != null ) { select = jobListPreparationAndReleaseTaskStatusOptions . select ( ) ; } Integer maxResults = null ; if ( jobListPreparationAndReleaseTaskStatusOptions != null ) { maxResults = jobListPreparationAndReleaseTaskStatusOptions . maxResults ( ) ; } Integer timeout = null ; if ( jobListPreparationAndReleaseTaskStatusOptions != null ) { timeout = jobListPreparationAndReleaseTaskStatusOptions . timeout ( ) ; } UUID clientRequestId = null ; if ( jobListPreparationAndReleaseTaskStatusOptions != null ) { clientRequestId = jobListPreparationAndReleaseTaskStatusOptions . clientRequestId ( ) ; } Boolean returnClientRequestId = null ; if ( jobListPreparationAndReleaseTaskStatusOptions != null ) { returnClientRequestId = jobListPreparationAndReleaseTaskStatusOptions . returnClientRequestId ( ) ; } DateTime ocpDate = null ; if ( jobListPreparationAndReleaseTaskStatusOptions != null ) { ocpDate = jobListPreparationAndReleaseTaskStatusOptions . ocpDate ( ) ; } String parameterizedHost = Joiner . on ( ", " ) . join ( "{batchUrl}" , this . client . batchUrl ( ) ) ; DateTimeRfc1123 ocpDateConverted = null ; if ( ocpDate != null ) { ocpDateConverted = new DateTimeRfc1123 ( ocpDate ) ; } return service . listPreparationAndReleaseTaskStatus ( jobId , this . client . apiVersion ( ) , this . client . acceptLanguage ( ) , filter , select , maxResults , timeout , clientRequestId , returnClientRequestId , ocpDateConverted , parameterizedHost , this . client . userAgent ( ) ) . flatMap ( new Func1 < Response < ResponseBody > , Observable < ServiceResponseWithHeaders < Page < JobPreparationAndReleaseTaskExecutionInformation > , JobListPreparationAndReleaseTaskStatusHeaders > > > ( ) { @ Override public Observable < ServiceResponseWithHeaders < Page < JobPreparationAndReleaseTaskExecutionInformation > , JobListPreparationAndReleaseTaskStatusHeaders > > call ( Response < ResponseBody > response ) { try { ServiceResponseWithHeaders < PageImpl < JobPreparationAndReleaseTaskExecutionInformation > , JobListPreparationAndReleaseTaskStatusHeaders > result = listPreparationAndReleaseTaskStatusDelegate ( response ) ; return Observable . just ( new ServiceResponseWithHeaders < Page < JobPreparationAndReleaseTaskExecutionInformation > , JobListPreparationAndReleaseTaskStatusHeaders > ( result . body ( ) , result . headers ( ) , result . response ( ) ) ) ; } catch ( Throwable t ) { return Observable . error ( t ) ; } } } ) ; |
public class INodeFileUnderConstruction { /** * Initialize lease recovery for this object */
void assignPrimaryDatanode ( ) { } } | // assign the first alive datanode as the primary datanode
if ( targets . length == 0 ) { NameNode . stateChangeLog . warn ( "BLOCK*" + " INodeFileUnderConstruction.initLeaseRecovery:" + " No blocks found, lease removed." ) ; } int previous = primaryNodeIndex ; Block lastBlock = this . getLastBlock ( ) ; // find an alive datanode beginning from previous .
// This causes us to cycle through the targets on successive retries .
for ( int i = 1 ; i <= targets . length ; i ++ ) { int j = ( previous + i ) % targets . length ; if ( targets [ j ] . isAlive ) { DatanodeDescriptor primary = targets [ primaryNodeIndex = j ] ; primary . addBlockToBeRecovered ( lastBlock , targets ) ; NameNode . stateChangeLog . info ( "BLOCK* " + lastBlock + " recovery started, primary=" + primary ) ; return ; } } |
public class Jackson { /** * Used to configure the provided Jackson ` ObjectMapper ` in the configuration context for the specified content type .
* [ source , groovy ]
* def http = HttpBuilder . configure {
* request . uri = " $ { serverRule . serverUrl } / jackson "
* request . contentType = OTHER _ TYPE
* Jackson . mapper ( delegate , objectMapper , [ OTHER _ TYPE ] )
* @ param config the configuration
* @ param mapper the ` ObjectMapper ` to be used .
* @ param contentTypes the content types to be configured with the mapper */
public static void mapper ( final HttpConfig config , final ObjectMapper mapper , final Iterable < String > contentTypes ) { } } | config . context ( contentTypes , OBJECT_MAPPER_ID , mapper ) ; |
public class VaadinConfirmDialog { /** * Show a modal three way ( eg . yes / no / cancel ) VaadinConfirmDialog in a window .
* @ param ui
* UI
* @ param windowCaption
* Caption for the confirmation dialog window .
* @ param message
* Message to display as window content .
* @ param okCaption
* Caption for the ok button .
* @ param cancelCaption
* Caption for cancel button .
* @ param notOKCaption
* Caption for notOK button .
* @ param listener
* Listener for dialog result .
* @ return the VaadinConfirmDialog instance created */
public static VaadinConfirmDialog show ( final UI ui , final String windowCaption , final String message , final String okCaption , final String cancelCaption , final String notOKCaption , final Listener listener ) { } } | VaadinConfirmDialog d = getFactory ( ) . create ( windowCaption , message , okCaption , cancelCaption , notOKCaption ) ; d . show ( ui , listener , true ) ; return d ; |
public class CPInstancePersistenceImpl { /** * Returns all the cp instances where groupId = & # 63 ; .
* @ param groupId the group ID
* @ return the matching cp instances */
@ Override public List < CPInstance > findByGroupId ( long groupId ) { } } | return findByGroupId ( groupId , QueryUtil . ALL_POS , QueryUtil . ALL_POS , null ) ; |
public class Feature { /** * Convenience method to get a Character member .
* @ param key name of the member
* @ return the value of the member , null if it doesn ' t exist
* @ since 1.0.0 */
public Character getCharacterProperty ( String key ) { } } | JsonElement propertyKey = properties ( ) . get ( key ) ; return propertyKey == null ? null : propertyKey . getAsCharacter ( ) ; |
public class DFSUtil { /** * Converts a string to a byte array using UTF8 encoding . */
public static byte [ ] string2Bytes ( String str ) { } } | try { final int len = str . length ( ) ; // if we can , we will use it to return the bytes
byte [ ] rawBytes = new byte [ len ] ; // get all chars of the given string
char [ ] charArray = UTF8 . getCharArray ( len ) ; str . getChars ( 0 , len , charArray , 0 ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( charArray [ i ] > UTF8 . MAX_ASCII_CODE ) { // non - ASCII chars present
// do expensive conversion
return str . getBytes ( utf8charsetName ) ; } // copy to output array
rawBytes [ i ] = ( byte ) charArray [ i ] ; } // only ASCII present - return raw bytes
return rawBytes ; } catch ( UnsupportedEncodingException e ) { assert false : "UTF8 encoding is not supported " ; } return null ; |
public class CmsDateConverter { /** * Parses the provided String as a date . < p >
* First try to parse the String with the given time format . < p >
* If that fails try to parse the date with the browser settings . < p >
* @ param dateText the string representing a date
* @ return the date created , or null if there was a parse error
* @ throws Exception in case the text can not be parsed to a date */
public static Date toDayDate ( final String dateText ) throws Exception { } } | Date date = null ; if ( dateText . length ( ) > 0 ) { date = Z_DATE_FORMAT . parse ( dateText . trim ( ) ) ; } return date ; |
public class Convertor { /** * Converts a { @ link Model } into an { @ link IAtomContainer } using the given { @ link IChemObjectBuilder } .
* @ param model RDF graph to deserialize into an { @ link IAtomContainer } .
* @ param builder { @ link IChemObjectBuilder } used to create new { @ link IChemObject } s .
* @ return a { @ link IAtomContainer } deserialized from the RDF graph . */
public static IAtomContainer model2Molecule ( Model model , IChemObjectBuilder builder ) { } } | ResIterator mols = model . listSubjectsWithProperty ( RDF . type , CDK . MOLECULE ) ; IAtomContainer mol = null ; if ( mols . hasNext ( ) ) { Resource rdfMol = mols . next ( ) ; mol = builder . newInstance ( IAtomContainer . class ) ; Map < Resource , IAtom > rdfToCDKAtomMap = new HashMap < Resource , IAtom > ( ) ; StmtIterator atoms = rdfMol . listProperties ( CDK . HASATOM ) ; while ( atoms . hasNext ( ) ) { Resource rdfAtom = atoms . nextStatement ( ) . getResource ( ) ; IAtom atom ; if ( rdfAtom . hasProperty ( RDF . type , CDK . PSEUDOATOM ) ) { atom = builder . newInstance ( IPseudoAtom . class ) ; atom . setStereoParity ( 0 ) ; Statement label = rdfAtom . getProperty ( CDK . HASLABEL ) ; if ( label != null ) ( ( IPseudoAtom ) atom ) . setLabel ( label . getString ( ) ) ; } else { atom = builder . newInstance ( IAtom . class ) ; } Statement symbol = rdfAtom . getProperty ( CDK . SYMBOL ) ; if ( symbol != null ) atom . setSymbol ( symbol . getString ( ) ) ; rdfToCDKAtomMap . put ( rdfAtom , atom ) ; deserializeAtomTypeFields ( rdfAtom , atom ) ; mol . addAtom ( atom ) ; } StmtIterator bonds = rdfMol . listProperties ( CDK . HASBOND ) ; while ( bonds . hasNext ( ) ) { Resource rdfBond = bonds . nextStatement ( ) . getResource ( ) ; IBond bond = builder . newInstance ( IBond . class ) ; StmtIterator bondAtoms = rdfBond . listProperties ( CDK . BINDSATOM ) ; int atomCounter = 0 ; while ( bondAtoms . hasNext ( ) ) { Statement rdfAtom = bondAtoms . nextStatement ( ) ; IAtom atom = rdfToCDKAtomMap . get ( rdfAtom . getResource ( ) ) ; bond . setAtom ( atom , atomCounter ) ; atomCounter ++ ; } Resource order = rdfBond . getProperty ( CDK . HASORDER ) . getResource ( ) ; bond . setOrder ( resource2Order ( order ) ) ; mol . addBond ( bond ) ; deserializeElectronContainerFields ( rdfBond , bond ) ; } } return mol ; |
public class ObjectFactory { /** * Create an instance of { @ link JAXBElement } { @ code < }
* { @ link CmisExtensionType } { @ code > } */
@ XmlElementDecl ( namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/" , name = "extension" , scope = MoveObject . class ) public JAXBElement < CmisExtensionType > createMoveObjectExtension ( CmisExtensionType value ) { } } | return new JAXBElement < CmisExtensionType > ( _GetPropertiesExtension_QNAME , CmisExtensionType . class , MoveObject . class , value ) ; |
public class GeometryConverter { private static org . geomajas . gwt . client . spatial . geometry . Geometry [ ] convertGeometries ( Geometry geometry , org . geomajas . gwt . client . spatial . geometry . Geometry [ ] geometries ) { } } | for ( int i = 0 ; i < geometries . length ; i ++ ) { geometries [ i ] = toGwt ( geometry . getGeometries ( ) [ i ] ) ; } return geometries ; |
public class HtmlDocumentBuilder { /** * < p > useTags . < / p >
* @ param tags a { @ link java . lang . String } object .
* @ return a { @ link com . greenpepper . html . HtmlDocumentBuilder } object . */
public HtmlDocumentBuilder useTags ( String ... tags ) { } } | this . tags . clear ( ) ; this . tags . addAll ( Arrays . asList ( tags ) ) ; return this ; |
public class ServerFeatureServiceImpl { @ Override public void search ( String crs , final VectorServerLayer layer , Geometry location , double buffer , final FeatureMapFunction callback ) { } } | SearchByLocationRequest request = new SearchByLocationRequest ( ) ; request . setBuffer ( buffer ) ; request . addLayerWithFilter ( layer . getServerLayerId ( ) , layer . getServerLayerId ( ) , layer . getFilter ( ) ) ; request . setLocation ( location ) ; request . setSearchType ( SearchLayerType . SEARCH_ALL_LAYERS . getValue ( ) ) ; request . setCrs ( crs ) ; request . setFeatureIncludes ( 11 ) ; GwtCommand command = new GwtCommand ( SearchByLocationRequest . COMMAND ) ; command . setCommandRequest ( request ) ; GeomajasServerExtension . getInstance ( ) . getCommandService ( ) . execute ( command , new AbstractCommandCallback < SearchByLocationResponse > ( ) { public void execute ( SearchByLocationResponse response ) { for ( List < org . geomajas . layer . feature . Feature > dtos : response . getFeatureMap ( ) . values ( ) ) { List < Feature > features = new ArrayList < Feature > ( dtos . size ( ) ) ; for ( org . geomajas . layer . feature . Feature feature : dtos ) { features . add ( create ( feature , layer ) ) ; } Map < FeaturesSupported , List < Feature > > map = new HashMap < FeaturesSupported , List < Feature > > ( ) ; map . put ( layer , features ) ; callback . execute ( map ) ; } } } ) ; |
public class OsgiKieModule { /** * Determines if the provided string is OSGi bundle URL or not .
* @ param str string to check
* @ return true if the string is OSGi bundle URL , otherwise false */
public static boolean isOsgiBundleUrl ( String str ) { } } | if ( str == null ) { throw new NullPointerException ( "Specified string can not be null!" ) ; } return str . startsWith ( "bundle" ) && str . contains ( "://" ) ; |
public class JsonFormat { /** * Parses an object from an input stream , does not close the input stream . */
public < T > T read ( final InputStream stream , final DataTypeDescriptor < T > descriptor ) { } } | try { return jsonFormat . read ( stream , descriptor ) ; } catch ( Exception e ) { throw propagate ( e ) ; } |
public class CertUtil { /** * 验证书链 。
* @ param cert
* @ return */
private static boolean verifyCertificateChain ( X509Certificate cert ) { } } | if ( null == cert ) { LogUtil . writeErrorLog ( "cert must Not null" ) ; return false ; } X509Certificate middleCert = CertUtil . getMiddleCert ( ) ; if ( null == middleCert ) { LogUtil . writeErrorLog ( "middleCert must Not null" ) ; return false ; } X509Certificate rootCert = CertUtil . getRootCert ( ) ; if ( null == rootCert ) { LogUtil . writeErrorLog ( "rootCert or cert must Not null" ) ; return false ; } try { X509CertSelector selector = new X509CertSelector ( ) ; selector . setCertificate ( cert ) ; Set < TrustAnchor > trustAnchors = new HashSet < TrustAnchor > ( ) ; trustAnchors . add ( new TrustAnchor ( rootCert , null ) ) ; PKIXBuilderParameters pkixParams = new PKIXBuilderParameters ( trustAnchors , selector ) ; Set < X509Certificate > intermediateCerts = new HashSet < X509Certificate > ( ) ; intermediateCerts . add ( rootCert ) ; intermediateCerts . add ( middleCert ) ; intermediateCerts . add ( cert ) ; pkixParams . setRevocationEnabled ( false ) ; CertStore intermediateCertStore = CertStore . getInstance ( "Collection" , new CollectionCertStoreParameters ( intermediateCerts ) , "BC" ) ; pkixParams . addCertStore ( intermediateCertStore ) ; CertPathBuilder builder = CertPathBuilder . getInstance ( "PKIX" , "BC" ) ; @ SuppressWarnings ( "unused" ) PKIXCertPathBuilderResult result = ( PKIXCertPathBuilderResult ) builder . build ( pkixParams ) ; LogUtil . writeLog ( "verify certificate chain succeed." ) ; return true ; } catch ( java . security . cert . CertPathBuilderException e ) { LogUtil . writeErrorLog ( "verify certificate chain fail." , e ) ; } catch ( Exception e ) { LogUtil . writeErrorLog ( "verify certificate chain exception: " , e ) ; } return false ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.