idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
148,700 | public void addRequiredBundles ( Set < String > bundles ) { // TODO manage transitive dependencies // don't require self Set < String > bundlesToMerge ; String bundleName = ( String ) getMainAttributes ( ) . get ( BUNDLE_SYMBOLIC_NAME ) ; if ( bundleName != null ) { int idx = bundleName . indexOf ( ' ' ) ; if ( idx >= 0 ) { bundleName = bundleName . substring ( 0 , idx ) ; } } if ( bundleName != null && bundles . contains ( bundleName ) || projectName != null && bundles . contains ( projectName ) ) { bundlesToMerge = new LinkedHashSet < String > ( bundles ) ; bundlesToMerge . remove ( bundleName ) ; bundlesToMerge . remove ( projectName ) ; } else { bundlesToMerge = bundles ; } String s = ( String ) getMainAttributes ( ) . get ( REQUIRE_BUNDLE ) ; Wrapper < Boolean > modified = Wrapper . wrap ( this . modified ) ; String result = mergeIntoCommaSeparatedList ( s , bundlesToMerge , modified , lineDelimiter ) ; this . modified = modified . get ( ) ; getMainAttributes ( ) . put ( REQUIRE_BUNDLE , result ) ; } | adds the qualified names to the require - bundle attribute if not already present . | 288 | 16 |
148,701 | public void addExportedPackages ( Set < String > packages ) { String s = ( String ) getMainAttributes ( ) . get ( EXPORT_PACKAGE ) ; Wrapper < Boolean > modified = Wrapper . wrap ( this . modified ) ; String result = mergeIntoCommaSeparatedList ( s , packages , modified , lineDelimiter ) ; this . modified = modified . get ( ) ; getMainAttributes ( ) . put ( EXPORT_PACKAGE , result ) ; } | adds the qualified names to the export - package attribute if not already present . | 108 | 16 |
148,702 | public void createProposals ( final Collection < ContentAssistContext > contexts , final IIdeContentProposalAcceptor acceptor ) { Iterable < ContentAssistContext > _filteredContexts = this . getFilteredContexts ( contexts ) ; for ( final ContentAssistContext context : _filteredContexts ) { ImmutableList < AbstractElement > _firstSetGrammarElements = context . getFirstSetGrammarElements ( ) ; for ( final AbstractElement element : _firstSetGrammarElements ) { { boolean _canAcceptMoreProposals = acceptor . canAcceptMoreProposals ( ) ; boolean _not = ( ! _canAcceptMoreProposals ) ; if ( _not ) { return ; } this . createProposals ( element , context , acceptor ) ; } } } } | Create content assist proposals and pass them to the given acceptor . | 181 | 13 |
148,703 | public String convertFromJavaString ( String string , boolean useUnicode ) { int firstEscapeSequence = string . indexOf ( ' ' ) ; if ( firstEscapeSequence == - 1 ) { return string ; } int length = string . length ( ) ; StringBuilder result = new StringBuilder ( length ) ; appendRegion ( string , 0 , firstEscapeSequence , result ) ; return convertFromJavaString ( string , useUnicode , firstEscapeSequence , result ) ; } | Resolve Java control character sequences to the actual character value . Optionally handle unicode escape sequences too . | 108 | 21 |
148,704 | public String convertToJavaString ( String input , boolean useUnicode ) { int length = input . length ( ) ; StringBuilder result = new StringBuilder ( length + 4 ) ; for ( int i = 0 ; i < length ; i ++ ) { escapeAndAppendTo ( input . charAt ( i ) , useUnicode , result ) ; } return result . toString ( ) ; } | Escapes control characters with a preceding backslash . Optionally encodes special chars as unicode escape sequence . The resulting string is safe to be put into a Java string literal between the quotes . | 86 | 40 |
148,705 | private void performDownload ( HttpResponse response , File destFile ) throws IOException { HttpEntity entity = response . getEntity ( ) ; if ( entity == null ) { return ; } //get content length long contentLength = entity . getContentLength ( ) ; if ( contentLength >= 0 ) { size = toLengthText ( contentLength ) ; } processedBytes = 0 ; loggedKb = 0 ; //open stream and start downloading InputStream is = entity . getContent ( ) ; streamAndMove ( is , destFile ) ; } | Save an HTTP response to a file | 114 | 7 |
148,706 | private void stream ( InputStream is , File destFile ) throws IOException { try { startProgress ( ) ; OutputStream os = new FileOutputStream ( destFile ) ; boolean finished = false ; try { byte [ ] buf = new byte [ 1024 * 10 ] ; int read ; while ( ( read = is . read ( buf ) ) >= 0 ) { os . write ( buf , 0 , read ) ; processedBytes += read ; logProgress ( ) ; } os . flush ( ) ; finished = true ; } finally { os . close ( ) ; if ( ! finished ) { destFile . delete ( ) ; } } } finally { is . close ( ) ; completeProgress ( ) ; } } | Copy bytes from an input stream to a file and log progress | 147 | 12 |
148,707 | private String getCachedETag ( HttpHost host , String file ) { Map < String , Object > cachedETags = readCachedETags ( ) ; @ SuppressWarnings ( "unchecked" ) Map < String , Object > hostMap = ( Map < String , Object > ) cachedETags . get ( host . toURI ( ) ) ; if ( hostMap == null ) { return null ; } @ SuppressWarnings ( "unchecked" ) Map < String , String > etagMap = ( Map < String , String > ) hostMap . get ( file ) ; if ( etagMap == null ) { return null ; } return etagMap . get ( "ETag" ) ; } | Get the cached ETag for the given host and file | 155 | 11 |
148,708 | private File makeDestFile ( URL src ) { if ( dest == null ) { throw new IllegalArgumentException ( "Please provide a download destination" ) ; } File destFile = dest ; if ( destFile . isDirectory ( ) ) { //guess name from URL String name = src . toString ( ) ; if ( name . endsWith ( "/" ) ) { name = name . substring ( 0 , name . length ( ) - 1 ) ; } name = name . substring ( name . lastIndexOf ( ' ' ) + 1 ) ; destFile = new File ( dest , name ) ; } else { //create destination directory File parent = destFile . getParentFile ( ) ; if ( parent != null ) { parent . mkdirs ( ) ; } } return destFile ; } | Generates the path to an output file for a given source URL . Creates all necessary parent directories for the destination file . | 170 | 25 |
148,709 | private void addAuthentication ( HttpHost host , Credentials credentials , AuthScheme authScheme , HttpClientContext context ) { AuthCache authCache = context . getAuthCache ( ) ; if ( authCache == null ) { authCache = new BasicAuthCache ( ) ; context . setAuthCache ( authCache ) ; } CredentialsProvider credsProvider = context . getCredentialsProvider ( ) ; if ( credsProvider == null ) { credsProvider = new BasicCredentialsProvider ( ) ; context . setCredentialsProvider ( credsProvider ) ; } credsProvider . setCredentials ( new AuthScope ( host ) , credentials ) ; if ( authScheme != null ) { authCache . put ( host , authScheme ) ; } } | Add authentication information for the given host | 168 | 7 |
148,710 | private String toLengthText ( long bytes ) { if ( bytes < 1024 ) { return bytes + " B" ; } else if ( bytes < 1024 * 1024 ) { return ( bytes / 1024 ) + " KB" ; } else if ( bytes < 1024 * 1024 * 1024 ) { return String . format ( "%.2f MB" , bytes / ( 1024.0 * 1024.0 ) ) ; } else { return String . format ( "%.2f GB" , bytes / ( 1024.0 * 1024.0 * 1024.0 ) ) ; } } | Converts a number of bytes to a human - readable string | 118 | 12 |
148,711 | public void close ( ) throws IOException { for ( CloseableHttpClient c : cachedClients . values ( ) ) { c . close ( ) ; } cachedClients . clear ( ) ; } | Close all HTTP clients created by this factory | 42 | 8 |
148,712 | public static Provider getCurrentProvider ( boolean useSwingEventQueue ) { Provider provider ; if ( Platform . isX11 ( ) ) { provider = new X11Provider ( ) ; } else if ( Platform . isWindows ( ) ) { provider = new WindowsProvider ( ) ; } else if ( Platform . isMac ( ) ) { provider = new CarbonProvider ( ) ; } else { LOGGER . warn ( "No suitable provider for " + System . getProperty ( "os.name" ) ) ; return null ; } provider . setUseSwingEventQueue ( useSwingEventQueue ) ; provider . init ( ) ; return provider ; } | Get global hotkey provider for current platform | 136 | 8 |
148,713 | protected void fireEvent ( HotKey hotKey ) { HotKeyEvent event = new HotKeyEvent ( hotKey ) ; if ( useSwingEventQueue ) { SwingUtilities . invokeLater ( event ) ; } else { if ( eventQueue == null ) { eventQueue = Executors . newSingleThreadExecutor ( ) ; } eventQueue . execute ( event ) ; } } | Helper method fro providers to fire hotkey event in a separate thread | 81 | 13 |
148,714 | public Object newInstance ( String resource ) { try { String name = resource . startsWith ( "/" ) ? resource : "/" + resource ; File file = new File ( this . getClass ( ) . getResource ( name ) . toURI ( ) ) ; return newInstance ( classLoader . parseClass ( new GroovyCodeSource ( file ) , true ) ) ; } catch ( Exception e ) { throw new GroovyClassInstantiationFailed ( classLoader , resource , e ) ; } } | Creates an object instance from the Groovy resource | 105 | 10 |
148,715 | private void addTypes ( Injector injector , List < Class < ? > > types ) { for ( Binding < ? > binding : injector . getBindings ( ) . values ( ) ) { Key < ? > key = binding . getKey ( ) ; Type type = key . getTypeLiteral ( ) . getType ( ) ; if ( hasAnnotatedMethods ( type ) ) { types . add ( ( ( Class < ? > ) type ) ) ; } } if ( injector . getParent ( ) != null ) { addTypes ( injector . getParent ( ) , types ) ; } } | Adds steps types from given injector and recursively its parent | 132 | 13 |
148,716 | public void map ( Story story , MetaFilter metaFilter ) { if ( metaFilter . allow ( story . getMeta ( ) ) ) { boolean allowed = false ; for ( Scenario scenario : story . getScenarios ( ) ) { // scenario also inherits meta from story Meta inherited = scenario . getMeta ( ) . inheritFrom ( story . getMeta ( ) ) ; if ( metaFilter . allow ( inherited ) ) { allowed = true ; break ; } } if ( allowed ) { add ( metaFilter . asString ( ) , story ) ; } } } | Maps a story if it is allowed by the meta filter | 119 | 11 |
148,717 | protected MetaMatcher createMetaMatcher ( String filterAsString , Map < String , MetaMatcher > metaMatchers ) { for ( String key : metaMatchers . keySet ( ) ) { if ( filterAsString . startsWith ( key ) ) { return metaMatchers . get ( key ) ; } } if ( filterAsString . startsWith ( GROOVY ) ) { return new GroovyMetaMatcher ( ) ; } return new DefaultMetaMatcher ( ) ; } | Creates a MetaMatcher based on the filter content . | 104 | 12 |
148,718 | public static URL codeLocationFromClass ( Class < ? > codeLocationClass ) { String pathOfClass = codeLocationClass . getName ( ) . replace ( "." , "/" ) + ".class" ; URL classResource = codeLocationClass . getClassLoader ( ) . getResource ( pathOfClass ) ; String codeLocationPath = removeEnd ( getPathFromURL ( classResource ) , pathOfClass ) ; if ( codeLocationPath . endsWith ( ".jar!/" ) ) { codeLocationPath = removeEnd ( codeLocationPath , "!/" ) ; } return codeLocationFromPath ( codeLocationPath ) ; } | Creates a code location URL from a class | 133 | 9 |
148,719 | public static URL codeLocationFromPath ( String filePath ) { try { return new File ( filePath ) . toURI ( ) . toURL ( ) ; } catch ( Exception e ) { throw new InvalidCodeLocation ( filePath ) ; } } | Creates a code location URL from a file path | 52 | 10 |
148,720 | public static URL codeLocationFromURL ( String url ) { try { return new URL ( url ) ; } catch ( Exception e ) { throw new InvalidCodeLocation ( url ) ; } } | Creates a code location URL from a URL | 39 | 9 |
148,721 | public void run ( Configuration configuration , List < CandidateSteps > candidateSteps , Story story ) throws Throwable { run ( configuration , candidateSteps , story , MetaFilter . EMPTY ) ; } | Runs a Story with the given configuration and steps . | 42 | 11 |
148,722 | public void run ( Configuration configuration , List < CandidateSteps > candidateSteps , Story story , MetaFilter filter ) throws Throwable { run ( configuration , candidateSteps , story , filter , null ) ; } | Runs a Story with the given configuration and steps applying the given meta filter . | 44 | 16 |
148,723 | public void run ( Configuration configuration , List < CandidateSteps > candidateSteps , Story story , MetaFilter filter , State beforeStories ) throws Throwable { run ( configuration , new ProvidedStepsFactory ( candidateSteps ) , story , filter , beforeStories ) ; } | Runs a Story with the given configuration and steps applying the given meta filter and staring from given state . | 58 | 21 |
148,724 | public void run ( Configuration configuration , InjectableStepsFactory stepsFactory , Story story , MetaFilter filter , State beforeStories ) throws Throwable { RunContext context = new RunContext ( configuration , stepsFactory , story . getPath ( ) , filter ) ; if ( beforeStories != null ) { context . stateIs ( beforeStories ) ; } Map < String , String > storyParameters = new HashMap <> ( ) ; run ( context , story , storyParameters ) ; } | Runs a Story with the given steps factory applying the given meta filter and staring from given state . | 103 | 20 |
148,725 | public Story storyOfPath ( Configuration configuration , String storyPath ) { String storyAsText = configuration . storyLoader ( ) . loadStoryAsText ( storyPath ) ; return configuration . storyParser ( ) . parseStory ( storyAsText , storyPath ) ; } | Returns the parsed story from the given path | 55 | 8 |
148,726 | public Story storyOfText ( Configuration configuration , String storyAsText , String storyId ) { return configuration . storyParser ( ) . parseStory ( storyAsText , storyId ) ; } | Returns the parsed story from the given text | 39 | 8 |
148,727 | public Object newInstance ( String className ) { try { return classLoader . loadClass ( className ) . newInstance ( ) ; } catch ( Exception e ) { throw new ScalaInstanceNotFound ( className ) ; } } | Creates an object instance from the Scala class name | 48 | 10 |
148,728 | @ Override public Map < String , String > values ( ) { Map < String , String > values = new LinkedHashMap <> ( ) ; for ( Row each : delegates ) { for ( Entry < String , String > entry : each . values ( ) . entrySet ( ) ) { String name = entry . getKey ( ) ; if ( ! values . containsKey ( name ) ) { values . put ( name , entry . getValue ( ) ) ; } } } return values ; } | Returns values aggregated from all the delegates without overriding values that already exist . | 105 | 15 |
148,729 | public List < Object > stepsInstances ( List < CandidateSteps > candidateSteps ) { List < Object > instances = new ArrayList <> ( ) ; for ( CandidateSteps steps : candidateSteps ) { if ( steps instanceof Steps ) { instances . add ( ( ( Steps ) steps ) . instance ( ) ) ; } } return instances ; } | Returns the steps instances associated to CandidateSteps | 76 | 9 |
148,730 | public List < StepCandidate > prioritise ( String stepAsText , List < StepCandidate > candidates ) { return prioritisingStrategy . prioritise ( stepAsText , candidates ) ; } | Prioritises the list of step candidates that match a given step . | 41 | 14 |
148,731 | protected String format ( String key , String defaultPattern , Object ... args ) { String escape = escape ( defaultPattern ) ; String s = lookupPattern ( key , escape ) ; Object [ ] objects = escapeAll ( args ) ; return MessageFormat . format ( s , objects ) ; } | Formats event output by key usually equal to the method name . | 59 | 13 |
148,732 | protected Object [ ] escape ( final Format format , Object ... args ) { // Transformer that escapes HTML,XML,JSON strings Transformer < Object , Object > escapingTransformer = new Transformer < Object , Object > ( ) { @ Override public Object transform ( Object object ) { return format . escapeValue ( object ) ; } } ; List < Object > list = Arrays . asList ( ArrayUtils . clone ( args ) ) ; CollectionUtils . transform ( list , escapingTransformer ) ; return list . toArray ( ) ; } | Escapes args string values according to format | 116 | 8 |
148,733 | protected void print ( String text ) { String tableStart = format ( PARAMETER_TABLE_START , PARAMETER_TABLE_START ) ; String tableEnd = format ( PARAMETER_TABLE_END , PARAMETER_TABLE_END ) ; boolean containsTable = text . contains ( tableStart ) && text . contains ( tableEnd ) ; String textToPrint = containsTable ? transformPrintingTable ( text , tableStart , tableEnd ) : text ; print ( output , textToPrint . replace ( format ( PARAMETER_VALUE_START , PARAMETER_VALUE_START ) , format ( "parameterValueStart" , EMPTY ) ) . replace ( format ( PARAMETER_VALUE_END , PARAMETER_VALUE_END ) , format ( "parameterValueEnd" , EMPTY ) ) . replace ( format ( PARAMETER_VALUE_NEWLINE , PARAMETER_VALUE_NEWLINE ) , format ( "parameterValueNewline" , NL ) ) ) ; } | Prints text to output stream replacing parameter start and end placeholders | 229 | 13 |
148,734 | private List < ParameterConverter > methodReturningConverters ( final Class < ? > type ) { final List < ParameterConverter > converters = new ArrayList <> ( ) ; for ( final Method method : type . getMethods ( ) ) { if ( method . isAnnotationPresent ( AsParameterConverter . class ) ) { converters . add ( new MethodReturningConverter ( method , type , this ) ) ; } } return converters ; } | Create parameter converters from methods annotated with | 105 | 9 |
148,735 | static InjectionProvider < ? > [ ] toArray ( final Set < InjectionProvider < ? > > injectionProviders ) { return injectionProviders . toArray ( new InjectionProvider < ? > [ injectionProviders . size ( ) ] ) ; } | Set to array . | 54 | 4 |
148,736 | @ AsParameterConverter public Trader retrieveTrader ( String name ) { for ( Trader trader : traders ) { if ( trader . getName ( ) . equals ( name ) ) { return trader ; } } return mockTradePersister ( ) . retrieveTrader ( name ) ; } | Method used as dynamical parameter converter | 60 | 7 |
148,737 | private Class < ? > beanType ( String name ) { Class < ? > type = context . getType ( name ) ; if ( ClassUtils . isCglibProxyClass ( type ) ) { return AopProxyUtils . ultimateTargetClass ( context . getBean ( name ) ) ; } return type ; } | Return the bean type untangling the proxy if needed | 69 | 10 |
148,738 | private boolean findBinding ( Injector injector , Class < ? > type ) { boolean found = false ; for ( Key < ? > key : injector . getBindings ( ) . keySet ( ) ) { if ( key . getTypeLiteral ( ) . getRawType ( ) . equals ( type ) ) { found = true ; break ; } } if ( ! found && injector . getParent ( ) != null ) { return findBinding ( injector . getParent ( ) , type ) ; } return found ; } | Finds binding for a type in the given injector and if not found recurses to its parent | 116 | 20 |
148,739 | public List < String > scan ( ) { try { JarFile jar = new JarFile ( jarURL . getFile ( ) ) ; try { List < String > result = new ArrayList <> ( ) ; Enumeration < JarEntry > en = jar . entries ( ) ; while ( en . hasMoreElements ( ) ) { JarEntry entry = en . nextElement ( ) ; String path = entry . getName ( ) ; boolean match = includes . size ( ) == 0 ; if ( ! match ) { for ( String pattern : includes ) { if ( patternMatches ( pattern , path ) ) { match = true ; break ; } } } if ( match ) { for ( String pattern : excludes ) { if ( patternMatches ( pattern , path ) ) { match = false ; break ; } } } if ( match ) { result . add ( path ) ; } } return result ; } finally { jar . close ( ) ; } } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } } | Scans the jar file and returns the paths that match the includes and excludes . | 218 | 16 |
148,740 | public String getMethodSignature ( ) { if ( method != null ) { String methodSignature = method . toString ( ) ; return methodSignature . replaceFirst ( "public void " , "" ) ; } return null ; } | Method signature without public void prefix | 49 | 6 |
148,741 | @ Override public Configuration configuration ( ) { return new MostUsefulConfiguration ( ) // where to find the stories . useStoryLoader ( new LoadFromClasspath ( this . getClass ( ) ) ) // CONSOLE and TXT reporting . useStoryReporterBuilder ( new StoryReporterBuilder ( ) . withDefaultFormats ( ) . withFormats ( Format . CONSOLE , Format . TXT ) ) ; } | Here we specify the configuration starting from default MostUsefulConfiguration and changing only what is needed | 90 | 18 |
148,742 | public GetAssignmentGroupOptions includes ( List < Include > includes ) { List < Include > assignmentDependents = Arrays . asList ( Include . DISCUSSION_TOPIC , Include . ASSIGNMENT_VISIBILITY , Include . SUBMISSION ) ; if ( includes . stream ( ) . anyMatch ( assignmentDependents :: contains ) && ! includes . contains ( Include . ASSIGNMENTS ) ) { throw new IllegalArgumentException ( "Including discussion topics, all dates, assignment visibility or submissions is only valid if you also include submissions" ) ; } addEnumList ( "include[]" , includes ) ; return this ; } | Additional objects to include with the requested group . Note that all the optional includes depend on assignments also being included . | 138 | 22 |
148,743 | private void ensureToolValidForCreation ( ExternalTool tool ) { //check for the unconditionally required fields if ( StringUtils . isAnyBlank ( tool . getName ( ) , tool . getPrivacyLevel ( ) , tool . getConsumerKey ( ) , tool . getSharedSecret ( ) ) ) { throw new IllegalArgumentException ( "External tool requires all of the following for creation: name, privacy level, consumer key, shared secret" ) ; } //check that there is either a URL or a domain. One or the other is required if ( StringUtils . isBlank ( tool . getUrl ( ) ) && StringUtils . isBlank ( tool . getDomain ( ) ) ) { throw new IllegalArgumentException ( "External tool requires either a URL or domain for creation" ) ; } } | Ensure that a tool object is valid for creation . The API requires certain fields to be filled out . Throws an IllegalArgumentException if the conditions are not met . | 175 | 35 |
148,744 | public GetSingleConversationOptions filters ( List < String > filters ) { if ( filters . size ( ) == 1 ) { //Canvas API doesn't want the [] if it is only one value addSingleItem ( "filter" , filters . get ( 0 ) ) ; } else { optionsMap . put ( "filter[]" , filters ) ; } return this ; } | Used when setting the visible field in the response . See the List Conversations docs for details | 79 | 18 |
148,745 | public < T extends CanvasReader > T getReader ( Class < T > type , OauthToken oauthToken ) { return getReader ( type , oauthToken , null ) ; } | Get a reader implementation class to perform API calls with . | 40 | 11 |
148,746 | public < T extends CanvasReader > T getReader ( Class < T > type , OauthToken oauthToken , Integer paginationPageSize ) { LOG . debug ( "Factory call to instantiate class: " + type . getName ( ) ) ; RestClient restClient = new RefreshingRestClient ( ) ; @ SuppressWarnings ( "unchecked" ) Class < T > concreteClass = ( Class < T > ) readerMap . get ( type ) ; if ( concreteClass == null ) { throw new UnsupportedOperationException ( "No implementation for requested interface found: " + type . getName ( ) ) ; } LOG . debug ( "got class: " + concreteClass ) ; try { Constructor < T > constructor = concreteClass . getConstructor ( String . class , Integer . class , OauthToken . class , RestClient . class , Integer . TYPE , Integer . TYPE , Integer . class , Boolean . class ) ; return constructor . newInstance ( canvasBaseUrl , CANVAS_API_VERSION , oauthToken , restClient , connectTimeout , readTimeout , paginationPageSize , false ) ; } catch ( NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e ) { throw new UnsupportedOperationException ( "Unknown error instantiating the concrete API class: " + type . getName ( ) , e ) ; } } | Get a reader implementation class to perform API calls with while specifying an explicit page size for paginated API calls . This gets translated to a per_page = parameter on API requests . Note that Canvas does not guarantee it will honor this page size request . There is an explicit maximum page size on the server side which could change . The default page size is 10 which can be limiting when for example trying to get all users in a 800 person course . | 294 | 90 |
148,747 | public < T extends CanvasWriter > T getWriter ( Class < T > type , OauthToken oauthToken ) { return getWriter ( type , oauthToken , false ) ; } | Get a writer implementation to push data into Canvas . | 40 | 11 |
148,748 | public < T extends CanvasWriter > T getWriter ( Class < T > type , OauthToken oauthToken , Boolean serializeNulls ) { LOG . debug ( "Factory call to instantiate class: " + type . getName ( ) ) ; RestClient restClient = new RefreshingRestClient ( ) ; @ SuppressWarnings ( "unchecked" ) Class < T > concreteClass = ( Class < T > ) writerMap . get ( type ) ; if ( concreteClass == null ) { throw new UnsupportedOperationException ( "No implementation for requested interface found: " + type . getName ( ) ) ; } LOG . debug ( "got writer class: " + concreteClass ) ; try { Constructor < T > constructor = concreteClass . getConstructor ( String . class , Integer . class , OauthToken . class , RestClient . class , Integer . TYPE , Integer . TYPE , Integer . class , Boolean . class ) ; return constructor . newInstance ( canvasBaseUrl , CANVAS_API_VERSION , oauthToken , restClient , connectTimeout , readTimeout , null , serializeNulls ) ; } catch ( NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e ) { throw new UnsupportedOperationException ( "Unknown error instantiating the concrete API class: " + type . getName ( ) , e ) ; } } | Get a writer implementation to push data into Canvas while being able to control the behavior of blank values . If the serializeNulls parameter is set to true this writer will serialize null fields in the JSON being sent to Canvas . This is required if you want to explicitly blank out a value that is currently set to something . | 295 | 67 |
148,749 | public ListActiveCoursesInAccountOptions searchTerm ( String searchTerm ) { if ( searchTerm == null || searchTerm . length ( ) < 3 ) { throw new IllegalArgumentException ( "Search term must be at least 3 characters" ) ; } addSingleItem ( "search_term" , searchTerm ) ; return this ; } | Filter on a search term . Can be course name code or full ID . Must be at least 3 characters | 71 | 21 |
148,750 | public ListExternalToolsOptions searchTerm ( String searchTerm ) { if ( searchTerm == null || searchTerm . length ( ) < 3 ) { throw new IllegalArgumentException ( "Search term must be at least 3 characters" ) ; } addSingleItem ( "search_term" , searchTerm ) ; return this ; } | Only return tools with a name matching this partial string | 68 | 10 |
148,751 | private List < EnrollmentTerm > parseEnrollmentTermList ( final List < Response > responses ) { return responses . stream ( ) . map ( this :: parseEnrollmentTermList ) . flatMap ( Collection :: stream ) . collect ( Collectors . toList ( ) ) ; } | a useless object at the top level of the response JSON for no reason at all . | 59 | 17 |
148,752 | private Response sendJsonPostOrPut ( OauthToken token , String url , String json , int connectTimeout , int readTimeout , String method ) throws IOException { LOG . debug ( "Sending JSON " + method + " to URL: " + url ) ; Response response = new Response ( ) ; HttpClient httpClient = createHttpClient ( connectTimeout , readTimeout ) ; HttpEntityEnclosingRequestBase action ; if ( "POST" . equals ( method ) ) { action = new HttpPost ( url ) ; } else if ( "PUT" . equals ( method ) ) { action = new HttpPut ( url ) ; } else { throw new IllegalArgumentException ( "Method must be either POST or PUT" ) ; } Long beginTime = System . currentTimeMillis ( ) ; action . setHeader ( "Authorization" , "Bearer" + " " + token . getAccessToken ( ) ) ; StringEntity requestBody = new StringEntity ( json , ContentType . APPLICATION_JSON ) ; action . setEntity ( requestBody ) ; try { HttpResponse httpResponse = httpClient . execute ( action ) ; String content = handleResponse ( httpResponse , action ) ; response . setContent ( content ) ; response . setResponseCode ( httpResponse . getStatusLine ( ) . getStatusCode ( ) ) ; Long endTime = System . currentTimeMillis ( ) ; LOG . debug ( "POST call took: " + ( endTime - beginTime ) + "ms" ) ; } finally { action . releaseConnection ( ) ; } return response ; } | PUT and POST are identical calls except for the header specifying the method | 339 | 13 |
148,753 | protected void addEnumList ( String key , List < ? extends Enum > list ) { optionsMap . put ( key , list . stream ( ) . map ( i -> i . toString ( ) ) . collect ( Collectors . toList ( ) ) ) ; } | Add a list of enums to the options map | 58 | 10 |
148,754 | public void setLargePayloadSupportEnabled ( AmazonS3 s3 , String s3BucketName ) { if ( s3 == null || s3BucketName == null ) { String errorMessage = "S3 client and/or S3 bucket name cannot be null." ; LOG . error ( errorMessage ) ; throw new AmazonClientException ( errorMessage ) ; } if ( isLargePayloadSupportEnabled ( ) ) { LOG . warn ( "Large-payload support is already enabled. Overwriting AmazonS3Client and S3BucketName." ) ; } this . s3 = s3 ; this . s3BucketName = s3BucketName ; largePayloadSupport = true ; LOG . info ( "Large-payload support enabled." ) ; } | Enables support for large - payload messages . | 164 | 9 |
148,755 | private String readLine ( boolean trim ) throws IOException { boolean done = false ; boolean sawCarriage = false ; // bytes to trim (the \r and the \n) int removalBytes = 0 ; while ( ! done ) { if ( isReadBufferEmpty ( ) ) { offset = 0 ; end = 0 ; int bytesRead = inputStream . read ( buffer , end , Math . min ( DEFAULT_READ_COUNT , buffer . length - end ) ) ; if ( bytesRead < 0 ) { // we failed to read anything more... throw new IOException ( "Reached the end of the stream" ) ; } else { end += bytesRead ; } } int originalOffset = offset ; for ( ; ! done && offset < end ; offset ++ ) { if ( buffer [ offset ] == LF ) { int cpLength = offset - originalOffset + 1 ; if ( trim ) { int length = 0 ; if ( buffer [ offset ] == LF ) { length ++ ; if ( sawCarriage ) { length ++ ; } } cpLength -= length ; } if ( cpLength > 0 ) { copyToStrBuffer ( buffer , originalOffset , cpLength ) ; } else { // negative length means we need to trim a \r from strBuffer removalBytes = cpLength ; } done = true ; } else { // did not see newline: sawCarriage = buffer [ offset ] == CR ; } } if ( ! done ) { copyToStrBuffer ( buffer , originalOffset , end - originalOffset ) ; offset = end ; } } int strLength = strBufferIndex + removalBytes ; strBufferIndex = 0 ; return new String ( strBuffer , 0 , strLength , charset ) ; } | Reads a line from the input stream where a line is terminated by \ r \ n or \ r \ n | 359 | 23 |
148,756 | private void copyToStrBuffer ( byte [ ] buffer , int offset , int length ) { Preconditions . checkArgument ( length >= 0 ) ; if ( strBuffer . length - strBufferIndex < length ) { // cannot fit, expanding buffer expandStrBuffer ( length ) ; } System . arraycopy ( buffer , offset , strBuffer , strBufferIndex , Math . min ( length , MAX_ALLOWABLE_BUFFER_SIZE - strBufferIndex ) ) ; strBufferIndex += length ; } | Copies from buffer to our internal strBufferIndex expanding the internal buffer if necessary | 106 | 16 |
148,757 | public String read ( int numBytes ) throws IOException { Preconditions . checkArgument ( numBytes >= 0 ) ; Preconditions . checkArgument ( numBytes <= MAX_ALLOWABLE_BUFFER_SIZE ) ; int numBytesRemaining = numBytes ; // first read whatever we need from our buffer if ( ! isReadBufferEmpty ( ) ) { int length = Math . min ( end - offset , numBytesRemaining ) ; copyToStrBuffer ( buffer , offset , length ) ; offset += length ; numBytesRemaining -= length ; } // next read the remaining chars directly into our strBuffer if ( numBytesRemaining > 0 ) { readAmountToStrBuffer ( numBytesRemaining ) ; } if ( strBufferIndex > 0 && strBuffer [ strBufferIndex - 1 ] != LF ) { // the last byte doesn't correspond to lf return readLine ( false ) ; } int strBufferLength = strBufferIndex ; strBufferIndex = 0 ; return new String ( strBuffer , 0 , strBufferLength , charset ) ; } | Reads numBytes bytes and returns the corresponding string | 225 | 10 |
148,758 | public DefaultStreamingEndpoint languages ( List < String > languages ) { addPostParameter ( Constants . LANGUAGE_PARAM , Joiner . on ( ' ' ) . join ( languages ) ) ; return this ; } | Filter for public tweets on these languages . | 49 | 8 |
148,759 | @ Override public void process ( ) { if ( client . isDone ( ) || executorService . isTerminated ( ) ) { throw new IllegalStateException ( "Client is already stopped" ) ; } Runnable runner = new Runnable ( ) { @ Override public void run ( ) { try { while ( ! client . isDone ( ) ) { String msg = messageQueue . take ( ) ; try { parseMessage ( msg ) ; } catch ( Exception e ) { logger . warn ( "Exception thrown during parsing msg " + msg , e ) ; onException ( e ) ; } } } catch ( Exception e ) { onException ( e ) ; } } } ; executorService . execute ( runner ) ; } | Forks off a runnable with the executor provided . Multiple calls are allowed but the listeners must be threadsafe . | 155 | 25 |
148,760 | public void stop ( int waitMillis ) throws InterruptedException { try { if ( ! isDone ( ) ) { setExitStatus ( new Event ( EventType . STOPPED_BY_USER , String . format ( "Stopped by user: waiting for %d ms" , waitMillis ) ) ) ; } if ( ! waitForFinish ( waitMillis ) ) { logger . warn ( "{} Client thread failed to finish in {} millis" , name , waitMillis ) ; } } finally { rateTracker . shutdown ( ) ; } } | Stops the current connection . No reconnecting will occur . Kills thread + cleanup . Waits for the loop to end | 118 | 24 |
148,761 | public void fireEvent ( final WorkerEvent event , final Worker worker , final String queue , final Job job , final Object runner , final Object result , final Throwable t ) { final ConcurrentSet < WorkerListener > listeners = this . eventListenerMap . get ( event ) ; if ( listeners != null ) { for ( final WorkerListener listener : listeners ) { if ( listener != null ) { try { listener . onEvent ( event , worker , queue , job , runner , result , t ) ; } catch ( Exception e ) { log . error ( "Failure executing listener " + listener + " for event " + event + " from queue " + queue + " on worker " + worker , e ) ; } } } } } | Notify all WorkerListeners currently registered for the given WorkerEvent . | 151 | 14 |
148,762 | public static List < String > createBacktrace ( final Throwable t ) { final List < String > bTrace = new LinkedList < String > ( ) ; for ( final StackTraceElement ste : t . getStackTrace ( ) ) { bTrace . add ( BT_PREFIX + ste . toString ( ) ) ; } if ( t . getCause ( ) != null ) { addCauseToBacktrace ( t . getCause ( ) , bTrace ) ; } return bTrace ; } | Creates a Resque backtrace from a Throwable s stack trace . Includes causes . | 112 | 18 |
148,763 | private static void addCauseToBacktrace ( final Throwable cause , final List < String > bTrace ) { if ( cause . getMessage ( ) == null ) { bTrace . add ( BT_CAUSED_BY_PREFIX + cause . getClass ( ) . getName ( ) ) ; } else { bTrace . add ( BT_CAUSED_BY_PREFIX + cause . getClass ( ) . getName ( ) + ": " + cause . getMessage ( ) ) ; } for ( final StackTraceElement ste : cause . getStackTrace ( ) ) { bTrace . add ( BT_PREFIX + ste . toString ( ) ) ; } if ( cause . getCause ( ) != null ) { addCauseToBacktrace ( cause . getCause ( ) , bTrace ) ; } } | Add a cause to the backtrace . | 185 | 8 |
148,764 | @ SafeVarargs public static < K , V > Map < K , V > map ( final Entry < ? extends K , ? extends V > ... entries ) { final Map < K , V > map = new LinkedHashMap < K , V > ( entries . length ) ; for ( final Entry < ? extends K , ? extends V > entry : entries ) { map . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } return map ; } | A convenient way of creating a map on the fly . | 101 | 11 |
148,765 | @ SafeVarargs public static < K > Set < K > set ( final K ... keys ) { return new LinkedHashSet < K > ( Arrays . asList ( keys ) ) ; } | Creates a Set out of the given keys | 42 | 9 |
148,766 | public static boolean nullSafeEquals ( final Object obj1 , final Object obj2 ) { return ( ( obj1 == null && obj2 == null ) || ( obj1 != null && obj2 != null && obj1 . equals ( obj2 ) ) ) ; } | Test for equality . | 56 | 4 |
148,767 | private long size ( final Jedis jedis , final String queueName ) { final String key = key ( QUEUE , queueName ) ; final long size ; if ( JedisUtils . isDelayedQueue ( jedis , key ) ) { // If delayed queue, use ZCARD size = jedis . zcard ( key ) ; } else { // Else, use LLEN size = jedis . llen ( key ) ; } return size ; } | Size of a queue . | 102 | 5 |
148,768 | private List < Job > getJobs ( final Jedis jedis , final String queueName , final long jobOffset , final long jobCount ) throws Exception { final String key = key ( QUEUE , queueName ) ; final List < Job > jobs = new ArrayList <> ( ) ; if ( JedisUtils . isDelayedQueue ( jedis , key ) ) { // If delayed queue, use ZRANGEWITHSCORES final Set < Tuple > elements = jedis . zrangeWithScores ( key , jobOffset , jobOffset + jobCount - 1 ) ; for ( final Tuple elementWithScore : elements ) { final Job job = ObjectMapperFactory . get ( ) . readValue ( elementWithScore . getElement ( ) , Job . class ) ; job . setRunAt ( elementWithScore . getScore ( ) ) ; jobs . add ( job ) ; } } else { // Else, use LRANGE final List < String > elements = jedis . lrange ( key , jobOffset , jobOffset + jobCount - 1 ) ; for ( final String element : elements ) { jobs . add ( ObjectMapperFactory . get ( ) . readValue ( element , Job . class ) ) ; } } return jobs ; } | Get list of Jobs from a queue . | 271 | 8 |
148,769 | @ SuppressWarnings ( "unchecked" ) public void setVars ( final Map < String , ? extends Object > vars ) { this . vars = ( Map < String , Object > ) vars ; } | Set the named arguments . | 48 | 5 |
148,770 | @ JsonAnySetter public void setUnknownField ( final String name , final Object value ) { this . unknownFields . put ( name , value ) ; } | Set an unknown field . | 35 | 5 |
148,771 | @ JsonIgnore public void setUnknownFields ( final Map < String , Object > unknownFields ) { this . unknownFields . clear ( ) ; this . unknownFields . putAll ( unknownFields ) ; } | Set all unknown fields | 49 | 4 |
148,772 | public void addJobType ( final String jobName , final Class < ? > jobType ) { checkJobType ( jobName , jobType ) ; this . jobTypes . put ( jobName , jobType ) ; } | Allow the given job type to be executed . | 46 | 9 |
148,773 | public void removeJobType ( final Class < ? > jobType ) { if ( jobType == null ) { throw new IllegalArgumentException ( "jobType must not be null" ) ; } this . jobTypes . values ( ) . remove ( jobType ) ; } | Disallow the job type from being executed . | 57 | 9 |
148,774 | public void setJobTypes ( final Map < String , ? extends Class < ? > > jobTypes ) { checkJobTypes ( jobTypes ) ; this . jobTypes . clear ( ) ; this . jobTypes . putAll ( jobTypes ) ; } | Clear any current allowed job types and use the given set . | 52 | 12 |
148,775 | protected void checkJobTypes ( final Map < String , ? extends Class < ? > > jobTypes ) { if ( jobTypes == null ) { throw new IllegalArgumentException ( "jobTypes must not be null" ) ; } for ( final Entry < String , ? extends Class < ? > > entry : jobTypes . entrySet ( ) ) { try { checkJobType ( entry . getKey ( ) , entry . getValue ( ) ) ; } catch ( IllegalArgumentException iae ) { throw new IllegalArgumentException ( "jobTypes contained invalid value" , iae ) ; } } } | Verify the given job types are all valid . | 127 | 10 |
148,776 | protected void checkJobType ( final String jobName , final Class < ? > jobType ) { if ( jobName == null ) { throw new IllegalArgumentException ( "jobName must not be null" ) ; } if ( jobType == null ) { throw new IllegalArgumentException ( "jobType must not be null" ) ; } if ( ! ( Runnable . class . isAssignableFrom ( jobType ) ) && ! ( Callable . class . isAssignableFrom ( jobType ) ) ) { throw new IllegalArgumentException ( "jobType must implement either Runnable or Callable: " + jobType ) ; } } | Determine if a job name and job type are valid . | 140 | 13 |
148,777 | public static void doPublish ( final Jedis jedis , final String namespace , final String channel , final String jobJson ) { jedis . publish ( JesqueUtils . createKey ( namespace , CHANNEL , channel ) , jobJson ) ; } | Helper method that encapsulates the minimum logic for publishing a job to a channel . | 58 | 16 |
148,778 | public static < T > T createObject ( final Class < T > clazz , final Object ... args ) throws NoSuchConstructorException , AmbiguousConstructorException , ReflectiveOperationException { return findConstructor ( clazz , args ) . newInstance ( args ) ; } | Create an object of the given type using a constructor that matches the supplied arguments . | 58 | 16 |
148,779 | public static < T > T createObject ( final Class < T > clazz , final Object [ ] args , final Map < String , Object > vars ) throws NoSuchConstructorException , AmbiguousConstructorException , ReflectiveOperationException { return invokeSetters ( findConstructor ( clazz , args ) . newInstance ( args ) , vars ) ; } | Create an object of the given type using a constructor that matches the supplied arguments and invoke the setters with the supplied variables . | 77 | 25 |
148,780 | @ SuppressWarnings ( "rawtypes" ) private static < T > Constructor < T > findConstructor ( final Class < T > clazz , final Object ... args ) throws NoSuchConstructorException , AmbiguousConstructorException { final Object [ ] cArgs = ( args == null ) ? new Object [ 0 ] : args ; Constructor < T > constructorToUse = null ; final Constructor < ? > [ ] candidates = clazz . getConstructors ( ) ; Arrays . sort ( candidates , ConstructorComparator . INSTANCE ) ; int minTypeDiffWeight = Integer . MAX_VALUE ; Set < Constructor < ? > > ambiguousConstructors = null ; for ( final Constructor candidate : candidates ) { final Class [ ] paramTypes = candidate . getParameterTypes ( ) ; if ( constructorToUse != null && cArgs . length > paramTypes . length ) { // Already found greedy constructor that can be satisfied. // Do not look any further, there are only less greedy // constructors left. break ; } if ( paramTypes . length != cArgs . length ) { continue ; } final int typeDiffWeight = getTypeDifferenceWeight ( paramTypes , cArgs ) ; if ( typeDiffWeight < minTypeDiffWeight ) { // Choose this constructor if it represents the closest match. constructorToUse = candidate ; minTypeDiffWeight = typeDiffWeight ; ambiguousConstructors = null ; } else if ( constructorToUse != null && typeDiffWeight == minTypeDiffWeight ) { if ( ambiguousConstructors == null ) { ambiguousConstructors = new LinkedHashSet < Constructor < ? > > ( ) ; ambiguousConstructors . add ( constructorToUse ) ; } ambiguousConstructors . add ( candidate ) ; } } if ( ambiguousConstructors != null && ! ambiguousConstructors . isEmpty ( ) ) { throw new AmbiguousConstructorException ( clazz , cArgs , ambiguousConstructors ) ; } if ( constructorToUse == null ) { throw new NoSuchConstructorException ( clazz , cArgs ) ; } return constructorToUse ; } | Find a Constructor on the given type that matches the given arguments . | 439 | 14 |
148,781 | public static < T > T invokeSetters ( final T instance , final Map < String , Object > vars ) throws ReflectiveOperationException { if ( instance != null && vars != null ) { final Class < ? > clazz = instance . getClass ( ) ; final Method [ ] methods = clazz . getMethods ( ) ; for ( final Entry < String , Object > entry : vars . entrySet ( ) ) { final String methodName = "set" + entry . getKey ( ) . substring ( 0 , 1 ) . toUpperCase ( Locale . US ) + entry . getKey ( ) . substring ( 1 ) ; boolean found = false ; for ( final Method method : methods ) { if ( methodName . equals ( method . getName ( ) ) && method . getParameterTypes ( ) . length == 1 ) { method . invoke ( instance , entry . getValue ( ) ) ; found = true ; break ; } } if ( ! found ) { throw new NoSuchMethodException ( "Expected setter named '" + methodName + "' for var '" + entry . getKey ( ) + "'" ) ; } } } return instance ; } | Invoke the setters for the given variables on the given instance . | 252 | 14 |
148,782 | protected static void checkQueues ( final Iterable < String > queues ) { if ( queues == null ) { throw new IllegalArgumentException ( "queues must not be null" ) ; } for ( final String queue : queues ) { if ( queue == null || "" . equals ( queue ) ) { throw new IllegalArgumentException ( "queues' members must not be null: " + queues ) ; } } } | Verify that the given queues are all valid . | 89 | 10 |
148,783 | protected String failMsg ( final Throwable thrwbl , final String queue , final Job job ) throws IOException { final JobFailure failure = new JobFailure ( ) ; failure . setFailedAt ( new Date ( ) ) ; failure . setWorker ( this . name ) ; failure . setQueue ( queue ) ; failure . setPayload ( job ) ; failure . setThrowable ( thrwbl ) ; return ObjectMapperFactory . get ( ) . writeValueAsString ( failure ) ; } | Create and serialize a JobFailure . | 106 | 8 |
148,784 | protected String statusMsg ( final String queue , final Job job ) throws IOException { final WorkerStatus status = new WorkerStatus ( ) ; status . setRunAt ( new Date ( ) ) ; status . setQueue ( queue ) ; status . setPayload ( job ) ; return ObjectMapperFactory . get ( ) . writeValueAsString ( status ) ; } | Create and serialize a WorkerStatus . | 76 | 8 |
148,785 | protected String pauseMsg ( ) throws IOException { final WorkerStatus status = new WorkerStatus ( ) ; status . setRunAt ( new Date ( ) ) ; status . setPaused ( isPaused ( ) ) ; return ObjectMapperFactory . get ( ) . writeValueAsString ( status ) ; } | Create and serialize a WorkerStatus for a pause event . | 65 | 12 |
148,786 | protected String createName ( ) { final StringBuilder buf = new StringBuilder ( 128 ) ; try { buf . append ( InetAddress . getLocalHost ( ) . getHostName ( ) ) . append ( COLON ) . append ( ManagementFactory . getRuntimeMXBean ( ) . getName ( ) . split ( "@" ) [ 0 ] ) // PID . append ( ' ' ) . append ( this . workerId ) . append ( COLON ) . append ( JAVA_DYNAMIC_QUEUES ) ; for ( final String queueName : this . queueNames ) { buf . append ( ' ' ) . append ( queueName ) ; } } catch ( UnknownHostException uhe ) { throw new RuntimeException ( uhe ) ; } return buf . toString ( ) ; } | Creates a unique name suitable for use with Resque . | 171 | 12 |
148,787 | @ Override public void join ( final long millis ) throws InterruptedException { for ( final Thread thread : this . threads ) { thread . join ( millis ) ; } } | Join to internal threads and wait millis time per thread or until all threads are finished if millis is 0 . | 38 | 23 |
148,788 | protected static void checkChannels ( final Iterable < String > channels ) { if ( channels == null ) { throw new IllegalArgumentException ( "channels must not be null" ) ; } for ( final String channel : channels ) { if ( channel == null || "" . equals ( channel ) ) { throw new IllegalArgumentException ( "channels' members must not be null: " + channels ) ; } } } | Verify that the given channels are all valid . | 89 | 10 |
148,789 | public static < V > V doWorkInPool ( final Pool < Jedis > pool , final PoolWork < Jedis , V > work ) throws Exception { if ( pool == null ) { throw new IllegalArgumentException ( "pool must not be null" ) ; } if ( work == null ) { throw new IllegalArgumentException ( "work must not be null" ) ; } final V result ; final Jedis poolResource = pool . getResource ( ) ; try { result = work . doWork ( poolResource ) ; } finally { poolResource . close ( ) ; } return result ; } | Perform the given work with a Jedis connection from the given pool . | 126 | 15 |
148,790 | public static < V > V doWorkInPoolNicely ( final Pool < Jedis > pool , final PoolWork < Jedis , V > work ) { final V result ; try { result = doWorkInPool ( pool , work ) ; } catch ( RuntimeException re ) { throw re ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } return result ; } | Perform the given work with a Jedis connection from the given pool . Wraps any thrown checked exceptions in a RuntimeException . | 82 | 26 |
148,791 | public static Pool < Jedis > createJedisPool ( final Config jesqueConfig , final GenericObjectPoolConfig poolConfig ) { if ( jesqueConfig == null ) { throw new IllegalArgumentException ( "jesqueConfig must not be null" ) ; } if ( poolConfig == null ) { throw new IllegalArgumentException ( "poolConfig must not be null" ) ; } if ( jesqueConfig . getMasterName ( ) != null && ! "" . equals ( jesqueConfig . getMasterName ( ) ) && jesqueConfig . getSentinels ( ) != null && jesqueConfig . getSentinels ( ) . size ( ) > 0 ) { return new JedisSentinelPool ( jesqueConfig . getMasterName ( ) , jesqueConfig . getSentinels ( ) , poolConfig , jesqueConfig . getTimeout ( ) , jesqueConfig . getPassword ( ) , jesqueConfig . getDatabase ( ) ) ; } else { return new JedisPool ( poolConfig , jesqueConfig . getHost ( ) , jesqueConfig . getPort ( ) , jesqueConfig . getTimeout ( ) , jesqueConfig . getPassword ( ) , jesqueConfig . getDatabase ( ) ) ; } } | A simple helper method that creates a pool of connections to Redis using the supplied configurations . | 263 | 18 |
148,792 | public static void doEnqueue ( final Jedis jedis , final String namespace , final String queue , final String jobJson ) { jedis . sadd ( JesqueUtils . createKey ( namespace , QUEUES ) , queue ) ; jedis . rpush ( JesqueUtils . createKey ( namespace , QUEUE , queue ) , jobJson ) ; } | Helper method that encapsulates the minimum logic for adding a job to a queue . | 83 | 16 |
148,793 | public static void doBatchEnqueue ( final Jedis jedis , final String namespace , final String queue , final List < String > jobJsons ) { Pipeline pipelined = jedis . pipelined ( ) ; pipelined . sadd ( JesqueUtils . createKey ( namespace , QUEUES ) , queue ) ; for ( String jobJson : jobJsons ) { pipelined . rpush ( JesqueUtils . createKey ( namespace , QUEUE , queue ) , jobJson ) ; } pipelined . sync ( ) ; } | Helper method that encapsulates the minimum logic for adding jobs to a queue . | 124 | 15 |
148,794 | public static void doPriorityEnqueue ( final Jedis jedis , final String namespace , final String queue , final String jobJson ) { jedis . sadd ( JesqueUtils . createKey ( namespace , QUEUES ) , queue ) ; jedis . lpush ( JesqueUtils . createKey ( namespace , QUEUE , queue ) , jobJson ) ; } | Helper method that encapsulates the minimum logic for adding a high priority job to a queue . | 85 | 18 |
148,795 | public static boolean doAcquireLock ( final Jedis jedis , final String namespace , final String lockName , final String lockHolder , final int timeout ) { final String key = JesqueUtils . createKey ( namespace , lockName ) ; // If lock already exists, extend it String existingLockHolder = jedis . get ( key ) ; if ( ( existingLockHolder != null ) && existingLockHolder . equals ( lockHolder ) ) { if ( jedis . expire ( key , timeout ) == 1 ) { existingLockHolder = jedis . get ( key ) ; if ( ( existingLockHolder != null ) && existingLockHolder . equals ( lockHolder ) ) { return true ; } } } // Check to see if the key exists and is expired for cleanup purposes if ( jedis . exists ( key ) && ( jedis . ttl ( key ) < 0 ) ) { // It is expired, but it may be in the process of being created, so // sleep and check again try { Thread . sleep ( 2000 ) ; } catch ( InterruptedException ie ) { } // Ignore interruptions if ( jedis . ttl ( key ) < 0 ) { existingLockHolder = jedis . get ( key ) ; // If it is our lock mark the time to live if ( ( existingLockHolder != null ) && existingLockHolder . equals ( lockHolder ) ) { if ( jedis . expire ( key , timeout ) == 1 ) { existingLockHolder = jedis . get ( key ) ; if ( ( existingLockHolder != null ) && existingLockHolder . equals ( lockHolder ) ) { return true ; } } } else { // The key is expired, whack it! jedis . del ( key ) ; } } else { // Someone else locked it while we were sleeping return false ; } } // Ignore the cleanup steps above, start with no assumptions test // creating the key if ( jedis . setnx ( key , lockHolder ) == 1 ) { // Created the lock, now set the expiration if ( jedis . expire ( key , timeout ) == 1 ) { // Set the timeout existingLockHolder = jedis . get ( key ) ; if ( ( existingLockHolder != null ) && existingLockHolder . equals ( lockHolder ) ) { return true ; } } else { // Don't know why it failed, but for now just report failed // acquisition return false ; } } // Failed to create the lock return false ; } | Helper method that encapsulates the logic to acquire a lock . | 549 | 12 |
148,796 | public ConfigBuilder withHost ( final String host ) { if ( host == null || "" . equals ( host ) ) { throw new IllegalArgumentException ( "host must not be null or empty: " + host ) ; } this . host = host ; return this ; } | Configs created by this ConfigBuilder will have the given Redis hostname . | 57 | 16 |
148,797 | public ConfigBuilder withSentinels ( final Set < String > sentinels ) { if ( sentinels == null || sentinels . size ( ) < 1 ) { throw new IllegalArgumentException ( "sentinels is null or empty: " + sentinels ) ; } this . sentinels = sentinels ; return this ; } | Configs created by this ConfigBuilder will use the given Redis sentinels . | 75 | 17 |
148,798 | public ConfigBuilder withMasterName ( final String masterName ) { if ( masterName == null || "" . equals ( masterName ) ) { throw new IllegalArgumentException ( "masterName is null or empty: " + masterName ) ; } this . masterName = masterName ; return this ; } | Configs created by this ConfigBuilder will use the given Redis master name . | 63 | 16 |
148,799 | public static boolean ensureJedisConnection ( final Jedis jedis ) { final boolean jedisOK = testJedisConnection ( jedis ) ; if ( ! jedisOK ) { try { jedis . quit ( ) ; } catch ( Exception e ) { } // Ignore try { jedis . disconnect ( ) ; } catch ( Exception e ) { } // Ignore jedis . connect ( ) ; } return jedisOK ; } | Ensure that the given connection is established . | 100 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.