idx int64 0 165k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
7,500 | private static void updateParallel ( Object mojo ) throws Exception { try { String currentParallel = getStringField ( PARALLEL_FIELD , mojo ) ; if ( currentParallel != null ) { warn ( mojo , "Ekstazi does not support parallel parameter. This parameter will be set to null for this run." ) ; setField ( PARALLEL_FIELD , mojo , null ) ; } } catch ( NoSuchMethodException ex ) { } } | Sets parallel parameter to null if the parameter is different from null and prints a warning . |
7,501 | private static boolean isOneVMPerClass ( Object mojo ) throws Exception { try { return ! invokeAndGetBoolean ( IS_REUSE_FORKS , mojo ) ; } catch ( NoSuchMethodException ex ) { return false ; } } | Returns true if one test class is executed in one VM . |
7,502 | public static < Type > ArrayObjectProvider < Type > getProvider ( final Class < Type > arrayType ) { return new ArrayObjectProvider < Type > ( arrayType ) ; } | Produces typed arrays . |
7,503 | public FineUploader5Request addCustomHeaders ( final Map < String , String > aCustomHeaders ) { m_aRequestCustomHeaders . addAll ( aCustomHeaders ) ; return this ; } | Additional headers sent along with each upload request . |
7,504 | public FineUploader5Request setEndpoint ( final ISimpleURL aRequestEndpoint ) { ValueEnforcer . notNull ( aRequestEndpoint , "RequestEndpoint" ) ; m_aRequestEndpoint = aRequestEndpoint ; return this ; } | The endpoint to send upload requests to . |
7,505 | public FineUploader5Request setFilenameParam ( final String sFilenameParam ) { ValueEnforcer . notEmpty ( sFilenameParam , "FilenameParam" ) ; m_sRequestFilenameParam = sFilenameParam ; return this ; } | The name of the parameter passed if the original filename has been edited or a Blob is being sent . |
7,506 | public FineUploader5Request setUUIDName ( final String sUUIDName ) { ValueEnforcer . notEmpty ( sUUIDName , "UUIDName" ) ; m_sRequestUUIDName = sUUIDName ; return this ; } | The name of the parameter the uniquely identifies each associated item . The value is a Level 4 UUID . |
7,507 | public FineUploader5Request setTotalFileSizeName ( final String sTotalFileSizeName ) { ValueEnforcer . notEmpty ( sTotalFileSizeName , "TotalFileSizeName" ) ; m_sRequestTotalFileSizeName = sTotalFileSizeName ; return this ; } | The name of the parameter passed that specifies the total file size in bytes . |
7,508 | public boolean canBeBundledWith ( final WebSiteResourceWithCondition aOther ) { ValueEnforcer . notNull ( aOther , "Other" ) ; if ( ! m_bIsBundlable || ! aOther . isBundlable ( ) ) return false ; if ( ! m_aResource . getResourceType ( ) . equals ( aOther . m_aResource . getResourceType ( ) ) ) return false ; if ( ! EqualsHelper . equals ( m_sConditionalComment , aOther . m_sConditionalComment ) ) return false ; if ( ! EqualsHelper . equals ( m_aMediaList , aOther . m_aMediaList ) ) return false ; return true ; } | Check if this resource can be bundled with the passed resource . |
7,509 | public static WebSiteResourceWithCondition createForJS ( final IJSPathProvider aPP , final boolean bRegular ) { return createForJS ( aPP . getJSItemPath ( bRegular ) , aPP . getConditionalComment ( ) , aPP . isBundlable ( ) ) ; } | Factory method for JavaScript resources . |
7,510 | public static WebSiteResourceWithCondition createForCSS ( final ICSSPathProvider aPP , final boolean bRegular ) { return createForCSS ( aPP . getCSSItemPath ( bRegular ) , aPP . getConditionalComment ( ) , aPP . isBundlable ( ) , aPP . getMediaList ( ) ) ; } | Factory method for CSS resources . |
7,511 | public static boolean canBeDeleted ( final IUser aUser ) { return aUser != null && ! aUser . isDeleted ( ) && ! aUser . isAdministrator ( ) ; } | Check if a user can be deleted or not . Currently all not deleted users can be deleted except for the administrator special user . |
7,512 | public static IHCConversionSettings createConversionSettings ( ) { final HCConversionSettings aRealCS = HCSettings . getMutableConversionSettings ( ) . getClone ( ) ; aRealCS . getMutableXMLWriterSettings ( ) . setEmitNamespaces ( false ) ; final IHCCustomizer aCustomizer = aRealCS . getCustomizer ( ) ; if ( aCustomizer instanceof HCCustomizerAutoFocusFirstCtrl ) aRealCS . setCustomizer ( null ) ; else if ( aCustomizer instanceof HCCustomizerList ) ( ( HCCustomizerList ) aCustomizer ) . removeAllCustomizersOfClass ( HCCustomizerAutoFocusFirstCtrl . class ) ; return aRealCS ; } | Create the HC conversion settings to be used for HTML serialization . |
7,513 | public static void unregisterCSSIncludeFromThisRequest ( final ICSSPathProvider aCSSPathProvider ) { final CSSResourceSet aSet = _getPerRequestSet ( false ) ; if ( aSet != null ) aSet . removeItem ( aCSSPathProvider ) ; } | Unregister an existing CSS item only from this request |
7,514 | public final HCOutput setFor ( final IHCHasID < ? > aFor ) { if ( aFor == null ) m_sFor = null ; else m_sFor = aFor . ensureID ( ) . getID ( ) ; return this ; } | Specifies the relationship between the result of the calculation and the elements used in the calculation |
7,515 | public void visitLdcInsn ( Object cst ) { if ( cst instanceof Type ) { int sort = ( ( Type ) cst ) . getSort ( ) ; if ( sort == Type . OBJECT ) { String className = Types . descToInternalName ( ( ( Type ) cst ) . getDescriptor ( ) ) ; insertTInvocation0 ( className , mProbeCounter . incrementAndGet ( ) ) ; } } mv . visitLdcInsn ( cst ) ; } | METHOD VISITOR INTERFACE |
7,516 | private void insertTInvocation0 ( String className , int probeId ) { if ( ! mSeenClasses . add ( className ) ) return ; if ( Types . isIgnorableInternalName ( className ) ) return ; boolean isNonInnerClass = true ; if ( isNonInnerClass && mIsNewerThanJava4 ) { insertTInvocation ( className , probeId ) ; } else { mv . visitLdcInsn ( className . replaceAll ( "/" , "." ) ) ; mv . visitMethodInsn ( Opcodes . INVOKESTATIC , Names . COVERAGE_MONITOR_VM , Instr . COVERAGE_MONITOR_MNAME , Instr . STRING_V_DESC , false ) ; } } | Checks if the class name belongs to a set of classes that should be ignored ; if not an invocation to coverage monitor is inserted . |
7,517 | protected Plugin lookupPlugin ( String key ) { List < Plugin > plugins = project . getBuildPlugins ( ) ; for ( Iterator < Plugin > iterator = plugins . iterator ( ) ; iterator . hasNext ( ) ; ) { Plugin plugin = iterator . next ( ) ; if ( key . equalsIgnoreCase ( plugin . getKey ( ) ) ) { return plugin ; } } return null ; } | Find plugin based on the plugin key . Returns null if plugin cannot be located . |
7,518 | protected boolean isRestoreGoalPresent ( ) { Plugin ekstaziPlugin = lookupPlugin ( EKSTAZI_PLUGIN_KEY ) ; if ( ekstaziPlugin == null ) { return false ; } for ( Object execution : ekstaziPlugin . getExecutions ( ) ) { for ( Object goal : ( ( PluginExecution ) execution ) . getGoals ( ) ) { if ( ( ( String ) goal ) . equals ( "restore" ) ) { return true ; } } } return false ; } | Returns true if restore goal is present false otherwise . |
7,519 | private void restoreExcludesFile ( File excludesFileFile ) throws MojoExecutionException { if ( ! excludesFileFile . exists ( ) ) { return ; } try { String [ ] lines = FileUtil . readLines ( excludesFileFile ) ; List < String > newLines = new ArrayList < String > ( ) ; for ( String line : lines ) { if ( line . equals ( EKSTAZI_LINE_MARKER ) ) break ; newLines . add ( line ) ; } FileUtil . writeLines ( excludesFileFile , newLines ) ; } catch ( IOException ex ) { throw new MojoExecutionException ( "Could not restore 'excludesFile'" , ex ) ; } } | Removes lines from excludesFile that are added by Ekstazi . |
7,520 | private static List < byte [ ] > parsePrivateKeyASN1 ( ByteBuffer byteBuffer ) { final List < byte [ ] > collection = new ArrayList < byte [ ] > ( ) ; while ( byteBuffer . hasRemaining ( ) ) { byte type = byteBuffer . get ( ) ; int length = UnsignedBytes . toInt ( byteBuffer . get ( ) ) ; if ( ( length & 0x80 ) != 0 ) { int numberOfOctets = length ^ 0x80 ; length = 0 ; for ( int i = 0 ; i < numberOfOctets ; ++ i ) { int lengthChunk = UnsignedBytes . toInt ( byteBuffer . get ( ) ) ; length += lengthChunk << ( numberOfOctets - i - 1 ) * 8 ; } } if ( length < 0 ) { throw new IllegalArgumentException ( ) ; } if ( type == 0x30 ) { int position = byteBuffer . position ( ) ; byte [ ] data = Arrays . copyOfRange ( byteBuffer . array ( ) , position , position + length ) ; return parsePrivateKeyASN1 ( ByteBuffer . wrap ( data ) ) ; } if ( type == 0x02 ) { byte [ ] segment = new byte [ length ] ; byteBuffer . get ( segment ) ; collection . add ( segment ) ; } } return collection ; } | This is a simplistic ASN . 1 parser that can only parse a collection of primitive types . |
7,521 | public static ICommonsList < String > getCleanPathParts ( final String sPath ) { String sRealPath = StringHelper . trimStartAndEnd ( sPath . trim ( ) , "/" , "/" ) ; sRealPath = FilenameHelper . getCleanPath ( sRealPath ) ; final ICommonsList < String > aPathParts = StringHelper . getExploded ( '/' , sRealPath ) ; return aPathParts ; } | Clean the provided path and split it into parts separated by slashes . |
7,522 | public FineUploader5Paste setDefaultName ( final String sDefaultName ) { ValueEnforcer . notEmpty ( sDefaultName , "DefaultName" ) ; m_sPasteDefaultName = sDefaultName ; return this ; } | The default name given to pasted images . |
7,523 | public String ordinalize ( int number ) { String numberStr = Integer . toString ( number ) ; if ( 11 <= number && number <= 13 ) return numberStr + "th" ; int remainder = number % 10 ; if ( remainder == 1 ) return numberStr + "st" ; if ( remainder == 2 ) return numberStr + "nd" ; if ( remainder == 3 ) return numberStr + "rd" ; return numberStr + "th" ; } | Turns a non - negative number into an ordinal string used to denote the position in an ordered sequence such as 1st 2nd 3rd 4th . |
7,524 | protected boolean isLoginInProgress ( final IRequestWebScopeWithoutResponse aRequestScope ) { return CLogin . REQUEST_ACTION_VALIDATE_LOGIN_CREDENTIALS . equals ( aRequestScope . params ( ) . getAsString ( CLogin . REQUEST_PARAM_ACTION ) ) ; } | Check if the login process is in progress |
7,525 | protected String getLoginName ( final IRequestWebScopeWithoutResponse aRequestScope ) { return aRequestScope . params ( ) . getAsString ( CLogin . REQUEST_ATTR_USERID ) ; } | Get the current login name |
7,526 | protected String getPassword ( final IRequestWebScopeWithoutResponse aRequestScope ) { return aRequestScope . params ( ) . getAsString ( CLogin . REQUEST_ATTR_PASSWORD ) ; } | Get the current password |
7,527 | public final EContinue checkUserAndShowLogin ( final IRequestWebScopeWithoutResponse aRequestScope , final UnifiedResponse aUnifiedResponse ) { final LoggedInUserManager aLoggedInUserManager = LoggedInUserManager . getInstance ( ) ; String sSessionUserID = aLoggedInUserManager . getCurrentUserID ( ) ; boolean bLoggedInInThisRequest = false ; if ( sSessionUserID == null ) { boolean bLoginError = false ; ICredentialValidationResult aLoginResult = ELoginResult . SUCCESS ; if ( isLoginInProgress ( aRequestScope ) ) { final String sLoginName = getLoginName ( aRequestScope ) ; final String sPassword = getPassword ( aRequestScope ) ; final IUser aUser = getUserOfLoginName ( sLoginName ) ; aLoginResult = aLoggedInUserManager . loginUser ( aUser , sPassword , m_aRequiredRoleIDs ) ; if ( aLoginResult . isSuccess ( ) ) { sSessionUserID = aUser . getID ( ) ; bLoggedInInThisRequest = true ; } else { if ( GlobalDebug . isDebugMode ( ) ) LOGGER . warn ( "Login of '" + sLoginName + "' failed because " + aLoginResult ) ; bLoginError = StringHelper . hasText ( sLoginName ) || StringHelper . hasText ( sPassword ) ; } } if ( sSessionUserID == null ) { final IHTMLProvider aLoginScreenProvider = createLoginScreen ( bLoginError , aLoginResult ) ; PhotonHTMLHelper . createHTMLResponse ( aRequestScope , aUnifiedResponse , aLoginScreenProvider ) ; } } final LoginInfo aLoginInfo = aLoggedInUserManager . getLoginInfo ( sSessionUserID ) ; if ( aLoginInfo != null ) { aLoginInfo . setLastAccessDTNow ( ) ; modifyLoginInfo ( aLoginInfo , aRequestScope , bLoggedInInThisRequest ) ; } else { if ( sSessionUserID != null ) LOGGER . error ( "Failed to resolve LoginInfo of user ID '" + sSessionUserID + "'" ) ; } if ( bLoggedInInThisRequest ) { aUnifiedResponse . setRedirect ( aRequestScope . getURL ( ) ) ; return EContinue . BREAK ; } return EContinue . valueOf ( sSessionUserID != null ) ; } | Main login routine . |
7,528 | public static JSInvocation setSelectOptions ( final IJSExpression aSelector , final IJSExpression aValueList ) { return getFormHelper ( ) . invoke ( "setSelectOptions" ) . arg ( aSelector ) . arg ( aValueList ) ; } | Set all options of a < ; select> ; |
7,529 | protected boolean isMagicCorrect ( BufferedReader br ) throws IOException { if ( mCheckMagicSequence ) { String magicLine = br . readLine ( ) ; return ( magicLine != null && magicLine . equals ( mMode . getMagicSequence ( ) ) ) ; } else { return true ; } } | Check magic sequence . Note that subclasses are responsible to decide if something should be read from buffer . This approach was taken to support old format without magic sequence . |
7,530 | protected RegData parseLine ( State state , String line ) { int sepIndex = line . indexOf ( SEPARATOR ) ; String urlExternalForm = line . substring ( 0 , sepIndex ) ; String hash = line . substring ( sepIndex + SEPARATOR_LEN ) ; return new RegData ( urlExternalForm , hash ) ; } | Parses a single line from the file . This method is never invoked for magic sequence . The line includes path to file and hash . Subclasses may include more fields . |
7,531 | protected void printLine ( State state , Writer pw , String externalForm , String hash ) throws IOException { pw . write ( externalForm ) ; pw . write ( SEPARATOR ) ; pw . write ( hash ) ; pw . write ( '\n' ) ; } | Prints one line to the given writer ; the line includes path to file and hash . Subclasses may include more fields . |
7,532 | public void update ( final float delta ) { if ( transitionInProgress ) { currentValue += ( targetValue - initialValue ) * delta / transitionLength ; if ( isInitialGreater ) { if ( currentValue <= targetValue ) { finalizeTransition ( ) ; } } else { if ( currentValue >= targetValue ) { finalizeTransition ( ) ; } } } } | Updates current value as long as it doesn t match the target value . |
7,533 | public void setCurrentValue ( final float currentValue ) { this . currentValue = currentValue ; initialValue = currentValue ; targetValue = currentValue ; transitionInProgress = false ; } | Ends transition . Immediately changes managed current value . |
7,534 | public static IHCNode markdown ( final String sMD ) { try { final HCNodeList aNL = MARKDOWN_PROC . process ( sMD ) . getNodeList ( ) ; if ( aNL . getChildCount ( ) == 1 && aNL . getChildAtIndex ( 0 ) instanceof HCP ) return ( ( HCP ) aNL . getChildAtIndex ( 0 ) ) . getAllChildrenAsNodeList ( ) ; return aNL ; } catch ( final Exception ex ) { LOGGER . warn ( "Failed to markdown '" + sMD + "': " + ex . getMessage ( ) ) ; return new HCTextNode ( sMD ) ; } } | Process the provided String as Markdown and return the created IHCNode . |
7,535 | public final void getContent ( final WPECTYPE aWPEC ) { if ( isValidToDisplayPage ( aWPEC ) . isValid ( ) ) { beforeFillContent ( aWPEC ) ; fillContent ( aWPEC ) ; afterFillContent ( aWPEC ) ; } else { onInvalidToDisplayPage ( aWPEC ) ; } } | Default implementation calling the abstract fillContent method and creating the help node if desired . |
7,536 | public static final AjaxFunctionDeclaration addAjax ( final String sPrefix , final IAjaxExecutor aExecutor ) { final String sFuncName = StringHelper . hasText ( sPrefix ) ? sPrefix + AjaxFunctionDeclaration . getUniqueFunctionID ( ) : null ; final AjaxFunctionDeclaration aFunction = AjaxFunctionDeclaration . builder ( sFuncName ) . withExecutor ( aExecutor ) . build ( ) ; GlobalAjaxInvoker . getInstance ( ) . getRegistry ( ) . registerFunction ( aFunction ) ; return aFunction ; } | Add a per - page AJAX executor with an automatically generated name . It is automatically generated with the global AjaxInvoker . |
7,537 | public QRSCT reference ( String reference ) { if ( reference != null && reference . length ( ) <= 35 ) { this . text = "" ; this . reference = checkValidSigns ( reference ) ; return this ; } throw new IllegalArgumentException ( "supplied reference [" + reference + "] not valid: has to be not null and of max length 35" ) ; } | Sets the reference of this builder !!!If you set this attribute attribute text will be reset to an empty string!!! It s only possible to define one of these attributes |
7,538 | public QRSCT text ( String text ) { if ( text != null && text . length ( ) <= 140 ) { this . reference = "" ; this . text = checkValidSigns ( text ) ; return this ; } throw new IllegalArgumentException ( "supplied text [" + text + "] not valid: has to be not null and of max length 140" ) ; } | Sets the text of this builder !!!If you set this attribute attribute reference will be reset to an empty string!!! It s only possible to define one of these attributes |
7,539 | private void processClasspath ( String classpathElement ) throws ResourceNotFoundException , ParseErrorException , Exception { if ( classpathElement . endsWith ( ".jar" ) ) { } else { final File dir = new File ( classpathElement ) ; processPackage ( dir , dir ) ; } } | Process the classes for a specified package |
7,540 | private void processPackage ( File root , File dir ) { getLog ( ) . debug ( "- package: " + dir ) ; if ( null != dir && dir . isDirectory ( ) ) { for ( File f : dir . listFiles ( new FileFilter ( ) { public boolean accept ( File pathname ) { return pathname . isDirectory ( ) || pathname . getName ( ) . endsWith ( ".class" ) ; } } ) ) { if ( f . isDirectory ( ) ) { processPackage ( root , f ) ; } else if ( f . getParentFile ( ) . getAbsolutePath ( ) . replace ( File . separatorChar , '.' ) . endsWith ( basePackage + '.' + domainPackageName ) ) { final String simpleName = f . getName ( ) . substring ( 0 , f . getName ( ) . lastIndexOf ( ".class" ) ) ; final String className = String . format ( "%s.%s.%s" , basePackage , domainPackageName , simpleName ) ; getLog ( ) . debug ( String . format ( "--- class %s" , className ) ) ; try { Class clazz = loader . loadClass ( className ) ; if ( ! Modifier . isAbstract ( clazz . getModifiers ( ) ) && isEntity ( clazz ) ) { getLog ( ) . debug ( "@Entity " + clazz . getName ( ) ) ; final Entity entity = new Entity ( ) ; entity . setClazz ( clazz ) ; final String packageName = clazz . getPackage ( ) . getName ( ) ; Group group = packages . get ( packageName ) ; if ( null == group ) { group = new Group ( ) ; group . setName ( packageName ) ; packages . put ( packageName , group ) ; } group . getEntities ( ) . put ( simpleName , entity ) ; entities . put ( entity . getClassName ( ) , entity ) ; } } catch ( ClassNotFoundException ex ) { Logger . getLogger ( ProcessDomainMojo . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } } } } } | Recursive method to process a folder or file ; if a folder call recursively for each file . If for a file process the file using the classVisitor . |
7,541 | private HolidayMap _getHolidays ( final int nYear , final Configuration aConfig , final String ... aArgs ) { if ( LOGGER . isDebugEnabled ( ) ) LOGGER . debug ( "Adding holidays for " + aConfig . getDescription ( ) ) ; final HolidayMap aHolidayMap = new HolidayMap ( ) ; for ( final IHolidayParser aParser : _getParsers ( aConfig . getHolidays ( ) ) ) aParser . parse ( nYear , aHolidayMap , aConfig . getHolidays ( ) ) ; if ( ArrayHelper . isNotEmpty ( aArgs ) ) { final String sHierarchy = aArgs [ 0 ] ; for ( final Configuration aSubConfig : aConfig . getSubConfigurations ( ) ) { if ( sHierarchy . equalsIgnoreCase ( aSubConfig . getHierarchy ( ) ) ) { final HolidayMap aSubHolidays = _getHolidays ( nYear , aSubConfig , ArrayHelper . getCopy ( aArgs , 1 , aArgs . length - 1 ) ) ; aHolidayMap . addAll ( aSubHolidays ) ; break ; } } } return aHolidayMap ; } | Parses the provided configuration for the provided year and fills the list of holidays . |
7,542 | private static void _validateConfigurationHierarchy ( final Configuration aConfig ) { final ICommonsSet < String > aHierarchySet = new CommonsHashSet < > ( ) ; for ( final Configuration aSubConfig : aConfig . getSubConfigurations ( ) ) { final String sHierarchy = aSubConfig . getHierarchy ( ) ; if ( ! aHierarchySet . add ( sHierarchy ) ) throw new IllegalArgumentException ( "Configuration for " + aConfig . getHierarchy ( ) + " contains multiple SubConfigurations with the same hierarchy id '" + sHierarchy + "'. " ) ; } for ( final Configuration aSubConfig : aConfig . getSubConfigurations ( ) ) _validateConfigurationHierarchy ( aSubConfig ) ; } | Validates the content of the provided configuration by checking for multiple hierarchy entries within one configuration . It traverses down the configuration tree . |
7,543 | private static CalendarHierarchy _createConfigurationHierarchy ( final Configuration aConfig , final CalendarHierarchy aParent ) { final ECountry eCountry = ECountry . getFromIDOrNull ( aConfig . getHierarchy ( ) ) ; final CalendarHierarchy aHierarchy = new CalendarHierarchy ( aParent , aConfig . getHierarchy ( ) , eCountry ) ; for ( final Configuration aSubConfig : aConfig . getSubConfigurations ( ) ) { final CalendarHierarchy aSubHierarchy = _createConfigurationHierarchy ( aSubConfig , aHierarchy ) ; aHierarchy . addChild ( aSubHierarchy ) ; } return aHierarchy ; } | Creates the configuration hierarchy for the provided configuration . |
7,544 | public static void setDbType ( JdbcDialect dialect , String key , String type ) { Properties props = getTypesProps ( dialect ) ; props . setProperty ( key , type ) ; } | Add a type for your DB s dialect |
7,545 | private static ICommonsSet < LocalDate > _getEthiopianOrthodoxHolidaysInGregorianYear ( final int nGregorianYear , final int nEOMonth , final int nEODay ) { return CalendarHelper . getDatesFromChronologyWithinGregorianYear ( nEOMonth , nEODay , nGregorianYear , CopticChronology . INSTANCE ) ; } | Returns a set of gregorian dates within a gregorian year which equal the Ethiopian orthodox month and day . Because the Ethiopian orthodox year different from the gregorian there may be more than one occurrence of an Ethiopian orthodox date in an gregorian year . |
7,546 | public Result parse ( Command cmd , InputStream input , ResultType type ) { return parseResults ( cmd , input , type ) ; } | Parses the input stream as either XML select or ask results . |
7,547 | public static Result parseResults ( Command cmd , InputStream input , ResultType type ) throws SparqlException { try { return createResults ( cmd , input , type ) ; } catch ( Throwable t ) { logger . debug ( "Error parsing results from stream, cleaning up." ) ; try { input . close ( ) ; } catch ( IOException e ) { logger . warn ( "Error closing input stream from failed protocol response" , e ) ; } throw SparqlException . convert ( "Error parsing SPARQL protocol results from stream" , t ) ; } } | Parses an XMLResults object based on the contents of the given stream . |
7,548 | private static Result createResults ( Command cmd , InputStream stream , ResultType type ) throws SparqlException { XMLInputFactory xmlStreamFactory = XMLInputFactory . newInstance ( ) ; xmlStreamFactory . setProperty ( XMLInputFactory . IS_COALESCING , true ) ; xmlStreamFactory . setProperty ( XMLInputFactory2 . P_AUTO_CLOSE_INPUT , true ) ; XMLStreamReader rdr ; try { rdr = xmlStreamFactory . createXMLStreamReader ( stream , "UTF-8" ) ; } catch ( XMLStreamException e ) { throw new SparqlException ( "Unable to open XML data" , e ) ; } List < String > cols = new ArrayList < String > ( ) ; List < String > md = new ArrayList < String > ( ) ; try { if ( rdr . nextTag ( ) != START_ELEMENT || ! nameIs ( rdr , SPARQL ) ) { throw new SparqlException ( "Result is not a SPARQL XML result document" ) ; } String base = null ; if ( cmd != null ) { base = ( ( ProtocolDataSource ) cmd . getConnection ( ) . getDataSource ( ) ) . getUrl ( ) . toString ( ) ; } parseHeader ( base , rdr , cols , md ) ; if ( rdr . nextTag ( ) != START_ELEMENT ) throw new SparqlException ( "No body to result document" ) ; String typeName = rdr . getLocalName ( ) ; if ( typeName . equalsIgnoreCase ( RESULTS . toString ( ) ) ) { if ( type != null && type != ResultType . SELECT ) { throw new SparqlException ( "Unexpected result type; expected " + type + " but found SELECT." ) ; } return new XMLSelectResults ( cmd , rdr , cols , md ) ; } if ( typeName . equalsIgnoreCase ( BOOLEAN . toString ( ) ) ) { if ( type != null && type != ResultType . ASK ) { throw new SparqlException ( "Unexpected result type; expected " + type + " but found ASK." ) ; } if ( ! cols . isEmpty ( ) ) { logger . warn ( "Boolean result contained column definitions in head: {}" , cols ) ; } return parseBooleanResult ( cmd , rdr , md ) ; } throw new SparqlException ( "Unknown element type in result document. Expected <results> or <boolean> but got <" + typeName + ">" ) ; } catch ( XMLStreamException e ) { throw new SparqlException ( "Error reading the XML stream" , e ) ; } } | Sets up an XML parser for the input and creates the appropriate result type based on the parsed XML . |
7,549 | static private void parseHeader ( String base , XMLStreamReader rdr , List < String > cols , List < String > md ) throws XMLStreamException , SparqlException { logger . debug ( "xml:base is initially {}" , base ) ; base = getBase ( base , rdr ) ; testOpen ( rdr , rdr . nextTag ( ) , HEAD , "Missing header from XML results" ) ; base = getBase ( base , rdr ) ; boolean endedVars = false ; int eventType ; while ( ( eventType = rdr . nextTag ( ) ) != END_ELEMENT || ! nameIs ( rdr , HEAD ) ) { if ( eventType == START_ELEMENT ) { if ( nameIs ( rdr , VARIABLE ) ) { if ( endedVars ) throw new SparqlException ( "Encountered a variable after header metadata" ) ; String var = rdr . getAttributeValue ( null , "name" ) ; if ( var != null ) cols . add ( var ) ; else logger . warn ( "<variable> element without 'name' attribute" ) ; } else if ( nameIs ( rdr , LINK ) ) { String b = getBase ( base , rdr ) ; String href = rdr . getAttributeValue ( null , HREF ) ; if ( href != null ) md . add ( resolve ( b , href ) ) ; else logger . warn ( "<link> element without 'href' attribute" ) ; endedVars = true ; } } } testClose ( rdr , eventType , HEAD , "Unexpected element in header: " + rdr . getLocalName ( ) ) ; } | Parse the < ; head> ; element with the variables and metadata . |
7,550 | static final boolean nameIs ( XMLStreamReader rdr , Element elt ) { return rdr . getLocalName ( ) . equalsIgnoreCase ( elt . name ( ) ) ; } | Convenience method to test if the current local name is the same as an expected element . |
7,551 | public static void runOnUiThread ( final Runnable runnable ) { Condition . INSTANCE . ensureNotNull ( runnable , "The runnable may not be null" ) ; new Handler ( Looper . getMainLooper ( ) ) . post ( runnable ) ; } | Executes a specific runnable on the UI thread . |
7,552 | private final boolean notifyOnLoad ( final KeyType key , final ParamType ... params ) { boolean result = true ; for ( Listener < DataType , KeyType , ViewType , ParamType > listener : listeners ) { result &= listener . onLoadData ( this , key , params ) ; } return result ; } | Notifies all listeners that the data binder starts to load data asynchronously . |
7,553 | private final void notifyOnFinished ( final KeyType key , final DataType data , final ViewType view , final ParamType ... params ) { for ( Listener < DataType , KeyType , ViewType , ParamType > listener : listeners ) { listener . onFinished ( this , key , data , view , params ) ; } } | Notifies all listeners that the data binder is showing data which has been loaded either asynchronously or from cache . |
7,554 | private void notifyOnCanceled ( ) { for ( Listener < DataType , KeyType , ViewType , ParamType > listener : listeners ) { listener . onCanceled ( this ) ; } } | Notifies all listeners that the data binder has been canceled . |
7,555 | private DataType getCachedData ( final KeyType key ) { synchronized ( cache ) { return cache . get ( key ) ; } } | Returns the data which corresponds to a specific key from the cache . |
7,556 | private void cacheData ( final KeyType key , final DataType data ) { synchronized ( cache ) { if ( useCache ) { cache . put ( key , data ) ; } } } | Adds the data which corresponds to a specific key to the cache if caching is enabled . |
7,557 | private void loadDataAsynchronously ( final Task < DataType , KeyType , ViewType , ParamType > task ) { threadPool . submit ( new Runnable ( ) { public void run ( ) { if ( ! isCanceled ( ) ) { while ( ! notifyOnLoad ( task . key , task . params ) ) { try { Thread . sleep ( 100 ) ; } catch ( InterruptedException e ) { break ; } } task . result = loadData ( task ) ; Message message = Message . obtain ( ) ; message . obj = task ; sendMessage ( message ) ; } } } ) ; } | Asynchronously executes a specific task in order to load data and to display it afterwards . |
7,558 | private DataType loadData ( final Task < DataType , KeyType , ViewType , ParamType > task ) { try { DataType data = doInBackground ( task . key , task . params ) ; if ( data != null ) { cacheData ( task . key , data ) ; } logger . logInfo ( getClass ( ) , "Loaded data with key " + task . key ) ; return data ; } catch ( Exception e ) { logger . logError ( getClass ( ) , "An error occurred while loading data with key " + task . key , e ) ; return null ; } } | Executes a specific task in order to load data . |
7,559 | public final void addListener ( final Listener < DataType , KeyType , ViewType , ParamType > listener ) { listeners . add ( listener ) ; } | Adds a new listener which should be notified about the events of the data binder . |
7,560 | public final void removeListener ( final Listener < DataType , KeyType , ViewType , ParamType > listener ) { listeners . remove ( listener ) ; } | Removes a specific listener which should not be notified about the events of the data binder anymore . |
7,561 | public final void load ( final KeyType key , final ViewType view , final ParamType ... params ) { load ( key , view , true , params ) ; } | Loads the the data which corresponds to a specific key and displays it in a specific view . If the data has already been loaded it will be retrieved from the cache . By default the data is loaded in a background thread . |
7,562 | public final void load ( final KeyType key , final ViewType view , final boolean async , final ParamType ... params ) { Condition . INSTANCE . ensureNotNull ( key , "The key may not be null" ) ; Condition . INSTANCE . ensureNotNull ( view , "The view may not be null" ) ; Condition . INSTANCE . ensureNotNull ( params , "The array may not be null" ) ; setCanceled ( false ) ; views . put ( view , key ) ; DataType data = getCachedData ( key ) ; if ( ! isCanceled ( ) ) { if ( data != null ) { onPostExecute ( view , data , 0 , params ) ; notifyOnFinished ( key , data , view , params ) ; logger . logInfo ( getClass ( ) , "Loaded data with key " + key + " from cache" ) ; } else { onPreExecute ( view , params ) ; Task < DataType , KeyType , ViewType , ParamType > task = new Task < > ( view , key , params ) ; if ( async ) { loadDataAsynchronously ( task ) ; } else { data = loadData ( task ) ; onPostExecute ( view , data , 0 , params ) ; notifyOnFinished ( key , data , view , params ) ; } } } } | Loads the the data which corresponds to a specific key and displays it in a specific view . If the data has already been loaded it will be retrieved from the cache . |
7,563 | public final boolean isCached ( final KeyType key ) { Condition . INSTANCE . ensureNotNull ( key , "The key may not be null" ) ; synchronized ( cache ) { return cache . get ( key ) != null ; } } | Returns whether the data which corresponds to a specific key is currently cached or not . |
7,564 | public final void useCache ( final boolean useCache ) { synchronized ( cache ) { this . useCache = useCache ; logger . logDebug ( getClass ( ) , useCache ? "Enabled" : "Disabled" + " caching" ) ; if ( ! useCache ) { clearCache ( ) ; } } } | Sets whether data should be cached or not . |
7,565 | private static void profile ( Task task , String message , int tries ) { for ( int i = 0 ; i < tries ; i ++ ) { long start = System . nanoTime ( ) ; task . run ( ) ; long finish = System . nanoTime ( ) ; System . out . println ( String . format ( "[Try %d] %-30s: %-5.2fms" , i + 1 , message , ( finish - start ) / 1000000.0 ) ) ; } } | Poor mans profiler |
7,566 | private void obtainShadowElevation ( final TypedArray typedArray ) { int defaultValue = getResources ( ) . getDimensionPixelSize ( R . dimen . elevation_shadow_view_shadow_elevation_default_value ) ; elevation = pixelsToDp ( getContext ( ) , typedArray . getDimensionPixelSize ( R . styleable . ElevationShadowView_shadowElevation , defaultValue ) ) ; } | Obtains the elevation of the shadow which is visualized by the view from a specific typed array . |
7,567 | private void obtainShadowOrientation ( final TypedArray typedArray ) { int defaultValue = getResources ( ) . getInteger ( R . integer . elevation_shadow_view_shadow_orientation_default_value ) ; orientation = Orientation . fromValue ( typedArray . getInteger ( R . styleable . ElevationShadowView_shadowOrientation , defaultValue ) ) ; } | Obtains the orientation of the shadow which is visualized by the view from a specific typed array . |
7,568 | private void obtainEmulateParallelLight ( final TypedArray typedArray ) { boolean defaultValue = getResources ( ) . getBoolean ( R . bool . elevation_shadow_view_emulate_parallel_light_default_value ) ; emulateParallelLight = typedArray . getBoolean ( R . styleable . ElevationShadowView_emulateParallelLight , defaultValue ) ; } | Obtains the boolean value which specifies whether parallel light should be emulated from a specific typed array . |
7,569 | private void adaptElevationShadow ( ) { setImageBitmap ( createElevationShadow ( getContext ( ) , elevation , orientation , emulateParallelLight ) ) ; setScaleType ( orientation == Orientation . LEFT || orientation == Orientation . TOP || orientation == Orientation . RIGHT || orientation == Orientation . BOTTOM ? ScaleType . FIT_XY : ScaleType . FIT_CENTER ) ; } | Adapts the shadow which is visualized by the view depending on its current attributes . |
7,570 | public final void setShadowElevation ( final int elevation ) { Condition . INSTANCE . ensureAtLeast ( elevation , 0 , "The elevation must be at least 0" ) ; Condition . INSTANCE . ensureAtMaximum ( elevation , ElevationUtil . MAX_ELEVATION , "The elevation must be at maximum " + ElevationUtil . MAX_ELEVATION ) ; this . elevation = elevation ; adaptElevationShadow ( ) ; } | Sets the elevation of the shadow which should be visualized by the view . |
7,571 | public final void setShadowOrientation ( final Orientation orientation ) { Condition . INSTANCE . ensureNotNull ( orientation , "The orientation may not be null" ) ; this . orientation = orientation ; adaptElevationShadow ( ) ; } | Sets the orientation of the shadow which should be visualized by the view . |
7,572 | public boolean hasError ( Response < ByteSource > rs ) { StatusType statusType = StatusType . valueOf ( rs . getStatus ( ) ) ; return ( statusType == StatusType . CLIENT_ERROR || statusType == StatusType . SERVER_ERROR ) ; } | Returns TRUE in case status code of response starts with 4 or 5 |
7,573 | protected void handleError ( URI requestUri , HttpMethod requestMethod , int statusCode , String statusMessage , ByteSource errorBody ) throws RestEndpointIOException { throw new RestEndpointException ( requestUri , requestMethod , statusCode , statusMessage , errorBody ) ; } | Handler methods for HTTP client errors |
7,574 | public void init ( APUtils utils ) throws DuzztInitializationException { URL url = GenerateEDSLProcessor . class . getResource ( ST_RESOURCE_NAME ) ; this . sourceGenGroup = new STGroupFile ( url , ST_ENCODING , ST_DELIM_START_CHAR , ST_DELIM_STOP_CHAR ) ; sourceGenGroup . setListener ( new ReporterDiagnosticListener ( utils . getReporter ( ) ) ) ; sourceGenGroup . load ( ) ; if ( ! sourceGenGroup . isDefined ( ST_MAIN_TEMPLATE_NAME ) ) { sourceGenGroup = null ; throw new DuzztInitializationException ( "Could not find main template '" + ST_MAIN_TEMPLATE_NAME + "' in template group file " + url . toString ( ) ) ; } this . isJava9OrNewer = isJava9OrNewer ( utils . getProcessingEnv ( ) . getSourceVersion ( ) ) ; } | Initialize the Duzzt embedded DSL generator . |
7,575 | public void process ( Element elem , GenerateEmbeddedDSL annotation , Elements elementUtils , Types typeUtils , Filer filer , Reporter reporter ) throws IOException { if ( ! ElementUtils . checkElementKind ( elem , ElementKind . CLASS , ElementKind . INTERFACE ) ) { throw new IllegalArgumentException ( "Annotation " + GenerateEmbeddedDSL . class . getSimpleName ( ) + " can only be used on class or interface declarations!" ) ; } TypeElement te = ( TypeElement ) elem ; ReporterDiagnosticListener dl = new ReporterDiagnosticListener ( reporter ) ; DSLSettings settings = new DSLSettings ( annotation ) ; DSLSpecification spec = DSLSpecification . create ( te , settings , elementUtils , typeUtils ) ; BricsCompiler compiler = new BricsCompiler ( spec . getImplementation ( ) ) ; DuzztAutomaton automaton = compiler . compile ( spec . getDSLSyntax ( ) , spec . getSubExpressions ( ) ) ; automaton . reassignStateIds ( typeUtils ) ; render ( spec , automaton , filer , dl ) ; } | Process an annotated element . |
7,576 | public static boolean isPermissionGranted ( final Context context , final String permission ) { Condition . INSTANCE . ensureNotNull ( context , "The context may not be null" ) ; Condition . INSTANCE . ensureNotNull ( permission , "The permission may not be null" ) ; Condition . INSTANCE . ensureNotEmpty ( permission , "The permission may not be empty" ) ; return Build . VERSION . SDK_INT < Build . VERSION_CODES . M || ContextCompat . checkSelfPermission ( context , permission ) == PackageManager . PERMISSION_GRANTED ; } | Returns whether a specific permission is granted or not . |
7,577 | public static boolean areAllPermissionsGranted ( final Context context , final String ... permissions ) { Condition . INSTANCE . ensureNotNull ( context , "The context may not be null" ) ; Condition . INSTANCE . ensureNotNull ( permissions , "The array may not be null" ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . M ) { for ( String permission : permissions ) { if ( ! isPermissionGranted ( context , permission ) ) { return false ; } } } return true ; } | Returns whether all permissions which are contained by a specific array are granted or not . |
7,578 | public static String [ ] getNotGrantedPermissions ( final Context context , final String ... permissions ) { Condition . INSTANCE . ensureNotNull ( permissions , "The array may not be null" ) ; Collection < String > notGrantedPermissions = new LinkedList < > ( ) ; for ( String permission : permissions ) { if ( ! isPermissionGranted ( context , permission ) ) { notGrantedPermissions . add ( permission ) ; } } String [ ] result = new String [ notGrantedPermissions . size ( ) ] ; notGrantedPermissions . toArray ( result ) ; return result ; } | Returns the subset of specific permissions which are not granted . |
7,579 | private List < O > findByDate ( String dateField , Date start , Date end , int numObjects , boolean asc ) { if ( start == null ) start = new Date ( 0 ) ; if ( end == null ) end = new Date ( ) ; return getDatastore ( ) . find ( clazz ) . filter ( dateField + " >" , start ) . filter ( dateField + " <" , end ) . order ( asc ? dateField : '-' + dateField ) . limit ( numObjects ) . asList ( ) ; } | A private helper method that can be applied to creationDate crawledDate lastModifiedDate . For usage sample see the methods below |
7,580 | public List < O > createdInPeriod ( Date start , Date end , int numObjects ) { return findByDate ( "creationDate" , start , end , numObjects , true ) ; } | Returns a list of images created in the time period specified by start and end |
7,581 | public List < Similarity > similar ( Image object , double threshold ) { Query < Similarity > q = getDatastore ( ) . createQuery ( Similarity . class ) ; q . or ( q . criteria ( "firstObject" ) . equal ( object ) , q . criteria ( "secondObject" ) . equal ( object ) ) ; return q . order ( "-similarityScore" ) . filter ( "similarityScore >" , threshold ) . asList ( ) ; } | Returns a list of objects that are similar to the specified object |
7,582 | public void createZookeeperBase ( ) throws WorkerDaoException { createPersistentEmptyNodeIfNotExist ( BASE_ZK ) ; createPersistentEmptyNodeIfNotExist ( WORKERS_ZK ) ; createPersistentEmptyNodeIfNotExist ( PLANS_ZK ) ; createPersistentEmptyNodeIfNotExist ( SAVED_ZK ) ; createPersistentEmptyNodeIfNotExist ( LOCKS_ZK ) ; createPersistentEmptyNodeIfNotExist ( PLAN_WORKERS_ZK ) ; } | Creates all the required base directories in ZK for the application to run |
7,583 | public List < String > findWorkersWorkingOnPlan ( Plan plan ) throws WorkerDaoException { try { Stat exists = framework . getCuratorFramework ( ) . checkExists ( ) . forPath ( PLAN_WORKERS_ZK + "/" + plan . getName ( ) ) ; if ( exists == null ) { return new ArrayList < String > ( ) ; } return framework . getCuratorFramework ( ) . getChildren ( ) . forPath ( PLAN_WORKERS_ZK + "/" + plan . getName ( ) ) ; } catch ( Exception e ) { throw new WorkerDaoException ( e ) ; } } | Returns the node name of all the ephemeral nodes under a plan . This is effectively who is working on the plan . |
7,584 | public Plan findPlanByName ( String name ) throws WorkerDaoException { Stat planStat ; byte [ ] planBytes ; try { planStat = framework . getCuratorFramework ( ) . checkExists ( ) . forPath ( PLANS_ZK + "/" + name ) ; if ( planStat == null ) { return null ; } planBytes = framework . getCuratorFramework ( ) . getData ( ) . forPath ( PLANS_ZK + "/" + name ) ; } catch ( Exception e ) { LOGGER . warn ( e ) ; throw new WorkerDaoException ( e ) ; } Plan p = null ; try { p = deserializePlan ( planBytes ) ; } catch ( JsonParseException | JsonMappingException e ) { LOGGER . warn ( "while parsing plan " + name , e ) ; } catch ( IOException e ) { LOGGER . warn ( "while parsing plan " + name , e ) ; } return p ; } | Search zookeeper for a plan with given name . |
7,585 | public void createOrUpdatePlan ( Plan plan ) throws WorkerDaoException { try { createZookeeperBase ( ) ; Stat s = this . framework . getCuratorFramework ( ) . checkExists ( ) . forPath ( PLANS_ZK + "/" + plan . getName ( ) ) ; if ( s != null ) { framework . getCuratorFramework ( ) . setData ( ) . withVersion ( s . getVersion ( ) ) . forPath ( PLANS_ZK + "/" + plan . getName ( ) , serializePlan ( plan ) ) ; } else { framework . getCuratorFramework ( ) . create ( ) . withMode ( CreateMode . PERSISTENT ) . withACL ( Ids . OPEN_ACL_UNSAFE ) . forPath ( PLANS_ZK + "/" + plan . getName ( ) , serializePlan ( plan ) ) ; } } catch ( Exception e ) { LOGGER . warn ( e ) ; throw new WorkerDaoException ( e ) ; } } | Creates or updates a plan in zookeeper . |
7,586 | public void createEphemeralNodeForDaemon ( TeknekDaemon d ) throws WorkerDaoException { try { byte [ ] hostbytes = d . getHostname ( ) . getBytes ( ENCODING ) ; framework . getCuratorFramework ( ) . create ( ) . withMode ( CreateMode . EPHEMERAL ) . withACL ( Ids . OPEN_ACL_UNSAFE ) . forPath ( WORKERS_ZK + "/" + d . getMyId ( ) , hostbytes ) ; } catch ( Exception e ) { LOGGER . warn ( e ) ; throw new WorkerDaoException ( e ) ; } } | Creates an ephemeral node so that we can determine how many current live nodes there are |
7,587 | public List < WorkerStatus > findAllWorkerStatusForPlan ( Plan plan , List < String > otherWorkers ) throws WorkerDaoException { List < WorkerStatus > results = new ArrayList < WorkerStatus > ( ) ; try { Stat preCheck = framework . getCuratorFramework ( ) . checkExists ( ) . forPath ( PLAN_WORKERS_ZK + "/" + plan . getName ( ) ) ; if ( preCheck == null ) { return results ; } } catch ( Exception e1 ) { LOGGER . warn ( e1 ) ; throw new WorkerDaoException ( e1 ) ; } for ( String worker : otherWorkers ) { String lookAtPath = PLAN_WORKERS_ZK + "/" + plan . getName ( ) + "/" + worker ; try { Stat stat = framework . getCuratorFramework ( ) . checkExists ( ) . forPath ( lookAtPath ) ; byte [ ] data = framework . getCuratorFramework ( ) . getData ( ) . storingStatIn ( stat ) . forPath ( lookAtPath ) ; results . add ( MAPPER . readValue ( data , WorkerStatus . class ) ) ; } catch ( Exception e ) { LOGGER . warn ( e ) ; throw new WorkerDaoException ( e ) ; } } return results ; } | Gets the status of each worker . The status contains the partitionId being consumed . This information helps the next worker bind to an unconsumed partition |
7,588 | public void registerWorkerStatus ( ZooKeeper zk , Plan plan , WorkerStatus s ) throws WorkerDaoException { String writeToPath = PLAN_WORKERS_ZK + "/" + plan . getName ( ) + "/" + s . getWorkerUuid ( ) ; try { Stat planBase = zk . exists ( PLAN_WORKERS_ZK + "/" + plan . getName ( ) , false ) ; if ( planBase == null ) { try { zk . create ( PLAN_WORKERS_ZK + "/" + plan . getName ( ) , new byte [ 0 ] , Ids . OPEN_ACL_UNSAFE , CreateMode . PERSISTENT ) ; } catch ( Exception ignore ) { } } zk . create ( writeToPath , MAPPER . writeValueAsBytes ( s ) , Ids . OPEN_ACL_UNSAFE , CreateMode . EPHEMERAL ) ; LOGGER . debug ( "Registered as ephemeral " + writeToPath ) ; zk . exists ( PLANS_ZK + "/" + plan . getName ( ) , true ) ; } catch ( KeeperException | InterruptedException | IOException e ) { LOGGER . warn ( e ) ; throw new WorkerDaoException ( e ) ; } } | Registers an ephemeral node representing ownership of a feed partition . Note we do not use curator here because we want a standard watch not from the main thread! |
7,589 | public void deletePlan ( Plan p ) throws WorkerDaoException { String planNode = PLANS_ZK + "/" + p . getName ( ) ; try { Stat s = framework . getCuratorFramework ( ) . checkExists ( ) . forPath ( planNode ) ; framework . getCuratorFramework ( ) . delete ( ) . withVersion ( s . getVersion ( ) ) . forPath ( planNode ) ; } catch ( Exception e ) { throw new WorkerDaoException ( e ) ; } } | Note you should call stop the plan if it is running before deleting |
7,590 | public static int indexOf ( final boolean [ ] array , final boolean value ) { Condition . INSTANCE . ensureNotNull ( array , "The array may not be null" ) ; for ( int i = 0 ; i < array . length ; i ++ ) { if ( array [ i ] == value ) { return i ; } } return - 1 ; } | Returns the index of the first item of an array which equals a specific boolean value . |
7,591 | protected final void addUnusedView ( final View view , final int viewType ) { if ( useCache ) { if ( unusedViews == null ) { unusedViews = new SparseArray < > ( adapter . getViewTypeCount ( ) ) ; } Queue < View > queue = unusedViews . get ( viewType ) ; if ( queue == null ) { queue = new LinkedList < > ( ) ; unusedViews . put ( viewType , queue ) ; } queue . add ( view ) ; } } | Adds an unused view to the cache . |
7,592 | protected final View pollUnusedView ( final int viewType ) { if ( useCache && unusedViews != null ) { Queue < View > queue = unusedViews . get ( viewType ) ; if ( queue != null ) { return queue . poll ( ) ; } } return null ; } | Retrieves an unused view which corresponds to a specific view type from the cache if any is available . |
7,593 | public final View getView ( final ItemType item ) { Condition . INSTANCE . ensureNotNull ( item , "The item may not be null" ) ; return activeViews . get ( item ) ; } | Returns the view which is currently used to visualize a specific item . |
7,594 | public final void clearCache ( ) { if ( unusedViews != null ) { unusedViews . clear ( ) ; unusedViews = null ; } logger . logDebug ( getClass ( ) , "Removed all unused views from cache" ) ; } | Removes all unused views from the cache . |
7,595 | public final void clearCache ( final int viewType ) { if ( unusedViews != null ) { unusedViews . remove ( viewType ) ; } logger . logDebug ( getClass ( ) , "Removed all unused views of view type " + viewType + " from cache" ) ; } | Removes all unused views which correspond to a specific view type from the cache . |
7,596 | public void init ( ) { try { zk = new ZooKeeper ( parent . getProperties ( ) . get ( TeknekDaemon . ZK_SERVER_LIST ) . toString ( ) , 30000 , this ) ; } catch ( IOException e1 ) { throw new RuntimeException ( e1 ) ; } Feed feed = DriverFactory . buildFeed ( plan . getFeedDesc ( ) ) ; List < WorkerStatus > workerStatus ; try { workerStatus = parent . getWorkerDao ( ) . findAllWorkerStatusForPlan ( plan , otherWorkers ) ; } catch ( WorkerDaoException e1 ) { throw new RuntimeException ( e1 ) ; } if ( workerStatus . size ( ) >= feed . getFeedPartitions ( ) . size ( ) ) { throw new RuntimeException ( "Number of running workers " + workerStatus . size ( ) + " >= feed partitions " + feed . getFeedPartitions ( ) . size ( ) + " plan should be fixed " + plan . getName ( ) ) ; } FeedPartition toProcess = findPartitionToProcess ( workerStatus , feed . getFeedPartitions ( ) ) ; if ( toProcess != null ) { driver = DriverFactory . createDriver ( toProcess , plan , parent . getMetricRegistry ( ) ) ; driver . initialize ( ) ; WorkerStatus iGotThis = new WorkerStatus ( myId . toString ( ) , toProcess . getPartitionId ( ) , parent . getMyId ( ) ) ; try { parent . getWorkerDao ( ) . registerWorkerStatus ( zk , plan , iGotThis ) ; } catch ( WorkerDaoException e ) { throw new RuntimeException ( e ) ; } } else { throw new RuntimeException ( "Could not start plan " + plan . getName ( ) ) ; } } | Deterine what partitions of the feed are already attached to other workers . |
7,597 | private void shutdown ( ) { parent . workerThreads . get ( plan ) . remove ( this ) ; if ( zk != null ) { try { logger . debug ( "closing " + zk . getSessionId ( ) ) ; zk . close ( ) ; zk = null ; } catch ( InterruptedException e1 ) { logger . debug ( e1 ) ; } logger . debug ( "shutdown complete" ) ; } } | Remove ourselves from parents worker threads and close our zk connection |
7,598 | public String getDescription ( final Locale aContentLocale ) { final String ret = m_eCountry == null ? null : m_eCountry . getDisplayText ( aContentLocale ) ; return ret != null ? ret : "undefined" ; } | Returns the hierarchies description text from the resource bundle . |
7,599 | private static RDFNode toNode ( Object value ) { if ( value == null ) { return null ; } else if ( value instanceof RDFNode ) { return ( RDFNode ) value ; } else if ( value instanceof IRI ) { return new NamedNodeImpl ( URI . create ( ( ( IRI ) value ) . iri . toString ( ) ) ) ; } else if ( value instanceof PlainLiteral ) { PlainLiteral pl = ( PlainLiteral ) value ; String lang = pl . language != null ? pl . language . toString ( ) : null ; return new PlainLiteralImpl ( pl . lexical . toString ( ) , lang ) ; } else if ( value instanceof TypedLiteral ) { TypedLiteral tl = ( TypedLiteral ) value ; return new TypedLiteralImpl ( tl . lexical . toString ( ) , URI . create ( tl . datatype . toString ( ) ) ) ; } else if ( value instanceof BNode ) { return new BlankNodeImpl ( ( ( BNode ) value ) . label . toString ( ) ) ; } else { if ( value instanceof CharSequence ) { value = value . toString ( ) ; } return Conversions . toLiteral ( value ) ; } } | Convert a protocol data object to an RDFNode . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.