idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
21,300 | public static void copyAll ( Resource base , Resource [ ] resources , File targetDir ) throws IOException { final URL baseUrl = base . getURL ( ) ; for ( Resource resource : resources ) { final InputStream input = resource . getInputStream ( ) ; final File target = new File ( targetDir , resource . getURL ( ) . toString ( ) . substring ( baseUrl . toString ( ) . length ( ) ) ) ; copy ( new BufferedInputStream ( input ) , new BufferedOutputStream ( Files . newOutputStream ( target . toPath ( ) ) ) ) ; } } | Copies all the resources for the given target directory . The base resource serves to calculate the relative path such that the directory structure is maintained . |
21,301 | public static void copy ( byte [ ] in , OutputStream out ) throws IOException { assert in != null : "No input byte array specified" ; assert out != null : "No output stream specified" ; try { out . write ( in ) ; } finally { try { out . close ( ) ; } catch ( IOException ex ) { } } } | Copy the contents of the given byte array to the given OutputStream . Closes the stream when done . |
21,302 | public static byte [ ] copyToByteArray ( InputStream in ) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream ( BUFFER_SIZE ) ; copy ( in , out ) ; return out . toByteArray ( ) ; } | Copy the contents of the given InputStream into a new byte array . Closes the stream when done . |
21,303 | public static int copy ( Reader in , Writer out ) throws IOException { assert in != null : "No input Reader specified" ; assert out != null : "No output Writer specified" ; try { int byteCount = 0 ; char [ ] buffer = new char [ BUFFER_SIZE ] ; int bytesRead = - 1 ; while ( ( bytesRead = in . read ( buffer ) ) != - 1 ) { out . write ( buffer , 0 , bytesRead ) ; byteCount += bytesRead ; } out . flush ( ) ; return byteCount ; } finally { try { in . close ( ) ; } catch ( IOException ex ) { } try { out . close ( ) ; } catch ( IOException ex ) { } } } | Copy the contents of the given Reader to the given Writer . Closes both when done . |
21,304 | public static void copy ( String in , Writer out ) throws IOException { assert in != null : "No input String specified" ; assert out != null : "No output Writer specified" ; try { out . write ( in ) ; } finally { try { out . close ( ) ; } catch ( IOException ex ) { } } } | Copy the contents of the given String to the given output Writer . Closes the write when done . |
21,305 | public static String copyToString ( Reader in ) throws IOException { StringWriter out = new StringWriter ( ) ; copy ( in , out ) ; return out . toString ( ) ; } | Copy the contents of the given Reader into a String . Closes the reader when done . |
21,306 | protected void pulsate ( ServiceInstance instance , HealthStatus status ) { Optional < String > opt = instance . getInstanceId ( ) ; if ( ! opt . isPresent ( ) ) { if ( instance . getMetadata ( ) . contains ( "instanceId" ) ) { opt = Optional . of ( instance . getMetadata ( ) . asMap ( ) . get ( "instanceId" ) ) ; } else { if ( LOG . isErrorEnabled ( ) ) { LOG . error ( "Cannot determine the instance ID. Are you sure you are running on AWS EC2?" ) ; } } } opt . ifPresent ( instanceId -> { if ( discoveryService != null && discoveryService . getHealthCheckCustomConfig ( ) != null ) { CustomHealthStatus customHealthStatus = CustomHealthStatus . UNHEALTHY ; if ( status . getOperational ( ) . isPresent ( ) ) { customHealthStatus = CustomHealthStatus . HEALTHY ; } UpdateInstanceCustomHealthStatusRequest updateInstanceCustomHealthStatusRequest = new UpdateInstanceCustomHealthStatusRequest ( ) . withInstanceId ( instanceId ) . withServiceId ( route53AutoRegistrationConfiguration . getAwsServiceId ( ) ) . withStatus ( customHealthStatus ) ; getDiscoveryClient ( ) . updateInstanceCustomHealthStatus ( updateInstanceCustomHealthStatusRequest ) ; } if ( status . getOperational ( ) . isPresent ( ) && ! status . getOperational ( ) . get ( ) ) { getDiscoveryClient ( ) . deregisterInstance ( new DeregisterInstanceRequest ( ) . withInstanceId ( instanceId ) . withServiceId ( route53AutoRegistrationConfiguration . getAwsServiceId ( ) ) ) ; LOG . info ( "Health status is non operational, instance id " + instanceId + " was de-registered from the discovery service." ) ; } } ) ; } | If custom health check is enabled this sends a heartbeat to it . In most cases aws monitoring works off polling an application s endpoint |
21,307 | protected void deregister ( ServiceInstance instance ) { if ( instance . getInstanceId ( ) . isPresent ( ) ) { DeregisterInstanceRequest deregisterInstanceRequest = new DeregisterInstanceRequest ( ) . withServiceId ( route53AutoRegistrationConfiguration . getAwsServiceId ( ) ) . withInstanceId ( instance . getInstanceId ( ) . get ( ) ) ; getDiscoveryClient ( ) . deregisterInstance ( deregisterInstanceRequest ) ; } } | shutdown instance if it fails health check can gracefully stop . |
21,308 | public void deleteService ( String serviceId ) { DeleteServiceRequest deleteServiceRequest = new DeleteServiceRequest ( ) . withId ( serviceId ) ; getDiscoveryClient ( ) . deleteService ( deleteServiceRequest ) ; } | These are convenience methods to help cleanup things like integration test data . |
21,309 | public void deleteNamespace ( String namespaceId ) { DeleteNamespaceRequest deleteNamespaceRequest = new DeleteNamespaceRequest ( ) . withId ( namespaceId ) ; getDiscoveryClient ( ) . deleteNamespace ( deleteNamespaceRequest ) ; } | these are convenience methods to help cleanup things like integration test data . |
21,310 | public String createService ( AWSServiceDiscovery serviceDiscovery , String name , String description , String namespaceId , Long ttl ) { if ( serviceDiscovery == null ) { serviceDiscovery = AWSServiceDiscoveryClient . builder ( ) . withClientConfiguration ( clientConfiguration . getClientConfiguration ( ) ) . build ( ) ; } DnsRecord dnsRecord = new DnsRecord ( ) . withType ( RecordType . A ) . withTTL ( ttl ) ; DnsConfig dnsConfig = new DnsConfig ( ) . withDnsRecords ( dnsRecord ) . withNamespaceId ( namespaceId ) . withRoutingPolicy ( RoutingPolicy . WEIGHTED ) ; CreateServiceRequest createServiceRequest = new CreateServiceRequest ( ) . withDnsConfig ( dnsConfig ) . withDescription ( description ) . withName ( name ) ; CreateServiceResult servicerResult = serviceDiscovery . createService ( createServiceRequest ) ; Service createdService = servicerResult . getService ( ) ; return createdService . getId ( ) ; } | Create service helper for integration tests . |
21,311 | private GetOperationResult checkOperation ( String operationId ) { String result = "" ; GetOperationResult opResult = null ; try { while ( ! result . equals ( "SUCCESS" ) && ! result . equals ( "FAIL" ) ) { opResult = getDiscoveryClient ( ) . getOperation ( new GetOperationRequest ( ) . withOperationId ( operationId ) ) ; result = opResult . getOperation ( ) . getStatus ( ) ; if ( opResult . getOperation ( ) . getStatus ( ) . equals ( "SUCCESS" ) ) { LOG . info ( "Successfully get operation id " + operationId ) ; return opResult ; } else { if ( opResult . getOperation ( ) . getStatus ( ) . equals ( "FAIL" ) ) { LOG . error ( "Error calling aws service for operationId:" + operationId + " error code:" + opResult . getOperation ( ) . getErrorCode ( ) + " error message:" + opResult . getOperation ( ) . getErrorMessage ( ) ) ; return opResult ; } } Thread . currentThread ( ) . sleep ( 5000 ) ; } } catch ( InterruptedException e ) { LOG . error ( "Error polling for aws response operation:" , e ) ; } return opResult ; } | Loop for checking of the call to aws is complete or not . This is the non - async version used for testing |
21,312 | public void setSerialization ( Map < SerializationFeature , Boolean > serialization ) { if ( CollectionUtils . isNotEmpty ( serialization ) ) { this . serialization = serialization ; } } | Sets the serialization features to use . |
21,313 | public void setDeserialization ( Map < DeserializationFeature , Boolean > deserialization ) { if ( CollectionUtils . isNotEmpty ( deserialization ) ) { this . deserialization = deserialization ; } } | Sets the deserialization features to use . |
21,314 | public void setMapper ( Map < MapperFeature , Boolean > mapper ) { if ( CollectionUtils . isNotEmpty ( mapper ) ) { this . mapper = mapper ; } } | Sets the object mapper features to use . |
21,315 | public void setParser ( Map < JsonParser . Feature , Boolean > parser ) { if ( CollectionUtils . isNotEmpty ( parser ) ) { this . parser = parser ; } } | Sets the parser features to use . |
21,316 | public void setGenerator ( Map < JsonGenerator . Feature , Boolean > generator ) { if ( CollectionUtils . isNotEmpty ( generator ) ) { this . generator = generator ; } } | Sets the generator features to use . |
21,317 | @ SuppressWarnings ( "unused" ) protected final void warnMissingProperty ( Class type , String method , String property ) { if ( LOG . isWarnEnabled ( ) ) { LOG . warn ( "Configuration property [{}] could not be set as the underlying method [{}] does not exist on builder [{}]. This usually indicates the configuration option was deprecated and has been removed by the builder implementation (potentially a third-party library)." , property , method , type ) ; } } | Allows printing warning messages produced by the compiler . |
21,318 | @ SuppressWarnings ( { "unchecked" , "unused" } ) protected final Object getProxiedBean ( BeanContext beanContext ) { DefaultBeanContext defaultBeanContext = ( DefaultBeanContext ) beanContext ; Optional < String > qualifier = getAnnotationMetadata ( ) . getAnnotationNameByStereotype ( javax . inject . Qualifier . class ) ; return defaultBeanContext . getProxyTargetBean ( getBeanType ( ) , ( Qualifier < T > ) qualifier . map ( q -> Qualifiers . byAnnotation ( getAnnotationMetadata ( ) , q ) ) . orElse ( null ) ) ; } | Resolves the proxied bean instance for this bean . |
21,319 | @ SuppressWarnings ( "unused" ) protected final AbstractBeanDefinition addPreDestroy ( Class declaringType , String method , Argument [ ] arguments , AnnotationMetadata annotationMetadata , boolean requiresReflection ) { return addInjectionPointInternal ( declaringType , method , arguments , annotationMetadata , requiresReflection , this . preDestroyMethods ) ; } | Adds a pre destroy method definition . |
21,320 | @ SuppressWarnings ( { "WeakerAccess" , "unused" } ) protected Object injectBean ( BeanResolutionContext resolutionContext , BeanContext context , Object bean ) { return bean ; } | The default implementation which provides no injection . To be overridden by compile time tooling . |
21,321 | @ SuppressWarnings ( { "WeakerAccess" , "unused" } ) protected Object injectAnother ( BeanResolutionContext resolutionContext , BeanContext context , Object bean ) { DefaultBeanContext defaultContext = ( DefaultBeanContext ) context ; if ( bean == null ) { throw new BeanInstantiationException ( resolutionContext , "Bean factory returned null" ) ; } return defaultContext . inject ( resolutionContext , this , bean ) ; } | Inject another bean for example one created via factory . |
21,322 | @ SuppressWarnings ( { "WeakerAccess" , "unused" , "unchecked" } ) protected Object postConstruct ( BeanResolutionContext resolutionContext , BeanContext context , Object bean ) { DefaultBeanContext defaultContext = ( DefaultBeanContext ) context ; Collection < BeanRegistration < BeanInitializedEventListener > > beanInitializedEventListeners = ( ( DefaultBeanContext ) context ) . beanInitializedEventListeners ; if ( CollectionUtils . isNotEmpty ( beanInitializedEventListeners ) ) { for ( BeanRegistration < BeanInitializedEventListener > registration : beanInitializedEventListeners ) { BeanDefinition < BeanInitializedEventListener > definition = registration . getBeanDefinition ( ) ; List < Argument < ? > > typeArguments = definition . getTypeArguments ( BeanInitializedEventListener . class ) ; if ( CollectionUtils . isEmpty ( typeArguments ) || typeArguments . get ( 0 ) . getType ( ) . isAssignableFrom ( getBeanType ( ) ) ) { BeanInitializedEventListener listener = registration . getBean ( ) ; bean = listener . onInitialized ( new BeanInitializingEvent ( context , this , bean ) ) ; if ( bean == null ) { throw new BeanInstantiationException ( resolutionContext , "Listener [" + listener + "] returned null from onInitialized event" ) ; } } } } for ( int i = 0 ; i < methodInjectionPoints . size ( ) ; i ++ ) { MethodInjectionPoint methodInjectionPoint = methodInjectionPoints . get ( i ) ; if ( methodInjectionPoint . isPostConstructMethod ( ) && methodInjectionPoint . requiresReflection ( ) ) { injectBeanMethod ( resolutionContext , defaultContext , i , bean ) ; } } if ( bean instanceof LifeCycle ) { bean = ( ( LifeCycle ) bean ) . start ( ) ; } return bean ; } | Default postConstruct hook that only invokes methods that require reflection . Generated subclasses should override to call methods that don t require reflection . |
21,323 | protected Object preDestroy ( BeanResolutionContext resolutionContext , BeanContext context , Object bean ) { DefaultBeanContext defaultContext = ( DefaultBeanContext ) context ; for ( int i = 0 ; i < methodInjectionPoints . size ( ) ; i ++ ) { MethodInjectionPoint methodInjectionPoint = methodInjectionPoints . get ( i ) ; if ( methodInjectionPoint . isPreDestroyMethod ( ) && methodInjectionPoint . requiresReflection ( ) ) { injectBeanMethod ( resolutionContext , defaultContext , i , bean ) ; } } if ( bean instanceof LifeCycle ) { bean = ( ( LifeCycle ) bean ) . stop ( ) ; } return bean ; } | Default preDestroy hook that only invokes methods that require reflection . Generated subclasses should override to call methods that don t require reflection . |
21,324 | @ SuppressWarnings ( "WeakerAccess" ) protected void injectBeanMethod ( BeanResolutionContext resolutionContext , DefaultBeanContext context , int methodIndex , Object bean ) { MethodInjectionPoint methodInjectionPoint = methodInjectionPoints . get ( methodIndex ) ; Argument [ ] methodArgumentTypes = methodInjectionPoint . getArguments ( ) ; Object [ ] methodArgs = new Object [ methodArgumentTypes . length ] ; for ( int i = 0 ; i < methodArgumentTypes . length ; i ++ ) { methodArgs [ i ] = getBeanForMethodArgument ( resolutionContext , context , methodIndex , i ) ; } try { methodInjectionPoint . invoke ( bean , methodArgs ) ; } catch ( Throwable e ) { throw new BeanInstantiationException ( this , e ) ; } } | Inject a bean method that requires reflection . |
21,325 | @ SuppressWarnings ( "unused" ) protected final void injectBeanField ( BeanResolutionContext resolutionContext , DefaultBeanContext context , int index , Object bean ) { FieldInjectionPoint fieldInjectionPoint = fieldInjectionPoints . get ( index ) ; boolean isInject = fieldInjectionPoint . getAnnotationMetadata ( ) . hasDeclaredAnnotation ( Inject . class ) ; try { Object value ; if ( isInject ) { value = getBeanForField ( resolutionContext , context , fieldInjectionPoint ) ; } else { value = getValueForField ( resolutionContext , context , index ) ; } if ( value != null ) { fieldInjectionPoint . set ( bean , value ) ; } } catch ( Throwable e ) { if ( e instanceof BeanContextException ) { throw ( BeanContextException ) e ; } else { throw new DependencyInjectionException ( resolutionContext , fieldInjectionPoint , "Error setting field value: " + e . getMessage ( ) , e ) ; } } } | Injects the value of a field of a bean that requires reflection . |
21,326 | @ SuppressWarnings ( "unused" ) protected final < T1 > Optional < T1 > getValueForPath ( BeanResolutionContext resolutionContext , BeanContext context , Argument < T1 > propertyType , String ... propertyPath ) { if ( context instanceof PropertyResolver ) { PropertyResolver propertyResolver = ( PropertyResolver ) context ; Class < ? > beanType = getBeanType ( ) ; String pathString = propertyPath . length > 1 ? String . join ( "." , propertyPath ) : propertyPath [ 0 ] ; String valString = resolvePropertyPath ( resolutionContext , pathString ) ; return propertyResolver . getProperty ( valString , ConversionContext . of ( propertyType ) ) ; } return Optional . empty ( ) ; } | Resolve a value for the given field of the given type and path . |
21,327 | protected final boolean containsValueForField ( BeanResolutionContext resolutionContext , BeanContext context , int fieldIndex ) { if ( context instanceof ApplicationContext ) { FieldInjectionPoint injectionPoint = fieldInjectionPoints . get ( fieldIndex ) ; final AnnotationMetadata annotationMetadata = injectionPoint . getAnnotationMetadata ( ) ; String valueAnnVal = annotationMetadata . getValue ( Value . class , String . class ) . orElse ( null ) ; String valString = resolvePropertyValueName ( resolutionContext , injectionPoint , valueAnnVal , annotationMetadata ) ; ApplicationContext applicationContext = ( ApplicationContext ) context ; Class fieldType = injectionPoint . getType ( ) ; boolean isConfigProps = fieldType . isAnnotationPresent ( ConfigurationProperties . class ) ; boolean result = isConfigProps || Map . class . isAssignableFrom ( fieldType ) ? applicationContext . containsProperties ( valString ) : applicationContext . containsProperty ( valString ) ; if ( ! result && isConfigurationProperties ( ) ) { String cliOption = resolveCliOption ( injectionPoint . getName ( ) ) ; if ( cliOption != null ) { return applicationContext . containsProperty ( cliOption ) ; } } return result ; } return false ; } | Obtains a value for the given field argument . |
21,328 | @ SuppressWarnings ( "MagicNumber" ) protected Resource [ ] findAllClassPathResources ( String location ) throws IOException { String path = location ; if ( path . startsWith ( "/" ) ) { path = path . substring ( 1 ) ; } Enumeration < URL > resourceUrls = getClassLoader ( ) . getResources ( path ) ; Set < Resource > result = new LinkedHashSet < Resource > ( 16 ) ; while ( resourceUrls . hasMoreElements ( ) ) { URL url = resourceUrls . nextElement ( ) ; result . add ( convertClassLoaderURL ( url ) ) ; } return result . toArray ( new Resource [ 0 ] ) ; } | Find all class location resources with the given location via the ClassLoader . |
21,329 | @ SuppressWarnings ( "MagicNumber" ) protected Set < Resource > doFindPathMatchingJarResources ( Resource rootDirResource , String subPattern ) throws IOException { URLConnection con = rootDirResource . getURL ( ) . openConnection ( ) ; JarFile jarFile ; String jarFileUrl ; String rootEntryPath ; boolean newJarFile = false ; if ( con instanceof JarURLConnection ) { JarURLConnection jarCon = ( JarURLConnection ) con ; ResourceUtils . useCachesIfNecessary ( jarCon ) ; jarFile = jarCon . getJarFile ( ) ; jarFileUrl = jarCon . getJarFileURL ( ) . toExternalForm ( ) ; JarEntry jarEntry = jarCon . getJarEntry ( ) ; rootEntryPath = ( jarEntry != null ? jarEntry . getName ( ) : "" ) ; } else { String urlFile = rootDirResource . getURL ( ) . getFile ( ) ; int separatorIndex = urlFile . indexOf ( ResourceUtils . JAR_URL_SEPARATOR ) ; if ( separatorIndex != - 1 ) { jarFileUrl = urlFile . substring ( 0 , separatorIndex ) ; rootEntryPath = urlFile . substring ( separatorIndex + ResourceUtils . JAR_URL_SEPARATOR . length ( ) ) ; jarFile = getJarFile ( jarFileUrl ) ; } else { jarFile = new JarFile ( urlFile ) ; jarFileUrl = urlFile ; rootEntryPath = "" ; } newJarFile = true ; } try { if ( ! "" . equals ( rootEntryPath ) && ! rootEntryPath . endsWith ( "/" ) ) { rootEntryPath = rootEntryPath + "/" ; } Set < Resource > result = new LinkedHashSet < Resource > ( 8 ) ; for ( Enumeration < JarEntry > entries = jarFile . entries ( ) ; entries . hasMoreElements ( ) ; ) { JarEntry entry = entries . nextElement ( ) ; String entryPath = entry . getName ( ) ; if ( entryPath . startsWith ( rootEntryPath ) ) { String relativePath = entryPath . substring ( rootEntryPath . length ( ) ) ; if ( getPathMatcher ( ) . match ( subPattern , relativePath ) ) { result . add ( rootDirResource . createRelative ( relativePath ) ) ; } } } return result ; } finally { if ( newJarFile ) { jarFile . close ( ) ; } } } | Find all resources in jar files that match the given location pattern via the Ant - style PathMatcher . |
21,330 | @ SuppressWarnings ( "MagicNumber" ) protected Set < File > retrieveMatchingFiles ( File rootDir , String pattern ) throws IOException { if ( ! rootDir . exists ( ) ) { return Collections . emptySet ( ) ; } if ( ! rootDir . isDirectory ( ) ) { return Collections . emptySet ( ) ; } if ( ! rootDir . canRead ( ) ) { return Collections . emptySet ( ) ; } String fullPattern = rootDir . getAbsolutePath ( ) . replace ( File . separator , "/" ) ; if ( ! pattern . startsWith ( "/" ) ) { fullPattern += "/" ; } fullPattern = fullPattern + pattern . replace ( File . separator , "/" ) ; Set < File > result = new LinkedHashSet < File > ( 8 ) ; doRetrieveMatchingFiles ( fullPattern , rootDir , result ) ; return result ; } | Retrieve files that match the given path pattern checking the given directory and its subdirectories . |
21,331 | protected void doRetrieveMatchingFiles ( String fullPattern , File dir , Set < File > result ) throws IOException { File [ ] dirContents = dir . listFiles ( ) ; if ( dirContents == null ) { return ; } for ( File content : dirContents ) { String currPath = content . getAbsolutePath ( ) . replace ( File . separator , "/" ) ; if ( content . isDirectory ( ) && getPathMatcher ( ) . matchStart ( fullPattern , currPath + "/" ) ) { if ( content . canRead ( ) ) { doRetrieveMatchingFiles ( fullPattern , content , result ) ; } } if ( getPathMatcher ( ) . match ( fullPattern , currPath ) ) { result . add ( content ) ; } } } | Recursively retrieve files that match the given pattern adding them to the given result list . |
21,332 | public Cookie put ( CharSequence name , Cookie cookie ) { return cookies . put ( name , cookie ) ; } | Put a new cookie . |
21,333 | public boolean canRetry ( Throwable exception ) { if ( exception == null ) { return false ; } Class < ? extends Throwable > exceptionClass = exception . getClass ( ) ; if ( hasIncludes && ! includes . contains ( exceptionClass ) ) { return false ; } else if ( hasExcludes && excludes . contains ( exceptionClass ) ) { return false ; } else { return this . attemptNumber . incrementAndGet ( ) < ( maxAttempts + 1 ) && ( ( maxDelay == null ) || overallDelay . get ( ) < maxDelay . toMillis ( ) ) ; } } | Should a retry attempt occur . |
21,334 | public static SQLMethodInvokeExpr makeBinaryMethodField ( SQLBinaryOpExpr expr , String alias , boolean first ) throws SqlParseException { List < SQLExpr > params = new ArrayList < > ( ) ; String scriptFieldAlias ; if ( first && ( alias == null || alias . equals ( "" ) ) ) { scriptFieldAlias = "field_" + SQLFunctions . random ( ) ; } else { scriptFieldAlias = alias ; } params . add ( new SQLCharExpr ( scriptFieldAlias ) ) ; switch ( expr . getOperator ( ) ) { case Add : return convertBinaryOperatorToMethod ( "add" , expr ) ; case Multiply : return convertBinaryOperatorToMethod ( "multiply" , expr ) ; case Divide : return convertBinaryOperatorToMethod ( "divide" , expr ) ; case Modulus : return convertBinaryOperatorToMethod ( "modulus" , expr ) ; case Subtract : return convertBinaryOperatorToMethod ( "subtract" , expr ) ; default : throw new SqlParseException ( expr . getOperator ( ) . getName ( ) + " is not support" ) ; } } | binary method can nested |
21,335 | public static QueryAction create ( Client client , String sql ) throws SqlParseException , SQLFeatureNotSupportedException { sql = sql . replaceAll ( "\n" , " " ) ; String firstWord = sql . substring ( 0 , sql . indexOf ( ' ' ) ) ; switch ( firstWord . toUpperCase ( ) ) { case "SELECT" : SQLQueryExpr sqlExpr = ( SQLQueryExpr ) toSqlExpr ( sql ) ; if ( isMulti ( sqlExpr ) ) { MultiQuerySelect multiSelect = new SqlParser ( ) . parseMultiSelect ( ( SQLUnionQuery ) sqlExpr . getSubQuery ( ) . getQuery ( ) ) ; handleSubQueries ( client , multiSelect . getFirstSelect ( ) ) ; handleSubQueries ( client , multiSelect . getSecondSelect ( ) ) ; return new MultiQueryAction ( client , multiSelect ) ; } else if ( isJoin ( sqlExpr , sql ) ) { JoinSelect joinSelect = new SqlParser ( ) . parseJoinSelect ( sqlExpr ) ; handleSubQueries ( client , joinSelect . getFirstTable ( ) ) ; handleSubQueries ( client , joinSelect . getSecondTable ( ) ) ; return ESJoinQueryActionFactory . createJoinAction ( client , joinSelect ) ; } else { Select select = new SqlParser ( ) . parseSelect ( sqlExpr ) ; handleSubQueries ( client , select ) ; return handleSelect ( client , select ) ; } case "DELETE" : SQLStatementParser parser = createSqlStatementParser ( sql ) ; SQLDeleteStatement deleteStatement = parser . parseDeleteStatement ( ) ; Delete delete = new SqlParser ( ) . parseDelete ( deleteStatement ) ; return new DeleteQueryAction ( client , delete ) ; case "SHOW" : return new ShowQueryAction ( client , sql ) ; default : throw new SQLFeatureNotSupportedException ( String . format ( "Unsupported query: %s" , sql ) ) ; } } | Create the compatible Query object based on the SQL query . |
21,336 | public static String hitsAsStringResult ( SearchHits results , MetaSearchResult metaResults ) throws IOException { if ( results == null ) return null ; Object [ ] searchHits ; searchHits = new Object [ ( int ) results . getTotalHits ( ) ] ; int i = 0 ; for ( SearchHit hit : results ) { HashMap < String , Object > value = new HashMap < > ( ) ; value . put ( "_id" , hit . getId ( ) ) ; value . put ( "_type" , hit . getType ( ) ) ; value . put ( "_score" , hit . getScore ( ) ) ; value . put ( "_source" , hit . getSourceAsMap ( ) ) ; searchHits [ i ] = value ; i ++ ; } HashMap < String , Object > hits = new HashMap < > ( ) ; hits . put ( "total" , results . getTotalHits ( ) ) ; hits . put ( "max_score" , results . getMaxScore ( ) ) ; hits . put ( "hits" , searchHits ) ; XContentBuilder builder = XContentFactory . contentBuilder ( XContentType . JSON ) . prettyPrint ( ) ; builder . startObject ( ) ; builder . field ( "took" , metaResults . getTookImMilli ( ) ) ; builder . field ( "timed_out" , metaResults . isTimedOut ( ) ) ; builder . field ( "_shards" , ImmutableMap . of ( "total" , metaResults . getTotalNumOfShards ( ) , "successful" , metaResults . getSuccessfulShards ( ) , "failed" , metaResults . getFailedShards ( ) ) ) ; builder . field ( "hits" , hits ) ; builder . endObject ( ) ; return BytesReference . bytes ( builder ) . utf8ToString ( ) ; } | use our deserializer instead of results toXcontent because the source field is differnet from sourceAsMap . |
21,337 | public void execute ( ) throws Exception { ActionRequest request = requestBuilder . request ( ) ; if ( requestBuilder instanceof JoinRequestBuilder ) { executeJoinRequestAndSendResponse ( ) ; } else if ( request instanceof SearchRequest ) { client . search ( ( SearchRequest ) request , new RestStatusToXContentListener < SearchResponse > ( channel ) ) ; } else if ( requestBuilder instanceof SqlElasticDeleteByQueryRequestBuilder ) { throw new UnsupportedOperationException ( "currently not support delete on elastic 2.0.0" ) ; } else if ( request instanceof GetIndexRequest ) { this . requestBuilder . getBuilder ( ) . execute ( new GetIndexRequestRestListener ( channel , ( GetIndexRequest ) request ) ) ; } else { throw new Exception ( String . format ( "Unsupported ActionRequest provided: %s" , request . getClass ( ) . getName ( ) ) ) ; } } | Execute the ActionRequest and returns the REST response using the channel . |
21,338 | public String [ ] getIndexArr ( ) { String [ ] indexArr = new String [ this . from . size ( ) ] ; for ( int i = 0 ; i < indexArr . length ; i ++ ) { indexArr [ i ] = this . from . get ( i ) . getIndex ( ) ; } return indexArr ; } | Get the indexes the query refer to . |
21,339 | public String [ ] getTypeArr ( ) { List < String > list = new ArrayList < > ( ) ; From index = null ; for ( int i = 0 ; i < from . size ( ) ; i ++ ) { index = from . get ( i ) ; if ( index . getType ( ) != null && index . getType ( ) . trim ( ) . length ( ) > 0 ) { list . add ( index . getType ( ) ) ; } } if ( list . size ( ) == 0 ) { return null ; } return list . toArray ( new String [ list . size ( ) ] ) ; } | Get the types the query refer to . |
21,340 | private void initFromSPIServiceLoader ( ) { String property = System . getProperty ( "druid.load.spifilter.skip" ) ; if ( property != null ) { return ; } ServiceLoader < Filter > druidAutoFilterLoader = ServiceLoader . load ( Filter . class ) ; for ( Filter autoFilter : druidAutoFilterLoader ) { AutoLoad autoLoad = autoFilter . getClass ( ) . getAnnotation ( AutoLoad . class ) ; if ( autoLoad != null && autoLoad . value ( ) ) { if ( LOG . isInfoEnabled ( ) ) { LOG . info ( "load filter from spi :" + autoFilter . getClass ( ) . getName ( ) ) ; } addFilter ( autoFilter ) ; } } } | load filters from SPI ServiceLoader |
21,341 | private boolean explanSpecialCondWithBothSidesAreLiterals ( SQLBinaryOpExpr bExpr , Where where ) throws SqlParseException { if ( ( bExpr . getLeft ( ) instanceof SQLNumericLiteralExpr || bExpr . getLeft ( ) instanceof SQLCharExpr ) && ( bExpr . getRight ( ) instanceof SQLNumericLiteralExpr || bExpr . getRight ( ) instanceof SQLCharExpr ) ) { SQLMethodInvokeExpr sqlMethodInvokeExpr = new SQLMethodInvokeExpr ( "script" , null ) ; String operator = bExpr . getOperator ( ) . getName ( ) ; if ( operator . equals ( "=" ) ) { operator = "==" ; } sqlMethodInvokeExpr . addParameter ( new SQLCharExpr ( Util . expr2Object ( bExpr . getLeft ( ) , "'" ) + " " + operator + " " + Util . expr2Object ( bExpr . getRight ( ) , "'" ) ) ) ; explanCond ( "AND" , sqlMethodInvokeExpr , where ) ; return true ; } return false ; } | some where conditions eg . 1 = 1 or 3 > 2 or a = b |
21,342 | private boolean explanSpecialCondWithBothSidesAreProperty ( SQLBinaryOpExpr bExpr , Where where ) throws SqlParseException { if ( ( bExpr . getLeft ( ) instanceof SQLPropertyExpr || bExpr . getLeft ( ) instanceof SQLIdentifierExpr ) && ( bExpr . getRight ( ) instanceof SQLPropertyExpr || bExpr . getRight ( ) instanceof SQLIdentifierExpr ) && Sets . newHashSet ( "=" , "<" , ">" , ">=" , "<=" ) . contains ( bExpr . getOperator ( ) . getName ( ) ) && ! Util . isFromJoinOrUnionTable ( bExpr ) ) { SQLMethodInvokeExpr sqlMethodInvokeExpr = new SQLMethodInvokeExpr ( "script" , null ) ; String operator = bExpr . getOperator ( ) . getName ( ) ; if ( operator . equals ( "=" ) ) { operator = "==" ; } String leftProperty = Util . expr2Object ( bExpr . getLeft ( ) ) . toString ( ) ; String rightProperty = Util . expr2Object ( bExpr . getRight ( ) ) . toString ( ) ; if ( leftProperty . split ( "\\." ) . length > 1 ) { leftProperty = leftProperty . substring ( leftProperty . split ( "\\." ) [ 0 ] . length ( ) + 1 ) ; } if ( rightProperty . split ( "\\." ) . length > 1 ) { rightProperty = rightProperty . substring ( rightProperty . split ( "\\." ) [ 0 ] . length ( ) + 1 ) ; } sqlMethodInvokeExpr . addParameter ( new SQLCharExpr ( "doc['" + leftProperty + "'].value " + operator + " doc['" + rightProperty + "'].value" ) ) ; explanCond ( "AND" , sqlMethodInvokeExpr , where ) ; return true ; } return false ; } | some where conditions eg . field1 = field2 or field1 > field2 |
21,343 | private void setIndicesAndTypes ( ) { request . setIndices ( query . getIndexArr ( ) ) ; String [ ] typeArr = query . getTypeArr ( ) ; if ( typeArr != null ) { request . setTypes ( typeArr ) ; } } | Set indices and types to the search request . |
21,344 | private void setWhere ( Where where ) throws SqlParseException { if ( where != null ) { BoolQueryBuilder boolQuery = QueryMaker . explan ( where , this . select . isQuery ) ; request . setQuery ( boolQuery ) ; } } | Create filters or queries based on the Where clause . |
21,345 | private void setSorts ( List < Order > orderBys ) { for ( Order order : orderBys ) { if ( order . getNestedPath ( ) != null ) { request . addSort ( SortBuilders . fieldSort ( order . getName ( ) ) . order ( SortOrder . valueOf ( order . getType ( ) ) ) . setNestedSort ( new NestedSortBuilder ( order . getNestedPath ( ) ) ) ) ; } else if ( order . getName ( ) . contains ( "script(" ) ) { String scriptStr = order . getName ( ) . substring ( "script(" . length ( ) , order . getName ( ) . length ( ) - 1 ) ; Script script = new Script ( scriptStr ) ; ScriptSortBuilder scriptSortBuilder = SortBuilders . scriptSort ( script , order . getScriptSortType ( ) ) ; scriptSortBuilder = scriptSortBuilder . order ( SortOrder . valueOf ( order . getType ( ) ) ) ; request . addSort ( scriptSortBuilder ) ; } else { request . addSort ( order . getName ( ) , SortOrder . valueOf ( order . getType ( ) ) ) ; } } } | Add sorts to the elasticsearch query based on the ORDER BY clause . |
21,346 | private void setLimit ( int from , int size ) { request . setFrom ( from ) ; if ( size > - 1 ) { request . setSize ( size ) ; } } | Add from and size to the ES query based on the LIMIT clause |
21,347 | public QueryAction explain ( String sql ) throws SqlParseException , SQLFeatureNotSupportedException { return ESActionFactory . create ( client , sql ) ; } | Prepare action And transform sql into ES ActionRequest |
21,348 | private ValuesSourceAggregationBuilder makeCountAgg ( MethodField field ) { if ( "DISTINCT" . equals ( field . getOption ( ) ) ) { if ( field . getParams ( ) . size ( ) == 1 ) { return AggregationBuilders . cardinality ( field . getAlias ( ) ) . field ( field . getParams ( ) . get ( 0 ) . value . toString ( ) ) ; } else { Integer precision_threshold = ( Integer ) ( field . getParams ( ) . get ( 1 ) . value ) ; return AggregationBuilders . cardinality ( field . getAlias ( ) ) . precisionThreshold ( precision_threshold ) . field ( field . getParams ( ) . get ( 0 ) . value . toString ( ) ) ; } } String fieldName = field . getParams ( ) . get ( 0 ) . value . toString ( ) ; if ( "*" . equals ( fieldName ) ) { KVValue kvValue = new KVValue ( null , "_index" ) ; field . getParams ( ) . set ( 0 , kvValue ) ; return AggregationBuilders . count ( field . getAlias ( ) ) . field ( kvValue . toString ( ) ) ; } else { return AggregationBuilders . count ( field . getAlias ( ) ) . field ( fieldName ) ; } } | Create count aggregation . |
21,349 | private void setIndicesAndTypes ( ) { DeleteByQueryRequest innerRequest = request . request ( ) ; innerRequest . indices ( query . getIndexArr ( ) ) ; String [ ] typeArr = query . getTypeArr ( ) ; if ( typeArr != null ) { innerRequest . getSearchRequest ( ) . types ( typeArr ) ; } } | Set indices and types to the delete by query request . |
21,350 | private MinusOneFieldAndOptimizationResult runWithScrollingAndAddFilter ( String firstFieldName , String secondFieldName ) throws SqlParseException { SearchResponse scrollResp = ElasticUtils . scrollOneTimeWithHits ( this . client , this . builder . getFirstSearchRequest ( ) , builder . getOriginalSelect ( true ) , this . maxDocsToFetchOnEachScrollShard ) ; Set < Object > results = new HashSet < > ( ) ; int currentNumOfResults = 0 ; SearchHit [ ] hits = scrollResp . getHits ( ) . getHits ( ) ; SearchHit someHit = null ; if ( hits . length != 0 ) { someHit = hits [ 0 ] ; } int totalDocsFetchedFromFirstTable = 0 ; int totalDocsFetchedFromSecondTable = 0 ; Where originalWhereSecondTable = this . builder . getOriginalSelect ( false ) . getWhere ( ) ; while ( hits . length != 0 ) { totalDocsFetchedFromFirstTable += hits . length ; Set < Object > currentSetFromResults = new HashSet < > ( ) ; fillSetFromHits ( firstFieldName , hits , currentSetFromResults ) ; Select secondQuerySelect = this . builder . getOriginalSelect ( false ) ; Where where = createWhereWithOrigianlAndTermsFilter ( secondFieldName , originalWhereSecondTable , currentSetFromResults ) ; secondQuerySelect . setWhere ( where ) ; DefaultQueryAction queryAction = new DefaultQueryAction ( this . client , secondQuerySelect ) ; queryAction . explain ( ) ; if ( totalDocsFetchedFromSecondTable > this . maxDocsToFetchOnSecondTable ) { break ; } SearchResponse responseForSecondTable = ElasticUtils . scrollOneTimeWithHits ( this . client , queryAction . getRequestBuilder ( ) , secondQuerySelect , this . maxDocsToFetchOnEachScrollShard ) ; SearchHits secondQuerySearchHits = responseForSecondTable . getHits ( ) ; SearchHit [ ] secondQueryHits = secondQuerySearchHits . getHits ( ) ; while ( secondQueryHits . length > 0 ) { totalDocsFetchedFromSecondTable += secondQueryHits . length ; removeValuesFromSetAccordingToHits ( secondFieldName , currentSetFromResults , secondQueryHits ) ; if ( totalDocsFetchedFromSecondTable > this . maxDocsToFetchOnSecondTable ) { break ; } responseForSecondTable = client . prepareSearchScroll ( responseForSecondTable . getScrollId ( ) ) . setScroll ( new TimeValue ( 600000 ) ) . execute ( ) . actionGet ( ) ; secondQueryHits = responseForSecondTable . getHits ( ) . getHits ( ) ; } results . addAll ( currentSetFromResults ) ; if ( totalDocsFetchedFromFirstTable > this . maxDocsToFetchOnFirstTable ) { System . out . println ( "too many results for first table, stoping at:" + totalDocsFetchedFromFirstTable ) ; break ; } scrollResp = client . prepareSearchScroll ( scrollResp . getScrollId ( ) ) . setScroll ( new TimeValue ( 600000 ) ) . execute ( ) . actionGet ( ) ; hits = scrollResp . getHits ( ) . getHits ( ) ; } return new MinusOneFieldAndOptimizationResult ( results , someHit ) ; } | 1 . 1 . 2 add all results left from miniset to bigset |
21,351 | public static String convertClassNameToUnderscoreName ( String name ) { StringBuilder result = new StringBuilder ( ) ; if ( name != null ) { int len = name . length ( ) ; if ( len > 0 ) { result . append ( name . charAt ( 0 ) ) ; for ( int i = 1 ; i < len ; i ++ ) { if ( true == Character . isUpperCase ( name . charAt ( i ) ) ) { result . append ( '_' ) ; } result . append ( name . charAt ( i ) ) ; } } } return result . toString ( ) . toUpperCase ( ) ; } | Convert a class name with underscores to the corresponding column name using _ . A name like CustomerNumber class name would match a CUSTOMER_NUMBER . |
21,352 | public static String convertUnderscoreNameToClassName ( String name ) { StringBuffer result = new StringBuffer ( ) ; boolean nextIsUpper = false ; if ( name != null ) { int len = name . length ( ) ; if ( len > 0 ) { String s = String . valueOf ( name . charAt ( 0 ) ) ; result . append ( s . toUpperCase ( ) ) ; for ( int i = 1 ; i < len ; i ++ ) { s = String . valueOf ( name . charAt ( i ) ) ; if ( "_" . equals ( s ) ) { nextIsUpper = true ; } else { if ( nextIsUpper ) { result . append ( s . toUpperCase ( ) ) ; nextIsUpper = false ; } else { result . append ( s . toLowerCase ( ) ) ; } } } } } return result . toString ( ) ; } | Convert a column name with underscores to the corresponding class name using camel case . A name like customer_number would match a CustomerNumber class name . |
21,353 | public Object convert ( Class type , Object value ) { if ( value == null ) { if ( useDefault ) { return ( defaultValue ) ; } else { throw new ConversionException ( "No value specified" ) ; } } if ( value instanceof java . sql . Date && java . sql . Date . class . equals ( type ) ) { return value ; } else if ( value instanceof java . sql . Time && java . sql . Time . class . equals ( type ) ) { return value ; } else if ( value instanceof java . sql . Timestamp && java . sql . Timestamp . class . equals ( type ) ) { return value ; } else { try { if ( java . sql . Date . class . equals ( type ) ) { return new java . sql . Date ( convertTimestamp2TimeMillis ( value . toString ( ) ) ) ; } else if ( java . sql . Time . class . equals ( type ) ) { return new java . sql . Time ( convertTimestamp2TimeMillis ( value . toString ( ) ) ) ; } else if ( java . sql . Timestamp . class . equals ( type ) ) { return new java . sql . Timestamp ( convertTimestamp2TimeMillis ( value . toString ( ) ) ) ; } else { return new Timestamp ( convertTimestamp2TimeMillis ( value . toString ( ) ) ) ; } } catch ( Exception e ) { throw new ConversionException ( "Value format invalid: " + e . getMessage ( ) , e ) ; } } } | Convert the specified input object into an output object of the specified type . |
21,354 | private static void makeAllColumnsPrimaryKeysIfNoPrimaryKeysFound ( Table table ) { if ( ( table != null ) && ( table . getPrimaryKeyColumns ( ) != null ) && ( table . getPrimaryKeyColumns ( ) . length == 0 ) ) { Column [ ] allCoumns = table . getColumns ( ) ; for ( Column column : allCoumns ) { column . setPrimaryKey ( true ) ; } } } | Treat tables with no primary keys as a table with all primary keys . |
21,355 | public static long sizeof ( final Object obj ) { if ( null == obj || isSharedFlyweight ( obj ) ) { return 0 ; } final IdentityHashMap visited = new IdentityHashMap ( 80000 ) ; try { return computeSizeof ( obj , visited , CLASS_METADATA_CACHE ) ; } catch ( RuntimeException re ) { return - 1 ; } catch ( NoClassDefFoundError ncdfe ) { return - 1 ; } } | Estimates the full size of the object graph rooted at obj . Duplicate data instances are correctly accounted for . The implementation is not recursive . |
21,356 | public static long sizedelta ( final Object base , final Object obj ) { if ( null == obj || isSharedFlyweight ( obj ) ) { return 0 ; } if ( null == base ) { throw new IllegalArgumentException ( "null input: base" ) ; } final IdentityHashMap visited = new IdentityHashMap ( 40000 ) ; try { computeSizeof ( base , visited , CLASS_METADATA_CACHE ) ; return visited . containsKey ( obj ) ? 0 : computeSizeof ( obj , visited , CLASS_METADATA_CACHE ) ; } catch ( RuntimeException re ) { return - 1 ; } catch ( NoClassDefFoundError ncdfe ) { return - 1 ; } } | Estimates the full size of the object graph rooted at obj by pre - populating the visited set with the object graph rooted at base . The net effect is to compute the size of obj by summing over all instance data contained in obj but not in base . |
21,357 | protected boolean isPackableWith ( Object value , int choose ) { if ( value == null ) { return false ; } if ( choose == CHOOSE_EXTENSION ) { if ( value . equals ( getDefaultFileExtension ( ) ) ) { return true ; } } else if ( choose == CHOOSE_NAME ) { if ( value . equals ( getName ( ) ) ) { return true ; } } return false ; } | String Chooser . |
21,358 | public static PackableObject identifyByHeader ( File file , List packables ) throws IOException { FileInputStream fis = null ; try { fis = new FileInputStream ( file ) ; byte [ ] headerBytes = new byte [ 20 ] ; fis . read ( headerBytes , 0 , 20 ) ; Iterator iter = packables . iterator ( ) ; while ( iter . hasNext ( ) ) { PackableObject p = ( PackableObject ) iter . next ( ) ; byte [ ] fieldHeader = p . getHeader ( ) ; if ( fieldHeader != null ) { if ( compareByteArrays ( headerBytes , fieldHeader ) ) { return p ; } } } String name = file . getName ( ) ; String extension = null ; String [ ] s = name . split ( "\\." ) ; if ( s . length > 1 ) { extension = s [ s . length - 1 ] ; } Iterator it = packables . iterator ( ) ; while ( it . hasNext ( ) ) { PackableObject p = ( PackableObject ) it . next ( ) ; if ( p . isPackableWith ( extension , PackableObject . CHOOSE_EXTENSION ) ) { return p ; } } return null ; } finally { IOUtils . closeQuietly ( fis ) ; } } | Compares a file to a list of packables and identifies an object by header . If no matching header is found it identifies the file by file extension . If identification was not successfull null is returned |
21,359 | public static boolean isNumeric ( int sqlType ) { return ( Types . BIT == sqlType ) || ( Types . BIGINT == sqlType ) || ( Types . DECIMAL == sqlType ) || ( Types . DOUBLE == sqlType ) || ( Types . FLOAT == sqlType ) || ( Types . INTEGER == sqlType ) || ( Types . NUMERIC == sqlType ) || ( Types . REAL == sqlType ) || ( Types . SMALLINT == sqlType ) || ( Types . TINYINT == sqlType ) ; } | Check whether the given SQL type is numeric . |
21,360 | protected AuthenticationInfo customInfoIfNecessay ( AuthenticationInfo authenticationInfo ) { if ( StringUtils . isNotBlank ( customUser ) ) { authenticationInfo . setUsername ( customUser ) ; } if ( StringUtils . isNotBlank ( customPasswd ) ) { authenticationInfo . setPassword ( customPasswd ) ; } if ( StringUtils . isNotBlank ( customSchema ) ) { authenticationInfo . setDefaultDatabaseName ( customSchema ) ; } return authenticationInfo ; } | override custom field |
21,361 | public void createPersistent ( String path , Object data , boolean createParents ) throws ZkInterruptedException , IllegalArgumentException , ZkException , RuntimeException { try { create ( path , data , CreateMode . PERSISTENT ) ; } catch ( ZkNodeExistsException e ) { if ( ! createParents ) { throw e ; } } catch ( ZkNoNodeException e ) { if ( ! createParents ) { throw e ; } String parentDir = path . substring ( 0 , path . lastIndexOf ( '/' ) ) ; createPersistent ( parentDir , createParents ) ; createPersistent ( path , data , createParents ) ; } } | Create a persistent Sequential node . |
21,362 | public String createPersistentSequential ( String path , Object data ) throws ZkInterruptedException , IllegalArgumentException , ZkException , RuntimeException { return create ( path , data , CreateMode . PERSISTENT_SEQUENTIAL ) ; } | Create a persistent sequental node . |
21,363 | public void createEphemeral ( final String path ) throws ZkInterruptedException , IllegalArgumentException , ZkException , RuntimeException { create ( path , null , CreateMode . EPHEMERAL ) ; } | Create an ephemeral node . |
21,364 | public String createEphemeralSequential ( final String path , final Object data ) throws ZkInterruptedException , IllegalArgumentException , ZkException , RuntimeException { return create ( path , data , CreateMode . EPHEMERAL_SEQUENTIAL ) ; } | Create an ephemeral sequential node . |
21,365 | public List < String > watchForChilds ( final String path ) { if ( _zookeeperEventThread != null && Thread . currentThread ( ) == _zookeeperEventThread ) { throw new IllegalArgumentException ( "Must not be done in the zookeeper event thread." ) ; } return retryUntilConnected ( new Callable < List < String > > ( ) { public List < String > call ( ) throws Exception { exists ( path , true ) ; try { return getChildren ( path , true ) ; } catch ( ZkNoNodeException e ) { } return null ; } } ) ; } | Installs a child watch for the given path . |
21,366 | public void close ( ) throws ZkInterruptedException { if ( _connection == null ) { return ; } LOG . debug ( "Closing ZkClient..." ) ; getEventLock ( ) . lock ( ) ; try { setShutdownTrigger ( true ) ; _eventThread . interrupt ( ) ; _eventThread . join ( 2000 ) ; _connection . close ( ) ; _connection = null ; } catch ( InterruptedException e ) { throw new ZkInterruptedException ( e ) ; } finally { getEventLock ( ) . unlock ( ) ; } LOG . debug ( "Closing ZkClient...done" ) ; } | Close the client . |
21,367 | public String createNoRetry ( final String path , final byte [ ] data , final CreateMode mode ) throws KeeperException , InterruptedException { return zookeeper . create ( path , data , acl , mode ) ; } | add by ljh at 2012 - 09 - 13 |
21,368 | public java . util . logging . Logger getParentLogger ( ) throws SQLFeatureNotSupportedException { try { Method getParentLoggerMethod = CommonDataSource . class . getDeclaredMethod ( "getParentLogger" , new Class < ? > [ 0 ] ) ; return ( java . util . logging . Logger ) getParentLoggerMethod . invoke ( delegate , new Object [ 0 ] ) ; } catch ( NoSuchMethodException e ) { throw new SQLFeatureNotSupportedException ( e ) ; } catch ( InvocationTargetException e2 ) { throw new SQLFeatureNotSupportedException ( e2 ) ; } catch ( IllegalArgumentException e2 ) { throw new SQLFeatureNotSupportedException ( e2 ) ; } catch ( IllegalAccessException e2 ) { throw new SQLFeatureNotSupportedException ( e2 ) ; } } | implemented from JDK7 |
21,369 | static Iterator < Page > lazySearch ( final Wikipedia wikipedia , final String query ) { final Response < Page > first = wikipedia . search ( query ) ; if ( first . nextOffset == null ) { return first . iterator ( ) ; } return new Iterator < Page > ( ) { Iterator < Page > current = first . iterator ( ) ; Long nextOffset = first . nextOffset ; public boolean hasNext ( ) { while ( ! current . hasNext ( ) && nextOffset != null ) { System . out . println ( "Wow.. even more results than " + nextOffset ) ; Response < Page > nextPage = wikipedia . resumeSearch ( query , nextOffset ) ; current = nextPage . iterator ( ) ; nextOffset = nextPage . nextOffset ; } return current . hasNext ( ) ; } public Page next ( ) { return current . next ( ) ; } public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; } | this will lazily continue searches making new http calls as necessary . |
21,370 | public WikipediaExample . Response < X > read ( JsonReader reader ) throws IOException { WikipediaExample . Response < X > pages = new WikipediaExample . Response < X > ( ) ; reader . beginObject ( ) ; while ( reader . hasNext ( ) ) { String nextName = reader . nextName ( ) ; if ( "query" . equals ( nextName ) ) { reader . beginObject ( ) ; while ( reader . hasNext ( ) ) { if ( query ( ) . equals ( reader . nextName ( ) ) ) { reader . beginObject ( ) ; while ( reader . hasNext ( ) ) { reader . nextName ( ) ; reader . beginObject ( ) ; pages . add ( build ( reader ) ) ; reader . endObject ( ) ; } reader . endObject ( ) ; } else { reader . skipValue ( ) ; } } reader . endObject ( ) ; } else if ( "continue" . equals ( nextName ) ) { reader . beginObject ( ) ; while ( reader . hasNext ( ) ) { if ( "gsroffset" . equals ( reader . nextName ( ) ) ) { pages . nextOffset = reader . nextLong ( ) ; } else { reader . skipValue ( ) ; } } reader . endObject ( ) ; } else { reader . skipValue ( ) ; } } reader . endObject ( ) ; return pages ; } | the wikipedia api doesn t use json arrays rather a series of nested objects . |
21,371 | public static HeaderTemplate append ( HeaderTemplate headerTemplate , Iterable < String > values ) { Set < String > headerValues = new LinkedHashSet < > ( headerTemplate . getValues ( ) ) ; headerValues . addAll ( StreamSupport . stream ( values . spliterator ( ) , false ) . filter ( Util :: isNotBlank ) . collect ( Collectors . toSet ( ) ) ) ; return create ( headerTemplate . getName ( ) , headerValues ) ; } | Append values to a Header Template . |
21,372 | public String expand ( Map < String , ? > variables ) { if ( variables == null ) { throw new IllegalArgumentException ( "variable map is required." ) ; } StringBuilder resolved = new StringBuilder ( ) ; for ( TemplateChunk chunk : this . templateChunks ) { if ( chunk instanceof Expression ) { String resolvedExpression = this . resolveExpression ( ( Expression ) chunk , variables ) ; if ( resolvedExpression != null ) { resolved . append ( resolvedExpression ) ; } } else { resolved . append ( chunk . getValue ( ) ) ; } } return resolved . toString ( ) ; } | Expand the template . |
21,373 | public List < String > getVariables ( ) { return this . templateChunks . stream ( ) . filter ( templateChunk -> Expression . class . isAssignableFrom ( templateChunk . getClass ( ) ) ) . map ( templateChunk -> ( ( Expression ) templateChunk ) . getName ( ) ) . filter ( Objects :: nonNull ) . collect ( Collectors . toList ( ) ) ; } | Variable names contained in the template . |
21,374 | public List < String > getLiterals ( ) { return this . templateChunks . stream ( ) . filter ( templateChunk -> Literal . class . isAssignableFrom ( templateChunk . getClass ( ) ) ) . map ( TemplateChunk :: toString ) . filter ( Objects :: nonNull ) . collect ( Collectors . toList ( ) ) ; } | List of all Literals in the Template . |
21,375 | private void parseFragment ( String fragment , boolean query ) { ChunkTokenizer tokenizer = new ChunkTokenizer ( fragment ) ; while ( tokenizer . hasNext ( ) ) { String chunk = tokenizer . next ( ) ; if ( chunk . startsWith ( "{" ) ) { FragmentType type = ( query ) ? FragmentType . QUERY : FragmentType . PATH_SEGMENT ; Expression expression = Expressions . create ( chunk , type ) ; if ( expression == null ) { this . templateChunks . add ( Literal . create ( encode ( chunk , query ) ) ) ; } else { this . templateChunks . add ( expression ) ; } } else { this . templateChunks . add ( Literal . create ( encode ( chunk , query ) ) ) ; } } } | Parse a template fragment . |
21,376 | Callable < ? > invokeMethod ( MethodHandler methodHandler , Object [ ] arguments ) { return ( ) -> { try { return methodHandler . invoke ( arguments ) ; } catch ( Throwable th ) { if ( th instanceof FeignException ) { throw ( FeignException ) th ; } throw new RuntimeException ( th ) ; } } ; } | Invoke the Method Handler as a Callable . |
21,377 | boolean matches ( String value ) { if ( pattern == null ) { return true ; } return pattern . matcher ( value ) . matches ( ) ; } | Checks if the provided value matches the variable pattern if one is defined . Always true if no pattern is defined . |
21,378 | public static UriTemplate append ( UriTemplate uriTemplate , String fragment ) { return new UriTemplate ( uriTemplate . toString ( ) + fragment , uriTemplate . encodeSlash ( ) , uriTemplate . getCharset ( ) ) ; } | Append a uri fragment to the template . |
21,379 | private boolean isReactive ( Type type ) { if ( ! ParameterizedType . class . isAssignableFrom ( type . getClass ( ) ) ) { return false ; } ParameterizedType parameterizedType = ( ParameterizedType ) type ; Type raw = parameterizedType . getRawType ( ) ; return Arrays . asList ( ( ( Class ) raw ) . getInterfaces ( ) ) . contains ( Publisher . class ) ; } | Ensure that the type provided implements a Reactive Streams Publisher . |
21,380 | public static String encode ( String value ) { return encodeReserved ( value , FragmentType . URI , Util . UTF_8 ) ; } | Uri Encode the value using the default Charset . Already encoded values are skipped . |
21,381 | public static String encode ( String value , Charset charset ) { return encodeReserved ( value , FragmentType . URI , charset ) ; } | Uri Encode the value . Already encoded values are skipped . |
21,382 | public static String decode ( String value , Charset charset ) { try { return URLDecoder . decode ( value , charset . name ( ) ) ; } catch ( UnsupportedEncodingException uee ) { return value ; } } | Uri Decode the value . |
21,383 | public static String pathEncode ( String path , Charset charset ) { return encodeReserved ( path , FragmentType . PATH_SEGMENT , charset ) ; } | Uri Encode a Path Fragment . |
21,384 | public static String queryEncode ( String query , Charset charset ) { return encodeReserved ( query , FragmentType . QUERY , charset ) ; } | Uri Encode a Query Fragment . |
21,385 | public static String queryParamEncode ( String queryParam , Charset charset ) { return encodeReserved ( queryParam , FragmentType . QUERY_PARAM , charset ) ; } | Uri Encode a Query Parameter name or value . |
21,386 | public static String encodeReserved ( String value , FragmentType type , Charset charset ) { Matcher matcher = PCT_ENCODED_PATTERN . matcher ( value ) ; if ( ! matcher . find ( ) ) { return encodeChunk ( value , type , charset ) ; } int length = value . length ( ) ; StringBuilder encoded = new StringBuilder ( length + 8 ) ; int index = 0 ; do { String before = value . substring ( index , matcher . start ( ) ) ; encoded . append ( encodeChunk ( before , type , charset ) ) ; encoded . append ( matcher . group ( ) ) ; index = matcher . end ( ) ; } while ( matcher . find ( ) ) ; String tail = value . substring ( index , length ) ; encoded . append ( encodeChunk ( tail , type , charset ) ) ; return encoded . toString ( ) ; } | Encodes the value preserving all reserved characters .. Values that are already pct - encoded are ignored . |
21,387 | private static String encodeChunk ( String value , FragmentType type , Charset charset ) { byte [ ] data = value . getBytes ( charset ) ; ByteArrayOutputStream encoded = new ByteArrayOutputStream ( ) ; for ( byte b : data ) { if ( type . isAllowed ( b ) ) { encoded . write ( b ) ; } else { pctEncode ( b , encoded ) ; } } return new String ( encoded . toByteArray ( ) ) ; } | Encode a Uri Chunk ensuring that all reserved characters are also encoded . |
21,388 | private static void pctEncode ( byte data , ByteArrayOutputStream bos ) { bos . write ( '%' ) ; char hex1 = Character . toUpperCase ( Character . forDigit ( ( data >> 4 ) & 0xF , 16 ) ) ; char hex2 = Character . toUpperCase ( Character . forDigit ( data & 0xF , 16 ) ) ; bos . write ( hex1 ) ; bos . write ( hex2 ) ; } | Percent Encode the provided byte . |
21,389 | public static RequestTemplate from ( RequestTemplate requestTemplate ) { RequestTemplate template = new RequestTemplate ( requestTemplate . target , requestTemplate . fragment , requestTemplate . uriTemplate , requestTemplate . method , requestTemplate . charset , requestTemplate . body , requestTemplate . decodeSlash , requestTemplate . collectionFormat ) ; if ( ! requestTemplate . queries ( ) . isEmpty ( ) ) { template . queries . putAll ( requestTemplate . queries ) ; } if ( ! requestTemplate . headers ( ) . isEmpty ( ) ) { template . headers . putAll ( requestTemplate . headers ) ; } return template ; } | Create a Request Template from an existing Request Template . |
21,390 | public RequestTemplate resolve ( Map < String , ? > variables ) { StringBuilder uri = new StringBuilder ( ) ; RequestTemplate resolved = RequestTemplate . from ( this ) ; if ( this . uriTemplate == null ) { this . uriTemplate = UriTemplate . create ( "" , ! this . decodeSlash , this . charset ) ; } uri . append ( this . uriTemplate . expand ( variables ) ) ; if ( ! this . queries . isEmpty ( ) ) { resolved . queries ( Collections . emptyMap ( ) ) ; StringBuilder query = new StringBuilder ( ) ; Iterator < QueryTemplate > queryTemplates = this . queries . values ( ) . iterator ( ) ; while ( queryTemplates . hasNext ( ) ) { QueryTemplate queryTemplate = queryTemplates . next ( ) ; String queryExpanded = queryTemplate . expand ( variables ) ; if ( Util . isNotBlank ( queryExpanded ) ) { query . append ( queryExpanded ) ; if ( queryTemplates . hasNext ( ) ) { query . append ( "&" ) ; } } } String queryString = query . toString ( ) ; if ( ! queryString . isEmpty ( ) ) { Matcher queryMatcher = QUERY_STRING_PATTERN . matcher ( uri ) ; if ( queryMatcher . find ( ) ) { uri . append ( "&" ) ; } else { uri . append ( "?" ) ; } uri . append ( queryString ) ; } } resolved . uri ( uri . toString ( ) ) ; if ( ! this . headers . isEmpty ( ) ) { resolved . headers ( Collections . emptyMap ( ) ) ; for ( HeaderTemplate headerTemplate : this . headers . values ( ) ) { String header = headerTemplate . expand ( variables ) ; if ( ! header . isEmpty ( ) ) { String headerValues = header . substring ( header . indexOf ( " " ) + 1 ) ; if ( ! headerValues . isEmpty ( ) ) { resolved . header ( headerTemplate . getName ( ) , headerValues ) ; } } } } resolved . body ( this . body . expand ( variables ) ) ; resolved . resolved = true ; return resolved ; } | Resolve all expressions using the variable value substitutions provided . Variable values will be pct - encoded if they are not already . |
21,391 | public RequestTemplate method ( String method ) { checkNotNull ( method , "method" ) ; try { this . method = HttpMethod . valueOf ( method ) ; } catch ( IllegalArgumentException iae ) { throw new IllegalArgumentException ( "Invalid HTTP Method: " + method ) ; } return this ; } | Set the Http Method . |
21,392 | public RequestTemplate uri ( String uri , boolean append ) { if ( UriUtils . isAbsolute ( uri ) ) { throw new IllegalArgumentException ( "url values must be not be absolute." ) ; } if ( uri == null ) { uri = "/" ; } else if ( ( ! uri . isEmpty ( ) && ! uri . startsWith ( "/" ) && ! uri . startsWith ( "{" ) && ! uri . startsWith ( "?" ) ) ) { uri = "/" + uri ; } Matcher queryMatcher = QUERY_STRING_PATTERN . matcher ( uri ) ; if ( queryMatcher . find ( ) ) { String queryString = uri . substring ( queryMatcher . start ( ) + 1 ) ; this . extractQueryTemplates ( queryString , append ) ; uri = uri . substring ( 0 , queryMatcher . start ( ) ) ; } int fragmentIndex = uri . indexOf ( '#' ) ; if ( fragmentIndex > - 1 ) { fragment = uri . substring ( fragmentIndex ) ; uri = uri . substring ( 0 , fragmentIndex ) ; } if ( append && this . uriTemplate != null ) { this . uriTemplate = UriTemplate . append ( this . uriTemplate , uri ) ; } else { this . uriTemplate = UriTemplate . create ( uri , ! this . decodeSlash , this . charset ) ; } return this ; } | Set the uri for the request . |
21,393 | public RequestTemplate target ( String target ) { if ( Util . isBlank ( target ) ) { return this ; } if ( ! UriUtils . isAbsolute ( target ) ) { throw new IllegalArgumentException ( "target values must be absolute." ) ; } if ( target . endsWith ( "/" ) ) { target = target . substring ( 0 , target . length ( ) - 1 ) ; } try { URI targetUri = URI . create ( target ) ; if ( Util . isNotBlank ( targetUri . getRawQuery ( ) ) ) { this . extractQueryTemplates ( targetUri . getRawQuery ( ) , true ) ; } this . target = targetUri . getScheme ( ) + "://" + targetUri . getAuthority ( ) + targetUri . getPath ( ) ; if ( targetUri . getFragment ( ) != null ) { this . fragment = "#" + targetUri . getFragment ( ) ; } } catch ( IllegalArgumentException iae ) { throw new IllegalArgumentException ( "Target is not a valid URI." , iae ) ; } return this ; } | Set the target host for this request . |
21,394 | public String url ( ) { StringBuilder url = new StringBuilder ( this . path ( ) ) ; if ( ! this . queries . isEmpty ( ) ) { url . append ( this . queryLine ( ) ) ; } if ( fragment != null ) { url . append ( fragment ) ; } return url . toString ( ) ; } | The URL for the request . If the template has not been resolved the url will represent a uri template . |
21,395 | public String path ( ) { StringBuilder path = new StringBuilder ( ) ; if ( this . target != null ) { path . append ( this . target ) ; } if ( this . uriTemplate != null ) { path . append ( this . uriTemplate . toString ( ) ) ; } if ( path . length ( ) == 0 ) { path . append ( "/" ) ; } return path . toString ( ) ; } | The Uri Path . |
21,396 | public List < String > variables ( ) { List < String > variables = new ArrayList < > ( this . uriTemplate . getVariables ( ) ) ; for ( QueryTemplate queryTemplate : this . queries . values ( ) ) { variables . addAll ( queryTemplate . getVariables ( ) ) ; } for ( HeaderTemplate headerTemplate : this . headers . values ( ) ) { variables . addAll ( headerTemplate . getVariables ( ) ) ; } variables . addAll ( this . body . getVariables ( ) ) ; return variables ; } | List all of the template variable expressions for this template . |
21,397 | public RequestTemplate query ( String name , Iterable < String > values ) { return appendQuery ( name , values , this . collectionFormat ) ; } | Specify a Query String parameter with the specified values . Values can be literals or template expressions . |
21,398 | private RequestTemplate appendQuery ( String name , Iterable < String > values , CollectionFormat collectionFormat ) { if ( ! values . iterator ( ) . hasNext ( ) ) { this . queries . remove ( name ) ; return this ; } this . queries . compute ( name , ( key , queryTemplate ) -> { if ( queryTemplate == null ) { return QueryTemplate . create ( name , values , this . charset , collectionFormat ) ; } else { return QueryTemplate . append ( queryTemplate , values , collectionFormat ) ; } } ) ; return this ; } | Appends the query name and values . |
21,399 | @ SuppressWarnings ( "unused" ) public RequestTemplate queries ( Map < String , Collection < String > > queries ) { if ( queries == null || queries . isEmpty ( ) ) { this . queries . clear ( ) ; } else { queries . forEach ( this :: query ) ; } return this ; } | Sets the Query Parameters . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.