signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class WeekView { /** * Draw all the events of a particular day .
* @ param date The day .
* @ param startFromPixel The left position of the day area . The events will never go any left from this value .
* @ param canvas The canvas to draw upon . */
private void drawEvents ( Calendar date , float startFromPixel , Canvas canvas ) { } } | if ( mEventRects != null && mEventRects . size ( ) > 0 ) { for ( int i = 0 ; i < mEventRects . size ( ) ; i ++ ) { if ( isSameDay ( mEventRects . get ( i ) . event . getStartTime ( ) , date ) && ! mEventRects . get ( i ) . event . isAllDay ( ) ) { // Calculate top .
float top = mHourHeight * 24 * mEventRects . get ( i ) . top / 1440 + mCurrentOrigin . y + mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight / 2 + mEventMarginVertical ; // Calculate bottom .
float bottom = mEventRects . get ( i ) . bottom ; bottom = mHourHeight * 24 * bottom / 1440 + mCurrentOrigin . y + mHeaderHeight + mHeaderRowPadding * 2 + mHeaderMarginBottom + mTimeTextHeight / 2 - mEventMarginVertical ; // Calculate left and right .
float left = startFromPixel + mEventRects . get ( i ) . left * mWidthPerDay ; if ( left < startFromPixel ) left += mOverlappingEventGap ; float right = left + mEventRects . get ( i ) . width * mWidthPerDay ; if ( right < startFromPixel + mWidthPerDay ) right -= mOverlappingEventGap ; // Draw the event and the event name on top of it .
if ( left < right && left < getWidth ( ) && top < getHeight ( ) && right > mHeaderColumnWidth && bottom > mHeaderHeight + mHeaderRowPadding * 2 + mTimeTextHeight / 2 + mHeaderMarginBottom ) { mEventRects . get ( i ) . rectF = new RectF ( left , top , right , bottom ) ; mEventBackgroundPaint . setColor ( mEventRects . get ( i ) . event . getColor ( ) == 0 ? mDefaultEventColor : mEventRects . get ( i ) . event . getColor ( ) ) ; canvas . drawRoundRect ( mEventRects . get ( i ) . rectF , mEventCornerRadius , mEventCornerRadius , mEventBackgroundPaint ) ; drawEventTitle ( mEventRects . get ( i ) . event , mEventRects . get ( i ) . rectF , canvas , top , left ) ; } else mEventRects . get ( i ) . rectF = null ; } } } |
public class RequestFromVertx { /** * Same like { @ link # parameter ( String ) } , but converts the parameter to
* Boolean if found .
* The parameter is decoded by default .
* @ param name The name of the post or query parameter
* @ param defaultValue A default value if parameter not found .
* @ return The value of the parameter or the defaultValue if not found . */
@ Override public Boolean parameterAsBoolean ( String name , boolean defaultValue ) { } } | // We have to check if the map contains the key , as the retrieval method returns false on missing key .
if ( ! request . params ( ) . contains ( name ) ) { return defaultValue ; } Boolean parameter = parameterAsBoolean ( name ) ; if ( parameter == null ) { return defaultValue ; } return parameter ; |
public class LdapServices { /** * Get the { @ link ILdapServer } from the portal spring context with the specified name .
* @ param name The name of the ILdapServer to return .
* @ return An { @ link ILdapServer } with the specified name , < code > null < / code > if there is no
* connection with the specified name . */
public static ILdapServer getLdapServer ( String name ) { } } | final ApplicationContext applicationContext = PortalApplicationContextLocator . getApplicationContext ( ) ; ILdapServer ldapServer = null ; try { ldapServer = ( ILdapServer ) applicationContext . getBean ( name , ILdapServer . class ) ; } catch ( NoSuchBeanDefinitionException nsbde ) { // Ignore the exception for not finding the named bean .
} if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "Found ILdapServer='" + ldapServer + "' for name='" + name + "'" ) ; } return ldapServer ; |
public class AjaxExceptionHandlerImpl { /** * { @ inheritDoc } */
@ Override public Iterable < ExceptionQueuedEvent > getHandledExceptionQueuedEvents ( ) { } } | return handled == null ? Collections . < ExceptionQueuedEvent > emptyList ( ) : handled ; |
public class TitanVertexDeserializer { /** * The neighboring vertices are represented by DetachedVertex instances */
public TinkerVertex readHadoopVertex ( final StaticBuffer key , Iterable < Entry > entries ) { } } | // Convert key to a vertex ID
final long vertexId = idManager . getKeyID ( key ) ; Preconditions . checkArgument ( vertexId > 0 ) ; // Partitioned vertex handling
if ( idManager . isPartitionedVertex ( vertexId ) ) { Preconditions . checkState ( setup . getFilterPartitionedVertices ( ) , "Read partitioned vertex (ID=%s), but partitioned vertex filtering is disabled." , vertexId ) ; log . debug ( "Skipping partitioned vertex with ID {}" , vertexId ) ; return null ; } // Create TinkerVertex
TinkerGraph tg = TinkerGraph . open ( ) ; boolean foundVertexState = ! verifyVertexExistence ; TinkerVertex tv = null ; // Iterate over edgestore columns to find the vertex ' s label relation
for ( final Entry data : entries ) { RelationReader relationReader = setup . getRelationReader ( vertexId ) ; final RelationCache relation = relationReader . parseRelation ( data , false , typeManager ) ; if ( systemTypes . isVertexLabelSystemType ( relation . typeId ) ) { // Found vertex Label
long vertexLabelId = relation . getOtherVertexId ( ) ; VertexLabel vl = typeManager . getExistingVertexLabel ( vertexLabelId ) ; // Create TinkerVertex with this label
// tv = ( TinkerVertex ) tg . addVertex ( T . label , vl . label ( ) , T . id , vertexId ) ;
tv = getOrCreateVertex ( vertexId , vl . name ( ) , tg ) ; } } // Added this following testing
if ( null == tv ) { // tv = ( TinkerVertex ) tg . addVertex ( T . id , vertexId ) ;
tv = getOrCreateVertex ( vertexId , null , tg ) ; } Preconditions . checkState ( null != tv , "Unable to determine vertex label for vertex with ID %s" , vertexId ) ; // Iterate over and decode edgestore columns ( relations ) on this vertex
for ( final Entry data : entries ) { try { RelationReader relationReader = setup . getRelationReader ( vertexId ) ; final RelationCache relation = relationReader . parseRelation ( data , false , typeManager ) ; if ( systemTypes . isVertexExistsSystemType ( relation . typeId ) ) { foundVertexState = true ; } if ( systemTypes . isSystemType ( relation . typeId ) ) continue ; // Ignore system types
final RelationType type = typeManager . getExistingRelationType ( relation . typeId ) ; if ( ( ( InternalRelationType ) type ) . isInvisibleType ( ) ) continue ; // Ignore hidden types
// Decode and create the relation ( edge or property )
if ( type . isPropertyKey ( ) ) { // Decode property
Object value = relation . getValue ( ) ; Preconditions . checkNotNull ( value ) ; VertexProperty . Cardinality card = getPropertyKeyCardinality ( type . name ( ) ) ; tv . property ( card , type . name ( ) , value , T . id , relation . relationId ) ; } else { assert type . isEdgeLabel ( ) ; // Partitioned vertex handling
if ( idManager . isPartitionedVertex ( relation . getOtherVertexId ( ) ) ) { Preconditions . checkState ( setup . getFilterPartitionedVertices ( ) , "Read edge incident on a partitioned vertex, but partitioned vertex filtering is disabled. " + "Relation ID: %s. This vertex ID: %s. Other vertex ID: %s. Edge label: %s." , relation . relationId , vertexId , relation . getOtherVertexId ( ) , type . name ( ) ) ; log . debug ( "Skipping edge with ID {} incident on partitioned vertex with ID {} (and nonpartitioned vertex with ID {})" , relation . relationId , relation . getOtherVertexId ( ) , vertexId ) ; continue ; } // Decode edge
TinkerEdge te ; if ( relation . direction . equals ( Direction . IN ) ) { // We don ' t know the label of the other vertex , but one must be provided
TinkerVertex outV = getOrCreateVertex ( relation . getOtherVertexId ( ) , null , tg ) ; te = ( TinkerEdge ) outV . addEdge ( type . name ( ) , tv , T . id , relation . relationId ) ; } else if ( relation . direction . equals ( Direction . OUT ) ) { // We don ' t know the label of the other vertex , but one must be provided
TinkerVertex inV = getOrCreateVertex ( relation . getOtherVertexId ( ) , null , tg ) ; te = ( TinkerEdge ) tv . addEdge ( type . name ( ) , inV , T . id , relation . relationId ) ; } else { throw new RuntimeException ( "Direction.BOTH is not supported" ) ; } if ( relation . hasProperties ( ) ) { // Load relation properties
for ( final LongObjectCursor < Object > next : relation ) { assert next . value != null ; RelationType rt = typeManager . getExistingRelationType ( next . key ) ; if ( rt . isPropertyKey ( ) ) { // PropertyKey pkey = ( PropertyKey ) vertex . getTypeManager ( ) . getPropertyKey ( rt . name ( ) ) ;
// log . debug ( " Retrieved key { } for name \ " { } \ " " , pkey , rt . name ( ) ) ;
// frel . property ( pkey . label ( ) , next . value ) ;
te . property ( rt . name ( ) , next . value ) ; } else { throw new RuntimeException ( "Metaedges are not supported" ) ; // assert next . value instanceof Long ;
// EdgeLabel el = ( EdgeLabel ) vertex . getTypeManager ( ) . getEdgeLabel ( rt . name ( ) ) ;
// log . debug ( " Retrieved ege label { } for name \ " { } \ " " , el , rt . name ( ) ) ;
// frel . setProperty ( el , new FaunusVertex ( configuration , ( Long ) next . value ) ) ;
} } } } // / / Iterate over and copy the relation ' s metaproperties
// if ( relation . hasProperties ( ) ) {
// / / Load relation properties
// for ( final LongObjectCursor < Object > next : relation ) {
// assert next . value ! = null ;
// RelationType rt = typeManager . getExistingRelationType ( next . key ) ;
// if ( rt . isPropertyKey ( ) ) {
// PropertyKey pkey = ( PropertyKey ) vertex . getTypeManager ( ) . getPropertyKey ( rt . name ( ) ) ;
// log . debug ( " Retrieved key { } for name \ " { } \ " " , pkey , rt . name ( ) ) ;
// frel . property ( pkey . label ( ) , next . value ) ;
// } else {
// assert next . value instanceof Long ;
// EdgeLabel el = ( EdgeLabel ) vertex . getTypeManager ( ) . getEdgeLabel ( rt . name ( ) ) ;
// log . debug ( " Retrieved ege label { } for name \ " { } \ " " , el , rt . name ( ) ) ;
// frel . setProperty ( el , new FaunusVertex ( configuration , ( Long ) next . value ) ) ;
// for ( TitanRelation rel : frel . query ( ) . queryAll ( ) . relations ( ) )
// ( ( FaunusRelation ) rel ) . setLifeCycle ( ElementLifeCycle . Loaded ) ;
// frel . setLifeCycle ( ElementLifeCycle . Loaded ) ;
} catch ( Exception e ) { throw new RuntimeException ( e ) ; } } // vertex . setLifeCycle ( ElementLifeCycle . Loaded ) ;
/* Since we are filtering out system relation types , we might end up with vertices that have no incident relations .
This is especially true for schema vertices . Those are filtered out . */
if ( ! foundVertexState ) { log . trace ( "Vertex {} has unknown lifecycle state" , vertexId ) ; return null ; } else if ( ! tv . edges ( Direction . BOTH ) . hasNext ( ) && ! tv . properties ( ) . hasNext ( ) ) { log . trace ( "Vertex {} has no relations" , vertexId ) ; return null ; } return tv ; |
public class FragmentBuilder { /** * This method determines whether the supplied node matches the specified class
* and optional URI .
* @ param node The node
* @ param cls The class
* @ param uri The optional URI
* @ return Whether the node is of the correct type and matches the optional URI */
protected boolean nodeMatches ( Node node , Class < ? extends Node > cls , String uri ) { } } | if ( node . getClass ( ) == cls ) { return uri == null || NodeUtil . isOriginalURI ( node , uri ) ; } return false ; |
public class DatanodeProtocols { /** * { @ inheritDoc } */
public long getProtocolVersion ( String protocol , long clientVersion ) throws IOException { } } | IOException last = new IOException ( "No DatanodeProtocol found." ) ; long lastProt = - 1 ; for ( int i = 0 ; i < numProtocol ; i ++ ) { try { if ( node [ i ] != null ) { long prot = node [ i ] . getProtocolVersion ( protocol , clientVersion ) ; if ( lastProt != - 1 ) { if ( prot != lastProt ) { throw new IOException ( "Versions of DatanodeProtocol " + " objects have to be same." + " Found version " + prot + " does not match with " + lastProt ) ; } lastProt = prot ; } } } catch ( IOException e ) { last = e ; LOG . info ( "Server " + i + " failed at getProtocolVersion." , e ) ; } } if ( lastProt == - 1 ) { throw last ; // fail if all DatanodeProtocol object failed .
} return lastProt ; // all objects have the same version |
public class CommandLine { /** * Registers a subcommand with the specified name . For example :
* < pre >
* CommandLine commandLine = new CommandLine ( new Git ( ) )
* . addSubcommand ( " status " , new GitStatus ( ) )
* . addSubcommand ( " commit " , new GitCommit ( ) ;
* . addSubcommand ( " add " , new GitAdd ( ) )
* . addSubcommand ( " branch " , new GitBranch ( ) )
* . addSubcommand ( " checkout " , new GitCheckout ( ) )
* < / pre >
* < p > The specified object can be an annotated object or a
* { @ code CommandLine } instance with its own nested subcommands . For example : < / p >
* < pre >
* CommandLine commandLine = new CommandLine ( new MainCommand ( ) )
* . addSubcommand ( " cmd1 " , new ChildCommand1 ( ) ) / / subcommand
* . addSubcommand ( " cmd2 " , new ChildCommand2 ( ) )
* . addSubcommand ( " cmd3 " , new CommandLine ( new ChildCommand3 ( ) ) / / subcommand with nested sub - subcommands
* . addSubcommand ( " cmd3sub1 " , new GrandChild3Command1 ( ) )
* . addSubcommand ( " cmd3sub2 " , new GrandChild3Command2 ( ) )
* . addSubcommand ( " cmd3sub3 " , new CommandLine ( new GrandChild3Command3 ( ) ) / / deeper nesting
* . addSubcommand ( " cmd3sub3sub1 " , new GreatGrandChild3Command3_1 ( ) )
* . addSubcommand ( " cmd3sub3sub2 " , new GreatGrandChild3Command3_2 ( ) )
* < / pre >
* < p > The default type converters are available on all subcommands and nested sub - subcommands , but custom type
* converters are registered only with the subcommand hierarchy as it existed when the custom type was registered .
* To ensure a custom type converter is available to all subcommands , register the type converter last , after
* adding subcommands . < / p >
* < p > See also the { @ link Command # subcommands ( ) } annotation to register subcommands declaratively . < / p >
* @ param name the string to recognize on the command line as a subcommand
* @ param command the object to initialize with command line arguments following the subcommand name .
* This may be a { @ code CommandLine } instance with its own ( nested ) subcommands
* @ return this CommandLine object , to allow method chaining
* @ see # registerConverter ( Class , ITypeConverter )
* @ since 0.9.7
* @ see Command # subcommands ( ) */
public CommandLine addSubcommand ( String name , Object command ) { } } | return addSubcommand ( name , command , new String [ 0 ] ) ; |
public class DeviceManager { /** * Push a DATA _ READY event if some client had registered it
* @ param attributeName The attribute name
* @ param counter
* @ throws DevFailed */
public void pushDataReadyEvent ( final String attributeName , final int counter ) throws DevFailed { } } | EventManager . getInstance ( ) . pushAttributeDataReadyEvent ( name , attributeName , counter ) ; |
public class CmsHtmlConverterJTidy { /** * Parses the htmlInput with regular expressions for cleanup purposes . < p >
* @ param htmlInput the HTML input
* @ return the processed HTML */
private String regExp ( String htmlInput ) { } } | String parsedHtml = htmlInput . trim ( ) ; if ( m_modeWord ) { // process all cleanup regular expressions
for ( int i = 0 ; i < m_cleanupPatterns . length ; i ++ ) { parsedHtml = m_clearStyle [ i ] . matcher ( parsedHtml ) . replaceAll ( "" ) ; } } // process all replace regular expressions
for ( int i = 0 ; i < m_replacePatterns . length ; i ++ ) { parsedHtml = m_replaceStyle [ i ] . matcher ( parsedHtml ) . replaceAll ( m_replaceValues [ i ] ) ; } return parsedHtml ; |
public class JavaInfoImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ SuppressWarnings ( "unchecked" ) @ Override public EList < String > getJavaClasspath ( ) { } } | return ( EList < String > ) eGet ( StorePackage . Literals . JAVA_INFO__JAVA_CLASSPATH , true ) ; |
public class Base64 { /** * base64解码
* @ param base64 被解码的base64字符串
* @ param destFile 目标文件
* @ return 目标文件
* @ since 4.0.9 */
public static File decodeToFile ( String base64 , File destFile ) { } } | return FileUtil . writeBytes ( Base64Decoder . decode ( base64 ) , destFile ) ; |
public class Transloadit { /** * Returns a single template .
* @ param id id of the template to retrieve .
* @ return { @ link Response }
* @ throws RequestException if request to transloadit server fails .
* @ throws LocalOperationException if something goes wrong while running non - http operations . */
public Response getTemplate ( String id ) throws RequestException , LocalOperationException { } } | Request request = new Request ( this ) ; return new Response ( request . get ( "/templates/" + id ) ) ; |
public class SourceMapGenerator { /** * Externalize the source map . */
public SourceMap toJSON ( ) { } } | SourceMap map = new SourceMap ( ) ; map . version = this . _version ; map . sources = this . _sources . toArray ( ) ; map . names = this . _names . toArray ( ) ; map . mappings = serializeMappings ( ) ; map . file = this . _file ; map . sourceRoot = this . _sourceRoot ; if ( this . _sourcesContents != null ) { map . sourcesContent = _generateSourcesContent ( map . sources , this . _sourceRoot ) ; } return map ; |
public class UploadObjectObserver { /** * Notified from
* { @ link AmazonS3EncryptionClient # uploadObject ( UploadObjectRequest ) } when
* failed to upload any part . This method is responsible for cancelling
* ongoing uploads and aborting the multi - part upload request . */
public void onAbort ( ) { } } | for ( Future < ? > future : getFutures ( ) ) { future . cancel ( true ) ; } if ( uploadId != null ) { try { s3 . abortMultipartUpload ( new AbortMultipartUploadRequest ( req . getBucketName ( ) , req . getKey ( ) , uploadId ) ) ; } catch ( Exception e ) { LogFactory . getLog ( getClass ( ) ) . debug ( "Failed to abort multi-part upload: " + uploadId , e ) ; } } |
public class VertxCompletableFuture { /** * Returns a new CompletableFuture that is asynchronously completed by a action running in the worker thread pool of
* Vert . x
* This method is different from { @ link CompletableFuture # runAsync ( Runnable ) } as it does not use a fork join
* executor , but the worker thread pool .
* @ param context the Vert . x context
* @ param runnable the action , when its execution completes , it completes the returned CompletableFuture . If the
* execution throws an exception , the returned CompletableFuture is completed exceptionally .
* @ return the new CompletableFuture */
public static VertxCompletableFuture < Void > runBlockingAsync ( Context context , Runnable runnable ) { } } | Objects . requireNonNull ( runnable ) ; VertxCompletableFuture < Void > future = new VertxCompletableFuture < > ( Objects . requireNonNull ( context ) ) ; context . < Void > executeBlocking ( fut -> { try { runnable . run ( ) ; fut . complete ( null ) ; } catch ( Throwable e ) { fut . fail ( e ) ; } } , false , ar -> { if ( ar . failed ( ) ) { future . completeExceptionally ( ar . cause ( ) ) ; } else { future . complete ( ar . result ( ) ) ; } } ) ; return future ; |
public class JDBC4PreparedStatement { /** * Sets the value of the designated parameter using the given object . */
@ Override public void setObject ( int parameterIndex , Object x ) throws SQLException { } } | checkParameterBounds ( parameterIndex ) ; this . parameters [ parameterIndex - 1 ] = x ; |
public class ExtendedJTATransactionImpl { /** * which can still be called otherwise false . */
public static boolean callbacksRegistered ( ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) Tr . entry ( tc , "callbacksRegistered" ) ; if ( _syncLevel < 0 ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) Tr . exit ( tc , "callbacksRegistered" , Boolean . FALSE ) ; return false ; } final int maxLevels = _syncLevels . size ( ) ; for ( int level = 0 ; level < maxLevels ; level ++ ) { final ArrayList syncs = _syncLevels . get ( _syncLevel ) ; if ( syncs != null && ! syncs . isEmpty ( ) ) { if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) Tr . exit ( tc , "callbacksRegistered" , Boolean . TRUE ) ; return true ; } } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) Tr . exit ( tc , "callbacksRegistered" , Boolean . FALSE ) ; return false ; |
public class RecencyDimensionMarshaller { /** * Marshall the given parameter object . */
public void marshall ( RecencyDimension recencyDimension , ProtocolMarshaller protocolMarshaller ) { } } | if ( recencyDimension == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( recencyDimension . getDuration ( ) , DURATION_BINDING ) ; protocolMarshaller . marshall ( recencyDimension . getRecencyType ( ) , RECENCYTYPE_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class PrintfFormat { /** * Return a substring starting at
* < code > start < / code > and ending at either the end
* of the String < code > s < / code > , the next unpaired
* percent sign , or at the end of the String if the
* last character is a percent sign .
* @ param s Control string .
* @ param start Position in the string
* < code > s < / code > to begin looking for the start
* of a control string .
* @ return the substring from the start position
* to the beginning of the control string . */
private String nonControl ( String s , int start ) { } } | String ret = "" ; cPos = s . indexOf ( "%" , start ) ; if ( cPos == - 1 ) cPos = s . length ( ) ; return s . substring ( start , cPos ) ; |
public class CommsUtils { /** * This method will get a runtime property from the sib . properties file as a boolean .
* @ param property The property key used to look up in the file .
* @ param defaultValue The default value if the property is not in the file .
* @ return Returns the property value . */
public static boolean getRuntimeBooleanProperty ( String property , String defaultValue ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( tc , "getRuntimeBooleanProperty" , new Object [ ] { property , defaultValue } ) ; boolean runtimeProp = Boolean . valueOf ( RuntimeInfo . getPropertyWithMsg ( property , defaultValue ) ) . booleanValue ( ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( tc , "getRuntimeBooleanProperty" , "" + runtimeProp ) ; return runtimeProp ; |
public class Ifc4PackageImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ Override public EClass getIfcDiscreteAccessoryType ( ) { } } | if ( ifcDiscreteAccessoryTypeEClass == null ) { ifcDiscreteAccessoryTypeEClass = ( EClass ) EPackage . Registry . INSTANCE . getEPackage ( Ifc4Package . eNS_URI ) . getEClassifiers ( ) . get ( 177 ) ; } return ifcDiscreteAccessoryTypeEClass ; |
public class Utils { /** * Helper method that deserializes and unmarshalls the message from the given stream . This
* method has been adapted from { @ code org . opensaml . ws . message . decoder . BaseMessageDecoder } .
* @ param messageStream
* input stream containing the message
* @ return the inbound message
* @ throws MessageDecodingException
* thrown if there is a problem deserializing and unmarshalling the message */
static XMLObject unmarshallMessage ( ParserPool parserPool , InputStream messageStream ) throws ClientProtocolException { } } | try { Document messageDoc = parserPool . parse ( messageStream ) ; Element messageElem = messageDoc . getDocumentElement ( ) ; Unmarshaller unmarshaller = Configuration . getUnmarshallerFactory ( ) . getUnmarshaller ( messageElem ) ; if ( unmarshaller == null ) { throw new ClientProtocolException ( "Unable to unmarshall message, no unmarshaller registered for message element " + XMLHelper . getNodeQName ( messageElem ) ) ; } XMLObject message = unmarshaller . unmarshall ( messageElem ) ; return message ; } catch ( XMLParserException e ) { throw new ClientProtocolException ( "Encountered error parsing message into its DOM representation" , e ) ; } catch ( UnmarshallingException e ) { throw new ClientProtocolException ( "Encountered error unmarshalling message from its DOM representation" , e ) ; } |
public class MultiEntityImporter { /** * addEntity .
* @ param alias a { @ link java . lang . String } object .
* @ param entityClass a { @ link java . lang . Class } object . */
public void addEntity ( String alias , Class < ? > entityClass ) { } } | EntityType entityType = Model . getType ( entityClass ) ; if ( null == entityType ) { throw new RuntimeException ( "cannot find entity type for " + entityClass ) ; } entityTypes . put ( alias , entityType ) ; |
public class DFSLocationsRoot { /** * Recompute the map of Hadoop locations */
private synchronized void reloadLocations ( ) { } } | map . clear ( ) ; for ( HadoopServer location : ServerRegistry . getInstance ( ) . getServers ( ) ) map . put ( location , new DFSLocation ( provider , location ) ) ; |
public class InternalDebugControl { /** * Tests if any of the specified debug flags are enabled .
* @ param state the JShell instance
* @ param flag the { @ code DBG _ * } bits to check
* @ return true if any of the flags are enabled */
public static boolean isDebugEnabled ( JShell state , int flag ) { } } | if ( debugMap == null ) { return false ; } Integer flags = debugMap . get ( state ) ; if ( flags == null ) { return false ; } return ( flags & flag ) != 0 ; |
public class AbstractClientOptionsBuilder { /** * Adds the specified { @ code decorator } .
* @ param requestType the type of the { @ link Request } that the { @ code decorator } is interested in
* @ param responseType the type of the { @ link Response } that the { @ code decorator } is interested in
* @ param decorator the { @ link Function } that transforms a { @ link Client } to another
* @ param < T > the type of the { @ link Client } being decorated
* @ param < R > the type of the { @ link Client } produced by the { @ code decorator }
* @ param < I > the { @ link Request } type of the { @ link Client } being decorated
* @ param < O > the { @ link Response } type of the { @ link Client } being decorated
* @ deprecated Use { @ link # decorator ( Function ) } or { @ link # rpcDecorator ( Function ) } . */
@ Deprecated public < T extends Client < I , O > , R extends Client < I , O > , I extends Request , O extends Response > B decorator ( Class < I > requestType , Class < O > responseType , Function < T , R > decorator ) { } } | decoration . add ( requestType , responseType , decorator ) ; return self ( ) ; |
public class BindingManager { /** * Returns a { @ link Element } for the given class */
Element getElement ( String className ) { } } | int templateStart = className . indexOf ( '<' ) ; if ( templateStart != - 1 ) { className = className . substring ( 0 , templateStart ) . trim ( ) ; } return elementUtils . getTypeElement ( className ) ; |
public class LLERGImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ Override public Object eGet ( int featureID , boolean resolve , boolean coreType ) { } } | switch ( featureID ) { case AfplibPackage . LLERG__RG_LENGTH : return getRGLength ( ) ; case AfplibPackage . LLERG__RG_FUNCT : return getRGFunct ( ) ; case AfplibPackage . LLERG__TRIPLETS : return getTriplets ( ) ; } return super . eGet ( featureID , resolve , coreType ) ; |
public class MessageFormat { /** * Finds the " other " sub - message .
* @ param partIndex the index of the first PluralFormat argument style part .
* @ return the " other " sub - message start part index . */
private int findOtherSubMessage ( int partIndex ) { } } | int count = msgPattern . countParts ( ) ; MessagePattern . Part part = msgPattern . getPart ( partIndex ) ; if ( part . getType ( ) . hasNumericValue ( ) ) { ++ partIndex ; } // Iterate over ( ARG _ SELECTOR [ ARG _ INT | ARG _ DOUBLE ] message ) tuples
// until ARG _ LIMIT or end of plural - only pattern .
do { part = msgPattern . getPart ( partIndex ++ ) ; MessagePattern . Part . Type type = part . getType ( ) ; if ( type == MessagePattern . Part . Type . ARG_LIMIT ) { break ; } assert type == MessagePattern . Part . Type . ARG_SELECTOR ; // part is an ARG _ SELECTOR followed by an optional explicit value , and then a message
if ( msgPattern . partSubstringMatches ( part , "other" ) ) { return partIndex ; } if ( msgPattern . getPartType ( partIndex ) . hasNumericValue ( ) ) { ++ partIndex ; // skip the numeric - value part of " = 1 " etc .
} partIndex = msgPattern . getLimitPartIndex ( partIndex ) ; } while ( ++ partIndex < count ) ; return 0 ; |
public class AbstractJaxbMojo { /** * Convenience method to invoke when some plugin configuration is incorrect .
* Will output the problem as a warning with some degree of log formatting .
* @ param propertyName The name of the problematic property .
* @ param description The problem description . */
@ SuppressWarnings ( "all" ) protected void warnAboutIncorrectPluginConfiguration ( final String propertyName , final String description ) { } } | final StringBuilder builder = new StringBuilder ( ) ; builder . append ( "\n+=================== [Incorrect Plugin Configuration Detected]\n" ) ; builder . append ( "|\n" ) ; builder . append ( "| Property : " + propertyName + "\n" ) ; builder . append ( "| Problem : " + description + "\n" ) ; builder . append ( "|\n" ) ; builder . append ( "+=================== [End Incorrect Plugin Configuration Detected]\n\n" ) ; getLog ( ) . warn ( builder . toString ( ) . replace ( "\n" , NEWLINE ) ) ; |
public class ESVersion { /** * Returns the version given its string representation , current version if the argument is null or empty */
public static ESVersion fromString ( String version ) { } } | String lVersion = version ; final boolean snapshot = lVersion . endsWith ( "-SNAPSHOT" ) ; if ( snapshot ) { lVersion = lVersion . substring ( 0 , lVersion . length ( ) - 9 ) ; } String [ ] parts = lVersion . split ( "[.-]" ) ; if ( parts . length < 3 || parts . length > 4 ) { throw new IllegalArgumentException ( "the lVersion needs to contain major, minor, and revision, and optionally the build: " + lVersion ) ; } try { final int rawMajor = Integer . parseInt ( parts [ 0 ] ) ; if ( rawMajor >= 5 && snapshot ) { // we don ' t support snapshot as part of the lVersion here anymore
throw new IllegalArgumentException ( "illegal lVersion format - snapshots are only supported until lVersion 2.x" ) ; } final int betaOffset = rawMajor < 5 ? 0 : 25 ; // we reverse the lVersion id calculation based on some assumption as we can ' t reliably reverse the modulo
final int major = rawMajor * 1000000 ; final int minor = Integer . parseInt ( parts [ 1 ] ) * 10000 ; final int revision = Integer . parseInt ( parts [ 2 ] ) * 100 ; int build = 99 ; if ( parts . length == 4 ) { String buildStr = parts [ 3 ] ; if ( buildStr . startsWith ( "alpha" ) ) { assert rawMajor >= 5 : "major must be >= 5 but was " + major ; build = Integer . parseInt ( buildStr . substring ( 5 ) ) ; assert build < 25 : "expected a beta build but " + build + " >= 25" ; } else if ( buildStr . startsWith ( "Beta" ) || buildStr . startsWith ( "beta" ) ) { build = betaOffset + Integer . parseInt ( buildStr . substring ( 4 ) ) ; assert build < 50 : "expected a beta build but " + build + " >= 50" ; } else if ( buildStr . startsWith ( "RC" ) || buildStr . startsWith ( "rc" ) ) { build = Integer . parseInt ( buildStr . substring ( 2 ) ) + 50 ; } else { throw new IllegalArgumentException ( "unable to parse lVersion " + lVersion ) ; } } return new ESVersion ( major + minor + revision + build ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( "unable to parse lVersion " + lVersion , e ) ; } |
public class Validator { /** * Validates to fields to ( case - insensitive ) match
* @ param name The field to check
* @ param anotherName The field to check against
* @ param message A custom error message instead of the default one */
public void expectMatch ( String name , String anotherName , String message ) { } } | String value = Optional . ofNullable ( get ( name ) ) . orElse ( "" ) ; String anotherValue = Optional . ofNullable ( get ( anotherName ) ) . orElse ( "" ) ; if ( ( StringUtils . isBlank ( value ) && StringUtils . isBlank ( anotherValue ) ) || ( StringUtils . isNotBlank ( value ) && ! value . equalsIgnoreCase ( anotherValue ) ) ) { addError ( name , Optional . ofNullable ( message ) . orElse ( messages . get ( Validation . MATCH_KEY . name ( ) , name , anotherName ) ) ) ; } |
public class AWSOpsWorksClient { /** * Updates a user ' s SSH public key .
* < b > Required Permissions < / b > : To use this action , an IAM user must have self - management enabled or an attached
* policy that explicitly grants permissions . For more information about user permissions , see < a
* href = " http : / / docs . aws . amazon . com / opsworks / latest / userguide / opsworks - security - users . html " > Managing User
* Permissions < / a > .
* @ param updateMyUserProfileRequest
* @ return Result of the UpdateMyUserProfile operation returned by the service .
* @ throws ValidationException
* Indicates that a request was not valid .
* @ sample AWSOpsWorks . UpdateMyUserProfile
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / opsworks - 2013-02-18 / UpdateMyUserProfile " target = " _ top " > AWS
* API Documentation < / a > */
@ Override public UpdateMyUserProfileResult updateMyUserProfile ( UpdateMyUserProfileRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeUpdateMyUserProfile ( request ) ; |
public class CharArrayBuffer { /** * Appends chars of the given string to this buffer . The capacity of the
* buffer is increased , if necessary , to accommodate all chars .
* @ param str the string . */
public void append ( final String str ) { } } | final String s = str != null ? str : "null" ; final int strlen = s . length ( ) ; final int newlen = this . len + strlen ; if ( newlen > this . array . length ) { expand ( newlen ) ; } s . getChars ( 0 , strlen , this . array , this . len ) ; this . len = newlen ; |
public class IIMFile { /** * Gets combined date / time value from two data sets .
* @ param dateDataSet
* data set containing date value
* @ param timeDataSet
* data set containing time value
* @ return date / time instance
* @ throws SerializationException
* if data sets can ' t be deserialized from binary format or
* can ' t be parsed */
public Date getDateTimeHelper ( int dateDataSet , int timeDataSet ) throws SerializationException { } } | DataSet dateDS = null ; DataSet timeDS = null ; for ( Iterator < DataSet > i = dataSets . iterator ( ) ; ( dateDS == null || timeDS == null ) && i . hasNext ( ) ; ) { DataSet ds = i . next ( ) ; DataSetInfo info = ds . getInfo ( ) ; if ( info . getDataSetNumber ( ) == dateDataSet ) { dateDS = ds ; } else if ( info . getDataSetNumber ( ) == timeDataSet ) { timeDS = ds ; } } Date result = null ; if ( dateDS != null && timeDS != null ) { DataSetInfo dateDSI = dateDS . getInfo ( ) ; DataSetInfo timeDSI = timeDS . getInfo ( ) ; SimpleDateFormat format = new SimpleDateFormat ( dateDSI . getSerializer ( ) . toString ( ) + timeDSI . getSerializer ( ) . toString ( ) ) ; StringBuffer date = new StringBuffer ( 20 ) ; try { date . append ( getData ( dateDS ) ) ; date . append ( getData ( timeDS ) ) ; result = format . parse ( date . toString ( ) ) ; } catch ( ParseException e ) { throw new SerializationException ( "Failed to read date (" + e . getMessage ( ) + ") with format " + date ) ; } } return result ; |
public class SmoothieMap { /** * If the specified key is not already associated with a value or is associated with null ,
* associates it with the given non - null value . Otherwise , replaces the associated value with
* the results of the given remapping function , or removes if the result is { @ code null } . This
* method may be of use when combining multiple mapped values for a key . For example , to either
* create or append a { @ code String msg } to a value mapping :
* < pre > { @ code
* map . merge ( key , msg , String : : concat )
* } < / pre >
* < p > If the function returns { @ code null } the mapping is removed . If the function itself throws
* an ( unchecked ) exception , the exception is rethrown , and the current mapping is left
* unchanged .
* @ param key key with which the resulting value is to be associated
* @ param value the non - null value to be merged with the existing value
* associated with the key or , if no existing value or a null value
* is associated with the key , to be associated with the key
* @ param remappingFunction the function to recompute a value if present
* @ return the new value associated with the specified key , or null if no
* value is associated with the key
* @ throws NullPointerException if remappingFunction is null */
@ Override public final V merge ( K key , V value , BiFunction < ? super V , ? super V , ? extends V > remappingFunction ) { } } | if ( value == null ) throw new NullPointerException ( ) ; if ( remappingFunction == null ) throw new NullPointerException ( ) ; long hash ; return segment ( segmentIndex ( hash = keyHashCode ( key ) ) ) . merge ( this , hash , key , value , remappingFunction ) ; |
public class KAMStoreImpl { /** * { @ inheritDoc } */
@ Override public List < Namespace > getNamespaces ( Kam kam ) { } } | if ( kam == null ) throw new InvalidArgument ( "kam" , kam ) ; if ( ! exists ( kam ) ) return null ; return getNamespaces ( kam . getKamInfo ( ) ) ; |
public class AfplibPackageImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public EClass getGSBMX ( ) { } } | if ( gsbmxEClass == null ) { gsbmxEClass = ( EClass ) EPackage . Registry . INSTANCE . getEPackage ( AfplibPackage . eNS_URI ) . getEClassifiers ( ) . get ( 465 ) ; } return gsbmxEClass ; |
public class PTBConstituent { /** * getter for adv - gets Adverbials are generally VP adjuncts .
* @ generated
* @ return value of the feature */
public String getAdv ( ) { } } | if ( PTBConstituent_Type . featOkTst && ( ( PTBConstituent_Type ) jcasType ) . casFeat_adv == null ) jcasType . jcas . throwFeatMissing ( "adv" , "de.julielab.jules.types.PTBConstituent" ) ; return jcasType . ll_cas . ll_getStringValue ( addr , ( ( PTBConstituent_Type ) jcasType ) . casFeatCode_adv ) ; |
public class SIMPUtils { /** * The key we use to lookup / insert a streamInfo object is based off the remoteMEuuid +
* the gatheringTargetDestUuid . This second value is null for standard consumer and set
* to a destinationUuid ( which could be an alias ) for gathering consumers . In this way
* we have seperate streams per consumer type . */
public static String getRemoteGetKey ( SIBUuid8 remoteUuid , SIBUuid12 gatheringTargetDestUuid ) { } } | String key = null ; if ( gatheringTargetDestUuid != null ) key = remoteUuid . toString ( ) + gatheringTargetDestUuid . toString ( ) ; else key = remoteUuid . toString ( ) + SIMPConstants . DEFAULT_CONSUMER_SET ; return key ; |
public class SingleThreadBlockingQpsBenchmark { /** * Setup with direct executors , small payloads and the default flow control window . */
@ Setup ( Level . Trial ) public void setup ( ) throws Exception { } } | super . setup ( ExecutorType . DIRECT , ExecutorType . DIRECT , MessageSize . SMALL , MessageSize . SMALL , FlowWindowSize . MEDIUM , ChannelType . NIO , 1 , 1 ) ; |
public class CmsDefaultXmlContentHandler { /** * Initializes the element mappings for this content handler . < p >
* Element mappings allow storing values from the XML content in other locations .
* For example , if you have an element called " Title " , it ' s likely a good idea to
* store the value of this element also in the " Title " property of a XML content resource . < p >
* @ param root the " mappings " element from the appinfo node of the XML content definition
* @ param contentDefinition the content definition the mappings belong to
* @ throws CmsXmlException if something goes wrong */
protected void initMappings ( Element root , CmsXmlContentDefinition contentDefinition ) throws CmsXmlException { } } | Iterator < Element > i = CmsXmlGenericWrapper . elementIterator ( root , APPINFO_MAPPING ) ; while ( i . hasNext ( ) ) { // iterate all " mapping " elements in the " mappings " node
Element element = i . next ( ) ; // this is a mapping node
String elementName = element . attributeValue ( APPINFO_ATTR_ELEMENT ) ; String maptoName = element . attributeValue ( APPINFO_ATTR_MAPTO ) ; String useDefault = element . attributeValue ( APPINFO_ATTR_USE_DEFAULT ) ; if ( ( elementName != null ) && ( maptoName != null ) ) { // add the element mapping
addMapping ( contentDefinition , elementName , maptoName , useDefault ) ; } } |
public class DynamicObjectStoreFactory { /** * Create an instance of { @ link ObjectStore } for mapping keys to values .
* The underlying store is backed by { @ link krati . store . DynamicDataStore DynamicDataStore } .
* @ param config - the configuration
* @ param keySerializer - the serializer for keys
* @ param valueSerializer - the serializer for values
* @ return the newly created store
* @ throws IOException if the store cannot be created . */
@ Override public ObjectStore < K , V > create ( StoreConfig config , Serializer < K > keySerializer , Serializer < V > valueSerializer ) throws IOException { } } | try { DataStore < byte [ ] , byte [ ] > base = StoreFactory . createDynamicDataStore ( config ) ; return new SerializableObjectStore < K , V > ( base , keySerializer , valueSerializer ) ; } catch ( Exception e ) { if ( e instanceof IOException ) { throw ( IOException ) e ; } else { throw new IOException ( e ) ; } } |
public class Reservation { /** * Create a ReservationFetcher to execute fetch .
* @ param pathWorkspaceSid The workspace _ sid
* @ param pathTaskSid The task _ sid
* @ param pathSid The sid
* @ return ReservationFetcher capable of executing the fetch */
public static ReservationFetcher fetcher ( final String pathWorkspaceSid , final String pathTaskSid , final String pathSid ) { } } | return new ReservationFetcher ( pathWorkspaceSid , pathTaskSid , pathSid ) ; |
public class XmlIOUtil { /** * Parses the { @ code messages } from the { @ link InputStream } using the given { @ code schema } . */
public static < T > List < T > parseListFrom ( InputStream in , Schema < T > schema ) throws IOException { } } | return parseListFrom ( in , schema , DEFAULT_INPUT_FACTORY ) ; |
public class CPDefinitionLinkUtil { /** * Returns a range of all the cp definition links where CPDefinitionId = & # 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 CPDefinitionLinkModelImpl } . 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 CPDefinitionId the cp definition ID
* @ param start the lower bound of the range of cp definition links
* @ param end the upper bound of the range of cp definition links ( not inclusive )
* @ return the range of matching cp definition links */
public static List < CPDefinitionLink > findByCPDefinitionId ( long CPDefinitionId , int start , int end ) { } } | return getPersistence ( ) . findByCPDefinitionId ( CPDefinitionId , start , end ) ; |
public class GeoUtils { /** * Computes which tiles on the given base zoom level need to include the given way ( which may be a polygon ) .
* @ param way the way that is mapped to tiles
* @ param baseZoomLevel the base zoom level which is used in the mapping
* @ param enlargementInMeter amount of pixels that is used to enlarge the bounding box of the way and the tiles in the mapping
* process
* @ return all tiles on the given base zoom level that need to include the given way , an empty set if no tiles are
* matched */
public static Set < TileCoordinate > mapWayToTiles ( final TDWay way , final byte baseZoomLevel , final int enlargementInMeter ) { } } | if ( way == null ) { LOGGER . fine ( "way is null in mapping to tiles" ) ; return Collections . emptySet ( ) ; } HashSet < TileCoordinate > matchedTiles = new HashSet < > ( ) ; Geometry wayGeometry = JTSUtils . toJTSGeometry ( way ) ; if ( wayGeometry == null ) { way . setInvalid ( true ) ; LOGGER . fine ( "unable to create geometry from way: " + way . getId ( ) ) ; return matchedTiles ; } TileCoordinate [ ] bbox = getWayBoundingBox ( way , baseZoomLevel , enlargementInMeter ) ; // calculate the tile coordinates and the corresponding bounding boxes
try { for ( int k = bbox [ 0 ] . getX ( ) ; k <= bbox [ 1 ] . getX ( ) ; k ++ ) { for ( int l = bbox [ 0 ] . getY ( ) ; l <= bbox [ 1 ] . getY ( ) ; l ++ ) { Geometry bboxGeometry = tileToJTSGeometry ( k , l , baseZoomLevel , enlargementInMeter ) ; if ( bboxGeometry . intersects ( wayGeometry ) ) { matchedTiles . add ( new TileCoordinate ( k , l , baseZoomLevel ) ) ; } } } } catch ( TopologyException e ) { LOGGER . fine ( "encountered error during mapping of a way to corresponding tiles, way id: " + way . getId ( ) ) ; return Collections . emptySet ( ) ; } return matchedTiles ; |
public class JcrIndexSearcher { /** * Evaluates the query and returns the hits that match the query .
* @ param query the query to execute .
* @ param sort the sort criteria .
* @ param resultFetchHint a hint on how many results should be fetched .
* @ return the query hits .
* @ throws IOException if an error occurs while executing the query . */
public QueryHits evaluate ( final Query query , final Sort sort , final long resultFetchHint ) throws IOException { } } | return SecurityHelper . doPrivilegedIOExceptionAction ( new PrivilegedExceptionAction < QueryHits > ( ) { public QueryHits run ( ) throws Exception { Query localQuery = query . rewrite ( reader ) ; QueryHits hits = null ; if ( localQuery instanceof JcrQuery ) { hits = ( ( JcrQuery ) localQuery ) . execute ( JcrIndexSearcher . this , session , sort ) ; } if ( hits == null ) { if ( sort == null || sort . getSort ( ) . length == 0 ) { hits = new LuceneQueryHits ( reader , JcrIndexSearcher . this , query ) ; } else { hits = new SortedLuceneQueryHits ( reader , JcrIndexSearcher . this , localQuery , sort , resultFetchHint ) ; } } return hits ; } } ) ; |
public class IOUtils { /** * Writes all the contents of a byte array to an OutputStream .
* @ param byteArray
* the input to read from
* @ param out
* the output stream to write to
* @ throws java . io . IOException
* if an IOExcption occurs */
public static void write ( byte [ ] byteArray , OutputStream out ) throws IOException { } } | if ( byteArray != null ) { out . write ( byteArray ) ; } |
public class Input { /** * xhash属性视图 */
@ JSONField ( serialize = false ) public boolean isXhash ( ) { } } | if ( getList ( ) != null ) { for ( Obj obj : getList ( ) ) { if ( obj . isXhash ( ) ) return true ; } } return false ; |
public class NodeUtil { /** * Returns whether this is a target of a call or new . */
static boolean isInvocationTarget ( Node n ) { } } | Node parent = n . getParent ( ) ; return parent != null && ( isCallOrNew ( parent ) || parent . isTaggedTemplateLit ( ) ) && parent . getFirstChild ( ) == n ; |
public class RegularFile { /** * Writes all available bytes from buffer { @ code buf } to this file starting at position { @ code
* pos } . { @ code pos } may be greater than the current size of this file , in which case this file is
* resized and all bytes between the current size and { @ code pos } are set to 0 . Returns the number
* of bytes written .
* @ throws IOException if the file needs more blocks but the disk is full */
public int write ( long pos , ByteBuffer buf ) throws IOException { } } | int len = buf . remaining ( ) ; prepareForWrite ( pos , len ) ; if ( len == 0 ) { return 0 ; } int blockIndex = blockIndex ( pos ) ; byte [ ] block = blocks [ blockIndex ] ; int off = offsetInBlock ( pos ) ; put ( block , off , buf ) ; while ( buf . hasRemaining ( ) ) { block = blocks [ ++ blockIndex ] ; put ( block , 0 , buf ) ; } long endPos = pos + len ; if ( endPos > size ) { size = endPos ; } return len ; |
public class ApiOvhSms { /** * Describe SMS offers available .
* REST : GET / sms / { serviceName } / seeOffers
* @ param countryCurrencyPrice [ required ] Filter to have the currency country prices
* @ param countryDestination [ required ] Filter to have the country destination
* @ param quantity [ required ] Sms pack offer quantity
* @ param serviceName [ required ] The internal name of your SMS offer */
public ArrayList < OvhPackOffer > serviceName_seeOffers_GET ( String serviceName , OvhCountryEnum countryCurrencyPrice , net . minidev . ovh . api . sms . OvhCountryEnum countryDestination , OvhPackQuantityEnum quantity ) throws IOException { } } | String qPath = "/sms/{serviceName}/seeOffers" ; StringBuilder sb = path ( qPath , serviceName ) ; query ( sb , "countryCurrencyPrice" , countryCurrencyPrice ) ; query ( sb , "countryDestination" , countryDestination ) ; query ( sb , "quantity" , quantity ) ; String resp = exec ( qPath , "GET" , sb . toString ( ) , null ) ; return convertTo ( resp , t5 ) ; |
public class Client { /** * Create an { @ link ApplicationSession } for the given application name on the Doradus
* server , creating a new connection the given REST API host , port , and TLS / SSL
* parameters . This static method allows an application session to be created without
* creating a Client object and then calling { @ link # openApplication ( String ) } . If the
* given sslParams is null , an unsecured ( HTTP ) connectio is opened . Otherwise , a
* TLS / SSL connection is created using the given credentials . An exception is thrown
* if the given application is unknown or cannot be accessed or if a connection cannot
* be established . If successful , the session object will be specific to the type of
* application opened , and it will have its own REST session to the Doradus server .
* @ param appName
* Name of an application to open .
* @ param host
* REST API host name or IP address .
* @ param port
* REST API port number .
* @ param sslParams
* { @ link SSLTransportParameters } object containing TLS / SSL parameters to
* use , or null to open an HTTP connection .
* @ param credentials
* { @ link Credentials } to use for all requests with the new application
* session . Can be null to use an unauthenticated session .
* @ return { @ link ApplicationSession }
* through which the application can be accessed .
* @ see com . dell . doradus . client . OLAPSession
* @ see com . dell . doradus . client . SpiderSession */
public static ApplicationSession openApplication ( String appName , String host , int port , SSLTransportParameters sslParams , Credentials credentials ) { } } | Utils . require ( ! Utils . isEmpty ( appName ) , "appName" ) ; Utils . require ( ! Utils . isEmpty ( host ) , "host" ) ; try ( Client client = new Client ( host , port , sslParams ) ) { client . setCredentials ( credentials ) ; ApplicationDefinition appDef = client . getAppDef ( appName ) ; Utils . require ( appDef != null , "Unknown application: %s" , appName ) ; RESTClient restClient = new RESTClient ( client . m_restClient ) ; return openApplication ( appDef , restClient ) ; } |
public class FDistort { /** * Applies a distortion which will rotate the input image by the specified amount . */
public FDistort rotate ( double angleInputToOutput ) { } } | PixelTransform < Point2D_F32 > outputToInput = DistortSupport . transformRotate ( input . width / 2 , input . height / 2 , output . width / 2 , output . height / 2 , ( float ) angleInputToOutput ) ; return transform ( outputToInput ) ; |
public class CodedInputStream { /** * Read a { @ code bytes } field value from the stream . */
public ByteString readBytes ( ) throws IOException { } } | final int size = readRawVarint32 ( ) ; if ( size == 0 ) { return ByteString . EMPTY ; } else if ( size <= ( bufferSize - bufferPos ) && size > 0 ) { // Fast path : We already have the bytes in a contiguous buffer , so
// just copy directly from it .
final ByteString result = ByteString . copyFrom ( buffer , bufferPos , size ) ; bufferPos += size ; return result ; } else { // Slow path : Build a byte array first then copy it .
return ByteString . copyFrom ( readRawBytes ( size ) ) ; } |
public class ArgumentUtils { /** * Adds a check that the given number is positive .
* @ param name The name of the argument
* @ param value The value
* @ throws IllegalArgumentException if the argument is not positive
* @ return The value */
public static @ Nonnull Number requirePositive ( String name , Number value ) { } } | requireNonNull ( name , value ) ; requirePositive ( name , value . intValue ( ) ) ; return value ; |
public class ScannerImpl { /** * Checks whether a plugin accepts an item .
* @ param selectedPlugin
* The plugin .
* @ param item
* The item .
* @ param path
* The path .
* @ param scope
* The scope .
* @ param < I >
* The item type .
* @ return < code > true < / code > if the plugin accepts the item for scanning . */
protected < I > boolean accepts ( ScannerPlugin < I , ? > selectedPlugin , I item , String path , Scope scope ) { } } | boolean accepted = false ; try { accepted = selectedPlugin . accepts ( item , path , scope ) ; } catch ( IOException e ) { LOGGER . error ( "Plugin " + selectedPlugin + " failed to check whether it can accept item " + path , e ) ; } return accepted ; |
public class PortletCookieServiceImpl { /** * ( non - Javadoc )
* @ see
* org . apereo . portal . portlet . container . services . IPortletCookieService # updatePortalCookie ( javax . servlet . http . HttpServletRequest ,
* javax . servlet . http . HttpServletResponse ) */
@ Override public void updatePortalCookie ( HttpServletRequest request , HttpServletResponse response ) { } } | // Get the portal cookie object
final IPortalCookie portalCookie = this . getOrCreatePortalCookie ( request ) ; // Create the browser cookie
final Cookie cookie = this . convertToCookie ( portalCookie , this . portalCookieAlwaysSecure || request . isSecure ( ) ) ; // Update the expiration date of the portal cookie stored in the DB if the update interval
// has passed
final DateTime expires = portalCookie . getExpires ( ) ; if ( DateTime . now ( ) . minusMillis ( this . maxAgeUpdateInterval ) . isAfter ( expires . minusSeconds ( this . maxAge ) ) ) { try { this . portletCookieDao . updatePortalCookieExpiration ( portalCookie , cookie . getMaxAge ( ) ) ; } catch ( HibernateOptimisticLockingFailureException e ) { // Especially with ngPortal UI multiple requests for individual portlet content may
// come at
// the same time . Sometimes another thread updated the portal cookie between our
// dao fetch and
// dao update . If this happens , simply ignore the update since another thread has
// already
// made the update .
logger . debug ( "Attempted to update expired portal cookie but another thread beat me to it." + " Ignoring update since the other thread handled it." ) ; return ; } // Update expiration dates of portlet cookies stored in session
removeExpiredPortletCookies ( request ) ; } // Update the cookie in the users browser
response . addCookie ( cookie ) ; |
public class ThreadPoolTaskScheduler { /** * Set the ScheduledExecutorService ' s pool size . Default is 1.
* < b > This setting can be modified at runtime , for example through JMX . < / b >
* @ param poolSize the new pool size */
public void setPoolSize ( int poolSize ) { } } | // Assert . isTrue ( poolSize > 0 , " ' poolSize ' must be 1 or higher " ) ;
this . poolSize = poolSize ; if ( this . scheduledExecutor instanceof ScheduledThreadPoolExecutor ) { ( ( ScheduledThreadPoolExecutor ) this . scheduledExecutor ) . setCorePoolSize ( poolSize ) ; } |
public class ServerBuilder { /** * Binds the specified annotated service object under the specified path prefix .
* @ param exceptionHandlersAndConverters an iterable object of { @ link ExceptionHandlerFunction } ,
* { @ link RequestConverterFunction } and / or
* { @ link ResponseConverterFunction } */
public ServerBuilder annotatedService ( String pathPrefix , Object service , Iterable < ? > exceptionHandlersAndConverters ) { } } | return annotatedService ( pathPrefix , service , Function . identity ( ) , exceptionHandlersAndConverters ) ; |
public class PhoenixReader { /** * Utility method . In some cases older compressed PPX files only have a name ( or other string attribute )
* but no UUID . This method ensures that we either use the UUID supplied , or if it is missing , we
* generate a UUID from the name .
* @ param uuid uuid from object
* @ param name name from object
* @ return UUID instance */
private UUID getUUID ( UUID uuid , String name ) { } } | return uuid == null ? UUID . nameUUIDFromBytes ( name . getBytes ( ) ) : uuid ; |
public class TypeMaker { /** * Like the above version , but use and return the array given . */
public static com . sun . javadoc . Type [ ] getTypes ( DocEnv env , List < Type > ts , com . sun . javadoc . Type res [ ] ) { } } | int i = 0 ; for ( Type t : ts ) { res [ i ++ ] = getType ( env , t ) ; } return res ; |
public class Command { /** * Create a CORBA Any object and insert a short in it ( special case for the
* DevUShort Tango type )
* @ param data The int array to be inserted into the Any object
* @ exception DevFailed If the Any object creation failed .
* Click < a href = " . . / . . / tango _ basic / idl _ html / Tango . html # DevFailed " > here < / a > to read
* < b > DevFailed < / b > exception specification */
public Any insert_u ( short data ) throws DevFailed { } } | Any out_any = alloc_any ( ) ; out_any . insert_ushort ( data ) ; return out_any ; |
public class CertificatesImpl { /** * Deletes a certificate from the specified account .
* You cannot delete a certificate if a resource ( pool or compute node ) is using it . Before you can delete a certificate , you must therefore make sure that the certificate is not associated with any existing pools , the certificate is not installed on any compute nodes ( even if you remove a certificate from a pool , it is not removed from existing compute nodes in that pool until they restart ) , and no running tasks depend on the certificate . If you try to delete a certificate that is in use , the deletion fails . The certificate status changes to deleteFailed . You can use Cancel Delete Certificate to set the status back to active if you decide that you want to continue using the certificate .
* @ param thumbprintAlgorithm The algorithm used to derive the thumbprint parameter . This must be sha1.
* @ param thumbprint The thumbprint of the certificate to be deleted .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the { @ link ServiceResponseWithHeaders } object if successful . */
public Observable < Void > deleteAsync ( String thumbprintAlgorithm , String thumbprint ) { } } | return deleteWithServiceResponseAsync ( thumbprintAlgorithm , thumbprint ) . map ( new Func1 < ServiceResponseWithHeaders < Void , CertificateDeleteHeaders > , Void > ( ) { @ Override public Void call ( ServiceResponseWithHeaders < Void , CertificateDeleteHeaders > response ) { return response . body ( ) ; } } ) ; |
public class ReflectiveInterceptor { /** * Access and return the ReloadableType field on a specified class .
* @ param clazz the class for which to discover the reloadable type
* @ return the reloadable type for the class , or null if not reloadable */
public static ReloadableType getRType ( Class < ? > clazz ) { } } | // ReloadableType rtype = null ;
WeakReference < ReloadableType > ref = classToRType . get ( clazz ) ; ReloadableType rtype = null ; if ( ref != null ) { rtype = ref . get ( ) ; } if ( rtype == null ) { if ( ! theOldWay ) { // ' theOldWay ' attempts to grab the field from the type via reflection . This usually works except
// in cases where the class is not resolved yet since it can cause the class to resolve and its
// static initializer to run . This was happening on a grails compile where the compiler is
// loading dependencies ( but not initializing them ) . Instead we can use this route of
// discovering the type registry and locating the reloadable type . This does some map lookups
// which may be a problem , but once discovered , it is cached in the weak ref so that shouldn ' t
// be an ongoing perf problem .
// TODO testcases for something that is reloaded without having been resolved
ClassLoader cl = clazz . getClassLoader ( ) ; TypeRegistry tr = TypeRegistry . getTypeRegistryFor ( cl ) ; if ( tr == null ) { classToRType . put ( clazz , ReloadableType . NOT_RELOADABLE_TYPE_REF ) ; } else { rtype = tr . getReloadableType ( clazz . getName ( ) . replace ( '.' , '/' ) ) ; if ( rtype == null ) { classToRType . put ( clazz , ReloadableType . NOT_RELOADABLE_TYPE_REF ) ; } else { classToRType . put ( clazz , new WeakReference < ReloadableType > ( rtype ) ) ; } } } else { // need to work it out
Field rtypeField ; try { // System . out . println ( " discovering field for " + clazz . getName ( ) ) ;
// TODO cache somewhere - will need a clazz > Field cache
rtypeField = clazz . getDeclaredField ( Constants . fReloadableTypeFieldName ) ; } catch ( NoSuchFieldException nsfe ) { classToRType . put ( clazz , ReloadableType . NOT_RELOADABLE_TYPE_REF ) ; // expensive if constantly discovering this
return null ; } try { rtypeField . setAccessible ( true ) ; rtype = ( ReloadableType ) rtypeField . get ( null ) ; if ( rtype == null ) { classToRType . put ( clazz , ReloadableType . NOT_RELOADABLE_TYPE_REF ) ; throw new ReloadException ( "ReloadableType field '" + Constants . fReloadableTypeFieldName + "' is 'null' on type " + clazz . getName ( ) ) ; } else { classToRType . put ( clazz , new WeakReference < ReloadableType > ( rtype ) ) ; } } catch ( Exception e ) { throw new ReloadException ( "Unable to access ReloadableType field '" + Constants . fReloadableTypeFieldName + "' on type " + clazz . getName ( ) , e ) ; } } } else if ( rtype == ReloadableType . NOT_RELOADABLE_TYPE ) { return null ; } return rtype ; |
public class StringHelper { /** * Sanitizes a string so it can be used as an identifier
* @ param s the string to sanitize
* @ return the sanitized string */
public static String sanitize ( String s ) { } } | StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; ++ i ) { char c = s . charAt ( i ) ; switch ( c ) { case '\u00c0' : case '\u00c1' : case '\u00c3' : case '\u00c4' : sb . append ( 'A' ) ; break ; case '\u00c8' : case '\u00c9' : case '\u00cb' : sb . append ( 'E' ) ; break ; case '\u00cc' : case '\u00cd' : case '\u00cf' : sb . append ( 'I' ) ; break ; case '\u00d2' : case '\u00d3' : case '\u00d5' : case '\u00d6' : sb . append ( 'O' ) ; break ; case '\u00d9' : case '\u00da' : case '\u00dc' : sb . append ( 'U' ) ; break ; case '\u00e0' : case '\u00e1' : case '\u00e3' : case '\u00e4' : sb . append ( 'a' ) ; break ; case '\u00e8' : case '\u00e9' : case '\u00eb' : sb . append ( 'e' ) ; break ; case '\u00ec' : case '\u00ed' : case '\u00ef' : sb . append ( 'i' ) ; break ; case '\u00f2' : case '\u00f3' : case '\u00f6' : case '\u00f5' : sb . append ( 'o' ) ; break ; case '\u00f9' : case '\u00fa' : case '\u00fc' : sb . append ( 'u' ) ; break ; case '\u00d1' : sb . append ( 'N' ) ; break ; case '\u00f1' : sb . append ( 'n' ) ; break ; case '\u010c' : sb . append ( 'C' ) ; break ; case '\u0160' : sb . append ( 'S' ) ; break ; case '\u017d' : sb . append ( 'Z' ) ; break ; case '\u010d' : sb . append ( 'c' ) ; break ; case '\u0161' : sb . append ( 's' ) ; break ; case '\u017e' : sb . append ( 'z' ) ; break ; case '\u00df' : sb . append ( "ss" ) ; break ; default : if ( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) || ( c >= '0' && c <= '9' ) ) { sb . append ( c ) ; } else { sb . append ( '_' ) ; } break ; } } return sb . toString ( ) ; |
public class TreeRpc { /** * Handles requests to replace or delete all of the rules in the given tree .
* It ' s an efficiency helper for cases where folks don ' t want to make a single
* call per rule when updating many rules at once .
* @ param tsdb The TSDB to which we belong
* @ param query The HTTP query to work with
* @ throws BadRequestException if the request was invalid . */
private void handleRules ( TSDB tsdb , HttpQuery query ) { } } | int tree_id = 0 ; List < TreeRule > rules = null ; if ( query . hasContent ( ) ) { rules = query . serializer ( ) . parseTreeRulesV1 ( ) ; if ( rules == null || rules . isEmpty ( ) ) { throw new BadRequestException ( "Missing tree rules" ) ; } // validate that they all belong to the same tree
tree_id = rules . get ( 0 ) . getTreeId ( ) ; for ( TreeRule rule : rules ) { if ( rule . getTreeId ( ) != tree_id ) { throw new BadRequestException ( "All rules must belong to the same tree" ) ; } } } else { tree_id = parseTreeId ( query , false ) ; } // make sure the tree exists
try { if ( Tree . fetchTree ( tsdb , tree_id ) . joinUninterruptibly ( ) == null ) { throw new BadRequestException ( HttpResponseStatus . NOT_FOUND , "Unable to locate tree: " + tree_id ) ; } if ( query . getAPIMethod ( ) == HttpMethod . POST || query . getAPIMethod ( ) == HttpMethod . PUT ) { if ( rules == null || rules . isEmpty ( ) ) { if ( rules == null || rules . isEmpty ( ) ) { throw new BadRequestException ( "Missing tree rules" ) ; } } // purge the existing tree rules if we ' re told to PUT
if ( query . getAPIMethod ( ) == HttpMethod . PUT ) { TreeRule . deleteAllRules ( tsdb , tree_id ) . joinUninterruptibly ( ) ; } for ( TreeRule rule : rules ) { rule . syncToStorage ( tsdb , query . getAPIMethod ( ) == HttpMethod . PUT ) . joinUninterruptibly ( ) ; } query . sendStatusOnly ( HttpResponseStatus . NO_CONTENT ) ; } else if ( query . getAPIMethod ( ) == HttpMethod . DELETE ) { TreeRule . deleteAllRules ( tsdb , tree_id ) . joinUninterruptibly ( ) ; query . sendStatusOnly ( HttpResponseStatus . NO_CONTENT ) ; } else { throw new BadRequestException ( HttpResponseStatus . BAD_REQUEST , "Unsupported HTTP request method" ) ; } } catch ( BadRequestException e ) { throw e ; } catch ( IllegalArgumentException e ) { throw new BadRequestException ( e ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } |
public class VmServerAddressMarshaller { /** * Marshall the given parameter object . */
public void marshall ( VmServerAddress vmServerAddress , ProtocolMarshaller protocolMarshaller ) { } } | if ( vmServerAddress == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( vmServerAddress . getVmManagerId ( ) , VMMANAGERID_BINDING ) ; protocolMarshaller . marshall ( vmServerAddress . getVmId ( ) , VMID_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class FileUtils { /** * Removes the given file or directory recursively .
* < p > If the file or directory does not exist , this does not throw an exception , but simply does nothing .
* It considers the fact that a file - to - be - deleted is not present a success .
* < p > This method is safe against other concurrent deletion attempts .
* @ param file The file or directory to delete .
* @ throws IOException Thrown if the directory could not be cleaned for some reason , for example
* due to missing access / write permissions . */
public static void deleteFileOrDirectory ( File file ) throws IOException { } } | checkNotNull ( file , "file" ) ; guardIfWindows ( FileUtils :: deleteFileOrDirectoryInternal , file ) ; |
public class LinuxParameters { /** * Any host devices to expose to the container . This parameter maps to < code > Devices < / code > in the < a
* href = " https : / / docs . docker . com / engine / api / v1.35 / # operation / ContainerCreate " > Create a container < / a > section of the
* < a href = " https : / / docs . docker . com / engine / api / v1.35 / " > Docker Remote API < / a > and the < code > - - device < / code > option to
* < a href = " https : / / docs . docker . com / engine / reference / run / " > docker run < / a > .
* < note >
* If you are using tasks that use the Fargate launch type , the < code > devices < / code > parameter is not supported .
* < / note >
* @ return Any host devices to expose to the container . This parameter maps to < code > Devices < / code > in the < a
* href = " https : / / docs . docker . com / engine / api / v1.35 / # operation / ContainerCreate " > Create a container < / a > section
* of the < a href = " https : / / docs . docker . com / engine / api / v1.35 / " > Docker Remote API < / a > and the
* < code > - - device < / code > option to < a href = " https : / / docs . docker . com / engine / reference / run / " > docker
* run < / a > . < / p > < note >
* If you are using tasks that use the Fargate launch type , the < code > devices < / code > parameter is not
* supported . */
public java . util . List < Device > getDevices ( ) { } } | if ( devices == null ) { devices = new com . amazonaws . internal . SdkInternalList < Device > ( ) ; } return devices ; |
public class ElementUtil { /** * Similar to the above but matches against a pattern . */
public static boolean hasNamedAnnotation ( AnnotatedConstruct ac , Pattern pattern ) { } } | for ( AnnotationMirror annotation : ac . getAnnotationMirrors ( ) ) { if ( pattern . matcher ( getName ( annotation . getAnnotationType ( ) . asElement ( ) ) ) . matches ( ) ) { return true ; } } return false ; |
public class OutboundMsgHolder { /** * Adds a { @ link Http2PushPromise } message .
* @ param pushPromise push promise message */
public void addPromise ( Http2PushPromise pushPromise ) { } } | promises . add ( pushPromise ) ; responseFuture . notifyPromiseAvailability ( ) ; responseFuture . notifyPushPromise ( ) ; |
public class Subscription { /** * Removes the client method handler represented by this subscription . */
public void unsubscribe ( ) { } } | List < InvocationHandler > handler = this . handlers . get ( target ) ; if ( handler != null ) { handler . remove ( this . handler ) ; } |
public class Edge { /** * Retrieves an iterator that steps over the items in this edge .
* @ return An iterator that walks this edge up to the end or terminating
* node . */
public Iterator < T > iterator ( ) { } } | return new Iterator < T > ( ) { private int currentPosition = start ; private boolean hasNext = true ; public boolean hasNext ( ) { return hasNext ; } @ SuppressWarnings ( "unchecked" ) public T next ( ) { if ( end == - 1 ) hasNext = ! sequence . getItem ( currentPosition ) . getClass ( ) . equals ( SequenceTerminal . class ) ; else hasNext = currentPosition < getEnd ( ) - 1 ; return ( T ) sequence . getItem ( currentPosition ++ ) ; } public void remove ( ) { throw new UnsupportedOperationException ( "The remove method is not supported." ) ; } } ; |
public class DeclarationTransformerImpl { /** * Core function . Parses CSS declaration into structure applicable to
* DataNodeImpl
* @ param d
* Declaration
* @ param properties
* Wrap of parsed declaration ' s properties
* @ param values
* Wrap of parsed declaration ' s value
* @ return < code > true < / code > in case of success , < code > false < / code >
* otherwise */
@ Override public boolean parseDeclaration ( Declaration d , Map < String , CSSProperty > properties , Map < String , Term < ? > > values ) { } } | final String propertyName = d . getProperty ( ) ; // no such declaration is supported or declaration is empty
if ( ! css . isSupportedCSSProperty ( propertyName ) || d . isEmpty ( ) ) return false ; try { Method m = methods . get ( propertyName ) ; if ( m != null ) { boolean result = ( Boolean ) m . invoke ( this , d , properties , values ) ; log . debug ( "Parsing /{}/ {}" , result , d ) ; return result ; } else { boolean result = processAdditionalCSSGenericProperty ( d , properties , values ) ; log . debug ( "Parsing with proxy /{}/ {}" , result , d ) ; return result ; } } catch ( IllegalArgumentException e ) { log . warn ( "Illegal argument" , e ) ; } catch ( IllegalAccessException e ) { log . warn ( "Illegal access" , e ) ; } catch ( InvocationTargetException e ) { log . warn ( "Invocation target" , e ) ; log . warn ( "Invotation target cause" , e . getCause ( ) ) ; } return false ; |
public class Layout { /** * Measure the children from container until the layout is full ( if ViewPort is enabled )
* @ param centerDataIndex of the item in center
* @ param measuredChildren the list of measured children
* measuredChildren list can be passed as null if it ' s not needed to
* create the list of the measured items */
public boolean measureUntilFull ( int centerDataIndex , final Collection < Widget > measuredChildren ) { } } | if ( centerDataIndex == - 1 ) { centerDataIndex = 0 ; } boolean firstChildInBoundsFound = false ; Log . d ( Log . SUBSYSTEM . LAYOUT , TAG , "measureUntilFull: centerDataIndex view = %d mContainer.size() = %d" , centerDataIndex , mContainer . size ( ) ) ; for ( int i = centerDataIndex ; i >= 0 && i < mContainer . size ( ) ; ) { boolean inBounds = true ; boolean childChanged = ! isChildMeasured ( i ) ; Widget view = childChanged ? measureChild ( i ) : mContainer . get ( i ) ; if ( ! mViewPort . isClippingEnabled ( ) ) { if ( childChanged ) { postMeasurement ( ) ; } } else { inBounds = inViewPort ( i ) ; if ( ! inBounds ) { if ( childChanged ) { invalidate ( i ) ; } childChanged = ! childChanged ; } } Log . d ( Log . SUBSYSTEM . LAYOUT , TAG , "measureUntilFull: measureChild view = %s " + "isBounds = %b dataIndex = %d childChanged = %b, viewport = %s" , view == null ? "<null>" : view . getName ( ) , inBounds , i , childChanged , mViewPort ) ; if ( view != null && inBounds ) { if ( measuredChildren != null ) { measuredChildren . add ( view ) ; } } boolean directionIsChanged = changeDirection ( i , centerDataIndex , inBounds ) ; i = getNextIndex ( i , centerDataIndex , directionIsChanged ) ; firstChildInBoundsFound = firstChildInBoundsFound || inBounds ; if ( directionIsChanged ) { inBounds = true ; } Log . d ( Log . SUBSYSTEM . LAYOUT , TAG , "measureUntilFull: directionIsChanged = %b inBounds = %b" , directionIsChanged , inBounds ) ; if ( mViewPort . isClippingEnabled ( ) && childChanged && inBounds ) { inBounds = postMeasurement ( ) ; } if ( firstChildInBoundsFound && ! inBounds ) { break ; } } return true ; |
public class ZaurusTableForm { /** * delete current row , answer special action codes , see comment below */
public int deleteRow ( ) { } } | // build the delete string
String deleteString = "DELETE FROM " + tableName + this . generatePKWhere ( ) ; PreparedStatement ps = null ; // System . out . println ( " delete string " + deleteString ) ;
try { // fill the question marks
ps = cConn . prepareStatement ( deleteString ) ; ps . clearParameters ( ) ; int i ; for ( int j = 0 ; j < primaryKeys . length ; j ++ ) { ps . setObject ( j + 1 , resultRowPKs [ aktRowNr ] [ j ] ) ; } // end of for ( int i = 0 ; i < primaryKeys . length ; i + + )
ps . executeUpdate ( ) ; } catch ( SQLException e ) { ZaurusEditor . printStatus ( "SQL Exception: " + e . getMessage ( ) ) ; return 0 ; } finally { try { if ( ps != null ) { ps . close ( ) ; } } catch ( SQLException e ) { } } // delete the corresponding primary key values from resultRowPKs
numberOfResult -- ; for ( int i = aktRowNr ; i < numberOfResult ; i ++ ) { for ( int j = 0 ; j < primaryKeys . length ; j ++ ) { resultRowPKs [ i ] [ j ] = resultRowPKs [ i + 1 ] [ j ] ; } } // there are the following outcomes after deleting aktRowNr :
/* A B C D E F
no rows left J N N N N N
one row left - J N J N N
deleted row was the last row - J J N N N
deleted row was the pre - last - - - - J N
first D X + D + *
. D X X D D
. D X +
last X
new numberOfResult 0 1 2 1 2 2
old aktRowNr 0 1 2 0 1 0
D - deleted row
X - any one row
+ - one or more rows
* - zero or more rows */
// A . return to the search panel and tell ' last row deleted ' on the status line
// B . show the previous row and disable previous button
// C . show the previous row as akt row
// D . show akt row and disable next button
// E . show akt row and disable next button
// F . show akt row
// these actions reduce to the following actions for ZaurusEditor :
// 1 . show search panel
// 2 . disable previous button
// 3 . disable next button
// 4 . do nothing
// and 1,2,3,4 are the possible return codes
int actionCode ; if ( numberOfResult == 0 ) { // case A
actionCode = 1 ; ZaurusEditor . printStatus ( "Last row was deleted." ) ; return actionCode ; } else if ( numberOfResult == aktRowNr ) { // B or C
// new aktRow is previous row
aktRowNr -- ; if ( aktRowNr == 0 ) { actionCode = 2 ; } else { actionCode = 4 ; } // end of if ( aktRowNr = = 0)
} else { // D , E , F
if ( numberOfResult >= 2 && aktRowNr < numberOfResult - 1 ) { actionCode = 4 ; } else { actionCode = 3 ; } // end of else
} this . showAktRow ( ) ; ZaurusEditor . printStatus ( "Row was deleted." ) ; return actionCode ; |
public class VersionHistoryImpl { /** * { @ inheritDoc } */
public boolean hasVersionLabel ( Version version , String label ) throws VersionException , RepositoryException { } } | checkValid ( ) ; NodeData versionData = getVersionDataByLabel ( label ) ; if ( versionData != null && version . getUUID ( ) . equals ( versionData . getIdentifier ( ) ) ) { return true ; } return false ; |
public class AbstractResource { /** * Gets the object with the given unique identifier .
* @ param inId the unique identifier . Cannot be < code > null < / code > .
* @ param req the HTTP servlet request .
* @ return the object with the given unique identifier . Guaranteed not
* < code > null < / code > .
* @ throws HttpStatusException if there is no object with the given
* unique identifier , or if the user is not authorized to access the
* object . */
@ GET @ Path ( "/{id}" ) @ Produces ( MediaType . APPLICATION_JSON ) public C getAny ( @ PathParam ( "id" ) Long inId , @ Context HttpServletRequest req ) { } } | E entity = this . dao . retrieve ( inId ) ; if ( entity == null ) { throw new HttpStatusException ( Response . Status . NOT_FOUND ) ; } else if ( isAuthorizedEntity ( entity , req ) && ( ! isRestricted ( ) || req . isUserInRole ( "admin" ) ) ) { return toComm ( entity , req ) ; } else { throw new HttpStatusException ( Response . Status . NOT_FOUND ) ; } |
public class Validate { /** * < p > Validate that the specified argument collection is neither
* < code > null < / code > nor contains any elements that are < code > null < / code > ;
* otherwise throwing an exception with the specified message .
* < pre > Validate . noNullElements ( myCollection , " The collection contains null elements " ) ; < / pre >
* < p > If the collection is < code > null < / code > , then the message in the exception
* is & quot ; The validated object is null & quot ; . < / p >
* @ param collection the collection to check
* @ param message the exception message if the collection has
* @ throws IllegalArgumentException if the collection is < code > null < / code > or
* an element in the collection is < code > null < / code > */
public static void noNullElements ( Collection < ? > collection , String message ) { } } | Validate . notNull ( collection ) ; for ( Object element : collection ) { if ( element == null ) { throw new IllegalArgumentException ( message ) ; } } |
public class EntityTypeValidator { /** * Validates the entity ID : - Validates that the entity ID does not contain illegal characters and
* validates the name length
* @ param entityType entity meta data
* @ throws MolgenisValidationException if the entity simple name content is invalid or the fully
* qualified name , simple name and package name are not consistent */
static void validateEntityId ( EntityType entityType ) { } } | // validate entity name ( e . g . illegal characters , length )
String id = entityType . getId ( ) ; if ( ! id . equals ( ATTRIBUTE_META_DATA ) && ! id . equals ( ENTITY_TYPE_META_DATA ) && ! id . equals ( PACKAGE ) ) { try { NameValidator . validateEntityName ( entityType . getId ( ) ) ; } catch ( MolgenisDataException e ) { throw new MolgenisValidationException ( new ConstraintViolation ( e . getMessage ( ) ) ) ; } } |
public class IntHashMap { /** * Returns a collection view of the mappings contained in this map . Each
* element in the returned collection is a < tt > Map . Entry < / tt > . The
* collection is backed by the map , so changes to the map are reflected in
* the collection , and vice - versa . The collection supports element
* removal , which removes the corresponding mapping from the map , via the
* < tt > Iterator . remove < / tt > , < tt > Collection . remove < / tt > ,
* < tt > removeAll < / tt > , < tt > retainAll < / tt > , and < tt > clear < / tt > operations .
* It does not support the < tt > add < / tt > or < tt > addAll < / tt > operations .
* @ return a collection view of the mappings contained in this map . */
public Set < Map . Entry < Integer , V > > entrySet ( ) { } } | if ( entrySet == null ) { entrySet = new AbstractSet < Map . Entry < Integer , V > > ( ) { public Iterator iterator ( ) { return ( Iterator ) new IntHashIterator ( ENTRIES ) ; } public boolean contains ( Object o ) { if ( ! ( o instanceof Map . Entry ) ) { return false ; } Map . Entry entry = ( Map . Entry ) o ; Integer key = ( Integer ) entry . getKey ( ) ; Entry tab [ ] = table ; int hash = ( key == null ? 0 : key . hashCode ( ) ) ; int index = ( hash & 0x7fffffff ) % tab . length ; for ( Entry e = tab [ index ] ; e != null ; e = e . next ) { if ( e . key == hash && e . equals ( entry ) ) { return true ; } } return false ; } public boolean remove ( Object o ) { if ( ! ( o instanceof Map . Entry ) ) { return false ; } Map . Entry entry = ( Map . Entry ) o ; Integer key = ( Integer ) entry . getKey ( ) ; Entry tab [ ] = table ; int hash = ( key == null ? 0 : key . hashCode ( ) ) ; int index = ( hash & 0x7fffffff ) % tab . length ; for ( Entry e = tab [ index ] , prev = null ; e != null ; prev = e , e = e . next ) { if ( e . key == hash && e . equals ( entry ) ) { modCount ++ ; if ( prev != null ) { prev . next = e . next ; } else { tab [ index ] = e . next ; } count -- ; e . value = null ; return true ; } } return false ; } public int size ( ) { return count ; } public void clear ( ) { IntHashMap . this . clear ( ) ; } } ; } return entrySet ; |
public class ComputerVisionImpl { /** * Optical Character Recognition ( OCR ) detects printed text in an image and extracts the recognized characters into a machine - usable character stream . Upon success , the OCR results will be returned . Upon failure , the error code together with an error message will be returned . The error code can be one of InvalidImageUrl , InvalidImageFormat , InvalidImageSize , NotSupportedImage , NotSupportedLanguage , or InternalServerError .
* @ param detectOrientation Whether detect the text orientation in the image . With detectOrientation = true the OCR service tries to detect the image orientation and correct it before further processing ( e . g . if it ' s upside - down ) .
* @ param image An image stream .
* @ param recognizePrintedTextInStreamOptionalParameter the object representing the optional parameters to be set before calling this API
* @ param serviceCallback the async ServiceCallback to handle successful and failed responses .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the { @ link ServiceFuture } object */
public ServiceFuture < OcrResult > recognizePrintedTextInStreamAsync ( boolean detectOrientation , byte [ ] image , RecognizePrintedTextInStreamOptionalParameter recognizePrintedTextInStreamOptionalParameter , final ServiceCallback < OcrResult > serviceCallback ) { } } | return ServiceFuture . fromResponse ( recognizePrintedTextInStreamWithServiceResponseAsync ( detectOrientation , image , recognizePrintedTextInStreamOptionalParameter ) , serviceCallback ) ; |
public class DelegateView { /** * Provides a mapping from the view coordinate space to the logical
* coordinate space of the model .
* @ param x
* x coordinate of the view location to convert
* @ param y
* y coordinate of the view location to convert
* @ param a
* the allocated region to render into
* @ return the location within the model that best represents the given
* point in the view */
@ Override public int viewToModel ( float x , float y , Shape a , Position . Bias [ ] bias ) { } } | if ( view != null ) { int retValue = view . viewToModel ( x , y , a , bias ) ; return retValue ; } return - 1 ; |
public class PersistentExecutorImpl { /** * { @ inheritDoc } */
@ Override public boolean createProperty ( String name , String value ) { } } | if ( name == null || name . length ( ) == 0 ) throw new IllegalArgumentException ( "name: " + name ) ; if ( value == null || value . length ( ) == 0 ) throw new IllegalArgumentException ( "value: " + value ) ; boolean created = false ; TransactionController tranController = new TransactionController ( ) ; try { tranController . preInvoke ( ) ; created = taskStore . createProperty ( name , value ) ; if ( ! created ) tranController . expectRollback ( ) ; } catch ( Throwable x ) { tranController . setFailure ( x ) ; } finally { PersistentStoreException x = tranController . postInvoke ( PersistentStoreException . class ) ; // TODO proposed spec class
if ( x != null ) throw x ; } return created ; |
public class CATBifurcatedConsumer { /** * This overrides the default close method in < code > CATConsumer < / code > as the consumer session
* is saved with us , and not in the main consumer .
* @ param requestNumber The request number to send replies with . */
@ Override public void close ( int requestNumber ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( this , tc , "close" , requestNumber ) ; try { bifSession . close ( ) ; try { getConversation ( ) . send ( poolManager . allocate ( ) , JFapChannelConstants . SEG_CLOSE_CONSUMER_SESS_R , requestNumber , JFapChannelConstants . PRIORITY_MEDIUM , true , ThrottlingPolicy . BLOCK_THREAD , null ) ; } catch ( SIException e ) { FFDCFilter . processException ( e , CLASS_NAME + ".close" , CommsConstants . CATBIFCONSUMER_CLOSE_01 , this ) ; SibTr . error ( tc , "COMMUNICATION_ERROR_SICO2033" , e ) ; } } catch ( SIException e ) { // No FFDC code needed
// Only FFDC if we haven ' t received a meTerminated event .
if ( ! ( ( ConversationState ) getConversation ( ) . getAttachment ( ) ) . hasMETerminated ( ) ) { FFDCFilter . processException ( e , CLASS_NAME + ".close" , CommsConstants . CATBIFCONSUMER_CLOSE_02 , this ) ; } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isDebugEnabled ( ) ) SibTr . debug ( tc , e . getMessage ( ) , e ) ; StaticCATHelper . sendExceptionToClient ( e , CommsConstants . CATBIFCONSUMER_CLOSE_02 , getConversation ( ) , requestNumber ) ; } if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( this , tc , "close" ) ; |
public class StreamGraphHasherV2 { /** * Generates a hash from a user - specified ID . */
private byte [ ] generateUserSpecifiedHash ( StreamNode node , Hasher hasher ) { } } | hasher . putString ( node . getTransformationUID ( ) , Charset . forName ( "UTF-8" ) ) ; return hasher . hash ( ) . asBytes ( ) ; |
public class PersistentExecutorImpl { /** * { @ inheritDoc } */
@ Override public int removeTimers ( String appName , String pattern , Character escape , TaskState state , boolean inState ) throws Exception { } } | pattern = pattern == null ? null : Utils . normalizeString ( pattern ) ; int updateCount = 0 ; TransactionController tranController = new TransactionController ( ) ; try { tranController . preInvoke ( ) ; updateCount = taskStore . remove ( pattern , escape , state , inState , appName ) ; } catch ( Throwable x ) { tranController . setFailure ( x ) ; } finally { Exception x = tranController . postInvoke ( Exception . class ) ; if ( x != null ) throw x ; } return updateCount ; |
public class IfcCompositeCurveSegmentImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ SuppressWarnings ( "unchecked" ) public EList < IfcCompositeCurve > getUsingCurves ( ) { } } | return ( EList < IfcCompositeCurve > ) eGet ( Ifc2x3tc1Package . Literals . IFC_COMPOSITE_CURVE_SEGMENT__USING_CURVES , true ) ; |
public class AnimatedLabel { /** * Advances the animated label to the next frame . You normally don ' t need to call this manually as it will be done
* by the animation thread . */
public synchronized void nextFrame ( ) { } } | currentFrame ++ ; if ( currentFrame >= frames . size ( ) ) { currentFrame = 0 ; } super . setLines ( frames . get ( currentFrame ) ) ; invalidate ( ) ; |
public class SourceParams { /** * Create parameters necessary for creating an EPS source .
* @ param amount A positive integer in the smallest currency unit representing the amount to
* charge the customer ( e . g . , 1099 for a € 10.99 payment ) .
* @ param name The full name of the account holder .
* @ param returnUrl The URL the customer should be redirected to after the authorization
* process .
* @ param statementDescriptor A custom statement descriptor for the payment ( optional ) .
* @ return a { @ link SourceParams } object that can be used to create an EPS source
* @ see < a href = " https : / / stripe . com / docs / sources / eps " > https : / / stripe . com / docs / sources / eps < / a > */
@ NonNull public static SourceParams createEPSParams ( @ IntRange ( from = 0 ) long amount , @ NonNull String name , @ NonNull String returnUrl , @ Nullable String statementDescriptor ) { } } | final SourceParams params = new SourceParams ( ) . setType ( Source . EPS ) . setCurrency ( Source . EURO ) . setAmount ( amount ) . setOwner ( createSimpleMap ( FIELD_NAME , name ) ) . setRedirect ( createSimpleMap ( FIELD_RETURN_URL , returnUrl ) ) ; if ( statementDescriptor != null ) { Map < String , Object > additionalParamsMap = createSimpleMap ( FIELD_STATEMENT_DESCRIPTOR , statementDescriptor ) ; params . setApiParameterMap ( additionalParamsMap ) ; } return params ; |
public class MessageControl { /** * GetVersionFromSchemaLocation Method . */
public String getVersionFromSchemaLocation ( String schemaLocation ) { } } | MessageVersion recMessageVersion = this . getMessageVersion ( ) ; recMessageVersion . close ( ) ; try { while ( recMessageVersion . hasNext ( ) ) { recMessageVersion . next ( ) ; String messageSchemaLocation = this . getSchemaLocation ( recMessageVersion , DBConstants . BLANK ) ; if ( schemaLocation . startsWith ( messageSchemaLocation ) ) return recMessageVersion . getField ( MessageVersion . CODE ) . toString ( ) ; } } catch ( DBException e ) { e . printStackTrace ( ) ; } return null ; |
public class RoutesInner { /** * Creates or updates a route in the specified route table .
* @ param resourceGroupName The name of the resource group .
* @ param routeTableName The name of the route table .
* @ param routeName The name of the route .
* @ param routeParameters Parameters supplied to the create or update route operation .
* @ param serviceCallback the async ServiceCallback to handle successful and failed responses .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the { @ link ServiceFuture } object */
public ServiceFuture < RouteInner > beginCreateOrUpdateAsync ( String resourceGroupName , String routeTableName , String routeName , RouteInner routeParameters , final ServiceCallback < RouteInner > serviceCallback ) { } } | return ServiceFuture . fromResponse ( beginCreateOrUpdateWithServiceResponseAsync ( resourceGroupName , routeTableName , routeName , routeParameters ) , serviceCallback ) ; |
public class Gen { /** * Sort ( int ) arrays of keys and values */
static void qsort2 ( int [ ] keys , int [ ] values , int lo , int hi ) { } } | int i = lo ; int j = hi ; int pivot = keys [ ( i + j ) / 2 ] ; do { while ( keys [ i ] < pivot ) i ++ ; while ( pivot < keys [ j ] ) j -- ; if ( i <= j ) { int temp1 = keys [ i ] ; keys [ i ] = keys [ j ] ; keys [ j ] = temp1 ; int temp2 = values [ i ] ; values [ i ] = values [ j ] ; values [ j ] = temp2 ; i ++ ; j -- ; } } while ( i <= j ) ; if ( lo < j ) qsort2 ( keys , values , lo , j ) ; if ( i < hi ) qsort2 ( keys , values , i , hi ) ; |
public class TypeAnnotationPosition { /** * Create a { @ code TypeAnnotationPosition } for a method type
* parameter bound .
* @ param location The type path .
* @ param onLambda The lambda for this variable .
* @ param parameter _ index The index of the type parameter .
* @ param bound _ index The index of the type parameter bound .
* @ param pos The position from the associated tree node . */
public static TypeAnnotationPosition methodTypeParameterBound ( final List < TypePathEntry > location , final JCLambda onLambda , final int parameter_index , final int bound_index , final int pos ) { } } | return new TypeAnnotationPosition ( TargetType . METHOD_TYPE_PARAMETER_BOUND , pos , parameter_index , onLambda , Integer . MIN_VALUE , bound_index , location ) ; |
public class HButtonBox { /** * Get the current string value in HTML .
* @ param out The html out stream .
* @ exception DBException File exception . */
public void printDisplayControl ( PrintWriter out ) { } } | if ( this . getScreenField ( ) . getConverter ( ) != null ) { String strFieldName = this . getScreenField ( ) . getConverter ( ) . getField ( ) . getFieldName ( false , false ) ; this . printInputControl ( out , null , strFieldName , null , null , null , HtmlConstants . BUTTON , 0 ) ; // Button that does nothing ?
} else if ( this . getScreenField ( ) . getParentScreen ( ) instanceof GridScreen ) { // These are command buttons such as " Form " or " Detail "
this . printInputControl ( out , null , null , null , null , null , HtmlConstants . BUTTON , 0 ) ; // Button that does nothing ?
} |
public class ColumnDefinition { /** * Deserialize columns from storage - level representation
* @ param serializedColumns storage - level partition containing the column definitions
* @ return the list of processed ColumnDefinitions */
public static List < ColumnDefinition > fromSchema ( UntypedResultSet serializedColumns , String ksName , String cfName , AbstractType < ? > rawComparator , boolean isSuper ) { } } | List < ColumnDefinition > cds = new ArrayList < > ( ) ; for ( UntypedResultSet . Row row : serializedColumns ) { Kind kind = row . has ( KIND ) ? Kind . deserialize ( row . getString ( KIND ) ) : Kind . REGULAR ; Integer componentIndex = null ; if ( row . has ( COMPONENT_INDEX ) ) componentIndex = row . getInt ( COMPONENT_INDEX ) ; else if ( kind == Kind . CLUSTERING_COLUMN && isSuper ) componentIndex = 1 ; // A ColumnDefinition for super columns applies to the column component
// Note : we save the column name as string , but we should not assume that it is an UTF8 name , we
// we need to use the comparator fromString method
AbstractType < ? > comparator = getComponentComparator ( rawComparator , componentIndex , kind ) ; ColumnIdentifier name = new ColumnIdentifier ( comparator . fromString ( row . getString ( COLUMN_NAME ) ) , comparator ) ; AbstractType < ? > validator ; try { validator = TypeParser . parse ( row . getString ( TYPE ) ) ; } catch ( RequestValidationException e ) { throw new RuntimeException ( e ) ; } IndexType indexType = null ; if ( row . has ( INDEX_TYPE ) ) indexType = IndexType . valueOf ( row . getString ( INDEX_TYPE ) ) ; Map < String , String > indexOptions = null ; if ( row . has ( INDEX_OPTIONS ) ) indexOptions = FBUtilities . fromJsonMap ( row . getString ( INDEX_OPTIONS ) ) ; String indexName = null ; if ( row . has ( INDEX_NAME ) ) indexName = row . getString ( INDEX_NAME ) ; cds . add ( new ColumnDefinition ( ksName , cfName , name , validator , indexType , indexOptions , indexName , componentIndex , kind ) ) ; } return cds ; |
public class InstallOptions { /** * Get the indicated option from the console . Continue prompting until the
* value is valid , or the user has indicated they want to cancel the
* installation . */
private void inputOption ( String optionId ) throws InstallationCancelledException { } } | OptionDefinition opt = OptionDefinition . get ( optionId , this ) ; if ( opt . getLabel ( ) == null || opt . getLabel ( ) . length ( ) == 0 ) { throw new InstallationCancelledException ( optionId + " is missing label (check OptionDefinition.properties?)" ) ; } System . out . println ( opt . getLabel ( ) ) ; System . out . println ( dashes ( opt . getLabel ( ) . length ( ) ) ) ; System . out . println ( opt . getDescription ( ) ) ; System . out . println ( ) ; String [ ] valids = opt . getValidValues ( ) ; if ( valids != null ) { System . out . print ( "Options : " ) ; for ( int i = 0 ; i < valids . length ; i ++ ) { if ( i > 0 ) { System . out . print ( ", " ) ; } System . out . print ( valids [ i ] ) ; } System . out . println ( ) ; } String defaultVal = opt . getDefaultValue ( ) ; if ( valids != null || defaultVal != null ) { System . out . println ( ) ; } boolean gotValidValue = false ; while ( ! gotValidValue ) { System . out . print ( "Enter a value " ) ; if ( defaultVal != null ) { System . out . print ( "[default is " + defaultVal + "] " ) ; } System . out . print ( "==> " ) ; String value = readLine ( ) . trim ( ) ; if ( value . length ( ) == 0 && defaultVal != null ) { value = defaultVal ; } System . out . println ( ) ; if ( value . equalsIgnoreCase ( "cancel" ) ) { throw new InstallationCancelledException ( "Cancelled by user." ) ; } try { opt . validateValue ( value ) ; gotValidValue = true ; _map . put ( optionId , value ) ; System . out . println ( ) ; } catch ( OptionValidationException e ) { System . out . println ( "Error: " + e . getMessage ( ) ) ; } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.