signature stringlengths 43 39.1k | implementation stringlengths 0 450k |
|---|---|
public class Util { /** * Returns a Little - Endian byte array extracted from the given int .
* @ param v the given int
* @ param arr a given array of 4 bytes that will be returned with the data
* @ return a Little - Endian byte array extracted from the given int . */
public static byte [ ] intToBytes ( int v , final byte [ ] arr ) { } } | for ( int i = 0 ; i < 4 ; i ++ ) { arr [ i ] = ( byte ) ( v & 0XFF ) ; v >>>= 8 ; } return arr ; |
public class Node { /** * Get the { @ link Cluster } that corresponds to the given clusterId . */
public Cluster getCluster ( final ClusterId clusterId ) { } } | for ( final Cluster cur : clusters ) if ( cur . getClusterId ( ) . equals ( clusterId ) ) return cur ; return null ; |
public class cachepolicy { /** * Use this API to fetch filtered set of cachepolicy resources .
* filter string should be in JSON format . eg : " port : 80 , servicetype : HTTP " . */
public static cachepolicy [ ] get_filtered ( nitro_service service , String filter ) throws Exception { } } | cachepolicy obj = new cachepolicy ( ) ; options option = new options ( ) ; option . set_filter ( filter ) ; cachepolicy [ ] response = ( cachepolicy [ ] ) obj . getfiltered ( service , option ) ; return response ; |
public class FrameListeners { /** * Called for each frame error detected .
* @ param msg The error message
* @ see de . quippy . jflac . FrameListener # processError ( java . lang . String ) */
public void processError ( String msg ) { } } | synchronized ( frameListeners ) { Iterator < FrameListener > it = frameListeners . iterator ( ) ; while ( it . hasNext ( ) ) { FrameListener listener = it . next ( ) ; listener . processError ( msg ) ; } } |
public class FacesBackingBeanFactory { /** * Get a FacesBackingBeanFactory .
* @ param servletContext the current ServletContext .
* @ return a FacesBackingBeanFactory for the given ServletContext . It may or may not be a cached instance . */
public static FacesBackingBeanFactory get ( ServletContext servletContext ) { } } | FacesBackingBeanFactory factory = ( FacesBackingBeanFactory ) servletContext . getAttribute ( CONTEXT_ATTR ) ; assert factory != null : FacesBackingBeanFactory . class . getName ( ) + " was not found in ServletContext attribute " + CONTEXT_ATTR ; factory . reinit ( servletContext ) ; return factory ; |
public class MultipartReader { /** * Read a single byte , except it will try to use the leftover bytes from the
* previous read first .
* @ return The single byte read
* @ throws IOException If an error occurs */
public int read ( ) throws IOException { } } | if ( leftover != null && leftover . remaining ( ) > 0 ) { int b = leftover . get ( ) ; if ( leftover . remaining ( ) == 0 ) { leftover = null ; } return b ; } return input . read ( ) ; |
public class PrcItemInCart { /** * < p > Find cart item by ID . < / p >
* @ param pShoppingCart cart
* @ param pCartItemItsId cart item ID
* @ return cart item
* @ throws Exception - an exception */
public final CartLn findCartItemById ( final Cart pShoppingCart , final Long pCartItemItsId ) throws Exception { } } | CartLn cartLn = null ; for ( CartLn ci : pShoppingCart . getItems ( ) ) { if ( ci . getItsId ( ) . equals ( pCartItemItsId ) ) { if ( ci . getDisab ( ) ) { throw new ExceptionWithCode ( ExceptionWithCode . SOMETHING_WRONG , "requested_item_disabled" ) ; } cartLn = ci ; break ; } } if ( cartLn == null ) { throw new ExceptionWithCode ( ExceptionWithCode . SOMETHING_WRONG , "requested_item_not_found" ) ; } return cartLn ; |
public class CommerceCountryUtil { /** * Returns the last commerce country in the ordered set where groupId = & # 63 ; and billingAllowed = & # 63 ; and active = & # 63 ; .
* @ param groupId the group ID
* @ param billingAllowed the billing allowed
* @ param active the active
* @ param orderByComparator the comparator to order the set by ( optionally < code > null < / code > )
* @ return the last matching commerce country , or < code > null < / code > if a matching commerce country could not be found */
public static CommerceCountry fetchByG_B_A_Last ( long groupId , boolean billingAllowed , boolean active , OrderByComparator < CommerceCountry > orderByComparator ) { } } | return getPersistence ( ) . fetchByG_B_A_Last ( groupId , billingAllowed , active , orderByComparator ) ; |
public class bridgetable { /** * Use this API to unset the properties of bridgetable resources .
* Properties that need to be unset are specified in args array . */
public static base_responses unset ( nitro_service client , bridgetable resources [ ] , String [ ] args ) throws Exception { } } | base_responses result = null ; if ( resources != null && resources . length > 0 ) { bridgetable unsetresources [ ] = new bridgetable [ resources . length ] ; for ( int i = 0 ; i < resources . length ; i ++ ) { unsetresources [ i ] = new bridgetable ( ) ; } result = unset_bulk_request ( client , unsetresources , args ) ; } return result ; |
import java . util . Arrays ; public class LongestBitonicSequence { /** * This function calculates the longest bitonic subsequence in a array .
* A bitonic sequence is a sequence of numbers which is first strictly increasing then after a point strictly decreasing .
* Examples :
* > > > longest _ bitonic _ sequence ( [ 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 ] )
* > > > longest _ bitonic _ sequence ( [ 1 , 11 , 2 , 10 , 4 , 5 , 2 , 1 ] )
* > > > longest _ bitonic _ sequence ( [ 80 , 60 , 30 , 40 , 20 , 10 ] )
* Args :
* array ( int [ ] ) : An array of integers .
* Returns :
* int : Length of the longest bitonic subsequence . */
public static int longestBitonicSequence ( int array [ ] ) { } } | int n = array . length ; int [ ] incSubSeq = new int [ n ] ; int [ ] decSubSeq = new int [ n ] ; Arrays . fill ( incSubSeq , 1 ) ; Arrays . fill ( decSubSeq , 1 ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( array [ i ] > array [ j ] && incSubSeq [ i ] < incSubSeq [ j ] + 1 ) { incSubSeq [ i ] = incSubSeq [ j ] + 1 ; } } } for ( int i = n - 2 ; i >= 0 ; i -- ) { for ( int j = n - 1 ; j > i ; j -- ) { if ( array [ i ] > array [ j ] && decSubSeq [ i ] < decSubSeq [ j ] + 1 ) { decSubSeq [ i ] = decSubSeq [ j ] + 1 ; } } } int maxLength = incSubSeq [ 0 ] + decSubSeq [ 0 ] - 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( incSubSeq [ i ] + decSubSeq [ i ] - 1 > maxLength ) { maxLength = incSubSeq [ i ] + decSubSeq [ i ] - 1 ; } } return maxLength ; |
public class BufferedMagicNumberStream { /** * Replies the count of characters available for reading . */
private int ensureBuffer ( int offset , int length ) throws IOException { } } | final int lastPos = offset + length - 1 ; final int desiredSize = ( ( lastPos / BUFFER_SIZE ) + 1 ) * BUFFER_SIZE ; final int currentSize = this . buffer . length ; if ( desiredSize > currentSize ) { final byte [ ] readBuffer = new byte [ desiredSize - currentSize ] ; final int count = this . in . read ( readBuffer ) ; if ( count > 0 ) { final byte [ ] newBuffer = new byte [ currentSize + count ] ; System . arraycopy ( this . buffer , 0 , newBuffer , 0 , currentSize ) ; System . arraycopy ( readBuffer , 0 , newBuffer , currentSize , count ) ; this . buffer = newBuffer ; } return ( lastPos < this . buffer . length ) ? length : length - ( lastPos - this . buffer . length + 1 ) ; } return length ; |
public class Criteria { /** * Crates new { @ link Predicate } with leading wildcard < br / >
* < strong > NOTE : < / strong > mind your schema and execution times as leading wildcards may not be supported .
* < strong > NOTE : < / strong > Strings will not be automatically split on whitespace .
* @ param s
* @ return
* @ throws InvalidDataAccessApiUsageException for strings with whitespace */
public Criteria endsWith ( String s ) { } } | assertNoBlankInWildcardedQuery ( s , true , false ) ; predicates . add ( new Predicate ( OperationKey . ENDS_WITH , s ) ) ; return this ; |
public class DBIDUtil { /** * Ensure that the given DBIDs are array - indexable .
* @ param ids IDs
* @ return Array DBIDs . */
public static ArrayDBIDs ensureArray ( DBIDs ids ) { } } | return ids instanceof ArrayDBIDs ? ( ArrayDBIDs ) ids : newArray ( ids ) ; |
public class MusicService { /** * Sets the current music state according to the value stored in preferences . Mostly for internal use .
* @ param preferences path to the preferences . Will be set as global music preferences path .
* @ param preferenceName name of the state preference .
* @ param defaultValue used if preference is not set . */
public void setMusicEnabledFromPreferences ( final String preferences , final String preferenceName , final boolean defaultValue ) { } } | musicPreferences = preferences ; musicEnabledPreferenceName = preferenceName ; setMusicEnabled ( readFromPreferences ( preferences , preferenceName , defaultValue ) ) ; |
public class SameDiff { /** * Get the output variable ( s ) for the specified differential function
* @ param function the function reference to get the output variable ( s ) for
* @ return the output variables for the given function */
public SDVariable [ ] getOutputVariablesForFunction ( DifferentialFunction function ) { } } | val inputs = getOutputsForFunction ( function ) ; if ( inputs == null ) { throw new ND4JIllegalStateException ( "No inputs found for function " + function ) ; } val vars = new SDVariable [ inputs . length ] ; for ( int i = 0 ; i < inputs . length ; i ++ ) { vars [ i ] = getVariable ( inputs [ i ] ) ; } return vars ; |
public class AsyncDispatcher { /** * If listeners are registered for this event type , run the listeners or
* queue the event , if already something is happening for this key . */
void deliverAsyncEvent ( final EntryEvent < K , V > _event ) { } } | if ( asyncListenerByType . get ( _event . getEventType ( ) ) . isEmpty ( ) ) { return ; } List < Listener < K , V > > _listeners = new ArrayList < Listener < K , V > > ( asyncListenerByType . get ( _event . getEventType ( ) ) ) ; if ( _listeners . isEmpty ( ) ) { return ; } K key = _event . getKey ( ) ; synchronized ( getLockObject ( key ) ) { Queue < EntryEvent < K , V > > q = keyQueue . get ( key ) ; if ( q != null ) { q . add ( _event ) ; return ; } q = new LinkedList < EntryEvent < K , V > > ( ) ; keyQueue . put ( key , q ) ; } runAllListenersInParallel ( _event , _listeners ) ; |
public class JmsQueueConnectionImpl { /** * This method overrides a superclass method , so that the superclass ' s
* createSession ( ) method can be inherited , but still return an object of
* this class ' s type . */
JmsSessionImpl instantiateSession ( boolean transacted , int acknowledgeMode , SICoreConnection coreConnection , JmsJcaSession jcaSession ) throws JMSException { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . entry ( this , tc , "instantiateSession" , new Object [ ] { transacted , acknowledgeMode , coreConnection , jcaSession } ) ; JmsQueueSessionImpl jmsQueueSession = new JmsQueueSessionImpl ( transacted , acknowledgeMode , coreConnection , this , jcaSession ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && tc . isEntryEnabled ( ) ) SibTr . exit ( this , tc , "instantiateSession" , jmsQueueSession ) ; return jmsQueueSession ; |
public class DrawerFragment { /** * Users of this fragment must call this method to set up the navigation drawer interactions .
* @ param fragmentId The android : id of this fragment in its activity ' s layout .
* @ param drawerLayout The DrawerLayout containing this fragment ' s UI . */
public void setUp ( int fragmentId , DrawerLayout drawerLayout ) { } } | mFragmentContainerView = getActivity ( ) . findViewById ( fragmentId ) ; mDrawerLayout = drawerLayout ; // set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout . setDrawerShadow ( R . drawable . drawer_shadow , GravityCompat . START ) ; // set up the drawer ' s list view with items and click listener
ActionBar actionBar = getActionBar ( ) ; actionBar . setDisplayHomeAsUpEnabled ( true ) ; actionBar . setHomeButtonEnabled ( true ) ; // ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon .
mDrawerToggle = new ActionBarDrawerToggle ( getActivity ( ) , /* host Activity */
mDrawerLayout , /* DrawerLayout object */
R . drawable . ic_drawer , /* nav drawer image to replace ' Up ' caret */
R . string . drawer_open , /* " open drawer " description for accessibility */
R . string . drawer_close /* " close drawer " description for accessibility */
) { @ Override public void onDrawerClosed ( View drawerView ) { super . onDrawerClosed ( drawerView ) ; if ( ! isAdded ( ) ) { return ; } getActivity ( ) . supportInvalidateOptionsMenu ( ) ; // calls onPrepareOptionsMenu ( )
} @ Override public void onDrawerOpened ( View drawerView ) { super . onDrawerOpened ( drawerView ) ; if ( ! isAdded ( ) ) { return ; } getActivity ( ) . supportInvalidateOptionsMenu ( ) ; // calls onPrepareOptionsMenu ( )
} } ; // Defer code dependent on restoration of previous instance state .
mDrawerLayout . post ( new Runnable ( ) { @ Override public void run ( ) { mDrawerToggle . syncState ( ) ; } } ) ; mDrawerLayout . setDrawerListener ( mDrawerToggle ) ; |
public class SchemaUsageAnalyzer { /** * Count the terms ( labels , descriptions , aliases ) of an item or property
* document .
* @ param termedDocument
* document to count the terms of
* @ param entityStatistics
* record where statistics are counted */
protected void countTerms ( TermedDocument termedDocument , EntityStatistics entityStatistics ) { } } | entityStatistics . countLabels += termedDocument . getLabels ( ) . size ( ) ; // for ( MonolingualTextValue mtv : termedDocument . getLabels ( ) . values ( ) )
// countKey ( usageStatistics . labelCounts , mtv . getLanguageCode ( ) , 1 ) ;
entityStatistics . countDescriptions += termedDocument . getDescriptions ( ) . size ( ) ; // for ( MonolingualTextValue mtv : termedDocument . getDescriptions ( )
// . values ( ) ) {
// countKey ( usageStatistics . descriptionCounts , mtv . getLanguageCode ( ) ,
for ( String languageKey : termedDocument . getAliases ( ) . keySet ( ) ) { int count = termedDocument . getAliases ( ) . get ( languageKey ) . size ( ) ; entityStatistics . countAliases += count ; // countKey ( usageStatistics . aliasCounts , languageKey , count ) ;
} |
public class MessageSourceSupport { /** * Create a MessageFormat for the given message and Locale .
* @ param msg the message to create a MessageFormat for
* @ param locale the Locale to create a MessageFormat for
* @ return the MessageFormat instance */
protected MessageFormat createMessageFormat ( String msg , Locale locale ) { } } | return new MessageFormat ( ( msg != null ? msg : "" ) , locale ) ; |
public class EbeanQueryCreator { /** * Creates a { @ link ExpressionList } from the given { @ link Part } .
* @ param part
* @ param root
* @ return */
private Expression toExpression ( Part part , ExpressionList < ? > root ) { } } | return new ExpressionBuilder ( part , root ) . build ( ) ; |
public class AbstractLRParser { /** * This method is called for shift actions .
* @ param newState
* is the new state id after shift .
* @ param token
* is the current token in token stream .
* @ throws ParserException */
private final void shift ( ParserAction action ) { } } | stateStack . push ( action . getParameter ( ) ) ; actionStack . add ( action ) ; streamPosition ++ ; shiftIgnoredTokens ( ) ; |
public class UrlUtilities { /** * Get content from the passed in URL . This code will open a connection to
* the passed in server , fetch the requested content , and return it as a
* byte [ ] .
* @ param url URL to hit
* @ param inCookies Map of session cookies ( or null if not needed )
* @ param outCookies Map of session cookies ( or null if not needed )
* @ param allowAllCerts override certificate validation ?
* @ return byte [ ] of content fetched from URL . */
public static byte [ ] getContentFromUrl ( URL url , Map inCookies , Map outCookies , boolean allowAllCerts ) { } } | URLConnection c = null ; try { c = getConnection ( url , inCookies , true , false , false , allowAllCerts ) ; ByteArrayOutputStream out = new ByteArrayOutputStream ( 16384 ) ; InputStream stream = IOUtilities . getInputStream ( c ) ; IOUtilities . transfer ( stream , out ) ; stream . close ( ) ; if ( outCookies != null ) { // [ optional ] Fetch cookies from server and update outCookie Map ( pick up JSESSIONID , other headers )
getCookies ( c , outCookies ) ; } return out . toByteArray ( ) ; } catch ( SSLHandshakeException e ) { // Don ' t read error response . it will just cause another exception .
LOG . warn ( "SSL Exception occurred fetching content from url: " + url , e ) ; return null ; } catch ( Exception e ) { readErrorResponse ( c ) ; LOG . warn ( "Exception occurred fetching content from url: " + url , e ) ; return null ; } finally { if ( c instanceof HttpURLConnection ) { disconnect ( ( HttpURLConnection ) c ) ; } } |
public class ApiClient { /** * Formats the specified query parameter to a list containing a single { @ code Pair } object .
* Note that { @ code value } must not be a collection .
* @ param name The name of the parameter .
* @ param value The value of the parameter .
* @ return A list containing a single { @ code Pair } object . */
public List < Pair > parameterToPair ( String name , Object value ) { } } | List < Pair > params = new ArrayList < Pair > ( ) ; // preconditions
if ( name == null || name . isEmpty ( ) || value == null || value instanceof Collection ) return params ; params . add ( new Pair ( name , parameterToString ( value ) ) ) ; return params ; |
public class Vertigo { /** * Undeploys a network from the given cluster . < p >
* This method supports both partial and complete undeployment of networks . When
* undeploying networks by specifying a { @ link NetworkConfig } , the network configuration
* should contain all components and connections that are being undeployed . If the
* configuration ' s components and connections match all deployed components and
* connections then the entire network will be undeployed .
* @ param cluster The cluster from which to undeploy the network .
* @ param network The network configuration to undeploy .
* @ return The Vertigo instance . */
public Vertigo undeployNetwork ( String cluster , NetworkConfig network ) { } } | return undeployNetwork ( cluster , network , null ) ; |
public class AgBuffer { /** * Clones this buffer but replaces all transport attributes with new attributes
* of the specified type .
* @ param type for new attributes
* @ return cloned seed */
public Attribute cloneAttributes ( AgBuffer orig , Type type , Attribute seed ) { } } | Map < Attribute , Attribute > map ; // old attributes to new attributes
Attribute attr ; State newState ; map = new HashMap < Attribute , Attribute > ( ) ; for ( State state : orig . states ) { attr = state . getAttribute ( ) ; map . put ( attr , new Attribute ( attr . symbol , null , type ) ) ; } for ( State state : orig . states ) { newState = state . cloneAttributeTransport ( map ) ; states . add ( newState ) ; } attr = map . get ( seed ) ; if ( attr == null ) { throw new IllegalArgumentException ( ) ; } return attr ; |
public class DefaultEngine { /** * On all inited . */
public void inited ( ) { } } | if ( preload ) { try { int count = 0 ; if ( templateSuffix == null ) { templateSuffix = new String [ ] { ".httl" } ; } for ( String suffix : templateSuffix ) { List < String > list = loader . list ( suffix ) ; if ( list == null ) { continue ; } count += list . size ( ) ; for ( String name : list ) { try { if ( logger != null && logger . isDebugEnabled ( ) ) { logger . debug ( "Preload the template: " + name ) ; } getTemplate ( name , getDefaultEncoding ( ) ) ; } catch ( Exception e ) { if ( logger != null && logger . isErrorEnabled ( ) ) { logger . error ( e . getMessage ( ) , e ) ; } } } } if ( logger != null && logger . isInfoEnabled ( ) ) { logger . info ( "Preload " + count + " templates from directory " + ( templateDirectory == null ? "/" : templateDirectory ) + " with suffix " + Arrays . toString ( templateSuffix ) ) ; } } catch ( Exception e ) { if ( logger != null && logger . isErrorEnabled ( ) ) { logger . error ( e . getMessage ( ) , e ) ; } } } |
public class DocumentElement { /** * setter for width - sets
* @ generated
* @ param v value to set into the feature */
public void setWidth ( float v ) { } } | if ( DocumentElement_Type . featOkTst && ( ( DocumentElement_Type ) jcasType ) . casFeat_width == null ) jcasType . jcas . throwFeatMissing ( "width" , "ch.epfl.bbp.uima.types.DocumentElement" ) ; jcasType . ll_cas . ll_setFloatValue ( addr , ( ( DocumentElement_Type ) jcasType ) . casFeatCode_width , v ) ; |
public class TextAnalyticsImpl { /** * The API returns a numeric score between 0 and 1.
* Scores close to 1 indicate positive sentiment , while scores close to 0 indicate negative sentiment . A score of 0.5 indicates the lack of sentiment ( e . g . a factoid statement ) . See the & lt ; a href = " https : / / docs . microsoft . com / en - us / azure / cognitive - services / text - analytics / overview # supported - languages " & gt ; Text Analytics Documentation & lt ; / a & gt ; for details about the languages that are supported by sentiment analysis .
* @ param sentimentOptionalParameter the object representing the optional parameters to be set before calling this API
* @ param serviceCallback the async ServiceCallback to handle successful and failed responses .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the { @ link ServiceFuture } object */
public ServiceFuture < SentimentBatchResult > sentimentAsync ( SentimentOptionalParameter sentimentOptionalParameter , final ServiceCallback < SentimentBatchResult > serviceCallback ) { } } | return ServiceFuture . fromResponse ( sentimentWithServiceResponseAsync ( sentimentOptionalParameter ) , serviceCallback ) ; |
public class QueryRunner { /** * Execute an SQL SELECT query with a single replacement parameter . The
* caller is responsible for closing the connection .
* @ param conn The connection to execute the query in .
* @ param sql The query to execute .
* @ param param The replacement parameter .
* @ param rsh The handler that converts the results into an object .
* @ return The object returned by the handler .
* @ throws java . sql . SQLException if a database access error occurs */
public < T > T query ( Connection conn , String sql , Object param , ResultSetHandler < T > rsh ) throws SQLException { } } | return this . query ( conn , sql , new Object [ ] { param } , rsh ) ; |
public class UtilLoggingLevel { /** * Gets list of supported levels .
* @ return list of supported levels . */
public static List getAllPossibleLevels ( ) { } } | ArrayList list = new ArrayList ( ) ; list . add ( FINE ) ; list . add ( FINER ) ; list . add ( FINEST ) ; list . add ( INFO ) ; list . add ( CONFIG ) ; list . add ( WARNING ) ; list . add ( SEVERE ) ; return list ; |
public class RestClient { /** * Checks the repository availability
* @ return This will return void if all is ok but will throw an exception if
* there are any problems
* @ throws RequestFailureException If the response code is not OK or the headers returned are missing
* the count field ( which can happen if we hit a URL that returns 200 but is not a valid repository ) .
* @ throws IOException If there is a problem with the URL */
@ Override public void checkRepositoryStatus ( ) throws IOException , RequestFailureException { } } | HttpURLConnection connection = createHeadConnection ( "/assets" ) ; testResponseCode ( connection ) ; Map < String , List < String > > results = connection . getHeaderFields ( ) ; if ( results == null ) { throw new RequestFailureException ( connection . getResponseCode ( ) , "No header returned, this does not look like a valid repository" , connection . getURL ( ) , null ) ; } List < String > count = results . get ( "count" ) ; if ( count == null ) { throw new RequestFailureException ( connection . getResponseCode ( ) , "No count returned, this does not look like a valid repository" , connection . getURL ( ) , null ) ; } |
public class DatatypeFactory { /** * < p > Create a Java representation of XML Schema builtin datatype < code > date < / code > or < code > g * < / code > . < / p >
* < p > For example , an instance of < code > gYear < / code > can be created invoking this factory
* with < code > month < / code > and < code > day < / code > parameters set to
* { @ link DatatypeConstants # FIELD _ UNDEFINED } . < / p >
* < p > A { @ link DatatypeConstants # FIELD _ UNDEFINED } value indicates that field is not set . < / p >
* @ param year of < code > XMLGregorianCalendar < / code > to be created .
* @ param month of < code > XMLGregorianCalendar < / code > to be created .
* @ param day of < code > XMLGregorianCalendar < / code > to be created .
* @ param timezone offset in minutes . { @ link DatatypeConstants # FIELD _ UNDEFINED } indicates optional field is not set .
* @ return < code > XMLGregorianCalendar < / code > created from parameter values .
* @ see DatatypeConstants # FIELD _ UNDEFINED
* @ throws IllegalArgumentException If any individual parameter ' s value is outside the maximum value constraint for the field
* as determined by the Date / Time Data Mapping table in { @ link XMLGregorianCalendar }
* or if the composite values constitute an invalid < code > XMLGregorianCalendar < / code > instance
* as determined by { @ link XMLGregorianCalendar # isValid ( ) } . */
public XMLGregorianCalendar newXMLGregorianCalendarDate ( final int year , final int month , final int day , final int timezone ) { } } | return newXMLGregorianCalendar ( year , month , day , DatatypeConstants . FIELD_UNDEFINED , // hour
DatatypeConstants . FIELD_UNDEFINED , // minute
DatatypeConstants . FIELD_UNDEFINED , // second
DatatypeConstants . FIELD_UNDEFINED , // millisecond
timezone ) ; |
public class DevirtualizePrototypeMethods { /** * Determines if a method definition site is eligible for rewrite as a global .
* < p > In order to be eligible for rewrite , the definition site must :
* < ul >
* < li > Not be exported
* < li > Be for a prototype method
* < / ul > */
private boolean isEligibleDefinitionSite ( String name , Node definitionSite ) { } } | switch ( definitionSite . getToken ( ) ) { case GETPROP : case MEMBER_FUNCTION_DEF : case STRING_KEY : break ; default : // No other node types are supported .
throw new IllegalArgumentException ( definitionSite . toString ( ) ) ; } // Exporting a method prevents rewrite .
CodingConvention codingConvention = compiler . getCodingConvention ( ) ; if ( codingConvention . isExported ( name ) ) { return false ; } if ( ! isPrototypeMethodDefinition ( definitionSite ) ) { return false ; } return true ; |
public class PublisherCreateOperation { /** * Read and reset the accumulator of query cache inside the given partition . */
private Future < Object > readAndResetAccumulator ( String mapName , String cacheId , Integer partitionId ) { } } | Operation operation = new ReadAndResetAccumulatorOperation ( mapName , cacheId ) ; OperationService operationService = getNodeEngine ( ) . getOperationService ( ) ; return operationService . invokeOnPartition ( MapService . SERVICE_NAME , operation , partitionId ) ; |
public class CombineAndSimplifyBounds { /** * Simplify BoundDimFilters that are children of an OR or an AND .
* @ param children the filters
* @ param disjunction true for disjunction , false for conjunction
* @ return simplified filters */
private static DimFilter doSimplify ( final List < DimFilter > children , boolean disjunction ) { } } | // Copy children list
final List < DimFilter > newChildren = Lists . newArrayList ( children ) ; // Group Bound filters by dimension , extractionFn , and comparator and compute a RangeSet for each one .
final Map < BoundRefKey , List < BoundDimFilter > > bounds = new HashMap < > ( ) ; final Iterator < DimFilter > iterator = newChildren . iterator ( ) ; while ( iterator . hasNext ( ) ) { final DimFilter child = iterator . next ( ) ; if ( child . equals ( Filtration . matchNothing ( ) ) ) { // Child matches nothing , equivalent to FALSE
// OR with FALSE = > ignore
// AND with FALSE = > always false , short circuit
if ( disjunction ) { iterator . remove ( ) ; } else { return Filtration . matchNothing ( ) ; } } else if ( child . equals ( Filtration . matchEverything ( ) ) ) { // Child matches everything , equivalent to TRUE
// OR with TRUE = > always true , short circuit
// AND with TRUE = > ignore
if ( disjunction ) { return Filtration . matchEverything ( ) ; } else { iterator . remove ( ) ; } } else if ( child instanceof BoundDimFilter ) { final BoundDimFilter bound = ( BoundDimFilter ) child ; final BoundRefKey boundRefKey = BoundRefKey . from ( bound ) ; List < BoundDimFilter > filterList = bounds . get ( boundRefKey ) ; if ( filterList == null ) { filterList = new ArrayList < > ( ) ; bounds . put ( boundRefKey , filterList ) ; } filterList . add ( bound ) ; } } // Try to simplify filters within each group .
for ( Map . Entry < BoundRefKey , List < BoundDimFilter > > entry : bounds . entrySet ( ) ) { final BoundRefKey boundRefKey = entry . getKey ( ) ; final List < BoundDimFilter > filterList = entry . getValue ( ) ; // Create a RangeSet for this group .
final RangeSet < BoundValue > rangeSet = disjunction ? RangeSets . unionRanges ( Bounds . toRanges ( filterList ) ) : RangeSets . intersectRanges ( Bounds . toRanges ( filterList ) ) ; if ( rangeSet . asRanges ( ) . size ( ) < filterList . size ( ) ) { // We found a simplification . Remove the old filters and add new ones .
for ( final BoundDimFilter bound : filterList ) { if ( ! newChildren . remove ( bound ) ) { throw new ISE ( "WTF?! Tried to remove bound but couldn't?" ) ; } } if ( rangeSet . asRanges ( ) . isEmpty ( ) ) { // range set matches nothing , equivalent to FALSE
// OR with FALSE = > ignore
// AND with FALSE = > always false , short circuit
if ( disjunction ) { newChildren . add ( Filtration . matchNothing ( ) ) ; } else { return Filtration . matchNothing ( ) ; } } for ( final Range < BoundValue > range : rangeSet . asRanges ( ) ) { if ( ! range . hasLowerBound ( ) && ! range . hasUpperBound ( ) ) { // range matches all , equivalent to TRUE
// AND with TRUE = > ignore
// OR with TRUE = > always true ; short circuit
if ( disjunction ) { return Filtration . matchEverything ( ) ; } else { newChildren . add ( Filtration . matchEverything ( ) ) ; } } else { newChildren . add ( Bounds . toFilter ( boundRefKey , range ) ) ; } } } } Preconditions . checkState ( newChildren . size ( ) > 0 , "newChildren.size > 0" ) ; if ( newChildren . size ( ) == 1 ) { return newChildren . get ( 0 ) ; } else { return disjunction ? new OrDimFilter ( newChildren ) : new AndDimFilter ( newChildren ) ; } |
public class FormData { /** * Returns the FormEntry for the given key . If no FormEntry exists yet for the given key , then a
* new one will be generated if generate = = true
* @ return the FormEntry for the key */
public FormEntry getFormEntry ( final String entryKey ) { } } | FormEntry entry = entries . get ( entryKey ) ; if ( entry == null ) { entry = addFormEntry ( entryKey , null ) ; } return entry ; |
public class ShutdownHookManager { /** * Remove the shutdown hook from the VM ( FeatureManager . deactivate )
* @ see { @ link Runtime # addShutdownHook ( Thread ) }
* @ see { @ link Runtime # removeShutdownHook ( Thread ) } */
@ FFDCIgnore ( IllegalStateException . class ) public synchronized void removeShutdownHook ( ) { } } | if ( shutdownInvoked ) return ; try { if ( hookSet . compareAndSet ( true , false ) ) { Runtime . getRuntime ( ) . removeShutdownHook ( this ) ; } } catch ( IllegalStateException e ) { // ok . based on timing , if we start shutting down , we may
// not be able to remove the hook .
} |
public class ByteArray { /** * 获取指定位置的数据
* @ param index
* 位置
* @ return 指定位置的数据
* @ throws IndexOutOfBoundsException
* 当index大于长度时抛出 */
public byte get ( int index ) throws IndexOutOfBoundsException { } } | if ( index >= this . size ) { throw new IndexOutOfBoundsException ( "数组大小为:" + this . size + ";下标为:" + index ) ; } return datas [ index ] ; |
public class ProductUrl { /** * Get Resource Url for GetProducts
* @ param cursorMark In your first deep paged request , set this parameter to . Then , in all subsequent requests , set this parameter to the subsequent values of that ' s returned in each response to continue paging through the results . Continue this pattern until is null , which signifies the end of the paged results .
* @ param defaultSort Sets the default sorting for content . Sort does not use AND in determining the order
* @ param filter A set of filter expressions representing the search parameters for a query . This parameter is optional . Refer to [ Sorting and Filtering ] ( . . / . . / . . / . . / Developer / api - guides / sorting - filtering . htm ) for a list of supported filters .
* @ param pageSize When creating paged results from a query , this value indicates the zero - based offset in the complete result set where the returned entities begin . For example , with this parameter set to 25 , to get the 51st through the 75th items , set startIndex to 50.
* @ param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object . This parameter should only be used to retrieve data . Attempting to update data using this parameter may cause data loss .
* @ param responseOptions Options you can specify for the response . This parameter is null by default . You can primarily use this parameter to return volume price band information in product details , which you can then display on category pages and search results depanding on your theme configuration . To return volume price band information , set this parameter to .
* @ param sortBy The element to sort the results by and the channel in which the results appear . Either ascending ( a - z ) or descending ( z - a ) channel . Optional . Refer to [ Sorting and Filtering ] ( . . / . . / . . / . . / Developer / api - guides / sorting - filtering . htm ) for more information .
* @ param startIndex When creating paged results from a query , this value indicates the zero - based offset in the complete result set where the returned entities begin . For example , with pageSize set to 25 , to get the 51st through the 75th items , set this parameter to 50.
* @ return String Resource Url */
public static MozuUrl getProductsUrl ( String cursorMark , String defaultSort , String filter , Integer pageSize , String responseFields , String responseOptions , String sortBy , Integer startIndex ) { } } | UrlFormatter formatter = new UrlFormatter ( "/api/commerce/catalog/storefront/products/?filter={filter}&startIndex={startIndex}&pageSize={pageSize}&sortBy={sortBy}&responseOptions={responseOptions}&cursorMark={cursorMark}&defaultSort={defaultSort}&responseFields={responseFields}" ) ; formatter . formatUrl ( "cursorMark" , cursorMark ) ; formatter . formatUrl ( "defaultSort" , defaultSort ) ; formatter . formatUrl ( "filter" , filter ) ; formatter . formatUrl ( "pageSize" , pageSize ) ; formatter . formatUrl ( "responseFields" , responseFields ) ; formatter . formatUrl ( "responseOptions" , responseOptions ) ; formatter . formatUrl ( "sortBy" , sortBy ) ; formatter . formatUrl ( "startIndex" , startIndex ) ; return new MozuUrl ( formatter . getResourceUrl ( ) , MozuUrl . UrlLocation . TENANT_POD ) ; |
public class PDF417Writer { /** * This takes an array holding the values of the PDF 417
* @ param input a byte array of information with 0 is black , and 1 is white
* @ param margin border around the barcode
* @ return BitMatrix of the input */
private static BitMatrix bitMatrixFromBitArray ( byte [ ] [ ] input , int margin ) { } } | // Creates the bit matrix with extra space for whitespace
BitMatrix output = new BitMatrix ( input [ 0 ] . length + 2 * margin , input . length + 2 * margin ) ; output . clear ( ) ; for ( int y = 0 , yOutput = output . getHeight ( ) - margin - 1 ; y < input . length ; y ++ , yOutput -- ) { byte [ ] inputY = input [ y ] ; for ( int x = 0 ; x < input [ 0 ] . length ; x ++ ) { // Zero is white in the byte matrix
if ( inputY [ x ] == 1 ) { output . set ( x + margin , yOutput ) ; } } } return output ; |
public class CmsPatternPanelYearlyView { /** * Handler for week of month changes .
* @ param event the change event . */
@ UiHandler ( "m_atNumber" ) void onWeekOfMonthChange ( ValueChangeEvent < String > event ) { } } | if ( handleChange ( ) ) { m_controller . setWeekOfMonth ( event . getValue ( ) ) ; } |
public class RestController { /** * Get ' s an XREF entity or a list of MREF entities
* < p > Example :
* < p > / api / v1 / person / 99 / address */
@ PostMapping ( value = "/{entityTypeId}/{id}/{refAttributeName}" , params = "_method=GET" , produces = APPLICATION_JSON_VALUE ) public Object retrieveEntityAttributePost ( @ PathVariable ( "entityTypeId" ) String entityTypeId , @ PathVariable ( "id" ) String untypedId , @ PathVariable ( "refAttributeName" ) String refAttributeName , @ Valid @ RequestBody EntityCollectionRequest request ) { } } | Set < String > attributesSet = toAttributeSet ( request . getAttributes ( ) ) ; Map < String , Set < String > > attributeExpandSet = toExpandMap ( request . getExpand ( ) ) ; return retrieveEntityAttributeInternal ( entityTypeId , untypedId , refAttributeName , request , attributesSet , attributeExpandSet ) ; |
public class PoolBase { /** * Setup a connection initial state .
* @ param connection a Connection
* @ throws ConnectionSetupException thrown if any exception is encountered */
private void setupConnection ( final Connection connection ) throws ConnectionSetupException { } } | try { if ( networkTimeout == UNINITIALIZED ) { networkTimeout = getAndSetNetworkTimeout ( connection , validationTimeout ) ; } else { setNetworkTimeout ( connection , validationTimeout ) ; } if ( connection . isReadOnly ( ) != isReadOnly ) { connection . setReadOnly ( isReadOnly ) ; } if ( connection . getAutoCommit ( ) != isAutoCommit ) { connection . setAutoCommit ( isAutoCommit ) ; } checkDriverSupport ( connection ) ; if ( transactionIsolation != defaultTransactionIsolation ) { connection . setTransactionIsolation ( transactionIsolation ) ; } if ( catalog != null ) { connection . setCatalog ( catalog ) ; } if ( schema != null ) { connection . setSchema ( schema ) ; } executeSql ( connection , config . getConnectionInitSql ( ) , true ) ; setNetworkTimeout ( connection , networkTimeout ) ; } catch ( SQLException e ) { throw new ConnectionSetupException ( e ) ; } |
public class CollUtil { /** * 查找第一个匹配元素对象
* @ param < T > 集合元素类型
* @ param collection 集合
* @ param filter 过滤器 , 满足过滤条件的第一个元素将被返回
* @ return 满足过滤条件的第一个元素
* @ since 3.1.0 */
public static < T > T findOne ( Iterable < T > collection , Filter < T > filter ) { } } | if ( null != collection ) { for ( T t : collection ) { if ( filter . accept ( t ) ) { return t ; } } } return null ; |
public class DatabaseOperationsInner { /** * Cancels the asynchronous operation on the database .
* @ 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 serverName The name of the server .
* @ param databaseName The name of the database .
* @ param operationId The operation identifier .
* @ param serviceCallback the async ServiceCallback to handle successful and failed responses .
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the { @ link ServiceFuture } object */
public ServiceFuture < Void > cancelAsync ( String resourceGroupName , String serverName , String databaseName , UUID operationId , final ServiceCallback < Void > serviceCallback ) { } } | return ServiceFuture . fromResponse ( cancelWithServiceResponseAsync ( resourceGroupName , serverName , databaseName , operationId ) , serviceCallback ) ; |
public class BinaryRecordInput { /** * Get a thread - local record input for the supplied DataInput .
* @ param inp data input stream
* @ return binary record input corresponding to the supplied DataInput . */
public static BinaryRecordInput get ( DataInput inp ) { } } | BinaryRecordInput bin = ( BinaryRecordInput ) bIn . get ( ) ; bin . setDataInput ( inp ) ; return bin ; |
public class ConnectionImpl { /** * ( non - Javadoc )
* @ see com . ibm . wsspi . sib . core . SICoreConnection # getMeUuid ( ) */
@ Override public String getMeUuid ( ) { } } | if ( TraceComponent . isAnyTracingEnabled ( ) && CoreSPIConnection . tc . isEntryEnabled ( ) ) SibTr . entry ( CoreSPIConnection . tc , "getMeUuid" , this ) ; // get the meuuid from the messaging engine instead of messageprocessor
// When ME is stopping connection events are sent to MDB and MDB tries to connect
// to ME . Earlier messageprocessor . getmessagingengineuuid ( ) was being called but
// leads to NPE because messageprocessor . getmessagingengineuuid ( ) gets the uuid from persistent
// store is stopped ( null ) by now
SIBUuid8 meUUID = new SIBUuid8 ( _messageProcessor . getMessagingEngine ( ) . getUuid ( ) ) ; if ( TraceComponent . isAnyTracingEnabled ( ) && CoreSPIConnection . tc . isEntryEnabled ( ) ) SibTr . exit ( CoreSPIConnection . tc , "getMeUuid" , meUUID ) ; return meUUID . toString ( ) ; |
public class CmsNewResourceTypeDialog { /** * Creates a name pattern for the resource type . < p >
* @ return String name - pattern */
private String getNamePattern ( ) { } } | String niceName = m_typeShortName . getValue ( ) ; if ( m_typeShortName . getValue ( ) . contains ( "-" ) ) { int maxLength = 0 ; String [ ] nameParts = niceName . split ( "-" ) ; for ( int i = 0 ; i < nameParts . length ; i ++ ) { if ( nameParts [ i ] . length ( ) > maxLength ) { maxLength = nameParts [ i ] . length ( ) ; niceName = nameParts [ i ] ; } } } return niceName + "_%(number).xml" ; |
public class IfcPropertyImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
@ SuppressWarnings ( "unchecked" ) @ Override public EList < IfcPropertyDependencyRelationship > getPropertyDependsOn ( ) { } } | return ( EList < IfcPropertyDependencyRelationship > ) eGet ( Ifc4Package . Literals . IFC_PROPERTY__PROPERTY_DEPENDS_ON , true ) ; |
public class GlobalSuffixFinders { /** * Transforms a { @ link LocalSuffixFinder } into a global one . This is a convenience method , behaving like
* { @ link # fromLocalFinder ( LocalSuffixFinder , boolean ) } .
* @ see # fromLocalFinder ( LocalSuffixFinder , boolean ) */
public static < I , D > GlobalSuffixFinder < I , D > fromLocalFinder ( LocalSuffixFinder < I , D > localFinder ) { } } | return fromLocalFinder ( localFinder , false ) ; |
public class StringUtils { /** * Makes the initial letter upper - case .
* @ param s the string
* @ return first letter is now in upper - case */
public static String toInitialCase ( String s ) { } } | if ( isBlank ( s ) ) return s ; if ( s . length ( ) == 1 ) return s . toUpperCase ( ) ; return s . substring ( 0 , 1 ) . toUpperCase ( ) + s . substring ( 1 ) ; |
public class CertificateLoginModule { /** * Gets the required Callback objects needed by this login module .
* @ param callbackHandler
* @ return
* @ throws IOException
* @ throws UnsupportedCallbackException */
@ Override public Callback [ ] getRequiredCallbacks ( CallbackHandler callbackHandler ) throws IOException , UnsupportedCallbackException { } } | Callback [ ] callbacks = new Callback [ 1 ] ; callbacks [ 0 ] = new WSX509CertificateChainCallback ( null ) ; callbackHandler . handle ( callbacks ) ; return callbacks ; |
public class Frame { /** * Make this Frame exactly the same as the one given as a parameter .
* @ param other
* the Frame to make this object the same as */
public void copyFrom ( Frame < ValueType > other ) { } } | lastUpdateTimestamp = other . lastUpdateTimestamp ; slotList = new ArrayList < > ( other . slotList ) ; isTop = other . isTop ; isBottom = other . isBottom ; |
public class XmlUtils { /** * Gets the value of the child element by tag name under the given parent
* element . If there is more than one child element , return the value of the
* first one .
* @ param parent the parent element
* @ param tagName the tag name of the child element
* @ return value of the first child element , NULL if tag not exists */
public static String getElementValue ( Element parent , String tagName ) { } } | Element element = getChildElement ( parent , tagName ) ; if ( element != null ) { NodeList nodes = element . getChildNodes ( ) ; if ( nodes != null && nodes . getLength ( ) > 0 ) { for ( int i = 0 ; i < nodes . getLength ( ) ; i ++ ) { Node node = nodes . item ( i ) ; if ( node instanceof Text ) { return ( ( Text ) node ) . getData ( ) ; } } } } return null ; |
public class DefaultExtensionProcessor { /** * ( non - Javadoc )
* @ see
* com . ibm . ws . webcontainer . extension . DefaultExtensionProcessor # getZipFileWrapper
* ( com . ibm . wsspi . webcontainer . servlet . IServletContext ,
* com . ibm . ws . webcontainer . extension . DefaultExtensionProcessor ,
* java . util . zip . ZipFile , java . util . zip . ZipEntry ) */
protected com . ibm . ws . webcontainer . servlet . ZipFileServletWrapper getZipFileWrapper ( IServletContext _webapp , com . ibm . ws . webcontainer . extension . DefaultExtensionProcessor processor , ZipFileResource zipFileResources ) { } } | // TODO Auto - generated method stub
return new ZipFileServletWrapper ( _webapp , processor , zipFileResources ) ; |
public class DateIntervalFormat { /** * Get the TimeZone
* @ return A copy of the TimeZone associated with this date interval formatter . */
public TimeZone getTimeZone ( ) { } } | if ( fDateFormat != null ) { // Here we clone , like other getters here , but unlike
// DateFormat . getTimeZone ( ) and Calendar . getTimeZone ( )
// which return the TimeZone from the Calendar ' s zone variable
return ( TimeZone ) ( fDateFormat . getTimeZone ( ) . clone ( ) ) ; } // If fDateFormat is null ( unexpected ) , return default timezone .
return TimeZone . getDefault ( ) ; |
public class EventSourceImpl { /** * Register a listener for EventSource events
* @ param listener */
public void addEventSourceListener ( EventSourceListener listener ) { } } | LOG . entering ( CLASS_NAME , "addEventSourceListener" , listener ) ; if ( listener == null ) { throw new NullPointerException ( "listener" ) ; } listeners . add ( listener ) ; |
public class BulkMutationBatcher { /** * Prevents further mutations and waits for all outstanding mutations to complete .
* @ throws BulkMutationFailure If any mutations failed .
* @ throws InterruptedException If interrupted .
* @ throws TimeoutException If the outstanding requests don ' t finish in time . */
public void close ( Duration duration ) throws InterruptedException , TimeoutException { } } | closed = true ; long deadlineMs = System . currentTimeMillis ( ) + duration . toMillis ( ) ; synchronized ( lock ) { while ( numOutstanding . get ( ) > 0 ) { long waitMs = deadlineMs - System . currentTimeMillis ( ) ; if ( waitMs <= 0 ) { throw new TimeoutException ( "Timed out waiting outstanding mutations to finish" ) ; } lock . wait ( waitMs ) ; } // numFailures can only be checked after numOutstanding is zero .
if ( numFailures > 0 ) { throw new BulkMutationFailure ( numFailures ) ; } } |
public class AbstractWMultiSelectList { /** * { @ inheritDoc } */
@ Override protected void preparePaintComponent ( final Request request ) { } } | super . preparePaintComponent ( request ) ; // Validate the selected options ( allow handle invalid options )
findValidOptions ( getOptions ( ) , convertDataToList ( getData ( ) ) , true ) ; |
public class SysViewWorkspaceInitializer { /** * Parse of SysView export content and fill changes log within it .
* @ throws XMLStreamException
* if stream data corrupted
* @ throws FactoryConfigurationError
* if XML factory configured bad
* @ throws IOException
* fi IO error
* @ throws RepositoryException
* if Repository error
* @ throws NamespaceException
* if namespace is not registered
* @ throws IllegalNameException
* if illegal name */
protected PlainChangesLog read ( ) throws XMLStreamException , FactoryConfigurationError , IOException , NamespaceException , RepositoryException , IllegalNameException { } } | InputStream input = PrivilegedFileHelper . fileInputStream ( restorePath ) ; try { XMLStreamReader reader = XMLInputFactory . newInstance ( ) . createXMLStreamReader ( input ) ; // SV prefix URIs
String svURI = null ; String exoURI = null ; PlainChangesLog changes = new PlainChangesLogImpl ( ) ; // SVNodeData currentNode = null ;
Stack < SVNodeData > parents = new Stack < SVNodeData > ( ) ; SVPropertyData currentProperty = null ; ValueWriter propertyValue = null ; int propertyType = - 1 ; while ( reader . hasNext ( ) ) { int eventCode = reader . next ( ) ; switch ( eventCode ) { case StartElement . START_ELEMENT : { String lname = reader . getLocalName ( ) ; String prefix = reader . getPrefix ( ) ; if ( Constants . NS_SV_PREFIX . equals ( prefix ) ) { // read prefixes URIes from source SV XML
if ( svURI == null ) { svURI = reader . getNamespaceURI ( Constants . NS_SV_PREFIX ) ; exoURI = reader . getNamespaceURI ( Constants . NS_EXO_PREFIX ) ; } if ( Constants . SV_NODE . equals ( lname ) ) { String svName = reader . getAttributeValue ( svURI , Constants . SV_NAME ) ; String exoId = reader . getAttributeValue ( exoURI , Constants . EXO_ID ) ; if ( svName != null && exoId != null ) { // create subnode
QPath currentPath ; String parentId ; int orderNumber ; if ( parents . size ( ) > 0 ) { // path to a new node
SVNodeData parent = parents . peek ( ) ; InternalQName name = locationFactory . parseJCRName ( svName ) . getInternalName ( ) ; int [ ] chi = parent . addChildNode ( name ) ; orderNumber = chi [ 0 ] ; int index = chi [ 1 ] ; currentPath = QPath . makeChildPath ( parent . getQPath ( ) , name , index ) ; parentId = parent . getIdentifier ( ) ; } else { // root
currentPath = Constants . ROOT_PATH ; parentId = null ; orderNumber = 0 ; // register namespaces from jcr : root node
for ( int i = 0 ; i < reader . getNamespaceCount ( ) ; i ++ ) { String nsp = reader . getNamespacePrefix ( i ) ; try { namespaceRegistry . getURI ( nsp ) ; } catch ( NamespaceException e ) { namespaceRegistry . registerNamespace ( nsp , reader . getNamespaceURI ( i ) ) ; } } } SVNodeData currentNode = new SVNodeData ( currentPath , exoId , parentId , 0 , orderNumber ) ; AccessControlList acl = ACLInitializationHelper . initAcl ( parents . size ( ) == 0 ? null : parents . peek ( ) . getACL ( ) , null , null ) ; currentNode . setACL ( acl ) ; // push current node as parent
parents . push ( currentNode ) ; // add current node to changes log .
// add node , no event fire , persisted , internally created , root is ancestor to save
changes . add ( new ItemState ( currentNode , ItemState . ADDED , false , Constants . ROOT_PATH , true , true ) ) ; } else LOG . warn ( "Node skipped name=" + svName + " id=" + exoId + ". Context node " + ( parents . size ( ) > 0 ? parents . peek ( ) . getQPath ( ) . getAsString ( ) : "/" ) ) ; } else if ( Constants . SV_PROPERTY . equals ( lname ) ) { String svName = reader . getAttributeValue ( svURI , Constants . SV_NAME ) ; String exoId = reader . getAttributeValue ( exoURI , Constants . EXO_ID ) ; String svType = reader . getAttributeValue ( svURI , Constants . SV_TYPE ) ; if ( svName != null && svType != null && exoId != null ) { if ( parents . size ( ) > 0 ) { SVNodeData parent = parents . peek ( ) ; QPath currentPath = QPath . makeChildPath ( parent . getQPath ( ) , locationFactory . parseJCRName ( svName ) . getInternalName ( ) ) ; try { propertyType = PropertyType . valueFromName ( svType ) ; } catch ( IllegalArgumentException e ) { propertyType = ExtendedPropertyType . valueFromName ( svType ) ; } // exo : multivalued optional , assigned for multivalued properties only
String exoMultivalued = reader . getAttributeValue ( exoURI , Constants . EXO_MULTIVALUED ) ; currentProperty = new SVPropertyData ( currentPath , exoId , 0 , propertyType , parent . getIdentifier ( ) , ( "true" . equals ( exoMultivalued ) ? true : false ) ) ; } else LOG . warn ( "Property can'b be first name=" + svName + " type=" + svType + " id=" + exoId + ". Node should be prior. Context node " + ( parents . size ( ) > 0 ? parents . peek ( ) . getQPath ( ) . getAsString ( ) : "/" ) ) ; } else LOG . warn ( "Property skipped name=" + svName + " type=" + svType + " id=" + exoId + ". Context node " + ( parents . size ( ) > 0 ? parents . peek ( ) . getQPath ( ) . getAsString ( ) : "/" ) ) ; } else if ( Constants . SV_VALUE . equals ( lname ) && propertyType != - 1 ) { if ( propertyType == PropertyType . BINARY ) propertyValue = new BinaryValueWriter ( ) ; else propertyValue = new StringValueWriter ( ) ; } } break ; } case StartElement . CHARACTERS : { if ( propertyValue != null ) { // read property value text
propertyValue . write ( reader . getText ( ) ) ; } break ; } case StartElement . END_ELEMENT : { String lname = reader . getLocalName ( ) ; String prefix = reader . getPrefix ( ) ; if ( Constants . NS_SV_PREFIX . equals ( prefix ) ) { if ( Constants . SV_NODE . equals ( lname ) ) { // change current context
// - pop parent from the stack
SVNodeData parent = parents . pop ( ) ; if ( parent . getMixinTypeNames ( ) == null ) { // mixins cannot be null
parent . setMixinTypeNames ( new InternalQName [ 0 ] ) ; } } else if ( Constants . SV_PROPERTY . equals ( lname ) ) { // apply property to the current node and changes log
if ( currentProperty != null ) { SVNodeData parent = parents . peek ( ) ; // check NodeData specific properties
if ( currentProperty . getQPath ( ) . getName ( ) . equals ( Constants . JCR_PRIMARYTYPE ) ) { parent . setPrimartTypeName ( InternalQName . parse ( ValueDataUtil . getString ( currentProperty . getValues ( ) . get ( 0 ) ) ) ) ; } else if ( currentProperty . getQPath ( ) . getName ( ) . equals ( Constants . JCR_MIXINTYPES ) ) { InternalQName [ ] mixins = new InternalQName [ currentProperty . getValues ( ) . size ( ) ] ; for ( int i = 0 ; i < currentProperty . getValues ( ) . size ( ) ; i ++ ) { mixins [ i ] = InternalQName . parse ( ValueDataUtil . getString ( currentProperty . getValues ( ) . get ( i ) ) ) ; } parent . setMixinTypeNames ( mixins ) ; } else if ( currentProperty . getQPath ( ) . getName ( ) . equals ( Constants . EXO_OWNER ) ) { String exoOwner = ValueDataUtil . getString ( currentProperty . getValues ( ) . get ( 0 ) ) ; parent . setExoOwner ( exoOwner ) ; SVNodeData curParent = parents . pop ( ) ; AccessControlList acl = ACLInitializationHelper . initAcl ( parents . size ( ) == 0 ? null : parents . peek ( ) . getACL ( ) , exoOwner , curParent . getExoPrivileges ( ) ) ; curParent . setACL ( acl ) ; parents . push ( curParent ) ; } else if ( currentProperty . getQPath ( ) . getName ( ) . equals ( Constants . EXO_PERMISSIONS ) ) { List < String > exoPrivileges = new ArrayList < String > ( ) ; for ( int i = 0 ; i < currentProperty . getValues ( ) . size ( ) ; i ++ ) { exoPrivileges . add ( ValueDataUtil . getString ( currentProperty . getValues ( ) . get ( i ) ) ) ; } parent . setExoPrivileges ( exoPrivileges ) ; SVNodeData curParent = parents . pop ( ) ; AccessControlList acl = ACLInitializationHelper . initAcl ( parents . size ( ) == 0 ? null : parents . peek ( ) . getACL ( ) , curParent . getExoOwner ( ) , exoPrivileges ) ; curParent . setACL ( acl ) ; parents . push ( curParent ) ; } // add property , no event fire , persisted , internally created , root is ancestor to
// save
changes . add ( new ItemState ( currentProperty , ItemState . ADDED , false , Constants . ROOT_PATH , true , true ) ) ; // reset property context
propertyType = - 1 ; currentProperty = null ; } } else if ( Constants . SV_VALUE . equals ( lname ) ) { // apply property value to the current property
propertyValue . close ( ) ; TransientValueData vdata ; if ( propertyType == PropertyType . NAME ) { vdata = new TransientValueData ( currentProperty . getValues ( ) . size ( ) , locationFactory . parseJCRName ( propertyValue . getText ( ) ) . getInternalName ( ) ) ; } else if ( propertyType == PropertyType . PATH ) { vdata = new TransientValueData ( currentProperty . getValues ( ) . size ( ) , locationFactory . parseJCRPath ( propertyValue . getText ( ) ) . getInternalPath ( ) ) ; } else if ( propertyType == PropertyType . DATE ) { vdata = new TransientValueData ( currentProperty . getValues ( ) . size ( ) , JCRDateFormat . parse ( propertyValue . getText ( ) ) ) ; } else if ( propertyType == PropertyType . BINARY ) { if ( propertyValue . isText ( ) ) { vdata = new TransientValueData ( currentProperty . getValues ( ) . size ( ) , propertyValue . getText ( ) ) ; } else { File pfile = propertyValue . getFile ( ) ; if ( pfile != null ) { vdata = new TransientValueData ( currentProperty . getValues ( ) . size ( ) , null , new SpoolFile ( PrivilegedFileHelper . getAbsolutePath ( pfile ) ) , spoolConfig ) ; } else { vdata = new TransientValueData ( currentProperty . getValues ( ) . size ( ) , new byte [ ] { } ) ; } } } else { // other like String
vdata = new TransientValueData ( currentProperty . getValues ( ) . size ( ) , propertyValue . getText ( ) ) ; } currentProperty . getValues ( ) . add ( vdata ) ; // reset value context
propertyValue = null ; } } break ; } } } return changes ; } finally { input . close ( ) ; } |
public class HttpDownUtil { /** * 取当前请求的ContentLength */
public static long getDownContentSize ( HttpHeaders resHeaders ) { } } | String contentRange = resHeaders . get ( HttpHeaderNames . CONTENT_RANGE ) ; if ( contentRange != null ) { Pattern pattern = Pattern . compile ( "^[^\\d]*(\\d+)-(\\d+)/.*$" ) ; Matcher matcher = pattern . matcher ( contentRange ) ; if ( matcher . find ( ) ) { long startSize = Long . parseLong ( matcher . group ( 1 ) ) ; long endSize = Long . parseLong ( matcher . group ( 2 ) ) ; return endSize - startSize + 1 ; } } else { String contentLength = resHeaders . get ( HttpHeaderNames . CONTENT_LENGTH ) ; if ( contentLength != null ) { return Long . valueOf ( resHeaders . get ( HttpHeaderNames . CONTENT_LENGTH ) ) ; } } return 0 ; |
public class ResourceNotFoundException { /** * Value is a list of resource IDs that were not found .
* @ return Value is a list of resource IDs that were not found . */
@ com . fasterxml . jackson . annotation . JsonProperty ( "ResourceIds" ) public java . util . List < String > getResourceIds ( ) { } } | return resourceIds ; |
public class CmsVfsTab { /** * Selects a specific site . < p >
* @ param siteRoot the site root */
private void selectSite ( String siteRoot ) { } } | if ( m_sortSelectBox == null ) { return ; } Map < String , String > options = m_sortSelectBox . getItems ( ) ; String option = null ; for ( Map . Entry < String , String > entry : options . entrySet ( ) ) { if ( CmsStringUtil . comparePaths ( entry . getKey ( ) , siteRoot ) ) { option = entry . getKey ( ) ; break ; } } if ( option != null ) { m_sortSelectBox . setFormValue ( option , false ) ; } |
public class StorageUtil { /** * reads a XML Element Attribute ans cast it to a boolean value
* @ param el XML Element to read Attribute from it
* @ param attributeName Name of the Attribute to read
* @ param defaultValue if attribute doesn ' t exist return default value
* @ return Attribute Value */
public boolean toBoolean ( Element el , String attributeName , boolean defaultValue ) { } } | String value = el . getAttribute ( attributeName ) ; if ( value == null ) return defaultValue ; return Caster . toBooleanValue ( value , false ) ; |
public class FieldFinder { /** * find fields on target to validate and prepare for their validation */
@ SuppressWarnings ( "TryWithIdenticalCatches" ) private static Map < View , FormValidator . FieldInfo > findFieldsToValidate ( Object target ) { } } | final Field [ ] fields = target . getClass ( ) . getDeclaredFields ( ) ; if ( fields == null || fields . length == 0 ) { return Collections . emptyMap ( ) ; } final WeakHashMap < View , FormValidator . FieldInfo > infoMap = new WeakHashMap < > ( fields . length ) ; for ( Field field : fields ) { final List < FormValidator . ValidationInfo > infos = new ArrayList < > ( ) ; final Annotation [ ] annotations = field . getDeclaredAnnotations ( ) ; if ( annotations . length > 0 ) { if ( ! View . class . isAssignableFrom ( field . getType ( ) ) ) { // next field
continue ; } final View view ; try { field . setAccessible ( true ) ; view = ( View ) field . get ( target ) ; } catch ( IllegalAccessException e ) { throw new FormsValidationException ( e ) ; } if ( view == null ) { continue ; } for ( Annotation annotation : annotations ) { final IValidator validator ; try { validator = ValidatorFactory . getValidator ( annotation ) ; } catch ( IllegalAccessException e ) { throw new FormsValidationException ( e ) ; } catch ( InstantiationException e ) { throw new FormsValidationException ( e ) ; } if ( validator != null ) { FormValidator . ValidationInfo info = new FormValidator . ValidationInfo ( annotation , validator ) ; infos . add ( info ) ; } } final Condition conditionAnnotation = field . getAnnotation ( Condition . class ) ; if ( infos . size ( ) > 0 ) { Collections . sort ( infos , new Comparator < FormValidator . ValidationInfo > ( ) { @ Override public int compare ( FormValidator . ValidationInfo lhs , FormValidator . ValidationInfo rhs ) { return lhs . order < rhs . order ? - 1 : ( lhs . order == rhs . order ? 0 : 1 ) ; } } ) ; } final FormValidator . FieldInfo fieldInfo = new FormValidator . FieldInfo ( conditionAnnotation , infos ) ; infoMap . put ( view , fieldInfo ) ; } } return infoMap ; |
public class ProxiedFileSystemWrapper { /** * Getter for proxiedFs , using the passed parameters to create an instance of a proxiedFs .
* @ param properties
* @ param authType is either TOKEN or KEYTAB .
* @ param authPath is the KEYTAB location if the authType is KEYTAB ; otherwise , it is the token file .
* @ param uri File system URI .
* @ throws IOException
* @ throws InterruptedException
* @ throws URISyntaxException
* @ return proxiedFs */
public FileSystem getProxiedFileSystem ( State properties , AuthType authType , String authPath , String uri , final Configuration conf ) throws IOException , InterruptedException , URISyntaxException { } } | Preconditions . checkArgument ( StringUtils . isNotBlank ( properties . getProp ( ConfigurationKeys . FS_PROXY_AS_USER_NAME ) ) , "State does not contain a proper proxy user name" ) ; String proxyUserName = properties . getProp ( ConfigurationKeys . FS_PROXY_AS_USER_NAME ) ; UserGroupInformation proxyUser ; switch ( authType ) { case KEYTAB : // If the authentication type is KEYTAB , log in a super user first before creating a proxy user .
Preconditions . checkArgument ( StringUtils . isNotBlank ( properties . getProp ( ConfigurationKeys . SUPER_USER_NAME_TO_PROXY_AS_OTHERS ) ) , "State does not contain a proper proxy token file name" ) ; String superUser = properties . getProp ( ConfigurationKeys . SUPER_USER_NAME_TO_PROXY_AS_OTHERS ) ; UserGroupInformation . loginUserFromKeytab ( superUser , authPath ) ; proxyUser = UserGroupInformation . createProxyUser ( proxyUserName , UserGroupInformation . getLoginUser ( ) ) ; break ; case TOKEN : // If the authentication type is TOKEN , create a proxy user and then add the token to the user .
proxyUser = UserGroupInformation . createProxyUser ( proxyUserName , UserGroupInformation . getLoginUser ( ) ) ; Optional < Token < ? > > proxyToken = getTokenFromSeqFile ( authPath , proxyUserName ) ; if ( proxyToken . isPresent ( ) ) { proxyUser . addToken ( proxyToken . get ( ) ) ; } else { LOG . warn ( "No delegation token found for the current proxy user." ) ; } break ; default : LOG . warn ( "Creating a proxy user without authentication, which could not perform File system operations." ) ; proxyUser = UserGroupInformation . createProxyUser ( proxyUserName , UserGroupInformation . getLoginUser ( ) ) ; break ; } final URI fsURI = URI . create ( uri ) ; proxyUser . doAs ( new PrivilegedExceptionAction < Void > ( ) { @ Override public Void run ( ) throws IOException { LOG . debug ( "Now performing file system operations as :" + UserGroupInformation . getCurrentUser ( ) ) ; proxiedFs = FileSystem . get ( fsURI , conf ) ; return null ; } } ) ; return this . proxiedFs ; |
public class DataGrid { /** * Implementation of the { @ link IBehaviorConsumer } interface that extends the functionality of this
* tag beyond that exposed via the JSP tag attributes . This method accepts the following facets :
* < table >
* < tr > < td > Facet Name < / td > < td > Operation < / td > < / tr >
* < tr > < td > < code > resource < / code > < / td > < td > Adds or overrides a data grid resource key with a new value . < / td > < / tr >
* < / table >
* A new resource key is added in order to override a value defined in
* { @ link org . apache . beehive . netui . databinding . datagrid . api . rendering . IDataGridMessageKeys } . When a message
* is overridden or added here , the page author is able to override a single string resource such as a
* pager mesage or sort href .
* @ param name the name of the behavior
* @ param value the value of the behavior
* @ param facet th ebehavior ' s facet
* @ throws JspException when the behavior ' s facet isnot recognized */
public void setBehavior ( String name , Object value , String facet ) throws JspException { } } | if ( facet != null && facet . equals ( FACET_RESOURCE ) ) { _dataGridTagModel . addResourceOverride ( name , ( value != null ? value . toString ( ) : null ) ) ; } else { String s = Bundle . getString ( "Tags_BehaviorFacetNotSupported" , new Object [ ] { facet } ) ; throw new JspException ( s ) ; } |
public class ConfigurationIdMarshaller { /** * Marshall the given parameter object . */
public void marshall ( ConfigurationId configurationId , ProtocolMarshaller protocolMarshaller ) { } } | if ( configurationId == null ) { throw new SdkClientException ( "Invalid argument passed to marshall(...)" ) ; } try { protocolMarshaller . marshall ( configurationId . getId ( ) , ID_BINDING ) ; protocolMarshaller . marshall ( configurationId . getRevision ( ) , REVISION_BINDING ) ; } catch ( Exception e ) { throw new SdkClientException ( "Unable to marshall request to JSON: " + e . getMessage ( ) , e ) ; } |
public class ImagePathTag { /** * Returns the image URL generated by Jawr from a source image path
* @ param context
* the faces context
* @ param src
* the image source
* @ param base64
* the flag indicating if the image should be encoded in base64
* @ return the image URL generated by Jawr from a source image path */
protected String getImageUrl ( FacesContext context , String src , boolean base64 ) { } } | BinaryResourcesHandler imgRsHandler = getBinaryResourcesHandler ( context ) ; HttpServletResponse response = ( ( HttpServletResponse ) context . getExternalContext ( ) . getResponse ( ) ) ; HttpServletRequest request = ( HttpServletRequest ) context . getExternalContext ( ) . getRequest ( ) ; return ImageTagUtils . getImageUrl ( src , base64 , imgRsHandler , request , response ) ; |
public class MultipleEvaluationMetricRunner { /** * Gets all prediction files .
* @ param predictionFiles The prediction files .
* @ param path The path where the splits are .
* @ param predictionPrefix The prefix of the prediction files . */
public static void getAllPredictionFiles ( final Set < String > predictionFiles , final File path , final String predictionPrefix ) { } } | if ( path == null ) { return ; } File [ ] files = path . listFiles ( ) ; if ( files == null ) { return ; } for ( File file : files ) { if ( file . isDirectory ( ) ) { getAllPredictionFiles ( predictionFiles , file , predictionPrefix ) ; } else if ( file . getName ( ) . startsWith ( predictionPrefix ) ) { predictionFiles . add ( file . getAbsolutePath ( ) . replaceAll ( predictionPrefix , "" ) ) ; } } |
public class LinkedList { /** * ( non - Javadoc )
* @ see com . ibm . ws . objectManager . Collection # size ( ) */
public long size ( ) throws ObjectManagerException { } } | if ( Tracing . isAnyTracingEnabled ( ) && trace . isEntryEnabled ( ) ) trace . entry ( this , cclass , "size" ) ; // TODO Need to include toBeDeleted .
long listLength = size ; // For return ;
if ( Tracing . isAnyTracingEnabled ( ) && trace . isEntryEnabled ( ) ) trace . exit ( this , cclass , "size" , "returns listLength=" + listLength + "(int)" ) ; return listLength ; |
public class MpxjQuery { /** * This method displays the resource assignments for each resource . This time
* rather than just iterating through the list of all assignments in
* the file , we extract the assignments on a resource - by - resource basis .
* @ param file MPX file */
private static void listAssignmentsByResource ( ProjectFile file ) { } } | for ( Resource resource : file . getResources ( ) ) { System . out . println ( "Assignments for resource " + resource . getName ( ) + ":" ) ; for ( ResourceAssignment assignment : resource . getTaskAssignments ( ) ) { Task task = assignment . getTask ( ) ; System . out . println ( " " + task . getName ( ) ) ; } } System . out . println ( ) ; |
public class Model { /** * 增加特征到特征数中
* @ param cs
* @ param tempW */
protected static void printFeatureTree ( String cs , float [ ] tempW ) { } } | String name = "*" ; if ( tempW . length == 4 ) { name = "U" ; } name += "*" + ( cs . charAt ( cs . length ( ) - 1 ) - Config . FEATURE_BEGIN + 1 ) + ":" + cs . substring ( 0 , cs . length ( ) - 1 ) ; for ( int i = 0 ; i < tempW . length ; i ++ ) { if ( tempW [ i ] != 0 ) { System . out . println ( name + "\t" + Config . getTagName ( i / 4 - 1 ) + "\t" + Config . getTagName ( i % 4 ) + "\t" + tempW [ i ] ) ; } } |
public class SessionManagerMBeanImpl { /** * Reduce the map to the set of expected keys */
private Map < String , Object > filterUnexpectedKeys ( Map < String , Object > inputProps ) { } } | Map < String , Object > outputProps = new HashMap < String , Object > ( ) ; Set < Entry < String , Object > > entries = inputProps . entrySet ( ) ; for ( Map . Entry < String , Object > entry : entries ) { String key = entry . getKey ( ) ; if ( EXPECTED_KEYS . contains ( key ) ) { outputProps . put ( key , entry . getValue ( ) ) ; } } return outputProps ; |
public class JMPathOperation { /** * Create file optional .
* @ param path the path
* @ param attrs the attrs
* @ return the optional */
public static Optional < Path > createFile ( Path path , FileAttribute < ? > ... attrs ) { } } | debug ( log , "createFile" , path , attrs ) ; try { return Optional . of ( Files . createFile ( path , attrs ) ) ; } catch ( Exception e ) { return JMExceptionManager . handleExceptionAndReturnEmptyOptional ( log , e , "createFile" , path ) ; } |
public class Dict { /** * 填充Value Object对象 , 忽略大小写
* @ param < T > Bean类型
* @ param clazz Value Object ( 或者POJO ) 的类
* @ return vo */
public < T > T toBeanIgnoreCase ( Class < T > clazz ) { } } | return BeanUtil . mapToBeanIgnoreCase ( this , clazz , false ) ; |
public class TimeColumn { /** * Conditionally update this column , replacing current values with newValue for all rows where the current value
* matches the selection criteria
* Example :
* myColumn . set ( myColumn . valueIsMissing ( ) , LocalTime . now ( ) ) ; / / no more missing values */
public TimeColumn set ( Selection rowSelection , LocalTime newValue ) { } } | for ( int row : rowSelection ) { set ( row , newValue ) ; } return this ; |
public class JKStringUtil { /** * replace under score with space replace \ n char with platform indepent
* line . separator
* @ param value the value
* @ return the string */
public static String fixValue ( String value ) { } } | if ( value != null && ! value . equals ( "" ) ) { final String [ ] words = value . toLowerCase ( ) . split ( "_" ) ; value = "" ; for ( final String word : words ) { if ( word . length ( ) > 1 ) { value += word . substring ( 0 , 1 ) . toUpperCase ( ) + word . substring ( 1 ) + " " ; } else { value = word ; } } } if ( value . contains ( "\\n" ) ) { value = value . replace ( "\\n" , System . getProperty ( "line.separator" ) ) ; } return value ; |
public class ObjectSerializer { /** * Transform the given bytes into an object .
* @ param bytes The bytes to construct the object from
* @ return The object constructed */
@ SuppressWarnings ( "unchecked" ) public T toObject ( byte [ ] bytes ) { } } | try { return ( T ) new ObjectInputStream ( new ByteArrayInputStream ( bytes ) ) . readObject ( ) ; } catch ( IOException e ) { throw new SerializationException ( e ) ; } catch ( ClassNotFoundException c ) { throw new SerializationException ( c ) ; } |
public class OgnlPropertyExtractor { /** * extract .
* @ param target a { @ link java . lang . Object } object .
* @ param property a { @ link java . lang . String } object .
* @ return a { @ link java . lang . Object } object .
* @ throws java . lang . Exception if any . */
protected Object extract ( Object target , String property ) throws Exception { } } | if ( errorProperties . contains ( property ) ) return null ; Object value = null ; try { value = expressionEvaluator . eval ( property , target ) ; } catch ( EvaluationException e ) { return null ; } if ( value instanceof Boolean ) { if ( null == textResource ) { return value ; } else { if ( Boolean . TRUE . equals ( value ) ) return getText ( "common.yes" , "Y" ) ; else return getText ( "common.no" , "N" ) ; } } else { return value ; } |
public class XmlSchemaParser { /** * Wraps the { @ link InputStream } into an { @ link InputSource } and delegates to
* { @ link # parse ( InputSource , ParserOptions ) } .
* < b > Note : < / b > this method does not set the { @ link InputSource # setSystemId ( java . lang . String ) } property .
* However , it is recommended to use the { @ link # parse ( InputSource , ParserOptions ) } method directly .
* @ param in stream from which schema is read .
* @ param options to be applied during parsing .
* @ return { @ link MessageSchema } encoding for the schema .
* @ throws Exception on parsing error . */
public static MessageSchema parse ( final InputStream in , final ParserOptions options ) throws Exception { } } | return parse ( new InputSource ( in ) , options ) ; |
public class PersistenceUnitMetadataImpl { /** * If not already created , a new < code > persistence - unit - defaults < / code > element with the given value will be created .
* Otherwise , the existing < code > persistence - unit - defaults < / code > element will be returned .
* @ return a new or existing instance of < code > PersistenceUnitDefaults < PersistenceUnitMetadata < T > > < / code > */
public PersistenceUnitDefaults < PersistenceUnitMetadata < T > > getOrCreatePersistenceUnitDefaults ( ) { } } | Node node = childNode . getOrCreate ( "persistence-unit-defaults" ) ; PersistenceUnitDefaults < PersistenceUnitMetadata < T > > persistenceUnitDefaults = new PersistenceUnitDefaultsImpl < PersistenceUnitMetadata < T > > ( this , "persistence-unit-defaults" , childNode , node ) ; return persistenceUnitDefaults ; |
public class Utils { /** * Search for intermediate shape model by its c2j name .
* @ return ShapeModel
* @ throws IllegalArgumentException
* if the specified c2j name is not found in the intermediate model . */
public static ShapeModel findShapeModelByC2jName ( IntermediateModel intermediateModel , String shapeC2jName ) throws IllegalArgumentException { } } | ShapeModel shapeModel = findShapeModelByC2jNameIfExists ( intermediateModel , shapeC2jName ) ; if ( shapeModel != null ) { return shapeModel ; } else { throw new IllegalArgumentException ( shapeC2jName + " shape (c2j name) does not exist in the intermediate model." ) ; } |
public class AmazonGameLiftClient { /** * Resumes activity on a fleet that was suspended with < a > StopFleetActions < / a > . Currently , this operation is used to
* restart a fleet ' s auto - scaling activity .
* To start fleet actions , specify the fleet ID and the type of actions to restart . When auto - scaling fleet actions
* are restarted , Amazon GameLift once again initiates scaling events as triggered by the fleet ' s scaling policies .
* If actions on the fleet were never stopped , this operation will have no effect . You can view a fleet ' s stopped
* actions using < a > DescribeFleetAttributes < / a > .
* < b > Learn more < / b >
* < a href = " https : / / docs . aws . amazon . com / gamelift / latest / developerguide / fleets - intro . html " > Working with Fleets < / a > .
* < b > Related operations < / b >
* < ul >
* < li >
* < a > CreateFleet < / a >
* < / li >
* < li >
* < a > ListFleets < / a >
* < / li >
* < li >
* < a > DeleteFleet < / a >
* < / li >
* < li >
* Describe fleets :
* < ul >
* < li >
* < a > DescribeFleetAttributes < / a >
* < / li >
* < li >
* < a > DescribeFleetCapacity < / a >
* < / li >
* < li >
* < a > DescribeFleetPortSettings < / a >
* < / li >
* < li >
* < a > DescribeFleetUtilization < / a >
* < / li >
* < li >
* < a > DescribeRuntimeConfiguration < / a >
* < / li >
* < li >
* < a > DescribeEC2InstanceLimits < / a >
* < / li >
* < li >
* < a > DescribeFleetEvents < / a >
* < / li >
* < / ul >
* < / li >
* < li >
* Update fleets :
* < ul >
* < li >
* < a > UpdateFleetAttributes < / a >
* < / li >
* < li >
* < a > UpdateFleetCapacity < / a >
* < / li >
* < li >
* < a > UpdateFleetPortSettings < / a >
* < / li >
* < li >
* < a > UpdateRuntimeConfiguration < / a >
* < / li >
* < / ul >
* < / li >
* < li >
* Manage fleet actions :
* < ul >
* < li >
* < a > StartFleetActions < / a >
* < / li >
* < li >
* < a > StopFleetActions < / a >
* < / li >
* < / ul >
* < / li >
* < / ul >
* @ param startFleetActionsRequest
* @ return Result of the StartFleetActions operation returned by the service .
* @ 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 InvalidRequestException
* One or more parameter values in the request are invalid . Correct the invalid parameter values before
* retrying .
* @ throws UnauthorizedException
* The client failed authentication . Clients should not retry such requests .
* @ throws NotFoundException
* A service resource associated with the request could not be found . Clients should not retry such
* requests .
* @ sample AmazonGameLift . StartFleetActions
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / gamelift - 2015-10-01 / StartFleetActions " target = " _ top " > AWS API
* Documentation < / a > */
@ Override public StartFleetActionsResult startFleetActions ( StartFleetActionsRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeStartFleetActions ( request ) ; |
public class QueryStatisticsInner { /** * Lists a query ' s statistics .
* @ 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 serverName The name of the server .
* @ param databaseName The name of the database .
* @ param queryId The id of the query
* @ throws IllegalArgumentException thrown if parameters fail the validation
* @ return the observable to the List & lt ; QueryStatisticInner & gt ; object */
public Observable < List < QueryStatisticInner > > listByQueryAsync ( String resourceGroupName , String serverName , String databaseName , String queryId ) { } } | return listByQueryWithServiceResponseAsync ( resourceGroupName , serverName , databaseName , queryId ) . map ( new Func1 < ServiceResponse < List < QueryStatisticInner > > , List < QueryStatisticInner > > ( ) { @ Override public List < QueryStatisticInner > call ( ServiceResponse < List < QueryStatisticInner > > response ) { return response . body ( ) ; } } ) ; |
public class AWSShieldClient { /** * Lists all < a > Protection < / a > objects for the account .
* @ param listProtectionsRequest
* @ return Result of the ListProtections operation returned by the service .
* @ throws InternalErrorException
* Exception that indicates that a problem occurred with the service infrastructure . You can retry the
* request .
* @ throws ResourceNotFoundException
* Exception indicating the specified resource does not exist .
* @ throws InvalidPaginationTokenException
* Exception that indicates that the NextToken specified in the request is invalid . Submit the request using
* the NextToken value that was returned in the response .
* @ sample AWSShield . ListProtections
* @ see < a href = " http : / / docs . aws . amazon . com / goto / WebAPI / shield - 2016-06-02 / ListProtections " target = " _ top " > AWS API
* Documentation < / a > */
@ Override public ListProtectionsResult listProtections ( ListProtectionsRequest request ) { } } | request = beforeClientExecution ( request ) ; return executeListProtections ( request ) ; |
public class BinomialDistributionTypeImpl { /** * < ! - - begin - user - doc - - >
* < ! - - end - user - doc - - >
* @ generated */
public void setTrials ( long newTrials ) { } } | long oldTrials = trials ; trials = newTrials ; boolean oldTrialsESet = trialsESet ; trialsESet = true ; if ( eNotificationRequired ( ) ) eNotify ( new ENotificationImpl ( this , Notification . SET , BpsimPackage . BINOMIAL_DISTRIBUTION_TYPE__TRIALS , oldTrials , trials , ! oldTrialsESet ) ) ; |
public class ScreenField { /** * This field changed , if this is the main record , lock it !
* @ param field The field that changed . */
public void fieldChanged ( Field field ) { } } | BasePanel screenParent = this . getParentScreen ( ) ; if ( field == null ) if ( m_converterField != null ) field = m_converterField . getField ( ) ; // This field changed
if ( screenParent != null ) screenParent . fieldChanged ( field ) ; |
public class ClientSocketFactory { /** * Clears the recycled connections , e . g . on detection of backend
* server going down . */
public void clearRecycle ( ) { } } | ArrayList < ClientSocket > recycleList = null ; synchronized ( this ) { _idleHead = _idleTail = 0 ; for ( int i = 0 ; i < _idle . length ; i ++ ) { ClientSocket stream ; stream = _idle [ i ] ; _idle [ i ] = null ; if ( stream != null ) { if ( recycleList == null ) recycleList = new ArrayList < ClientSocket > ( ) ; recycleList . add ( stream ) ; } } } if ( recycleList != null ) { for ( ClientSocket stream : recycleList ) { stream . closeImpl ( ) ; } } |
public class Solo { /** * Returns a Button displaying the specified text .
* @ param text the text that is displayed , specified as a regular expression
* @ param onlyVisible { @ code true } if only visible buttons on the screen should be returned
* @ return the { @ link Button } displaying the specified text */
public Button getButton ( String text , boolean onlyVisible ) { } } | if ( config . commandLogging ) { Log . d ( config . commandLoggingTag , "getButton(\"" + text + "\", " + onlyVisible + ")" ) ; } return getter . getView ( Button . class , text , onlyVisible ) ; |
public class AddressBinding { /** * Turns this address into a ModelNode with an address property . < br / >
* This method allows to specify a base address prefix ( i . e server vs . domain addressing ) .
* @ param baseAddress
* @ param args parameters for address wildcards
* @ return a ModelNode with an address property */
public ModelNode asResource ( ModelNode baseAddress , String ... args ) { } } | assert getNumWildCards ( ) == args . length : "Address arguments don't match number of wildcards: " + getNumWildCards ( ) + " -> " + Arrays . toString ( args ) ; ModelNode model = new ModelNode ( ) ; model . get ( ADDRESS ) . set ( baseAddress ) ; int argsCounter = 0 ; for ( String [ ] tuple : address ) { String parent = tuple [ 0 ] ; String child = tuple [ 1 ] ; if ( parent . startsWith ( "{" ) ) { parent = args [ argsCounter ] ; argsCounter ++ ; } if ( child . startsWith ( "{" ) ) { child = args [ argsCounter ] ; argsCounter ++ ; } model . get ( ADDRESS ) . add ( parent , child ) ; } return model ; |
public class CSL { /** * Sets the processor ' s output format
* @ param format the format ( one of < code > " html " < / code > ,
* < code > " text " < / code > , < code > " asciidoc " < / code > , < code > " fo " < / code > ,
* or < code > " rtf " < / code > ) */
public void setOutputFormat ( String format ) { } } | try { runner . callMethod ( engine , "setOutputFormat" , format ) ; outputFormat = format ; } catch ( ScriptRunnerException e ) { throw new IllegalArgumentException ( "Could not set output format" , e ) ; } |
public class PinView { /** * Set titles ( see { @ link TextView } ) values to add to { @ link PinView } , with all attributes .
* @ param titles string array with the titles values */
@ Override public void setTitles ( String [ ] titles ) { } } | if ( titles != null ) { mLinearLayoutPinTexts . removeAllViews ( ) ; mPinTitles = titles ; pinTitlesIds = new int [ titles . length ] ; for ( int i = 0 ; i < titles . length ; i ++ ) { mLinearLayoutPinTexts . addView ( generatePinText ( i , titles ) , i ) ; } } |
public class HppRequest { /** * Creates the security hash from a number of fields and the shared secret .
* @ param secret
* @ return HppRequest */
public HppRequest hash ( String secret ) { } } | // Override payerRef with hppSelectStoredCard if present .
if ( this . hppSelectStoredCard != null && ! "" . equalsIgnoreCase ( this . hppSelectStoredCard ) ) { this . payerReference = this . hppSelectStoredCard ; } // check for any null values and set them to empty string for hashing
String timeStamp = null == this . timeStamp ? "" : this . timeStamp ; String merchantId = null == this . merchantId ? "" : this . merchantId ; String orderId = null == this . orderId ? "" : this . orderId ; String amount = null == this . amount ? "" : this . amount ; String currency = null == this . currency ? "" : this . currency ; String payerReference = null == this . payerReference ? "" : this . payerReference ; String paymentReference = null == this . paymentReference ? "" : this . paymentReference ; String hppFraudFilterMode = null == this . hppFraudFilterMode ? "" : this . hppFraudFilterMode ; // create String to hash . Check for card storage enable flag to determine if Real Vault transaction
StringBuilder toHash = new StringBuilder ( ) ; if ( Flag . TRUE . getFlag ( ) . equals ( cardStorageEnable ) || ( hppSelectStoredCard != null && ! hppSelectStoredCard . isEmpty ( ) ) ) { toHash . append ( timeStamp ) . append ( "." ) . append ( merchantId ) . append ( "." ) . append ( orderId ) . append ( "." ) . append ( amount ) . append ( "." ) . append ( currency ) . append ( "." ) . append ( payerReference ) . append ( "." ) . append ( paymentReference ) ; if ( ! hppFraudFilterMode . equals ( "" ) ) { toHash . append ( "." ) . append ( this . hppFraudFilterMode ) ; } } else { toHash . append ( timeStamp ) . append ( "." ) . append ( merchantId ) . append ( "." ) . append ( orderId ) . append ( "." ) . append ( amount ) . append ( "." ) . append ( currency ) ; if ( ! hppFraudFilterMode . equals ( "" ) ) { toHash . append ( "." ) . append ( this . hppFraudFilterMode ) ; } } this . hash = GenerationUtils . generateHash ( toHash . toString ( ) , secret ) ; return this ; |
public class ZipCompletionScanner { /** * Boyer Moore scan that proceeds backwards from the end of the file looking for ENDSIG
* @ throws NonScannableZipException */
private static boolean scanForEndSig ( File file , FileChannel channel ) throws IOException , NonScannableZipException { } } | // TODO Consider just reading in MAX _ REVERSE _ SCAN bytes - - increased peak memory cost but less complex
ByteBuffer bb = getByteBuffer ( CHUNK_SIZE ) ; long start = channel . size ( ) ; long end = Math . max ( 0 , start - MAX_REVERSE_SCAN ) ; long channelPos = Math . max ( 0 , start - CHUNK_SIZE ) ; long lastChannelPos = channelPos ; boolean firstRead = true ; while ( lastChannelPos >= end ) { read ( bb , channel , channelPos ) ; int actualRead = bb . limit ( ) ; if ( firstRead ) { long expectedRead = Math . min ( CHUNK_SIZE , start ) ; if ( actualRead > expectedRead ) { // File is still growing
return false ; } firstRead = false ; } int bufferPos = actualRead - 1 ; while ( bufferPos >= SIG_PATTERN_LENGTH ) { // Following is based on the Boyer Moore algorithm but simplified to reflect
// a ) the pattern is static
// b ) the pattern has no repeating bytes
int patternPos ; for ( patternPos = SIG_PATTERN_LENGTH - 1 ; patternPos >= 0 && ENDSIG_PATTERN [ patternPos ] == bb . get ( bufferPos - patternPos ) ; -- patternPos ) { // empty loop while bytes match
} // Switch gives same results as checking the " good suffix array " in the Boyer Moore algorithm
switch ( patternPos ) { case - 1 : { // Pattern matched . Confirm is this is the start of a valid end of central dir record
long startEndRecord = channelPos + bufferPos - SIG_PATTERN_LENGTH + 1 ; if ( validateEndRecord ( file , channel , startEndRecord ) ) { return true ; } // wasn ' t a valid end record ; continue scan
bufferPos -= 4 ; break ; } case 3 : { // No bytes matched ; the common case .
// With our pattern , this is the only case where the Boyer Moore algorithm ' s " bad char array " may
// produce a shift greater than the " good suffix array " ( which would shift 1 byte )
int idx = bb . get ( bufferPos - patternPos ) - Byte . MIN_VALUE ; bufferPos -= END_BAD_BYTE_SKIP [ idx ] ; break ; } default : // 1 or more bytes matched
bufferPos -= 4 ; } } // Move back a full chunk . If we didn ' t read a full chunk , that ' s ok ,
// it means we read all data and the outer while loop will terminate
if ( channelPos <= bufferPos ) { break ; } lastChannelPos = channelPos ; channelPos -= Math . min ( channelPos - bufferPos , CHUNK_SIZE - bufferPos ) ; } return false ; |
public class InterconnectClient { /** * Returns the specified interconnect . Get a list of available interconnects by making a list ( )
* request .
* < p > Sample code :
* < pre > < code >
* try ( InterconnectClient interconnectClient = InterconnectClient . create ( ) ) {
* ProjectGlobalInterconnectName interconnect = ProjectGlobalInterconnectName . of ( " [ PROJECT ] " , " [ INTERCONNECT ] " ) ;
* Interconnect response = interconnectClient . getInterconnect ( interconnect . toString ( ) ) ;
* < / code > < / pre >
* @ param interconnect Name of the interconnect to return .
* @ throws com . google . api . gax . rpc . ApiException if the remote call fails */
@ BetaApi public final Interconnect getInterconnect ( String interconnect ) { } } | GetInterconnectHttpRequest request = GetInterconnectHttpRequest . newBuilder ( ) . setInterconnect ( interconnect ) . build ( ) ; return getInterconnect ( request ) ; |
public class CurrentGpsInfo { /** * Method to add a new { @ link RMCSentence } .
* @ param rmc the sentence to add . */
public void addRMC ( RMCSentence rmc ) { } } | try { if ( rmc . isValid ( ) ) { date = rmc . getDate ( ) ; time = rmc . getTime ( ) ; // correctedCourse = rmc . getCorrectedCourse ( ) ;
faaMode = rmc . getMode ( ) ; position = rmc . getPosition ( ) ; dataStatus = rmc . getStatus ( ) ; kmHSpeed = rmc . getSpeed ( ) ; fieldCount = rmc . getFieldCount ( ) ; } } catch ( Exception e ) { // ignore it , this should be handled in the isValid ,
// if an exception is thrown , we can ' t deal with it here .
} |
public class LogOutputStream { /** * Write a block of characters to the output stream
* @ param b the array containing the data
* @ param off the offset into the array where data starts
* @ param len the length of block
* @ throws java . io . IOException if the data cannot be written into the stream .
* @ see java . io . OutputStream # write ( byte [ ] , int , int ) */
public void write ( final byte [ ] b , final int off , final int len ) throws IOException { } } | // find the line breaks and pass other chars through in blocks
int offset = off ; int blockStartOffset = offset ; int remaining = len ; while ( remaining > 0 ) { while ( remaining > 0 && b [ offset ] != LF && b [ offset ] != CR ) { offset ++ ; remaining -- ; } // either end of buffer or a line separator char
int blockLength = offset - blockStartOffset ; if ( blockLength > 0 ) { buffer . write ( b , blockStartOffset , blockLength ) ; lastReceivedByte = 0 ; } while ( remaining > 0 && ( b [ offset ] == LF || b [ offset ] == CR ) ) { write ( b [ offset ] ) ; offset ++ ; remaining -- ; } blockStartOffset = offset ; } |
public class ManagedBuffer { /** * Convenience method for creating a { @ link ManagedBuffer } with
* a { @ link BufferCollector # NOOP _ COLLECTOR } from a NIO buffer .
* Effectively , this creates an * unmanaged * buffer that
* looks like a managed buffer from an existing NIO buffer that
* does not belong to any pool .
* @ param < B > the buffer type
* @ param buffer the buffer to wrap
* @ return the managed buffer */
public static < B extends Buffer > ManagedBuffer < B > wrap ( B buffer ) { } } | return new ManagedBuffer < B > ( buffer , BufferCollector . noopCollector ( ) ) ; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.