signature
stringlengths
43
39.1k
implementation
stringlengths
0
450k
public class CommercePriceListPersistenceImpl { /** * Returns the commerce price lists before and after the current commerce price list in the ordered set where displayDate & lt ; & # 63 ; and status = & # 63 ; . * @ param commercePriceListId the primary key of the current commerce price list * @ param displayDate the display date * @ param status the status * @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > ) * @ return the previous , current , and next commerce price list * @ throws NoSuchPriceListException if a commerce price list with the primary key could not be found */ @ Override public CommercePriceList [ ] findByLtD_S_PrevAndNext ( long commercePriceListId , Date displayDate , int status , OrderByComparator < CommercePriceList > orderByComparator ) throws NoSuchPriceListException { } }
CommercePriceList commercePriceList = findByPrimaryKey ( commercePriceListId ) ; Session session = null ; try { session = openSession ( ) ; CommercePriceList [ ] array = new CommercePriceListImpl [ 3 ] ; array [ 0 ] = getByLtD_S_PrevAndNext ( session , commercePriceList , displayDate , status , orderByComparator , true ) ; array [ 1 ] = commercePriceList ; array [ 2 ] = getByLtD_S_PrevAndNext ( session , commercePriceList , displayDate , status , orderByComparator , false ) ; return array ; } catch ( Exception e ) { throw processException ( e ) ; } finally { closeSession ( session ) ; }
public class GConvertImage { /** * Converts one type of between two types of images using a default method . Both are the same image type * then a simple type cast if performed at the pixel level . If the input is multi - band and the output * is single band then it will average the bands . If input is single band and output is multi - band * then the single band is copied into each of the other bands . * In some cases a temporary image will be created to store intermediate results . If this is an issue * you will need to create a specialized conversion algorithm . * @ param input Input image which is being converted . Not modified . * @ param output ( Optional ) The output image . If null a new image is created . Modified . * @ return Converted image . */ public static void convert ( ImageBase input , ImageBase output ) { } }
ImageType typeIn = input . getImageType ( ) ; ImageType typeOut = output . getImageType ( ) ; if ( input instanceof ImageGray ) { ImageGray sb = ( ImageGray ) input ; if ( output instanceof ImageGray ) { if ( input . getClass ( ) == output . getClass ( ) ) { output . setTo ( input ) ; } else { try { Method m = ConvertImage . class . getMethod ( "convert" , input . getClass ( ) , output . getClass ( ) ) ; m . invoke ( null , input , output ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Unknown conversion. " + input . getClass ( ) . getSimpleName ( ) + " to " + output . getClass ( ) . getSimpleName ( ) ) ; } } } else if ( output instanceof Planar ) { Planar ms = ( Planar ) output ; for ( int i = 0 ; i < ms . getNumBands ( ) ; i ++ ) { convert ( input , ms . getBand ( i ) ) ; } } else if ( output instanceof ImageInterleaved ) { ImageInterleaved il = ( ImageInterleaved ) output ; for ( int i = 0 ; i < il . getNumBands ( ) ; i ++ ) { GImageMiscOps . insertBand ( sb , i , il ) ; } } } else if ( input instanceof ImageInterleaved && output instanceof ImageInterleaved ) { if ( input . getClass ( ) == output . getClass ( ) ) { output . setTo ( input ) ; } else { try { Method m = ConvertImage . class . getMethod ( "convert" , input . getClass ( ) , output . getClass ( ) ) ; m . invoke ( null , input , output ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Unknown conversion. " + input . getClass ( ) . getSimpleName ( ) + " to " + output . getClass ( ) . getSimpleName ( ) ) ; } } } else if ( input instanceof Planar && output instanceof ImageGray ) { Planar mi = ( Planar ) input ; ImageGray so = ( ImageGray ) output ; if ( mi . getImageType ( ) . getDataType ( ) != so . getDataType ( ) ) { int w = output . width ; int h = output . height ; ImageGray tmp = GeneralizedImageOps . createSingleBand ( mi . getImageType ( ) . getDataType ( ) , w , h ) ; average ( mi , tmp ) ; convert ( tmp , so ) ; } else { average ( mi , so ) ; } } else if ( input instanceof Planar && output instanceof ImageInterleaved ) { String functionName ; if ( typeIn . getDataType ( ) == typeOut . getDataType ( ) ) { functionName = "convert" ; } else { functionName = "convert" + typeIn . getDataType ( ) + typeOut . getDataType ( ) ; } try { Method m = ConvertImage . class . getMethod ( functionName , input . getClass ( ) , output . getClass ( ) ) ; m . invoke ( null , input , output ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Unknown conversion. " + input . getClass ( ) . getSimpleName ( ) + " to " + output . getClass ( ) . getSimpleName ( ) ) ; } } else if ( input instanceof Planar && output instanceof Planar ) { Planar mi = ( Planar ) input ; Planar mo = ( Planar ) output ; if ( mi . getBandType ( ) == mo . getBandType ( ) ) { mo . setTo ( mi ) ; } else { for ( int i = 0 ; i < mi . getNumBands ( ) ; i ++ ) { convert ( mi . getBand ( i ) , mo . getBand ( i ) ) ; } } } else if ( input instanceof ImageInterleaved && output instanceof Planar ) { String functionName ; if ( typeIn . getDataType ( ) == typeOut . getDataType ( ) ) { functionName = "convert" ; } else { functionName = "convert" + typeIn . getDataType ( ) + typeOut . getDataType ( ) ; } try { Method m = ConvertImage . class . getMethod ( functionName , input . getClass ( ) , output . getClass ( ) ) ; m . invoke ( null , input , output ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Unknown conversion. " + input . getClass ( ) . getSimpleName ( ) + " to " + output . getClass ( ) . getSimpleName ( ) ) ; } } else if ( input instanceof ImageInterleaved && output instanceof ImageGray ) { ImageInterleaved mb = ( ImageInterleaved ) input ; ImageGray so = ( ImageGray ) output ; if ( mb . getImageType ( ) . getDataType ( ) != so . getDataType ( ) ) { int w = output . width ; int h = output . height ; ImageGray tmp = GeneralizedImageOps . createSingleBand ( mb . getImageType ( ) . getDataType ( ) , w , h ) ; average ( mb , tmp ) ; convert ( tmp , so ) ; } else { average ( mb , so ) ; } } else { String nameInput = input . getClass ( ) . getSimpleName ( ) ; String nameOutput = output . getClass ( ) . getSimpleName ( ) ; throw new IllegalArgumentException ( "Don't know how to convert between input types. " + nameInput + " " + nameOutput ) ; }
public class ApplicationExtensions { /** * Gets the resource stream from the given parameters . * @ param application * the application * @ param path * the path * @ param contentType * the content type * @ return the resource stream * @ throws IOException * Signals that an I / O exception has occurred . */ public static IResourceStream getResourceStream ( final WebApplication application , final String path , final String contentType ) throws IOException { } }
return new ByteArrayResourceStreamWriter ( ) { private static final long serialVersionUID = 1L ; @ Override public String getContentType ( ) { return contentType ; } @ Override protected byte [ ] load ( ) throws IOException { final String realPath = ApplicationExtensions . getRealPath ( application , path ) ; final File file = new File ( realPath ) ; final byte [ ] data = Files . readBytes ( file ) ; return data ; } } ;
public class OQL { /** * PropertyBinding */ private void _buildPropertyBinding ( final PropertyBinding binding , final StringBuilder stmt , final List < Object > params ) { } }
if ( binding instanceof RelationalBinding ) { _buildRelationalBinding ( ( RelationalBinding ) binding , stmt , params ) ; // throws SearchException } else if ( binding instanceof InBinding ) { _buildInBinding ( ( InBinding ) binding , stmt , params ) ; // throws SearchException } else if ( binding instanceof LikeBinding ) { _buildLikeBinding ( ( LikeBinding ) binding , stmt , params ) ; // throws SearchException } else if ( binding instanceof TextMatchBinding ) { _buildTextMatchBinding ( ( TextMatchBinding ) binding , stmt , params ) ; // throws SearchException } else if ( binding instanceof NullBinding ) { _buildNullBinding ( ( NullBinding ) binding , stmt ) ; // throws SearchException } else { throw new IllegalArgumentException ( "unsupported PropertyBinding: " + String . valueOf ( binding ) ) ; }
public class Assembly { /** * Prepares a file for tus upload . * @ param inptStream { @ link InputStream } * @ param fieldName the form field name assigned to the file . * @ param assemblyUrl the assembly url affiliated with the tus upload . * @ throws IOException when there ' s a failure with reading the input stream . */ protected void processTusFile ( InputStream inptStream , String fieldName , String assemblyUrl ) throws IOException { } }
TusUpload upload = getTusUploadInstance ( inptStream , fieldName , assemblyUrl ) ; Map < String , String > metadata = new HashMap < String , String > ( ) ; metadata . put ( "filename" , fieldName ) ; metadata . put ( "assembly_url" , assemblyUrl ) ; metadata . put ( "fieldname" , fieldName ) ; upload . setMetadata ( metadata ) ; uploads . add ( upload ) ;
public class JCuda { /** * Map graphics resources for access by CUDA . * < pre > * cudaError _ t cudaGraphicsMapResources ( * int count , * cudaGraphicsResource _ t * resources , * cudaStream _ t stream = 0 ) * < / pre > * < div > * < p > Map graphics resources for access by * CUDA . Maps the < tt > count < / tt > graphics resources in < tt > resources < / tt > * for access by CUDA . * < p > The resources in < tt > resources < / tt > * may be accessed by CUDA until they are unmapped . The graphics API from * which < tt > resources < / tt > were registered should not access any * resources while they are mapped by CUDA . If an application does so , * the results are * undefined . * < p > This function provides the synchronization * guarantee that any graphics calls issued before cudaGraphicsMapResources ( ) * will complete before any subsequent CUDA work issued in < tt > stream < / tt > * begins . * < p > If < tt > resources < / tt > contains any * duplicate entries then cudaErrorInvalidResourceHandle is returned . If * any of < tt > resources < / tt > are presently mapped for access by CUDA then * cudaErrorUnknown is returned . * < div > * < span > Note : < / span > * < p > Note that this * function may also return error codes from previous , asynchronous * launches . * < / div > * < / div > * @ param count Number of resources to map * @ param resources Resources to map for CUDA * @ param stream Stream for synchronization * @ return cudaSuccess , cudaErrorInvalidResourceHandle , cudaErrorUnknown * @ see JCuda # cudaGraphicsResourceGetMappedPointer * @ see JCuda # cudaGraphicsSubResourceGetMappedArray * @ see JCuda # cudaGraphicsUnmapResources */ public static int cudaGraphicsMapResources ( int count , cudaGraphicsResource resources [ ] , cudaStream_t stream ) { } }
return checkResult ( cudaGraphicsMapResourcesNative ( count , resources , stream ) ) ;
public class MoreCollectors { /** * A Collector into an { @ link ImmutableList } . */ public static < T > Collector < T , List < T > , List < T > > toList ( ) { } }
return Collector . of ( ArrayList :: new , List :: add , ( left , right ) -> { left . addAll ( right ) ; return left ; } , ImmutableList :: copyOf ) ;
public class AbstractExceptionAwareLogic { /** * Handle exceptions . * @ param e the thrown exception * @ param httpActionAdapter the HTTP action adapter * @ param context the web context * @ return the final HTTP result */ protected R handleException ( final Exception e , final HttpActionAdapter < R , C > httpActionAdapter , final C context ) { } }
if ( httpActionAdapter == null || context == null ) { throw runtimeException ( e ) ; } else if ( e instanceof HttpAction ) { final HttpAction action = ( HttpAction ) e ; logger . debug ( "extra HTTP action required in security: {}" , action . getCode ( ) ) ; return httpActionAdapter . adapt ( action , context ) ; } else { if ( CommonHelper . isNotBlank ( errorUrl ) ) { final HttpAction action = RedirectionActionHelper . buildRedirectUrlAction ( context , errorUrl ) ; return httpActionAdapter . adapt ( action , context ) ; } else { throw runtimeException ( e ) ; } }
public class CRCResourceManagementImpl { /** * < ! - - begin - user - doc - - > * < ! - - end - user - doc - - > * @ generated */ @ Override public Object eGet ( int featureID , boolean resolve , boolean coreType ) { } }
switch ( featureID ) { case AfplibPackage . CRC_RESOURCE_MANAGEMENT__FMT_QUAL : return getFmtQual ( ) ; case AfplibPackage . CRC_RESOURCE_MANAGEMENT__RM_VALUE : return getRMValue ( ) ; case AfplibPackage . CRC_RESOURCE_MANAGEMENT__RES_CLASS_FLG : return getResClassFlg ( ) ; } return super . eGet ( featureID , resolve , coreType ) ;
public class BrowserConfig { /** * Initializes the default fonts . Current implementation just defines the same physical names for basic * AWT logical fonts . */ protected void initDefaultFonts ( ) { } }
defaultFonts = new HashMap < String , String > ( 3 ) ; defaultFonts . put ( Font . SERIF , Font . SERIF ) ; defaultFonts . put ( Font . SANS_SERIF , Font . SANS_SERIF ) ; defaultFonts . put ( Font . MONOSPACED , Font . MONOSPACED ) ;
public class AverageBondLengthCalculator { /** * Calculate the average bond length for the bonds in a reaction . * @ param reaction the reaction to use * @ return the average bond length */ public static double calculateAverageBondLength ( IReaction reaction ) { } }
IAtomContainerSet reactants = reaction . getReactants ( ) ; double reactantAverage = 0.0 ; if ( reactants != null ) { reactantAverage = calculateAverageBondLength ( reactants ) / reactants . getAtomContainerCount ( ) ; } IAtomContainerSet products = reaction . getProducts ( ) ; double productAverage = 0.0 ; if ( products != null ) { productAverage = calculateAverageBondLength ( products ) / products . getAtomContainerCount ( ) ; } if ( productAverage == 0.0 && reactantAverage == 0.0 ) { return 1.0 ; } else { return ( productAverage + reactantAverage ) / 2.0 ; }
public class DocumentObjectMapper { /** * Setter for column value , by default converted from string value , in case * of map it is automatically converted into map using BasicDBObject . * @ param document * mongo document * @ param entityObject * searched entity . * @ param column * column field . */ static void setFieldValue ( DBObject document , Object entityObject , Attribute column , boolean isLob ) { } }
Object value = null ; if ( document != null ) { value = isLob ? ( ( DBObject ) document . get ( "metadata" ) ) . get ( ( ( AbstractAttribute ) column ) . getJPAColumnName ( ) ) : document . get ( ( ( AbstractAttribute ) column ) . getJPAColumnName ( ) ) ; } if ( value != null ) { Class javaType = column . getJavaType ( ) ; try { switch ( AttributeType . getType ( javaType ) ) { case MAP : PropertyAccessorHelper . set ( entityObject , ( Field ) column . getJavaMember ( ) , ( ( BasicDBObject ) value ) . toMap ( ) ) ; break ; case SET : List collectionValues = Arrays . asList ( ( ( BasicDBList ) value ) . toArray ( ) ) ; PropertyAccessorHelper . set ( entityObject , ( Field ) column . getJavaMember ( ) , new HashSet ( collectionValues ) ) ; break ; case LIST : PropertyAccessorHelper . set ( entityObject , ( Field ) column . getJavaMember ( ) , Arrays . asList ( ( ( BasicDBList ) value ) . toArray ( ) ) ) ; break ; case POINT : BasicDBList list = ( BasicDBList ) value ; Object xObj = list . get ( 0 ) ; Object yObj = list . get ( 1 ) ; if ( xObj != null && yObj != null ) { try { double x = Double . parseDouble ( xObj . toString ( ) ) ; double y = Double . parseDouble ( yObj . toString ( ) ) ; Point point = new Point ( x , y ) ; PropertyAccessorHelper . set ( entityObject , ( Field ) column . getJavaMember ( ) , point ) ; } catch ( NumberFormatException e ) { log . error ( "Error while reading geolocation data for column {} ; Reason - possible corrupt data, Caused by : ." , column , e ) ; throw new EntityReaderException ( "Error while reading geolocation data for column " + column + "; Reason - possible corrupt data." , e ) ; } } break ; case ENUM : EnumAccessor accessor = new EnumAccessor ( ) ; value = accessor . fromString ( javaType , value . toString ( ) ) ; PropertyAccessorHelper . set ( entityObject , ( Field ) column . getJavaMember ( ) , value ) ; break ; case PRIMITIVE : value = MongoDBUtils . populateValue ( value , value . getClass ( ) ) ; value = MongoDBUtils . getTranslatedObject ( value , value . getClass ( ) , javaType ) ; PropertyAccessorHelper . set ( entityObject , ( Field ) column . getJavaMember ( ) , value ) ; break ; } } catch ( PropertyAccessException paex ) { log . error ( "Error while setting column {} value, caused by : ." , ( ( AbstractAttribute ) column ) . getJPAColumnName ( ) , paex ) ; throw new PersistenceException ( paex ) ; } }
public class EditText { /** * Sets the Drawables ( if any ) to appear to the start of , above , to the end * of , and below the text . Use { @ code null } if you do not want a Drawable * there . The Drawables must already have had { @ link Drawable # setBounds } * called . * Calling this method will overwrite any Drawables previously set using * { @ link # setCompoundDrawables } or related methods . * @ attr ref android . R . styleable # TextView _ drawableStart * @ attr ref android . R . styleable # TextView _ drawableTop * @ attr ref android . R . styleable # TextView _ drawableEnd * @ attr ref android . R . styleable # TextView _ drawableBottom */ @ TargetApi ( Build . VERSION_CODES . JELLY_BEAN_MR1 ) public void setCompoundDrawablesRelative ( Drawable start , Drawable top , Drawable end , Drawable bottom ) { } }
if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN_MR1 ) mInputView . setCompoundDrawablesRelative ( start , top , end , bottom ) ; else mInputView . setCompoundDrawables ( start , top , end , bottom ) ;
public class Allure { /** * Syntax sugar for { @ link # step ( ThrowableContextRunnable ) } . * @ param name the name of step . * @ param runnable the step ' s body . */ public static < T > T step ( final String name , final ThrowableRunnable < T > runnable ) { } }
return step ( step -> { step . name ( name ) ; return runnable . run ( ) ; } ) ;
public class BaseValidator { /** * < ! - - begin - user - doc - - > * < ! - - end - user - doc - - > * @ generated */ public boolean validateCharset ( Charset charset , DiagnosticChain diagnostics , Map < Object , Object > context ) { } }
return true ;
public class AnnotationAwareOrderComparator { /** * This implementation checks for the { @ link Order } annotation * on various kinds of elements , in addition to the * { @ link com . freetmp . common . core . Ordered } check in the superclass . */ protected Integer findOrder ( Object obj ) { } }
// Check for regular Ordered interface Integer order = super . findOrder ( obj ) ; if ( order != null ) { return order ; } // Check for @ Order annotation on various kinds of elements if ( obj instanceof Class ) { return OrderUtils . getOrder ( ( Class ) obj ) ; } else if ( obj instanceof Method ) { Order ann = AnnotationUtils . findAnnotation ( ( Method ) obj , Order . class ) ; if ( ann != null ) { return ann . value ( ) ; } } else if ( obj instanceof AnnotatedElement ) { Order ann = AnnotationUtils . getAnnotation ( ( AnnotatedElement ) obj , Order . class ) ; if ( ann != null ) { return ann . value ( ) ; } } else if ( obj != null ) { return OrderUtils . getOrder ( obj . getClass ( ) ) ; } return null ;
public class DataFlow { /** * Run the { @ code transfer } dataflow analysis over the method or lambda which is the leaf of the * { @ code methodPath } . * < p > For caching , we make the following assumptions : - if two paths to methods are { @ code equal } , * their control flow graph is the same . - if two transfer functions are { @ code equal } , and are * run over the same control flow graph , the analysis result is the same . - for all contexts , the * analysis result is the same . */ private static < A extends AbstractValue < A > , S extends Store < S > , T extends TransferFunction < A , S > > Result < A , S , T > methodDataflow ( TreePath methodPath , Context context , T transfer ) { } }
final ProcessingEnvironment env = JavacProcessingEnvironment . instance ( context ) ; final ControlFlowGraph cfg ; try { cfg = cfgCache . getUnchecked ( CfgParams . create ( methodPath , env ) ) ; } catch ( UncheckedExecutionException e ) { throw e . getCause ( ) instanceof CompletionFailure ? ( CompletionFailure ) e . getCause ( ) : e ; } final AnalysisParams aparams = AnalysisParams . create ( transfer , cfg , env ) ; @ SuppressWarnings ( "unchecked" ) final Analysis < A , S , T > analysis = ( Analysis < A , S , T > ) analysisCache . getUnchecked ( aparams ) ; return new Result < A , S , T > ( ) { @ Override public Analysis < A , S , T > getAnalysis ( ) { return analysis ; } @ Override public ControlFlowGraph getControlFlowGraph ( ) { return cfg ; } } ;
public class Convert { /** * 转换为Short < br > * 如果给定的值为 < code > null < / code > , 或者转换失败 , 返回默认值 < br > * 转换失败不会报错 * @ param value 被转换的值 * @ param defaultValue 转换错误时的默认值 * @ return 结果 */ public static Short toShort ( Object value , Short defaultValue ) { } }
return convert ( Short . class , value , defaultValue ) ;
public class MSLocale { /** * 既知のIDかどうか 。 * < p > プロパティファイルに定義されているかで確認する 。 * @ since 0.5 * @ param id ロケールID ( 10進数 ) 。 */ public static boolean isKnownById ( int id ) { } }
final String hexId = Utils . supplyZero ( Integer . toHexString ( id ) . toUpperCase ( ) , 4 ) ; String code = messageResolver . getMessage ( String . format ( "locale.%s.code" , hexId ) ) ; return Utils . isNotEmpty ( code ) ;
public class OMVRBTree { /** * Return SimpleImmutableEntry for entry , or null if null */ static < K , V > Map . Entry < K , V > exportEntry ( final OMVRBTreeEntryPosition < K , V > omvrbTreeEntryPosition ) { } }
return omvrbTreeEntryPosition == null ? null : new OSimpleImmutableEntry < K , V > ( omvrbTreeEntryPosition . entry ) ;
public class FrameworkProjectMgr { /** * @ return an existing Project object and returns it * @ param name The name of the project */ public FrameworkProject getFrameworkProject ( final String name ) { } }
FrameworkProject frameworkProject = loadChild ( name ) ; if ( null != frameworkProject ) { return frameworkProject ; } throw new NoSuchResourceException ( "Project does not exist: " + name , this ) ;
public class BufferedSeekInputStream { /** * Positions the underlying stream at the given position , then refills * the buffer . * @ param p the position to set * @ throws IOException if an IO error occurs */ private void positionDirect ( long p ) throws IOException { } }
long newBlockStart = p / buffer . length * buffer . length ; input . position ( newBlockStart ) ; buffer ( ) ; offset = ( int ) ( p % buffer . length ) ;
public class Context { /** * The method must NOT be public or protected */ SecurityController getSecurityController ( ) { } }
SecurityController global = SecurityController . global ( ) ; if ( global != null ) { return global ; } return securityController ;
public class SparseWeightedGraph { /** * { @ inheritDoc } */ public double strength ( int vertex ) { } }
SparseWeightedEdgeSet e = getEdgeSet ( vertex ) ; return ( e == null ) ? 0 : e . sum ( ) ;
public class AWSOpsWorksClient { /** * Describes the available AWS OpsWorks Stacks agent versions . You must specify a stack ID or a configuration * manager . < code > DescribeAgentVersions < / code > returns a list of available agent versions for the specified stack or * configuration manager . * @ param describeAgentVersionsRequest * @ return Result of the DescribeAgentVersions operation returned by the service . * @ throws ValidationException * Indicates that a request was not valid . * @ throws ResourceNotFoundException * Indicates that a resource was not found . * @ sample AWSOpsWorks . DescribeAgentVersions * @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / opsworks - 2013-02-18 / DescribeAgentVersions " target = " _ top " > AWS * API Documentation < / a > */ @ Override public DescribeAgentVersionsResult describeAgentVersions ( DescribeAgentVersionsRequest request ) { } }
request = beforeClientExecution ( request ) ; return executeDescribeAgentVersions ( request ) ;
public class AbstractTagger { /** * 序列标注方法 , 输入为文件 * @ param input 输入文件 UTF8编码 * @ return 标注结果 */ public String tagFile ( String input , String sep ) { } }
StringBuilder res = new StringBuilder ( ) ; try { InputStreamReader read = new InputStreamReader ( new FileInputStream ( input ) , "utf-8" ) ; BufferedReader lbin = new BufferedReader ( read ) ; String str = lbin . readLine ( ) ; while ( str != null ) { String s = ( String ) tag ( str ) ; res . append ( s ) ; res . append ( "\n" ) ; str = lbin . readLine ( ) ; } lbin . close ( ) ; return res . toString ( ) ; } catch ( IOException e ) { System . out . println ( "读输入文件错误" ) ; e . printStackTrace ( ) ; } return "" ;
public class GroupService { /** * Create sub groups in group with { @ code groupId } * @ param config group hierarchy config * @ param groupId group id */ private void createSubgroups ( GroupHierarchyConfig config , String groupId ) { } }
config . getSubitems ( ) . forEach ( cfg -> { if ( cfg instanceof GroupHierarchyConfig ) { GroupMetadata curGroup = findGroup ( ( GroupHierarchyConfig ) cfg , groupId ) ; String subGroupId ; if ( curGroup != null ) { subGroupId = curGroup . getId ( ) ; } else { subGroupId = create ( converter . createGroupConfig ( ( GroupHierarchyConfig ) cfg , groupId ) ) . getResult ( ) . as ( GroupByIdRef . class ) . getId ( ) ; } createSubgroups ( ( GroupHierarchyConfig ) cfg , subGroupId ) ; } else if ( cfg instanceof CreateServerConfig ) { ( ( CreateServerConfig ) cfg ) . group ( Group . refById ( groupId ) ) ; } else { ( ( CompositeServerConfig ) cfg ) . getServer ( ) . group ( Group . refById ( groupId ) ) ; } } ) ;
public class PowerIteration { /** * Calculate and normalize y = ( A - pI ) x . * Returns the largest element of y in magnitude . */ private static double ax ( Matrix A , double [ ] x , double [ ] y , double p ) { } }
A . ax ( x , y ) ; if ( p != 0.0 ) { for ( int i = 0 ; i < y . length ; i ++ ) { y [ i ] -= p * x [ i ] ; } } double lambda = y [ 0 ] ; for ( int i = 1 ; i < y . length ; i ++ ) { if ( Math . abs ( y [ i ] ) > Math . abs ( lambda ) ) { lambda = y [ i ] ; } } for ( int i = 0 ; i < y . length ; i ++ ) { x [ i ] = y [ i ] / lambda ; } return lambda ;
public class NativeAppCallAttachmentStore { /** * Removes any temporary files associated with a particular native app call . * @ param context the Context the call is being made from * @ param callId the unique ID of the call */ public void cleanupAttachmentsForCall ( Context context , UUID callId ) { } }
File dir = getAttachmentsDirectoryForCall ( callId , false ) ; Utility . deleteDirectory ( dir ) ;
public class LocalDateTime { /** * Returns a copy of this { @ code LocalDateTime } with the specified number of years added . * This method adds the specified amount to the years field in three steps : * < ol > * < li > Add the input years to the year field < / li > * < li > Check if the resulting date would be invalid < / li > * < li > Adjust the day - of - month to the last valid day if necessary < / li > * < / ol > * For example , 2008-02-29 ( leap year ) plus one year would result in the * invalid date 2009-02-29 ( standard year ) . Instead of returning an invalid * result , the last valid day of the month , 2009-02-28 , is selected instead . * This instance is immutable and unaffected by this method call . * @ param years the years to add , may be negative * @ return a { @ code LocalDateTime } based on this date - time with the years added , not null * @ throws DateTimeException if the result exceeds the supported date range */ public LocalDateTime plusYears ( long years ) { } }
LocalDate newDate = date . plusYears ( years ) ; return with ( newDate , time ) ;
public class AWSStorageGatewayClient { /** * Lists virtual tapes in your virtual tape library ( VTL ) and your virtual tape shelf ( VTS ) . You specify the tapes * to list by specifying one or more tape Amazon Resource Names ( ARNs ) . If you don ' t specify a tape ARN , the * operation lists all virtual tapes in both your VTL and VTS . * This operation supports pagination . By default , the operation returns a maximum of up to 100 tapes . You can * optionally specify the < code > Limit < / code > parameter in the body to limit the number of tapes in the response . If * the number of tapes returned in the response is truncated , the response includes a < code > Marker < / code > element * that you can use in your subsequent request to retrieve the next set of tapes . This operation is only supported * in the tape gateway type . * @ param listTapesRequest * A JSON object that contains one or more of the following fields : < / p > * < ul > * < li > * < a > ListTapesInput $ Limit < / a > * < / li > * < li > * < a > ListTapesInput $ Marker < / a > * < / li > * < li > * < a > ListTapesInput $ TapeARNs < / a > * < / li > * @ return Result of the ListTapes operation returned by the service . * @ throws InvalidGatewayRequestException * An exception occurred because an invalid gateway request was issued to the service . For more information , * see the error and message fields . * @ throws InternalServerErrorException * An internal server error has occurred during the request . For more information , see the error and message * fields . * @ sample AWSStorageGateway . ListTapes * @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / storagegateway - 2013-06-30 / ListTapes " target = " _ top " > AWS API * Documentation < / a > */ @ Override public ListTapesResult listTapes ( ListTapesRequest request ) { } }
request = beforeClientExecution ( request ) ; return executeListTapes ( request ) ;
public class RiakUserMetadata { /** * Get the user metadata entries * This method allows access to the user metadata entries directly as raw bytes . The * { @ code Set } is an unmodifiable view of all the entries . * @ return an unmodifiable view of all the entries . */ public Set < Map . Entry < BinaryValue , BinaryValue > > getUserMetadata ( ) { } }
return Collections . unmodifiableSet ( meta . entrySet ( ) ) ;
public class UploadListElementMarshaller { /** * Marshall the given parameter object . */ public void marshall ( UploadListElement uploadListElement , ProtocolMarshaller protocolMarshaller ) { } }
if ( uploadListElement == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( uploadListElement . getMultipartUploadId ( ) , MULTIPARTUPLOADID_BINDING ) ; protocolMarshaller . marshall ( uploadListElement . getVaultARN ( ) , VAULTARN_BINDING ) ; protocolMarshaller . marshall ( uploadListElement . getArchiveDescription ( ) , ARCHIVEDESCRIPTION_BINDING ) ; protocolMarshaller . marshall ( uploadListElement . getPartSizeInBytes ( ) , PARTSIZEINBYTES_BINDING ) ; protocolMarshaller . marshall ( uploadListElement . getCreationDate ( ) , CREATIONDATE_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; }
public class BloomFilter { /** * Applies the MurmurHash3 ( x86_32 ) algorithm to the given data . * See this < a href = " https : / / github . com / aappleby / smhasher / blob / master / src / MurmurHash3 . cpp " > C + + code for the original . < / a > */ public static int murmurHash3 ( byte [ ] data , long nTweak , int hashNum , byte [ ] object ) { } }
int h1 = ( int ) ( hashNum * 0xFBA4C795L + nTweak ) ; final int c1 = 0xcc9e2d51 ; final int c2 = 0x1b873593 ; int numBlocks = ( object . length / 4 ) * 4 ; // body for ( int i = 0 ; i < numBlocks ; i += 4 ) { int k1 = ( object [ i ] & 0xFF ) | ( ( object [ i + 1 ] & 0xFF ) << 8 ) | ( ( object [ i + 2 ] & 0xFF ) << 16 ) | ( ( object [ i + 3 ] & 0xFF ) << 24 ) ; k1 *= c1 ; k1 = rotateLeft32 ( k1 , 15 ) ; k1 *= c2 ; h1 ^= k1 ; h1 = rotateLeft32 ( h1 , 13 ) ; h1 = h1 * 5 + 0xe6546b64 ; } int k1 = 0 ; switch ( object . length & 3 ) { case 3 : k1 ^= ( object [ numBlocks + 2 ] & 0xff ) << 16 ; // Fall through . case 2 : k1 ^= ( object [ numBlocks + 1 ] & 0xff ) << 8 ; // Fall through . case 1 : k1 ^= ( object [ numBlocks ] & 0xff ) ; k1 *= c1 ; k1 = rotateLeft32 ( k1 , 15 ) ; k1 *= c2 ; h1 ^= k1 ; // Fall through . default : // Do nothing . break ; } // finalization h1 ^= object . length ; h1 ^= h1 >>> 16 ; h1 *= 0x85ebca6b ; h1 ^= h1 >>> 13 ; h1 *= 0xc2b2ae35 ; h1 ^= h1 >>> 16 ; return ( int ) ( ( h1 & 0xFFFFFFFFL ) % ( data . length * 8 ) ) ;
public class AllCallReply { /** * Note : this can be used as an accurate check whether the all call reply * has been received correctly without knowing the interrogator in advance . * @ return true if the interrogator ID is conformant with Annex 10 V4 */ public boolean hasValidInterrogatorID ( ) { } }
assert ( interrogator . length == 3 ) ; // 3.1.2.3.3.2 // the first 17 bits have to be zero if ( interrogator [ 0 ] != 0 || interrogator [ 1 ] != 0 || ( interrogator [ 2 ] & 0x80 ) != 0 ) return false ; int cl = ( interrogator [ 2 ] >> 4 ) & 0x7 ; // 3.1.2.5.2.1.3 // code label is only defined for 0-4 if ( cl > 4 ) return false ; // Note : seems to be used by ACAS // int ii = interrogator [ 2 ] & 0xF ; // / / 3.1.2.5.2.1.2.4 // / / surveillance identifier of 0 shall never be used // if ( cl > 0 & & ii = = 0 ) return false ; return true ;
public class NetworkInterfaceTapConfigurationsInner { /** * Creates or updates a Tap configuration in the specified NetworkInterface . * @ param resourceGroupName The name of the resource group . * @ param networkInterfaceName The name of the network interface . * @ param tapConfigurationName The name of the tap configuration . * @ param tapConfigurationParameters Parameters supplied to the create or update tap configuration operation . * @ throws IllegalArgumentException thrown if parameters fail the validation * @ return the observable for the request */ public Observable < ServiceResponse < NetworkInterfaceTapConfigurationInner > > createOrUpdateWithServiceResponseAsync ( String resourceGroupName , String networkInterfaceName , String tapConfigurationName , NetworkInterfaceTapConfigurationInner tapConfigurationParameters ) { } }
if ( resourceGroupName == null ) { throw new IllegalArgumentException ( "Parameter resourceGroupName is required and cannot be null." ) ; } if ( networkInterfaceName == null ) { throw new IllegalArgumentException ( "Parameter networkInterfaceName is required and cannot be null." ) ; } if ( tapConfigurationName == null ) { throw new IllegalArgumentException ( "Parameter tapConfigurationName is required and cannot be null." ) ; } if ( this . client . subscriptionId ( ) == null ) { throw new IllegalArgumentException ( "Parameter this.client.subscriptionId() is required and cannot be null." ) ; } if ( tapConfigurationParameters == null ) { throw new IllegalArgumentException ( "Parameter tapConfigurationParameters is required and cannot be null." ) ; } Validator . validate ( tapConfigurationParameters ) ; final String apiVersion = "2018-08-01" ; Observable < Response < ResponseBody > > observable = service . createOrUpdate ( resourceGroupName , networkInterfaceName , tapConfigurationName , this . client . subscriptionId ( ) , tapConfigurationParameters , apiVersion , this . client . acceptLanguage ( ) , this . client . userAgent ( ) ) ; return client . getAzureClient ( ) . getPutOrPatchResultAsync ( observable , new TypeToken < NetworkInterfaceTapConfigurationInner > ( ) { } . getType ( ) ) ;
public class DashboardResources { /** * Returns a dashboard by its ID . * @ param req The HTTP request . * @ param dashboardId The dashboard ID to retrieve . * @ return The corresponding dashboard . * @ throws WebApplicationException If no corresponding dashboard exists . */ @ GET @ Produces ( MediaType . APPLICATION_JSON ) @ Path ( "/{dashboardId}" ) @ Description ( "Returns a dashboard by its ID." ) public DashboardDto getDashboardByID ( @ Context HttpServletRequest req , @ PathParam ( "dashboardId" ) BigInteger dashboardId ) { } }
if ( dashboardId == null || dashboardId . compareTo ( BigInteger . ZERO ) < 1 ) { throw new WebApplicationException ( "Dashboard Id cannot be null and must be a positive non-zero number." , Status . BAD_REQUEST ) ; } Dashboard dashboard = dService . findDashboardByPrimaryKey ( dashboardId ) ; if ( dashboard != null && ! dashboard . isShared ( ) ) { validateAndGetOwner ( req , null ) ; validateResourceAuthorization ( req , dashboard . getOwner ( ) , getRemoteUser ( req ) ) ; } if ( dashboard != null ) { return DashboardDto . transformToDto ( dashboard ) ; } throw new WebApplicationException ( Response . Status . NOT_FOUND . getReasonPhrase ( ) , Response . Status . NOT_FOUND ) ;
public class SlotPortsView { /** * todo : cause we don ' t support cgroup yet , now vcores is useless */ private int getSlotCount ( int memory , int vcores ) { } }
int cpuports = ( int ) Math . ceil ( vcores / JOYConstants . JSTORM_VCORE_WEIGHT ) ; int memoryports = ( int ) Math . floor ( memory / JOYConstants . JSTORM_MEMORY_WEIGHT ) ; // return cpuports > memoryports ? memoryports : cpuports ; return memoryports ;
public class HalParser { /** * Parse embedded items of a given link - relation type not as HalRepresentation , but as a sub - type of * HalRepresentation , so extra attributes of the embedded items can be accessed . * @ param type the Java class used to map JSON to . * @ param typeInfo type information of the embedded items . * @ param < T > The type used to parse the HAL document * @ return T * @ throws IOException if a low - level I / O problem ( unexpected end - of - input , network error ) occurs . * @ throws JsonParseException if the json document can not be parsed by Jackson ' s ObjectMapper * @ throws JsonMappingException if the input JSON structure can not be mapped to the specified HalRepresentation type * @ since 0.1.0 */ public < T extends HalRepresentation > T as ( final Class < T > type , final List < EmbeddedTypeInfo > typeInfo ) throws IOException { } }
final JsonNode jsonNode = objectMapper . readTree ( json ) ; final T halRepresentation = objectMapper . convertValue ( jsonNode , type ) ; resolveEmbeddedTypeInfo ( typeInfo , jsonNode , halRepresentation ) ; return halRepresentation ;
public class AutoAckErrorCommand { /** * one day in milliseconds */ @ Override public Date getScheduleTime ( ) { } }
if ( nextScheduleTimeAdd < 0 ) { return null ; } long current = System . currentTimeMillis ( ) ; Date nextSchedule = new Date ( current + nextScheduleTimeAdd ) ; logger . debug ( "Next schedule for job {} is set to {}" , this . getClass ( ) . getSimpleName ( ) , nextSchedule ) ; return nextSchedule ;
public class SystemEventTypeMappings { /** * Get Java model type for the given event type . * @ param eventType the event type . * @ return the Java model type if mapping exists , null otherwise . */ @ Beta public static Type getMapping ( final String eventType ) { } }
if ( ! containsMappingFor ( eventType ) ) { return null ; } else { return systemEventMappings . get ( canonicalizeEventType ( eventType ) ) ; }
public class Configuration { /** * Creates a new MetricRegistryInstance . * @ param api The api with which to register configuration - specific endpoints . * @ return A metric registry instance , initialized based on this configuration . * @ throws RuntimeException if anything goes wrong during registration , for example the name is already in use . */ public < T extends MetricRegistryInstance > T create ( MetricRegistryConstructor < T > constructor , EndpointRegistration api ) { } }
return create ( constructor , ( ) -> DateTime . now ( DateTimeZone . UTC ) , api ) ;
public class StartupVerticle { /** * { @ inheritDoc } */ @ Override public void start ( Future < Void > startedResult ) throws Exception { } }
jerseyServer . createServer ( ) . then ( server -> { startedResult . complete ( ) ; return null ; } ) . otherwise ( t -> { startedResult . fail ( t ) ; return null ; } ) ;
public class GVRAccessibilityTalkBack { /** * Initialize { @ code TextToSpeech } and treats unsupported languages exceptions by setting a default language . */ private void init ( ) { } }
mTextToSpeech = new TextToSpeech ( mContext , new OnInitListener ( ) { @ Override public void onInit ( int status ) { if ( status == TextToSpeech . SUCCESS ) { checkCurrentLocale ( ) ; int result = mTextToSpeech . setLanguage ( mLocale ) ; if ( result == TextToSpeech . LANG_MISSING_DATA || result == TextToSpeech . LANG_NOT_SUPPORTED ) { mLocale = getDefaultLocale ( ) ; init ( ) ; Log . i ( TAG , "set default locale (English US) for gvrAccessibility" ) ; } } } } ) ;
public class Supplier { /** * The predefined Supplier selects values using the given { @ link com . hazelcast . mapreduce . KeyPredicate } * and does not perform any kind of data transformation . Input value types need to match the * aggregations expected value type to make this Supplier work . * @ param < KeyIn > the input key type * @ param < ValueIn > the input value type * @ param < ValueOut > the supplied value type * @ return selected values from the underlying data structure as stored */ public static < KeyIn , ValueIn , ValueOut > Supplier < KeyIn , ValueIn , ValueOut > fromKeyPredicate ( KeyPredicate < KeyIn > keyPredicate ) { } }
return new KeyPredicateSupplier < KeyIn , ValueIn , ValueOut > ( keyPredicate ) ;
public class DividerAdapterBuilder { /** * Sets the divider that appears before the wrapped adapters items . */ @ NonNull public DividerAdapterBuilder leadingView ( @ NonNull ViewFactory viewFactory ) { } }
mLeadingItem = new Item ( checkNotNull ( viewFactory , "viewFactory" ) , false ) ; return this ;
public class UserBS { /** * Verificar se usuário é de uma determinada instituição . * @ param user * Usuário para verificação . * @ param company * Instituição para verificação . * @ return CompanyUser Instituição que pertence a determinado usuário . */ public CompanyUser retrieveCompanyUser ( User user , Company company ) { } }
Criteria criteria = this . dao . newCriteria ( CompanyUser . class ) ; criteria . add ( Restrictions . eq ( "company" , company ) ) ; criteria . add ( Restrictions . eq ( "user" , user ) ) ; return ( CompanyUser ) criteria . uniqueResult ( ) ;
public class Execution { /** * Calculates the preferred locations based on the location preference constraint . * @ param locationPreferenceConstraint constraint for the location preference * @ return Future containing the collection of preferred locations . This might not be completed if not all inputs * have been a resource assigned . */ @ VisibleForTesting public CompletableFuture < Collection < TaskManagerLocation > > calculatePreferredLocations ( LocationPreferenceConstraint locationPreferenceConstraint ) { } }
final Collection < CompletableFuture < TaskManagerLocation > > preferredLocationFutures = getVertex ( ) . getPreferredLocations ( ) ; final CompletableFuture < Collection < TaskManagerLocation > > preferredLocationsFuture ; switch ( locationPreferenceConstraint ) { case ALL : preferredLocationsFuture = FutureUtils . combineAll ( preferredLocationFutures ) ; break ; case ANY : final ArrayList < TaskManagerLocation > completedTaskManagerLocations = new ArrayList < > ( preferredLocationFutures . size ( ) ) ; for ( CompletableFuture < TaskManagerLocation > preferredLocationFuture : preferredLocationFutures ) { if ( preferredLocationFuture . isDone ( ) && ! preferredLocationFuture . isCompletedExceptionally ( ) ) { final TaskManagerLocation taskManagerLocation = preferredLocationFuture . getNow ( null ) ; if ( taskManagerLocation == null ) { throw new FlinkRuntimeException ( "TaskManagerLocationFuture was completed with null. This indicates a programming bug." ) ; } completedTaskManagerLocations . add ( taskManagerLocation ) ; } } preferredLocationsFuture = CompletableFuture . completedFuture ( completedTaskManagerLocations ) ; break ; default : throw new RuntimeException ( "Unknown LocationPreferenceConstraint " + locationPreferenceConstraint + '.' ) ; } return preferredLocationsFuture ;
public class PngOptimizer { private List < byte [ ] > copyScanlines ( List < byte [ ] > original ) { } }
final List < byte [ ] > copy = new ArrayList < > ( original . size ( ) ) ; for ( byte [ ] scanline : original ) { copy . add ( scanline . clone ( ) ) ; } return copy ;
public class GlobusGSSContextImpl { protected void setGssMode ( Object value ) throws GSSException { } }
if ( ! ( value instanceof Integer ) ) { throw new GlobusGSSException ( GSSException . FAILURE , GlobusGSSException . BAD_OPTION_TYPE , "badType" , new Object [ ] { "GSS mode" , Integer . class } ) ; } Integer v = ( Integer ) value ; if ( v == GSIConstants . MODE_GSI || v == GSIConstants . MODE_SSL ) { this . gssMode = v ; } else { throw new GlobusGSSException ( GSSException . FAILURE , GlobusGSSException . BAD_OPTION , "badGssMode" ) ; }
public class CSSIdentifierSerializer { /** * See https : / / drafts . csswg . org / cssom / # escape - a - character - as - code - point . */ private boolean shouldEscapeAsCodePoint ( int codeUnit , int index , int firstCodeUnit ) { } }
// If the character is in the range [ \ 1 - \ 1F ] ( U + 0001 to U + 001F ) or is U + 007F , [ . . . ] if ( isInRange ( codeUnit , 0x0001 , 0x001F ) || codeUnit == 0x007F ) { return true ; } else if ( index == 0 && isInRange ( codeUnit , 0x0030 , 0x0039 ) ) { // If the character is the first character and is in the range [ 0-9 ] ( U + 0030 to U + 0039 ) , [ . . . ] return true ; } else { // If the character is the second character and is in the range [ 0-9 ] ( U + 0030 to U + 0039 ) and the first // character is a ' - ' ( U + 002D ) , [ . . . ] return index == 1 && isInRange ( codeUnit , 0x0030 , 0x0039 ) && firstCodeUnit == 0x002D ; }
public class JMeterPluginsUtils { /** * Builds full URL from wiki page name unless a URL is already passed in . * @ param helpPage wiki page name ( not full URL ) or URL to external wiki * @ return full URL to helpPage */ public static String buildHelpPageUrl ( String helpPage ) { } }
try { if ( helpPage . matches ( "[hH][tT][tT][pP][sS]?://.*" ) ) { log . debug ( "Help page URL found, skipping building link to " + WIKI_BASE ) ; return helpPage ; } } catch ( PatternSyntaxException ex ) { log . warn ( "Invalid regex" , ex ) ; } if ( helpPage . endsWith ( "Gui" ) ) { helpPage = helpPage . substring ( 0 , helpPage . length ( ) - 3 ) ; } return WIKI_BASE + helpPage + "/?utm_source=jmeter&utm_medium=helplink&utm_campaign=" + helpPage ;
public class UTF8Reader { /** * / * Internal methods */ private void reportInvalidInitial ( int mask , int offset ) throws IOException { } }
// input ( byte ) ptr has been advanced by one , by now : int bytePos = _byteCount + _inputPtr - 1 ; int charPos = _charCount + offset + 1 ; throw new CharConversionException ( "Invalid UTF-8 start byte 0x" + Integer . toHexString ( mask ) + " (at char #" + charPos + ", byte #" + bytePos + ")" ) ;
public class FileUtils { /** * Get the file size in a human - readable string . * @ param size * @ return * @ author paulburke */ public static String getReadableFileSize ( int size ) { } }
final int BYTES_IN_KILOBYTES = 1024 ; final DecimalFormat dec = new DecimalFormat ( "###.#" ) ; final String KILOBYTES = " KB" ; final String MEGABYTES = " MB" ; final String GIGABYTES = " GB" ; float fileSize = 0 ; String suffix = KILOBYTES ; if ( size > BYTES_IN_KILOBYTES ) { fileSize = size / BYTES_IN_KILOBYTES ; if ( fileSize > BYTES_IN_KILOBYTES ) { fileSize = fileSize / BYTES_IN_KILOBYTES ; if ( fileSize > BYTES_IN_KILOBYTES ) { fileSize = fileSize / BYTES_IN_KILOBYTES ; suffix = GIGABYTES ; } else { suffix = MEGABYTES ; } } } return String . valueOf ( dec . format ( fileSize ) + suffix ) ;
public class CnvTfsEnum { /** * < p > Convert from string . < / p > * @ param pAddParam additional params , e . g . IRequestData * to fill owner itsVersion . * @ param pStrVal name * @ return Enum value * @ throws Exception - an exception */ @ Override public final E fromString ( final Map < String , Object > pAddParam , final String pStrVal ) throws Exception { } }
if ( pStrVal == null || "" . equals ( pStrVal ) ) { return null ; } return Enum . valueOf ( this . enumClass , pStrVal ) ;
public class CodeModelUtils { /** * Returns a property file ( created if necessary ) . * @ param thePackage * package to create property file * @ param name * property file name . * @ return Property file . */ public static JPropertyFile getOrCreatePropertyFile ( JPackage thePackage , String name ) { } }
JPropertyFile propertyFile = null ; for ( Iterator < JResourceFile > iterator = thePackage . propertyFiles ( ) ; iterator . hasNext ( ) && ( null == propertyFile ) ; ) { final JResourceFile resourceFile = ( JResourceFile ) iterator . next ( ) ; if ( resourceFile instanceof JPropertyFile && name . equals ( resourceFile . name ( ) ) ) { propertyFile = ( JPropertyFile ) resourceFile ; } } if ( null == propertyFile ) { propertyFile = new JPropertyFile ( name ) ; thePackage . addResourceFile ( propertyFile ) ; } return propertyFile ;
public class ServletHelper { /** * Safe version of < code > ServletRequest . setAttribute ( String , Object ) < / code > to * work around an error in certain Tomcat versions . * < pre > * java . lang . NullPointerException * 1 . : org . apache . catalina . connector . Request . notifyAttributeAssigned ( Request . java : 1493) * 2 . : org . apache . catalina . connector . Request . setAttribute ( Request . java : 1483) * 3 . : org . apache . catalina . connector . RequestFacade . setAttribute ( RequestFacade . java : 539) * < / pre > * @ param aRequest * Servlet request . May not be < code > null < / code > . * @ param sAttrName * Attribute name . May not be < code > null < / code > . * @ param aAttrValue * Attribute value . May be < code > null < / code > . */ public static void setRequestAttribute ( @ Nonnull final ServletRequest aRequest , @ Nonnull final String sAttrName , @ Nullable final Object aAttrValue ) { } }
try { aRequest . setAttribute ( sAttrName , aAttrValue ) ; } catch ( final Exception ex ) { // Happens in certain Tomcat versions ( e . g . 7.0.42 with JDK 8 ) : if ( isLogExceptions ( ) ) if ( LOGGER . isWarnEnabled ( ) ) LOGGER . warn ( "[ServletHelper] Failed to set attribute '" + sAttrName + "' in HTTP request" , ex ) ; }
public class ProcedureCompiler { /** * get the short name of the class ( no package ) * @ param className fully qualified ( or not ) class name * @ return short name of the class ( no package ) */ public static String deriveShortProcedureName ( String className ) { } }
if ( className == null || className . trim ( ) . isEmpty ( ) ) { return null ; } String [ ] parts = className . split ( "\\." ) ; String shortName = parts [ parts . length - 1 ] ; return shortName ;
public class NonBlockingBufferedReader { /** * Tells whether this stream is ready to be read . A buffered character stream * is ready if the buffer is not empty , or if the underlying character stream * is ready . * @ return < code > true < / code > if the reader is ready * @ exception IOException * If an I / O error occurs */ @ Override public boolean ready ( ) throws IOException { } }
_ensureOpen ( ) ; /* * If newline needs to be skipped and the next char to be read is a newline * character , then just skip it right away . */ if ( m_bSkipLF ) { /* * Note that in . ready ( ) will return true if and only if the next read on * the stream will not block . */ if ( m_nNextCharIndex >= m_nChars && m_aReader . ready ( ) ) _fill ( ) ; if ( m_nNextCharIndex < m_nChars ) { if ( m_aBuf [ m_nNextCharIndex ] == '\n' ) m_nNextCharIndex ++ ; m_bSkipLF = false ; } } return m_nNextCharIndex < m_nChars || m_aReader . ready ( ) ;
public class CalligraphyFactory { /** * Handle the created view * @ param view nullable . * @ param context shouldn ' t be null . * @ param attrs shouldn ' t be null . * @ return null if null is passed in . */ public View onViewCreated ( View view , Context context , AttributeSet attrs ) { } }
if ( view != null && view . getTag ( R . id . calligraphy_tag_id ) != Boolean . TRUE ) { onViewCreatedInternal ( view , context , attrs ) ; view . setTag ( R . id . calligraphy_tag_id , Boolean . TRUE ) ; } return view ;
public class IncludeDescriptorsProcessor { /** * Replaces special include tags found in a descriptor document with the document tree of descriptors specified in * these include tags . If the include tag specifies a XPath query expression ( through the select attribute ) , only * the elements returned by the query will be included . * @ throws org . craftercms . core . exception . ItemProcessingException if there was an error while trying to perform an * include */ @ Override public Item process ( Context context , CachingOptions cachingOptions , Item item ) throws ItemProcessingException { } }
if ( item . getDescriptorDom ( ) != null ) { includeDescriptors ( context , cachingOptions , item ) ; } return item ;
public class DocumentObjectMapper { /** * Extract entity field . * @ param entity * the entity * @ param dbObj * the db obj * @ param column * the column * @ throws PropertyAccessException * the property access exception */ static void extractFieldValue ( Object entity , DBObject dbObj , Attribute column ) throws PropertyAccessException { } }
try { Object valueObject = PropertyAccessorHelper . getObject ( entity , ( Field ) column . getJavaMember ( ) ) ; if ( valueObject != null ) { Class javaType = column . getJavaType ( ) ; switch ( AttributeType . getType ( javaType ) ) { case MAP : Map mapObj = ( Map ) valueObject ; // BasicDBObjectBuilder builder = // BasicDBObjectBuilder . start ( mapObj ) ; BasicDBObjectBuilder b = new BasicDBObjectBuilder ( ) ; Iterator i = mapObj . entrySet ( ) . iterator ( ) ; while ( i . hasNext ( ) ) { Map . Entry entry = ( Map . Entry ) i . next ( ) ; b . add ( entry . getKey ( ) . toString ( ) , MongoDBUtils . populateValue ( entry . getValue ( ) , entry . getValue ( ) . getClass ( ) ) ) ; } dbObj . put ( ( ( AbstractAttribute ) column ) . getJPAColumnName ( ) , b . get ( ) ) ; break ; case SET : case LIST : Collection collection = ( Collection ) valueObject ; BasicDBList basicDBList = new BasicDBList ( ) ; for ( Object o : collection ) { basicDBList . add ( o ) ; } dbObj . put ( ( ( AbstractAttribute ) column ) . getJPAColumnName ( ) , basicDBList ) ; break ; case POINT : Point p = ( Point ) valueObject ; double [ ] coordinate = new double [ ] { p . getX ( ) , p . getY ( ) } ; dbObj . put ( ( ( AbstractAttribute ) column ) . getJPAColumnName ( ) , coordinate ) ; break ; case ENUM : case PRIMITIVE : dbObj . put ( ( ( AbstractAttribute ) column ) . getJPAColumnName ( ) , MongoDBUtils . populateValue ( valueObject , javaType ) ) ; break ; } } } catch ( PropertyAccessException paex ) { log . error ( "Error while getting column {} value, caused by : ." , ( ( AbstractAttribute ) column ) . getJPAColumnName ( ) , paex ) ; throw new PersistenceException ( paex ) ; }
public class C10NConfigBase { /** * < p > Create a custom implementation binding for the given c10n interface * < p > There are two basic usages : * < pre > < code > * bind ( Messages . class ) . to ( JapaneseMessagesImpl . class , Locale . JAPANESE ) ; * < / code > < / pre > * which will use the < code > JapaneseMessagesImpl . class < / code > when locale is * set to < code > Locale . JAPANESE < / code > * < p > The second usage is : * < pre > < code > * bind ( Messages . class ) . to ( FallbackMessagesImpl . class ) ; * < / code > < / pre > * which will use the < code > FallbackMessagesImpl . class < / code > when no other * implementation class was matched for the current locale . * @ param c10nInterface C10N interface to create an implementation binding for ( not - null ) * @ param < T > C10N interface type * @ return implementation binding DSL object */ protected < T > C10NImplementationBinder < T > bind ( Class < T > c10nInterface ) { } }
C10NImplementationBinder < T > binder = new C10NImplementationBinder < T > ( ) ; binders . put ( c10nInterface , binder ) ; return binder ;
public class B2BUAHelper { /** * Modify Messages with new headers and header attributes * Moved from CallManager and Call * The method deals with custom and standard headers , such as R - URI , Route etc * TODO : refactor / rename / handle more specific headers * @ param sipFactory SipFactory * @ param message * @ param headers */ public static void addHeadersToMessage ( SipServletRequest message , Map < String , ArrayList < String > > headers , SipFactory sipFactory ) { } }
if ( headers != null && sipFactory != null ) { for ( Map . Entry < String , ArrayList < String > > entry : headers . entrySet ( ) ) { // check if header exists String headerName = entry . getKey ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "headerName=" + headerName + " headerVal=" + message . getHeader ( headerName ) ) ; } if ( headerName . equalsIgnoreCase ( "Request-URI" ) ) { // handle Request - URI javax . servlet . sip . URI reqURI = message . getRequestURI ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "ReqURI=" + reqURI . toString ( ) + " msgReqURI=" + message . getRequestURI ( ) ) ; } for ( String keyValPair : entry . getValue ( ) ) { String parName = "" ; String parVal = "" ; int equalsPos = keyValPair . indexOf ( "=" ) ; parName = keyValPair . substring ( 0 , equalsPos ) ; parVal = keyValPair . substring ( equalsPos + 1 ) ; reqURI . setParameter ( parName , parVal ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "ReqURI pars =" + parName + "=" + parVal + " equalsPos=" + equalsPos + " keyValPair=" + keyValPair ) ; } } message . setRequestURI ( reqURI ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "ReqURI=" + reqURI . toString ( ) + " msgReqURI=" + message . getRequestURI ( ) ) ; } } else if ( headerName . equalsIgnoreCase ( "Route" ) ) { // handle Route String headerVal = message . getHeader ( headerName ) ; // TODO : do we want to add arbitrary parameters ? if ( logger . isDebugEnabled ( ) ) { logger . debug ( "ROUTE: " + headerName + "=" + headerVal ) ; } // check how many pairs of host + port for ( String keyValPair : entry . getValue ( ) ) { String parName = "" ; String parVal = "" ; int equalsPos = keyValPair . indexOf ( "=" ) ; if ( equalsPos > 0 ) { parName = keyValPair . substring ( 0 , equalsPos ) ; } parVal = keyValPair . substring ( equalsPos + 1 ) ; if ( parName . isEmpty ( ) || parName . equalsIgnoreCase ( "host_name" ) ) { try { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "adding ROUTE parVal =" + parVal ) ; } final SipURI uri = sipFactory . createSipURI ( null , parVal ) ; message . pushRoute ( ( SipURI ) uri ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "added ROUTE parVal =" + uri . toString ( ) ) ; } } catch ( Exception e ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "error adding ROUTE uri =" + parVal ) ; } } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "ROUTE pars =" + parName + "=" + parVal + " equalsPos=" + equalsPos + " keyValPair=" + keyValPair ) ; } } } else { StringBuilder sb = new StringBuilder ( ) ; try { String headerVal = message . getHeader ( headerName ) ; if ( headerVal != null && ! headerVal . isEmpty ( ) ) { if ( entry . getValue ( ) instanceof ArrayList ) { for ( String pair : entry . getValue ( ) ) { sb . append ( ";" ) . append ( pair ) ; } } message . setHeader ( headerName , headerVal + sb . toString ( ) ) ; } else { if ( entry . getValue ( ) instanceof ArrayList ) { for ( String pair : entry . getValue ( ) ) { sb . append ( pair ) . append ( ";" ) ; } } message . addHeader ( headerName , sb . toString ( ) ) ; } } catch ( IllegalArgumentException iae ) { logger . error ( "Exception while setting message header: " + iae . getMessage ( ) ) ; } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "headerName=" + headerName + " headerVal=" + message . getHeader ( headerName ) ) ; } } } else { logger . error ( "headers are null" ) ; }
public class DateListProperty { /** * Resets the timezone associated with the property . If utc is true , any TZID parameters are removed and the Java * timezone is updated to UTC time . If utc is false , TZID parameters are removed and the Java timezone is set to the * default timezone ( i . e . represents a " floating " local time ) * @ param utc the UTC value */ public final void setUtc ( final boolean utc ) { } }
if ( dates == null || ! Value . DATE_TIME . equals ( dates . getType ( ) ) ) { throw new UnsupportedOperationException ( "TimeZone is not applicable to current value" ) ; } dates . setUtc ( utc ) ; getParameters ( ) . remove ( getParameter ( Parameter . TZID ) ) ;
public class MinDelta { /** * Checks whether the minimum delta observed during the current run of the given * search is still above the required minimum . * @ param search search for which the minimum delta has to be checked * @ return < code > true < / code > in case of a minimum delta below the required minimum */ @ Override public boolean searchShouldStop ( Search < ? > search ) { } }
return search . getMinDelta ( ) != JamesConstants . INVALID_DELTA && search . getMinDelta ( ) < minDelta ;
public class Validators { /** * Creates and returns a validator , which allows to validate texts to ensure , that they begin * with an uppercase letter . Empty texts are also accepted . * @ param context * The context , which should be used to retrieve the error message , as an instance of * the class { @ link Context } . The context may not be null * @ return The validator , which has been created , as an instance of the type { @ link Validator } */ public static Validator < CharSequence > beginsWithUppercaseLetter ( @ NonNull final Context context ) { } }
return new BeginsWithUppercaseLetterValidator ( context , R . string . default_error_message ) ;
public class OIDCClientAuthenticatorUtil { /** * This method handle the redirect to the OpenID Connect server with query parameters */ public ProviderAuthenticationResult handleRedirectToServer ( HttpServletRequest req , HttpServletResponse res , ConvergedClientConfig clientConfig ) { } }
String authorizationEndpoint = clientConfig . getAuthorizationEndpointUrl ( ) ; if ( ! checkHttpsRequirement ( clientConfig , authorizationEndpoint ) ) { Tr . error ( tc , "OIDC_CLIENT_URL_PROTOCOL_NOT_HTTPS" , authorizationEndpoint ) ; return new ProviderAuthenticationResult ( AuthResult . SEND_401 , HttpServletResponse . SC_UNAUTHORIZED ) ; } if ( clientConfig . createSession ( ) ) { try { req . getSession ( true ) ; } catch ( Exception e ) { // ignore it . Session exists } } String strRandom = OidcUtil . generateRandom ( OidcUtil . RANDOM_LENGTH ) ; String timestamp = OidcUtil . getTimeStamp ( ) ; String state = timestamp + strRandom ; if ( ! req . getMethod ( ) . equalsIgnoreCase ( "GET" ) && req . getParameter ( "oidc_client" ) != null ) { state = state + req . getParameter ( "oidc_client" ) ; } String cookieValue = HashUtils . createStateCookieValue ( clientConfig , state ) ; String cookieName = ClientConstants . WAS_OIDC_STATE_KEY + HashUtils . getStrHashCode ( state ) ; boolean isHttpsRequest = req . getScheme ( ) . toLowerCase ( ) . contains ( "https" ) ; int cookieLifeTime = ( int ) clientConfig . getAuthenticationTimeLimitInSeconds ( ) ; Cookie cookie = OidcClientUtil . createCookie ( cookieName , cookieValue , cookieLifeTime , req ) ; if ( clientConfig . isHttpsRequired ( ) == true && isHttpsRequest ) { cookie . setSecure ( true ) ; } res . addCookie ( cookie ) ; String redirect_url = setRedirectUrlIfNotDefined ( req , clientConfig ) ; if ( ! checkHttpsRequirement ( clientConfig , redirect_url ) ) { Tr . error ( tc , "OIDC_CLIENT_URL_PROTOCOL_NOT_HTTPS" , redirect_url ) ; return new ProviderAuthenticationResult ( AuthResult . SEND_401 , HttpServletResponse . SC_UNAUTHORIZED ) ; } String acr_values = req . getParameter ( "acr_values" ) ; String authzEndPointUrlWithQuery = null ; try { boolean openidScopeMissing = ! clientConfig . isSocial ( ) && ! isOpenIDScopeSpecified ( clientConfig ) ; // some social media use nonstandard scope boolean scopeMissing = clientConfig . getScope ( ) == null || clientConfig . getScope ( ) . length ( ) == 0 ; if ( openidScopeMissing || scopeMissing ) { Tr . error ( tc , "OIDC_CLIENT_REQUEST_MISSING_OPENID_SCOPE" , clientConfig . getClientId ( ) , clientConfig . getScope ( ) ) ; // CWWKS1713E return new ProviderAuthenticationResult ( AuthResult . SEND_401 , HttpServletResponse . SC_UNAUTHORIZED ) ; } authzEndPointUrlWithQuery = buildAuthorizationUrlWithQuery ( req , ( OidcClientRequest ) req . getAttribute ( ClientConstants . ATTRIB_OIDC_CLIENT_REQUEST ) , state , clientConfig , redirect_url , acr_values ) ; // preserve post param . WebAppSecurityConfig webAppSecConfig = WebAppSecurityCollaboratorImpl . getGlobalWebAppSecurityConfig ( ) ; PostParameterHelper pph = new PostParameterHelper ( webAppSecConfig ) ; pph . save ( req , res ) ; // Redirect to OP // If clientSideRedirect is true ( default is true ) then do the // redirect . If the user agent doesn ' t support javascript then config can set this to false . if ( clientConfig . isClientSideRedirect ( ) ) { String domain = OidcClientUtil . getSsoDomain ( req ) ; doClientSideRedirect ( res , authzEndPointUrlWithQuery , state , domain ) ; } else { String urlCookieName = ClientConstants . WAS_REQ_URL_OIDC + HashUtils . getStrHashCode ( state ) ; Cookie c = OidcClientUtil . createCookie ( urlCookieName , getReqURL ( req ) , cookieLifeTime , req ) ; if ( clientConfig . isHttpsRequired ( ) == true && isHttpsRequest ) { cookie . setSecure ( true ) ; } res . addCookie ( c ) ; } } catch ( UnsupportedEncodingException e ) { Tr . error ( tc , "OIDC_CLIENT_AUTHORIZE_ERR" , new Object [ ] { clientConfig . getClientId ( ) , e . getLocalizedMessage ( ) , ClientConstants . CHARSET } ) ; return new ProviderAuthenticationResult ( AuthResult . SEND_401 , HttpServletResponse . SC_UNAUTHORIZED ) ; } catch ( IOException ioe ) { Tr . error ( tc , "OIDC_CLIENT_AUTHORIZE_ERR" , new Object [ ] { clientConfig . getClientId ( ) , ioe . getLocalizedMessage ( ) , ClientConstants . CHARSET } ) ; return new ProviderAuthenticationResult ( AuthResult . SEND_401 , HttpServletResponse . SC_UNAUTHORIZED ) ; } return new ProviderAuthenticationResult ( AuthResult . REDIRECT_TO_PROVIDER , HttpServletResponse . SC_OK , null , null , null , authzEndPointUrlWithQuery ) ;
public class FileSystemUtilities { /** * Filters all supplied files using the provided { @ code acceptFilter } . * @ param files The list of files to resolve , filter and return . If the { @ code files } List * contains directories , they are searched for Files recursively . Any found Files in such * a search are included in the resulting File List if they match the acceptFilter supplied . * @ param acceptFilter A filter matched to all files in the given List . If the acceptFilter matches a file , it is * included in the result . * @ param log The active Maven Log . * @ return All files in ( or files in subdirectories of directories provided in ) the files List , provided that each * file is accepted by an ExclusionRegExpFileFilter . */ public static List < File > filterFiles ( final List < File > files , final Filter < File > acceptFilter , final Log log ) { } }
// Check sanity Validate . notNull ( files , "files" ) ; final List < File > toReturn = new ArrayList < File > ( ) ; if ( files . size ( ) > 0 ) { for ( File current : files ) { final boolean isAcceptedFile = EXISTING_FILE . accept ( current ) && acceptFilter . accept ( current ) ; final boolean isAcceptedDirectory = EXISTING_DIRECTORY . accept ( current ) && acceptFilter . accept ( current ) ; if ( isAcceptedFile ) { toReturn . add ( current ) ; } else if ( isAcceptedDirectory ) { recurseAndPopulate ( toReturn , Collections . singletonList ( acceptFilter ) , current , false , log ) ; } } } // All done return toReturn ;
public class DataTransferServiceClient { /** * Retrieves a supported data source and returns its settings , which can be used for UI rendering . * < p > Sample code : * < pre > < code > * try ( DataTransferServiceClient dataTransferServiceClient = DataTransferServiceClient . create ( ) ) { * DataSourceName name = ProjectDataSourceName . of ( " [ PROJECT ] " , " [ DATA _ SOURCE ] " ) ; * DataSource response = dataTransferServiceClient . getDataSource ( name . toString ( ) ) ; * < / code > < / pre > * @ param name The field will contain name of the resource requested , for example : * ` projects / { project _ id } / dataSources / { data _ source _ id } ` * @ throws com . google . api . gax . rpc . ApiException if the remote call fails */ public final DataSource getDataSource ( String name ) { } }
GetDataSourceRequest request = GetDataSourceRequest . newBuilder ( ) . setName ( name ) . build ( ) ; return getDataSource ( request ) ;
public class AsynchronousHandlerInvocation { /** * { @ inheritDoc } */ @ Override public void invoke ( final Object listener , final Object message , final MessagePublication publication ) { } }
executor . execute ( new Runnable ( ) { @ Override public void run ( ) { delegate . invoke ( listener , message , publication ) ; } } ) ;
public class JDBCClob { /** * Retrieves the character position at which the specified substring * < code > searchstr < / code > appears in the SQL < code > CLOB < / code > value * represented by this < code > Clob < / code > object . The search * begins at position < code > start < / code > . * @ param searchstr the substring for which to search * @ param start the position at which to begin searching ; the first position * is 1 * @ return the position at which the substring appears or - 1 if it is not * present ; the first position is 1 * @ exception SQLException if there is an error accessing the * < code > CLOB < / code > value or if start is less than 1 * @ exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method * @ since JDK 1.2 , HSQLDB 1.7.2 */ public long position ( final String searchstr , long start ) throws SQLException { } }
final String ldata = data ; checkValid ( ldata ) ; if ( start < MIN_POS ) { throw Util . outOfRangeArgument ( "start: " + start ) ; } if ( searchstr == null || start > MAX_POS ) { return - 1 ; } final int pos = ldata . indexOf ( searchstr , ( int ) -- start ) ; return ( pos < 0 ) ? - 1 : pos + 1 ;
public class CPDefinitionLocalizationPersistenceImpl { /** * Caches the cp definition localizations in the entity cache if it is enabled . * @ param cpDefinitionLocalizations the cp definition localizations */ @ Override public void cacheResult ( List < CPDefinitionLocalization > cpDefinitionLocalizations ) { } }
for ( CPDefinitionLocalization cpDefinitionLocalization : cpDefinitionLocalizations ) { if ( entityCache . getResult ( CPDefinitionLocalizationModelImpl . ENTITY_CACHE_ENABLED , CPDefinitionLocalizationImpl . class , cpDefinitionLocalization . getPrimaryKey ( ) ) == null ) { cacheResult ( cpDefinitionLocalization ) ; } else { cpDefinitionLocalization . resetOriginalValues ( ) ; } }
public class ConstantPropagationAnalysis { /** * Returns the value of the leaf of { @ code exprPath } , if it is determined to be a constant ( always * evaluates to the same numeric value ) , and null otherwise . Note that returning null does not * necessarily mean the expression is * not * a constant . */ @ Nullable public static Number numberValue ( TreePath exprPath , Context context ) { } }
Constant val = DataFlow . expressionDataflow ( exprPath , context , CONSTANT_PROPAGATION ) ; if ( val == null || ! val . isConstant ( ) ) { return null ; } return val . getValue ( ) ;
public class CmsSearchCategoryCollector { /** * Convenience method to format a map of categories in a nice 2 column list , for example * for display of debugging output . < p > * @ param categories the map to format * @ return the formatted category map */ public static final String formatCategoryMap ( Map < String , Integer > categories ) { } }
StringBuffer result = new StringBuffer ( 256 ) ; result . append ( "Total categories: " ) ; result . append ( categories . size ( ) ) ; result . append ( '\n' ) ; Iterator < Map . Entry < String , Integer > > i = categories . entrySet ( ) . iterator ( ) ; while ( i . hasNext ( ) ) { Map . Entry < String , Integer > entry = i . next ( ) ; result . append ( CmsStringUtil . padRight ( entry . getKey ( ) , 30 ) ) ; result . append ( entry . getValue ( ) . intValue ( ) ) ; result . append ( '\n' ) ; } return result . toString ( ) ;
public class GenericHibernateDao { /** * Deletes the passed entity . * @ param e The entity to remove from the database . */ public void delete ( E e ) { } }
LOG . trace ( "Deleting " + entityClass . getSimpleName ( ) + " with ID " + e . getId ( ) ) ; getSession ( ) . delete ( e ) ;
public class Expressions { /** * Create a new Path expression * @ param type type of expression * @ param metadata path metadata * @ param < T > type of expression * @ return path expression */ public static < T extends Enum < T > > EnumPath < T > enumPath ( Class < ? extends T > type , PathMetadata metadata ) { } }
return new EnumPath < T > ( type , metadata ) ;
public class PropertyAdapter { /** * Generate a default example value for property . * @ param property property * @ param markupDocBuilder doc builder * @ return a generated example for the property */ public static Object generateExample ( Property property , MarkupDocBuilder markupDocBuilder ) { } }
if ( property . getType ( ) == null ) { return "untyped" ; } switch ( property . getType ( ) ) { case "integer" : return ExamplesUtil . generateIntegerExample ( property instanceof IntegerProperty ? ( ( IntegerProperty ) property ) . getEnum ( ) : null ) ; case "number" : return 0.0 ; case "boolean" : return true ; case "string" : return ExamplesUtil . generateStringExample ( property . getFormat ( ) , property instanceof StringProperty ? ( ( StringProperty ) property ) . getEnum ( ) : null ) ; case "ref" : if ( property instanceof RefProperty ) { if ( logger . isDebugEnabled ( ) ) logger . debug ( "generateExample RefProperty for " + property . getName ( ) ) ; return markupDocBuilder . copy ( false ) . crossReference ( ( ( RefProperty ) property ) . getSimpleRef ( ) ) . toString ( ) ; } else { if ( logger . isDebugEnabled ( ) ) logger . debug ( "generateExample for ref not RefProperty" ) ; } case "array" : if ( property instanceof ArrayProperty ) { return generateArrayExample ( ( ArrayProperty ) property , markupDocBuilder ) ; } default : return property . getType ( ) ; }
public class ShareActionProviders { /** * Creates a sharing { @ link Intent } . * @ return The sharing intent . */ private Intent createShareIntent ( ) { } }
Intent shareIntent = new Intent ( Intent . ACTION_SEND ) ; shareIntent . setType ( "image/*" ) ; Uri uri = Uri . fromFile ( getFileStreamPath ( "shared.png" ) ) ; shareIntent . putExtra ( Intent . EXTRA_STREAM , uri ) ; return shareIntent ;
public class VersionNumber { /** * Try to determine the version number of the operating system by parsing the user agent string . * @ param family * family of the operating system * @ param userAgent * user agent string * @ return extracted version number */ public static VersionNumber parseOperatingSystemVersion ( @ Nonnull final OperatingSystemFamily family , @ Nonnull final String userAgent ) { } }
Check . notNull ( family , "family" ) ; Check . notNull ( userAgent , "userAgent" ) ; return VersionParser . parseOperatingSystemVersion ( family , userAgent ) ;
public class MediaChannel { /** * Disables the channel and deactivates it ' s resources . * @ throws IllegalStateException * When an attempt is done to deactivate the channel while * inactive . */ public void close ( ) throws IllegalStateException { } }
if ( this . open ) { // Close channels this . rtpChannel . close ( ) ; if ( ! this . rtcpMux ) { this . rtcpChannel . close ( ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( this . mediaType + " channel " + this . ssrc + " is closed" ) ; } // Reset state reset ( ) ; this . open = false ; } else { throw new IllegalStateException ( "Channel is already inactive" ) ; }
public class CloseableReference { /** * Clones a collection of references and returns a list . Returns null if the list is null . If the * list is non - null , clones each reference . If a reference cannot be cloned due to already being * closed , the list will contain a null value in its place . * @ param refs the references to clone * @ return the list of cloned references or null */ public static < T > List < CloseableReference < T > > cloneOrNull ( @ PropagatesNullable Collection < CloseableReference < T > > refs ) { } }
if ( refs == null ) { return null ; } List < CloseableReference < T > > ret = new ArrayList < > ( refs . size ( ) ) ; for ( CloseableReference < T > ref : refs ) { ret . add ( CloseableReference . cloneOrNull ( ref ) ) ; } return ret ;
public class I18nSpecificInList { /** * < p > Setter for lang . < / p > * @ param pLang reference */ public final void setLang ( final Languages pLang ) { } }
this . lang = pLang ; if ( this . itsId == null ) { this . itsId = new IdI18nSpecificInList ( ) ; } this . itsId . setLang ( this . lang ) ;
public class snmpgroup { /** * Use this API to delete snmpgroup . */ public static base_response delete ( nitro_service client , snmpgroup resource ) throws Exception { } }
snmpgroup deleteresource = new snmpgroup ( ) ; deleteresource . name = resource . name ; deleteresource . securitylevel = resource . securitylevel ; return deleteresource . delete_resource ( client ) ;
public class CollectionNumbers { /** * Returns either the wrapped array ( if exists and matches the type ) * or a copy - USE WITH CAUTION AS IT MAY EXPOSE THE INTERNAL STATE * OF THE COLLECTION . * @ param coll the collection * @ return the array */ public static short [ ] shortArrayWrappedOrCopy ( CollectionNumber coll ) { } }
short [ ] array = wrappedShortArray ( coll ) ; if ( array != null ) { return array ; } return shortArrayCopyOf ( coll ) ;
public class SARLPackageExplorerPart { /** * Returns the package explorer part of the active perspective . If * there isn ' t any package explorer part < code > null < / code > is returned . * @ return the package explorer from the active perspective */ public static SARLPackageExplorerPart getFromActivePerspective ( ) { } }
final IWorkbenchPage activePage = JavaPlugin . getActivePage ( ) ; if ( activePage == null ) { return null ; } final IViewPart view = activePage . findView ( ID_PACKAGES ) ; if ( view instanceof PackageExplorerPart ) { return ( SARLPackageExplorerPart ) view ; } return null ;
public class IOGroovyMethods { /** * Write the byte [ ] to the output stream . * The stream is closed before this method returns . * @ param os an output stream * @ param bytes the byte [ ] to write to the output stream * @ throws IOException if an IOException occurs . * @ since 1.7.1 */ public static void setBytes ( OutputStream os , byte [ ] bytes ) throws IOException { } }
try { os . write ( bytes ) ; } finally { closeWithWarning ( os ) ; }
public class AbstractMarkupText { /** * Find all " tokens " that match the given pattern in this text . * A token is like a substring , except that it ' s aware of word boundaries . * For example , while " bc " is a string of " abc " , calling { @ code findTokens } * with " bc " as a pattern on string " abc " won ' t match anything . * This method is convenient for finding keywords that follow a certain syntax * from natural text . You can then use { @ link MarkupText . SubText # surroundWith ( String , String ) } * to put mark up around such text . */ public List < MarkupText . SubText > findTokens ( Pattern pattern ) { } }
String text = getText ( ) ; Matcher m = pattern . matcher ( text ) ; List < SubText > r = new ArrayList < > ( ) ; while ( m . find ( ) ) { int idx = m . start ( ) ; if ( idx > 0 ) { char ch = text . charAt ( idx - 1 ) ; if ( Character . isLetter ( ch ) || Character . isDigit ( ch ) ) continue ; // not at a word boundary } idx = m . end ( ) ; if ( idx < text . length ( ) ) { char ch = text . charAt ( idx ) ; if ( Character . isLetter ( ch ) || Character . isDigit ( ch ) ) continue ; // not at a word boundary } r . add ( createSubText ( m ) ) ; } return r ;
public class HandlerSocketHandler { /** * Check if have to reconnect on session closed */ @ Override public final void onSessionClosed ( Session session ) { } }
this . hsClient . getConnector ( ) . removeSession ( session ) ; HandlerSocketSession hSession = ( HandlerSocketSession ) session ; hSession . destroy ( ) ; if ( this . hsClient . getConnector ( ) . isStarted ( ) && hSession . isAllowReconnect ( ) ) { this . reconnect ( session ) ; } for ( HSClientStateListener listener : this . hsClient . getHSClientStateListeners ( ) ) { listener . onDisconnected ( this . hsClient , session . getRemoteSocketAddress ( ) ) ; }
public class BlockSelectorMarkupHandler { /** * Text events */ @ Override public void handleText ( final char [ ] buffer , final int offset , final int len , final int line , final int col ) throws ParseException { } }
if ( ! this . insideAllSelectorMatchingBlock ) { this . someSelectorsMatch = false ; for ( int i = 0 ; i < this . selectorsLen ; i ++ ) { if ( this . matchingMarkupLevelsPerSelector [ i ] > this . markupLevel ) { this . selectorMatches [ i ] = this . selectorFilters [ i ] . matchText ( true , this . markupLevel , this . markupBlocks [ this . markupLevel ] ) ; if ( this . selectorMatches [ i ] ) { this . someSelectorsMatch = true ; } } else { this . selectorMatches [ i ] = true ; this . someSelectorsMatch = true ; } } if ( this . someSelectorsMatch ) { markCurrentSelection ( ) ; this . selectedHandler . handleText ( buffer , offset , len , line , col ) ; unmarkCurrentSelection ( ) ; return ; } unmarkCurrentSelection ( ) ; this . nonSelectedHandler . handleText ( buffer , offset , len , line , col ) ; return ; } markCurrentSelection ( ) ; this . selectedHandler . handleText ( buffer , offset , len , line , col ) ; unmarkCurrentSelection ( ) ;
public class TemporaryFiles { /** * Create a temporary file . */ public AsyncWork < File , IOException > createFileAsync ( String prefix , String suffix ) { } }
return new Task . OnFile < File , IOException > ( tempDir , "Create temporary file" , Task . PRIORITY_NORMAL ) { @ Override public File run ( ) throws IOException { return createFileSync ( prefix , suffix ) ; } } . start ( ) . getOutput ( ) ;
public class AbstractBigtableAdmin { /** * { @ inheritDoc } */ @ Override public HTableDescriptor [ ] enableTables ( Pattern pattern ) throws IOException { } }
HTableDescriptor [ ] tableDescriptors = listTables ( pattern ) ; for ( HTableDescriptor descriptor : tableDescriptors ) { enableTable ( descriptor . getTableName ( ) ) ; } return tableDescriptors ;
public class LocalUniqueIndex { /** * Create a new index that allows only a single value for each unique key . * @ param name the name of the index ; may not be null or empty * @ param workspaceName the name of the workspace ; may not be null * @ param db the database in which the index information is to be stored ; may not be null * @ param converter the converter from { @ link StaticOperand } to values being indexed ; may not be null * @ param valueSerializer the serializer for the type of value being indexed ; may not be null * @ param rawSerializer the raw value serializer for the type of value being indexed ; may not be null * @ return the new index ; never null */ static < T > LocalUniqueIndex < T > create ( String name , String workspaceName , DB db , Converter < T > converter , BTreeKeySerializer < T > valueSerializer , Serializer < T > rawSerializer ) { } }
return new LocalUniqueIndex < > ( name , workspaceName , db , converter , valueSerializer , rawSerializer ) ;
public class Ifc2x3tc1FactoryImpl { /** * < ! - - begin - user - doc - - > * < ! - - end - user - doc - - > * @ generated */ public IfcThermalLoadTypeEnum createIfcThermalLoadTypeEnumFromString ( EDataType eDataType , String initialValue ) { } }
IfcThermalLoadTypeEnum result = IfcThermalLoadTypeEnum . get ( initialValue ) ; if ( result == null ) throw new IllegalArgumentException ( "The value '" + initialValue + "' is not a valid enumerator of '" + eDataType . getName ( ) + "'" ) ; return result ;
public class CPDefinitionUtil { /** * Returns the last cp definition in the ordered set where displayDate & lt ; & # 63 ; and status = & # 63 ; . * @ param displayDate the display date * @ param status the status * @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > ) * @ return the last matching cp definition * @ throws NoSuchCPDefinitionException if a matching cp definition could not be found */ public static CPDefinition findByLtD_S_Last ( Date displayDate , int status , OrderByComparator < CPDefinition > orderByComparator ) throws com . liferay . commerce . product . exception . NoSuchCPDefinitionException { } }
return getPersistence ( ) . findByLtD_S_Last ( displayDate , status , orderByComparator ) ;
public class DefaultPDUReader { /** * / * ( non - Javadoc ) * @ see org . jsmpp . PDUReader # readPDU ( java . io . InputStream , org . jsmpp . bean . Command ) */ public byte [ ] readPDU ( DataInputStream in , Command pduHeader ) throws IOException { } }
return readPDU ( in , pduHeader . getCommandLength ( ) , pduHeader . getCommandId ( ) , pduHeader . getCommandStatus ( ) , pduHeader . getSequenceNumber ( ) ) ;
public class BondImpl { /** * TODO first check if those bonds haven ' t been made already */ private void addSelfToAtoms ( ) { } }
List < Bond > bonds = atomA . getBonds ( ) ; if ( bonds == null ) { bonds = new ArrayList < Bond > ( AtomImpl . BONDS_INITIAL_CAPACITY ) ; atomA . setBonds ( bonds ) ; } boolean exists = false ; for ( Bond bond : bonds ) { // TODO is it equals ( ) what we want here , or is it = = ? - JD 2016-03-02 if ( bond . getOther ( atomA ) . equals ( atomB ) ) { exists = true ; break ; } } if ( ! exists ) { atomA . addBond ( this ) ; atomB . addBond ( this ) ; }
public class CuratorFrameworkFactory { /** * Create a new client with default session timeout and default connection timeout * @ param connectString list of servers to connect to * @ param retryPolicy retry policy to use * @ return client */ public static CuratorFramework newClient ( String connectString , RetryPolicy retryPolicy ) { } }
return newClient ( connectString , DEFAULT_SESSION_TIMEOUT_MS , DEFAULT_CONNECTION_TIMEOUT_MS , retryPolicy ) ;
public class AbstractRegionPainter { /** * Decodes and returns a color , which is derived from a base color in UI * defaults . * @ param key A key corresponding to the value in the UI Defaults table * of UIManager where the base color is defined * @ param hOffset The hue offset used for derivation . * @ param sOffset The saturation offset used for derivation . * @ param bOffset The brightness offset used for derivation . * @ param aOffset The alpha offset used for derivation . Between 0 . . . 255 * @ return The derived color , whos color value will change if the parent * uiDefault color changes . */ protected final Color decodeColor ( String key , float hOffset , float sOffset , float bOffset , int aOffset ) { } }
if ( UIManager . getLookAndFeel ( ) instanceof SeaGlassLookAndFeel ) { SeaGlassLookAndFeel laf = ( SeaGlassLookAndFeel ) UIManager . getLookAndFeel ( ) ; return laf . getDerivedColor ( key , hOffset , sOffset , bOffset , aOffset , true ) ; } else { // can not give a right answer as painter should not be used outside // of nimbus laf but do the best we can return Color . getHSBColor ( hOffset , sOffset , bOffset ) ; }
public class ExceptionSoftener { /** * Soften a CheckedLongSupplier to an LongSupplier that doesn ' t need to declare any checked exceptions thrown * e . g . * < pre > * { @ code * LongSupplier supplier = ExceptionSoftener . softenLongSupplier ( ( ) - > { throw new IOException ( ) ; } ) * supplier . getAsLong ( ) ; / / throws IOException but doesn ' t need to declare it * / / as a method reference * ExceptionSoftener . softenLongSupplier ( this : : getLong ) ; * < / pre > * @ param s CheckedLongSupplier to soften * @ return LongSupplier that can throw checked exceptions */ public static LongSupplier softenLongSupplier ( final CheckedLongSupplier s ) { } }
return ( ) -> { try { return s . getAsLong ( ) ; } catch ( final Throwable e ) { throw throwSoftenedException ( e ) ; } } ;