signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class ElasticSearchAttackStore { /** * { @ inheritDoc } */
@ Override public Collection < Attack > findAttacks ( SearchCriteria criteria ) { } } | if ( criteria == null ) { throw new IllegalArgumentException ( "criteria must be non-null" ) ; } try { return attackRepository . findAttacksBySearchCriteria ( criteria ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } |
public class ModelsImpl { /** * Get suggestion examples that would improve the accuracy of the entity model .
* @ param appId The application ID .
* @ param versionId The version ID .
* @ param entityId The target entity extractor model to enhance .
* @ param getEntitySuggestionsOptionalParameter the object representing the optional parameters to be set before calling this API
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the List & lt ; EntitiesSuggestionExample & gt ; object */
public Observable < List < EntitiesSuggestionExample > > getEntitySuggestionsAsync ( UUID appId , String versionId , UUID entityId , GetEntitySuggestionsOptionalParameter getEntitySuggestionsOptionalParameter ) { } } | return getEntitySuggestionsWithServiceResponseAsync ( appId , versionId , entityId , getEntitySuggestionsOptionalParameter ) . map ( new Func1 < ServiceResponse < List < EntitiesSuggestionExample > > , List < EntitiesSuggestionExample > > ( ) { @ Override public List < EntitiesSuggestionExample > call ( ServiceResponse < List < EntitiesSuggestionExample > > response ) { return response . body ( ) ; } } ) ; |
public class MappeableRunContainer { /** * to return ArrayContainer or BitmapContainer */
private void smartAppend ( short [ ] vl , short val ) { } } | int oldend ; if ( ( nbrruns == 0 ) || ( toIntUnsigned ( val ) > ( oldend = toIntUnsigned ( vl [ 2 * ( nbrruns - 1 ) ] ) + toIntUnsigned ( vl [ 2 * ( nbrruns - 1 ) + 1 ] ) ) + 1 ) ) { // we add a new one
vl [ 2 * nbrruns ] = val ; vl [ 2 * nbrruns + 1 ] = 0 ; nbrruns ++ ; return ; } if ( val == ( short ) ( oldend + 1 ) ) { // we merge
vl [ 2 * ( nbrruns - 1 ) + 1 ] ++ ; } |
public class CPDefinitionOptionValueRelUtil { /** * Returns the cp definition option value rels before and after the current cp definition option value rel in the ordered set where groupId = & # 63 ; .
* @ param CPDefinitionOptionValueRelId the primary key of the current cp definition option value rel
* @ param groupId the group ID
* @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > )
* @ return the previous , current , and next cp definition option value rel
* @ throws NoSuchCPDefinitionOptionValueRelException if a cp definition option value rel with the primary key could not be found */
public static CPDefinitionOptionValueRel [ ] findByGroupId_PrevAndNext ( long CPDefinitionOptionValueRelId , long groupId , OrderByComparator < CPDefinitionOptionValueRel > orderByComparator ) throws com . liferay . commerce . product . exception . NoSuchCPDefinitionOptionValueRelException { } } | return getPersistence ( ) . findByGroupId_PrevAndNext ( CPDefinitionOptionValueRelId , groupId , orderByComparator ) ; |
public class UpdateManager { /** * Add one { @ link DefaultUpdateRepository ) .
* @ param id of repo
* @ param url of repo */
public void addRepository ( String id , URL url ) { } } | for ( UpdateRepository ur : repositories ) { if ( ur . getId ( ) . equals ( id ) ) { throw new RuntimeException ( "Repository with id " + id + " already exists" ) ; } } repositories . add ( new DefaultUpdateRepository ( id , url ) ) ; |
public class FNPRGImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public void setReserved2 ( byte [ ] newReserved2 ) { } } | byte [ ] oldReserved2 = reserved2 ; reserved2 = newReserved2 ; if ( eNotificationRequired ( ) ) eNotify ( new ENotificationImpl ( this , Notification . SET , AfplibPackage . FNPRG__RESERVED2 , oldReserved2 , reserved2 ) ) ; |
public class BufferParallelAggregation { /** * Groups the containers by their keys
* @ param bitmaps input bitmaps
* @ return The containers from the bitmaps grouped by key */
public static SortedMap < Short , List < MappeableContainer > > groupByKey ( ImmutableRoaringBitmap ... bitmaps ) { } } | Map < Short , List < MappeableContainer > > grouped = new HashMap < > ( ) ; for ( ImmutableRoaringBitmap bitmap : bitmaps ) { MappeableContainerPointer it = bitmap . highLowContainer . getContainerPointer ( ) ; while ( null != it . getContainer ( ) ) { MappeableContainer container = it . getContainer ( ) ; Short key = it . key ( ) ; List < MappeableContainer > slice = grouped . get ( key ) ; if ( null == slice ) { slice = new ArrayList < > ( ) ; grouped . put ( key , slice ) ; } slice . add ( container ) ; it . advance ( ) ; } } SortedMap < Short , List < MappeableContainer > > sorted = new TreeMap < > ( BufferUtil :: compareUnsigned ) ; sorted . putAll ( grouped ) ; return sorted ; |
public class MapModel { /** * Refresh the MapModel object , using a configuration object acquired from the server . This will automatically
* build the list of layers .
* @ param mapInfo The configuration object . */
private void refresh ( final ClientMapInfo mapInfo ) { } } | actualRefresh ( mapInfo ) ; if ( state == State . INITIALIZING ) { // only change the initial bounds the first time around
Bbox initialBounds = new Bbox ( mapInfo . getInitialBounds ( ) ) ; mapView . applyBounds ( initialBounds , MapView . ZoomOption . LEVEL_CLOSEST ) ; } state = State . INITIALIZED ; fireRefreshEvents ( ) ; while ( whenInitializedRunnables . size ( ) > 0 ) { Runnable runnable = whenInitializedRunnables . remove ( 0 ) ; runnable . run ( ) ; } |
public class TaskContext { /** * Get the list of post - fork { @ link Converter } s for a given branch .
* @ param index branch index
* @ param forkTaskState a { @ link TaskState } instance specific to the fork identified by the branch index
* @ return list ( possibly empty ) of { @ link Converter } s */
@ SuppressWarnings ( "unchecked" ) public List < Converter < ? , ? , ? , ? > > getConverters ( int index , TaskState forkTaskState ) { } } | String converterClassKey = ForkOperatorUtils . getPropertyNameForBranch ( ConfigurationKeys . CONVERTER_CLASSES_KEY , index ) ; if ( ! this . taskState . contains ( converterClassKey ) ) { return Collections . emptyList ( ) ; } if ( index >= 0 ) { forkTaskState . setProp ( ConfigurationKeys . FORK_BRANCH_ID_KEY , index ) ; } List < Converter < ? , ? , ? , ? > > converters = Lists . newArrayList ( ) ; for ( String converterClass : Splitter . on ( "," ) . omitEmptyStrings ( ) . trimResults ( ) . split ( this . taskState . getProp ( converterClassKey ) ) ) { try { Converter < ? , ? , ? , ? > converter = Converter . class . cast ( Class . forName ( converterClass ) . newInstance ( ) ) ; InstrumentedConverterDecorator instrumentedConverter = new InstrumentedConverterDecorator < > ( converter ) ; instrumentedConverter . init ( forkTaskState ) ; converters . add ( instrumentedConverter ) ; } catch ( ClassNotFoundException cnfe ) { throw new RuntimeException ( cnfe ) ; } catch ( InstantiationException ie ) { throw new RuntimeException ( ie ) ; } catch ( IllegalAccessException iae ) { throw new RuntimeException ( iae ) ; } } return converters ; |
public class RegExpSubstitution { /** * Replace only the last occurrence . < br >
* 替换掉最后一个出现的地方
* @ param textThe original String . < br > 替换前的原始字符串 。
* @ returnThe String after substitution ; If no match found , the same String as the input one will be returned . < br >
* 替换后的结果 ; 如果没有发生替换 , 则结果与原来输入的字符串完全相同 。 */
public String replaceLast ( CharSequence text ) { } } | StringBuilder sb = new StringBuilder ( ) ; AutomatonMatcher am = runAutomation . newMatcher ( text ) ; int start = 0 ; int end = 0 ; while ( am . find ( ) ) { start = am . start ( ) ; end = am . end ( ) ; } if ( start != 0 || end != 0 ) { sb . append ( text , 0 , start ) ; sb . append ( replacement ) ; sb . append ( text , end , text . length ( ) ) ; } else { sb . append ( text ) ; } return sb . toString ( ) ; |
public class InternalUtils { /** * corners ) */
static int addPointsToArray ( Point2D p0In , Point2D p1In , Point2D [ ] pointsArray , int idx , Envelope2D fullRange2D , boolean clockwise , double densifyDist ) // PointerOfArrayOf ( Point2D )
// pointsArray , int idx ,
// Envelope2D fullRange2D ,
// boolean clockwise , double
// densifyDist )
{ } } | Point2D p0 = new Point2D ( ) ; p0 . setCoords ( p0In ) ; Point2D p1 = new Point2D ( ) ; p1 . setCoords ( p1In ) ; fullRange2D . _snapToBoundary ( p0 ) ; fullRange2D . _snapToBoundary ( p1 ) ; // / / _ ASSERT ( ( p0 . x = = fullRange2D . xmin | | p0 . x = = fullRange2D . xmax ) & &
// ( p1 . x = = fullRange2D . xmin | | p1 . x = = fullRange2D . xmax ) ) ;
double boundDist0 = fullRange2D . _boundaryDistance ( p0 ) ; double boundDist1 = fullRange2D . _boundaryDistance ( p1 ) ; if ( boundDist1 == 0.0 ) boundDist1 = fullRange2D . getLength ( ) ; if ( ( p0 . x == p1 . x || p0 . y == p1 . y && ( p0 . y == fullRange2D . ymin || p0 . y == fullRange2D . ymax ) ) && ( boundDist1 > boundDist0 ) == clockwise ) { Point2D delta = new Point2D ( ) ; delta . setCoords ( p1 . x - p0 . x , p1 . y - p0 . y ) ; if ( densifyDist != 0 ) // if ( densifyDist )
{ long cPoints = ( long ) ( delta . _norm ( 0 ) / densifyDist ) ; if ( cPoints > 0 ) // if ( cPoints )
{ delta . scale ( 1.0 / ( cPoints + 1 ) ) ; for ( long i = 0 ; i < cPoints ; i ++ ) { p0 . add ( delta ) ; pointsArray [ idx ++ ] . setCoords ( p0 . x , p0 . y ) ; // ARRAYELEMENT ( pointsArray ,
// idx + + ) . setCoords ( p0 . x ,
// p0 . y ) ;
} } } } else { int side0 = fullRange2D . _envelopeSide ( p0 ) ; int side1 = fullRange2D . _envelopeSide ( p1 ) ; // create up to four corner points ; the order depends on boolean
// clockwise
Point2D corner ; int deltaSide = clockwise ? 1 : 3 ; // 3 is equivalent to - 1
do { side0 = ( side0 + deltaSide ) & 3 ; corner = fullRange2D . queryCorner ( side0 ) ; if ( densifyDist != 0 ) // if ( densifyDist )
{ idx = addPointsToArray ( p0 , corner , pointsArray , idx , fullRange2D , clockwise , densifyDist ) ; } pointsArray [ idx ++ ] . setCoords ( corner . x , corner . y ) ; // ARRAYELEMENT ( pointsArray ,
// idx + + ) . setCoords ( corner . x ,
// corner . y ) ;
p0 = corner ; } while ( ( side0 & 3 ) != side1 ) ; if ( densifyDist != 0 ) // if ( densifyDist )
idx = addPointsToArray ( p0 , p1 , pointsArray , idx , fullRange2D , clockwise , densifyDist ) ; } return idx ; |
public class StreamUtils { /** * Copy from an input stream to a file ( and buffer it ) and close the input stream .
* It is highly recommended to use FileUtils . retryCopy whenever possible , and not use a raw ` InputStream `
* @ param is The input stream to copy bytes from . ` is ` is closed regardless of the copy result .
* @ param file The file to copy bytes to . Any parent directories are automatically created .
* @ return The count of bytes written to the file
* @ throws IOException */
public static long copyToFileAndClose ( InputStream is , File file ) throws IOException { } } | file . getParentFile ( ) . mkdirs ( ) ; try ( OutputStream os = new BufferedOutputStream ( new FileOutputStream ( file ) ) ) { final long result = ByteStreams . copy ( is , os ) ; // Workarround for http : / / hg . openjdk . java . net / jdk8 / jdk8 / jdk / rev / 759aa847dcaf
os . flush ( ) ; return result ; } finally { is . close ( ) ; } |
public class S3LocationMarshaller { /** * Marshall the given parameter object . */
public void marshall ( S3Location s3Location , ProtocolMarshaller protocolMarshaller ) { } } | if ( s3Location == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( s3Location . getBucketName ( ) , BUCKETNAME_BINDING ) ; protocolMarshaller . marshall ( s3Location . getBucketKey ( ) , BUCKETKEY_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class AbstractBigtableAdmin { /** * shell is switch to use the methods defined in the interface . */
@ Deprecated public void addColumn ( String tableName , HColumnDescriptor column ) throws IOException { } } | addColumn ( TableName . valueOf ( tableName ) , column ) ; |
public class LogoutController { /** * Process the incoming request and response .
* @ param request HttpServletRequest object
* @ param response HttpServletResponse object */
@ RequestMapping public void doLogout ( HttpServletRequest request , HttpServletResponse response ) throws IOException { } } | String redirect = this . selectRedirectionUrl ( request ) ; final HttpSession session = request . getSession ( false ) ; if ( session != null ) { // Record that an authenticated user is requesting to log out
try { final IPerson person = personManager . getPerson ( request ) ; if ( person != null && person . getSecurityContext ( ) . isAuthenticated ( ) ) { this . portalEventFactory . publishLogoutEvent ( request , this , person ) ; } } catch ( final Exception e ) { logger . error ( "Exception recording logout " + "associated with request " + request , e ) ; } final String originalUid = this . identitySwapperManager . getOriginalUsername ( session ) ; // Logging out from a swapped user , just redirect to the Login servlet
if ( originalUid != null ) { redirect = request . getContextPath ( ) + "/Login" ; } else { // Clear out the existing session for the user
try { session . invalidate ( ) ; } catch ( final IllegalStateException ise ) { // IllegalStateException indicates session was already invalidated .
// This is fine . LogoutController is looking to guarantee the logged out
// session is invalid ;
// it need not insist that it be the one to perform the invalidating .
if ( logger . isTraceEnabled ( ) ) { logger . trace ( "LogoutController encountered IllegalStateException invalidating a presumably already-invalidated session." , ise ) ; } } } } if ( logger . isTraceEnabled ( ) ) { logger . trace ( "Redirecting to " + redirect + " to send the user back to the guest page." ) ; } final String encodedRedirectURL = response . encodeRedirectURL ( redirect ) ; response . sendRedirect ( encodedRedirectURL ) ; |
public class DocumentTemplateRepository { /** * Returns the document template , if any for the specified { @ link DocumentType } and exact application tenancy , and exact date . */
@ Programmatic public DocumentTemplate findByTypeAndAtPathAndDate ( final DocumentType documentType , final String atPath , final LocalDate date ) { } } | return repositoryService . firstMatch ( new QueryDefault < > ( DocumentTemplate . class , "findByTypeAndAtPathAndDate" , "type" , documentType , "atPath" , atPath , "date" , date ) ) ; |
public class BetterImageSpan { /** * Returns the width of the image span and increases the height if font metrics are available . */
@ Override public int getSize ( Paint paint , CharSequence text , int start , int end , Paint . FontMetricsInt fontMetrics ) { } } | updateBounds ( ) ; if ( fontMetrics == null ) { return mWidth ; } int offsetAbove = getOffsetAboveBaseline ( fontMetrics ) ; int offsetBelow = mHeight + offsetAbove ; if ( offsetAbove < fontMetrics . ascent ) { fontMetrics . ascent = offsetAbove ; } if ( offsetAbove < fontMetrics . top ) { fontMetrics . top = offsetAbove ; } if ( offsetBelow > fontMetrics . descent ) { fontMetrics . descent = offsetBelow ; } if ( offsetBelow > fontMetrics . bottom ) { fontMetrics . bottom = offsetBelow ; } return mWidth ; |
public class AmazonGameLiftClient { /** * Cancels a matchmaking ticket that is currently being processed . To stop the matchmaking operation , specify the
* ticket ID . If successful , work on the ticket is stopped , and the ticket status is changed to
* < code > CANCELLED < / code > .
* < ul >
* < li >
* < a > StartMatchmaking < / a >
* < / li >
* < li >
* < a > DescribeMatchmaking < / a >
* < / li >
* < li >
* < a > StopMatchmaking < / a >
* < / li >
* < li >
* < a > AcceptMatch < / a >
* < / li >
* < li >
* < a > StartMatchBackfill < / a >
* < / li >
* < / ul >
* @ param stopMatchmakingRequest
* Represents the input for a request action .
* @ return Result of the StopMatchmaking operation returned by the service .
* @ throws InvalidRequestException
* One or more parameter values in the request are invalid . Correct the invalid parameter values before
* retrying .
* @ throws NotFoundException
* A service resource associated with the request could not be found . Clients should not retry such
* requests .
* @ throws InternalServiceException
* The service encountered an unrecoverable internal failure while processing the request . Clients can retry
* such requests immediately or after a waiting period .
* @ throws UnsupportedRegionException
* The requested operation is not supported in the region specified .
* @ sample AmazonGameLift . StopMatchmaking
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / gamelift - 2015-10-01 / StopMatchmaking " target = " _ top " > AWS API
* Documentation < / a > */
@ Override public StopMatchmakingResult stopMatchmaking ( StopMatchmakingRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeStopMatchmaking ( request ) ; |
public class Searches { /** * Searches the first matching element returning it .
* @ param < E > the element type parameter
* @ param iterator the iterator to be searched
* @ param predicate the predicate to be applied to each element
* @ throws IllegalArgumentException if no element matches
* @ return the found element */
public static < E > E findFirst ( Iterator < E > iterator , Predicate < E > predicate ) { } } | final Iterator < E > filtered = new FilteringIterator < E > ( iterator , predicate ) ; return new FirstElement < E > ( ) . apply ( filtered ) ; |
public class DefaultClusterManager { /** * Selects a group in the cluster . */
private void doSelectGroup ( final Message < JsonObject > message ) { } } | final Object key = message . body ( ) . getValue ( "key" ) ; if ( key == null ) { message . reply ( new JsonObject ( ) . putString ( "status" , "error" ) . putString ( "message" , "No key specified." ) ) ; } else { selectGroup ( key , new Handler < AsyncResult < String > > ( ) { @ Override public void handle ( AsyncResult < String > result ) { if ( result . failed ( ) ) { message . reply ( new JsonObject ( ) . putString ( "status" , "error" ) . putString ( "message" , result . cause ( ) . getMessage ( ) ) ) ; } else if ( result . result ( ) == null ) { message . reply ( new JsonObject ( ) . putString ( "status" , "error" ) . putString ( "message" , "No groups to select." ) ) ; } else { message . reply ( new JsonObject ( ) . putString ( "status" , "ok" ) . putString ( "result" , result . result ( ) ) ) ; } } } ) ; } |
public class Constraint { /** * Verifies that the given annotation type corresponds to a known constraint .
* @ param anno annotation type
* @ param consName constraint name
* @ return true if known */
public static boolean matches ( Class < ? extends Annotation > anno , String consName ) { } } | return VALIDATORS . get ( anno ) . equals ( consName ) ; |
public class FlowControllerFactory { /** * Create a page flow of the given type . The page flow stack ( for nesting ) will be cleared or pushed , and the new
* instance will be stored as the current page flow .
* @ deprecated Use { @ link # createPageFlow ( RequestContext , Class ) } instead .
* @ param request the current HttpServletRequest .
* @ param response the current HttpServletResponse .
* @ param pageFlowClass the type of the desired page flow .
* @ param servletContext the current ServletContext .
* @ return the newly - created { @ link PageFlowController } , or < code > null < / code > if none was found . */
public static PageFlowController getPageFlow ( Class pageFlowClass , HttpServletRequest request , HttpServletResponse response , ServletContext servletContext ) { } } | try { FlowControllerFactory factory = get ( servletContext ) ; return factory . createPageFlow ( new RequestContext ( request , response ) , pageFlowClass ) ; } catch ( InstantiationException e ) { LOG . error ( "Could not instantiate PageFlowController of type " + pageFlowClass . getName ( ) , e ) ; return null ; } catch ( IllegalAccessException e ) { LOG . error ( "Could not instantiate PageFlowController of type " + pageFlowClass . getName ( ) , e ) ; return null ; } |
public class PortletAppTypeImpl { /** * Returns all < code > filter < / code > elements
* @ return list of < code > filter < / code > */
public List < FilterType < PortletAppType < T > > > getAllFilter ( ) { } } | List < FilterType < PortletAppType < T > > > list = new ArrayList < FilterType < PortletAppType < T > > > ( ) ; List < Node > nodeList = childNode . get ( "filter" ) ; for ( Node node : nodeList ) { FilterType < PortletAppType < T > > type = new FilterTypeImpl < PortletAppType < T > > ( this , "filter" , childNode , node ) ; list . add ( type ) ; } return list ; |
public class RemoveUnusedShapes { /** * Recursively resolves the shapes represented by the member . When the member is a map ,
* both the key shape and the value shape of the map will be resolved , so that the
* returning list could have more than one elements . */
private static List < String > resolveMemberShapes ( MemberModel member ) { } } | if ( member == null ) return new LinkedList < String > ( ) ; if ( member . getEnumType ( ) != null ) { return Collections . singletonList ( member . getEnumType ( ) ) ; } else if ( member . isList ( ) ) { return resolveMemberShapes ( member . getListModel ( ) . getListMemberModel ( ) ) ; } else if ( member . isMap ( ) ) { List < String > memberShapes = new LinkedList < String > ( ) ; memberShapes . addAll ( resolveMemberShapes ( member . getMapModel ( ) . getKeyModel ( ) ) ) ; memberShapes . addAll ( resolveMemberShapes ( member . getMapModel ( ) . getValueModel ( ) ) ) ; return memberShapes ; } else if ( member . isSimple ( ) ) { // member is scalar , do nothing
return new LinkedList < String > ( ) ; } else { // member is a structure .
return Collections . singletonList ( member . getVariable ( ) . getSimpleType ( ) ) ; } |
public class FastDriverCommandExecutor { /** * Sends the { @ code command } to the driver server for execution . The server will be started
* if requesting a new session . Likewise , if terminating a session , the server will be shutdown
* once a response is received .
* @ param command The command to execute .
* @ return The command response .
* @ throws java . io . IOException If an I / O error occurs while sending the command . */
@ Override public Response execute ( Command command ) throws IOException { } } | if ( DriverCommand . NEW_SESSION . equals ( command . getName ( ) ) ) { service . start ( ) ; } try { return super . execute ( command ) ; } catch ( Throwable t ) { Throwable rootCause = Throwables . getRootCause ( t ) ; if ( rootCause instanceof ConnectException && "Connection refused" . equals ( rootCause . getMessage ( ) ) && ! service . isRunning ( ) ) { throw new WebDriverException ( "The driver server has unexpectedly died!" , t ) ; } Throwables . propagateIfPossible ( t ) ; throw new WebDriverException ( t ) ; } finally { if ( DriverCommand . QUIT . equals ( command . getName ( ) ) ) { service . stop ( ) ; } } |
public class MacroParametersUtils { /** * < p > extractParameterMultiple . < / p >
* @ param name a { @ link java . lang . String } object .
* @ param parameters a { @ link java . util . Map } object .
* @ return an array of { @ link java . lang . String } objects . */
public static String [ ] extractParameterMultiple ( String name , Map parameters ) { } } | String paramValues = extractParameter ( name , parameters ) ; return StringUtils . stripAll ( StringUtils . split ( paramValues , ", " ) ) ; |
public class JsonEscapeUtil { /** * Perform an unescape operation based on a Reader , writing the result to a Writer .
* Note this reader is going to be read char - by - char , so some kind of buffering might be appropriate if this
* is an inconvenience for the specific Reader implementation . */
static void unescape ( final Reader reader , final Writer writer ) throws IOException { } } | if ( reader == null ) { return ; } final int [ ] escapes = new int [ 4 ] ; int c1 , c2 ; // c1 : current char , c2 : next char
c2 = reader . read ( ) ; while ( c2 >= 0 ) { c1 = c2 ; c2 = reader . read ( ) ; /* * Check the need for an unescape operation at this point */
if ( c1 != ESCAPE_PREFIX || c2 < 0 ) { writer . write ( c1 ) ; continue ; } int codepoint = - 1 ; if ( c1 == ESCAPE_PREFIX ) { switch ( c2 ) { case 'b' : codepoint = 0x08 ; c1 = c2 ; c2 = reader . read ( ) ; break ; case 't' : codepoint = 0x09 ; c1 = c2 ; c2 = reader . read ( ) ; break ; case 'n' : codepoint = 0x0A ; c1 = c2 ; c2 = reader . read ( ) ; break ; case 'f' : codepoint = 0x0C ; c1 = c2 ; c2 = reader . read ( ) ; break ; case 'r' : codepoint = 0x0D ; c1 = c2 ; c2 = reader . read ( ) ; break ; case '"' : codepoint = 0x22 ; c1 = c2 ; c2 = reader . read ( ) ; break ; case '\\' : codepoint = 0x5C ; c1 = c2 ; c2 = reader . read ( ) ; break ; case '/' : codepoint = 0x2F ; c1 = c2 ; c2 = reader . read ( ) ; break ; } if ( codepoint == - 1 ) { if ( c2 == ESCAPE_UHEXA_PREFIX2 ) { // This can be a uhexa escape , we need exactly four more characters
int escapei = 0 ; int ce = reader . read ( ) ; while ( ce >= 0 && escapei < 4 ) { if ( ! ( ( ce >= '0' && ce <= '9' ) || ( ce >= 'A' && ce <= 'F' ) || ( ce >= 'a' && ce <= 'f' ) ) ) { break ; } escapes [ escapei ] = ce ; ce = reader . read ( ) ; escapei ++ ; } if ( escapei < 4 ) { // We weren ' t able to consume the required four hexa chars , leave it as slash + ' u ' , which
// is invalid , and let the corresponding JSON parser fail .
writer . write ( c1 ) ; writer . write ( c2 ) ; for ( int i = 0 ; i < escapei ; i ++ ) { c1 = c2 ; c2 = escapes [ i ] ; writer . write ( c2 ) ; } c1 = c2 ; c2 = ce ; continue ; } c1 = escapes [ 3 ] ; c2 = ce ; codepoint = parseIntFromReference ( escapes , 0 , 4 , 16 ) ; // Don ' t continue here , just let the unescape code below do its job
} else { // Other escape sequences are not allowed by JSON . So we leave it as is
// and expect the corresponding JSON parser to fail .
writer . write ( c1 ) ; writer . write ( c2 ) ; c1 = c2 ; c2 = reader . read ( ) ; continue ; } } } /* * Perform the real unescape */
if ( codepoint > '\uFFFF' ) { writer . write ( Character . toChars ( codepoint ) ) ; } else { writer . write ( ( char ) codepoint ) ; } } |
public class MongoDBNativeQuery { /** * This method insert a list of documents into a collection . Params w and wtimeout are read from QueryOptions .
* @ param documentList The new list of documents to be inserted
* @ param options Some options like timeout
* @ return A BulkWriteResult from MongoDB API */
public BulkWriteResult insert ( List < Document > documentList , QueryOptions options ) { } } | List < WriteModel < Document > > actions = new ArrayList < > ( documentList . size ( ) ) ; for ( Document document : documentList ) { actions . add ( new InsertOneModel < > ( document ) ) ; } int writeConcern = 1 ; int ms = 0 ; if ( options != null && ( options . containsKey ( "w" ) || options . containsKey ( "wtimeout" ) ) ) { writeConcern = options . getInt ( "w" , 1 ) ; ms = options . getInt ( "wtimeout" , 0 ) ; } dbCollection . withWriteConcern ( new WriteConcern ( writeConcern , ms ) ) ; return dbCollection . bulkWrite ( actions , new BulkWriteOptions ( ) . ordered ( false ) ) ; |
public class TagUtil { /** * If any tag is in the exclude list and strictExclude is true , this will return false .
* If any tag is in the exclude list and strictExclude is false , then it will depend upon whether or not there is a tag in the includeTags list .
* If the includeTags list is empty or if any tag is in the includeTags list , return true .
* Otherwise , return false . */
public static boolean checkMatchingTags ( Collection < String > tags , Set < String > includeTags , Set < String > excludeTags , boolean strictExclude ) { } } | boolean foundIncludeMatch = false ; if ( includeTags . isEmpty ( ) ) return true ; for ( String tag : tags ) { if ( excludeTags . contains ( tag ) ) // If strict , seeing an excluded tag means this set of tags didn ' t meet the criteria .
if ( strictExclude ) return false ; // If not strict , only ignore the excluded tags .
else continue ; if ( includeTags . isEmpty ( ) || includeTags . contains ( tag ) ) foundIncludeMatch = true ; } return foundIncludeMatch ; |
public class NameOpValue { /** * Adds a value to the list of values .
* @ param value the value to add . */
public void add ( Value value ) { } } | if ( values == null ) values = new LinkedList ( ) ; values . add ( value ) ; |
public class CodeBuilderFragment2 { /** * Create the Web - interface bindings for the builders .
* @ return the bindings . */
protected BindingFactory createWebBindings ( ) { } } | final BindingFactory factory = new BindingFactory ( getClass ( ) . getName ( ) ) ; for ( final AbstractSubCodeBuilderFragment subFragment : this . subFragments ) { subFragment . generateWebBindings ( factory ) ; } return factory ; |
public class MPdfWriter { /** * Effectue le rendu de la liste .
* @ param table
* MBasicTable
* @ param datatable
* Table
* @ throws BadElementException */
protected void renderList ( final MBasicTable table , final Table datatable ) throws BadElementException { } } | final int columnCount = table . getColumnCount ( ) ; final int rowCount = table . getRowCount ( ) ; // data rows
final Font font = FontFactory . getFont ( FontFactory . HELVETICA , 10 , Font . NORMAL ) ; datatable . getDefaultCell ( ) . setBorderWidth ( 1 ) ; datatable . getDefaultCell ( ) . setHorizontalAlignment ( Element . ALIGN_LEFT ) ; // datatable . setDefaultCellGrayFill ( 0 ) ;
Object value ; String text ; int horizontalAlignment ; for ( int k = 0 ; k < rowCount ; k ++ ) { for ( int i = 0 ; i < columnCount ; i ++ ) { value = getValueAt ( table , k , i ) ; if ( value instanceof Number || value instanceof Date ) { horizontalAlignment = Element . ALIGN_RIGHT ; } else if ( value instanceof Boolean ) { horizontalAlignment = Element . ALIGN_CENTER ; } else { horizontalAlignment = Element . ALIGN_LEFT ; } datatable . getDefaultCell ( ) . setHorizontalAlignment ( horizontalAlignment ) ; text = getTextAt ( table , k , i ) ; datatable . addCell ( new Phrase ( 8 , text != null ? text : "" , font ) ) ; } } |
public class TreeInfo { /** * Return true if a tree represents the null literal . */
public static boolean isNull ( JCTree tree ) { } } | if ( ! tree . hasTag ( LITERAL ) ) return false ; JCLiteral lit = ( JCLiteral ) tree ; return ( lit . typetag == BOT ) ; |
public class ValidDBInstanceModificationsMessage { /** * Valid processor features for your DB instance .
* < b > NOTE : < / b > This method appends the values to the existing list ( if any ) . Use
* { @ link # setValidProcessorFeatures ( java . util . Collection ) } or
* { @ link # withValidProcessorFeatures ( java . util . Collection ) } if you want to override the existing values .
* @ param validProcessorFeatures
* Valid processor features for your DB instance .
* @ return Returns a reference to this object so that method calls can be chained together . */
public ValidDBInstanceModificationsMessage withValidProcessorFeatures ( AvailableProcessorFeature ... validProcessorFeatures ) { } } | if ( this . validProcessorFeatures == null ) { setValidProcessorFeatures ( new com . amazonaws . internal . SdkInternalList < AvailableProcessorFeature > ( validProcessorFeatures . length ) ) ; } for ( AvailableProcessorFeature ele : validProcessorFeatures ) { this . validProcessorFeatures . add ( ele ) ; } return this ; |
public class FieldAccessor { /** * Retrieves the value of the field specified in this fluent interface .
* Examples :
* < pre >
* / / import static { @ link org . fest . reflect . core . Reflection # field ( String ) org . fest . reflect . core . Reflection . field } ;
* / / Retrieves the value of the field " name "
* String name = { @ link org . fest . reflect . core . Reflection # field ( String ) field } ( " name " ) . { @ link FieldName # ofType ( Class ) ofType } ( String . class ) . { @ link FieldType # in ( Object ) in } ( person ) . { @ link FieldAccessor # get ( ) get } ( ) ;
* / / Sets the value of the field " name " to " Yoda "
* { @ link org . fest . reflect . core . Reflection # field ( String ) field } ( " name " ) . { @ link FieldName # ofType ( Class ) ofType } ( String . class ) . { @ link FieldType # in ( Object ) in } ( person ) . { @ link FieldAccessor # set ( Object ) set } ( " Yoda " ) ;
* / / Retrieves the value of the field " powers "
* List & lt ; String & gt ; powers = { @ link org . fest . reflect . core . Reflection # field ( String ) field } ( " powers " ) . { @ link FieldName # ofType ( org . fest . reflect . reference . TypeRef ) ofType } ( new { @ link org . fest . reflect . reference . TypeRef TypeRef } & lt ; List & lt ; String & gt ; & gt ; ( ) { } ) . { @ link FieldTypeRef # in ( Object ) in } ( jedi ) . { @ link FieldAccessor # get ( ) get } ( ) ;
* / / Sets the value of the field " powers "
* List & lt ; String & gt ; powers = new ArrayList & lt ; String & gt ; ( ) ;
* powers . add ( " heal " ) ;
* { @ link org . fest . reflect . core . Reflection # field ( String ) field } ( " powers " ) . { @ link FieldName # ofType ( org . fest . reflect . reference . TypeRef ) ofType } ( new { @ link org . fest . reflect . reference . TypeRef TypeRef } & lt ; List & lt ; String & gt ; & gt ; ( ) { } ) . { @ link FieldTypeRef # in ( Object ) in } ( jedi ) . { @ link FieldAccessor # set ( Object ) set } ( powers ) ;
* / / Retrieves the value of the static field " count " in Person . class
* int count = { @ link org . fest . reflect . core . Reflection # field ( String ) field } ( " count " ) . { @ link org . fest . reflect . field . FieldName # ofType ( Class ) ofType } ( int . class ) . { @ link org . fest . reflect . field . FieldType # in ( Object ) in } ( Person . class ) . { @ link org . fest . reflect . field . FieldAccessor # get ( ) get } ( ) ;
* < / pre >
* @ return the value of the field in this fluent interface .
* @ throws ReflectionError if the value of the field cannot be retrieved . */
public @ Nullable T get ( ) { } } | Field f = checkNotNull ( field ) ; try { setAccessible ( f , true ) ; Object value = f . get ( target ) ; return castSafely ( value , checkNotNull ( fieldType ) ) ; } catch ( Throwable t ) { String msg = String . format ( "Failed to get the value of field '%s'" , f . getName ( ) ) ; throw new ReflectionError ( msg , t ) ; } finally { setAccessibleIgnoringExceptions ( f , accessible ) ; } |
public class Assert { /** * region Threading */
public static void assertDispatchQueue ( @ NonNull DispatchQueue queue ) { } } | if ( imp != null && ( queue == null || ! queue . isCurrent ( ) ) ) { imp . assertFailed ( StringUtils . format ( "Expected '%s' queue but was '%s'" , queue != null ? queue . getName ( ) : "<missing queue>" , Thread . currentThread ( ) . getName ( ) ) ) ; } |
public class ObjectType { /** * Detects a cycle in the implicit prototype chain . This method accesses
* the { @ link # getImplicitPrototype ( ) } method and must therefore be
* invoked only after the object is sufficiently initialized to respond to
* calls to this method . < p >
* @ return True iff an implicit prototype cycle was detected . */
final boolean detectImplicitPrototypeCycle ( ) { } } | // detecting cycle
this . visited = true ; ObjectType p = getImplicitPrototype ( ) ; while ( p != null ) { if ( p . visited ) { return true ; } else { p . visited = true ; } p = p . getImplicitPrototype ( ) ; } // clean up
p = this ; do { p . visited = false ; p = p . getImplicitPrototype ( ) ; } while ( p != null ) ; return false ; |
public class ListDashboardsResult { /** * The list of matching dashboards .
* @ param dashboardEntries
* The list of matching dashboards . */
public void setDashboardEntries ( java . util . Collection < DashboardEntry > dashboardEntries ) { } } | if ( dashboardEntries == null ) { this . dashboardEntries = null ; return ; } this . dashboardEntries = new com . amazonaws . internal . SdkInternalList < DashboardEntry > ( dashboardEntries ) ; |
public class Buffer { /** * Returns true if the buffer is dirty due to a modification by the
* specified transaction .
* @ param txNum
* the id of the transaction
* @ return true if the transaction modified the buffer */
boolean isModifiedBy ( long txNum ) { } } | internalLock . writeLock ( ) . lock ( ) ; try { return modifiedBy . contains ( txNum ) ; } finally { internalLock . writeLock ( ) . unlock ( ) ; } |
public class Context { /** * Report a runtime error using the error reporter for the current thread .
* @ param message the error message to report
* @ see org . mozilla . javascript . ErrorReporter */
public static EvaluatorException reportRuntimeError ( String message ) { } } | int [ ] linep = { 0 } ; String filename = getSourcePositionFromStack ( linep ) ; return Context . reportRuntimeError ( message , filename , linep [ 0 ] , null , 0 ) ; |
public class RegexRule { /** * 添加一个正则规则 正则规则有两种 , 正正则和反正则
* URL符合正则规则需要满足下面条件 : 1 . 至少能匹配一条正正则 2 . 不能和任何反正则匹配
* 正正则示例 : + a . * c是一条正正则 , 正则的内容为a . * c , 起始加号表示正正则
* 反正则示例 : - a . * c时一条反正则 , 正则的内容为a . * c , 起始减号表示反正则
* 如果一个规则的起始字符不为加号且不为减号 , 则该正则为正正则 , 正则的内容为自身
* 例如a . * c是一条正正则 , 正则的内容为a . * c
* @ param rule 正则规则
* @ return 自身 */
public RegexRule addRule ( String rule ) { } } | if ( rule . length ( ) == 0 ) { return this ; } char pn = rule . charAt ( 0 ) ; String realrule = rule . substring ( 1 ) ; if ( pn == '+' ) { addPositive ( realrule ) ; } else if ( pn == '-' ) { addNegative ( realrule ) ; } else { addPositive ( rule ) ; } return this ; |
public class CmdArgs { /** * Add an option
* @ param < T > Type of option
* @ param cls Option type class
* @ param name Option name Option name without
* @ param description Option description
* @ param exclusiveGroup A group of options . Only options of a single group
* are accepted .
* @ param mandatory */
public final < T > void addOption ( Class < T > cls , String name , String description , String exclusiveGroup , boolean mandatory ) { } } | if ( names . contains ( name ) ) { throw new IllegalArgumentException ( name + " is already added as argument" ) ; } Option opt = new Option ( cls , name , description , exclusiveGroup , mandatory ) ; Option old = map . put ( name , opt ) ; if ( old != null ) { throw new IllegalArgumentException ( name + " was already added" ) ; } if ( exclusiveGroup != null ) { groups . add ( exclusiveGroup , opt ) ; } |
public class Script { /** * AddMasterListeners Method . */
public void addMasterListeners ( ) { } } | super . addMasterListeners ( ) ; PropertiesField fldProperties = ( PropertiesField ) this . getField ( Script . PROPERTIES ) ; fldProperties . addPropertiesFieldBehavior ( this . getField ( Script . SOURCE_PARAM ) , SOURCE_PARAM ) ; fldProperties . addPropertiesFieldBehavior ( this . getField ( Script . DESTINATION_PARAM ) , DESTINATION_PARAM ) ; |
public class AmazonWebServiceClient { /** * Returns the most specific request metric collector , starting from the request level , then
* client level , then finally the AWS SDK level . */
private final RequestMetricCollector findRequestMetricCollector ( RequestMetricCollector reqLevelMetricsCollector ) { } } | RequestMetricCollector requestMetricCollector ; if ( reqLevelMetricsCollector != null ) { requestMetricCollector = reqLevelMetricsCollector ; } else if ( getRequestMetricsCollector ( ) != null ) { requestMetricCollector = getRequestMetricsCollector ( ) ; } else { requestMetricCollector = AwsSdkMetrics . getRequestMetricCollector ( ) ; } return requestMetricCollector ; |
public class SubmitReconciliationOrderReports { /** * Runs the example .
* @ param adManagerServices the services factory .
* @ param session the session .
* @ param reconciliationOrderReportId the ID of the reconciliation order report to submit .
* @ throws ApiException if the API request failed with one or more service errors .
* @ throws RemoteException if the API request failed due to other errors . */
public static void runExample ( AdManagerServices adManagerServices , AdManagerSession session , long reconciliationOrderReportId ) throws RemoteException { } } | // Get the ReconciliationOrderReportService .
ReconciliationOrderReportServiceInterface reconciliationOrderReportService = adManagerServices . get ( session , ReconciliationOrderReportServiceInterface . class ) ; // Create a statement to select reconciliation order reports .
StatementBuilder statementBuilder = new StatementBuilder ( ) . where ( "id = :id" ) . orderBy ( "id ASC" ) . limit ( 1 ) . withBindVariableValue ( "id" , reconciliationOrderReportId ) ; // Get reconciliation order reports by statement .
ReconciliationOrderReportPage page = reconciliationOrderReportService . getReconciliationOrderReportsByStatement ( statementBuilder . toStatement ( ) ) ; ReconciliationOrderReport reconciliationOrderReport = Iterables . getOnlyElement ( Arrays . asList ( page . getResults ( ) ) ) ; System . out . printf ( "Reconciliation order report with ID %d will be submitted.%n" , reconciliationOrderReport . getId ( ) ) ; // Remove limit and offset from statement .
statementBuilder . removeLimitAndOffset ( ) ; // Create action to submit reconciliation order reports .
com . google . api . ads . admanager . axis . v201808 . SubmitReconciliationOrderReports action = new com . google . api . ads . admanager . axis . v201808 . SubmitReconciliationOrderReports ( ) ; // Perform action .
UpdateResult result = reconciliationOrderReportService . performReconciliationOrderReportAction ( action , statementBuilder . toStatement ( ) ) ; if ( result != null && result . getNumChanges ( ) > 0 ) { System . out . printf ( "Number of reconciliation order reports submitted: %d%n" , result . getNumChanges ( ) ) ; } else { System . out . println ( "No reconciliation order reports were submitted." ) ; } |
public class ConditionMarshaller { /** * Marshall the given parameter object . */
public void marshall ( Condition condition , ProtocolMarshaller protocolMarshaller ) { } } | if ( condition == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( condition . getConditionType ( ) , CONDITIONTYPE_BINDING ) ; protocolMarshaller . marshall ( condition . getConditionKey ( ) , CONDITIONKEY_BINDING ) ; protocolMarshaller . marshall ( condition . getConditionValue ( ) , CONDITIONVALUE_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class AddressInfo { /** * Returns an { @ code AddressInfo } object for the provided region identity and name . The object
* corresponds to a region address . */
public static AddressInfo of ( RegionId regionId , String name ) { } } | return of ( RegionAddressId . of ( regionId , name ) ) ; |
public class ImgUtil { /** * 图像切片 ( 指定切片的宽度和高度 )
* @ param srcImageFile 源图像
* @ param descDir 切片目标文件夹
* @ param destWidth 目标切片宽度 。 默认200
* @ param destHeight 目标切片高度 。 默认150 */
public static void slice ( File srcImageFile , File descDir , int destWidth , int destHeight ) { } } | slice ( read ( srcImageFile ) , descDir , destWidth , destHeight ) ; |
public class ClassHelper { /** * Create an instance of a class .
* @ param type
* The class .
* @ param < T >
* The class type .
* @ return The instance . */
public static < T > T newInstance ( Class < T > type ) { } } | try { return type . newInstance ( ) ; } catch ( InstantiationException e ) { throw new XOException ( "Cannot create instance of type '" + type . getName ( ) + "'" , e ) ; } catch ( IllegalAccessException e ) { throw new XOException ( "Access denied to type '" + type . getName ( ) + "'" , e ) ; } |
public class TrieMap { /** * Removes the mapping for a key from this map if it is present and returns
* the value to which this map previously associated the key , or { @ code
* null } if the map contained no mapping for the key .
* @ param key key whose mapping is to be removed from the map
* @ return the previous value associated with key , or { @ code null } if there
* was no mapping for key . */
public V remove ( Object key ) { } } | checkKey ( key ) ; String cs = ( String ) key ; Node < V > n = lookup ( cs ) ; if ( n != null && n . isTerminal ( ) ) { V old = n . value ; n . value = null ; size -- ; return old ; } else { return ( n == null ) ? null : n . value ; } |
public class Lexer { /** * scan a string for interesting characters that might need further
* review . return the number of chars that are uninteresting and can
* be skipped .
* ( lth ) hi world , any thoughts on how to make this routine faster ? */
private void stringScan ( Bytes bytes ) { } } | int mask = IJC | NFP | ( validateUTF8 ? NUC : 0 ) ; long pos = bytes . readPosition ( ) ; long limit = bytes . readLimit ( ) ; while ( pos < limit && ( ( CHAR_LOOKUP_TABLE [ bytes . readUnsignedByte ( pos ) ] & mask ) == 0 ) ) { pos ++ ; } bytes . readPosition ( pos ) ; |
public class Iterate { /** * Flip the keys and values of the multimap . */
public static < K , V > UnifiedSetMultimap < V , K > flip ( SetMultimap < K , V > setMultimap ) { } } | final UnifiedSetMultimap < V , K > result = new UnifiedSetMultimap < V , K > ( ) ; setMultimap . forEachKeyMultiValues ( new Procedure2 < K , Iterable < V > > ( ) { public void value ( final K key , Iterable < V > values ) { Iterate . forEach ( values , new Procedure < V > ( ) { public void value ( V value ) { result . put ( value , key ) ; } } ) ; } } ) ; return result ; |
public class CassandraCpoAttribute { @ Override protected void initTransformClass ( CpoMetaDescriptor metaDescriptor ) throws CpoException { } } | super . initTransformClass ( metaDescriptor ) ; if ( getCpoTransform ( ) != null && getCpoTransform ( ) instanceof CassandraCpoTransform ) { cassandraTransform = ( CassandraCpoTransform ) getCpoTransform ( ) ; for ( Method m : findMethods ( cassandraTransform . getClass ( ) , TRANSFORM_OUT_NAME , 2 , true ) ) { if ( m . getParameterTypes ( ) [ 0 ] . getName ( ) . equals ( "org.synchronoss.cpo.cassandra.CassandraBoundStatementFactory" ) ) { transformPSOutMethod = m ; } } } // TODO Revisit this . Initializing the java sql type here . Not sure that this is the right place .
setDataTypeInt ( metaDescriptor . getDataTypeInt ( getDataType ( ) ) ) ; |
public class AmazonSimpleEmailServiceClient { /** * Creates a receipt rule set by cloning an existing one . All receipt rules and configurations are copied to the new
* receipt rule set and are completely independent of the source rule set .
* For information about setting up rule sets , see the < a
* href = " http : / / docs . aws . amazon . com / ses / latest / DeveloperGuide / receiving - email - receipt - rule - set . html " > Amazon SES
* Developer Guide < / a > .
* You can execute this operation no more than once per second .
* @ param cloneReceiptRuleSetRequest
* Represents a request to create a receipt rule set by cloning an existing one . You use receipt rule sets to
* receive email with Amazon SES . For more information , see the < a
* href = " http : / / docs . aws . amazon . com / ses / latest / DeveloperGuide / receiving - email - concepts . html " > Amazon SES
* Developer Guide < / a > .
* @ return Result of the CloneReceiptRuleSet operation returned by the service .
* @ throws RuleSetDoesNotExistException
* Indicates that the provided receipt rule set does not exist .
* @ throws AlreadyExistsException
* Indicates that a resource could not be created because of a naming conflict .
* @ throws LimitExceededException
* Indicates that a resource could not be created because of service limits . For a list of Amazon SES
* limits , see the < a href = " http : / / docs . aws . amazon . com / ses / latest / DeveloperGuide / limits . html " > Amazon SES
* Developer Guide < / a > .
* @ sample AmazonSimpleEmailService . CloneReceiptRuleSet
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / email - 2010-12-01 / CloneReceiptRuleSet " target = " _ top " > AWS API
* Documentation < / a > */
@ Override public CloneReceiptRuleSetResult cloneReceiptRuleSet ( CloneReceiptRuleSetRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeCloneReceiptRuleSet ( request ) ; |
public class StreamingJobsInner { /** * Creates a streaming job or replaces an already existing streaming job .
* @ param resourceGroupName The name of the resource group that contains the resource . You can obtain this value from the Azure Resource Manager API or the portal .
* @ param jobName The name of the streaming job .
* @ param streamingJob The definition of the streaming job that will be used to create a new streaming job or replace the existing one .
* @ param ifMatch The ETag of the streaming job . Omit this value to always overwrite the current record set . Specify the last - seen ETag value to prevent accidentally overwritting concurrent changes .
* @ param ifNoneMatch Set to ' * ' to allow a new streaming job to be created , but to prevent updating an existing record set . Other values will result in a 412 Pre - condition Failed response .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the StreamingJobInner object */
public Observable < StreamingJobInner > beginCreateOrReplaceAsync ( String resourceGroupName , String jobName , StreamingJobInner streamingJob , String ifMatch , String ifNoneMatch ) { } } | return beginCreateOrReplaceWithServiceResponseAsync ( resourceGroupName , jobName , streamingJob , ifMatch , ifNoneMatch ) . map ( new Func1 < ServiceResponseWithHeaders < StreamingJobInner , StreamingJobsCreateOrReplaceHeaders > , StreamingJobInner > ( ) { @ Override public StreamingJobInner call ( ServiceResponseWithHeaders < StreamingJobInner , StreamingJobsCreateOrReplaceHeaders > response ) { return response . body ( ) ; } } ) ; |
public class DescribeWorkspaceDirectoriesResult { /** * Information about the directories .
* @ return Information about the directories . */
public java . util . List < WorkspaceDirectory > getDirectories ( ) { } } | if ( directories == null ) { directories = new com . amazonaws . internal . SdkInternalList < WorkspaceDirectory > ( ) ; } return directories ; |
public class AbstractCertStoreInspector { /** * Finds the certificate of the SCEP message object recipient .
* @ param store
* the certificate store to inspect .
* @ return the recipient ' s certificate .
* @ throws CertStoreException
* if the CertStore cannot be inspected */
X509Certificate selectCertificate ( final CertStore store , final Collection < X509CertSelector > selectors ) throws CertStoreException { } } | for ( CertSelector selector : selectors ) { LOGGER . debug ( "Selecting certificate using {}" , selector ) ; Collection < ? extends Certificate > certs = store . getCertificates ( selector ) ; if ( certs . size ( ) > 0 ) { LOGGER . debug ( "Selected {} certificate(s) using {}" , certs . size ( ) , selector ) ; return ( X509Certificate ) certs . iterator ( ) . next ( ) ; } else { LOGGER . debug ( "No certificates selected" ) ; } } return ( X509Certificate ) store . getCertificates ( null ) . iterator ( ) . next ( ) ; |
public class ImagePainter { /** * The actual painting function . Draws the images with the object ' s id .
* @ param paintable
* A { @ link org . geomajas . gwt . client . gfx . paintable . Image } object .
* @ param group
* The group where the object resides in ( optional ) .
* @ param context
* A MapContext object , responsible for actual drawing . */
public void paint ( Paintable paintable , Object group , MapContext context ) { } } | Image image = ( Image ) paintable ; context . getVectorContext ( ) . drawImage ( group , image . getId ( ) , image . getHref ( ) , image . getBounds ( ) , image . getStyle ( ) ) ; |
public class ToastrSettings { /** * { @ inheritDoc } */
@ Override public Set < StringTextValue < ? > > asSet ( ) { } } | final Set < StringTextValue < ? > > allSettings = new HashSet < > ( ) ; allSettings . add ( getCloseButton ( ) ) ; allSettings . add ( getDebug ( ) ) ; allSettings . add ( getExtendedTimeOut ( ) ) ; allSettings . add ( getHideDuration ( ) ) ; allSettings . add ( getHideEasing ( ) ) ; allSettings . add ( getHideMethod ( ) ) ; allSettings . add ( getNewestOnTop ( ) ) ; allSettings . add ( getOnclick ( ) ) ; allSettings . add ( getPositionClass ( ) ) ; allSettings . add ( getPreventDuplicates ( ) ) ; allSettings . add ( getProgressBar ( ) ) ; allSettings . add ( getShowDuration ( ) ) ; allSettings . add ( getShowEasing ( ) ) ; allSettings . add ( getShowMethod ( ) ) ; allSettings . add ( getTapToDismiss ( ) ) ; allSettings . add ( getTimeOut ( ) ) ; allSettings . add ( getToastrType ( ) ) ; return allSettings ; |
public class MdlJsonConfigValidator { /** * Main .
* @ param pArgs command - line arguments */
public static void main ( @ Nonnull final String [ ] pArgs ) { } } | if ( pArgs . length == 0 ) { System . err . println ( "ModuleDirectoryLayout configuration file not specified." ) ; System . exit ( 1 ) ; } final File inputFile = Util . canonize ( new File ( pArgs [ 0 ] ) ) ; System . out . println ( "Checking " + inputFile ) ; MdlJsonConfig jsonConfig = null ; FileInputStream fis = null ; try { fis = new FileInputStream ( inputFile ) ; jsonConfig = ModuleDirectoryLayoutCheck . readConfigFile ( fis ) ; } catch ( IOException e ) { System . err . println ( e . getMessage ( ) ) ; System . exit ( 2 ) ; } finally { Util . closeQuietly ( fis ) ; } try { jsonConfig . validate ( ) ; } catch ( ConfigValidationException e ) { System . err . println ( "Error: " + e . getMessage ( ) ) ; System . exit ( 2 ) ; } System . out . println ( "ModuleDirectoryLayout configuration file OK" ) ; |
public class VMath { /** * Computes component - wise v1 + s1.
* @ param v1 vector to add to
* @ param s1 constant value to add
* @ return v1 + s1 */
public static double [ ] plus ( final double [ ] v1 , final double s1 ) { } } | final double [ ] result = new double [ v1 . length ] ; for ( int i = 0 ; i < result . length ; i ++ ) { result [ i ] = v1 [ i ] + s1 ; } return result ; |
public class SimulatorSettings { /** * Try N times to erase the device ( sleeping in between each attempt ) .
* If that fails , try shutting down the device and then erase again .
* If none of that worked , throw a WebDriverException with a detailed message . */
private void tryToEraseSimulator ( ) { } } | int numTries = 0 ; boolean successfulReset = false ; while ( ( ! successfulReset ) && ( numTries < NUMBER_TRIES_RESET_DEVICE ) ) { log . info ( "Wait " + SLEEP_TIME_BETWEEN_RESET_TRIES + " milliseconds before reattempt." ) ; try { Thread . sleep ( SLEEP_TIME_BETWEEN_RESET_TRIES ) ; } catch ( InterruptedException e ) { // ignored
} successfulReset = eraseSimulator ( ) ; numTries += 1 ; } if ( ! successfulReset ) { int totalWaitTime = SLEEP_TIME_BETWEEN_RESET_TRIES * NUMBER_TRIES_RESET_DEVICE ; String message = "Erase contents and settings still failed. Total waiting time: " + totalWaitTime + ". Now try to shutdown device: " + deviceUUID ; log . warning ( message ) ; Boolean successfulShutdown = shutdownDevice ( ) ; if ( successfulShutdown ) { successfulReset = eraseSimulator ( ) ; } if ( ! successfulReset ) { message = "Unable to erase contents and settings of this device: " + deviceUUID ; log . warning ( message ) ; // add more information to exception message
message += ". Tried " + NUMBER_TRIES_RESET_DEVICE + " times with with a waiting period of " + SLEEP_TIME_BETWEEN_RESET_TRIES + " millisecond between each attempt. " ; if ( ! successfulShutdown ) { message += "Also unable to shut down the device." ; } throw new WebDriverException ( message ) ; } } |
public class PTable { /** * Lock the current object ( Always called from the record class ) .
* Override this to return a valid flag . but remember to call inherited .
* @ param table The table .
* @ return true if successful , false is lock failed .
* @ exception DBException INVALID _ RECORD - Record not current . */
public synchronized int edit ( FieldTable table ) throws DBException { } } | this . saveCurrentKeys ( table , null , false ) ; return Constants . NORMAL_RETURN ; |
public class DataSourceConverter { /** * Get data source map .
* @ param dataSourceConfigurationMap data source configuration map
* @ return data source map */
public static Map < String , DataSource > getDataSourceMap ( final Map < String , DataSourceConfiguration > dataSourceConfigurationMap ) { } } | Map < String , DataSource > result = new LinkedHashMap < > ( dataSourceConfigurationMap . size ( ) , 1 ) ; for ( Entry < String , DataSourceConfiguration > entry : dataSourceConfigurationMap . entrySet ( ) ) { result . put ( entry . getKey ( ) , entry . getValue ( ) . createDataSource ( ) ) ; } return result ; |
public class JsonObjectUtils { /** * 参数错误 : Field
* @ param errors
* @ return */
public static JsonObjectBase buildFieldError ( Map < String , String > errors , ErrorCode statusCode ) { } } | JsonObjectError json = new JsonObjectError ( ) ; json . setStatus ( statusCode . getCode ( ) ) ; for ( String str : errors . keySet ( ) ) { json . addFieldError ( str , contextReader . getMessage ( errors . get ( str ) ) ) ; } LOG . info ( json . toString ( ) ) ; return json ; |
public class HttpPath { /** * Scans the path portion of the URI , i . e . everything after the
* host and port .
* @ param userPath the user ' s supplied path
* @ param attributes the attributes for the new path
* @ param uri the full uri for the new path .
* @ return the found path . */
public PathImpl fsWalk ( String userPath , Map < String , Object > attributes , String uri ) { } } | String path ; String query = null ; int queryIndex = uri . indexOf ( '?' ) ; if ( queryIndex >= 0 ) { path = uri . substring ( 0 , queryIndex ) ; query = uri . substring ( queryIndex + 1 ) ; } else path = uri ; if ( path . length ( ) == 0 ) path = "/" ; return create ( _root , userPath , attributes , path , query ) ; |
public class ResourcePath { /** * Gets level from parent use same logic ( but reverse ) as { @ link com . day . text . Text # getAbsoluteParent ( String , int ) } .
* @ param path Path
* @ return level & gt ; = 0 if path is value , - 1 if path is invalid */
public static int getAbsoluteLevel ( @ NotNull String path ) { } } | if ( StringUtils . isEmpty ( path ) || StringUtils . equals ( path , "/" ) ) { return - 1 ; } return StringUtils . countMatches ( path , "/" ) - 1 ; |
public class ThreadLocalSecureRandomUuidFactory { /** * / * package private */
static long toInt ( final byte [ ] buffer , final int initialOffset ) { } } | int offset = initialOffset ; return ( buffer [ offset ] << 24 ) + ( ( buffer [ ++ offset ] & 0xFF ) << 16 ) + ( ( buffer [ ++ offset ] & 0xFF ) << 8 ) + ( buffer [ ++ offset ] & 0xFF ) ; |
public class ChannelHelper { /** * ScatteringChannel support
* @ param channel
* @ param dsts
* @ return
* @ throws IOException */
public static final long read ( ReadableByteChannel channel , ByteBuffer [ ] dsts ) throws IOException { } } | return read ( channel , dsts , 0 , dsts . length ) ; |
public class Label { /** * Number of busy { @ link Executor } s that are carrying out some work right now . */
@ Exported public int getBusyExecutors ( ) { } } | int r = 0 ; for ( Node n : getNodes ( ) ) { Computer c = n . toComputer ( ) ; if ( c != null && c . isOnline ( ) ) r += c . countBusy ( ) ; } return r ; |
public class InteropFramework { /** * Write a { @ link Document } to file , serialized according to the file extension
* @ param filename path of the file to write the Document to
* @ param document a { @ link Document } to serialize */
public void writeDocument ( String filename , ProvFormat format , Document document ) { } } | Namespace . withThreadNamespace ( document . getNamespace ( ) ) ; try { logger . debug ( "writing " + format ) ; logger . debug ( "writing " + filename ) ; setNamespaces ( document ) ; switch ( format ) { case PROVN : { u . writeDocument ( document , filename , pFactory ) ; break ; } case XML : { ProvSerialiser serial = ProvSerialiser . getThreadProvSerialiser ( ) ; logger . debug ( "namespaces " + document . getNamespace ( ) ) ; serial . serialiseDocument ( new File ( filename ) , document , true ) ; break ; } case TURTLE : { new org . openprovenance . prov . rdf . Utility ( pFactory , onto ) . dumpRDF ( document , RDFFormat . TURTLE , filename ) ; break ; } case RDFXML : { new org . openprovenance . prov . rdf . Utility ( pFactory , onto ) . dumpRDF ( document , RDFFormat . RDFXML , filename ) ; break ; } case TRIG : { new org . openprovenance . prov . rdf . Utility ( pFactory , onto ) . dumpRDF ( document , RDFFormat . TRIG , filename ) ; break ; } case JSON : { new org . openprovenance . prov . json . Converter ( pFactory ) . writeDocument ( document , filename ) ; break ; } case DOT : { String configFile = null ; // TODO : get it as option
ProvToDot toDot = ( configFile == null ) ? new ProvToDot ( ProvToDot . Config . ROLE_NO_LABEL ) : new ProvToDot ( configFile ) ; toDot . setLayout ( layout ) ; toDot . convert ( document , filename , title ) ; break ; } case PDF : case JPEG : case PNG : case SVG : { String configFile = null ; // give it as option
File tmp = File . createTempFile ( "viz-" , ".dot" ) ; String dotFileOut = tmp . getAbsolutePath ( ) ; // give it as option ,
// if not available
// create tmp file
ProvToDot toDot ; if ( configFile != null ) { toDot = new ProvToDot ( configFile ) ; } else { toDot = new ProvToDot ( ProvToDot . Config . ROLE_NO_LABEL ) ; } toDot . setLayout ( layout ) ; toDot . convert ( document , dotFileOut , filename , extensionMap . get ( format ) , title ) ; tmp . delete ( ) ; break ; } default : break ; } } catch ( JAXBException e ) { if ( verbose != null ) e . printStackTrace ( ) ; throw new InteropException ( e ) ; } catch ( IOException e ) { if ( verbose != null ) e . printStackTrace ( ) ; throw new InteropException ( e ) ; } |
public class ConstantPool { /** * Adds a field ref constant . */
public FieldRefConstant addFieldRef ( String className , String name , String type ) { } } | FieldRefConstant entry = getFieldRef ( className , name , type ) ; if ( entry != null ) return entry ; ClassConstant classEntry = addClass ( className ) ; NameAndTypeConstant typeEntry = addNameAndType ( name , type ) ; entry = new FieldRefConstant ( this , _entries . size ( ) , classEntry . getIndex ( ) , typeEntry . getIndex ( ) ) ; addConstant ( entry ) ; return entry ; |
public class DJGroupRegistrationManager { /** * PropertyColumn only can be used for grouping ( not OperationColumn ) */
protected Object transformEntity ( Entity entity ) throws JRException { } } | // log . debug ( " transforming group . . . " ) ;
DJGroup djgroup = ( DJGroup ) entity ; PropertyColumn column = djgroup . getColumnToGroupBy ( ) ; JRDesignGroup group = new JRDesignGroup ( ) ; group . setName ( djgroup . getName ( ) ) ; getLayoutManager ( ) . getReferencesMap ( ) . put ( group . getName ( ) , djgroup ) ; group . setCountVariable ( new JRDesignVariable ( ) ) ; JRDesignSection gfs = ( JRDesignSection ) group . getGroupFooterSection ( ) ; gfs . getBandsList ( ) . add ( new JRDesignBand ( ) ) ; JRDesignSection ghs = ( JRDesignSection ) group . getGroupHeaderSection ( ) ; ghs . getBandsList ( ) . add ( new JRDesignBand ( ) ) ; JRDesignExpression jrExpression = new JRDesignExpression ( ) ; CustomExpression expressionToGroupBy = column . getExpressionToGroupBy ( ) ; if ( expressionToGroupBy != null ) { // new in 3.0.7 - b5
useVariableForCustomExpression ( group , jrExpression , expressionToGroupBy ) ; } else { if ( column instanceof ExpressionColumn ) { ExpressionColumn col = ( ExpressionColumn ) column ; CustomExpression customExpression = col . getExpression ( ) ; useVariableForCustomExpression ( group , jrExpression , customExpression ) ; } else { jrExpression . setText ( column . getTextForExpression ( ) ) ; jrExpression . setValueClassName ( column . getValueClassNameForExpression ( ) ) ; } } group . setExpression ( jrExpression ) ; return group ; |
public class JsonArray { /** * Retrieves the nth element in the array as integer . < br >
* If it is neither { @ code null } nor a { @ link Long } , { @ link IllegalStateException } will be thrown .
* @ param index
* @ return The element
* @ throws IllegalStateException The given index points neither { @ code null } nor a { @ link Long } .
* @ author vvakame */
public Long getLongOrNull ( int index ) throws IllegalStateException { } } | Type type = stateList . get ( index ) ; if ( type == null ) { return null ; } switch ( type ) { case NULL : return null ; case LONG : Object obj = get ( index ) ; if ( obj instanceof Integer ) { return ( long ) ( Integer ) obj ; } else if ( obj instanceof Long ) { return ( Long ) obj ; } else if ( obj instanceof Byte ) { return ( long ) ( Byte ) obj ; } else if ( obj instanceof Short ) { return ( long ) ( Short ) obj ; } else { throw new IllegalStateException ( "unexpected class. class=" + obj . getClass ( ) . getCanonicalName ( ) ) ; } default : throw new IllegalStateException ( "unexpected token. token=" + type ) ; } |
public class Waehrung { /** * Validiert den uebergebenen Waehrungscode .
* @ param code Waehrungscode als String
* @ return Waehrungscode zur Weiterverarbeitung */
public static String validate ( String code ) { } } | try { toCurrency ( code ) ; } catch ( IllegalArgumentException ex ) { throw new InvalidValueException ( code , "currency" ) ; } return code ; |
public class AWSAppSyncClient { /** * Deletes a < code > Type < / code > object .
* @ param deleteTypeRequest
* @ return Result of the DeleteType operation returned by the service .
* @ throws BadRequestException
* The request is not well formed . For example , a value is invalid or a required field is missing . Check the
* field values , and then try again .
* @ throws ConcurrentModificationException
* Another modification is in progress at this time and it must complete before you can make your change .
* @ throws NotFoundException
* The resource specified in the request was not found . Check the resource , and then try again .
* @ throws UnauthorizedException
* You are not authorized to perform this operation .
* @ throws InternalFailureException
* An internal AWS AppSync error occurred . Try your request again .
* @ sample AWSAppSync . DeleteType
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / appsync - 2017-07-25 / DeleteType " target = " _ top " > AWS API
* Documentation < / a > */
@ Override public DeleteTypeResult deleteType ( DeleteTypeRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeDeleteType ( request ) ; |
public class CommonOps_DSCC { /** * Zeros an inner rectangle inside the matrix .
* @ param A Matrix that is to be modified .
* @ param row0 Start row .
* @ param row1 Stop row + 1.
* @ param col0 Start column .
* @ param col1 Stop column + 1. */
public static void zero ( DMatrixSparseCSC A , int row0 , int row1 , int col0 , int col1 ) { } } | for ( int col = col1 - 1 ; col >= col0 ; col -- ) { int numRemoved = 0 ; int idx0 = A . col_idx [ col ] , idx1 = A . col_idx [ col + 1 ] ; for ( int i = idx0 ; i < idx1 ; i ++ ) { int row = A . nz_rows [ i ] ; // if sorted a faster technique could be used
if ( row >= row0 && row < row1 ) { numRemoved ++ ; } else if ( numRemoved > 0 ) { A . nz_rows [ i - numRemoved ] = row ; A . nz_values [ i - numRemoved ] = A . nz_values [ i ] ; } } if ( numRemoved > 0 ) { // this could be done more intelligently . Each time a column is adjusted all the columns are adjusted
// after it . Maybe accumulate the changes in each column and do it in one pass ? Need an array to store
// those results though
for ( int i = idx1 ; i < A . nz_length ; i ++ ) { A . nz_rows [ i - numRemoved ] = A . nz_rows [ i ] ; A . nz_values [ i - numRemoved ] = A . nz_values [ i ] ; } A . nz_length -= numRemoved ; for ( int i = col + 1 ; i <= A . numCols ; i ++ ) { A . col_idx [ i ] -= numRemoved ; } } } |
public class PermissionManager { /** * Check if this is a restricted permission .
* @ param permission
* @ return < code > true < / code > if the permission is restricted */
private boolean isRestricted ( Permission permission ) { } } | for ( Permission restrictedPermission : restrictablePermissions ) { if ( restrictedPermission . implies ( permission ) ) { return true ; } } return false ; |
public class WstxSAXParser { /** * XLMReader ( SAX2 ) implementation : parsing */
@ SuppressWarnings ( "resource" ) @ Override public void parse ( InputSource input ) throws SAXException { } } | mScanner = null ; String sysIdStr = input . getSystemId ( ) ; ReaderConfig cfg = mConfig ; URL srcUrl = null ; // Let ' s figure out input , first , before sending start - doc event
InputStream is = null ; Reader r = input . getCharacterStream ( ) ; if ( r == null ) { is = input . getByteStream ( ) ; if ( is == null ) { if ( sysIdStr == null ) { throw new SAXException ( "Invalid InputSource passed: neither character or byte stream passed, nor system id specified" ) ; } try { srcUrl = URLUtil . urlFromSystemId ( sysIdStr ) ; is = URLUtil . inputStreamFromURL ( srcUrl ) ; } catch ( IOException ioe ) { SAXException saxe = new SAXException ( ioe ) ; ExceptionUtil . setInitCause ( saxe , ioe ) ; throw saxe ; } } } if ( mContentHandler != null ) { mContentHandler . setDocumentLocator ( this ) ; mContentHandler . startDocument ( ) ; } /* Note : since we are reusing the same config instance , need to
* make sure state is not carried forward . Thus : */
cfg . resetState ( ) ; try { String inputEnc = input . getEncoding ( ) ; String publicId = input . getPublicId ( ) ; // Got an InputStream and encoding ? Can create a Reader :
if ( r == null && ( inputEnc != null && inputEnc . length ( ) > 0 ) ) { r = DefaultInputResolver . constructOptimizedReader ( cfg , is , false , inputEnc ) ; } InputBootstrapper bs ; SystemId systemId = SystemId . construct ( sysIdStr , srcUrl ) ; if ( r != null ) { bs = ReaderBootstrapper . getInstance ( publicId , systemId , r , inputEnc ) ; // false - > not for event reader ; false - > no auto - closing
mScanner = ( BasicStreamReader ) mStaxFactory . createSR ( cfg , systemId , bs , false , false ) ; } else { bs = StreamBootstrapper . getInstance ( publicId , systemId , is ) ; mScanner = ( BasicStreamReader ) mStaxFactory . createSR ( cfg , systemId , bs , false , false ) ; } // Need to get xml declaration stuff out now :
{ String enc2 = mScanner . getEncoding ( ) ; if ( enc2 == null ) { enc2 = mScanner . getCharacterEncodingScheme ( ) ; } mEncoding = enc2 ; } mXmlVersion = mScanner . getVersion ( ) ; mStandalone = mScanner . standaloneSet ( ) ; mAttrCollector = mScanner . getAttributeCollector ( ) ; mElemStack = mScanner . getInputElementStack ( ) ; fireEvents ( ) ; } catch ( IOException io ) { throwSaxException ( io ) ; } catch ( XMLStreamException strex ) { throwSaxException ( strex ) ; } finally { if ( mContentHandler != null ) { mContentHandler . endDocument ( ) ; } // Could try holding onto the buffers , too . . . but
// maybe it ' s better to allow them to be reclaimed , if
// needed by GC
if ( mScanner != null ) { BasicStreamReader sr = mScanner ; mScanner = null ; try { sr . close ( ) ; } catch ( XMLStreamException sex ) { } } if ( r != null ) { try { r . close ( ) ; } catch ( IOException ioe ) { } } if ( is != null ) { try { is . close ( ) ; } catch ( IOException ioe ) { } } } |
public class JBEANBOX { /** * Equal to " @ VALUE " annotation */
public static BeanBox value ( Object value , boolean pureValue , boolean required ) { } } | return new BeanBox ( ) . setTarget ( value ) . setPureValue ( pureValue ) . setRequired ( required ) ; |
public class Matrix3x2d { /** * Apply a " view " transformation to this matrix that maps the given < code > ( left , bottom ) < / code > and
* < code > ( right , top ) < / code > corners to < code > ( - 1 , - 1 ) < / code > and < code > ( 1 , 1 ) < / code > respectively and store the result in < code > dest < / code > .
* If < code > M < / code > is < code > this < / code > matrix and < code > O < / code > the orthographic projection matrix ,
* then the new matrix will be < code > M * O < / code > . So when transforming a
* vector < code > v < / code > with the new matrix by using < code > M * O * v < / code > , the
* orthographic projection transformation will be applied first !
* @ see # setView ( double , double , double , double )
* @ param left
* the distance from the center to the left view edge
* @ param right
* the distance from the center to the right view edge
* @ param bottom
* the distance from the center to the bottom view edge
* @ param top
* the distance from the center to the top view edge
* @ param dest
* will hold the result
* @ return dest */
public Matrix3x2d view ( double left , double right , double bottom , double top , Matrix3x2d dest ) { } } | double rm00 = 2.0 / ( right - left ) ; double rm11 = 2.0 / ( top - bottom ) ; double rm20 = ( left + right ) / ( left - right ) ; double rm21 = ( bottom + top ) / ( bottom - top ) ; dest . m20 = m00 * rm20 + m10 * rm21 + m20 ; dest . m21 = m01 * rm20 + m11 * rm21 + m21 ; dest . m00 = m00 * rm00 ; dest . m01 = m01 * rm00 ; dest . m10 = m10 * rm11 ; dest . m11 = m11 * rm11 ; return dest ; |
public class Estimate { public static CreateSubscriptionRequest createSubscription ( ) throws IOException { } } | String uri = uri ( "estimates" , "create_subscription" ) ; return new CreateSubscriptionRequest ( Method . POST , uri ) ; |
public class Reflections { /** * Returns the parameterized type of a class , if exists . Wild cards , type
* variables and raw types will be returned as an empty list .
* If a field is of type Set < String > then java . lang . String is returned .
* If a field is of type Map < String , Integer > then [ java . lang . String ,
* java . lang . Integer ] is returned .
* @ param ownerClass the implementing target class to check against
* @ param ownerClass generic interface to resolve the type argument from
* @ return A list of classes of the parameterized type . */
public static List < Class < ? > > getParameterizedType ( final Class < ? > ownerClass , Class < ? > genericSuperClass ) { } } | Type [ ] types = null ; if ( genericSuperClass . isInterface ( ) ) { types = ownerClass . getGenericInterfaces ( ) ; } else { types = new Type [ ] { ownerClass . getGenericSuperclass ( ) } ; } List < Class < ? > > classes = new ArrayList < > ( ) ; for ( Type type : types ) { if ( ! ParameterizedType . class . isAssignableFrom ( type . getClass ( ) ) ) { // the field is it a raw type and does not have generic type
// argument . Return empty list .
return new ArrayList < Class < ? > > ( ) ; } ParameterizedType ptype = ( ParameterizedType ) type ; Type [ ] targs = ptype . getActualTypeArguments ( ) ; for ( Type aType : targs ) { classes . add ( extractClass ( ownerClass , aType ) ) ; } } return classes ; |
public class Conversion { /** * Converts a long into an array of Char using the default ( little endian , Lsb0 ) byte and
* bit ordering .
* @ param src the long to convert
* @ param srcPos the position in { @ code src } , in bits , from where to start the conversion
* @ param dstInit the initial value for the result String
* @ param dstPos the position in { @ code dst } where to copy the result
* @ param nHexs the number of Chars to copy to { @ code dst } , must be smaller or equal to the
* width of the input ( from srcPos to msb )
* @ return { @ code dst }
* @ throws IllegalArgumentException if { @ code ( nHexs - 1 ) * 4 + srcPos > = 64}
* @ throws StringIndexOutOfBoundsException if { @ code dst . init . length ( ) < dstPos } */
public static String longToHex ( final long src , final int srcPos , final String dstInit , final int dstPos , final int nHexs ) { } } | if ( 0 == nHexs ) { return dstInit ; } if ( ( nHexs - 1 ) * 4 + srcPos >= 64 ) { throw new IllegalArgumentException ( "(nHexs-1)*4+srcPos is greater or equal to than 64" ) ; } final StringBuilder sb = new StringBuilder ( dstInit ) ; int append = sb . length ( ) ; for ( int i = 0 ; i < nHexs ; i ++ ) { final int shift = i * 4 + srcPos ; final int bits = ( int ) ( 0xF & ( src >> shift ) ) ; if ( dstPos + i == append ) { ++ append ; sb . append ( intToHexDigit ( bits ) ) ; } else { sb . setCharAt ( dstPos + i , intToHexDigit ( bits ) ) ; } } return sb . toString ( ) ; |
public class OcniExtractor { /** * Finds all block comments and associates them with their containing type .
* This is trickier than you might expect because of inner types . */
private static ListMultimap < TreeNode , Comment > findBlockComments ( CompilationUnit unit ) { } } | ListMultimap < TreeNode , Comment > blockComments = MultimapBuilder . hashKeys ( ) . arrayListValues ( ) . build ( ) ; for ( Comment comment : unit . getCommentList ( ) ) { if ( ! comment . isBlockComment ( ) ) { continue ; } int commentPos = comment . getStartPosition ( ) ; AbstractTypeDeclaration containingType = null ; int containingTypePos = - 1 ; for ( AbstractTypeDeclaration type : unit . getTypes ( ) ) { int typePos = type . getStartPosition ( ) ; if ( typePos < 0 ) { continue ; } int typeEnd = typePos + type . getLength ( ) ; if ( commentPos > typePos && commentPos < typeEnd && typePos > containingTypePos ) { containingType = type ; containingTypePos = typePos ; } } blockComments . put ( containingType != null ? containingType : unit , comment ) ; } return blockComments ; |
public class Duration { /** * Create a duration with the specified number of hours assuming that
* there are the standard number of milliseconds in an hour .
* This method assumes that there are 60 minutes in an hour ,
* 60 seconds in a minute and 1000 milliseconds in a second .
* All currently supplied chronologies use this definition .
* A Duration is a representation of an amount of time . If you want to express
* the concept of ' hours ' you should consider using the { @ link Hours } class .
* @ param hours the number of standard hours in this duration
* @ return the duration , never null
* @ throws ArithmeticException if the hours value is too large
* @ since 1.6 */
public static Duration standardHours ( long hours ) { } } | if ( hours == 0 ) { return ZERO ; } return new Duration ( FieldUtils . safeMultiply ( hours , DateTimeConstants . MILLIS_PER_HOUR ) ) ; |
public class HBaseDataHandler { /** * ( non - Javadoc )
* @ see
* com . impetus . client . hbase . admin . DataHandler # deleteRow ( java . lang . String ,
* java . lang . String ) */
public void deleteRow ( Object rowKey , String tableName , String columnFamilyName ) throws IOException { } } | hbaseWriter . delete ( gethTable ( tableName ) , rowKey , columnFamilyName ) ; |
public class WeekPeriod { /** * 返回与指定时间点相差的秒数 .
* @ return */
public int getSeconds ( ) { } } | // TODO ahai 未做测试
Calendar cld = Calendar . getInstance ( ) ; cld . set ( Calendar . DAY_OF_WEEK , this . weekday + 1 ) ; cld . set ( Calendar . HOUR_OF_DAY , this . hour ) ; cld . set ( Calendar . MINUTE , this . minute ) ; cld . set ( Calendar . SECOND , this . second ) ; long time = cld . getTimeInMillis ( ) ; // System . out . println ( " time : " +
// DateUtil . getTime ( DateUtil . toDate ( time ) ) ) ;
long diff = time - System . currentTimeMillis ( ) ; if ( diff <= 0 ) { // 一定要小于等于0
// 本周的时间已过 , 下周再执行
diff += 7 * 24 * 60 * 60 * 1000L ; } int seconds = ( int ) ( diff / 1000 ) ; return seconds ; |
public class ConstructorResultImpl { /** * If not already created , a new < code > column < / code > element will be created and returned .
* Otherwise , the first existing < code > column < / code > element will be returned .
* @ return the instance defined for the element < code > column < / code > */
public ColumnResult < ConstructorResult < T > > getOrCreateColumn ( ) { } } | List < Node > nodeList = childNode . get ( "column" ) ; if ( nodeList != null && nodeList . size ( ) > 0 ) { return new ColumnResultImpl < ConstructorResult < T > > ( this , "column" , childNode , nodeList . get ( 0 ) ) ; } return createColumn ( ) ; |
public class MapUtils { /** * Sorts the provided Map by the value instead of by key like TreeMap does .
* The Value - Type needs to implement the Comparable - interface .
* Note : this will require one Map . Entry for each element in the Map , so for very large
* Maps this will incur some memory overhead but will not fully duplicate the contents of the map .
* @ param < K > the key - type of the Map that should be sorted
* @ param < V > the value - type of the Map that should be sorted . Needs to derive from { @ link Comparable }
* @ param map A map with some elements which should be sorted by Value .
* @ return Returns a new List of Map . Entry values sorted by value . */
public static < K , V extends Comparable < V > > List < Entry < K , V > > sortByValue ( Map < K , V > map ) { } } | List < Entry < K , V > > entries = new ArrayList < > ( map . entrySet ( ) ) ; entries . sort ( new ByValue < > ( ) ) ; return entries ; |
public class FavorAdapter { /** * Create an implementation of the API defined by the specified { @ code service } interface . */
@ SuppressWarnings ( "unchecked" ) public < T > T create ( Class < T > service ) { } } | validateServiceClass ( service ) ; for ( Annotation annotation : service . getDeclaredAnnotations ( ) ) { if ( annotation . annotationType ( ) == AllFavor . class ) allFavor = true ; } return ( T ) Proxy . newProxyInstance ( service . getClassLoader ( ) , new Class < ? > [ ] { service } , new FavorHandler ( getMethodInfoCache ( service ) ) ) ; |
public class AbstractBuffer { /** * Checks bounds for a slice . */
protected long checkSlice ( long offset , long length ) { } } | checkOffset ( offset ) ; if ( limit == - 1 ) { if ( offset + length > capacity ) { if ( capacity < maxCapacity ) { capacity ( calculateCapacity ( offset + length ) ) ; } else { throw new BufferUnderflowException ( ) ; } } } else { if ( offset + length > limit ) throw new BufferUnderflowException ( ) ; } return offset ( offset ) ; |
public class ServletWrapper { /** * Method unload */
public void unload ( ) throws Exception { } } | if ( com . ibm . ejs . ras . TraceComponent . isAnyTracingEnabled ( ) && logger . isLoggable ( Level . FINE ) ) // 306998.15
logger . entering ( CLASS_NAME , "unload className-->[" + servletConfig . getClassName ( ) + "], servletName[" + servletConfig . getServletName ( ) + "]" ) ; // 569469
// logger . logp ( Level . FINE , CLASS _ NAME , " unload " ,
// " entry className - - > [ " + servletConfig . getClassName ( ) + " ] , servletName [ " + servletConfig . getServletName ( ) + " ] " ) ;
// / / PK26183
if ( state == UNINITIALIZED_STATE ) { return ; } try { doDestroy ( ) ; } catch ( Throwable th ) { com . ibm . wsspi . webcontainer . util . FFDCWrapper . processException ( th , "com.ibm.ws.webcontainer.servlet.ServletWrapper.unload" , "1511" , this ) ; logger . logp ( Level . SEVERE , CLASS_NAME , "unload" , "Exception.occured.during.servlet.unload" , th ) ; } finally { /* * 125087 : Do not explicitly null out the servlet instance or its classloader . These should
* be GCed when the wrapper itself is garbage collected . */
// target = null ;
// targetLoader = null ;
invalidateCacheWrappers ( ) ; state = UNINITIALIZED_STATE ; } if ( com . ibm . ejs . ras . TraceComponent . isAnyTracingEnabled ( ) && logger . isLoggable ( Level . FINE ) ) // 306998.15
logger . exiting ( CLASS_NAME , "unload" ) ; // 569469 |
public class AbstractFormPage { /** * Sets the form to the bean passed in , updating the form via AJAX .
* @ param bean the bean to set the form to .
* @ param target the target of whatever triggers the form fill action . */
protected void setForm ( final T bean , final AjaxRequestTarget target ) { } } | LOG . debug ( "Setting form to {}" , bean ) ; // update the model with the new bean
formModel . setObject ( bean ) ; // add the form to the target
target . add ( form ) ; // update the button
updateSaveButton . setModel ( Model . of ( "Update" ) ) ; target . add ( updateSaveButton ) ; |
public class MyFacesExceptionHandlerWrapperImpl { /** * { @ inheritDoc } */
@ Override public void handle ( ) throws FacesException { } } | init ( ) ; if ( ! isUseMyFacesErrorHandling ( ) ) { if ( isErrorPagePresent ( ) ) { FacesContext facesContext = FacesContext . getCurrentInstance ( ) ; // save current view in the request map to access it on the error page
facesContext . getExternalContext ( ) . getRequestMap ( ) . put ( ErrorPageWriter . VIEW_KEY , facesContext . getViewRoot ( ) ) ; } try { super . handle ( ) ; } catch ( FacesException e ) { FacesContext facesContext = FacesContext . getCurrentInstance ( ) ; if ( e . getCause ( ) instanceof ViewNotFoundException ) { facesContext . getExternalContext ( ) . setResponseStatus ( HttpServletResponse . SC_NOT_FOUND ) ; } else { facesContext . getExternalContext ( ) . setResponseStatus ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR ) ; } throw e ; } return ; } else { if ( unhandled != null && ! unhandled . isEmpty ( ) ) { if ( handled == null ) { handled = new LinkedList < ExceptionQueuedEvent > ( ) ; } List < Throwable > throwableList = new ArrayList < Throwable > ( ) ; List < UIComponent > components = new ArrayList < UIComponent > ( ) ; FacesContext facesContext = null ; do { // For each ExceptionEvent in the list
// get the event to handle
ExceptionQueuedEvent event = unhandled . peek ( ) ; try { // call its getContext ( ) method
ExceptionQueuedEventContext context = event . getContext ( ) ; if ( facesContext == null ) { facesContext = event . getContext ( ) . getContext ( ) ; } // and call getException ( ) on the returned result
Throwable exception = context . getException ( ) ; // Upon encountering the first such Exception that is not an instance of
// javax . faces . event . AbortProcessingException
if ( ! shouldSkip ( exception ) ) { // set handledAndThrown so that getHandledExceptionQueuedEvent ( ) returns this event
handledAndThrown = event ; Throwable rootCause = getRootCause ( exception ) ; throwableList . add ( rootCause == null ? exception : rootCause ) ; components . add ( event . getContext ( ) . getComponent ( ) ) ; // break ;
} else { // Testing mojarra it logs a message and the exception
// however , this behaviour is not mentioned in the spec
log . log ( Level . SEVERE , exception . getClass ( ) . getName ( ) + " occured while processing " + ( context . inBeforePhase ( ) ? "beforePhase() of " : ( context . inAfterPhase ( ) ? "afterPhase() of " : "" ) ) + "phase " + context . getPhaseId ( ) + ": " + "UIComponent-ClientId=" + ( context . getComponent ( ) != null ? context . getComponent ( ) . getClientId ( context . getContext ( ) ) : "" ) + ", " + "Message=" + exception . getMessage ( ) ) ; log . log ( Level . SEVERE , exception . getMessage ( ) , exception ) ; } } finally { // if we will throw the Exception or if we just logged it ,
// we handled it in either way - - > add to handled
handled . add ( event ) ; unhandled . remove ( event ) ; } } while ( ! unhandled . isEmpty ( ) ) ; if ( facesContext == null ) { facesContext = FacesContext . getCurrentInstance ( ) ; } if ( throwableList . size ( ) == 1 ) { ErrorPageWriter . handle ( facesContext , components , throwableList . get ( 0 ) ) ; } else if ( throwableList . size ( ) > 1 ) { ErrorPageWriter . handle ( facesContext , components , throwableList . toArray ( new Throwable [ throwableList . size ( ) ] ) ) ; } } } |
public class AccountPasswordFormValidator { /** * NB : This validation method correctly matches a state defined in the
* edit - account flow , but there doesn ' t appear currently to be a way to
* enter it . */
public void validateEnterPassword ( AccountPasswordForm form , MessageContext context ) { } } | // ensure that a current account password was entered
if ( StringUtils . isBlank ( form . getCurrentPassword ( ) ) ) { context . addMessage ( new MessageBuilder ( ) . error ( ) . source ( "currentPassword" ) . code ( "please.enter.current.password" ) . defaultText ( "Please enter your current password" ) . build ( ) ) ; } // check to see if the provided password matches the current account
// password
else { ILocalAccountPerson account = accountDao . getPerson ( form . getUserId ( ) ) ; if ( ! passwordService . validatePassword ( form . getCurrentPassword ( ) , account . getPassword ( ) ) ) { context . addMessage ( new MessageBuilder ( ) . error ( ) . source ( "currentPassword" ) . code ( "current.password.doesnt.match" ) . defaultText ( "Provided password does not match the current account password" ) . build ( ) ) ; } } // ensure a new account password was entered
if ( StringUtils . isBlank ( form . getNewPassword ( ) ) ) { context . addMessage ( new MessageBuilder ( ) . error ( ) . source ( "newPassword" ) . code ( "please.enter.new.password" ) . defaultText ( "Please enter a new password" ) . build ( ) ) ; } // ensure a new account password confirmation was entered
if ( StringUtils . isBlank ( form . getConfirmNewPassword ( ) ) ) { context . addMessage ( new MessageBuilder ( ) . error ( ) . source ( "confirmNewPassword" ) . code ( "please.enter.confirm.password" ) . defaultText ( "Please confirm your new password" ) . build ( ) ) ; } // ensure the new password and new password confirmation match
if ( StringUtils . isNotBlank ( form . getNewPassword ( ) ) && StringUtils . isNotBlank ( form . getConfirmNewPassword ( ) ) && ! form . getNewPassword ( ) . equals ( form . getConfirmNewPassword ( ) ) ) { context . addMessage ( new MessageBuilder ( ) . error ( ) . source ( "confirmPassword" ) . code ( "passwords.must.match" ) . defaultText ( "Passwords must match" ) . build ( ) ) ; } |
public class AESUtil { /** * Encrypt .
* @ param data the data
* @ param key the key
* @ return the string */
public static String encrypt ( String data , byte [ ] key ) { } } | try { Key k = toSecretKey ( key ) ; Cipher cipher = Cipher . getInstance ( CIPHER_ALGORITHM ) ; cipher . init ( Cipher . ENCRYPT_MODE , k ) ; byte [ ] toByteArray = data . getBytes ( ) ; byte [ ] encrypted = cipher . doFinal ( toByteArray ) ; return Hex . encodeHexString ( encrypted ) ; } catch ( GeneralSecurityException e ) { throw new RuntimeException ( "Failed to encrypt." , e ) ; } |
public class Output { /** * { @ inheritDoc } */
@ Override protected void writeArbitraryObject ( Object object ) { } } | log . debug ( "writeArbitraryObject: {}" , object ) ; Class < ? > objectClass = object . getClass ( ) ; // If we need to serialize class information . . .
if ( ! objectClass . isAnnotationPresent ( Anonymous . class ) ) { putString ( Serializer . getClassName ( objectClass ) ) ; } else { putString ( "" ) ; } // Store key / value pairs
amf3_mode += 1 ; // Iterate thru fields of an object to build " name - value " map from it
for ( Field field : objectClass . getFields ( ) ) { String fieldName = field . getName ( ) ; log . debug ( "Field: {} class: {}" , field , objectClass ) ; // Check if the Field corresponding to the getter / setter pair is transient
if ( ! serializeField ( objectClass , fieldName , field , null ) ) { continue ; } Object value ; try { // Get field value
value = field . get ( object ) ; } catch ( IllegalAccessException err ) { // Swallow on private and protected properties access exception
continue ; } // Write out prop name
putString ( fieldName ) ; // Write out
Serializer . serialize ( this , field , null , object , value ) ; } amf3_mode -= 1 ; // Write out end of object marker
putString ( "" ) ; |
public class WeakCounterImpl { /** * Initializes the key set .
* Only one key will have the initial value and the remaining is zero . */
public void init ( ) { } } | registerListener ( ) ; for ( int i = 0 ; i < entries . length ; ++ i ) { final int index = i ; awaitCounterOperation ( readOnlyMap . eval ( entries [ index ] . key , ReadFunction . getInstance ( ) ) . thenAccept ( value -> initEntry ( index , value ) ) ) ; } selector . updatePreferredKeys ( ) ; |
public class InterceptorMetaDataFactory { /** * Get the array of InterceptorProxy objects required for invoking the
* AroundInvoke or AroundTimeout interceptors methods when a method is invoked .
* @ param kind the interceptor kind ; must be either AROUND _ INVOKE or AROUND _ TIMEOUT
* @ param m the method
* @ return array of InterceptorProxy for invoking interceptors or a null reference
* if no around invoke interceptor methods need to be invoked .
* @ throws EJBConfigurationException is thrown if interceptor - order element is used
* for specified business method and the order is incomplete . */
private InterceptorProxy [ ] getAroundInterceptorProxies ( InterceptorMethodKind kind , Method m ) throws EJBConfigurationException { } } | final boolean isTraceOn = TraceComponent . isAnyTracingEnabled ( ) ; if ( isTraceOn && tc . isEntryEnabled ( ) ) { Tr . entry ( tc , "getAroundInterceptorProxies: " + kind + ", " + m ) ; } // d630717 - Unconditionally create an ordered list of interceptors to
// pass to getInterceptorProxies .
List < String > orderedList = orderMethodLevelInterceptors ( m ) ; // Now create the InterceptorProxy array required for business method specified
// by the caller .
InterceptorProxy [ ] proxies = getInterceptorProxies ( kind , orderedList ) ; // d630717
// Return the InterceptorProxy array for invoking around invoke interceptors
// for the businesss method specified by the caller .
if ( isTraceOn && tc . isEntryEnabled ( ) ) { Tr . exit ( tc , "getAroundInterceptorProxies" ) ; } return proxies ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.