idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
23,700 | public void postCrawling ( CrawlSession session , ExitStatus exitStatus ) { LOG . debug ( "postCrawling" ) ; StateFlowGraph sfg = session . getStateFlowGraph ( ) ; checkSFG ( sfg ) ; String [ ] [ ] clusters = null ; result = outModelCache . close ( session , exitStatus , clusters ) ; outputBuilder . write ( result , se... | Generated the report . |
23,701 | public FormAction setValuesInForm ( Form form ) { FormAction formAction = new FormAction ( ) ; form . setFormAction ( formAction ) ; this . forms . add ( form ) ; return formAction ; } | Links the form with an HTML element which can be clicked . |
23,702 | public static Document removeTags ( Document dom , String tagName ) { NodeList list ; try { list = XPathHelper . evaluateXpathExpression ( dom , "//" + tagName . toUpperCase ( ) ) ; while ( list . getLength ( ) > 0 ) { Node sc = list . item ( 0 ) ; if ( sc != null ) { sc . getParentNode ( ) . removeChild ( sc ) ; } lis... | Removes all the given tags from the document . |
23,703 | public static byte [ ] getDocumentToByteArray ( Document dom ) { try { TransformerFactory tFactory = TransformerFactory . newInstance ( ) ; Transformer transformer = tFactory . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; transformer . setOutputProperty ( OutputKeys . OMIT_XML_... | Serialize the Document object . |
23,704 | public static String addFolderSlashIfNeeded ( String folderName ) { if ( ! "" . equals ( folderName ) && ! folderName . endsWith ( "/" ) ) { return folderName + "/" ; } else { return folderName ; } } | Adds a slash to a path if it doesn t end with a slash . |
23,705 | public static String getTemplateAsString ( String fileName ) throws IOException { String fNameJar = getFileNameInPath ( fileName ) ; InputStream inStream = DomUtils . class . getResourceAsStream ( "/" + fNameJar ) ; if ( inStream == null ) { File f = new File ( fileName ) ; if ( f . exists ( ) ) { inStream = new FileIn... | Retrieves the content of the filename . Also reads from JAR Searches for the resource in the root folder in the jar |
23,706 | public static void writeDocumentToFile ( Document document , String filePathname , String method , int indent ) throws TransformerException , IOException { Transformer transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; transformer ... | Write the document object to a file . |
23,707 | public static String getTextContent ( Document document , boolean individualTokens ) { String textContent = null ; if ( individualTokens ) { List < String > tokens = getTextTokens ( document ) ; textContent = StringUtils . join ( tokens , "," ) ; } else { textContent = document . getDocumentElement ( ) . getTextContent... | To get all the textual content in the dom |
23,708 | public boolean equivalent ( Element otherElement , boolean logging ) { if ( eventable . getElement ( ) . equals ( otherElement ) ) { if ( logging ) { LOGGER . info ( "Element equal" ) ; } return true ; } if ( eventable . getElement ( ) . equalAttributes ( otherElement ) ) { if ( logging ) { LOGGER . info ( "Element att... | Comparator against other element . |
23,709 | @ SuppressWarnings ( "unchecked" ) public List < Difference > compare ( ) { Diff diff = new Diff ( this . controlDOM , this . testDOM ) ; DetailedDiff detDiff = new DetailedDiff ( diff ) ; return detDiff . getAllDifferences ( ) ; } | Compare the controlDOM and testDOM and save and return the differences in a list . |
23,710 | protected void setInputElementValue ( Node element , FormInput input ) { LOGGER . debug ( "INPUTFIELD: {} ({})" , input . getIdentification ( ) , input . getType ( ) ) ; if ( element == null || input . getInputValues ( ) . isEmpty ( ) ) { return ; } try { switch ( input . getType ( ) ) { case TEXT : case TEXTAREA : cas... | Fills in the element with the InputValues for input |
23,711 | private void handleHidden ( FormInput input ) { String text = input . getInputValues ( ) . iterator ( ) . next ( ) . getValue ( ) ; if ( null == text || text . length ( ) == 0 ) { return ; } WebElement inputElement = browser . getWebElement ( input . getIdentification ( ) ) ; JavascriptExecutor js = ( JavascriptExecuto... | Enter information into the hidden input field . |
23,712 | public EmbeddedBrowser get ( ) { LOGGER . debug ( "Setting up a Browser" ) ; ImmutableSortedSet < String > filterAttributes = configuration . getCrawlRules ( ) . getPreCrawlConfig ( ) . getFilterAttributeNames ( ) ; long crawlWaitReload = configuration . getCrawlRules ( ) . getWaitAfterReloadUrl ( ) ; long crawlWaitEve... | Build a new WebDriver based EmbeddedBrowser . |
23,713 | public StackTraceElement [ ] asStackTrace ( ) { int i = 1 ; StackTraceElement [ ] list = new StackTraceElement [ this . size ( ) ] ; for ( Eventable e : this ) { list [ this . size ( ) - i ] = new StackTraceElement ( e . getEventType ( ) . toString ( ) , e . getIdentification ( ) . toString ( ) , e . getElement ( ) . t... | Build a stack trace for this path . This can be used in generating more meaningful exceptions while using Crawljax in conjunction with JUnit for example . |
23,714 | public static WebDriverBackedEmbeddedBrowser withRemoteDriver ( String hubUrl , ImmutableSortedSet < String > filterAttributes , long crawlWaitEvent , long crawlWaitReload ) { return WebDriverBackedEmbeddedBrowser . withDriver ( buildRemoteWebDriver ( hubUrl ) , filterAttributes , crawlWaitEvent , crawlWaitReload ) ; } | Create a RemoteWebDriver backed EmbeddedBrowser . |
23,715 | public static WebDriverBackedEmbeddedBrowser withDriver ( WebDriver driver , ImmutableSortedSet < String > filterAttributes , long crawlWaitEvent , long crawlWaitReload ) { return new WebDriverBackedEmbeddedBrowser ( driver , filterAttributes , crawlWaitEvent , crawlWaitReload ) ; } | Create a WebDriver backed EmbeddedBrowser . |
23,716 | private static RemoteWebDriver buildRemoteWebDriver ( String hubUrl ) { DesiredCapabilities capabilities = new DesiredCapabilities ( ) ; capabilities . setPlatform ( Platform . ANY ) ; URL url ; try { url = new URL ( hubUrl ) ; } catch ( MalformedURLException e ) { LOGGER . error ( "The given hub url of the remote serv... | Private used static method for creation of a RemoteWebDriver . Taking care of the default Capabilities and using the HttpCommandExecutor . |
23,717 | public void handlePopups ( ) { if ( browser instanceof PhantomJSDriver ) { return ; } if ( ExpectedConditions . alertIsPresent ( ) . apply ( browser ) != null ) { try { browser . switchTo ( ) . alert ( ) . accept ( ) ; LOGGER . info ( "Alert accepted" ) ; } catch ( Exception e ) { LOGGER . error ( "Handling of PopUp wi... | alert prompt and confirm behave as if the OK button is always clicked . |
23,718 | private boolean fireEventWait ( WebElement webElement , Eventable eventable ) throws ElementNotVisibleException , InterruptedException { switch ( eventable . getEventType ( ) ) { case click : try { webElement . click ( ) ; } catch ( ElementNotVisibleException e ) { throw e ; } catch ( WebDriverException e ) { throwIfCo... | Fires the event and waits for a specified time . |
23,719 | private String filterAttributes ( String html ) { String filteredHtml = html ; for ( String attribute : this . filterAttributes ) { String regex = "\\s" + attribute + "=\"[^\"]*\"" ; Pattern p = Pattern . compile ( regex , Pattern . CASE_INSENSITIVE ) ; Matcher m = p . matcher ( html ) ; filteredHtml = m . replaceAll (... | Filters attributes from the HTML string . |
23,720 | public synchronized boolean fireEventAndWait ( Eventable eventable ) throws ElementNotVisibleException , NoSuchElementException , InterruptedException { try { boolean handleChanged = false ; boolean result = false ; if ( eventable . getRelatedFrame ( ) != null && ! eventable . getRelatedFrame ( ) . equals ( "" ) ) { LO... | Fires an event on an element using its identification . |
23,721 | public Object executeJavaScript ( String code ) throws CrawljaxException { try { JavascriptExecutor js = ( JavascriptExecutor ) browser ; return js . executeScript ( code ) ; } catch ( WebDriverException e ) { throwIfConnectionException ( e ) ; throw new CrawljaxException ( e ) ; } } | Execute JavaScript in the browser . |
23,722 | private InputValue getInputValue ( FormInput input ) { WebElement inputElement = browser . getWebElement ( input . getIdentification ( ) ) ; switch ( input . getType ( ) ) { case TEXT : case PASSWORD : case HIDDEN : case SELECT : case TEXTAREA : return new InputValue ( inputElement . getAttribute ( "value" ) ) ; case R... | Generates the InputValue for the form input by inspecting the current value of the corresponding WebElement on the DOM . |
23,723 | public static Properties loadProps ( String filename ) { Properties props = new Properties ( ) ; FileInputStream fis = null ; try { fis = new FileInputStream ( filename ) ; props . load ( fis ) ; return props ; } catch ( IOException ex ) { throw new RuntimeException ( ex ) ; } finally { Closer . closeQuietly ( fis ) ; ... | loading Properties from files |
23,724 | public static Properties getProps ( Properties props , String name , Properties defaultProperties ) { final String propString = props . getProperty ( name ) ; if ( propString == null ) return defaultProperties ; String [ ] propValues = propString . split ( "," ) ; if ( propValues . length < 1 ) { throw new IllegalArgum... | Get a property of type java . util . Properties or return the default if no such property is defined |
23,725 | public static String getString ( Properties props , String name , String defaultValue ) { return props . containsKey ( name ) ? props . getProperty ( name ) : defaultValue ; } | Get a string property or if no such property is defined return the given default value |
23,726 | public static int read ( ReadableByteChannel channel , ByteBuffer buffer ) throws IOException { int count = channel . read ( buffer ) ; if ( count == - 1 ) throw new EOFException ( "Received -1 when reading from channel, socket has likely been closed." ) ; return count ; } | read data from channel to buffer |
23,727 | public static void writeShortString ( ByteBuffer buffer , String s ) { if ( s == null ) { buffer . putShort ( ( short ) - 1 ) ; } else if ( s . length ( ) > Short . MAX_VALUE ) { throw new IllegalArgumentException ( "String exceeds the maximum size of " + Short . MAX_VALUE + "." ) ; } else { byte [ ] data = getBytes ( ... | Write a size prefixed string where the size is stored as a 2 byte short |
23,728 | public static void putUnsignedInt ( ByteBuffer buffer , int index , long value ) { buffer . putInt ( index , ( int ) ( value & 0xffffffffL ) ) ; } | Write the given long value as a 4 byte unsigned integer . Overflow is ignored . |
23,729 | public static long crc32 ( byte [ ] bytes , int offset , int size ) { CRC32 crc = new CRC32 ( ) ; crc . update ( bytes , offset , size ) ; return crc . getValue ( ) ; } | Compute the CRC32 of the segment of the byte array given by the specificed size and offset |
23,730 | public static Thread newThread ( String name , Runnable runnable , boolean daemon ) { Thread thread = new Thread ( runnable , name ) ; thread . setDaemon ( daemon ) ; return thread ; } | Create a new thread |
23,731 | private static void unregisterMBean ( String name ) { MBeanServer mbs = ManagementFactory . getPlatformMBeanServer ( ) ; try { synchronized ( mbs ) { ObjectName objName = new ObjectName ( name ) ; if ( mbs . isRegistered ( objName ) ) { mbs . unregisterMBean ( objName ) ; } } } catch ( Exception e ) { e . printStackTra... | Unregister the mbean with the given name if there is one registered |
23,732 | @ SuppressWarnings ( "resource" ) public static FileChannel openChannel ( File file , boolean mutable ) throws IOException { if ( mutable ) { return new RandomAccessFile ( file , "rw" ) . getChannel ( ) ; } return new FileInputStream ( file ) . getChannel ( ) ; } | open a readable or writeable FileChannel |
23,733 | @ SuppressWarnings ( "unchecked" ) public static < E > E getObject ( String className ) { if ( className == null ) { return ( E ) null ; } try { return ( E ) Class . forName ( className ) . newInstance ( ) ; } catch ( InstantiationException e ) { throw new RuntimeException ( e ) ; } catch ( IllegalAccessException e ) {... | create an instance from the className |
23,734 | public static String md5 ( byte [ ] source ) { try { MessageDigest md = MessageDigest . getInstance ( "MD5" ) ; md . update ( source ) ; byte tmp [ ] = md . digest ( ) ; char str [ ] = new char [ 32 ] ; int k = 0 ; for ( byte b : tmp ) { str [ k ++ ] = hexDigits [ b >>> 4 & 0xf ] ; str [ k ++ ] = hexDigits [ b & 0xf ] ... | digest message with MD5 |
23,735 | public void append ( LogSegment segment ) { while ( true ) { List < LogSegment > curr = contents . get ( ) ; List < LogSegment > updated = new ArrayList < LogSegment > ( curr ) ; updated . add ( segment ) ; if ( contents . compareAndSet ( curr , updated ) ) { return ; } } } | Append the given item to the end of the list |
23,736 | public List < LogSegment > trunc ( int newStart ) { if ( newStart < 0 ) { throw new IllegalArgumentException ( "Starting index must be positive." ) ; } while ( true ) { List < LogSegment > curr = contents . get ( ) ; int newLength = Math . max ( curr . size ( ) - newStart , 0 ) ; List < LogSegment > updatedList = new A... | Delete the first n items from the list |
23,737 | public LogSegment getLastView ( ) { List < LogSegment > views = getView ( ) ; return views . get ( views . size ( ) - 1 ) ; } | get the last segment at the moment |
23,738 | private void cleanupLogs ( ) throws IOException { logger . trace ( "Beginning log cleanup..." ) ; int total = 0 ; Iterator < Log > iter = getLogIterator ( ) ; long startMs = System . currentTimeMillis ( ) ; while ( iter . hasNext ( ) ) { Log log = iter . next ( ) ; total += cleanupExpiredSegments ( log ) + cleanupSegme... | Runs through the log removing segments older than a certain age |
23,739 | private int cleanupSegmentsToMaintainSize ( final Log log ) throws IOException { if ( logRetentionSize < 0 || log . size ( ) < logRetentionSize ) return 0 ; List < LogSegment > toBeDeleted = log . markDeletedWhile ( new LogSegmentFilter ( ) { long diff = log . size ( ) - logRetentionSize ; public boolean filter ( LogSe... | Runs through the log removing segments until the size of the log is at least logRetentionSize bytes in size |
23,740 | private int deleteSegments ( Log log , List < LogSegment > segments ) { int total = 0 ; for ( LogSegment segment : segments ) { boolean deleted = false ; try { try { segment . getMessageSet ( ) . close ( ) ; } catch ( IOException e ) { logger . warn ( e . getMessage ( ) , e ) ; } if ( ! segment . getFile ( ) . delete (... | Attemps to delete all provided segments from a log and returns how many it was able to |
23,741 | public void startup ( ) { if ( config . getEnableZookeeper ( ) ) { serverRegister . registerBrokerInZk ( ) ; for ( String topic : getAllTopics ( ) ) { serverRegister . processTask ( new TopicTask ( TopicTask . TaskType . CREATE , topic ) ) ; } startupLatch . countDown ( ) ; } logger . debug ( "Starting log flusher ever... | Register this broker in ZK for the first time . |
23,742 | public void flushAllLogs ( final boolean force ) { Iterator < Log > iter = getLogIterator ( ) ; while ( iter . hasNext ( ) ) { Log log = iter . next ( ) ; try { boolean needFlush = force ; if ( ! needFlush ) { long timeSinceLastFlush = System . currentTimeMillis ( ) - log . getLastFlushedTime ( ) ; Integer logFlushInte... | flush all messages to disk |
23,743 | public ILog getLog ( String topic , int partition ) { TopicNameValidator . validate ( topic ) ; Pool < Integer , Log > p = getLogPool ( topic , partition ) ; return p == null ? null : p . get ( partition ) ; } | Get the log if exists or return null |
23,744 | public ILog getOrCreateLog ( String topic , int partition ) throws IOException { final int configPartitionNumber = getPartition ( topic ) ; if ( partition >= configPartitionNumber ) { throw new IOException ( "partition is bigger than the number of configuration: " + configPartitionNumber ) ; } boolean hasNewTopic = fal... | Create the log if it does not exist or return back exist log |
23,745 | public int createLogs ( String topic , final int partitions , final boolean forceEnlarge ) { TopicNameValidator . validate ( topic ) ; synchronized ( logCreationLock ) { final int configPartitions = getPartition ( topic ) ; if ( configPartitions >= partitions || ! forceEnlarge ) { return configPartitions ; } topicParti... | create logs with given partition number |
23,746 | public List < Long > getOffsets ( OffsetRequest offsetRequest ) { ILog log = getLog ( offsetRequest . topic , offsetRequest . partition ) ; if ( log != null ) { return log . getOffsetsBefore ( offsetRequest ) ; } return ILog . EMPTY_OFFSETS ; } | read offsets before given time |
23,747 | private Send handle ( SelectionKey key , Receive request ) { final short requestTypeId = request . buffer ( ) . getShort ( ) ; final RequestKeys requestType = RequestKeys . valueOf ( requestTypeId ) ; if ( requestLogger . isTraceEnabled ( ) ) { if ( requestType == null ) { throw new InvalidRequestException ( "No mappin... | Handle a completed request producing an optional response |
23,748 | public static Authentication build ( String crypt ) throws IllegalArgumentException { if ( crypt == null ) { return new PlainAuth ( null ) ; } String [ ] value = crypt . split ( ":" ) ; if ( value . length == 2 ) { String type = value [ 0 ] . trim ( ) ; String password = value [ 1 ] . trim ( ) ; if ( password != null &... | build an Authentication . |
23,749 | public static Broker createBroker ( int id , String brokerInfoString ) { String [ ] brokerInfo = brokerInfoString . split ( ":" ) ; String creator = brokerInfo [ 0 ] . replace ( '#' , ':' ) ; String hostname = brokerInfo [ 1 ] . replace ( '#' , ':' ) ; String port = brokerInfo [ 2 ] ; boolean autocreated = Boolean . va... | create a broker with given broker info |
23,750 | public static StringConsumers buildConsumer ( final String zookeeperConfig , final String topic , final String groupId , final IMessageListener < String > listener ) { return buildConsumer ( zookeeperConfig , topic , groupId , listener , 2 ) ; } | create a consumer |
23,751 | public MessageSet read ( long readOffset , long size ) throws IOException { return new FileMessageSet ( channel , this . offset + readOffset , Math . min ( this . offset + readOffset + size , highWaterMark ( ) ) , false , new AtomicBoolean ( false ) ) ; } | read message from file |
23,752 | public long [ ] append ( MessageSet messages ) throws IOException { checkMutable ( ) ; long written = 0L ; while ( written < messages . getSizeInBytes ( ) ) written += messages . writeTo ( channel , 0 , messages . getSizeInBytes ( ) ) ; long beforeOffset = setSize . getAndAdd ( written ) ; return new long [ ] { written... | Append this message to the message set |
23,753 | public void flush ( ) throws IOException { checkMutable ( ) ; long startTime = System . currentTimeMillis ( ) ; channel . force ( true ) ; long elapsedTime = System . currentTimeMillis ( ) - startTime ; LogFlushStats . recordFlushRequest ( elapsedTime ) ; logger . debug ( "flush time " + elapsedTime ) ; setHighWaterMar... | Commit all written data to the physical disk |
23,754 | private long recover ( ) throws IOException { checkMutable ( ) ; long len = channel . size ( ) ; ByteBuffer buffer = ByteBuffer . allocate ( 4 ) ; long validUpTo = 0 ; long next = 0L ; do { next = validateMessage ( channel , validUpTo , len , buffer ) ; if ( next >= 0 ) validUpTo = next ; } while ( next >= 0 ) ; channe... | Recover log up to the last complete entry . Truncate off any bytes from any incomplete messages written |
23,755 | private long validateMessage ( FileChannel channel , long start , long len , ByteBuffer buffer ) throws IOException { buffer . rewind ( ) ; int read = channel . read ( buffer , start ) ; if ( read < 4 ) return - 1 ; int size = buffer . getInt ( 0 ) ; if ( size < Message . MinHeaderSize ) return - 1 ; long next = start ... | Read validate and discard a single message returning the next valid offset and the message being validated |
23,756 | public int createPartitions ( String topic , int partitionNum , boolean enlarge ) throws IOException { KV < Receive , ErrorMapping > response = send ( new CreaterRequest ( topic , partitionNum , enlarge ) ) ; return Utils . deserializeIntArray ( response . k . buffer ( ) ) [ 0 ] ; } | create partitions in the broker |
23,757 | public int deleteTopic ( String topic , String password ) throws IOException { KV < Receive , ErrorMapping > response = send ( new DeleterRequest ( topic , password ) ) ; return Utils . deserializeIntArray ( response . k . buffer ( ) ) [ 0 ] ; } | delete topic never used |
23,758 | public ByteBuffer payload ( ) { ByteBuffer payload = buffer . duplicate ( ) ; payload . position ( headerSize ( magic ( ) ) ) ; payload = payload . slice ( ) ; payload . limit ( payloadSize ( ) ) ; payload . rewind ( ) ; return payload ; } | get the real data without message header |
23,759 | private void validateSegments ( List < LogSegment > segments ) { synchronized ( lock ) { for ( int i = 0 ; i < segments . size ( ) - 1 ; i ++ ) { LogSegment curr = segments . get ( i ) ; LogSegment next = segments . get ( i + 1 ) ; if ( curr . start ( ) + curr . size ( ) != next . start ( ) ) { throw new IllegalStateEx... | Check that the ranges and sizes add up otherwise we have lost some data somewhere |
23,760 | public MessageSet read ( long offset , int length ) throws IOException { List < LogSegment > views = segments . getView ( ) ; LogSegment found = findRange ( views , offset , views . size ( ) ) ; if ( found == null ) { if ( logger . isTraceEnabled ( ) ) { logger . trace ( format ( "NOT FOUND MessageSet from Log[%s], off... | read messages beginning from offset |
23,761 | public void flush ( ) throws IOException { if ( unflushed . get ( ) == 0 ) return ; synchronized ( lock ) { if ( logger . isTraceEnabled ( ) ) { logger . debug ( "Flushing log '" + name + "' last flushed: " + getLastFlushedTime ( ) + " current time: " + System . currentTimeMillis ( ) ) ; } segments . getLastView ( ) . ... | Flush this log file to the physical disk |
23,762 | public static < T extends Range > T findRange ( List < T > ranges , long value , int arraySize ) { if ( ranges . size ( ) < 1 ) return null ; T first = ranges . get ( 0 ) ; T last = ranges . get ( arraySize - 1 ) ; if ( value < first . start ( ) || value > last . start ( ) + last . size ( ) ) { throw new OffsetOutOfRan... | Find a given range object in a list of ranges by a value in that range . Does a binary search over the ranges but instead of checking for equality looks within the range . Takes the array size as an option in case the array grows while searching happens |
23,763 | public static String nameFromOffset ( long offset ) { NumberFormat nf = NumberFormat . getInstance ( ) ; nf . setMinimumIntegerDigits ( 20 ) ; nf . setMaximumFractionDigits ( 0 ) ; nf . setGroupingUsed ( false ) ; return nf . format ( offset ) + Log . FileSuffix ; } | Make log segment file name from offset bytes . All this does is pad out the offset number with zeros so that ls sorts the files numerically |
23,764 | List < LogSegment > markDeletedWhile ( LogSegmentFilter filter ) throws IOException { synchronized ( lock ) { List < LogSegment > view = segments . getView ( ) ; List < LogSegment > deletable = new ArrayList < LogSegment > ( ) ; for ( LogSegment seg : view ) { if ( filter . filter ( seg ) ) { deletable . add ( seg ) ; ... | Delete any log segments matching the given predicate function |
23,765 | public void verifyMessageSize ( int maxMessageSize ) { Iterator < MessageAndOffset > shallowIter = internalIterator ( true ) ; while ( shallowIter . hasNext ( ) ) { MessageAndOffset messageAndOffset = shallowIter . next ( ) ; int payloadSize = messageAndOffset . message . payloadSize ( ) ; if ( payloadSize > maxMessage... | check max size of each message |
23,766 | public void close ( ) { Closer . closeQuietly ( acceptor ) ; for ( Processor processor : processors ) { Closer . closeQuietly ( processor ) ; } } | Shutdown the socket server |
23,767 | public void startup ( ) throws InterruptedException { final int maxCacheConnectionPerThread = serverConfig . getMaxConnections ( ) / processors . length ; logger . debug ( "start {} Processor threads" , processors . length ) ; for ( int i = 0 ; i < processors . length ; i ++ ) { processors [ i ] = new Processor ( handl... | Start the socket server and waiting for finished |
23,768 | public static List < String > getChildrenParentMayNotExist ( ZkClient zkClient , String path ) { try { return zkClient . getChildren ( path ) ; } catch ( ZkNoNodeException e ) { return null ; } } | get children nodes name |
23,769 | public static Cluster getCluster ( ZkClient zkClient ) { Cluster cluster = new Cluster ( ) ; List < String > nodes = getChildrenParentMayNotExist ( zkClient , BrokerIdsPath ) ; for ( String node : nodes ) { final String brokerInfoString = readData ( zkClient , BrokerIdsPath + "/" + node ) ; cluster . add ( Broker . cre... | read all brokers in the zookeeper |
23,770 | public static Map < String , List < String > > getPartitionsForTopics ( ZkClient zkClient , Collection < String > topics ) { Map < String , List < String > > ret = new HashMap < String , List < String > > ( ) ; for ( String topic : topics ) { List < String > partList = new ArrayList < String > ( ) ; List < String > bro... | read broker info for watching topics |
23,771 | public static Map < String , List < String > > getConsumersPerTopic ( ZkClient zkClient , String group ) { ZkGroupDirs dirs = new ZkGroupDirs ( group ) ; List < String > consumers = getChildrenParentMayNotExist ( zkClient , dirs . consumerRegistryDir ) ; Map < String , List < String > > consumersPerTopicMap = new HashM... | get all consumers for the group |
23,772 | public static void createEphemeralPath ( ZkClient zkClient , String path , String data ) { try { zkClient . createEphemeral ( path , Utils . getBytes ( data ) ) ; } catch ( ZkNoNodeException e ) { createParentPath ( zkClient , path ) ; zkClient . createEphemeral ( path , Utils . getBytes ( data ) ) ; } } | Create an ephemeral node with the given path and data . Create parents if necessary . |
23,773 | public void addProducer ( Broker broker ) { Properties props = new Properties ( ) ; props . put ( "host" , broker . host ) ; props . put ( "port" , "" + broker . port ) ; props . putAll ( config . getProperties ( ) ) ; if ( sync ) { SyncProducer producer = new SyncProducer ( new SyncProducerConfig ( props ) ) ; logger ... | add a new producer either synchronous or asynchronous connecting to the specified broker |
23,774 | public void send ( ProducerPoolData < V > ppd ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "send message: " + ppd ) ; } if ( sync ) { Message [ ] messages = new Message [ ppd . data . size ( ) ] ; int index = 0 ; for ( V v : ppd . data ) { messages [ index ] = serializer . toMessage ( v ) ; index ++ ; } By... | selects either a synchronous or an asynchronous producer for the specified broker id and calls the send API on the selected producer to publish the data to the specified broker partition |
23,775 | public void close ( ) { logger . info ( "Closing all sync producers" ) ; if ( sync ) { for ( SyncProducer p : syncProducers . values ( ) ) { p . close ( ) ; } } else { for ( AsyncProducer < V > p : asyncProducers . values ( ) ) { p . close ( ) ; } } } | Closes all the producers in the pool |
23,776 | public ProducerPoolData < V > getProducerPoolData ( String topic , Partition bidPid , List < V > data ) { return new ProducerPoolData < V > ( topic , bidPid , data ) ; } | This constructs and returns the request object for the producer pool |
23,777 | public static ProducerRequest readFrom ( ByteBuffer buffer ) { String topic = Utils . readShortString ( buffer ) ; int partition = buffer . getInt ( ) ; int messageSetSize = buffer . getInt ( ) ; ByteBuffer messageSetBuffer = buffer . slice ( ) ; messageSetBuffer . limit ( messageSetSize ) ; buffer . position ( buffer ... | read a producer request from buffer |
23,778 | protected String getExpectedMessage ( ) { StringBuilder syntax = new StringBuilder ( "<tag> " ) ; syntax . append ( getName ( ) ) ; String args = getArgSyntax ( ) ; if ( args != null && args . length ( ) > 0 ) { syntax . append ( ' ' ) ; syntax . append ( args ) ; } return syntax . toString ( ) ; } | Provides a message which describes the expected format and arguments for this command . This is used to provide user feedback when a command request is malformed . |
23,779 | public ServerSetup createCopy ( String bindAddress ) { ServerSetup setup = new ServerSetup ( getPort ( ) , bindAddress , getProtocol ( ) ) ; setup . setServerStartupTimeout ( getServerStartupTimeout ( ) ) ; setup . setConnectionTimeout ( getConnectionTimeout ( ) ) ; setup . setReadTimeout ( getReadTimeout ( ) ) ; setup... | Create a deep copy . |
23,780 | public static ServerSetup [ ] verbose ( ServerSetup [ ] serverSetups ) { ServerSetup [ ] copies = new ServerSetup [ serverSetups . length ] ; for ( int i = 0 ; i < serverSetups . length ; i ++ ) { copies [ i ] = serverSetups [ i ] . createCopy ( ) . setVerbose ( true ) ; } return copies ; } | Creates a copy with verbose mode enabled . |
23,781 | public void doRun ( Properties properties ) { ServerSetup [ ] serverSetup = new PropertiesBasedServerSetupBuilder ( ) . build ( properties ) ; if ( serverSetup . length == 0 ) { printUsage ( System . out ) ; } else { greenMail = new GreenMail ( serverSetup ) ; log . info ( "Starting GreenMail standalone v{} using {}" ,... | Start and configure GreenMail using given properties . |
23,782 | private String decodeStr ( String str ) { try { return MimeUtility . decodeText ( str ) ; } catch ( UnsupportedEncodingException e ) { return str ; } } | Returns the decoded string in case it contains non us - ascii characters . Returns the same string if it doesn t or the passed value in case of an UnsupportedEncodingException . |
23,783 | public static void copyStream ( final InputStream src , OutputStream dest ) throws IOException { byte [ ] buffer = new byte [ 1024 ] ; int read ; while ( ( read = src . read ( buffer ) ) > - 1 ) { dest . write ( buffer , 0 , read ) ; } dest . flush ( ) ; } | Writes the content of an input stream to an output stream |
23,784 | public static int getLineCount ( String str ) { if ( null == str || str . isEmpty ( ) ) { return 0 ; } int count = 1 ; for ( char c : str . toCharArray ( ) ) { if ( '\n' == c ) { count ++ ; } } return count ; } | Counts the number of lines . |
23,785 | public static void sendTextEmail ( String to , String from , String subject , String msg , final ServerSetup setup ) { sendMimeMessage ( createTextEmail ( to , from , subject , msg , setup ) ) ; } | Sends a text message using given server setup for SMTP . |
23,786 | public static void sendMimeMessage ( MimeMessage mimeMessage ) { try { Transport . send ( mimeMessage ) ; } catch ( MessagingException e ) { throw new IllegalStateException ( "Can not send message " + mimeMessage , e ) ; } } | Send the message using the JavaMail session defined in the message |
23,787 | public static void sendMessageBody ( String to , String from , String subject , Object body , String contentType , ServerSetup serverSetup ) { try { Session smtpSession = getSession ( serverSetup ) ; MimeMessage mimeMessage = new MimeMessage ( smtpSession ) ; mimeMessage . setRecipients ( Message . RecipientType . TO ,... | Send the message with the given attributes and the given body using the specified SMTP settings |
23,788 | public static MimeMultipart createMultipartWithAttachment ( String msg , final byte [ ] attachment , final String contentType , final String filename , String description ) { try { MimeMultipart multiPart = new MimeMultipart ( ) ; MimeBodyPart textPart = new MimeBodyPart ( ) ; multiPart . addBodyPart ( textPart ) ; tex... | Create new multipart with a text part and an attachment |
23,789 | public static Session getSession ( final ServerSetup setup , Properties mailProps ) { Properties props = setup . configureJavaMailSessionProperties ( mailProps , false ) ; log . debug ( "Mail session properties are {}" , props ) ; return Session . getInstance ( props , null ) ; } | Gets a JavaMail Session for given server type such as IMAP and additional props for JavaMail . |
23,790 | public static void setQuota ( final GreenMailUser user , final Quota quota ) { Session session = GreenMailUtil . getSession ( ServerSetupTest . IMAP ) ; try { Store store = session . getStore ( "imap" ) ; store . connect ( user . getEmail ( ) , user . getPassword ( ) ) ; try { ( ( QuotaAwareStore ) store ) . setQuota (... | Sets a quota for a users . |
23,791 | public boolean hasUser ( String userId ) { String normalized = normalizerUserName ( userId ) ; return loginToUser . containsKey ( normalized ) || emailToUser . containsKey ( normalized ) ; } | Checks if user exists . |
23,792 | protected void closeServerSocket ( ) { if ( null != serverSocket ) { try { if ( ! serverSocket . isClosed ( ) ) { serverSocket . close ( ) ; if ( log . isTraceEnabled ( ) ) { log . trace ( "Closed server socket " + serverSocket + "/ref=" + Integer . toHexString ( System . identityHashCode ( serverSocket ) ) + " for " +... | Closes the server socket . |
23,793 | protected synchronized void quit ( ) { log . debug ( "Stopping {}" , getName ( ) ) ; closeServerSocket ( ) ; synchronized ( handlers ) { for ( ProtocolHandler handler : handlers ) { handler . close ( ) ; } handlers . clear ( ) ; } log . debug ( "Stopped {}" , getName ( ) ) ; } | Quits server by closing server socket and closing client socket handlers . |
23,794 | public final synchronized void stopService ( long millis ) { running = false ; try { if ( keepRunning ) { keepRunning = false ; interrupt ( ) ; quit ( ) ; if ( 0L == millis ) { join ( ) ; } else { join ( millis ) ; } } } catch ( InterruptedException e ) { log . warn ( "Got interrupted while stopping {}" , this , e ) ; ... | Stops the service . If a timeout is given and the service has still not gracefully been stopped after timeout ms the service is stopped by force . |
23,795 | private static Date getSentDate ( MimeMessage msg , Date defaultVal ) { if ( msg == null ) { return defaultVal ; } try { Date sentDate = msg . getSentDate ( ) ; if ( sentDate == null ) { return defaultVal ; } else { return sentDate ; } } catch ( MessagingException me ) { return new Date ( ) ; } } | Compute sent date |
23,796 | private String parseEnvelope ( ) { List < String > response = new ArrayList < > ( ) ; response . add ( LB + Q + sentDateEnvelopeString + Q + SP ) ; if ( subject != null && ( subject . length ( ) != 0 ) ) { response . add ( Q + escapeHeader ( subject ) + Q + SP ) ; } else { response . add ( NIL + SP ) ; } addAddressToEn... | Builds IMAP envelope String from pre - parsed data . |
23,797 | private String parseAddress ( String address ) { try { StringBuilder buf = new StringBuilder ( ) ; InternetAddress [ ] netAddrs = InternetAddress . parseHeader ( address , false ) ; for ( InternetAddress netAddr : netAddrs ) { if ( buf . length ( ) > 0 ) { buf . append ( SP ) ; } buf . append ( LB ) ; String personal =... | Parses a String email address to an IMAP address string . |
23,798 | void decodeContentType ( String rawLine ) { int slash = rawLine . indexOf ( '/' ) ; if ( slash == - 1 ) { return ; } else { primaryType = rawLine . substring ( 0 , slash ) . trim ( ) ; } int semicolon = rawLine . indexOf ( ';' ) ; if ( semicolon == - 1 ) { secondaryType = rawLine . substring ( slash + 1 ) . trim ( ) ; ... | Decode a content Type header line into types and parameters pairs |
23,799 | protected void doConfigure ( ) { if ( config != null ) { for ( UserBean user : config . getUsersToCreate ( ) ) { setUser ( user . getEmail ( ) , user . getLogin ( ) , user . getPassword ( ) ) ; } getManagers ( ) . getUserManager ( ) . setAuthRequired ( ! config . isAuthenticationDisabled ( ) ) ; } } | This method can be used by child classes to apply the configuration that is stored in config . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.