idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
137,400 | protected static boolean appendParams ( StringBuilder SB , Object optParam , List < String > finishedParams , boolean alreadyAppended ) { if ( optParam != null ) { if ( optParam instanceof String ) { List < String > nameValuePairs = StringUtility . splitString ( ( String ) optParam , ' ' ) ; int len = nameValuePairs . size ( ) ; for ( int i = 0 ; i < len ; i ++ ) { SB . append ( alreadyAppended ? ' ' : ' ' ) ; String S = nameValuePairs . get ( i ) ; int pos = S . indexOf ( ' ' ) ; if ( pos == - 1 ) { SB . append ( S ) ; alreadyAppended = true ; } else { String name = S . substring ( 0 , pos ) ; if ( ! finishedParams . contains ( name ) ) { SB . append ( S ) ; finishedParams . add ( name ) ; alreadyAppended = true ; } } } } else if ( optParam instanceof String [ ] ) { String [ ] SA = ( String [ ] ) optParam ; int len = SA . length ; for ( int c = 0 ; c < len ; c += 2 ) { String name = SA [ c ] ; if ( ! finishedParams . contains ( name ) ) { SB . append ( alreadyAppended ? ' ' : ' ' ) . append ( name ) . append ( ' ' ) . append ( SA [ c + 1 ] ) ; finishedParams . add ( name ) ; alreadyAppended = true ; } } } else throw new IllegalArgumentException ( "Unsupported type for optParam: " + optParam . getClass ( ) . getName ( ) ) ; } return alreadyAppended ; } | Appends the parameters to a URL . Parameters should already be URL encoded but not XML encoded . | 377 | 19 |
137,401 | public String getURL ( String classAndParams ) throws IOException , SQLException { String className , params ; int pos = classAndParams . indexOf ( ' ' ) ; if ( pos == - 1 ) { className = classAndParams ; params = null ; } else { className = classAndParams . substring ( 0 , pos ) ; params = classAndParams . substring ( pos + 1 ) ; } return getURL ( className , params ) ; } | Gets a relative URL from a String containing a classname and optional parameters . Parameters should already be URL encoded but not XML encoded . | 107 | 27 |
137,402 | public String getURL ( String classname , String params ) throws IOException , SQLException { try { Class < ? extends WebPage > clazz = Class . forName ( classname ) . asSubclass ( WebPage . class ) ; return getURL ( clazz , params ) ; } catch ( ClassNotFoundException err ) { throw new IOException ( "Unable to load class: " + classname , err ) ; } } | Gets a relative URL given its classname and optional parameters . Parameters should already be URL encoded but not XML encoded . | 94 | 24 |
137,403 | public String getURL ( String url , Object optParam , boolean keepSettings ) throws IOException { StringBuilder SB = new StringBuilder ( ) ; SB . append ( url ) ; List < String > finishedParams = new SortedArrayList <> ( ) ; boolean alreadyAppended = appendParams ( SB , optParam , finishedParams , false ) ; if ( keepSettings ) appendSettings ( finishedParams , alreadyAppended , SB ) ; return SB . toString ( ) ; } | Gets the context - relative URL optionally with the settings embedded . Parameters should already be URL encoded but not XML encoded . | 104 | 24 |
137,404 | public String getURL ( WebPage page ) throws IOException , SQLException { return getURL ( page , ( Object ) null ) ; } | Gets the context - relative URL to a web page . | 31 | 12 |
137,405 | public String getURL ( String url , Object optParam ) throws IOException { return getURL ( url , optParam , true ) ; } | Gets the URL String with the given parameters embedded keeping the current settings . | 29 | 15 |
137,406 | public boolean isLynx ( ) { if ( ! isLynxDone ) { String agent = req . getHeader ( "user-agent" ) ; isLynx = agent != null && agent . toLowerCase ( Locale . ROOT ) . contains ( "lynx" ) ; isLynxDone = true ; } return isLynx ; } | Determines if the request is for a Lynx browser | 75 | 12 |
137,407 | public boolean isBlackBerry ( ) { if ( ! isBlackBerryDone ) { String agent = req . getHeader ( "user-agent" ) ; isBlackBerry = agent != null && agent . startsWith ( "BlackBerry" ) ; isBlackBerryDone = true ; } return isBlackBerry ; } | Determines if the request is for a BlackBerry browser | 65 | 11 |
137,408 | public boolean isLinux ( ) { if ( ! isLinuxDone ) { String agent = req . getHeader ( "user-agent" ) ; isLinux = agent == null || agent . toLowerCase ( Locale . ROOT ) . contains ( "linux" ) ; isLinuxDone = true ; } return isLinux ; } | Determines if the request is for a Linux browser | 69 | 11 |
137,409 | public static String addParams ( String href , HttpParameters params , String encoding ) throws UnsupportedEncodingException { if ( params != null ) { StringBuilder sb = new StringBuilder ( href ) ; // First find any anchor and if has parameters int anchorStart = href . lastIndexOf ( ' ' ) ; String anchor ; boolean hasQuestion ; if ( anchorStart == - 1 ) { anchor = null ; hasQuestion = href . lastIndexOf ( ' ' ) != - 1 ; } else { anchor = href . substring ( anchorStart ) ; sb . setLength ( anchorStart ) ; hasQuestion = href . lastIndexOf ( ' ' , anchorStart - 1 ) != - 1 ; } for ( Map . Entry < String , List < String > > entry : params . getParameterMap ( ) . entrySet ( ) ) { String encodedName = URLEncoder . encode ( entry . getKey ( ) , encoding ) ; for ( String value : entry . getValue ( ) ) { if ( hasQuestion ) sb . append ( ' ' ) ; else { sb . append ( ' ' ) ; hasQuestion = true ; } sb . append ( encodedName ) ; assert value != null : "null values no longer supported to be consistent with servlet environment" ; sb . append ( ' ' ) . append ( URLEncoder . encode ( value , encoding ) ) ; } } if ( anchor != null ) sb . append ( anchor ) ; href = sb . toString ( ) ; } return href ; } | Adds all of the parameters to a URL . | 327 | 9 |
137,410 | public static String toJSONString ( Object o ) { try { return objectMapper . writer ( ) . without ( SerializationFeature . INDENT_OUTPUT ) . writeValueAsString ( o ) ; } catch ( JsonProcessingException e ) { throw new RuntimeException ( e ) ; } } | A not - pretty printed JSON string . Returns a portable JSON string . | 65 | 14 |
137,411 | final public void beginLightArea ( WebSiteRequest req , HttpServletResponse resp , ChainWriter out ) throws IOException { beginLightArea ( req , resp , out , null , false ) ; } | Begins a lighter colored area of the site . | 43 | 10 |
137,412 | private void makeNewFile ( ) throws IOException { String filename = prefix + ( files . size ( ) + 1 ) + suffix ; File file = new File ( parent , filename ) ; out = new FileOutputStream ( file ) ; bytesOut = 0 ; files . add ( file ) ; } | All accesses are already synchronized . | 62 | 7 |
137,413 | public static FileMessage decode ( String encodedMessage , File file ) throws IOException { return decode ( encodedMessage . isEmpty ( ) ? ByteArray . EMPTY_BYTE_ARRAY : new ByteArray ( Base64Coder . decode ( encodedMessage ) ) , file ) ; } | base - 64 decodes the message into the provided file . | 60 | 12 |
137,414 | @ Deprecated public static FileMessage decode ( String encodedMessage ) throws IOException { return decode ( encodedMessage . isEmpty ( ) ? ByteArray . EMPTY_BYTE_ARRAY : new ByteArray ( Base64Coder . decode ( encodedMessage ) ) ) ; } | base - 64 decodes the message into a temp file . | 58 | 12 |
137,415 | public static FileMessage decode ( ByteArray encodedMessage , File file ) throws IOException { try ( OutputStream out = new FileOutputStream ( file ) ) { out . write ( encodedMessage . array , 0 , encodedMessage . size ) ; } return new FileMessage ( true , file ) ; } | Restores this message into the provided file . | 62 | 9 |
137,416 | @ Deprecated public static FileMessage decode ( ByteArray encodedMessage ) throws IOException { File file = File . createTempFile ( "FileMessage." , null ) ; file . deleteOnExit ( ) ; return decode ( encodedMessage , file ) ; } | Restores this message into a temp file . | 53 | 9 |
137,417 | public static Registry createRegistry ( int port , RMIClientSocketFactory csf , RMIServerSocketFactory ssf ) throws RemoteException { synchronized ( registryCache ) { Integer portObj = port ; Registry registry = registryCache . get ( portObj ) ; if ( registry == null ) { registry = LocateRegistry . createRegistry ( port , csf , ssf ) ; registryCache . put ( portObj , registry ) ; } return registry ; } } | Creates a registry or returns the registry that is already using the port . | 99 | 15 |
137,418 | final public void close ( ) { List < C > connsToClose ; synchronized ( poolLock ) { // Prevent any new connections isClosed = true ; // Find any connections that are available and open connsToClose = new ArrayList <> ( availableConnections . size ( ) ) ; for ( PooledConnection < C > availableConnection : availableConnections ) { synchronized ( availableConnection ) { C conn = availableConnection . connection ; if ( conn != null ) { availableConnection . connection = null ; connsToClose . add ( conn ) ; } } } poolLock . notifyAll ( ) ; } // Close all of the connections for ( C conn : connsToClose ) { try { close ( conn ) ; } catch ( Exception err ) { logger . log ( Level . WARNING , null , err ) ; } } } | Shuts down the pool exceptions during close will be logged as a warning and not thrown . | 175 | 18 |
137,419 | final public int getConnectionCount ( ) { int total = 0 ; synchronized ( poolLock ) { for ( PooledConnection < C > pooledConnection : allConnections ) { if ( pooledConnection . connection != null ) total ++ ; } } return total ; } | Gets the number of connections currently connected . | 54 | 9 |
137,420 | private void release ( PooledConnection < C > pooledConnection ) { long currentTime = System . currentTimeMillis ( ) ; long useTime ; synchronized ( pooledConnection ) { pooledConnection . releaseTime = currentTime ; useTime = currentTime - pooledConnection . startTime ; if ( useTime > 0 ) pooledConnection . totalTime . addAndGet ( useTime ) ; pooledConnection . allocateStackTrace = null ; } // Remove from the pool synchronized ( poolLock ) { try { if ( busyConnections . remove ( pooledConnection ) ) availableConnections . add ( pooledConnection ) ; } finally { poolLock . notify ( ) ; } } } | Releases a PooledConnection . It is safe to release it multiple times . The connection should have either been closed or reset before this is called because this makes the connection available for the next request . | 138 | 40 |
137,421 | 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 . | 52 | 12 |
137,422 | @ Override 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 ; // Find any connections that are available and been idle too long 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 // Idle too long || ( maxConnectionAge != UNLIMITED_MAX_CONNECTION_AGE && ( availableConnection . createTime > time // System time reset? || ( time - availableConnection . createTime ) >= maxConnectionAge // Max connection age reached ) ) ) { availableConnection . connection = null ; connsToClose . add ( conn ) ; } } } } } // Close all of the connections 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 . | 357 | 48 |
137,423 | public static byte [ ] md5 ( File file ) throws IOException { try ( InputStream in = new FileInputStream ( file ) ) { return md5 ( in ) ; } } | Gets the MD5 hashcode of a file . | 39 | 11 |
137,424 | 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 ) { // Intentional empty block } } finally { BufferManager . release ( trashBuffer , false ) ; } return md5in . hash ( ) ; } | Gets the MD5 hashcode of an input stream . | 107 | 12 |
137,425 | 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 . | 38 | 33 |
137,426 | public File getFile ( ) throws IllegalStateException { File f = tempFile ; if ( f == null ) throw new IllegalStateException ( ) ; return f ; } | Gets the temp file . | 35 | 6 |
137,427 | 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 . | 181 | 10 |
137,428 | @ Override 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 . | 52 | 16 |
137,429 | private void saveProperties ( ) { assert Thread . holdsLock ( properties ) ; try { // Create a properties instance that sorts the output by keys (case-insensitive) Properties writer = new Properties ( ) { private static final long serialVersionUID = 6953022173340009928L ; @ Override 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 { // Write any comments from when file was read if ( sourceFileComments != null ) { for ( String line : sourceFileComments ) { out . write ( line . getBytes ( propertiesCharset ) ) ; out . write ( EOL . getBytes ( propertiesCharset ) ) ; } } // Wrap to skip any comments generated by Properties code 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 . | 353 | 23 |
137,430 | @ Override 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 <> ( ) ; // Could this be a simple sequence like TopologicalSorter? Any benefit? 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 . | 127 | 17 |
137,431 | @ Override 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 | 90 | 3 |
137,432 | @ Override 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 . | 49 | 7 |
137,433 | @ Override public void endContentLine ( ChainWriter out , WebSiteRequest req , HttpServletResponse resp , int rowspan , boolean endsInternal ) { out . print ( " </td>\n" + " </tr>\n" ) ; } | Ends one line of content . | 56 | 7 |
137,434 | 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 . | 91 | 19 |
137,435 | 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 . | 91 | 19 |
137,436 | 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 . | 85 | 19 |
137,437 | final public void Update ( String s ) { byte [ ] chars = s . getBytes ( ) ; // Changed on 2004-04-10 due to getBytes(int,int,char[],byte) being deprecated //byte chars[]; //chars = new byte[s.length()]; //s.getBytes(0, s.length(), chars, 0); Update ( chars , chars . length ) ; } | Update buffer with given string . | 88 | 6 |
137,438 | 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 . | 109 | 15 |
137,439 | 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 > ( ) { @ Override 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 ( ) { @ Override public Collection < ChildRef > getEdges ( Page page ) { return page . getChildRefs ( ) ; } } , new CapturePage . EdgeFilter ( ) { @ Override 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 . | 286 | 18 |
137,440 | 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 . | 64 | 34 |
137,441 | 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 . | 66 | 54 |
137,442 | 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 . | 50 | 39 |
137,443 | @ Override 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 . | 45 | 15 |
137,444 | @ Override 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 ) ; // Strip extension if will not leave empty 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 . | 221 | 23 |
137,445 | @ Override 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 ) { // Resource removed between calls to exists() and getLength() // fall-through to return filename } catch ( IOException e ) { throw new WrappedException ( e ) ; } } } return filename ; } throw new IllegalStateException ( "Path not set" ) ; } | The label is always the filename . | 328 | 7 |
137,446 | 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 . | 96 | 14 |
137,447 | 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 . | 92 | 9 |
137,448 | @ Override 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 . | 149 | 19 |
137,449 | 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 . | 155 | 11 |
137,450 | 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 . | 110 | 14 |
137,451 | 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 . | 113 | 23 |
137,452 | 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 . | 146 | 30 |
137,453 | 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 . | 121 | 28 |
137,454 | public Map < String , Object > getProperty ( ) { // TODO: If we have properties volatile, could do the null and frozen cases outside the synchronized block // TODO: Would this be faster? 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 . | 84 | 30 |
137,455 | 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 . | 60 | 8 |
137,456 | 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 { // Reset generator when duplicate found (this should be extremely rare) idGenerator . reset ( ) ; } } } } | Adds a child element to this node . | 172 | 8 |
137,457 | 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 . | 57 | 24 |
137,458 | public BufferResult getBody ( ) { BufferResult b = body ; if ( b == null ) return EmptyResult . getInstance ( ) ; return b ; } | Every node may potentially have HTML body . | 33 | 8 |
137,459 | 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 . | 66 | 14 |
137,460 | 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 ) ) { // Found match if ( matches == null ) matches = new ArrayList <> ( ) ; matches . add ( elementType . cast ( elem ) ) ; } else { // Look further down the tree matches = findTopLevelElementsRecurse ( elementType , elem , matches ) ; } } return matches ; } | Recursive component of findTopLevelElements . | 132 | 10 |
137,461 | 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 > ( ) { @ Override public Runnable createCall ( final SocketListener listener ) { return new Runnable ( ) { @ Override 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 . | 154 | 23 |
137,462 | @ Override 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 . | 64 | 14 |
137,463 | @ Override 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 . | 93 | 18 |
137,464 | @ Override 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 . | 48 | 9 |
137,465 | public boolean send ( ProbeTestRun testRun ) throws MalformedURLException { LOGGER . info ( "Connected to Probe Dock API at " + configuration . getServerConfiguration ( ) . getApiUrl ( ) ) ; // Print the payload to the outout stream 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 | 131 | 6 |
137,466 | 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 | 110 | 9 |
137,467 | 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 . | 76 | 24 |
137,468 | 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 . | 436 | 5 |
137,469 | 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 . | 461 | 6 |
137,470 | 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 . | 91 | 7 |
137,471 | 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 . | 186 | 6 |
137,472 | 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 . | 54 | 12 |
137,473 | 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 . | 240 | 7 |
137,474 | 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 . | 103 | 6 |
137,475 | 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 . | 69 | 11 |
137,476 | 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 . | 147 | 36 |
137,477 | 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 | 267 | 15 |
137,478 | 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 | 230 | 13 |
137,479 | @ Override 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 | 47 | 8 |
137,480 | @ Function 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 | 106 | 17 |
137,481 | @ Override public Configuration visit ( AstConnectNode connectNode , State state ) { // masking is a no-op by default for each stream state . readUnmasker = Masker . IDENTITY_MASKER ; state . writeMasker = Masker . IDENTITY_MASKER ; state . pipelineAsMap = new LinkedHashMap <> ( ) ; for ( AstStreamableNode streamable : connectNode . getStreamables ( ) ) { streamable . accept ( this , state ) ; } /* Add the completion handler */ 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 ) ; /* * TODO. This is weird. I will only have one pipeline per connect. But if I don't set a factory When a connect * occurs it will create a shallow copy of the pipeline I set. This doesn't work due to the beforeAdd methods in * ExecutionHandler. Namely when the pipeline is cloned it uses the same handler objects so the handler future * is not null and we fail with an assertion error. */ ChannelPipelineFactory pipelineFactory = new ChannelPipelineFactory ( ) { private int numCalled ; @ Override public ChannelPipeline getPipeline ( ) { if ( numCalled ++ != 0 ) { throw new RobotException ( "getPipeline called more than once" ) ; } return pipeline ; } } ; // Now that connect supports barrier and expression value, connect uri may not be available at this point. // To defer the evaluation of connect uri and initialization of ClientBootstrap, LocationResolver and // ClientResolver are created with information necessary to create ClientBootstrap when the connect uri // is available. Supplier < URI > locationResolver = connectNode . getLocation ( ) :: getValue ; OptionsResolver optionsResolver = new OptionsResolver ( connectNode . getOptions ( ) ) ; ClientBootstrapResolver clientResolver = new ClientBootstrapResolver ( bootstrapFactory , addressFactory , pipelineFactory , locationResolver , optionsResolver , awaitBarrier , connectNode . getRegionInfo ( ) ) ; // retain pipelines for tear down 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 | 615 | 22 |
137,482 | 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 . | 140 | 10 |
137,483 | 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 . | 166 | 8 |
137,484 | 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 . | 168 | 8 |
137,485 | public void setOutputBinding ( Map < String , String > value ) { outputBinding . clear ( ) ; outputBindingDefinitions . clear ( ) ; for ( Map . Entry < String , String > entry : value . entrySet ( ) ) putOutputBinding ( entry . getKey ( ) , entry . getValue ( ) ) ; } /** * Registers an expression for a field. * @param field the name. * @param expression the SpEL definition. */ public void putOutputBinding ( String field , String expression ) { outputBindingDefinitions . put ( field , expression ) ; } private Expression getOutputBinding ( String field ) { Expression binding = outputBinding . get ( field ) ; if ( binding == null ) { String definition = outputBindingDefinitions . get ( field ) ; if ( definition == null ) { if ( outputFields . length == 1 && outputFields [ 0 ] . equals ( field ) ) definition = "#root" ; else definition = "#root?." + field ; } logger . debug ( "Field {} bound as #{{}}" , field , definition ) ; binding = expressionParser . parseExpression ( definition ) ; outputBinding . put ( field , binding ) ; } return binding ; } /** * Gets whether items in collection and array returns * should be emitted as individual output tuples. */ public boolean getScatterOutput ( ) { return scatterOutput ; } /** * Sets whether items in collection and array returns * should be emitted as individual output tuples. */ public void setScatterOutput ( boolean value ) { scatterOutput = value ; } @ Override public Number getParallelism ( ) { return parallelism ; } /** * Sets the Storm parallelism hint. */ public void setParallelism ( Number value ) { parallelism = value ; } @ Override public String getId ( ) { return id ; } @ Override public void setId ( String value ) { id = value ; } @ Override public void setApplicationContext ( ApplicationContext value ) { spring = value ; } | Sets expressions per field . | 433 | 6 |
137,486 | @ Function 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 ) ; // Mutual authentication context . requestConf ( true ) ; // Will use encryption later context . requestInteg ( true ) ; // Will use integrity later return context ; } catch ( GSSException ex ) { throw new RuntimeException ( "Exception creating client GSSContext" , ex ) ; } } | Create a GSS Context from a clients point of view . | 153 | 12 |
137,487 | @ Function public static byte [ ] getClientToken ( GSSContext context ) { byte [ ] initialToken = new byte [ 0 ] ; if ( ! context . isEstablished ( ) ) { try { // token is ignored on the first call 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 . | 113 | 32 |
137,488 | @ Function 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 . | 82 | 31 |
137,489 | @ Function public static GSSContext createServerGSSContext ( ) { System . out . println ( "createServerGSSContext()..." ) ; try { final GSSManager manager = GSSManager . getInstance ( ) ; // // Create server credentials to accept kerberos tokens. This should // make use of the sun.security.krb5.principal system property to // authenticate with the KDC. // 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 ) ; } // // Create the GSSContext used to process requests from clients. The client // requets should use Kerberos since the server credentials are Kerberos // based. // 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 . | 347 | 24 |
137,490 | @ Function 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 . | 91 | 11 |
137,491 | @ Function public static byte [ ] generateMIC ( GSSContext context , MessageProp prop , byte [ ] message ) { try { // Ensure the default Quality-of-Protection is applied. 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 . | 110 | 12 |
137,492 | public Packet getNextPacket ( ) { Packet parsedPacket = parseNextPacketFromPdml ( ) ; if ( parsedPacket == null ) { // All packets have been read return null ; } parsedPacket = addTcpdumpInfoToPacket ( parsedPacket ) ; return parsedPacket ; } | Returns the next Packet that can be parsed or null if all packets have been read | 70 | 17 |
137,493 | private Packet addTcpdumpInfoToPacket ( Packet parsedPacket ) { int packetSize = parsedPacket . getPacketSize ( ) ; tcpdumpReader . readNewPacket ( packetSize ) ; // Get Tcp Payload 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 | 143 | 22 |
137,494 | 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" ) ) { // At packet tag currentPacket = setPacketProperties ( xppFactory . newStartTag ( ) ) ; } else if ( parser . getRawName ( ) . contains ( "proto" ) ) { currentPacket = setProtoProperties ( xppFactory . newStartTag ( ) , currentPacket ) ; } else if ( parser . getRawName ( ) . contains ( "field" ) ) { fieldStack . push ( "field" ) ; // Added http after all others 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 ; // Returned if at end of pdml } 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 | 493 | 17 |
137,495 | public void connect ( ) throws Exception { // connection must be null if the connection failed 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 . | 94 | 9 |
137,496 | public void disconnect ( ) throws Exception { if ( connection != null ) { try { if ( connection instanceof Closeable ) { ( ( Closeable ) connection ) . close ( ) ; } else { try { connection . getInputStream ( ) . close ( ) ; } catch ( IOException e ) { // ignore } try { connection . getOutputStream ( ) . close ( ) ; } catch ( IOException e ) { // ignore } } } finally { connection = null ; } } } | Discoonects from the k3po server . | 102 | 12 |
137,497 | 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 . | 156 | 8 |
137,498 | 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 . | 213 | 9 |
137,499 | 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 | 61 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.