idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
40,600
private void sendPending ( ) { while ( outstanding . get ( ) < concurrency ) { final TopicQueue queue = pendingTopics . poll ( ) ; if ( queue == null ) { return ; } queue . pending = false ; final int sent = queue . sendBatch ( ) ; if ( sent == batchSize ) { queue . pending = true ; pendingTopics . offer ( queue ) ; } } }
Send any pending topics .
40,601
private void serve ( HttpRequest request , HttpResponse response ) { String url = request . getUri ( ) ; System . out . println ( "[Server] serve " + url ) ; IncomingWebRequestTracer incomingWebrequestTracer = oneAgentSDK . traceIncomingWebRequest ( webAppInfo , url , request . getMethod ( ) ) ; for ( Entry < String , List < String > > headerField : request . getHeaders ( ) . entrySet ( ) ) { for ( String value : headerField . getValue ( ) ) { incomingWebrequestTracer . addRequestHeader ( headerField . getKey ( ) , value ) ; } } for ( Entry < String , List < String > > parameter : request . getParameters ( ) . entrySet ( ) ) { for ( String value : parameter . getValue ( ) ) { incomingWebrequestTracer . addParameter ( parameter . getKey ( ) , value ) ; } } incomingWebrequestTracer . setRemoteAddress ( request . getRemoteIpAddress ( ) ) ; incomingWebrequestTracer . start ( ) ; try { response . setContent ( "Hello world!" . getBytes ( ) ) ; response . setStatusCode ( 200 ) ; incomingWebrequestTracer . setStatusCode ( 200 ) ; } catch ( Exception e ) { incomingWebrequestTracer . error ( e ) ; e . printStackTrace ( ) ; throw new RuntimeException ( e ) ; } finally { incomingWebrequestTracer . end ( ) ; } }
faked http request handling . shows usage of OneAgent SDK s incoming webrequest API
40,602
private void receiveMessage ( ) { MessagingSystemInfo messagingSystemInfo = oneAgentSdk . createMessagingSystemInfo ( "DynatraceSample" , "theQueue" , MessageDestinationType . QUEUE , ChannelType . IN_PROCESS , null ) ; IncomingMessageReceiveTracer incomingMessageReceiveTracer = oneAgentSdk . traceIncomingMessageReceive ( messagingSystemInfo ) ; incomingMessageReceiveTracer . start ( ) ; try { Message msg = queueManager . receive ( "theQeue" ) ; if ( msg == null ) { return ; } IncomingMessageProcessTracer incomingMessageProcessTracer = oneAgentSdk . traceIncomingMessageProcess ( messagingSystemInfo ) ; incomingMessageProcessTracer . setDynatraceStringTag ( msg . getProperty ( OneAgentSDK . DYNATRACE_MESSAGE_PROPERTYNAME ) ) ; incomingMessageProcessTracer . setVendorMessageId ( msg . getVendorMessageId ( ) ) ; incomingMessageProcessTracer . start ( ) ; try { System . out . println ( "Message received: " + msg . toString ( ) ) ; } catch ( Exception e ) { incomingMessageProcessTracer . error ( e ) ; } finally { incomingMessageProcessTracer . end ( ) ; } } catch ( Exception e ) { incomingMessageReceiveTracer . error ( e ) ; } finally { incomingMessageReceiveTracer . end ( ) ; } }
shows how to trace a blocking receive of a message
40,603
public void versionDownloadableFound ( String versionDownloadable ) { if ( Comparator . isVersionDownloadableNewer ( mActivity , versionDownloadable ) ) { if ( hasToShowNotice ( versionDownloadable ) && ! hasUserTappedToNotShowNoticeAgain ( versionDownloadable ) ) { mLibraryResultCallaback . foundUpdateAndShowIt ( versionDownloadable ) ; } else { mLibraryResultCallaback . foundUpdateAndDontShowIt ( versionDownloadable ) ; } } else { mLibraryResultCallaback . returnUpToDate ( versionDownloadable ) ; } }
If the library found a version available on the Store and it s different from the installed one notify it to the user .
40,604
private boolean hasUserTappedToNotShowNoticeAgain ( String versionDownloadable ) { SharedPreferences prefs = mActivity . getSharedPreferences ( PREFS_FILENAME , 0 ) ; String prefKey = DONT_SHOW_AGAIN_PREF_KEY + versionDownloadable ; return prefs . getBoolean ( prefKey , false ) ; }
Get if the user has tapped on No thanks button on dialog for this downloable version .
40,605
private void saveNumberOfChecksForUpdatedVersion ( String versionDownloadable , int mChecksMade ) { mChecksMade ++ ; SharedPreferences prefs = mActivity . getSharedPreferences ( PREFS_FILENAME , 0 ) ; SharedPreferences . Editor editor = prefs . edit ( ) ; editor . putInt ( SUCCESSFUL_CHEKS_PREF_KEY + versionDownloadable , mChecksMade ) ; editor . commit ( ) ; }
Update number of checks for this version downloadable from the Store .
40,606
public static boolean isVersionDownloadableNewer ( Activity mActivity , String versionDownloadable ) { String versionInstalled = null ; try { versionInstalled = mActivity . getPackageManager ( ) . getPackageInfo ( mActivity . getPackageName ( ) , 0 ) . versionName ; } catch ( PackageManager . NameNotFoundException ignored ) { } if ( versionInstalled . equals ( versionDownloadable ) ) { return false ; } else { return versionCompareNumerically ( versionDownloadable , versionInstalled ) > 0 ; } }
Compare the string versionDownloadable to the version installed of the app .
40,607
public static boolean isAvailable ( Context context ) { boolean connected = false ; ConnectivityManager cm = ( ConnectivityManager ) context . getSystemService ( Context . CONNECTIVITY_SERVICE ) ; if ( cm != null ) { NetworkInfo ni = cm . getActiveNetworkInfo ( ) ; if ( ni != null ) { connected = ni . isConnected ( ) ; } } return connected ; }
Check if a network is available
40,608
protected void onPostExecute ( Integer result ) { if ( result == VERSION_DOWNLOADABLE_FOUND ) { mResultInterface . versionDownloadableFound ( mVersionDownloadable ) ; } else if ( result == NETWORK_ERROR ) { mResultInterface . networkError ( ) ; Network . logConnectionError ( ) ; } else if ( result == MULTIPLE_APKS_PUBLISHED ) { mResultInterface . multipleApksPublished ( ) ; Log . e ( Constants . LOG_TAG , "Multiple APKs published " ) ; } else if ( result == PACKAGE_NOT_PUBLISHED ) { mResultInterface . appUnpublished ( ) ; Log . e ( Constants . LOG_TAG , "App unpublished" ) ; } else if ( result == STORE_ERROR ) { mResultInterface . storeError ( ) ; Log . e ( Constants . LOG_TAG , "Store page format error" ) ; } }
Return to UpdateChecker class to work with the versionDownloadable if the library found it .
40,609
public static String makeServicePath ( String serviceName ) { checkNotNull ( serviceName ) ; checkArgument ( ! "" . equals ( serviceName ) ) ; return ZKPaths . makePath ( ROOT_SERVICES_PATH , serviceName ) ; }
Construct the path in ZooKeeper to where a service s children live .
40,610
public ServiceCachingPolicyBuilder withMaxServiceInstanceIdleTime ( int maxServiceInstanceIdleTime , TimeUnit unit ) { checkState ( maxServiceInstanceIdleTime > 0 ) ; checkNotNull ( unit ) ; _maxServiceInstanceIdleTimeNanos = unit . toNanos ( maxServiceInstanceIdleTime ) ; return this ; }
Set the amount of time a cached instance is allowed to sit idle in the cache before being eligible for expiration . If never called cached instances will not expire solely due to idle time .
40,611
private void destroyService ( ServiceHandle < S > serviceHandle ) { try { _serviceFactory . destroy ( serviceHandle . getEndPoint ( ) , serviceHandle . getService ( ) ) ; } catch ( Exception e ) { LOG . warn ( "Error destroying serviceHandle" , e ) ; } }
Destroys a service handle quietly swallows any exception occurred
40,612
public PartitionContextBuilder put ( String key , Object value ) { _map . put ( key , value ) ; return this ; }
Adds the specified key and value to the partition context . Null keys or values and duplicate keys are not allowed .
40,613
public static InstanceMetrics forInstance ( MetricRegistry metrics , Object instance , String serviceName ) { return new InstanceMetrics ( metrics , instance , serviceName ) ; }
Create a metrics instance that corresponds to a single instance of a class . This is useful for cases where there exists one instance per service . For example in a ServicePool .
40,614
private String [ ] collectPartitionKeyAnnotations ( Method method ) { Annotation [ ] [ ] annotations = method . getParameterAnnotations ( ) ; String [ ] keyMappings = new String [ annotations . length ] ; boolean keyMappingFound = false ; Map < String , Integer > unique = Maps . newHashMap ( ) ; for ( int i = 0 ; i < annotations . length ; i ++ ) { PartitionKey annotation = findPartitionKeyAnnotation ( annotations [ i ] ) ; if ( annotation == null ) { continue ; } String key = checkNotNull ( annotation . value ( ) ) ; Integer prev = unique . put ( key , i ) ; checkState ( prev == null , "Method '%s' has multiple arguments annotated with the same @PartitionKey " + "value '%s': arguments %s and %s" , method , key , prev , i ) ; keyMappings [ i ] = key ; keyMappingFound = true ; } return keyMappingFound ? keyMappings : null ; }
Returns an array indexed by argument index with the value of the
40,615
public void checkIn ( ServiceHandle < S > handle ) throws Exception { checkNotNull ( handle ) ; S service = handle . getService ( ) ; ServiceEndPoint endPoint = handle . getEndPoint ( ) ; Long invalidRevision = _invalidRevisions . get ( endPoint ) ; Long serviceRevision = _checkedOutRevisions . remove ( handle ) ; if ( _isClosed || ( invalidRevision != null && serviceRevision < invalidRevision ) ) { _pool . invalidateObject ( endPoint , service ) ; } else { _pool . returnObject ( endPoint , service ) ; } }
Returns a service instance for an end point to the cache so that it may be used by other users .
40,616
private List < Integer > computeHashCodes ( String endPointId ) { List < Integer > list = Lists . newArrayListWithCapacity ( _entriesPerEndPoint ) ; for ( int i = 0 ; list . size ( ) < _entriesPerEndPoint ; i ++ ) { Hasher hasher = Hashing . md5 ( ) . newHasher ( ) ; hasher . putInt ( i ) ; putUnencodedChars ( hasher , endPointId ) ; ByteBuffer buf = ByteBuffer . wrap ( hasher . hash ( ) . asBytes ( ) ) ; while ( buf . hasRemaining ( ) && list . size ( ) < _entriesPerEndPoint ) { list . add ( buf . getInt ( ) ) ; } } return list ; }
Returns a list of pseudo - random 32 - bit values derived from the specified end point ID .
40,617
public static < S > void close ( S dynamicProxy ) { try { Closeables . close ( getPool ( dynamicProxy ) , true ) ; } catch ( IOException e ) { throw new AssertionError ( ) ; } }
Closes the service pool associated with the specified dynamic service proxy .
40,618
@ SuppressWarnings ( "UnusedParameters" ) protected String serialize ( String serviceName , String id , Payload payload ) { return String . valueOf ( payload ) ; }
Subclasses may override this to customize the persistent format of the payload .
40,619
static String getDeepName ( final Element element ) { if ( element == null ) { return "" ; } return getDeepName ( element . getParentElement ( ) ) + '/' + element . getName ( ) ; }
Returns fully qualified name for an Xml element .
40,620
static boolean isElementParentName ( Element element , String name ) { Element parent = element . getParentElement ( ) ; if ( parent == null ) { return false ; } return isElementName ( parent , name ) ; }
Returns true if an elements parents name is same as argument
40,621
void createWrappedStructure ( final WrapperFactory factory ) { HierarchyWrapper currentWrapper = null ; for ( Content child : castToContentList ( elementContent ) ) { Wrapper < ? > wrapper = factory . create ( child ) ; if ( wrapper instanceof SingleNewlineInTextWrapper ) { continue ; } if ( currentWrapper == null ) { currentWrapper = new HierarchyWrapper ( wrapper ) ; children . add ( currentWrapper ) ; } else { currentWrapper . addContent ( wrapper ) ; } if ( currentWrapper . containsElement ( ) ) { currentWrapper . createWrappedStructure ( factory ) ; currentWrapper = null ; } } }
Traverses the initial xml element wrapper and builds hierarchy
40,622
void processOperation ( HierarchyWrapperOperation operation ) { operation . startOfProcess ( ) ; otherContentList . forEach ( operation :: processOtherContent ) ; if ( elementContent != null && elementContent . isContentElement ( ) ) { operation . processElement ( elementContent ) ; } operation . manipulateChildElements ( children ) ; HierarchyWrapperOperation subOperation = operation . createSubOperation ( ) ; for ( HierarchyWrapper child : children ) { child . processOperation ( subOperation ) ; } operation . endOfProcess ( ) ; }
Template method to traverse xml hierarchy
40,623
public void scanForIgnoredSections ( String originalXml ) { this . originalXml = originalXml ; SortpomPiScanner sortpomPiScanner = new SortpomPiScanner ( logger ) ; sortpomPiScanner . scan ( originalXml ) ; if ( sortpomPiScanner . isScanError ( ) ) { throw new FailureException ( sortpomPiScanner . getFirstError ( ) ) ; } containsIgnoredSections = sortpomPiScanner . containsIgnoredSections ( ) ; }
Checks if pom file contains any processing instructions
40,624
public String getIndentCharacters ( ) { if ( nrOfIndentSpace == 0 ) { return "" ; } if ( nrOfIndentSpace == INDENT_TAB ) { return "\t" ; } if ( nrOfIndentSpace < INDENT_TAB || nrOfIndentSpace > MAX_INDENT_SPACES ) { throw new FailureException ( "nrOfIndentSpace cannot be below -1 or above 255, was: " + nrOfIndentSpace ) ; } char [ ] chars = new char [ nrOfIndentSpace ] ; Arrays . fill ( chars , ' ' ) ; return new String ( chars ) ; }
Gets the indent characters from parameter .
40,625
public void setup ( PluginParameters parameters ) { this . pomFile = parameters . pomFile ; this . backupFileExtension = parameters . backupFileExtension ; this . encoding = parameters . encoding ; this . customSortOrderFile = parameters . customSortOrderFile ; this . predefinedSortOrder = parameters . predefinedSortOrder ; this . violationFilename = parameters . violationFilename ; }
Initializes the class with sortpom parameters .
40,626
public String getPomFileContent ( ) { try ( InputStream inputStream = new FileInputStream ( pomFile ) ) { return IOUtils . toString ( inputStream , encoding ) ; } catch ( UnsupportedCharsetException ex ) { throw new FailureException ( "Could not handle encoding: " + encoding , ex ) ; } catch ( IOException ex ) { throw new FailureException ( "Could not read pom file: " + pomFile . getAbsolutePath ( ) , ex ) ; } }
Loads the pom file that will be sorted .
40,627
private String getDefaultSortOrderXml ( ) throws IOException { CheckedSupplier < InputStream , IOException > createStreamFunc = ( ) -> { if ( customSortOrderFile != null ) { UrlWrapper urlWrapper = new UrlWrapper ( customSortOrderFile ) ; if ( urlWrapper . isUrl ( ) ) { return urlWrapper . openStream ( ) ; } else { return openCustomSortOrderFile ( ) ; } } else if ( predefinedSortOrder != null ) { return getPredefinedSortOrder ( predefinedSortOrder ) ; } return getPredefinedSortOrder ( DEFAULT_SORT_ORDER_FILENAME ) ; } ; try ( InputStream inputStream = createStreamFunc . get ( ) ) { return IOUtils . toString ( inputStream , encoding ) ; } }
Retrieves the default sort order for sortpom
40,628
private InputStream openCustomSortOrderFile ( ) throws FileNotFoundException { InputStream inputStream ; try { inputStream = new FileInputStream ( customSortOrderFile ) ; } catch ( FileNotFoundException ex ) { try { URL resource = this . getClass ( ) . getClassLoader ( ) . getResource ( customSortOrderFile ) ; if ( resource == null ) { throw new IOException ( "Cannot find resource" ) ; } inputStream = resource . openStream ( ) ; } catch ( IOException e1 ) { throw new FileNotFoundException ( String . format ( "Could not find %s or %s in classpath" , new File ( customSortOrderFile ) . getAbsolutePath ( ) , customSortOrderFile ) ) ; } } return inputStream ; }
Load custom sort order file from absolute or class path .
40,629
public static XmlOrderedResult nameDiffers ( String originalElementName , String newElementName ) { return new XmlOrderedResult ( false , String . format ( "The xml element <%s> should be placed before <%s>" , newElementName , originalElementName ) ) ; }
The xml elements was not in the right order
40,630
public void processElement ( Wrapper < Element > elementWrapper ) { Element content = elementWrapper . getContent ( ) ; content . detach ( ) ; content . removeContent ( ) ; }
Detach each xml element
40,631
public void scan ( String originalXml ) { Matcher matcher = INSTRUCTION_PATTERN . matcher ( originalXml ) ; while ( matcher . find ( ) ) { scanOneInstruction ( matcher . group ( 1 ) ) ; containsIgnoredSections = true ; } if ( expectedNextInstruction != IGNORE ) { addError ( String . format ( "Xml processing instructions for sortpom was not properly terminated. Every <?sortpom %s?> must be followed with <?sortpom %s?>" , IGNORE , RESUME ) ) ; } }
Scan and verifies the pom file for processing instructions
40,632
public void processElement ( Wrapper < Element > elementWrapper ) { Element element = elementWrapper . getContent ( ) ; element . setAttributes ( getSortedAttributes ( element ) ) ; }
Sort attributes of each element
40,633
public void processOtherContent ( Wrapper < Content > content ) { if ( parentElement != null ) { parentElement . addContent ( content . getContent ( ) ) ; } }
Add all other content to the parent xml element
40,634
public void processElement ( Wrapper < Element > element ) { activeElement = element . getContent ( ) ; if ( parentElement != null ) { parentElement . addContent ( activeElement ) ; } }
Add the element to its parent
40,635
public void manipulateChildElements ( List < HierarchyWrapper > children ) { for ( int i = 0 ; i < children . size ( ) ; i ++ ) { HierarchyWrapper wrapperImpl = children . get ( i ) ; final Wrapper < Element > wrapper = wrapperImpl . getElementContent ( ) ; if ( wrapper != null && wrapper . isSortable ( ) ) { insertChildInSortedOrder ( children , i , wrapperImpl , wrapper ) ; } } }
Sort all children of an element
40,636
public void startOfProcess ( ) { String previousBaseIndent = baseIndent . substring ( INDENT_LENGTH ) ; builder . append ( previousBaseIndent ) . append ( "HierarchyWrapper{\n" ) ; processFirstOtherContent = true ; }
Add text before each element
40,637
public void processOtherContent ( Wrapper < Content > content ) { if ( processFirstOtherContent ) { builder . append ( baseIndent ) . append ( "otherContentList=" ) . append ( "\n" ) ; processFirstOtherContent = false ; } builder . append ( content . toString ( baseIndent ) ) . append ( "\n" ) ; }
Add each other element to string
40,638
public void processElement ( Wrapper < Element > elementWrapper ) { builder . append ( baseIndent ) . append ( "elementContent=" ) . append ( elementWrapper ) . append ( "\n" ) ; }
Add each element to string
40,639
public void manipulateChildElements ( List < HierarchyWrapper > children ) { if ( ! children . isEmpty ( ) ) { builder . append ( baseIndent ) . append ( "children=" ) . append ( "\n" ) ; } }
Add text before processing each child
40,640
public void addElement ( Element element , int sortOrder ) { final String deepName = getDeepName ( element ) ; elementNameSortOrderMap . put ( deepName , sortOrder ) ; }
Add an Xml element to the map
40,641
public boolean containsElement ( Element element ) { String deepName = getDeepName ( element ) ; return elementNameSortOrderMap . containsKey ( deepName ) ; }
Returns true if element is in the map
40,642
public void setOriginalXml ( final InputStream originalXml ) throws JDOMException , IOException { SAXBuilder parser = new SAXBuilder ( ) ; originalDocument = parser . build ( originalXml ) ; }
Sets the original xml that should be sorted . Builds a dom document of the xml .
40,643
public void sortXml ( ) { newDocument = ( Document ) originalDocument . clone ( ) ; final Element rootElement = ( Element ) originalDocument . getRootElement ( ) . clone ( ) ; HierarchyRootWrapper rootWrapper = factory . createFromRootElement ( rootElement ) ; rootWrapper . createWrappedStructure ( factory ) ; rootWrapper . detachStructure ( ) ; rootWrapper . sortStructureAttributes ( ) ; rootWrapper . sortStructureElements ( ) ; rootWrapper . connectXmlStructure ( ) ; newDocument . setRootElement ( rootWrapper . getElementContent ( ) . getContent ( ) ) ; }
Creates a new dom document that contains the sorted xml .
40,644
public void setup ( PluginParameters pluginParameters ) { this . indentCharacters = pluginParameters . indentCharacters ; this . lineSeparatorUtil = pluginParameters . lineSeparatorUtil ; this . encoding = pluginParameters . encoding ; this . expandEmptyElements = pluginParameters . expandEmptyElements ; this . indentBlankLines = pluginParameters . indentBlankLines ; }
Setup default configuration
40,645
public String getSortedXml ( Document newDocument ) { try ( ByteArrayOutputStream sortedXml = new ByteArrayOutputStream ( ) ) { BufferedLineSeparatorOutputStream bufferedLineOutputStream = new BufferedLineSeparatorOutputStream ( lineSeparatorUtil . toString ( ) , sortedXml ) ; XMLOutputter xmlOutputter = new PatchedXMLOutputter ( bufferedLineOutputStream , indentBlankLines ) ; xmlOutputter . setFormat ( createPrettyFormat ( ) ) ; xmlOutputter . output ( newDocument , bufferedLineOutputStream ) ; bufferedLineOutputStream . close ( ) ; return sortedXml . toString ( encoding ) ; } catch ( IOException ioex ) { throw new FailureException ( "Could not format pom files content" , ioex ) ; } }
Returns the sorted xml as an OutputStream .
40,646
private void initializeSortOrderMap ( ) { try { Document document = createDocumentFromDefaultSortOrderFile ( ) ; addElementsToSortOrderMap ( document . getRootElement ( ) , SORT_ORDER_BASE ) ; } catch ( IOException | JDOMException e ) { throw new FailureException ( e . getMessage ( ) , e ) ; } }
Creates sort order map from chosen sort order .
40,647
private void addElementsToSortOrderMap ( final Element element , int baseSortOrder ) { elementSortOrderMap . addElement ( element , baseSortOrder ) ; final List < Element > castToChildElementList = castToChildElementList ( element ) ; int sortOrder = baseSortOrder ; for ( Element child : castToChildElementList ) { sortOrder += SORT_ORDER_INCREMENT ; addElementsToSortOrderMap ( child , sortOrder ) ; } }
Processes the chosen sort order . Adds sort order element and sort index to a map .
40,648
public void sortPom ( ) { log . info ( "Sorting file " + pomFile . getAbsolutePath ( ) ) ; String originalXml = fileUtil . getPomFileContent ( ) ; String sortedXml = sortXml ( originalXml ) ; if ( pomFileIsSorted ( originalXml , sortedXml ) ) { log . info ( "Pom file is already sorted, exiting" ) ; return ; } createBackupFile ( ) ; saveSortedPomFile ( sortedXml ) ; }
Sorts the pom file .
40,649
private String sortXml ( final String originalXml ) { xmlProcessingInstructionParser . scanForIgnoredSections ( originalXml ) ; String xml = xmlProcessingInstructionParser . replaceIgnoredSections ( ) ; insertXmlInXmlProcessor ( xml , ( ) -> "Could not sort " + pomFile . getAbsolutePath ( ) + " content: " ) ; xmlProcessor . sortXml ( ) ; Document newDocument = xmlProcessor . getNewDocument ( ) ; String sortedXml = xmlOutputGenerator . getSortedXml ( newDocument ) ; if ( xmlProcessingInstructionParser . existsIgnoredSections ( ) ) { sortedXml = xmlProcessingInstructionParser . revertIgnoredSections ( sortedXml ) ; } return sortedXml ; }
Sorts the incoming xml .
40,650
private void createBackupFile ( ) { if ( createBackupFile ) { if ( backupFileExtension . trim ( ) . length ( ) == 0 ) { throw new FailureException ( "Could not create backup file, extension name was empty" ) ; } fileUtil . backupFile ( ) ; log . info ( String . format ( "Saved backup of %s to %s%s" , pomFile . getAbsolutePath ( ) , pomFile . getAbsolutePath ( ) , backupFileExtension ) ) ; } }
Creates the backup file for pom .
40,651
private void saveSortedPomFile ( final String sortedXml ) { fileUtil . savePomFile ( sortedXml ) ; log . info ( "Saved sorted pom file to " + pomFile . getAbsolutePath ( ) ) ; }
Saves the sorted pom file .
40,652
public void verifyPom ( ) { String pomFileName = pomFile . getAbsolutePath ( ) ; log . info ( "Verifying file " + pomFileName ) ; XmlOrderedResult xmlOrderedResult = isPomElementsSorted ( ) ; if ( ! xmlOrderedResult . isOrdered ( ) ) { switch ( verifyFailType ) { case WARN : log . warn ( xmlOrderedResult . getErrorMessage ( ) ) ; saveViolationFile ( xmlOrderedResult ) ; log . warn ( String . format ( TEXT_FILE_NOT_SORTED , pomFileName ) ) ; break ; case SORT : log . info ( xmlOrderedResult . getErrorMessage ( ) ) ; saveViolationFile ( xmlOrderedResult ) ; log . info ( String . format ( TEXT_FILE_NOT_SORTED , pomFileName ) ) ; sortPom ( ) ; break ; case STOP : log . error ( xmlOrderedResult . getErrorMessage ( ) ) ; saveViolationFile ( xmlOrderedResult ) ; log . error ( String . format ( TEXT_FILE_NOT_SORTED , pomFileName ) ) ; throw new FailureException ( String . format ( TEXT_FILE_NOT_SORTED , pomFileName ) ) ; } } }
Verify that the pom - file is sorted regardless of formatting
40,653
public static byte [ ] s2n ( String string ) { if ( string == null ) { return null ; } byte [ ] stringBytes = string . getBytes ( UTF8 ) ; byte [ ] allBytes = new byte [ stringBytes . length + 1 ] ; System . arraycopy ( stringBytes , 0 , allBytes , 0 , stringBytes . length ) ; return allBytes ; }
Java - to - native string mapping
40,654
public synchronized boolean spell ( String word ) { requireValidHandle ( ) ; if ( ! isValidInput ( word ) ) { return false ; } int spellResult = getLib ( ) . voikkoSpellCstr ( handle , s2n ( word ) ) ; return ( spellResult == Libvoikko . VOIKKO_SPELL_OK ) ; }
Check the spelling of given word .
40,655
public synchronized List < GrammarError > grammarErrors ( String text , String language ) { requireValidHandle ( ) ; List < GrammarError > errorList = new ArrayList < GrammarError > ( ) ; if ( ! isValidInput ( text ) ) { return errorList ; } int offset = 0 ; for ( String paragraph : text . replace ( "\r" , "\n" ) . split ( "\\n" ) ) { appendErrorsFromParagraph ( errorList , paragraph , offset , language ) ; offset += paragraph . length ( ) + 1 ; } return errorList ; }
Check the given text for grammar errors and return a list of GrammarError objects representing the errors that were found . Unlike the C based API this method accepts multiple paragraphs separated by newline characters .
40,656
public synchronized List < Analysis > analyze ( String word ) { requireValidHandle ( ) ; List < Analysis > analysisList = new ArrayList < Analysis > ( ) ; if ( ! isValidInput ( word ) ) { return analysisList ; } Libvoikko lib = getLib ( ) ; Pointer cAnalysisList = lib . voikkoAnalyzeWordCstr ( handle , s2n ( word ) ) ; if ( cAnalysisList == null ) { return analysisList ; } for ( Pointer cAnalysis : cAnalysisList . getPointerArray ( 0 ) ) { Pointer cKeys = lib . voikko_mor_analysis_keys ( cAnalysis ) ; Analysis analysis = new Analysis ( ) ; for ( Pointer cKey : cKeys . getPointerArray ( 0 ) ) { String key = stringFromPointer ( cKey ) ; ByteArray value = lib . voikko_mor_analysis_value_cstr ( cAnalysis , s2n ( key ) ) ; analysis . put ( key , value . toString ( ) ) ; lib . voikko_free_mor_analysis_value_cstr ( value ) ; } analysisList . add ( analysis ) ; } lib . voikko_free_mor_analysis ( cAnalysisList ) ; return analysisList ; }
Analyze the morphology of given word and return the list of analysis results .
40,657
public synchronized List < Token > tokens ( String text ) { requireValidHandle ( ) ; List < Token > allTokens = new ArrayList < Token > ( ) ; int lastStart = 0 ; for ( int i = indexOfSpecialUnknown ( text , 0 ) ; i != - 1 ; i = indexOfSpecialUnknown ( text , i + 1 ) ) { allTokens . addAll ( tokensNonNull ( text . substring ( lastStart , i ) , lastStart ) ) ; allTokens . add ( new Token ( TokenType . UNKNOWN , Character . toString ( text . charAt ( i ) ) , i ) ) ; lastStart = i + 1 ; } allTokens . addAll ( tokensNonNull ( text . substring ( lastStart ) , lastStart ) ) ; return allTokens ; }
Split the given natural language text into a list of Token objects .
40,658
public synchronized List < Sentence > sentences ( String text ) { requireValidHandle ( ) ; Libvoikko lib = getLib ( ) ; List < Sentence > result = new ArrayList < Sentence > ( ) ; if ( ! isValidInput ( text ) ) { result . add ( new Sentence ( text , SentenceStartType . NONE ) ) ; return result ; } byte [ ] textBytes = s2n ( text ) ; int textLen = textBytes . length - 1 ; SizeTByReference sentenceLenByRef = new SizeTByReference ( ) ; while ( textLen > 0 ) { int sentenceTypeInt = lib . voikkoNextSentenceStartCstr ( handle , textBytes , new SizeT ( textLen ) , sentenceLenByRef ) ; int sentenceLen = sentenceLenByRef . getValue ( ) . intValue ( ) ; SentenceStartType sentenceType = SentenceStartType . values ( ) [ sentenceTypeInt ] ; String tokenText = text . substring ( 0 , sentenceLen ) ; result . add ( new Sentence ( tokenText , sentenceType ) ) ; text = text . substring ( sentenceLen ) ; textBytes = s2n ( text ) ; textLen = textBytes . length - 1 ; } return result ; }
Split the given natural language text into a list of Sentence objects .
40,659
public static void addLibraryPath ( String libraryPath ) { for ( String libraryName : LIBRARY_NAMES ) { NativeLibrary . addSearchPath ( libraryName , libraryPath ) ; } }
Set the explicit path to the folder containing shared library files .
40,660
public final < U > void addPartial ( HtmlView < U > partial , U model ) { getVisitor ( ) . closeBeginTag ( ) ; partial . getVisitor ( ) . depth = getVisitor ( ) . depth ; if ( this . getVisitor ( ) . isWriting ( ) ) getVisitor ( ) . write ( partial . render ( model ) ) ; }
Adds a partial view to this view .
40,661
public File attemptToDownload ( URL fileLocation ) throws URISyntaxException , IOException { String filename = FilenameUtils . getName ( fileLocation . getFile ( ) ) ; SocketConfig socketConfig = SocketConfig . custom ( ) . setSoTimeout ( fileDownloadReadTimeout ) . build ( ) ; RequestConfig requestConfig = RequestConfig . custom ( ) . setConnectTimeout ( fileDownloadConnectTimeout ) . build ( ) ; HttpClientBuilder httpClientBuilder = HttpClients . custom ( ) . setDefaultSocketConfig ( socketConfig ) . setDefaultRequestConfig ( requestConfig ) . disableContentCompression ( ) ; if ( useSystemProxy && proxyConfig . isProxyAvailable ( ) ) { LOG . info ( "Using http proxy: " + proxyConfig . getHost ( ) + ":" + proxyConfig . getPort ( ) ) ; httpClientBuilder . setProxy ( new HttpHost ( proxyConfig . getHost ( ) , proxyConfig . getPort ( ) ) ) ; } CloseableHttpClient httpClient = httpClientBuilder . build ( ) ; LOG . info ( "Downloading '" + filename + "'..." ) ; CloseableHttpResponse fileDownloadResponse = httpClient . execute ( new HttpGet ( fileLocation . toURI ( ) ) ) ; HttpEntity remoteFileStream = fileDownloadResponse . getEntity ( ) ; File fileToDownload = new File ( downloadDirectory + File . separator + filename ) ; try { copyInputStreamToFile ( remoteFileStream . getContent ( ) , fileToDownload ) ; } catch ( IOException ex ) { LOG . error ( "Problem downloading '" + filename + "'... " + ex . getCause ( ) . getLocalizedMessage ( ) ) ; fileToDownload = null ; } finally { fileDownloadResponse . close ( ) ; } return fileToDownload ; }
Attempt to download a file
40,662
private String localFilePath ( File downloadDirectory ) throws MojoFailureException { if ( downloadDirectory . exists ( ) ) { if ( downloadDirectory . isDirectory ( ) ) { return downloadDirectory . getAbsolutePath ( ) ; } else { throw new MojoFailureException ( "'" + downloadDirectory . getAbsolutePath ( ) + "' is not a directory!" ) ; } } if ( downloadDirectory . mkdirs ( ) ) { return downloadDirectory . getAbsolutePath ( ) ; } else { throw new MojoFailureException ( "Unable to create download directory!" ) ; } }
Set the location directory where files will be downloaded to
40,663
protected File downloadFile ( DriverDetails driverDetails , boolean shouldWeCheckFileHash ) throws MojoExecutionException , IOException , URISyntaxException { URL remoteFileLocation = driverDetails . fileLocation ; final String filename = FilenameUtils . getName ( remoteFileLocation . getFile ( ) ) ; for ( int retryAttempts = 1 ; retryAttempts <= this . fileDownloadRetryAttempts ; retryAttempts ++ ) { File downloadedFile = fileDownloader . attemptToDownload ( remoteFileLocation ) ; if ( null != downloadedFile ) { if ( ! shouldWeCheckFileHash || checkFileHash ( downloadedFile , driverDetails . hash , driverDetails . hashType ) ) { LOG . info ( "Archive file '" + downloadedFile . getName ( ) + "' is valid : true" ) ; return downloadedFile ; } else { LOG . info ( "Archive file '" + downloadedFile . getName ( ) + "' is valid : false" ) ; } } LOG . info ( "Problem downloading '" + filename + "'... " ) ; if ( retryAttempts < this . fileDownloadRetryAttempts ) { LOG . info ( "Retry attempt " + ( retryAttempts ) + " for '" + filename + "'" ) ; } } throw new MojoExecutionException ( "Unable to successfully download '" + filename + "'!" ) ; }
Perform the file download
40,664
InputStream getInputStream ( ) throws IOException { switch ( filetype ) { case GZ : LOG . debug ( "Decompressing .gz file" ) ; return new GzipCompressorInputStream ( new FileInputStream ( compressedFile ) ) ; case BZ2 : LOG . debug ( "Decompressing .bz2 file" ) ; return new BZip2CompressorInputStream ( new FileInputStream ( compressedFile ) ) ; } return null ; }
Get an InputStream for the decompressed file .
40,665
DownloadableFileType getArchiveType ( ) { try { return DownloadableFileType . valueOf ( FilenameUtils . getExtension ( decompressedFilename ) . toUpperCase ( ) ) ; } catch ( IllegalArgumentException e ) { LOG . debug ( "Not a recognised Archive type" ) ; return null ; } }
Find out if the uncompressed file is an archive
40,666
private void setRepositoryMapFile ( ) throws MojoExecutionException { if ( this . customRepositoryMap != null && ! this . customRepositoryMap . isEmpty ( ) ) { File repositoryMap = getRepositoryMapFile ( this . customRepositoryMap ) ; if ( repositoryMap . exists ( ) ) { checkRepositoryMapIsValid ( repositoryMap ) ; try { this . xmlRepositoryMap = repositoryMap . toURI ( ) . toURL ( ) . openStream ( ) ; } catch ( IOException ioe ) { throw new MojoExecutionException ( ioe . getLocalizedMessage ( ) ) ; } } else { throw new MojoExecutionException ( "Repository map '" + repositoryMap . getAbsolutePath ( ) + "' does not exist" ) ; } } if ( this . xmlRepositoryMap == null ) { this . xmlRepositoryMap = this . getClass ( ) . getResourceAsStream ( "/RepositoryMap.xml" ) ; } }
Set the RepositoryMap used to get file information . If the supplied map is invalid it will default to the pre - packaged one here .
40,667
protected void checkRepositoryMapIsValid ( File repositoryMap ) throws MojoExecutionException { URL schemaFile = this . getClass ( ) . getResource ( "/RepositoryMap.xsd" ) ; Source xmlFile = new StreamSource ( repositoryMap ) ; SchemaFactory schemaFactory = SchemaFactory . newInstance ( XMLConstants . W3C_XML_SCHEMA_NS_URI ) ; try { Schema schema = schemaFactory . newSchema ( schemaFile ) ; Validator validator = schema . newValidator ( ) ; validator . validate ( xmlFile ) ; LOG . info ( "Repository map '" + xmlFile . getSystemId ( ) + "' is valid" ) ; LOG . info ( " " ) ; } catch ( SAXException | IOException ex ) { throw new MojoExecutionException ( repositoryMap . getName ( ) + " is not valid: " + ex . getLocalizedMessage ( ) ) ; } }
Validate any custom repository maps that are supplied against the xsd . Throw an error and stop if it is not valid . Assume it doesn t exist if we get an IOError and fall back to default file .
40,668
public String extractFileFromArchive ( File downloadedCompressedFile , String extractedToFilePath , BinaryType possibleFilenames ) throws IOException , IllegalArgumentException , MojoFailureException { DownloadableFileType fileType = DownloadableFileType . valueOf ( FilenameUtils . getExtension ( downloadedCompressedFile . getName ( ) ) . toUpperCase ( ) ) ; LOG . debug ( "Determined archive type: " + fileType ) ; LOG . debug ( "Overwrite files that exist: " + overwriteFilesThatExist ) ; switch ( fileType ) { case GZ : case BZ2 : CompressedFile compressedFile = new CompressedFile ( downloadedCompressedFile ) ; if ( null != compressedFile . getArchiveType ( ) && compressedFile . getArchiveType ( ) . equals ( TAR ) ) { return untarFile ( compressedFile . getInputStream ( ) , extractedToFilePath , possibleFilenames ) ; } else { return copyFileToDisk ( compressedFile . getInputStream ( ) , extractedToFilePath , compressedFile . getDecompressedFilename ( ) ) ; } case ZIP : return unzipFile ( downloadedCompressedFile , extractedToFilePath , possibleFilenames ) ; case EXE : if ( possibleFilenames . getBinaryFilenames ( ) . contains ( downloadedCompressedFile . getName ( ) ) ) { return copyFileToDisk ( new FileInputStream ( downloadedCompressedFile ) , extractedToFilePath , downloadedCompressedFile . getName ( ) ) ; } default : throw new IllegalArgumentException ( "." + fileType + " is an unsupported archive type" ) ; } }
Extract binary from a downloaded archive file
40,669
private String copyFileToDisk ( InputStream inputStream , String pathToExtractTo , String filename ) throws IOException { if ( ! overwriteFilesThatExist ) { File [ ] existingFiles = new File ( pathToExtractTo ) . listFiles ( ) ; if ( null != existingFiles && existingFiles . length > 0 ) { for ( File existingFile : existingFiles ) { String existingFilename = existingFile . getName ( ) ; if ( existingFilename . equals ( filename ) ) { LOG . info ( "Binary '" + existingFilename + "' exists: true" ) ; LOG . info ( "Using existing '" + existingFilename + " 'binary." ) ; return existingFile . getAbsolutePath ( ) ; } } } } File outputFile = new File ( pathToExtractTo , filename ) ; try { if ( ! outputFile . exists ( ) && ! outputFile . getParentFile ( ) . mkdirs ( ) && ! outputFile . createNewFile ( ) ) { throw new IOException ( "Unable to create " + outputFile . getAbsolutePath ( ) ) ; } LOG . info ( "Extracting binary '" + filename + "'..." ) ; FileUtils . copyInputStreamToFile ( inputStream , outputFile ) ; LOG . info ( "Binary copied to " + outputFile . getAbsolutePath ( ) ) ; if ( ! outputFile . setExecutable ( true ) && ! outputFile . canExecute ( ) ) { LOG . warn ( "Unable to set executable flag (+x) on " + filename ) ; } } finally { inputStream . close ( ) ; } return outputFile . getAbsolutePath ( ) ; }
Copy a file from an inputsteam to disk
40,670
void postStart ( final DownloadRequest request , final long totalBytes ) { downloadPoster . execute ( new Runnable ( ) { public void run ( ) { request . downloadCallback ( ) . onStart ( request . downloadId ( ) , totalBytes ) ; } } ) ; }
Post download start event .
40,671
void postRetry ( final DownloadRequest request ) { downloadPoster . execute ( new Runnable ( ) { public void run ( ) { request . downloadCallback ( ) . onRetry ( request . downloadId ( ) ) ; } } ) ; }
Post download retry event .
40,672
void postProgress ( final DownloadRequest request , final long bytesWritten , final long totalBytes ) { downloadPoster . execute ( new Runnable ( ) { public void run ( ) { request . downloadCallback ( ) . onProgress ( request . downloadId ( ) , bytesWritten , totalBytes ) ; } } ) ; }
Post download progress event .
40,673
void postSuccess ( final DownloadRequest request ) { downloadPoster . execute ( new Runnable ( ) { public void run ( ) { request . downloadCallback ( ) . onSuccess ( request . downloadId ( ) , request . destinationFilePath ( ) ) ; } } ) ; }
Post download success event .
40,674
void postFailure ( final DownloadRequest request , final int statusCode , final String errMsg ) { downloadPoster . execute ( new Runnable ( ) { public void run ( ) { request . downloadCallback ( ) . onFailure ( request . downloadId ( ) , statusCode , errMsg ) ; } } ) ; }
Post download failure event .
40,675
public int add ( DownloadRequest request ) { request = checkNotNull ( request , "request == null" ) ; if ( isDownloading ( request . uri ( ) . toString ( ) ) ) { return - 1 ; } request . context ( context ) ; request . downloader ( downloader . copy ( ) ) ; return downloadRequestQueue . add ( request ) ? request . downloadId ( ) : - 1 ; }
Add one download request into the queue .
40,676
@ SuppressWarnings ( "ResultOfMethodCallIgnored" ) void updateDestinationFilePath ( String filename ) { String separator = destinationDirectory . endsWith ( "/" ) ? "" : File . separator ; destinationFilePath = destinationDirectory + separator + filename ; Log . d ( "TAG" , "destinationFilePath: " + destinationFilePath ) ; File file = new File ( destinationFilePath ) ; if ( ! file . getParentFile ( ) . exists ( ) ) { file . getParentFile ( ) . mkdirs ( ) ; } }
Update absolute file path according to the directory and filename .
40,677
boolean add ( DownloadRequest request ) { if ( query ( request . downloadId ( ) ) != DownloadState . INVALID || query ( request . uri ( ) ) != DownloadState . INVALID ) { Log . w ( TAG , "the download requst is in downloading" ) ; return false ; } request . downloadRequestQueue ( this ) ; synchronized ( currentRequests ) { currentRequests . add ( request ) ; } downloadQueue . add ( request ) ; return true ; }
Add download request to the download request queue .
40,678
boolean cancel ( int downloadId ) { synchronized ( currentRequests ) { for ( DownloadRequest request : currentRequests ) { if ( request . downloadId ( ) == downloadId ) { request . cancel ( ) ; return true ; } } } return false ; }
Cancel a download in progress .
40,679
DownloadState query ( int downloadId ) { synchronized ( currentRequests ) { for ( DownloadRequest request : currentRequests ) { if ( request . downloadId ( ) == downloadId ) { return request . downloadState ( ) ; } } } return DownloadState . INVALID ; }
To check if the request is downloading according to download id .
40,680
DownloadState query ( Uri uri ) { synchronized ( currentRequests ) { for ( DownloadRequest request : currentRequests ) { if ( request . uri ( ) . toString ( ) . equals ( uri . toString ( ) ) ) { return request . downloadState ( ) ; } } } return DownloadState . INVALID ; }
To check if the request is downloading according to download url .
40,681
void release ( ) { cancelAll ( ) ; if ( downloadQueue != null ) { downloadQueue = null ; } if ( dispatchers != null ) { stop ( ) ; for ( int i = 0 ; i < dispatchers . length ; i ++ ) { dispatchers [ i ] = null ; } dispatchers = null ; } }
Release all the resource .
40,682
static boolean isWifi ( Context context ) { if ( context == null ) { return false ; } ConnectivityManager manager = ( ConnectivityManager ) context . getSystemService ( Context . CONNECTIVITY_SERVICE ) ; if ( manager == null ) { return false ; } NetworkInfo info = manager . getActiveNetworkInfo ( ) ; return info != null && ( info . getType ( ) == ConnectivityManager . TYPE_WIFI ) ; }
To check whether current network is wifi .
40,683
static String getFilenameFromUrl ( String url ) { String filename = md5 ( url ) + ".down" ; int index = url . lastIndexOf ( "/" ) ; if ( index > 0 ) { String tmpFilename = url . substring ( index + 1 ) ; int qmarkIndex = tmpFilename . indexOf ( "?" ) ; if ( qmarkIndex > 0 ) { tmpFilename = tmpFilename . substring ( 0 , qmarkIndex - 1 ) ; } if ( tmpFilename . contains ( "." ) ) { filename = tmpFilename ; } } return filename ; }
Get filename from url .
40,684
public static String getFilenameFromHeader ( String url , String contentDisposition ) { String filename ; if ( ! TextUtils . isEmpty ( contentDisposition ) ) { int index = contentDisposition . indexOf ( "filename" ) ; if ( index > 0 ) { filename = contentDisposition . substring ( index + 9 , contentDisposition . length ( ) ) ; return filename ; } else { filename = getFilenameFromUrl ( url ) ; } } else { filename = getFilenameFromUrl ( url ) ; } try { filename = URLDecoder . decode ( filename , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { } return filename ; }
Get filename from content disposition in header .
40,685
@ SuppressWarnings ( "unchecked" ) public static JobManagerProfiler loadJobManagerProfiler ( String profilerClassName , InetAddress jobManagerBindAddress ) { final Class < ? extends JobManagerProfiler > profilerClass ; try { profilerClass = ( Class < ? extends JobManagerProfiler > ) Class . forName ( profilerClassName ) ; } catch ( ClassNotFoundException e ) { LOG . error ( "Cannot find class " + profilerClassName + ": " + StringUtils . stringifyException ( e ) ) ; return null ; } JobManagerProfiler profiler = null ; try { final Constructor < JobManagerProfiler > constr = ( Constructor < JobManagerProfiler > ) profilerClass . getConstructor ( InetAddress . class ) ; profiler = constr . newInstance ( jobManagerBindAddress ) ; } catch ( InvocationTargetException e ) { LOG . error ( "Cannot create profiler: " + StringUtils . stringifyException ( e ) ) ; return null ; } catch ( NoSuchMethodException e ) { LOG . error ( "Cannot create profiler: " + StringUtils . stringifyException ( e ) ) ; return null ; } catch ( InstantiationException e ) { LOG . error ( "Cannot create profiler: " + StringUtils . stringifyException ( e ) ) ; return null ; } catch ( IllegalAccessException e ) { LOG . error ( "Cannot create profiler: " + StringUtils . stringifyException ( e ) ) ; return null ; } catch ( IllegalArgumentException e ) { LOG . error ( "Cannot create profiler: " + StringUtils . stringifyException ( e ) ) ; return null ; } return profiler ; }
Creates an instance of the job manager s profiling component .
40,686
@ SuppressWarnings ( "unchecked" ) public static TaskManagerProfiler loadTaskManagerProfiler ( String profilerClassName , InetAddress jobManagerAddress , InstanceConnectionInfo instanceConnectionInfo ) { final Class < ? extends TaskManagerProfiler > profilerClass ; try { profilerClass = ( Class < ? extends TaskManagerProfiler > ) Class . forName ( profilerClassName ) ; } catch ( ClassNotFoundException e ) { LOG . error ( "Cannot find class " + profilerClassName + ": " + StringUtils . stringifyException ( e ) ) ; return null ; } Constructor < ? extends TaskManagerProfiler > constructor = null ; try { constructor = profilerClass . getConstructor ( InetAddress . class , InstanceConnectionInfo . class ) ; } catch ( SecurityException e1 ) { LOG . error ( e1 ) ; return null ; } catch ( NoSuchMethodException e1 ) { LOG . error ( e1 ) ; return null ; } TaskManagerProfiler profiler = null ; try { profiler = constructor . newInstance ( jobManagerAddress , instanceConnectionInfo ) ; } catch ( IllegalArgumentException e ) { LOG . error ( e ) ; } catch ( InstantiationException e ) { LOG . error ( e ) ; } catch ( IllegalAccessException e ) { LOG . error ( e ) ; } catch ( InvocationTargetException e ) { LOG . error ( e ) ; } return profiler ; }
Creates an instance of the task manager s profiling component .
40,687
public static boolean createWire ( final DistributionPattern pattern , final int nodeLowerStage , final int nodeUpperStage , final int sizeSetLowerStage , final int sizeSetUpperStage ) { switch ( pattern ) { case BIPARTITE : return true ; case POINTWISE : if ( sizeSetLowerStage < sizeSetUpperStage ) { if ( nodeLowerStage == ( nodeUpperStage % sizeSetLowerStage ) ) { return true ; } } else { if ( ( nodeLowerStage % sizeSetUpperStage ) == nodeUpperStage ) { return true ; } } return false ; default : throw new IllegalStateException ( "No Match for Distribution Pattern found." ) ; } }
Checks if two subtasks of different tasks should be wired .
40,688
void insertForwardEdge ( final ManagementGroupEdge edge , final int index ) { while ( index >= this . forwardEdges . size ( ) ) { this . forwardEdges . add ( null ) ; } this . forwardEdges . set ( index , edge ) ; }
Inserts a new edge starting at this group vertex at the given index .
40,689
void insertBackwardEdge ( final ManagementGroupEdge edge , final int index ) { while ( index >= this . backwardEdges . size ( ) ) { this . backwardEdges . add ( null ) ; } this . backwardEdges . set ( index , edge ) ; }
Inserts a new edge arriving at this group vertex at the given index .
40,690
public ManagementGroupEdge getForwardEdge ( final int index ) { if ( index < this . forwardEdges . size ( ) ) { return this . forwardEdges . get ( index ) ; } return null ; }
Returns the group edge which leaves this group vertex at the given index .
40,691
public ManagementGroupEdge getBackwardEdge ( final int index ) { if ( index < this . backwardEdges . size ( ) ) { return this . backwardEdges . get ( index ) ; } return null ; }
Returns the group edge which arrives at this group vertex at the given index .
40,692
void collectVertices ( final List < ManagementVertex > vertices ) { final Iterator < ManagementVertex > it = this . groupMembers . iterator ( ) ; while ( it . hasNext ( ) ) { vertices . add ( it . next ( ) ) ; } }
Adds all management vertices which are included in this group vertex to the given list .
40,693
public ManagementVertex getGroupMember ( final int index ) { if ( index < this . groupMembers . size ( ) ) { return this . groupMembers . get ( index ) ; } return null ; }
Returns the management vertex with the given index .
40,694
public List < ManagementGroupVertex > getSuccessors ( ) { final List < ManagementGroupVertex > successors = new ArrayList < ManagementGroupVertex > ( ) ; for ( ManagementGroupEdge edge : this . forwardEdges ) { successors . add ( edge . getTarget ( ) ) ; } return successors ; }
Returns the list of successors of this group vertex . A successor is a group vertex which can be reached via a group edge originating at this group vertex .
40,695
public List < ManagementGroupVertex > getPredecessors ( ) { final List < ManagementGroupVertex > predecessors = new ArrayList < ManagementGroupVertex > ( ) ; for ( ManagementGroupEdge edge : this . backwardEdges ) { predecessors . add ( edge . getSource ( ) ) ; } return predecessors ; }
Returns the list of predecessors of this group vertex . A predecessors is a group vertex which can be reached via a group edge arriving at this group vertex .
40,696
public String toJson ( ) { StringBuilder json = new StringBuilder ( "" ) ; json . append ( "{" ) ; json . append ( "\"groupvertexid\": \"" + this . getID ( ) + "\"," ) ; json . append ( "\"groupvertexname\": \"" + StringUtils . escapeHtml ( this . getName ( ) ) + "\"," ) ; json . append ( "\"numberofgroupmembers\": " + this . getNumberOfGroupMembers ( ) + "," ) ; json . append ( "\"groupmembers\": [" ) ; Map < ExecutionState , Integer > stateCounts = new HashMap < ExecutionState , Integer > ( ) ; for ( ExecutionState state : ExecutionState . values ( ) ) { stateCounts . put ( state , new Integer ( 0 ) ) ; } for ( int j = 0 ; j < this . getNumberOfGroupMembers ( ) ; j ++ ) { ManagementVertex vertex = this . getGroupMember ( j ) ; json . append ( vertex . toJson ( ) ) ; if ( j != this . getNumberOfGroupMembers ( ) - 1 ) { json . append ( "," ) ; } Integer count = stateCounts . get ( vertex . getExecutionState ( ) ) + new Integer ( 1 ) ; stateCounts . put ( vertex . getExecutionState ( ) , count ) ; } json . append ( "]," ) ; json . append ( "\"backwardEdges\": [" ) ; for ( int edgeIndex = 0 ; edgeIndex < this . getNumberOfBackwardEdges ( ) ; edgeIndex ++ ) { ManagementGroupEdge edge = this . getBackwardEdge ( edgeIndex ) ; json . append ( "{" ) ; json . append ( "\"groupvertexid\": \"" + edge . getSource ( ) . getID ( ) + "\"," ) ; json . append ( "\"groupvertexname\": \"" + StringUtils . escapeHtml ( edge . getSource ( ) . getName ( ) ) + "\"," ) ; json . append ( "\"channelType\": \"" + edge . getChannelType ( ) + "\"" ) ; json . append ( "}" ) ; if ( edgeIndex != this . getNumberOfBackwardEdges ( ) - 1 ) { json . append ( "," ) ; } } json . append ( "]" ) ; for ( Map . Entry < ExecutionState , Integer > stateCount : stateCounts . entrySet ( ) ) { json . append ( ",\"" + stateCount . getKey ( ) + "\": " + stateCount . getValue ( ) ) ; } json . append ( "}" ) ; return json . toString ( ) ; }
Returns Json representation of this ManagementGroupVertex
40,697
public static final InstanceType createDefaultInstanceType ( ) { final HardwareDescription hardwareDescription = HardwareDescriptionFactory . extractFromSystem ( ) ; int diskCapacityInGB = 0 ; final String [ ] tempDirs = GlobalConfiguration . getString ( ConfigConstants . TASK_MANAGER_TMP_DIR_KEY , ConfigConstants . DEFAULT_TASK_MANAGER_TMP_PATH ) . split ( File . pathSeparator ) ; for ( final String tempDir : tempDirs ) { if ( tempDir != null ) { File f = new File ( tempDir ) ; diskCapacityInGB = Math . max ( diskCapacityInGB , ( int ) ( f . getFreeSpace ( ) / ( 1024L * 1024L * 1024L ) ) ) ; } } final int physicalMemory = ( int ) ( hardwareDescription . getSizeOfPhysicalMemory ( ) / ( 1024L * 1024L ) ) ; return InstanceTypeFactory . construct ( "default" , hardwareDescription . getNumberOfCPUCores ( ) , hardwareDescription . getNumberOfCPUCores ( ) , physicalMemory , diskCapacityInGB , 0 ) ; }
Creates a default instance type based on the hardware characteristics of the machine that calls this method . The default instance type contains the machine s number of CPU cores and size of physical memory . The disc capacity is calculated from the free space in the directory for temporary files .
40,698
public JobExecutionResult run ( JobWithJars prog , int parallelism , boolean wait ) throws CompilerException , ProgramInvocationException { return run ( getOptimizedPlan ( prog , parallelism ) , prog . getJarFiles ( ) , wait ) ; }
Runs a program on the nephele system whose job - manager is configured in this client s configuration . This method involves all steps from compiling job - graph generation to submission .
40,699
public FutureTask < Path > createTmpFile ( String name , String filePath , JobID jobID ) { synchronized ( count ) { Pair < JobID , String > key = new ImmutablePair ( jobID , name ) ; if ( count . containsKey ( key ) ) { count . put ( key , count . get ( key ) + 1 ) ; } else { count . put ( key , 1 ) ; } } CopyProcess cp = new CopyProcess ( name , filePath , jobID ) ; FutureTask < Path > copyTask = new FutureTask < Path > ( cp ) ; executorService . submit ( copyTask ) ; return copyTask ; }
If the file doesn t exists locally it will copy the file to the temp directory .