idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
14,000 | final public long getConnects ( ) { long total = 0 ; synchronized ( poolLock ) { for ( PooledConnection < C > conn : allConnections ) { total += conn . connectCount . get ( ) ; } } return total ; } | Gets the total number of connects for the entire pool . |
14,001 | final public void run ( ) { while ( true ) { try { try { sleep ( delayTime ) ; } catch ( InterruptedException err ) { logger . log ( Level . WARNING , null , err ) ; } long time = System . currentTimeMillis ( ) ; List < C > connsToClose ; synchronized ( poolLock ) { if ( isClosed ) return ; int maxIdle = maxIdleTime ; connsToClose = new ArrayList < > ( availableConnections . size ( ) ) ; for ( PooledConnection < C > availableConnection : availableConnections ) { synchronized ( availableConnection ) { C conn = availableConnection . connection ; if ( conn != null ) { if ( ( time - availableConnection . releaseTime ) > maxIdle || ( maxConnectionAge != UNLIMITED_MAX_CONNECTION_AGE && ( availableConnection . createTime > time || ( time - availableConnection . createTime ) >= maxConnectionAge ) ) ) { availableConnection . connection = null ; connsToClose . add ( conn ) ; } } } } } for ( C conn : connsToClose ) { try { close ( conn ) ; } catch ( Exception err ) { logger . log ( Level . WARNING , null , err ) ; } } } catch ( ThreadDeath TD ) { throw TD ; } catch ( Throwable T ) { logger . logp ( Level . SEVERE , AOPool . class . getName ( ) , "run" , null , T ) ; } } } | The RefreshConnection thread polls every connection in the connection pool . If it detects a connection is idle for more than the pre - defined MAX_IDLE_TIME it closes the connection . It will stop when the pool is flagged as closed . |
14,002 | public static byte [ ] md5 ( File file ) throws IOException { try ( InputStream in = new FileInputStream ( file ) ) { return md5 ( in ) ; } } | Gets the MD5 hashcode of a file . |
14,003 | public static byte [ ] md5 ( InputStream in ) throws IOException { MD5InputStream md5in = new MD5InputStream ( in ) ; byte [ ] trashBuffer = BufferManager . getBytes ( ) ; try { while ( md5in . read ( trashBuffer , 0 , BufferManager . BUFFER_SIZE ) != - 1 ) { } } finally { BufferManager . release ( trashBuffer , false ) ; } return md5in . hash ( ) ; } | Gets the MD5 hashcode of an input stream . |
14,004 | public void delete ( ) throws IOException { File f = tempFile ; if ( f != null ) { FileUtils . delete ( f ) ; tempFile = null ; } } | Deletes the underlying temp file immediately . Subsequent calls will not delete the temp file even if another file has the same path . If already deleted has no effect . |
14,005 | public File getFile ( ) throws IllegalStateException { File f = tempFile ; if ( f == null ) throw new IllegalStateException ( ) ; return f ; } | Gets the temp file . |
14,006 | private void buildData ( String path , WebPage page , List < TreePageData > data , WebSiteRequest req ) throws IOException , SQLException { if ( isVisible ( page ) ) { if ( path . length ( ) > 0 ) path = path + '/' + page . getShortTitle ( ) ; else path = page . getShortTitle ( ) ; WebPage [ ] pages = page . getCachedPages ( req ) ; int len = pages . length ; data . add ( new TreePageData ( len > 0 ? ( path + '/' ) : path , req . getContextPath ( ) + req . getURL ( page ) , page . getDescription ( ) ) ) ; for ( int c = 0 ; c < len ; c ++ ) buildData ( path , pages [ c ] , data , req ) ; } } | Recursively builds the list of all sites . |
14,007 | public void doGet ( ChainWriter out , WebSiteRequest req , HttpServletResponse resp ) throws IOException , SQLException { if ( req != null ) super . doGet ( out , req , resp ) ; } | The content of this page will not be included in the interal search engine . |
14,008 | private void saveProperties ( ) { assert Thread . holdsLock ( properties ) ; try { Properties writer = new Properties ( ) { private static final long serialVersionUID = 6953022173340009928L ; public Enumeration < Object > keys ( ) { SortedSet < Object > sortedSet = new TreeSet < > ( Collator . getInstance ( Locale . ROOT ) ) ; Enumeration < Object > e = super . keys ( ) ; while ( e . hasMoreElements ( ) ) sortedSet . add ( e . nextElement ( ) ) ; return Collections . enumeration ( sortedSet ) ; } } ; writer . putAll ( properties ) ; File tmpFile = File . createTempFile ( "ApplicationResources" , null , sourceFile . getParentFile ( ) ) ; OutputStream out = new BufferedOutputStream ( new FileOutputStream ( tmpFile ) ) ; try { if ( sourceFileComments != null ) { for ( String line : sourceFileComments ) { out . write ( line . getBytes ( propertiesCharset ) ) ; out . write ( EOL . getBytes ( propertiesCharset ) ) ; } } out = new SkipCommentsFilterOutputStream ( out ) ; writer . store ( out , null ) ; } finally { out . close ( ) ; } FileUtils . renameAllowNonAtomic ( tmpFile , sourceFile ) ; } catch ( IOException err ) { throw new RuntimeException ( err ) ; } } | Saves the properties file in ascending key order . All accesses must already hold a lock on the properties object . |
14,009 | public void checkGraph ( ) throws AsymmetricException , CycleException , EX { Set < V > vertices = graph . getVertices ( ) ; Map < V , Color > colors = new HashMap < > ( vertices . size ( ) * 4 / 3 + 1 ) ; Map < V , V > predecessors = new HashMap < > ( ) ; for ( V v : vertices ) { if ( ! colors . containsKey ( v ) ) doCheck ( colors , predecessors , v ) ; } } | Test the graph for cycles and makes sure that all connections are consistent with back connections . |
14,010 | public void configure ( ) { if ( getProperties ( ) . containsKey ( PROPERTY_NAME_FILE_PATTERN ) ) { filePattern = Pattern . compile ( getProperties ( ) . get ( PROPERTY_NAME_FILE_PATTERN ) . toString ( ) ) ; } else { filePattern = Pattern . compile ( DEFAULT_FILE_PATTERN ) ; } } | end method initialize |
14,011 | public int compareTo ( ElementRef o ) { int diff = pageRef . compareTo ( o . pageRef ) ; if ( diff != 0 ) return diff ; return id . compareTo ( o . id ) ; } | Orders by page then id . |
14,012 | public void endContentLine ( ChainWriter out , WebSiteRequest req , HttpServletResponse resp , int rowspan , boolean endsInternal ) { out . print ( " </td>\n" + " </tr>\n" ) ; } | Ends one line of content . |
14,013 | protected String getSender ( final SmsSendRequestDto smsSendRequestDto ) { if ( StringUtils . isNotBlank ( smsSendRequestDto . getSender ( ) ) ) { return smsSendRequestDto . getSender ( ) ; } Validate . notEmpty ( defaultSender , "defaultSender must not be null or blank" ) ; return defaultSender ; } | Returns the sender of the request . If no sender is specified the default sender will be returned . |
14,014 | protected String getReceiver ( final SmsSendRequestDto smsSendRequestDto ) { if ( StringUtils . isNotBlank ( smsSendRequestDto . getReceiver ( ) ) ) { return smsSendRequestDto . getReceiver ( ) ; } Validate . notEmpty ( defaultReceiver , "defaultReceiver must not be null or blank" ) ; return defaultReceiver ; } | Returns the receiver of the request . If no receiver is specified the default receiver will be returned . |
14,015 | protected String getMessage ( final SmsSendRequestDto smsSendRequestDto ) { if ( StringUtils . isNotBlank ( smsSendRequestDto . getMessage ( ) ) ) { return smsSendRequestDto . getMessage ( ) ; } Validate . notEmpty ( defaultMessage , "defaultMessage must not be null or blank" ) ; return defaultMessage ; } | Returns the message of the request . If no message is specified the default message will be returned . |
14,016 | final public void Update ( String s ) { byte [ ] chars = s . getBytes ( ) ; Update ( chars , chars . length ) ; } | Update buffer with given string . |
14,017 | public static String asHex ( byte [ ] hash ) { StringBuilder buf = new StringBuilder ( hash . length * 2 ) ; int i ; for ( i = 0 ; i < hash . length ; i ++ ) { if ( ( ( int ) hash [ i ] & 0xff ) < 0x10 ) buf . append ( "0" ) ; buf . append ( Long . toString ( ( int ) hash [ i ] & 0xff , 16 ) ) ; } return buf . toString ( ) ; } | Turns array of bytes into string representing each byte as unsigned hex number . |
14,018 | public static List < News > findAllNews ( ServletContext servletContext , HttpServletRequest request , HttpServletResponse response , Page page ) throws ServletException , IOException { final List < News > found = new ArrayList < > ( ) ; final SemanticCMS semanticCMS = SemanticCMS . getInstance ( servletContext ) ; CapturePage . traversePagesAnyOrder ( servletContext , request , response , page , CaptureLevel . META , new CapturePage . PageHandler < Void > ( ) { public Void handlePage ( Page page ) throws ServletException , IOException { for ( Element element : page . getElements ( ) ) { if ( element instanceof News ) { found . add ( ( News ) element ) ; } } return null ; } } , new CapturePage . TraversalEdges ( ) { public Collection < ChildRef > getEdges ( Page page ) { return page . getChildRefs ( ) ; } } , new CapturePage . EdgeFilter ( ) { public boolean applyEdge ( PageRef childPage ) { return semanticCMS . getBook ( childPage . getBookRef ( ) ) . isAccessible ( ) ; } } ) ; Collections . sort ( found ) ; return Collections . unmodifiableList ( found ) ; } | Gets all the new items in the given page and below sorted by news natural order . |
14,019 | public static LinkedBindingBuilder < Handler > bindHandler ( final Binder binder ) { final Multibinder < Handler > handlers = Multibinder . newSetBinder ( binder , Handler . class , HANDLER_NAMED ) ; return handlers . addBinding ( ) ; } | Bind a new handler into the jetty service . These handlers are bound before the servlet handler and can handle parts of the URI space before a servlet sees it . |
14,020 | public static LinkedBindingBuilder < Handler > bindLoggingHandler ( final Binder binder ) { final Multibinder < Handler > handlers = Multibinder . newSetBinder ( binder , Handler . class , LOGGING_NAMED ) ; return handlers . addBinding ( ) ; } | Bind a new handler into the jetty service . These handlers are bound after the servlet handler and will not see any requests before they have been handled . This is intended to bind logging statistics etc . which want to operate on the results of a request to the server . |
14,021 | public static LinkedBindingBuilder < HandlerWrapper > bindSecurityHandler ( final Binder binder ) { return binder . bind ( HandlerWrapper . class ) . annotatedWith ( SECURITY_NAMED ) ; } | Bind a delegating security handler . Any request will be routed through this handler and can be allowed or denied by this handler . If no handler is bound requests are forwarded to the internal handler collection . |
14,022 | public void printContentStart ( ChainWriter out , WebSiteRequest req , HttpServletResponse resp ) throws IOException , SQLException { out . print ( getDescription ( ) ) ; } | Prints the content that will be put before the auto - generated list . |
14,023 | protected String getElementIdTemplate ( ) { ResourceRef rr = getResourceRef ( ) ; if ( rr != null ) { String path = rr . getPath ( ) . toString ( ) ; int slashBefore ; if ( path . endsWith ( Path . SEPARATOR_STRING ) ) { slashBefore = path . lastIndexOf ( Path . SEPARATOR_CHAR , path . length ( ) - 2 ) ; } else { slashBefore = path . lastIndexOf ( Path . SEPARATOR_CHAR ) ; } String filename = path . substring ( slashBefore + 1 ) ; if ( filename . isEmpty ( ) ) throw new IllegalArgumentException ( "Invalid filename for file: " + path ) ; int lastDot = filename . lastIndexOf ( '.' ) ; if ( lastDot > 0 ) filename = filename . substring ( 0 , lastDot ) ; return filename ; } throw new IllegalStateException ( "Path not set" ) ; } | Does not include the size on the ID template also strips any file extension if it will not leave the filename empty . |
14,024 | public String getLabel ( ) { ResourceStore rs ; ResourceRef rr ; synchronized ( lock ) { rs = this . resourceStore ; rr = this . resourceRef ; } if ( rr != null ) { String path = rr . getPath ( ) . toString ( ) ; boolean isDirectory = path . endsWith ( Path . SEPARATOR_STRING ) ; int slashBefore ; if ( isDirectory ) { slashBefore = path . lastIndexOf ( Path . SEPARATOR_CHAR , path . length ( ) - 2 ) ; } else { slashBefore = path . lastIndexOf ( Path . SEPARATOR_CHAR ) ; } String filename = path . substring ( slashBefore + 1 ) ; if ( filename . isEmpty ( ) ) throw new IllegalArgumentException ( "Invalid filename for file: " + path ) ; if ( ! isDirectory ) { if ( rs != null ) { try { try ( ResourceConnection conn = rs . getResource ( rr . getPath ( ) ) . open ( ) ) { if ( conn . exists ( ) ) { return filename + " (" + StringUtility . getApproximateSize ( conn . getLength ( ) ) + ')' ; } } } catch ( FileNotFoundException e ) { } catch ( IOException e ) { throw new WrappedException ( e ) ; } } } return filename ; } throw new IllegalStateException ( "Path not set" ) ; } | The label is always the filename . |
14,025 | public static String getDispatchedPage ( ServletRequest request ) { String dispatchedPage = ( String ) request . getAttribute ( DISPATCHED_PAGE_REQUEST_ATTRIBUTE ) ; if ( logger . isLoggable ( Level . FINE ) ) logger . log ( Level . FINE , "request={0}, dispatchedPage={1}" , new Object [ ] { request , dispatchedPage } ) ; return dispatchedPage ; } | Gets the current - thread dispatched page or null if not set . |
14,026 | public static void setDispatchedPage ( ServletRequest request , String dispatchedPage ) { if ( logger . isLoggable ( Level . FINE ) ) logger . log ( Level . FINE , "request={0}, dispatchedPage={1}" , new Object [ ] { request , dispatchedPage } ) ; request . setAttribute ( DISPATCHED_PAGE_REQUEST_ATTRIBUTE , dispatchedPage ) ; } | Sets the current - thread dispatched page . |
14,027 | public String getLabel ( ) { String l = label ; if ( l != null ) return l ; String p = path ; if ( p != null ) { String filename = p . substring ( p . lastIndexOf ( '/' ) + 1 ) ; if ( filename . endsWith ( DOT_EXTENSION ) ) filename = filename . substring ( 0 , filename . length ( ) - DOT_EXTENSION . length ( ) ) ; if ( filename . isEmpty ( ) ) throw new IllegalArgumentException ( "Invalid filename for diagram: " + p ) ; return filename ; } throw new IllegalStateException ( "Cannot get label, neither label nor path set" ) ; } | If not set defaults to the last path segment of path with any . dia extension stripped . |
14,028 | public static SourceNode fromStringWithSourceMap ( String aGeneratedCode , SourceMapConsumer aSourceMapConsumer , final String aRelativePath ) { final SourceNode node = new SourceNode ( ) ; List < String > remainingLines = new ArrayList < > ( Util . split ( aGeneratedCode , REGEX_NEWLINE ) ) ; int [ ] lastGeneratedLine = new int [ ] { 1 } ; int [ ] lastGeneratedColumn = new int [ ] { 0 } ; Mapping [ ] lastMapping = new Mapping [ 1 ] ; aSourceMapConsumer . eachMapping ( ) . forEach ( mapping -> { if ( lastMapping [ 0 ] != null ) { if ( lastGeneratedLine [ 0 ] < mapping . generated . line ) { addMappingWithCode ( node , aRelativePath , lastMapping [ 0 ] , shiftNextLine ( remainingLines ) ) ; lastGeneratedLine [ 0 ] ++ ; lastGeneratedColumn [ 0 ] = 0 ; } else { String nextLine = remainingLines . get ( 0 ) ; String code = Util . substr ( nextLine , 0 , mapping . generated . column - lastGeneratedColumn [ 0 ] ) ; remainingLines . set ( 0 , Util . substr ( nextLine , mapping . generated . column - lastGeneratedColumn [ 0 ] ) ) ; lastGeneratedColumn [ 0 ] = mapping . generated . column ; addMappingWithCode ( node , aRelativePath , lastMapping [ 0 ] , code ) ; lastMapping [ 0 ] = mapping ; return ; } } while ( lastGeneratedLine [ 0 ] < mapping . generated . line ) { node . add ( shiftNextLine ( remainingLines ) ) ; lastGeneratedLine [ 0 ] ++ ; } if ( lastGeneratedColumn [ 0 ] < mapping . generated . column && ! remainingLines . isEmpty ( ) ) { String nextLine = remainingLines . get ( 0 ) ; node . add ( Util . substr ( nextLine , 0 , mapping . generated . column ) ) ; remainingLines . set ( 0 , Util . substr ( nextLine , mapping . generated . column ) ) ; lastGeneratedColumn [ 0 ] = mapping . generated . column ; } lastMapping [ 0 ] = mapping ; } ) ; if ( remainingLines . size ( ) > 0 ) { if ( lastMapping [ 0 ] != null ) { addMappingWithCode ( node , aRelativePath , lastMapping [ 0 ] , shiftNextLine ( remainingLines ) ) ; } node . add ( Util . join ( remainingLines , "" ) ) ; } aSourceMapConsumer . sources ( ) . forEach ( sourceFile -> { String content = aSourceMapConsumer . sourceContentFor ( sourceFile ) ; if ( content != null ) { if ( aRelativePath != null ) { sourceFile = Util . join ( aRelativePath , sourceFile ) ; } node . setSourceContent ( sourceFile , content ) ; } } ) ; return node ; } | Creates a SourceNode from generated code and a SourceMapConsumer . |
14,029 | public void add ( Object ... aChunk ) { List < Object > list ; if ( aChunk . length == 1 && aChunk [ 0 ] instanceof List ) { @ SuppressWarnings ( "unchecked" ) List < Object > l = ( List < Object > ) aChunk [ 0 ] ; list = l ; } else { list = Arrays . asList ( aChunk ) ; } list . forEach ( chunk -> { if ( chunk instanceof String ) { this . add ( ( String ) chunk ) ; } else if ( chunk instanceof SourceNode ) { this . add ( ( SourceNode ) chunk ) ; } else { throw new IllegalArgumentException ( ) ; } } ) ; } | Add a chunk of generated JS to this source node . |
14,030 | public void prepend ( Object ... aChunk ) { for ( int i = aChunk . length - 1 ; i >= 0 ; i -- ) { if ( aChunk [ i ] instanceof String ) { this . prepend ( ( String ) aChunk [ i ] ) ; } else if ( aChunk [ i ] instanceof SourceNode ) { this . prepend ( ( SourceNode ) aChunk [ i ] ) ; } else { throw new IllegalArgumentException ( ) ; } } } | Add a chunk of generated JS to the beginning of this source node . |
14,031 | public void join ( String aSep ) { List < Object > newChildren ; int i ; int len = this . children . size ( ) ; if ( len > 0 ) { newChildren = new ArrayList < > ( ) ; for ( i = 0 ; i < len - 1 ; i ++ ) { newChildren . add ( this . children . get ( i ) ) ; newChildren . add ( aSep ) ; } newChildren . add ( this . children . get ( i ) ) ; this . children = newChildren ; } } | Like String . prototype . join except for SourceNodes . Inserts aStr between each of this . children . |
14,032 | public void replaceRight ( Pattern aPattern , String aReplacement ) { Object lastChild = this . children . get ( this . children . size ( ) - 1 ) ; if ( lastChild instanceof SourceNode ) { ( ( SourceNode ) lastChild ) . replaceRight ( aPattern , aReplacement ) ; } else if ( lastChild instanceof String ) { this . children . set ( this . children . size ( ) - 1 , aPattern . matcher ( ( ( String ) lastChild ) ) . replaceFirst ( aReplacement ) ) ; } else { this . children . add ( aPattern . matcher ( "" ) . replaceFirst ( aReplacement ) ) ; } } | Call String . prototype . replace on the very right - most source snippet . Useful for trimming whitespace from the end of a source node etc . |
14,033 | public void walkSourceContents ( SourceWalker walker ) { for ( int i = 0 , len = this . children . size ( ) ; i < len ; i ++ ) { if ( this . children . get ( i ) instanceof SourceNode ) { ( ( SourceNode ) this . children . get ( i ) ) . walkSourceContents ( walker ) ; } } for ( Entry < String , String > entry : this . sourceContents . entrySet ( ) ) { walker . walk ( entry . getKey ( ) , entry . getValue ( ) ) ; } } | Walk over the tree of SourceNodes . The walking function is called for each source file content and is passed the filename and source content . |
14,034 | public Map < String , Object > getProperty ( ) { synchronized ( lock ) { if ( properties == null ) return Collections . emptyMap ( ) ; if ( frozen ) return properties ; return AoCollections . unmodifiableCopyMap ( properties ) ; } } | Gets an unmodifiable snapshot of all properties associated with a node . The returned map will not change even if properties are added to the node . |
14,035 | public List < Element > getChildElements ( ) { synchronized ( lock ) { if ( childElements == null ) return Collections . emptyList ( ) ; if ( frozen ) return childElements ; return AoCollections . unmodifiableCopyList ( childElements ) ; } } | Every node may potentially have child elements . |
14,036 | public Long addChildElement ( Element childElement , ElementWriter elementWriter ) { synchronized ( lock ) { checkNotFrozen ( ) ; if ( childElements == null ) childElements = new ArrayList < > ( ) ; childElements . add ( childElement ) ; if ( elementWriters == null ) elementWriters = new HashMap < > ( ) ; IdGenerator idGenerator = idGenerators . get ( ) ; while ( true ) { Long elementKey = idGenerator . getNextId ( ) ; if ( ! elementWriters . containsKey ( elementKey ) ) { elementWriters . put ( elementKey , elementWriter ) ; return elementKey ; } else { idGenerator . reset ( ) ; } } } } | Adds a child element to this node . |
14,037 | public Set < PageRef > getPageLinks ( ) { synchronized ( lock ) { if ( pageLinks == null ) return Collections . emptySet ( ) ; if ( frozen ) return pageLinks ; return AoCollections . unmodifiableCopySet ( pageLinks ) ; } } | Gets the set of all pages this node directly links to ; this does not include pages linked to by child elements . |
14,038 | public BufferResult getBody ( ) { BufferResult b = body ; if ( b == null ) return EmptyResult . getInstance ( ) ; return b ; } | Every node may potentially have HTML body . |
14,039 | public String getLabel ( ) { StringBuilder sb = new StringBuilder ( ) ; try { appendLabel ( sb ) ; } catch ( IOException e ) { throw new AssertionError ( "Should not happen because using StringBuilder" , e ) ; } return sb . toString ( ) ; } | Gets a short description useful for links and lists for this node . |
14,040 | private static < E extends Element > List < E > findTopLevelElementsRecurse ( Class < E > elementType , Node node , List < E > matches ) { for ( Element elem : node . getChildElements ( ) ) { if ( elementType . isInstance ( elem ) ) { if ( matches == null ) matches = new ArrayList < > ( ) ; matches . add ( elementType . cast ( elem ) ) ; } else { matches = findTopLevelElementsRecurse ( elementType , elem , matches ) ; } } return matches ; } | Recursive component of findTopLevelElements . |
14,041 | protected void setRemoteSocketAddress ( final SocketAddress newRemoteSocketAddress ) { synchronized ( remoteSocketAddressLock ) { final SocketAddress oldRemoteSocketAddress = this . remoteSocketAddress ; if ( ! newRemoteSocketAddress . equals ( oldRemoteSocketAddress ) ) { this . remoteSocketAddress = newRemoteSocketAddress ; listenerManager . enqueueEvent ( new ConcurrentListenerManager . Event < SocketListener > ( ) { public Runnable createCall ( final SocketListener listener ) { return new Runnable ( ) { public void run ( ) { listener . onRemoteSocketAddressChange ( AbstractSocket . this , oldRemoteSocketAddress , newRemoteSocketAddress ) ; } } ; } } ) ; } } } | Sets the most recently seen remote address . If the provided value is different than the previous will notify all listeners . |
14,042 | public void start ( Callback < ? super Socket > onStart , Callback < ? super Exception > onError ) throws IllegalStateException { if ( isClosed ( ) ) throw new IllegalStateException ( "Socket is closed" ) ; startImpl ( onStart , onError ) ; } | Makes sure the socket is not already closed then calls startImpl . |
14,043 | public ReadableInstant getLastModified ( ServletContext servletContext , HttpServletRequest request , HttpServletResponse response , Page page ) throws ServletException , IOException { List < News > news = NewsUtils . findAllNews ( servletContext , request , response , page ) ; return news . isEmpty ( ) ? null : news . get ( 0 ) . getPubDate ( ) ; } | The last modified time of news view is the pubDate of the most recent news entry . |
14,044 | public void search ( String [ ] words , WebSiteRequest req , HttpServletResponse response , List < SearchResult > results , AoByteArrayOutputStream bytes , List < WebPage > finishedPages ) { } | Do not include this in the search results . |
14,045 | public boolean send ( ProbeTestRun testRun ) throws MalformedURLException { LOGGER . info ( "Connected to Probe Dock API at " + configuration . getServerConfiguration ( ) . getApiUrl ( ) ) ; if ( configuration . isPayloadPrint ( ) ) { try ( OutputStreamWriter testRunOsw = new OutputStreamWriter ( System . out ) ) { serializer . serializePayload ( testRunOsw , testRun , true ) ; } catch ( IOException ioe ) { } } return sendTestRun ( testRun ) ; } | Send a payload to Probe Dock |
14,046 | private HttpURLConnection openConnection ( ServerConfiguration configuration , URL url ) throws IOException { if ( configuration . hasProxyConfiguration ( ) ) { Proxy proxy = new Proxy ( Proxy . Type . HTTP , new InetSocketAddress ( configuration . getProxyConfiguration ( ) . getHost ( ) , configuration . getProxyConfiguration ( ) . getPort ( ) ) ) ; return ( HttpURLConnection ) url . openConnection ( proxy ) ; } else { return ( HttpURLConnection ) url . openConnection ( ) ; } } | Open a connection regarding the configuration and the URL |
14,047 | public void loadImage ( ) throws InterruptedException { synchronized ( this ) { status = 0 ; image . getSource ( ) . startProduction ( this ) ; while ( ( status & ( IMAGEABORTED | IMAGEERROR | SINGLEFRAMEDONE | STATICIMAGEDONE ) ) == 0 ) { wait ( ) ; } } } | Loads an image and returns when a frame is done the image is done an error occurs or the image is aborted . |
14,048 | private FilterDescriptor createFilter ( FilterType filterType , Map < String , FilterDescriptor > filters , ScannerContext context ) { Store store = context . getStore ( ) ; FilterDescriptor filterDescriptor = getOrCreateNamedDescriptor ( FilterDescriptor . class , filterType . getFilterName ( ) . getValue ( ) , filters , store ) ; setAsyncSupported ( filterDescriptor , filterType . getAsyncSupported ( ) ) ; for ( DescriptionType descriptionType : filterType . getDescription ( ) ) { filterDescriptor . getDescriptions ( ) . add ( XmlDescriptorHelper . createDescription ( descriptionType , store ) ) ; } for ( DisplayNameType displayNameType : filterType . getDisplayName ( ) ) { filterDescriptor . getDisplayNames ( ) . add ( XmlDescriptorHelper . createDisplayName ( displayNameType , store ) ) ; } FullyQualifiedClassType filterClass = filterType . getFilterClass ( ) ; if ( filterClass != null ) { TypeResolver typeResolver = context . peek ( TypeResolver . class ) ; TypeCache . CachedType < TypeDescriptor > filterClassDescriptor = typeResolver . resolve ( filterClass . getValue ( ) , context ) ; filterDescriptor . setType ( filterClassDescriptor . getTypeDescriptor ( ) ) ; } for ( IconType iconType : filterType . getIcon ( ) ) { IconDescriptor iconDescriptor = XmlDescriptorHelper . createIcon ( iconType , store ) ; filterDescriptor . getIcons ( ) . add ( iconDescriptor ) ; } for ( ParamValueType paramValueType : filterType . getInitParam ( ) ) { ParamValueDescriptor paramValueDescriptor = createParamValue ( paramValueType , store ) ; filterDescriptor . getInitParams ( ) . add ( paramValueDescriptor ) ; } return filterDescriptor ; } | Create a filter descriptor . |
14,049 | private FilterMappingDescriptor createFilterMapping ( FilterMappingType filterMappingType , Map < String , FilterDescriptor > filters , Map < String , ServletDescriptor > servlets , Store store ) { FilterMappingDescriptor filterMappingDescriptor = store . create ( FilterMappingDescriptor . class ) ; FilterNameType filterName = filterMappingType . getFilterName ( ) ; FilterDescriptor filterDescriptor = getOrCreateNamedDescriptor ( FilterDescriptor . class , filterName . getValue ( ) , filters , store ) ; filterDescriptor . getMappings ( ) . add ( filterMappingDescriptor ) ; for ( Object urlPatternOrServletName : filterMappingType . getUrlPatternOrServletName ( ) ) { if ( urlPatternOrServletName instanceof UrlPatternType ) { UrlPatternType urlPatternType = ( UrlPatternType ) urlPatternOrServletName ; UrlPatternDescriptor urlPatternDescriptor = createUrlPattern ( urlPatternType , store ) ; filterMappingDescriptor . getUrlPatterns ( ) . add ( urlPatternDescriptor ) ; } else if ( urlPatternOrServletName instanceof ServletNameType ) { ServletNameType servletNameType = ( ServletNameType ) urlPatternOrServletName ; ServletDescriptor servletDescriptor = getOrCreateNamedDescriptor ( ServletDescriptor . class , servletNameType . getValue ( ) , servlets , store ) ; filterMappingDescriptor . setServlet ( servletDescriptor ) ; } } for ( DispatcherType dispatcherType : filterMappingType . getDispatcher ( ) ) { DispatcherDescriptor dispatcherDescriptor = store . create ( DispatcherDescriptor . class ) ; dispatcherDescriptor . setValue ( dispatcherType . getValue ( ) ) ; filterMappingDescriptor . getDispatchers ( ) . add ( dispatcherDescriptor ) ; } return filterMappingDescriptor ; } | Create a filter mapping descriptor . |
14,050 | private < T extends NamedDescriptor > T getOrCreateNamedDescriptor ( Class < T > type , String name , Map < String , T > descriptors , Store store ) { T descriptor = descriptors . get ( name ) ; if ( descriptor == null ) { descriptor = store . create ( type ) ; descriptor . setName ( name ) ; descriptors . put ( name , descriptor ) ; } return descriptor ; } | Get or create a named descriptor . |
14,051 | private ParamValueDescriptor createParamValue ( ParamValueType paramValueType , Store store ) { ParamValueDescriptor paramValueDescriptor = store . create ( ParamValueDescriptor . class ) ; for ( DescriptionType descriptionType : paramValueType . getDescription ( ) ) { DescriptionDescriptor descriptionDescriptor = XmlDescriptorHelper . createDescription ( descriptionType , store ) ; paramValueDescriptor . getDescriptions ( ) . add ( descriptionDescriptor ) ; } paramValueDescriptor . setName ( paramValueType . getParamName ( ) . getValue ( ) ) ; XsdStringType paramValue = paramValueType . getParamValue ( ) ; if ( paramValue != null ) { paramValueDescriptor . setValue ( paramValue . getValue ( ) ) ; } return paramValueDescriptor ; } | Create a param value descriptor . |
14,052 | private void setAsyncSupported ( AsyncSupportedDescriptor asyncSupportedDescriptor , TrueFalseType asyncSupported ) { if ( asyncSupported != null ) { asyncSupportedDescriptor . setAsyncSupported ( asyncSupported . isValue ( ) ) ; } } | Set the value for an async supported on the given descriptor . |
14,053 | private ServletMappingDescriptor createServletMapping ( ServletMappingType servletMappingType , Map < String , ServletDescriptor > servlets , Store store ) { ServletMappingDescriptor servletMappingDescriptor = store . create ( ServletMappingDescriptor . class ) ; ServletNameType servletName = servletMappingType . getServletName ( ) ; ServletDescriptor servletDescriptor = getOrCreateNamedDescriptor ( ServletDescriptor . class , servletName . getValue ( ) , servlets , store ) ; servletDescriptor . getMappings ( ) . add ( servletMappingDescriptor ) ; for ( UrlPatternType urlPatternType : servletMappingType . getUrlPattern ( ) ) { UrlPatternDescriptor urlPatternDescriptor = createUrlPattern ( urlPatternType , store ) ; servletMappingDescriptor . getUrlPatterns ( ) . add ( urlPatternDescriptor ) ; } return servletMappingDescriptor ; } | Create a servlet mapping descriptor . |
14,054 | private SessionConfigDescriptor createSessionConfig ( SessionConfigType sessionConfigType , Store store ) { SessionConfigDescriptor sessionConfigDescriptor = store . create ( SessionConfigDescriptor . class ) ; XsdIntegerType sessionTimeout = sessionConfigType . getSessionTimeout ( ) ; if ( sessionTimeout != null ) { sessionConfigDescriptor . setSessionTimeout ( sessionTimeout . getValue ( ) . intValue ( ) ) ; } return sessionConfigDescriptor ; } | Create a session config descriptor . |
14,055 | public void finish ( ) throws IOException { int lastBlockSize = ( int ) ( byteCount % blockSize ) ; if ( lastBlockSize != 0 ) { while ( lastBlockSize < blockSize ) { out . write ( padding ) ; byteCount ++ ; lastBlockSize ++ ; } } out . flush ( ) ; } | Pads and flushes without closing the underlying stream . |
14,056 | private void detectFileChange ( ) throws IOException { checkClosed ( ) ; assert Thread . holdsLock ( filePosLock ) ; while ( ! file . exists ( ) ) { try { System . err . println ( "File not found, waiting: " + file . getPath ( ) ) ; Thread . sleep ( pollInterval ) ; } catch ( InterruptedException e ) { InterruptedIOException newExc = new InterruptedIOException ( e . getMessage ( ) ) ; newExc . initCause ( e ) ; throw newExc ; } checkClosed ( ) ; } long fileLen = file . length ( ) ; if ( fileLen < filePos ) filePos = 0 ; } | Checks the current position in the file . Detects if the file has changed in length . If closed throws an exception . If file doesn t exist waits until it does exist . |
14,057 | protected void processSynAckPacket ( Packet packet ) { String serverIp = packet . getSrcIpAddr ( ) ; int serverPort = packet . getSrcPort ( ) ; String clientIp = packet . getDestIpAddr ( ) ; int clientPort = packet . getDestPort ( ) ; String clientId = makeClientId ( clientIp , clientPort ) ; TcpServerScript serverFragmentWriter = scriptFragments . get ( clientId ) ; if ( serverFragmentWriter == null ) { serverFragmentWriter = new TcpServerScript ( emitterFactory . getRptScriptEmitter ( OUTPUT_TYPE , "tcp-server-" + serverIp + "-" + serverPort + "-client-" + clientIp + "-" + clientPort + "-ServerSide" ) ) ; } else if ( serverFragmentWriter . getState ( ) != ScriptState . CLOSED ) { throw new RptScriptsCreatorFailureException ( "Attempting to open already opened tcp connection from server composer:" + clientId ) ; } serverFragmentWriter . writeAccept ( serverIp , serverPort , packet ) ; scriptFragments . put ( clientId , serverFragmentWriter ) ; } | Processes the syn - ack packet which notes the start of tcp conversation |
14,058 | protected void processSynAckPacket ( Packet packet ) { Integer clientPort = packet . getDestPort ( ) ; Integer serverPort = packet . getSrcPort ( ) ; String serverIp = packet . getSrcIpAddr ( ) ; TcpClientScript scriptFragmentWriter = scripts . get ( clientPort ) ; if ( scriptFragmentWriter == null ) { scriptFragmentWriter = new TcpClientScript ( emitterFactory . getRptScriptEmitter ( OUTPUT_TYPE , "tcp-server-" + serverIp + "-" + serverPort + "-client-" + ipaddress + "-" + clientPort + "-ClientSide" ) ) ; } else if ( scriptFragmentWriter . getState ( ) != ScriptState . CLOSED ) { throw new RptScriptsCreatorFailureException ( "Attempting to open already opened tcp connection from client port:" + clientPort ) ; } scriptFragmentWriter . writeConnect ( serverIp , serverPort , packet ) ; scripts . put ( clientPort , scriptFragmentWriter ) ; } | Process a connection packet which is read as an syn - ack |
14,059 | public byte [ ] readBuffer ( final ChannelBuffer buffer ) { int len = getLength ( ) ; byte [ ] matched = new byte [ len ] ; buffer . readBytes ( matched ) ; return matched ; } | Read the data into an array of bytes |
14,060 | public static String randomizeLetterCase ( String text ) { StringBuilder result = new StringBuilder ( ) ; for ( int i = 0 ; i < text . length ( ) ; i ++ ) { char c = text . charAt ( i ) ; if ( RANDOM . nextBoolean ( ) ) { c = toUpperCase ( c ) ; } else { c = toLowerCase ( c ) ; } result . append ( c ) ; } return result . toString ( ) ; } | Takes a string and randomizes which letters in the text are upper or lower case |
14,061 | public Configuration visit ( AstConnectNode connectNode , State state ) { state . readUnmasker = Masker . IDENTITY_MASKER ; state . writeMasker = Masker . IDENTITY_MASKER ; state . pipelineAsMap = new LinkedHashMap < > ( ) ; for ( AstStreamableNode streamable : connectNode . getStreamables ( ) ) { streamable . accept ( this , state ) ; } String handlerName = String . format ( "completion#%d" , state . pipelineAsMap . size ( ) + 1 ) ; CompletionHandler completionHandler = new CompletionHandler ( ) ; completionHandler . setRegionInfo ( connectNode . getRegionInfo ( ) ) ; state . pipelineAsMap . put ( handlerName , completionHandler ) ; String awaitName = connectNode . getAwaitName ( ) ; Barrier awaitBarrier = null ; if ( awaitName != null ) { awaitBarrier = state . lookupBarrier ( awaitName ) ; } final ChannelPipeline pipeline = pipelineFromMap ( state . pipelineAsMap ) ; ChannelPipelineFactory pipelineFactory = new ChannelPipelineFactory ( ) { private int numCalled ; public ChannelPipeline getPipeline ( ) { if ( numCalled ++ != 0 ) { throw new RobotException ( "getPipeline called more than once" ) ; } return pipeline ; } } ; Supplier < URI > locationResolver = connectNode . getLocation ( ) :: getValue ; OptionsResolver optionsResolver = new OptionsResolver ( connectNode . getOptions ( ) ) ; ClientBootstrapResolver clientResolver = new ClientBootstrapResolver ( bootstrapFactory , addressFactory , pipelineFactory , locationResolver , optionsResolver , awaitBarrier , connectNode . getRegionInfo ( ) ) ; state . configuration . getClientAndServerPipelines ( ) . add ( pipeline ) ; state . configuration . getClientResolvers ( ) . add ( clientResolver ) ; return state . configuration ; } | Creates the pipeline visits all streamable nodes and the creates the ClientBootstrap with the pipeline and remote address |
14,062 | protected void init ( Map stormConf , TopologyContext topologyContext ) { setId ( topologyContext . getThisComponentId ( ) ) ; try { method = inputSignature . findMethod ( beanType ) ; logger . info ( "{} uses {}" , this , method . toGenericString ( ) ) ; } catch ( ReflectiveOperationException e ) { throw new IllegalStateException ( "Unusable input signature" , e ) ; } if ( spring == null ) spring = SingletonApplicationContext . get ( stormConf , topologyContext ) ; spring . getBean ( beanType ) ; logger . debug ( "Bean lookup successful" ) ; } | Instantiates the non - serializable state . |
14,063 | protected Object [ ] invoke ( Object [ ] arguments ) throws InvocationTargetException , IllegalAccessException { Object returnValue = invoke ( method , arguments ) ; if ( ! scatterOutput ) { logger . trace ( "Using return as is" ) ; return new Object [ ] { returnValue } ; } if ( returnValue instanceof Object [ ] ) { logger . trace ( "Scatter array return" ) ; return ( Object [ ] ) returnValue ; } if ( returnValue instanceof Collection ) { logger . trace ( "Scatter collection return" ) ; return ( ( Collection ) returnValue ) . toArray ( ) ; } logger . debug ( "Scatter singleton return" ) ; return returnValue == null ? EMPTY_ARRAY : new Object [ ] { returnValue } ; } | Gets the bean invocation return entries . |
14,064 | protected Object invoke ( Method method , Object [ ] arguments ) throws InvocationTargetException , IllegalAccessException { logger . trace ( "Lookup for call {}" , method ) ; Object bean = spring . getBean ( beanType ) ; try { return method . invoke ( bean , arguments ) ; } catch ( IllegalArgumentException e ) { StringBuilder msg = new StringBuilder ( method . toGenericString ( ) ) ; msg . append ( " invoked with incompatible arguments:" ) ; for ( Object a : arguments ) { msg . append ( ' ' ) ; if ( a == null ) msg . append ( "null" ) ; else msg . append ( a . getClass ( ) . getName ( ) ) ; } logger . error ( msg . toString ( ) ) ; throw e ; } } | Gets the bean invocation return value . |
14,065 | public void setOutputBinding ( Map < String , String > value ) { outputBinding . clear ( ) ; outputBindingDefinitions . clear ( ) ; for ( Map . Entry < String , String > entry : value . entrySet ( ) ) putOutputBinding ( entry . getKey ( ) , entry . getValue ( ) ) ; } | Sets expressions per field . |
14,066 | public static GSSContext createClientGSSContext ( String server ) { try { GSSManager manager = GSSManager . getInstance ( ) ; GSSName serverName = manager . createName ( server , null ) ; GSSContext context = manager . createContext ( serverName , krb5Oid , null , GSSContext . DEFAULT_LIFETIME ) ; context . requestMutualAuth ( true ) ; context . requestConf ( true ) ; context . requestInteg ( true ) ; return context ; } catch ( GSSException ex ) { throw new RuntimeException ( "Exception creating client GSSContext" , ex ) ; } } | Create a GSS Context from a clients point of view . |
14,067 | public static byte [ ] getClientToken ( GSSContext context ) { byte [ ] initialToken = new byte [ 0 ] ; if ( ! context . isEstablished ( ) ) { try { initialToken = context . initSecContext ( initialToken , 0 , initialToken . length ) ; return getTokenWithLengthPrefix ( initialToken ) ; } catch ( GSSException ex ) { throw new RuntimeException ( "Exception getting client token" , ex ) ; } } return null ; } | Create a token from a clients point of view for establishing a secure communication channel . This is a client side token so it needs to bootstrap the token creation . |
14,068 | public static boolean verifyMIC ( GSSContext context , MessageProp prop , byte [ ] message , byte [ ] mic ) { try { context . verifyMIC ( mic , 0 , mic . length , message , 0 , message . length , prop ) ; return true ; } catch ( GSSException ex ) { throw new RuntimeException ( "Exception verifying mic" , ex ) ; } } | Verify a message integrity check sent by a peer . If the MIC correctly identifies the message then the peer knows that the remote peer correctly received the message . |
14,069 | public static GSSContext createServerGSSContext ( ) { System . out . println ( "createServerGSSContext()..." ) ; try { final GSSManager manager = GSSManager . getInstance ( ) ; GSSCredential serverCreds ; try { serverCreds = Subject . doAs ( new Subject ( ) , new PrivilegedExceptionAction < GSSCredential > ( ) { public GSSCredential run ( ) throws GSSException { return manager . createCredential ( null , GSSCredential . INDEFINITE_LIFETIME , krb5Oid , GSSCredential . ACCEPT_ONLY ) ; } } ) ; } catch ( PrivilegedActionException e ) { throw new RuntimeException ( "Exception creating server credentials" , e ) ; } GSSContext retVal = manager . createContext ( serverCreds ) ; System . out . println ( "createServerGSSContext(), context: " + retVal ) ; return retVal ; } catch ( GSSException ex ) { System . out . println ( "createServerGSSContext(), finished with exception" ) ; throw new RuntimeException ( "Exception creating server GSSContext" , ex ) ; } } | Create a GSS Context not tied to any server name . Peers acting as a server create their context this way . |
14,070 | public static boolean acceptClientToken ( GSSContext context , byte [ ] token ) { try { if ( ! context . isEstablished ( ) ) { byte [ ] nextToken = context . acceptSecContext ( token , 0 , token . length ) ; return nextToken == null ; } return true ; } catch ( GSSException ex ) { throw new RuntimeException ( "Exception accepting client token" , ex ) ; } } | Accept a client token to establish a secure communication channel . |
14,071 | public static byte [ ] generateMIC ( GSSContext context , MessageProp prop , byte [ ] message ) { try { prop . setQOP ( 0 ) ; byte [ ] initialToken = context . getMIC ( message , 0 , message . length , prop ) ; return getTokenWithLengthPrefix ( initialToken ) ; } catch ( GSSException ex ) { throw new RuntimeException ( "Exception generating MIC for message" , ex ) ; } } | Generate a message integrity check for a given received message . |
14,072 | public Packet getNextPacket ( ) { Packet parsedPacket = parseNextPacketFromPdml ( ) ; if ( parsedPacket == null ) { return null ; } parsedPacket = addTcpdumpInfoToPacket ( parsedPacket ) ; return parsedPacket ; } | Returns the next Packet that can be parsed or null if all packets have been read |
14,073 | private Packet addTcpdumpInfoToPacket ( Packet parsedPacket ) { int packetSize = parsedPacket . getPacketSize ( ) ; tcpdumpReader . readNewPacket ( packetSize ) ; if ( parsedPacket . isTcp ( ) ) { int payloadSize = parsedPacket . getTcpPayloadSize ( ) ; int payloadStart = parsedPacket . getTcpPayloadStart ( ) ; parsedPacket . setTcpPayload ( tcpdumpReader . getPayload ( payloadStart , payloadSize ) ) ; } tcpdumpReader . packetReadComplete ( ) ; return parsedPacket ; } | Adds tcpdump info onto packet parsed from pdml i . e . adds the packet payload for various protocols |
14,074 | private Packet parseNextPacketFromPdml ( ) { Packet currentPacket = null ; int eventType ; fieldStack . empty ( ) ; try { eventType = parser . getEventType ( ) ; while ( eventType != XmlPullParser . END_DOCUMENT ) { switch ( eventType ) { case XmlPullParser . START_TAG : if ( parser . getRawName ( ) . contains ( "packet" ) ) { currentPacket = setPacketProperties ( xppFactory . newStartTag ( ) ) ; } else if ( parser . getRawName ( ) . contains ( "proto" ) ) { currentPacket = setProtoProperties ( xppFactory . newStartTag ( ) , currentPacket ) ; } else if ( parser . getRawName ( ) . contains ( "field" ) ) { fieldStack . push ( "field" ) ; if ( protoStack . peek ( ) . equals ( "http" ) && currentPacket . isTcp ( ) ) { currentPacket = setHttpFieldProperties ( xppFactory . newStartTag ( ) , currentPacket ) ; } else { currentPacket = setFieldProperties ( xppFactory . newStartTag ( ) , currentPacket ) ; } } else { ; } break ; case XmlPullParser . END_TAG : if ( parser . getRawName ( ) . contains ( "packet" ) ) { eventType = parser . next ( ) ; return currentPacket ; } else if ( parser . getRawName ( ) . contains ( "proto" ) ) { protoStack . pop ( ) ; } else if ( parser . getRawName ( ) . contains ( "field" ) ) { fieldStack . pop ( ) ; } default : } eventType = parser . next ( ) ; } return null ; } catch ( XmlPullParserException e ) { e . printStackTrace ( ) ; throw new ParserFailureException ( "Failed parsing pmdl " + e ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; throw new ParserFailureException ( "Failed reading parser.next " + e ) ; } } | Returns the Packet set with all properties that can be read from the pdml |
14,075 | public void connect ( ) throws Exception { URLConnection newConnection = location . openConnection ( ) ; newConnection . connect ( ) ; connection = newConnection ; InputStream bytesIn = connection . getInputStream ( ) ; CharsetDecoder decoder = UTF_8 . newDecoder ( ) ; textIn = new BufferedReader ( new InputStreamReader ( bytesIn , decoder ) ) ; } | Connects to the k3po server . |
14,076 | public void disconnect ( ) throws Exception { if ( connection != null ) { try { if ( connection instanceof Closeable ) { ( ( Closeable ) connection ) . close ( ) ; } else { try { connection . getInputStream ( ) . close ( ) ; } catch ( IOException e ) { } try { connection . getOutputStream ( ) . close ( ) ; } catch ( IOException e ) { } } } finally { connection = null ; } } } | Discoonects from the k3po server . |
14,077 | public void writeCommand ( Command command ) throws Exception { checkConnected ( ) ; switch ( command . getKind ( ) ) { case PREPARE : writeCommand ( ( PrepareCommand ) command ) ; break ; case START : writeCommand ( ( StartCommand ) command ) ; break ; case ABORT : writeCommand ( ( AbortCommand ) command ) ; break ; case AWAIT : writeCommand ( ( AwaitCommand ) command ) ; break ; case NOTIFY : writeCommand ( ( NotifyCommand ) command ) ; break ; case CLOSE : writeCommand ( ( CloseCommand ) command ) ; break ; default : throw new IllegalArgumentException ( "Urecognized command kind: " + command . getKind ( ) ) ; } } | Writes a command to the wire . |
14,078 | public CommandEvent readEvent ( int timeout , TimeUnit unit ) throws Exception { checkConnected ( ) ; connection . setReadTimeout ( ( int ) unit . toMillis ( timeout ) ) ; CommandEvent event = null ; String eventType = textIn . readLine ( ) ; if ( Thread . interrupted ( ) ) { throw new InterruptedException ( "thread interrupted during blocking read" ) ; } if ( eventType != null ) { switch ( eventType ) { case PREPARED_EVENT : event = readPreparedEvent ( ) ; break ; case STARTED_EVENT : event = readStartedEvent ( ) ; break ; case ERROR_EVENT : event = readErrorEvent ( ) ; break ; case FINISHED_EVENT : event = readFinishedEvent ( ) ; break ; case NOTIFIED_EVENT : event = readNotifiedEvent ( ) ; break ; default : throw new IllegalStateException ( "Invalid protocol frame: " + eventType ) ; } } return event ; } | Reads a command event from the wire . |
14,079 | private void writeEvent ( final ChannelHandlerContext ctx , final Object message ) { if ( isFinishedSent ) return ; if ( message instanceof FinishedMessage ) isFinishedSent = true ; Channels . write ( ctx , Channels . future ( null ) , message ) ; } | will send no message after the FINISHED |
14,080 | public static void main ( String ... args ) throws Exception { Options options = createOptions ( ) ; try { Parser parser = new PosixParser ( ) ; CommandLine cmd = parser . parse ( options , args ) ; if ( cmd . hasOption ( "version" ) ) { System . out . println ( "Version: " + Launcher . class . getPackage ( ) . getImplementationVersion ( ) ) ; } String scriptPathEntries = cmd . getOptionValue ( "scriptpath" , "src/test/scripts" ) ; String [ ] scriptPathEntryArray = scriptPathEntries . split ( ";" ) ; List < URL > scriptUrls = new ArrayList < > ( ) ; for ( String scriptPathEntry : scriptPathEntryArray ) { File scriptEntryFilePath = new File ( scriptPathEntry ) ; scriptUrls . add ( scriptEntryFilePath . toURI ( ) . toURL ( ) ) ; } String controlURI = cmd . getOptionValue ( "control" ) ; if ( controlURI == null ) { controlURI = "tcp://localhost:11642" ; } boolean verbose = cmd . hasOption ( "verbose" ) ; URLClassLoader scriptLoader = new URLClassLoader ( scriptUrls . toArray ( new URL [ 0 ] ) ) ; RobotServer server = new RobotServer ( URI . create ( controlURI ) , verbose , scriptLoader ) ; server . start ( ) ; server . join ( ) ; } catch ( ParseException ex ) { HelpFormatter helpFormatter = new HelpFormatter ( ) ; helpFormatter . printHelp ( Launcher . class . getSimpleName ( ) , options , true ) ; } } | Main entry point to running K3PO . |
14,081 | public static FunctionMapper newFunctionMapper ( ) { ServiceLoader < FunctionMapperSpi > loader = loadFunctionMapperSpi ( ) ; ConcurrentMap < String , FunctionMapperSpi > functionMappers = new ConcurrentHashMap < > ( ) ; for ( FunctionMapperSpi functionMapperSpi : loader ) { String prefixName = functionMapperSpi . getPrefixName ( ) ; FunctionMapperSpi oldFunctionMapperSpi = functionMappers . putIfAbsent ( prefixName , functionMapperSpi ) ; if ( oldFunctionMapperSpi != null ) { throw new ELException ( String . format ( "Duplicate prefix function mapper: %s" , prefixName ) ) ; } } return new FunctionMapper ( functionMappers ) ; } | Creates a new Function Mapper . |
14,082 | public Method resolveFunction ( String prefix , String localName ) { FunctionMapperSpi functionMapperSpi = findFunctionMapperSpi ( prefix ) ; return functionMapperSpi . resolveFunction ( localName ) ; } | Resolves a Function via prefix and local name . |
14,083 | public byte [ ] getPayload ( int payloadStart , int payloadSize ) { byte [ ] payloadBuffer = new byte [ payloadSize ] ; System . arraycopy ( currentBuffer , payloadStart , payloadBuffer , 0 , payloadSize ) ; return payloadBuffer ; } | Returns a portion of the internal buffer |
14,084 | public static Config stormConfig ( Properties source ) { Config result = new Config ( ) ; logger . debug ( "Mapping declared types for Storm properties..." ) ; for ( Field field : result . getClass ( ) . getDeclaredFields ( ) ) { if ( field . getType ( ) != String . class ) continue ; if ( field . getName ( ) . endsWith ( CONFIGURATION_TYPE_FIELD_SUFFIX ) ) continue ; try { String key = field . get ( result ) . toString ( ) ; String entry = source . getProperty ( key ) ; if ( entry == null ) continue ; String typeFieldName = field . getName ( ) + CONFIGURATION_TYPE_FIELD_SUFFIX ; Field typeField = result . getClass ( ) . getDeclaredField ( typeFieldName ) ; Object type = typeField . get ( result ) ; logger . trace ( "Detected key '{}' as: {}" , key , field ) ; Object value = null ; if ( type == String . class ) value = entry ; if ( type == ConfigValidation . IntegerValidator . class || type == ConfigValidation . PowerOf2Validator . class ) value = Integer . valueOf ( entry ) ; if ( type == Boolean . class ) value = Boolean . valueOf ( entry ) ; if ( type == ConfigValidation . StringOrStringListValidator . class ) value = asList ( entry . split ( LIST_CONTINUATION_PATTERN ) ) ; if ( value == null ) { logger . warn ( "No parser for key '{}' type: {}" , key , typeField ) ; value = entry ; } result . put ( key , value ) ; } catch ( ReflectiveOperationException e ) { logger . debug ( "Interpretation failure on {}: {}" , field , e ) ; } } for ( Map . Entry < Object , Object > e : source . entrySet ( ) ) { String key = e . getKey ( ) . toString ( ) ; if ( result . containsKey ( key ) ) continue ; result . put ( key , e . getValue ( ) ) ; } return result ; } | Applies type conversion where needed . |
14,085 | public static FunctionSignature valueOf ( String serial ) { int paramStart = serial . indexOf ( "(" ) ; int paramEnd = serial . indexOf ( ")" ) ; if ( paramStart < 0 || paramEnd != serial . length ( ) - 1 ) throw new IllegalArgumentException ( "Malformed method signature: " + serial ) ; String function = serial . substring ( 0 , paramStart ) . trim ( ) ; String arguments = serial . substring ( paramStart + 1 , paramEnd ) ; StringTokenizer tokenizer = new StringTokenizer ( arguments , ", " ) ; String [ ] names = new String [ tokenizer . countTokens ( ) ] ; for ( int i = 0 ; i < names . length ; ++ i ) names [ i ] = tokenizer . nextToken ( ) ; return new FunctionSignature ( function , names ) ; } | Parses a signature . |
14,086 | public Method findMethod ( Class < ? > type ) throws ReflectiveOperationException { Method match = null ; for ( Method option : type . getDeclaredMethods ( ) ) { if ( ! getFunction ( ) . equals ( option . getName ( ) ) ) continue ; Class < ? > [ ] parameters = option . getParameterTypes ( ) ; if ( parameters . length != getArguments ( ) . length ) continue ; if ( match != null ) { if ( refines ( option , match ) ) continue ; if ( ! refines ( match , option ) ) throw ambiguity ( match , option ) ; } match = option ; } Class < ? > [ ] parents = { type . getSuperclass ( ) } ; if ( type . isInterface ( ) ) parents = type . getInterfaces ( ) ; for ( Class < ? > parent : parents ) { if ( parent == null ) continue ; try { Method superMatch = findMethod ( parent ) ; if ( match == null ) { match = superMatch ; continue ; } if ( ! refines ( superMatch , match ) ) throw ambiguity ( match , superMatch ) ; } catch ( NoSuchMethodException ignored ) { } } if ( match == null ) { String fmt = "No method %s#%s with %d parameters" ; String msg = format ( fmt , type , getFunction ( ) , getArguments ( ) . length ) ; throw new NoSuchMethodException ( msg ) ; } match . setAccessible ( true ) ; return match ; } | Gets a method match . |
14,087 | public static Modifiers getInstance ( int bitmask ) { switch ( bitmask ) { case 0 : return NONE ; case Modifier . PUBLIC : return PUBLIC ; case Modifier . PUBLIC | Modifier . ABSTRACT : return PUBLIC_ABSTRACT ; case Modifier . PUBLIC | Modifier . STATIC : return PUBLIC_STATIC ; case Modifier . PROTECTED : return PROTECTED ; case Modifier . PRIVATE : return PRIVATE ; } return new Modifiers ( bitmask ) ; } | Returns a Modifiers object with the given bitmask . |
14,088 | public Result < V > [ ] getMatches ( String lookup , int limit ) { int strLen = lookup . length ( ) ; char [ ] chars = new char [ strLen + 1 ] ; lookup . getChars ( 0 , strLen , chars , 0 ) ; chars [ strLen ] = '\uffff' ; List resultList = new ArrayList ( ) ; fillMatchResults ( chars , limit , resultList ) ; return ( Result [ ] ) resultList . toArray ( new Result [ resultList . size ( ) ] ) ; } | Returns an empty array if no matches . |
14,089 | public synchronized < U extends T > U put ( U obj ) { if ( obj == null ) { return null ; } Entry < T > [ ] entries = mEntries ; int hash = hashCode ( obj ) ; int index = ( hash & 0x7fffffff ) % entries . length ; for ( Entry < T > e = entries [ index ] , prev = null ; e != null ; e = e . mNext ) { T iobj = e . get ( ) ; if ( iobj == null ) { if ( prev == null ) { entries [ index ] = e . mNext ; } else { prev . mNext = e . mNext ; } mSize -- ; } else if ( e . mHash == hash && obj . getClass ( ) == iobj . getClass ( ) && equals ( obj , iobj ) ) { return ( U ) iobj ; } else { prev = e ; } } if ( mSize >= mThreshold ) { cleanup ( ) ; if ( mSize >= mThreshold ) { rehash ( ) ; entries = mEntries ; index = ( hash & 0x7fffffff ) % entries . length ; } } entries [ index ] = new Entry < T > ( this , obj , hash , entries [ index ] ) ; mSize ++ ; return obj ; } | Pass in a candidate canonical object and get a unique instance from this set . The returned object will always be of the same type as that passed in . If the object passed in does not equal any object currently in the set it will be added to the set becoming canonical . |
14,090 | public static void fire ( Throwable t ) { if ( t != null ) { if ( t instanceof RuntimeException ) { throw ( RuntimeException ) t ; } if ( t instanceof Error ) { throw ( Error ) t ; } ThrowUnchecked impl = cImpl ; if ( impl == null ) { synchronized ( ThrowUnchecked . class ) { impl = cImpl ; if ( impl == null ) { cImpl = impl = AccessController . doPrivileged ( new PrivilegedAction < ThrowUnchecked > ( ) { public ThrowUnchecked run ( ) { return generateImpl ( ) ; } } ) ; } } } impl . doFire ( t ) ; } } | Throws the given exception even though it may be checked . This method only returns normally if the exception is null . |
14,091 | public static void fireFirstDeclared ( Throwable t , Class ... declaredTypes ) { Throwable cause = t ; while ( cause != null ) { cause = cause . getCause ( ) ; if ( cause == null ) { break ; } if ( declaredTypes != null ) { for ( Class declaredType : declaredTypes ) { if ( declaredType . isInstance ( cause ) ) { fire ( cause ) ; } } } if ( cause instanceof RuntimeException ) { throw ( RuntimeException ) cause ; } if ( cause instanceof Error ) { throw ( Error ) cause ; } } throw new UndeclaredThrowableException ( t ) ; } | Throws the either the original exception or the first found cause if it matches one of the given declared types or is unchecked . Otherwise the original exception is thrown as an UndeclaredThrowableException . This method only returns normally if the exception is null . |
14,092 | public static void fireCause ( Throwable t ) { if ( t != null ) { Throwable cause = t . getCause ( ) ; if ( cause == null ) { cause = t ; } fire ( cause ) ; } } | Throws the cause of the given exception even though it may be checked . If the cause is null then the original exception is thrown . This method only returns normally if the exception is null . |
14,093 | public static void fireDeclaredCause ( Throwable t , Class ... declaredTypes ) { if ( t != null ) { Throwable cause = t . getCause ( ) ; if ( cause == null ) { cause = t ; } fireDeclared ( cause , declaredTypes ) ; } } | Throws the cause of the given exception if it is unchecked or an instance of any of the given declared types . Otherwise it is thrown as an UndeclaredThrowableException . If the cause is null then the original exception is thrown . This method only returns normally if the exception is null . |
14,094 | public static void fireFirstDeclaredCause ( Throwable t , Class ... declaredTypes ) { Throwable cause = t ; while ( cause != null ) { cause = cause . getCause ( ) ; if ( cause == null ) { break ; } if ( declaredTypes != null ) { for ( Class declaredType : declaredTypes ) { if ( declaredType . isInstance ( cause ) ) { fire ( cause ) ; } } } if ( cause instanceof RuntimeException ) { throw ( RuntimeException ) cause ; } if ( cause instanceof Error ) { throw ( Error ) cause ; } } fireDeclaredCause ( t , declaredTypes ) ; } | Throws the first found cause that matches one of the given declared types or is unchecked . Otherwise the immediate cause is thrown as an UndeclaredThrowableException . If the immediate cause is null then the original exception is thrown . This method only returns normally if the exception is null . |
14,095 | public static void fireRootCause ( Throwable t ) { Throwable root = t ; while ( root != null ) { Throwable cause = root . getCause ( ) ; if ( cause == null ) { break ; } root = cause ; } fire ( root ) ; } | Throws the root cause of the given exception even though it may be checked . If the root cause is null then the original exception is thrown . This method only returns normally if the exception is null . |
14,096 | public static void fireDeclaredRootCause ( Throwable t , Class ... declaredTypes ) { Throwable root = t ; while ( root != null ) { Throwable cause = root . getCause ( ) ; if ( cause == null ) { break ; } root = cause ; } fireDeclared ( root , declaredTypes ) ; } | Throws the root cause of the given exception if it is unchecked or an instance of any of the given declared types . Otherwise it is thrown as an UndeclaredThrowableException . If the root cause is null then the original exception is thrown . This method only returns normally if the exception is null . |
14,097 | public void setCodeBuffer ( CodeBuffer code ) { mCodeBuffer = code ; mOldLineNumberTable = mLineNumberTable ; mOldLocalVariableTable = mLocalVariableTable ; mOldStackMapTable = mStackMapTable ; mAttributes . remove ( mLineNumberTable ) ; mAttributes . remove ( mLocalVariableTable ) ; mAttributes . remove ( mStackMapTable ) ; mLineNumberTable = null ; mLocalVariableTable = null ; mStackMapTable = null ; } | As a side effect of calling this method new line number and local variable tables are created . |
14,098 | public void localVariableUse ( LocalVariable localVar ) { if ( mLocalVariableTable == null ) { addAttribute ( new LocalVariableTableAttr ( getConstantPool ( ) ) ) ; } mLocalVariableTable . addEntry ( localVar ) ; } | Indicate a local variable s use information be recorded in the ClassFile as a debugging aid . If the LocalVariable doesn t provide both a start and end location then its information is not recorded . This method should be called at most once per LocalVariable instance . |
14,099 | private static RuntimeClassFile createClassFile ( ) { RuntimeClassFile cf = new RuntimeClassFile ( ) ; cf . addDefaultConstructor ( ) ; TypeDesc [ ] params = new TypeDesc [ ] { TypeDesc . STRING . toArrayType ( ) } ; MethodInfo mi = cf . addMethod ( Modifiers . PUBLIC_STATIC , "main" , null , params ) ; CodeBuilder b = new CodeBuilder ( mi ) ; TypeDesc bufferedReader = TypeDesc . forClass ( "java.io.BufferedReader" ) ; TypeDesc inputStreamReader = TypeDesc . forClass ( "java.io.InputStreamReader" ) ; TypeDesc inputStream = TypeDesc . forClass ( "java.io.InputStream" ) ; TypeDesc reader = TypeDesc . forClass ( "java.io.Reader" ) ; TypeDesc stringBuffer = TypeDesc . forClass ( "java.lang.StringBuffer" ) ; TypeDesc printStream = TypeDesc . forClass ( "java.io.PrintStream" ) ; LocalVariable in = b . createLocalVariable ( "in" , bufferedReader ) ; LocalVariable name = b . createLocalVariable ( "name" , TypeDesc . STRING ) ; b . newObject ( bufferedReader ) ; b . dup ( ) ; b . newObject ( inputStreamReader ) ; b . dup ( ) ; b . loadStaticField ( "java.lang.System" , "in" , inputStream ) ; params = new TypeDesc [ ] { inputStream } ; b . invokeConstructor ( inputStreamReader . getRootName ( ) , params ) ; params = new TypeDesc [ ] { reader } ; b . invokeConstructor ( bufferedReader . getRootName ( ) , params ) ; b . storeLocal ( in ) ; Label tryStart = b . createLabel ( ) . setLocation ( ) ; b . loadStaticField ( "java.lang.System" , "out" , printStream ) ; b . loadConstant ( "Please enter your name> " ) ; params = new TypeDesc [ ] { TypeDesc . STRING } ; b . invokeVirtual ( printStream , "print" , null , params ) ; b . loadLocal ( in ) ; b . invokeVirtual ( bufferedReader , "readLine" , TypeDesc . STRING , null ) ; b . storeLocal ( name ) ; Label printResponse = b . createLabel ( ) ; b . branch ( printResponse ) ; Label tryEnd = b . createLabel ( ) . setLocation ( ) ; b . exceptionHandler ( tryStart , tryEnd , "java.io.IOException" ) ; b . returnVoid ( ) ; printResponse . setLocation ( ) ; b . loadStaticField ( "java.lang.System" , "out" , printStream ) ; b . newObject ( stringBuffer ) ; b . dup ( ) ; b . loadConstant ( "Hello, " ) ; params = new TypeDesc [ ] { TypeDesc . STRING } ; b . invokeConstructor ( stringBuffer , params ) ; b . loadLocal ( name ) ; b . invokeVirtual ( stringBuffer , "append" , stringBuffer , params ) ; b . invokeVirtual ( stringBuffer , "toString" , TypeDesc . STRING , null ) ; params = new TypeDesc [ ] { TypeDesc . STRING } ; b . invokeVirtual ( printStream , "println" , null , params ) ; b . returnVoid ( ) ; return cf ; } | Creates a ClassFile which defines a simple interactive HelloWorld class . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.