idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
12,900 | Pipeline createPipeline ( Language lang , Language motherTongue , TextChecker . QueryParams params , UserConfig userConfig ) throws Exception { Pipeline lt = new Pipeline ( lang , params . altLanguages , motherTongue , cache , userConfig ) ; lt . setMaxErrorsPerWordRate ( config . getMaxErrorsPerWordRate ( ) ) ; if ( config . getLanguageModelDir ( ) != null ) { lt . activateLanguageModelRules ( config . getLanguageModelDir ( ) ) ; } if ( config . getWord2VecModelDir ( ) != null ) { lt . activateWord2VecModelRules ( config . getWord2VecModelDir ( ) ) ; } if ( config . getRulesConfigFile ( ) != null ) { configureFromRulesFile ( lt , lang ) ; } else { configureFromGUI ( lt , lang ) ; } if ( params . useQuerySettings ) { Tools . selectRules ( lt , new HashSet < > ( params . disabledCategories ) , new HashSet < > ( params . enabledCategories ) , new HashSet < > ( params . disabledRules ) , new HashSet < > ( params . enabledRules ) , params . useEnabledOnly ) ; } if ( pool != null ) { lt . setupFinished ( ) ; } return lt ; } | Create a JLanguageTool instance for a specific language mother tongue and rule configuration . Uses Pipeline wrapper to safely share objects |
12,901 | public List < String > lookup ( String lemma , String posTag ) { return mapping . get ( lemma + "|" + posTag ) ; } | Look up a word s inflected form as specified by the lemma and POS tag . |
12,902 | void createTables ( ) throws SQLException { try ( PreparedStatement prepSt = conn . prepareStatement ( "CREATE TABLE pings (" + " language_code VARCHAR(5) NOT NULL," + " check_date TIMESTAMP NOT NULL" + ")" ) ) { prepSt . executeUpdate ( ) ; } try ( PreparedStatement prepSt = conn . prepareStatement ( "CREATE TABLE feed_checks (" + " language_code VARCHAR(5) NOT NULL," + " check_date TIMESTAMP NOT NULL" + ")" ) ) { prepSt . executeUpdate ( ) ; } try ( PreparedStatement prepSt = conn . prepareStatement ( "CREATE TABLE feed_matches (" + " id INT NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)," + " language_code VARCHAR(5) NOT NULL," + " title VARCHAR(255) NOT NULL," + " rule_id VARCHAR(255) NOT NULL," + " rule_sub_id VARCHAR(255)," + " rule_description VARCHAR(255) NOT NULL," + " rule_message VARCHAR(255) NOT NULL," + " rule_category VARCHAR(255) NOT NULL," + " error_context VARCHAR(500) NOT NULL," + " edit_date TIMESTAMP NOT NULL," + " diff_id INT NOT NULL," + " fix_date TIMESTAMP," + " fix_diff_id INT" + ")" ) ) { prepSt . executeUpdate ( ) ; } } | Use this only for test cases - it s Derby - specific . |
12,903 | protected boolean ignoreToken ( AnalyzedTokenReadings [ ] tokens , int idx ) throws IOException { List < String > words = new ArrayList < > ( ) ; for ( AnalyzedTokenReadings token : tokens ) { words . add ( token . getToken ( ) ) ; } return ignoreWord ( words , idx ) ; } | Returns true iff the token at the given position should be ignored by the spell checker . |
12,904 | protected void filterSuggestions ( List < String > suggestions ) { suggestions . removeIf ( suggestion -> isProhibited ( suggestion ) ) ; filterDupes ( suggestions ) ; } | Remove prohibited words from suggestions . |
12,905 | private XParagraphCursor getParagraphCursor ( XComponentContext xContext ) { try { XTextCursor xCursor = getCursor ( xContext ) ; if ( xCursor == null ) { return null ; } return UnoRuntime . queryInterface ( XParagraphCursor . class , xCursor ) ; } catch ( Throwable t ) { MessageHandler . printException ( t ) ; return null ; } } | Returns ParagraphCursor from TextCursor Returns null if it fails |
12,906 | private XTextViewCursor getViewCursor ( XComponentContext xContext ) { try { XComponent xCurrentComponent = OfficeTools . getCurrentComponent ( xContext ) ; if ( xCurrentComponent == null ) { return null ; } XModel xModel = UnoRuntime . queryInterface ( XModel . class , xCurrentComponent ) ; if ( xModel == null ) { return null ; } XController xController = xModel . getCurrentController ( ) ; if ( xController == null ) { return null ; } XTextViewCursorSupplier xViewCursorSupplier = UnoRuntime . queryInterface ( XTextViewCursorSupplier . class , xController ) ; if ( xViewCursorSupplier == null ) { return null ; } return xViewCursorSupplier . getViewCursor ( ) ; } catch ( Throwable t ) { MessageHandler . printException ( t ) ; return null ; } } | Returns ViewCursor Returns null if it fails |
12,907 | int getNumberOfAllTextParagraphs ( ) { try { if ( xPCursor == null ) { return 0 ; } xPCursor . gotoStart ( false ) ; int nPara = 1 ; while ( xPCursor . gotoNextParagraph ( false ) ) nPara ++ ; return nPara ; } catch ( Throwable t ) { MessageHandler . printException ( t ) ; return 0 ; } } | Returns Number of all Paragraphs of Document without footnotes etc . Returns 0 if it fails |
12,908 | int getViewCursorParagraph ( ) { try { if ( xVCursor == null ) { return - 4 ; } XText xDocumentText = xVCursor . getText ( ) ; if ( xDocumentText == null ) { return - 3 ; } XTextCursor xModelCursor = xDocumentText . createTextCursorByRange ( xVCursor . getStart ( ) ) ; if ( xModelCursor == null ) { return - 2 ; } XParagraphCursor xParagraphCursor = UnoRuntime . queryInterface ( XParagraphCursor . class , xModelCursor ) ; if ( xParagraphCursor == null ) { return - 1 ; } int pos = 0 ; while ( xParagraphCursor . gotoPreviousParagraph ( false ) ) pos ++ ; return pos ; } catch ( Throwable t ) { MessageHandler . printException ( t ) ; return - 5 ; } } | Returns Paragraph number under ViewCursor Returns a negative value if it fails |
12,909 | public static void tagText ( String contents , JLanguageTool lt ) throws IOException { AnalyzedSentence analyzedText ; List < String > sentences = lt . sentenceTokenize ( contents ) ; for ( String sentence : sentences ) { analyzedText = lt . getAnalyzedSentence ( sentence ) ; System . out . println ( analyzedText ) ; } } | Tags text using the LanguageTool tagger printing results to System . out . |
12,910 | public static int checkText ( String contents , JLanguageTool lt , boolean isXmlFormat , boolean isJsonFormat , int contextSize , int lineOffset , int prevMatches , StringTools . ApiPrintMode apiMode , boolean listUnknownWords , List < String > unknownWords ) throws IOException { if ( contextSize == - 1 ) { contextSize = DEFAULT_CONTEXT_SIZE ; } long startTime = System . currentTimeMillis ( ) ; List < RuleMatch > ruleMatches = lt . check ( contents ) ; for ( RuleMatch r : ruleMatches ) { r . setLine ( r . getLine ( ) + lineOffset ) ; r . setEndLine ( r . getEndLine ( ) + lineOffset ) ; } if ( isXmlFormat ) { if ( listUnknownWords && apiMode == StringTools . ApiPrintMode . NORMAL_API ) { unknownWords = lt . getUnknownWords ( ) ; } RuleMatchAsXmlSerializer serializer = new RuleMatchAsXmlSerializer ( ) ; String xml = serializer . ruleMatchesToXml ( ruleMatches , contents , contextSize , apiMode , lt . getLanguage ( ) , unknownWords ) ; PrintStream out = new PrintStream ( System . out , true , "UTF-8" ) ; out . print ( xml ) ; } else if ( isJsonFormat ) { RuleMatchesAsJsonSerializer serializer = new RuleMatchesAsJsonSerializer ( ) ; String json = serializer . ruleMatchesToJson ( ruleMatches , contents , contextSize , new DetectedLanguage ( lt . getLanguage ( ) , lt . getLanguage ( ) ) ) ; PrintStream out = new PrintStream ( System . out , true , "UTF-8" ) ; out . print ( json ) ; } else { printMatches ( ruleMatches , prevMatches , contents , contextSize ) ; } if ( apiMode == StringTools . ApiPrintMode . NORMAL_API && ! isJsonFormat ) { SentenceTokenizer sentenceTokenizer = lt . getLanguage ( ) . getSentenceTokenizer ( ) ; int sentenceCount = sentenceTokenizer . tokenize ( contents ) . size ( ) ; displayTimeStats ( startTime , sentenceCount , isXmlFormat ) ; } return ruleMatches . size ( ) ; } | Check the given text and print results to System . out . |
12,911 | private static void printMatches ( List < RuleMatch > ruleMatches , int prevMatches , String contents , int contextSize ) { int i = 1 ; ContextTools contextTools = new ContextTools ( ) ; contextTools . setContextSize ( contextSize ) ; for ( RuleMatch match : ruleMatches ) { Rule rule = match . getRule ( ) ; String output = i + prevMatches + ".) Line " + ( match . getLine ( ) + 1 ) + ", column " + match . getColumn ( ) + ", Rule ID: " + rule . getId ( ) ; if ( rule instanceof AbstractPatternRule ) { AbstractPatternRule pRule = ( AbstractPatternRule ) rule ; if ( pRule . getSubId ( ) != null ) { output += "[" + pRule . getSubId ( ) + "]" ; } } System . out . println ( output ) ; String msg = match . getMessage ( ) ; msg = msg . replaceAll ( "</?suggestion>" , "'" ) ; System . out . println ( "Message: " + msg ) ; List < String > replacements = match . getSuggestedReplacements ( ) ; if ( ! replacements . isEmpty ( ) ) { System . out . println ( "Suggestion: " + String . join ( "; " , replacements ) ) ; } System . out . println ( contextTools . getPlainTextContext ( match . getFromPos ( ) , match . getToPos ( ) , contents ) ) ; if ( match . getUrl ( ) != null ) { System . out . println ( "More info: " + match . getUrl ( ) ) ; } else if ( rule . getUrl ( ) != null ) { System . out . println ( "More info: " + rule . getUrl ( ) ) ; } if ( i < ruleMatches . size ( ) ) { System . out . println ( ) ; } i ++ ; } } | Displays matches in a simple text format . |
12,912 | public static void profileRulesOnText ( String contents , JLanguageTool lt ) throws IOException { long [ ] workTime = new long [ 10 ] ; List < Rule > rules = lt . getAllActiveRules ( ) ; int ruleCount = rules . size ( ) ; System . out . printf ( "Testing %d rules%n" , ruleCount ) ; System . out . println ( "Rule ID\tTime\tSentences\tMatches\tSentences per sec." ) ; List < String > sentences = lt . sentenceTokenize ( contents ) ; for ( Rule rule : rules ) { if ( rule instanceof TextLevelRule ) { continue ; } int matchCount = 0 ; for ( int k = 0 ; k < 10 ; k ++ ) { long startTime = System . currentTimeMillis ( ) ; for ( String sentence : sentences ) { matchCount += rule . match ( lt . getAnalyzedSentence ( sentence ) ) . length ; } long endTime = System . currentTimeMillis ( ) ; workTime [ k ] = endTime - startTime ; } long time = median ( workTime ) ; float timeInSeconds = time / 1000.0f ; float sentencesPerSecond = sentences . size ( ) / timeInSeconds ; System . out . printf ( Locale . ENGLISH , "%s\t%d\t%d\t%d\t%.1f" , rule . getId ( ) , time , sentences . size ( ) , matchCount , sentencesPerSecond ) ; System . out . println ( ) ; } } | Simple rule profiler - used to run LT on a corpus to see which rule takes most time . Prints results to System . out . |
12,913 | public List < String > tokenize ( final String text ) { final List < String > l = new ArrayList < > ( ) ; final StringTokenizer st = new StringTokenizer ( text , nlTokenizingChars , true ) ; while ( st . hasMoreElements ( ) ) { String token = st . nextToken ( ) ; String origToken = token ; if ( token . length ( ) > 1 ) { if ( startsWithQuote ( token ) && endsWithQuote ( token ) && token . length ( ) > 2 ) { l . add ( token . substring ( 0 , 1 ) ) ; l . add ( token . substring ( 1 , token . length ( ) - 1 ) ) ; l . add ( token . substring ( token . length ( ) - 1 , token . length ( ) ) ) ; } else if ( endsWithQuote ( token ) ) { int cnt = 0 ; while ( endsWithQuote ( token ) ) { token = token . substring ( 0 , token . length ( ) - 1 ) ; cnt ++ ; } l . add ( token ) ; for ( int i = origToken . length ( ) - cnt ; i < origToken . length ( ) ; i ++ ) { l . add ( origToken . substring ( i , i + 1 ) ) ; } } else if ( startsWithQuote ( token ) ) { while ( startsWithQuote ( token ) ) { l . add ( token . substring ( 0 , 1 ) ) ; token = token . substring ( 1 , token . length ( ) ) ; } l . add ( token ) ; } else { l . add ( token ) ; } } else { l . add ( token ) ; } } return joinEMailsAndUrls ( l ) ; } | Tokenizes just like WordTokenizer with the exception for words such as oma s that contain an apostrophe in their middle . |
12,914 | public String getText ( ) { StringBuilder sb = new StringBuilder ( ) ; for ( AnalyzedTokenReadings element : tokens ) { sb . append ( element . getToken ( ) ) ; } return sb . toString ( ) ; } | Return the original text . |
12,915 | public String getAnnotations ( ) { StringBuilder sb = new StringBuilder ( 40 ) ; sb . append ( "Disambiguator log: \n" ) ; for ( AnalyzedTokenReadings element : tokens ) { if ( ! element . isWhitespace ( ) && ! "" . equals ( element . getHistoricalAnnotations ( ) ) ) { sb . append ( element . getHistoricalAnnotations ( ) ) ; sb . append ( '\n' ) ; } } return sb . toString ( ) ; } | Get disambiguator actions log . |
12,916 | public static void assureSet ( String s , String varName ) { Objects . requireNonNull ( varName ) ; if ( isEmpty ( s . trim ( ) ) ) { throw new IllegalArgumentException ( varName + " cannot be empty or whitespace only" ) ; } } | Throw exception if the given string is null or empty or only whitespace . |
12,917 | public static String readStream ( InputStream stream , String encoding ) throws IOException { InputStreamReader isr = null ; StringBuilder sb = new StringBuilder ( ) ; try { if ( encoding == null ) { isr = new InputStreamReader ( stream ) ; } else { isr = new InputStreamReader ( stream , encoding ) ; } try ( BufferedReader br = new BufferedReader ( isr ) ) { String line ; while ( ( line = br . readLine ( ) ) != null ) { sb . append ( line ) ; sb . append ( '\n' ) ; } } } finally { if ( isr != null ) { isr . close ( ) ; } } return sb . toString ( ) ; } | Read the text stream using the given encoding . |
12,918 | public static String addSpace ( String word , Language language ) { String space = " " ; if ( word . length ( ) == 1 ) { char c = word . charAt ( 0 ) ; if ( "fr" . equals ( language . getShortCode ( ) ) ) { if ( c == '.' || c == ',' ) { space = "" ; } } else { if ( c == '.' || c == ',' || c == ';' || c == ':' || c == '?' || c == '!' ) { space = "" ; } } } return space ; } | Adds spaces before words that are not punctuation . |
12,919 | public static String filterXML ( String str ) { String s = str ; if ( s . contains ( "<" ) ) { s = XML_COMMENT_PATTERN . matcher ( s ) . replaceAll ( " " ) ; s = XML_PATTERN . matcher ( s ) . replaceAll ( "" ) ; } return s ; } | Simple XML filtering for XML tags . |
12,920 | public final String getTranslatedName ( ResourceBundle messages ) { try { return messages . getString ( getShortCodeWithCountryAndVariant ( ) ) ; } catch ( MissingResourceException e ) { try { return messages . getString ( getShortCode ( ) ) ; } catch ( MissingResourceException e1 ) { return getName ( ) ; } } } | Get the name of the language translated to the current locale if available . Otherwise get the untranslated name . |
12,921 | void remove ( int numberOfParagraph , int startOfSentencePosition ) { for ( int i = 0 ; i < entries . size ( ) ; i ++ ) { if ( entries . get ( i ) . numberOfParagraph == numberOfParagraph && entries . get ( i ) . startOfSentencePosition == startOfSentencePosition ) { entries . remove ( i ) ; return ; } } } | Remove a cache entry for a sentence |
12,922 | void removeRange ( int firstParagraph , int lastParagraph ) { for ( int i = 0 ; i < entries . size ( ) ; i ++ ) { if ( entries . get ( i ) . numberOfParagraph >= firstParagraph && entries . get ( i ) . numberOfParagraph <= lastParagraph ) { entries . remove ( i ) ; i -- ; } } } | Remove all cache entries between firstParagraph and lastParagraph |
12,923 | public void add ( int numberOfParagraph , int startOfSentencePosition , int nextSentencePosition , SingleProofreadingError [ ] errorArray ) { entries . add ( new CacheEntry ( numberOfParagraph , startOfSentencePosition , nextSentencePosition , errorArray ) ) ; } | Add an cache entry |
12,924 | void put ( int numberOfParagraph , int startOfSentencePosition , int nextSentencePosition , SingleProofreadingError [ ] errorArray ) { remove ( numberOfParagraph , startOfSentencePosition ) ; add ( numberOfParagraph , startOfSentencePosition , nextSentencePosition , errorArray ) ; } | replace an cache entry |
12,925 | SingleProofreadingError [ ] getFromPara ( int numberOfParagraph , int startOfSentencePosition , int endOfSentencePosition ) { for ( CacheEntry anEntry : entries ) { if ( anEntry . numberOfParagraph == numberOfParagraph ) { List < SingleProofreadingError > errorList = new ArrayList < > ( ) ; for ( SingleProofreadingError eArray : anEntry . errorArray ) { if ( eArray . nErrorStart >= startOfSentencePosition && eArray . nErrorStart < endOfSentencePosition ) { errorList . add ( eArray ) ; } } return errorList . toArray ( new SingleProofreadingError [ 0 ] ) ; } } return null ; } | get Proofreading errors of sentence out of paragraph matches from cache |
12,926 | private ChunkType getChunkType ( List < ChunkTaggedToken > tokens , int chunkStartPos ) { boolean isPlural = false ; for ( int i = chunkStartPos ; i < tokens . size ( ) ; i ++ ) { ChunkTaggedToken token = tokens . get ( i ) ; if ( ! isBeginningOfNounPhrase ( token ) && ! isContinuationOfNounPhrase ( token ) ) { break ; } if ( false && "and" . equals ( token . getToken ( ) ) ) { isPlural = true ; } else if ( hasNounWithPluralReading ( token ) ) { isPlural = true ; } } return isPlural ? ChunkType . PLURAL : ChunkType . SINGULAR ; } | Get the type of the chunk that starts at the given position . |
12,927 | public final void addMemberAndGroup ( AnalyzedToken token ) { if ( patternToken . hasAndGroup ( ) ) { List < PatternTokenMatcher > andGroupList = andGroup ; for ( int i = 0 ; i < andGroupList . size ( ) ; i ++ ) { if ( ! andGroupCheck [ i + 1 ] ) { PatternTokenMatcher testAndGroup = andGroupList . get ( i ) ; if ( testAndGroup . isMatched ( token ) ) { andGroupCheck [ i + 1 ] = true ; } } } } } | Enables testing multiple conditions specified by different elements . Doesn t test exceptions . |
12,928 | public final String toXML ( PatternRuleId ruleId , Language language ) { List < String > filenames = language . getRuleFileNames ( ) ; XPath xpath = XPathFactory . newInstance ( ) . newXPath ( ) ; for ( String filename : filenames ) { try ( InputStream is = this . getClass ( ) . getResourceAsStream ( filename ) ) { Document doc = getDocument ( is ) ; Node ruleNode = ( Node ) xpath . evaluate ( "/rules/category/rule[@id='" + ruleId . getId ( ) + "']" , doc , XPathConstants . NODE ) ; if ( ruleNode != null ) { return nodeToString ( ruleNode ) ; } Node ruleNodeInGroup = ( Node ) xpath . evaluate ( "/rules/category/rulegroup/rule[@id='" + ruleId . getId ( ) + "']" , doc , XPathConstants . NODE ) ; if ( ruleNodeInGroup != null ) { return nodeToString ( ruleNodeInGroup ) ; } if ( ruleId . getSubId ( ) != null ) { NodeList ruleGroupNodes = ( NodeList ) xpath . evaluate ( "/rules/category/rulegroup[@id='" + ruleId . getId ( ) + "']/rule" , doc , XPathConstants . NODESET ) ; if ( ruleGroupNodes != null ) { for ( int i = 0 ; i < ruleGroupNodes . getLength ( ) ; i ++ ) { if ( Integer . toString ( i + 1 ) . equals ( ruleId . getSubId ( ) ) ) { return nodeToString ( ruleGroupNodes . item ( i ) ) ; } } } } else { Node ruleGroupNode = ( Node ) xpath . evaluate ( "/rules/category/rulegroup[@id='" + ruleId . getId ( ) + "']" , doc , XPathConstants . NODE ) ; if ( ruleGroupNode != null ) { return nodeToString ( ruleGroupNode ) ; } } } catch ( Exception e ) { throw new RuntimeException ( "Could not turn rule '" + ruleId + "' for language " + language + " into a string" , e ) ; } } throw new RuntimeException ( "Could not find rule '" + ruleId + "' for language " + language + " in files: " + filenames ) ; } | Return the given pattern rule as an indented XML string . |
12,929 | private boolean isNotCompound ( String word ) throws IOException { List < String > probablyCorrectWords = new ArrayList < > ( ) ; List < String > testedTokens = new ArrayList < > ( 2 ) ; for ( int i = 2 ; i < word . length ( ) ; i ++ ) { final String first = word . substring ( 0 , i ) ; final String second = word . substring ( i , word . length ( ) ) ; if ( prefixes . contains ( first . toLowerCase ( conversionLocale ) ) && ! isMisspelled ( speller1 , second ) && second . length ( ) > first . length ( ) ) { probablyCorrectWords . add ( word ) ; } else { testedTokens . clear ( ) ; testedTokens . add ( first ) ; testedTokens . add ( second ) ; List < AnalyzedTokenReadings > taggedToks = language . getTagger ( ) . tag ( testedTokens ) ; if ( taggedToks . size ( ) == 2 && ( taggedToks . get ( 0 ) . hasPosTag ( "adja" ) || ( taggedToks . get ( 0 ) . hasPosTag ( "num:comp" ) && ! taggedToks . get ( 0 ) . hasPosTag ( "adv" ) ) ) && taggedToks . get ( 1 ) . hasPartialPosTag ( "adj:" ) ) { probablyCorrectWords . add ( word ) ; } } } if ( ! probablyCorrectWords . isEmpty ( ) ) { addIgnoreTokens ( probablyCorrectWords ) ; return false ; } return true ; } | Check whether the word is a compound adjective or contains a non - splitting prefix . Used to suppress false positives . |
12,930 | private static void initLogFile ( ) { try ( BufferedWriter bw = new BufferedWriter ( new FileWriter ( getLogPath ( ) ) ) ) { Date date = new Date ( ) ; bw . write ( "LT office integration log from " + date . toString ( ) + logLineBreak ) ; } catch ( Throwable t ) { showError ( t ) ; } } | Initialize log - file |
12,931 | static void printToLogFile ( String str ) { try ( BufferedWriter bw = new BufferedWriter ( new FileWriter ( getLogPath ( ) , true ) ) ) { bw . write ( str + logLineBreak ) ; } catch ( Throwable t ) { showError ( t ) ; } } | write to log - file |
12,932 | public static ProxyProvider findProxySupport ( Bootstrap b ) { ProxyProvider . DeferredProxySupport proxy = BootstrapHandlers . findConfiguration ( ProxyProvider . DeferredProxySupport . class , b . config ( ) . handler ( ) ) ; if ( proxy == null ) { return null ; } return proxy . proxyProvider ; } | Find Proxy support in the given client bootstrap |
12,933 | public boolean shouldProxy ( SocketAddress address ) { SocketAddress addr = address ; if ( address instanceof TcpUtils . SocketAddressSupplier ) { addr = ( ( TcpUtils . SocketAddressSupplier ) address ) . get ( ) ; } return addr instanceof InetSocketAddress && shouldProxy ( ( ( InetSocketAddress ) addr ) . getHostString ( ) ) ; } | Should proxy the given address |
12,934 | public final UdpServer host ( String host ) { Objects . requireNonNull ( host , "host" ) ; return bootstrap ( b -> b . localAddress ( host , getPort ( b ) ) ) ; } | The host to which this server should bind . |
12,935 | public final UdpServer port ( int port ) { return bootstrap ( b -> b . localAddress ( getHost ( b ) , port ) ) ; } | The port to which this server should bind . |
12,936 | public final UdpServer wiretap ( String category , LogLevel level ) { Objects . requireNonNull ( category , "category" ) ; Objects . requireNonNull ( level , "level" ) ; return bootstrap ( b -> BootstrapHandlers . updateLogSupport ( b , new LoggingHandler ( category , level ) ) ) ; } | Apply a wire logger configuration using the specified category and logger level |
12,937 | public static boolean isConnectionReset ( Throwable err ) { return err instanceof AbortedException || ( err instanceof IOException && ( err . getMessage ( ) == null || err . getMessage ( ) . contains ( "Broken pipe" ) || err . getMessage ( ) . contains ( "Connection reset by peer" ) ) ) || ( err instanceof SocketException && err . getMessage ( ) != null && err . getMessage ( ) . contains ( "Connection reset by peer" ) ) ; } | Return true if connection has been simply aborted on a tcp level by verifying if the given inbound error . |
12,938 | public static Cookies newServerRequestHolder ( HttpHeaders headers , ServerCookieDecoder decoder ) { return new Cookies ( headers , HttpHeaderNames . COOKIE , false , decoder ) ; } | Return a new cookies holder from server request headers |
12,939 | public Map < CharSequence , Set < Cookie > > getCachedCookies ( ) { if ( ! STATE . compareAndSet ( this , NOT_READ , READING ) ) { for ( ; ; ) { if ( state == READ ) { return cachedCookies ; } } } List < String > allCookieHeaders = nettyHeaders . getAll ( cookiesHeaderName ) ; Map < String , Set < Cookie > > cookies = new HashMap < > ( ) ; for ( String aCookieHeader : allCookieHeaders ) { Set < Cookie > decode ; if ( isClientChannel ) { final Cookie c = ( ( ClientCookieDecoder ) decoder ) . decode ( aCookieHeader ) ; Set < Cookie > existingCookiesOfName = cookies . get ( c . name ( ) ) ; if ( null == existingCookiesOfName ) { existingCookiesOfName = new HashSet < > ( ) ; cookies . put ( c . name ( ) , existingCookiesOfName ) ; } existingCookiesOfName . add ( c ) ; } else { decode = ( ( ServerCookieDecoder ) decoder ) . decode ( aCookieHeader ) ; for ( Cookie cookie : decode ) { Set < Cookie > existingCookiesOfName = cookies . get ( cookie . name ( ) ) ; if ( null == existingCookiesOfName ) { existingCookiesOfName = new HashSet < > ( ) ; cookies . put ( cookie . name ( ) , existingCookiesOfName ) ; } existingCookiesOfName . add ( cookie ) ; } } } cachedCookies = Collections . unmodifiableMap ( cookies ) ; state = READ ; return cachedCookies ; } | Wait for the cookies to become available cache them and subsequently return the cached map of cookies . |
12,940 | public final UdpClient addressSupplier ( Supplier < ? extends SocketAddress > connectingAddressSupplier ) { Objects . requireNonNull ( connectingAddressSupplier , "connectingAddressSupplier" ) ; return bootstrap ( b -> b . remoteAddress ( connectingAddressSupplier . get ( ) ) ) ; } | The address to which this client should connect on subscribe . |
12,941 | public final UdpClient port ( int port ) { return bootstrap ( b -> b . remoteAddress ( getHost ( b ) , port ) ) ; } | The port to which this client should connect . |
12,942 | public static InetSocketAddress createInetSocketAddress ( String hostname , int port , boolean resolve ) { InetSocketAddress inetAddressForIpString = createForIpString ( hostname , port ) ; if ( inetAddressForIpString != null ) { return inetAddressForIpString ; } else { return resolve ? new InetSocketAddress ( hostname , port ) : InetSocketAddress . createUnresolved ( hostname , port ) ; } } | Creates InetSocketAddress instance . Numeric IP addresses will be detected and resolved without doing reverse DNS lookups . |
12,943 | public static InetSocketAddress replaceWithResolved ( InetSocketAddress inetSocketAddress ) { if ( ! inetSocketAddress . isUnresolved ( ) ) { return inetSocketAddress ; } inetSocketAddress = replaceUnresolvedNumericIp ( inetSocketAddress ) ; if ( ! inetSocketAddress . isUnresolved ( ) ) { return inetSocketAddress ; } else { return new InetSocketAddress ( inetSocketAddress . getHostString ( ) , inetSocketAddress . getPort ( ) ) ; } } | Replaces an unresolved InetSocketAddress with a resolved instance in the case that the passed address is unresolved . |
12,944 | public final TcpServer addressSupplier ( Supplier < ? extends SocketAddress > bindingAddressSupplier ) { Objects . requireNonNull ( bindingAddressSupplier , "bindingAddressSupplier" ) ; return bootstrap ( b -> b . localAddress ( bindingAddressSupplier . get ( ) ) ) ; } | The address to which this server should bind on subscribe . |
12,945 | public ByteBufMono aggregate ( ) { return Mono . using ( alloc :: compositeBuffer , b -> this . reduce ( b , ( prev , next ) -> { if ( prev . refCnt ( ) > 0 ) { return prev . addComponent ( true , next . retain ( ) ) ; } else { return prev ; } } ) . filter ( ByteBuf :: isReadable ) , b -> { if ( b . refCnt ( ) > 0 ) { b . release ( ) ; } } ) . as ( ByteBufMono :: new ) ; } | Aggregate subsequent byte buffers into a single buffer . |
12,946 | public Mono < Void > join ( final InetAddress multicastAddress , NetworkInterface iface ) { if ( null == iface && null != datagramChannel . config ( ) . getNetworkInterface ( ) ) { iface = datagramChannel . config ( ) . getNetworkInterface ( ) ; } final ChannelFuture future ; if ( null != iface ) { future = datagramChannel . joinGroup ( new InetSocketAddress ( multicastAddress , datagramChannel . localAddress ( ) . getPort ( ) ) , iface ) ; } else { future = datagramChannel . joinGroup ( multicastAddress ) ; } return FutureMono . from ( future ) . doOnSuccess ( v -> { if ( log . isInfoEnabled ( ) ) { log . info ( format ( future . channel ( ) , "JOIN {}" ) , multicastAddress ) ; } } ) ; } | Join a multicast group . |
12,947 | public final HttpClient mapConnect ( BiFunction < ? super Mono < ? extends Connection > , ? super Bootstrap , ? extends Mono < ? extends Connection > > connector ) { return new HttpClientOnConnectMap ( this , connector ) ; } | Intercept the connection lifecycle and allows to delay transform or inject a context . |
12,948 | public final HttpClient cookie ( String name , Consumer < ? super Cookie > cookieBuilder ) { return new HttpClientCookie ( this , name , cookieBuilder ) ; } | Apply cookies configuration . |
12,949 | public final HttpClient cookiesWhen ( String name , Function < ? super Cookie , Mono < ? extends Cookie > > cookieBuilder ) { return new HttpClientCookieWhen ( this , name , cookieBuilder ) ; } | Apply cookies configuration emitted by the returned Mono before requesting . |
12,950 | static ConnectionInfo newConnectionInfo ( Channel c ) { SocketChannel channel = ( SocketChannel ) c ; InetSocketAddress hostAddress = channel . localAddress ( ) ; InetSocketAddress remoteAddress = getRemoteAddress ( channel ) ; String scheme = channel . pipeline ( ) . get ( SslHandler . class ) != null ? "https" : "http" ; return new ConnectionInfo ( hostAddress , remoteAddress , scheme ) ; } | Retrieve the connection information from the current connection directly |
12,951 | public static SslProvider findSslSupport ( Bootstrap b ) { DeferredSslSupport ssl = BootstrapHandlers . findConfiguration ( DeferredSslSupport . class , b . config ( ) . handler ( ) ) ; if ( ssl == null ) { return null ; } return ssl . sslProvider ; } | Find Ssl support in the given client bootstrap |
12,952 | public static SslProvider findSslSupport ( ServerBootstrap b ) { SslSupportConsumer ssl = BootstrapHandlers . findConfiguration ( SslSupportConsumer . class , b . config ( ) . childHandler ( ) ) ; if ( ssl == null ) { return null ; } return ssl . sslProvider ; } | Find Ssl support in the given server bootstrap |
12,953 | public static Bootstrap removeSslSupport ( Bootstrap b ) { BootstrapHandlers . removeConfiguration ( b , NettyPipeline . SslHandler ) ; return b ; } | Remove Ssl support in the given client bootstrap |
12,954 | public final HttpServer compress ( int minResponseSize ) { if ( minResponseSize < 0 ) { throw new IllegalArgumentException ( "minResponseSize must be positive" ) ; } return tcpConfiguration ( tcp -> tcp . bootstrap ( b -> HttpServerConfiguration . compressSize ( b , minResponseSize ) ) ) ; } | Enable GZip response compression if the client request presents accept encoding headers AND the response reaches a minimum threshold |
12,955 | private SpanNamer spanNamer ( ) { if ( this . spanNamer == null ) { try { this . spanNamer = this . beanFactory . getBean ( SpanNamer . class ) ; } catch ( NoSuchBeanDefinitionException e ) { log . warn ( "SpanNamer bean not found - will provide a manually created instance" ) ; return new DefaultSpanNamer ( ) ; } } return this . spanNamer ; } | due to some race conditions trace keys might not be ready yet |
12,956 | @ ConditionalOnMissingBean ( SpringAwareManagedChannelBuilder . class ) public SpringAwareManagedChannelBuilder managedChannelBuilder ( Optional < List < GrpcManagedChannelBuilderCustomizer > > customizers ) { return new SpringAwareManagedChannelBuilder ( customizers ) ; } | This is wrapper around gRPC s managed channel builder that is spring - aware |
12,957 | static < T extends Annotation > T findAnnotation ( Method method , Class < T > clazz ) { T annotation = AnnotationUtils . findAnnotation ( method , clazz ) ; if ( annotation == null ) { try { annotation = AnnotationUtils . findAnnotation ( method . getDeclaringClass ( ) . getMethod ( method . getName ( ) , method . getParameterTypes ( ) ) , clazz ) ; } catch ( NoSuchMethodException | SecurityException ex ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Exception occurred while tyring to find the annotation" , ex ) ; } } } return annotation ; } | Searches for an annotation either on a method or inside the method parameters . |
12,958 | public Message < ? > postReceive ( Message < ? > message , MessageChannel channel ) { if ( emptyMessage ( message ) ) { return message ; } MessageHeaderAccessor headers = mutableHeaderAccessor ( message ) ; TraceContextOrSamplingFlags extracted = this . extractor . extract ( headers ) ; Span span = this . threadLocalSpan . next ( extracted ) ; MessageHeaderPropagation . removeAnyTraceHeaders ( headers , this . tracing . propagation ( ) . keys ( ) ) ; this . injector . inject ( span . context ( ) , headers ) ; if ( ! span . isNoop ( ) ) { span . kind ( Span . Kind . CONSUMER ) . name ( "receive" ) . start ( ) ; span . remoteServiceName ( REMOTE_SERVICE_NAME ) ; addTags ( message , span , channel ) ; } if ( log . isDebugEnabled ( ) ) { log . debug ( "Created a new span in post receive " + span ) ; } headers . setImmutable ( ) ; if ( message instanceof ErrorMessage ) { ErrorMessage errorMessage = ( ErrorMessage ) message ; return new ErrorMessage ( errorMessage . getPayload ( ) , headers . getMessageHeaders ( ) , errorMessage . getOriginalMessage ( ) ) ; } return new GenericMessage < > ( message . getPayload ( ) , headers . getMessageHeaders ( ) ) ; } | This starts a consumer span as a child of the incoming message or the current trace context placing it in scope until the receive completes . |
12,959 | public Message < ? > beforeHandle ( Message < ? > message , MessageChannel channel , MessageHandler handler ) { if ( emptyMessage ( message ) ) { return message ; } MessageHeaderAccessor headers = mutableHeaderAccessor ( message ) ; TraceContextOrSamplingFlags extracted = this . extractor . extract ( headers ) ; Span consumerSpan = this . tracer . nextSpan ( extracted ) ; if ( ! consumerSpan . isNoop ( ) ) { consumerSpan . kind ( Span . Kind . CONSUMER ) . start ( ) ; consumerSpan . remoteServiceName ( REMOTE_SERVICE_NAME ) ; addTags ( message , consumerSpan , channel ) ; consumerSpan . finish ( ) ; } this . threadLocalSpan . next ( TraceContextOrSamplingFlags . create ( consumerSpan . context ( ) ) ) . name ( "handle" ) . start ( ) ; MessageHeaderPropagation . removeAnyTraceHeaders ( headers , this . tracing . propagation ( ) . keys ( ) ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Created a new span in before handle" + consumerSpan ) ; } if ( message instanceof ErrorMessage ) { return new ErrorMessage ( ( Throwable ) message . getPayload ( ) , headers . getMessageHeaders ( ) ) ; } headers . setImmutable ( ) ; return new GenericMessage < > ( message . getPayload ( ) , headers . getMessageHeaders ( ) ) ; } | This starts a consumer span as a child of the incoming message or the current trace context . It then creates a span for the handler placing it in scope . |
12,960 | void addTags ( Message < ? > message , SpanCustomizer result , MessageChannel channel ) { if ( channel != null ) { result . tag ( "channel" , messageChannelName ( channel ) ) ; } } | When an upstream context was not present lookup keys are unlikely added . |
12,961 | public CheckResult check ( ) { try { post ( new byte [ ] { '[' , ']' } ) ; return CheckResult . OK ; } catch ( Exception e ) { return CheckResult . failed ( e ) ; } } | Sends an empty json message to the configured endpoint . |
12,962 | public Javalin start ( ) { Util . logJavalinBanner ( this . config . showJavalinBanner ) ; JettyUtil . disableJettyLogger ( ) ; long startupTimer = System . currentTimeMillis ( ) ; if ( server . getStarted ( ) ) { throw new IllegalStateException ( "Cannot call start() again on a started server." ) ; } server . setStarted ( true ) ; Util . printHelpfulMessageIfLoggerIsMissing ( ) ; eventManager . fireEvent ( JavalinEvent . SERVER_STARTING ) ; try { log . info ( "Starting Javalin ..." ) ; server . start ( servlet , wsServlet ) ; log . info ( "Javalin started in " + ( System . currentTimeMillis ( ) - startupTimer ) + "ms \\o/" ) ; eventManager . fireEvent ( JavalinEvent . SERVER_STARTED ) ; } catch ( Exception e ) { log . error ( "Failed to start Javalin" ) ; eventManager . fireEvent ( JavalinEvent . SERVER_START_FAILED ) ; if ( Boolean . TRUE . equals ( server . server ( ) . getAttribute ( "is-default-server" ) ) ) { stop ( ) ; } if ( e . getMessage ( ) != null && e . getMessage ( ) . contains ( "Failed to bind to" ) ) { throw new RuntimeException ( "Port already in use. Make sure no other process is using port " + server . getServerPort ( ) + " and try again." , e ) ; } else if ( e . getMessage ( ) != null && e . getMessage ( ) . contains ( "Permission denied" ) ) { throw new RuntimeException ( "Port 1-1023 require elevated privileges (process must be started by admin)." , e ) ; } throw new RuntimeException ( e ) ; } return this ; } | Synchronously starts the application instance . |
12,963 | public Javalin stop ( ) { eventManager . fireEvent ( JavalinEvent . SERVER_STOPPING ) ; log . info ( "Stopping Javalin ..." ) ; try { server . server ( ) . stop ( ) ; } catch ( Exception e ) { log . error ( "Javalin failed to stop gracefully" , e ) ; } log . info ( "Javalin has stopped" ) ; eventManager . fireEvent ( JavalinEvent . SERVER_STOPPED ) ; return this ; } | Synchronously stops the application instance . |
12,964 | private File [ ] getCrashReportFiles ( ) { final File dir = context . getFilesDir ( ) ; if ( dir == null ) { ACRA . log . w ( LOG_TAG , "Application files directory does not exist! The application may not be installed correctly. Please try reinstalling." ) ; return new File [ 0 ] ; } if ( ACRA . DEV_LOGGING ) ACRA . log . d ( LOG_TAG , "Looking for error files in " + dir . getAbsolutePath ( ) ) ; final FilenameFilter filter = ( dir1 , name ) -> name . endsWith ( ACRAConstants . REPORTFILE_EXTENSION ) ; final File [ ] result = dir . listFiles ( filter ) ; return ( result == null ) ? new File [ 0 ] : result ; } | Returns an array containing the names of pending crash report files . |
12,965 | public void waitForAllActivitiesDestroy ( int timeOutInMillis ) { synchronized ( activityStack ) { long start = System . currentTimeMillis ( ) ; long now = start ; while ( ! activityStack . isEmpty ( ) && start + timeOutInMillis > now ) { try { activityStack . wait ( start - now + timeOutInMillis ) ; } catch ( InterruptedException ignored ) { } now = System . currentTimeMillis ( ) ; } } } | wait until the last activity is stopped |
12,966 | private boolean isDebuggable ( ) { final PackageManager pm = context . getPackageManager ( ) ; try { return ( pm . getApplicationInfo ( context . getPackageName ( ) , 0 ) . flags & ApplicationInfo . FLAG_DEBUGGABLE ) > 0 ; } catch ( PackageManager . NameNotFoundException e ) { return false ; } } | Returns true if the application is debuggable . |
12,967 | private void deleteUnsentReportsFromOldAppVersion ( ) { final SharedPreferences prefs = new SharedPreferencesFactory ( context , config ) . create ( ) ; final long lastVersionNr = prefs . getInt ( ACRA . PREF_LAST_VERSION_NR , 0 ) ; final int appVersion = getAppVersion ( ) ; if ( appVersion > lastVersionNr ) { reportDeleter . deleteReports ( true , 0 ) ; reportDeleter . deleteReports ( false , 0 ) ; prefs . edit ( ) . putInt ( ACRA . PREF_LAST_VERSION_NR , appVersion ) . apply ( ) ; } } | Delete any old unsent reports if this is a newer version of the app than when we last started . |
12,968 | public CrashReportData createCrashData ( final ReportBuilder builder ) { final ExecutorService executorService = config . parallel ( ) ? Executors . newCachedThreadPool ( ) : Executors . newSingleThreadExecutor ( ) ; final CrashReportData crashReportData = new CrashReportData ( ) ; final List < Future < ? > > futures = new ArrayList < > ( ) ; for ( final Collector collector : collectors ) { futures . add ( executorService . submit ( ( ) -> { try { if ( ACRA . DEV_LOGGING ) ACRA . log . d ( LOG_TAG , "Calling collector " + collector . getClass ( ) . getName ( ) ) ; collector . collect ( context , config , builder , crashReportData ) ; if ( ACRA . DEV_LOGGING ) ACRA . log . d ( LOG_TAG , "Collector " + collector . getClass ( ) . getName ( ) + " completed" ) ; } catch ( CollectorException e ) { ACRA . log . w ( LOG_TAG , e ) ; } catch ( Exception t ) { ACRA . log . e ( LOG_TAG , "Error in collector " + collector . getClass ( ) . getSimpleName ( ) , t ) ; } } ) ) ; } for ( Future < ? > future : futures ) { while ( ! future . isDone ( ) ) { try { future . get ( ) ; } catch ( InterruptedException ignored ) { } catch ( ExecutionException e ) { break ; } } } return crashReportData ; } | Collects crash data . |
12,969 | private long getAvailableInternalMemorySize ( ) { final File path = Environment . getDataDirectory ( ) ; final StatFs stat = new StatFs ( path . getPath ( ) ) ; final long blockSize ; final long availableBlocks ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN_MR2 ) { blockSize = stat . getBlockSizeLong ( ) ; availableBlocks = stat . getAvailableBlocksLong ( ) ; } else { blockSize = stat . getBlockSize ( ) ; availableBlocks = stat . getAvailableBlocks ( ) ; } return availableBlocks * blockSize ; } | Calculates the free memory of the device . This is based on an inspection of the filesystem which in android devices is stored in RAM . |
12,970 | private long getTotalInternalMemorySize ( ) { final File path = Environment . getDataDirectory ( ) ; final StatFs stat = new StatFs ( path . getPath ( ) ) ; final long blockSize ; final long totalBlocks ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN_MR2 ) { blockSize = stat . getBlockSizeLong ( ) ; totalBlocks = stat . getBlockCountLong ( ) ; } else { blockSize = stat . getBlockSize ( ) ; totalBlocks = stat . getBlockCount ( ) ; } return totalBlocks * blockSize ; } | Calculates the total memory of the device . This is based on an inspection of the filesystem which in android devices is stored in RAM . |
12,971 | protected View getMainView ( ) { final TextView text = new TextView ( this ) ; final String dialogText = dialogConfiguration . text ( ) ; if ( dialogText != null ) { text . setText ( dialogText ) ; } return text ; } | Creates a main view containing text of resText or nothing if not found |
12,972 | protected View getCommentLabel ( ) { final String commentPrompt = dialogConfiguration . commentPrompt ( ) ; if ( commentPrompt != null ) { final TextView labelView = new TextView ( this ) ; labelView . setText ( commentPrompt ) ; return labelView ; } return null ; } | creates a comment label view with resCommentPrompt as text |
12,973 | protected View getEmailLabel ( ) { final String emailPrompt = dialogConfiguration . emailPrompt ( ) ; if ( emailPrompt != null ) { final TextView labelView = new TextView ( this ) ; labelView . setText ( emailPrompt ) ; return labelView ; } return null ; } | creates a email label view with resEmailPrompt as text |
12,974 | public CharSequence getCalendarContentDescription ( ) { return calendarContentDescription != null ? calendarContentDescription : getContext ( ) . getString ( R . string . calendar ) ; } | Get content description for calendar |
12,975 | public CalendarDay getSelectedDate ( ) { List < CalendarDay > dates = adapter . getSelectedDates ( ) ; if ( dates . isEmpty ( ) ) { return null ; } else { return dates . get ( dates . size ( ) - 1 ) ; } } | Get the currently selected date or null if no selection . Depending on the selection mode you might get different results . |
12,976 | public void setWeekDayFormatter ( WeekDayFormatter formatter ) { adapter . setWeekDayFormatter ( formatter == null ? WeekDayFormatter . DEFAULT : formatter ) ; } | Set a formatter for weekday labels . |
12,977 | public void setDayFormatter ( DayFormatter formatter ) { adapter . setDayFormatter ( formatter == null ? DayFormatter . DEFAULT : formatter ) ; } | Set a formatter for day labels . |
12,978 | public void addDecorators ( Collection < ? extends DayViewDecorator > decorators ) { if ( decorators == null ) { return ; } dayViewDecorators . addAll ( decorators ) ; adapter . setDecorators ( dayViewDecorators ) ; } | Add a collection of day decorators |
12,979 | public void addDecorator ( DayViewDecorator decorator ) { if ( decorator == null ) { return ; } dayViewDecorators . add ( decorator ) ; adapter . setDecorators ( dayViewDecorators ) ; } | Add a day decorator |
12,980 | protected void dispatchOnDateSelected ( final CalendarDay day , final boolean selected ) { if ( listener != null ) { listener . onDateSelected ( MaterialCalendarView . this , day , selected ) ; } } | Dispatch date change events to a listener if set |
12,981 | protected void dispatchOnRangeSelected ( final List < CalendarDay > days ) { if ( rangeListener != null ) { rangeListener . onRangeSelected ( MaterialCalendarView . this , days ) ; } } | Dispatch a range of days to a range listener if set ordered chronologically . |
12,982 | public void selectRange ( final CalendarDay firstDay , final CalendarDay lastDay ) { if ( firstDay == null || lastDay == null ) { return ; } else if ( firstDay . isAfter ( lastDay ) ) { adapter . selectRange ( lastDay , firstDay ) ; dispatchOnRangeSelected ( adapter . getSelectedDates ( ) ) ; } else { adapter . selectRange ( firstDay , lastDay ) ; dispatchOnRangeSelected ( adapter . getSelectedDates ( ) ) ; } } | Select a fresh range of date including first day and last day . |
12,983 | private static int clampSize ( int size , int spec ) { int specMode = MeasureSpec . getMode ( spec ) ; int specSize = MeasureSpec . getSize ( spec ) ; switch ( specMode ) { case MeasureSpec . EXACTLY : { return specSize ; } case MeasureSpec . AT_MOST : { return Math . min ( size , specSize ) ; } case MeasureSpec . UNSPECIFIED : default : { return size ; } } } | Clamp the size to the measure spec . |
12,984 | private static void enableView ( final View view , final boolean enable ) { view . setEnabled ( enable ) ; view . setAlpha ( enable ? 1f : 0.1f ) ; } | Used for enabling or disabling views while also changing the alpha . |
12,985 | public void setDayFormatter ( DayFormatter formatter ) { this . contentDescriptionFormatter = contentDescriptionFormatter == this . formatter ? formatter : contentDescriptionFormatter ; this . formatter = formatter == null ? DayFormatter . DEFAULT : formatter ; CharSequence currentLabel = getText ( ) ; Object [ ] spans = null ; if ( currentLabel instanceof Spanned ) { spans = ( ( Spanned ) currentLabel ) . getSpans ( 0 , currentLabel . length ( ) , Object . class ) ; } SpannableString newLabel = new SpannableString ( getLabel ( ) ) ; if ( spans != null ) { for ( Object span : spans ) { newLabel . setSpan ( span , 0 , newLabel . length ( ) , Spanned . SPAN_EXCLUSIVE_EXCLUSIVE ) ; } } setText ( newLabel ) ; } | Set the new label formatter and reformat the current label . This preserves current spans . |
12,986 | public void setDayFormatterContentDescription ( DayFormatter formatter ) { this . contentDescriptionFormatter = formatter == null ? this . formatter : formatter ; setContentDescription ( getContentDescriptionLabel ( ) ) ; } | Set the new content description formatter and reformat the current content description . |
12,987 | public void setDateSelected ( CalendarDay day , boolean selected ) { if ( selected ) { if ( ! selectedDates . contains ( day ) ) { selectedDates . add ( day ) ; invalidateSelectedDates ( ) ; } } else { if ( selectedDates . contains ( day ) ) { selectedDates . remove ( day ) ; invalidateSelectedDates ( ) ; } } } | Select or un - select a day . |
12,988 | public void selectRange ( final CalendarDay first , final CalendarDay last ) { selectedDates . clear ( ) ; LocalDate temp = LocalDate . of ( first . getYear ( ) , first . getMonth ( ) , first . getDay ( ) ) ; final LocalDate end = last . getDate ( ) ; while ( temp . isBefore ( end ) || temp . equals ( end ) ) { selectedDates . add ( CalendarDay . from ( temp ) ) ; temp = temp . plusDays ( 1 ) ; } invalidateSelectedDates ( ) ; } | Clear the previous selection select the range of days from first to last and finally invalidate . First day should be before last day otherwise the selection won t happen . |
12,989 | void applyTo ( DayViewFacade other ) { if ( selectionDrawable != null ) { other . setSelectionDrawable ( selectionDrawable ) ; } if ( backgroundDrawable != null ) { other . setBackgroundDrawable ( backgroundDrawable ) ; } other . spans . addAll ( spans ) ; other . isDecorated |= this . isDecorated ; other . daysDisabled = daysDisabled ; } | Apply things set this to other |
12,990 | public void report ( ) throws ServletException , IOException { final ServletRequestAttributes currentRequestAttributes = ( ServletRequestAttributes ) RequestContextHolder . currentRequestAttributes ( ) ; final HttpServletRequest httpServletRequest = currentRequestAttributes . getRequest ( ) ; final HttpServletResponse httpResponse = currentRequestAttributes . getResponse ( ) ; reportServlet . service ( httpServletRequest , httpResponse ) ; } | Display a report page . |
12,991 | @ SuppressWarnings ( "resource" ) private static String parseGwtRpcMethodName ( InputStream stream , String charEncoding ) { try { final Scanner scanner ; if ( charEncoding == null ) { scanner = new Scanner ( stream ) ; } else { scanner = new Scanner ( stream , charEncoding ) ; } scanner . useDelimiter ( GWT_RPC_SEPARATOR_CHAR_PATTERN ) ; scanner . next ( ) ; scanner . next ( ) ; scanner . next ( ) ; scanner . next ( ) ; scanner . next ( ) ; scanner . next ( ) ; return "." + scanner . next ( ) ; } catch ( final NoSuchElementException e ) { LOG . debug ( "Unable to parse GWT-RPC request" , e ) ; return null ; } } | Try to parse GWT - RPC method name from request body stream . Does not close the stream . |
12,992 | static boolean scanForChildTag ( XMLStreamReader reader , String tagName ) throws XMLStreamException { assert reader . isStartElement ( ) ; int level = - 1 ; while ( reader . hasNext ( ) ) { if ( reader . isStartElement ( ) ) { level ++ ; } else if ( reader . isEndElement ( ) ) { level -- ; } if ( level < 0 ) { break ; } reader . next ( ) ; if ( level == 0 && reader . isStartElement ( ) && reader . getLocalName ( ) . equals ( tagName ) ) { return true ; } } return false ; } | Scan xml for tag child of the current element |
12,993 | private static String parseSoapMethodName ( InputStream stream , String charEncoding ) { try { final XMLInputFactory factory = XMLInputFactory . newInstance ( ) ; factory . setProperty ( XMLInputFactory . SUPPORT_DTD , false ) ; factory . setProperty ( XMLInputFactory . IS_SUPPORTING_EXTERNAL_ENTITIES , false ) ; final XMLStreamReader xmlReader ; if ( charEncoding != null ) { xmlReader = factory . createXMLStreamReader ( stream , charEncoding ) ; } else { xmlReader = factory . createXMLStreamReader ( stream ) ; } xmlReader . nextTag ( ) ; if ( ! "Envelope" . equals ( xmlReader . getLocalName ( ) ) ) { LOG . debug ( "Unexpected first tag of SOAP request: '" + xmlReader . getLocalName ( ) + "' (expected 'Envelope')" ) ; return null ; } if ( ! scanForChildTag ( xmlReader , "Body" ) ) { LOG . debug ( "Unable to find SOAP 'Body' tag" ) ; return null ; } xmlReader . nextTag ( ) ; return "." + xmlReader . getLocalName ( ) ; } catch ( final XMLStreamException e ) { LOG . debug ( "Unable to parse SOAP request" , e ) ; return null ; } } | Try to parse SOAP method name from request body stream . Does not close the stream . |
12,994 | protected void writeHtml ( final MBasicTable table , final OutputStream outputStream , final boolean isSelection ) throws IOException { final Writer out = new OutputStreamWriter ( outputStream , "UTF-8" ) ; final String eol = isSelection ? "\n" : System . getProperty ( "line.separator" ) ; out . write ( "<!-- Fichier genere par " ) ; out . write ( System . getProperty ( "user.name" ) ) ; out . write ( " le " ) ; out . write ( DateFormat . getDateTimeInstance ( DateFormat . LONG , DateFormat . LONG ) . format ( new Date ( ) ) ) ; out . write ( " ) ; out . write ( eol ) ; out . write ( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">" ) ; out . write ( "<html>" ) ; out . write ( eol ) ; final String title = buildTitle ( table ) ; writeHtmlHead ( title , out , eol ) ; out . write ( "<body>" ) ; out . write ( eol ) ; if ( title != null ) { out . write ( "<h3>" ) ; out . write ( title ) ; out . write ( "</h3>" ) ; } out . write ( eol ) ; writeHtmlTable ( table , isSelection , out , eol ) ; out . write ( "</body>" ) ; out . write ( eol ) ; out . write ( "</html>" ) ; out . flush ( ) ; } | Exporte une JTable dans un fichier au format html . |
12,995 | private Object createJavaxConnectionManagerProxy ( Object javaxConnectionManager ) { assert javaxConnectionManager != null ; final InvocationHandler invocationHandler = new ConnectionManagerInvocationHandler ( javaxConnectionManager ) ; return createProxy ( javaxConnectionManager , invocationHandler ) ; } | pour jboss ou glassfish |
12,996 | protected String getRequestName ( InvocationContext context ) { final Method method = context . getMethod ( ) ; return method . getDeclaringClass ( ) . getSimpleName ( ) + '.' + method . getName ( ) ; } | Determine request name for an invocation context . |
12,997 | public MTable < T > addColumn ( final String attribute , final String libelle ) { final int modelIndex = getColumnCount ( ) ; final TableColumn tableColumn = new TableColumn ( modelIndex ) ; tableColumn . setIdentifier ( attribute ) ; if ( libelle == null ) { tableColumn . setHeaderValue ( attribute ) ; } else { tableColumn . setHeaderValue ( libelle ) ; } super . addColumn ( tableColumn ) ; return this ; } | Ajoute une colonne dans la table . |
12,998 | void writeTree ( ) throws DocumentException { margin = 0 ; final MBeanNode platformNode = mbeans . get ( 0 ) ; writeTree ( platformNode . getChildren ( ) ) ; for ( final MBeanNode node : mbeans ) { if ( node != platformNode ) { newPage ( ) ; addToDocument ( new Chunk ( node . getName ( ) , boldFont ) ) ; margin = 0 ; writeTree ( node . getChildren ( ) ) ; } } } | Affiche l arbre des MBeans . |
12,999 | public static ImageIcon getScaledInstance ( ImageIcon icon , int targetWidth , int targetHeight ) { return new ImageIcon ( getScaledInstance ( icon . getImage ( ) , targetWidth , targetHeight ) ) ; } | Redimensionne une ImageIcon . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.