idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
36,500 | public final FacetOptions addFacetOnFlieldnames ( Collection < String > fieldnames ) { Assert . notNull ( fieldnames , "Fieldnames must not be null!" ) ; for ( String fieldname : fieldnames ) { addFacetOnField ( fieldname ) ; } return this ; } | Append all fieldnames for faceting |
36,501 | public String createQueryStringFromNode ( Node node , int position ) { return createQueryStringFromNode ( node , position , null ) ; } | Create the plain query string representation of the given node . |
36,502 | @ SuppressWarnings ( "unchecked" ) public final < T extends SolrDataQuery > T addCriteria ( Criteria criteria ) { Assert . notNull ( criteria , "Cannot add null criteria." ) ; if ( this . criteria == null ) { this . criteria = criteria ; } else { if ( this . criteria instanceof Crotch ) { ( ( Crotch ) this . criteria ) . add ( criteria ) ; } else { Crotch tree = new Crotch ( ) ; tree . add ( this . criteria ) ; tree . add ( criteria ) ; this . criteria = tree ; } } return ( T ) this ; } | Add an criteria to the query . The criteria will be connected using AND . |
36,503 | protected void doClose ( ) { this . delegate = Collections . < T > emptyList ( ) . iterator ( ) ; this . referenceQuery . clear ( ) ; this . position = - 1 ; this . cursorMark = null ; } | Customization hook for clean up operations |
36,504 | public static Set < Exclusion > setupExcludedArtifacts ( List < String > excludedArtifacts ) throws MojoExecutionException { Set < Exclusion > exclusionSet = new HashSet < > ( ) ; for ( String artifact : Optional . ofNullable ( excludedArtifacts ) . orElse ( Collections . emptyList ( ) ) ) { exclusionSet . add ( convertExclusionPatternIntoExclusion ( artifact ) ) ; } for ( String artifact : BLACKLISTED_ARTIFACTS ) { exclusionSet . add ( convertExclusionPatternIntoExclusion ( artifact ) ) ; } return exclusionSet ; } | Build up an exclusion set |
36,505 | static Exclusion convertExclusionPatternIntoExclusion ( String exceptionPattern ) throws MojoExecutionException { Matcher matcher = COORDINATE_PATTERN . matcher ( exceptionPattern ) ; if ( ! matcher . matches ( ) ) { throw new MojoExecutionException ( String . format ( "Bad artifact coordinates %s, expected format is <groupId>:<artifactId>[:<extension>][:<classifier>]" , exceptionPattern ) ) ; } return new Exclusion ( matcher . group ( 1 ) , matcher . group ( 2 ) , matcher . group ( 4 ) , matcher . group ( 6 ) ) ; } | Convert an exclusion pattern into an Exclusion object |
36,506 | public static boolean artifactIsNotExcluded ( Collection < Exclusion > exclusions , Artifact artifact ) { return Optional . ofNullable ( exclusions ) . orElse ( Collections . emptyList ( ) ) . stream ( ) . noneMatch ( selectedExclusion -> null != artifact && selectedExclusion . getGroupId ( ) . equals ( artifact . getGroupId ( ) ) && ( selectedExclusion . getArtifactId ( ) . equals ( artifact . getArtifactId ( ) ) || ( selectedExclusion . getArtifactId ( ) . equals ( ARTIFACT_STAR ) ) ) ) ; } | Check that an artifact is not excluded |
36,507 | public static List < String > createDefaultJmeterArtifactsArray ( String jmeterVersion ) { List < String > artifacts = new ArrayList < > ( ) ; JMETER_ARTIFACT_NAMES . forEach ( artifactName -> artifacts . add ( String . format ( "%s:%s:%s" , JMETER_GROUP_ID , artifactName , jmeterVersion ) ) ) ; return artifacts ; } | Create a default Array of JMeter artifact coordinates |
36,508 | public static boolean isArtifactIsOlderThanArtifact ( Artifact artifact , Artifact comparisonArtifact ) throws InvalidVersionSpecificationException { GenericVersionScheme genericVersionScheme = new GenericVersionScheme ( ) ; Version firstArtifactVersion = genericVersionScheme . parseVersion ( artifact . getVersion ( ) ) ; Version secondArtifactVersion = genericVersionScheme . parseVersion ( comparisonArtifact . getVersion ( ) ) ; return firstArtifactVersion . compareTo ( secondArtifactVersion ) < 0 ; } | Check to see if a specified artifact is the same version or a newer version that the comparative artifact |
36,509 | public void doExecute ( ) throws MojoExecutionException { getLog ( ) . info ( " " ) ; getLog ( ) . info ( LINE_SEPARATOR ) ; getLog ( ) . info ( "C O N F I G U R I N G J M E T E R" ) ; getLog ( ) . info ( LINE_SEPARATOR ) ; getLog ( ) . info ( " " ) ; processedArtifacts . clear ( ) ; JMeterConfigurationHolder . getInstance ( ) . resetConfiguration ( ) ; parsedExcludedArtifacts = setupExcludedArtifacts ( excludedArtifacts ) ; getLog ( ) . info ( "Building JMeter directory structure..." ) ; generateJMeterDirectoryTree ( ) ; getLog ( ) . info ( "Configuring JMeter artifacts..." ) ; configureJMeterArtifacts ( ) ; getLog ( ) . info ( "Populating JMeter directory..." ) ; populateJMeterDirectoryTree ( ) ; getLog ( ) . info ( String . format ( "Copying extensions to JMeter lib/ext directory %s with downloadExtensionDependencies set to %s..." , libExtDirectory , downloadExtensionDependencies ) ) ; copyExplicitLibraries ( jmeterExtensions , libExtDirectory , downloadExtensionDependencies ) ; getLog ( ) . info ( String . format ( "Copying JUnit libraries to JMeter junit lib directory %s with downloadLibraryDependencies set to %s..." , libJUnitDirectory , downloadLibraryDependencies ) ) ; copyExplicitLibraries ( junitLibraries , libJUnitDirectory , downloadLibraryDependencies ) ; getLog ( ) . info ( String . format ( "Copying test libraries to JMeter lib directory %s with downloadLibraryDependencies set to %s..." , libDirectory , downloadLibraryDependencies ) ) ; copyExplicitLibraries ( testPlanLibraries , libDirectory , downloadLibraryDependencies ) ; getLog ( ) . info ( "Configuring JMeter properties..." ) ; configurePropertiesFiles ( ) ; getLog ( ) . info ( "Generating JSON Test config..." ) ; generateTestConfig ( ) ; JMeterConfigurationHolder . getInstance ( ) . freezeConfiguration ( ) ; } | Configure a local instance of JMeter |
36,510 | private void generateJMeterDirectoryTree ( ) { File workingDirectory = new File ( jmeterDirectory , "bin" ) ; workingDirectory . mkdirs ( ) ; JMeterConfigurationHolder . getInstance ( ) . setWorkingDirectory ( workingDirectory ) ; customPropertiesDirectory = new File ( jmeterDirectory , "custom_properties" ) ; customPropertiesDirectory . mkdirs ( ) ; libDirectory = new File ( jmeterDirectory , "lib" ) ; libExtDirectory = new File ( libDirectory , "ext" ) ; libExtDirectory . mkdirs ( ) ; libJUnitDirectory = new File ( libDirectory , "junit" ) ; libJUnitDirectory . mkdirs ( ) ; testFilesBuildDirectory . mkdirs ( ) ; resultsDirectory . mkdirs ( ) ; if ( generateReports ) { reportDirectory . mkdirs ( ) ; } logsDirectory . mkdirs ( ) ; } | Generate the directory tree utilised by JMeter . |
36,511 | private void configureJMeterArtifacts ( ) { if ( jmeterArtifacts . isEmpty ( ) ) { jmeterArtifacts = createDefaultJmeterArtifactsArray ( jmeterVersion ) ; } getLog ( ) . debug ( "JMeter Artifact List:" ) ; jmeterArtifacts . forEach ( artifact -> getLog ( ) . debug ( artifact ) ) ; } | This sets the default list of artifacts that we use to set up a local instance of JMeter . We only use this default list if < ; jmeterArtifacts> ; has not been overridden in the POM . |
36,512 | private void copyExplicitLibraries ( List < String > desiredArtifacts , File destination , boolean downloadDependencies ) throws MojoExecutionException { for ( String desiredArtifact : desiredArtifacts ) { copyExplicitLibrary ( desiredArtifact , destination , downloadDependencies ) ; } } | Copy a list of libraries to a specific folder . |
36,513 | private Artifact getArtifactResult ( Artifact desiredArtifact ) throws MojoExecutionException { ArtifactRequest artifactRequest = new ArtifactRequest ( ) ; artifactRequest . setArtifact ( desiredArtifact ) ; artifactRequest . setRepositories ( repositoryList ) ; try { return repositorySystem . resolveArtifact ( repositorySystemSession , artifactRequest ) . getArtifact ( ) ; } catch ( ArtifactResolutionException e ) { throw new MojoExecutionException ( e . getMessage ( ) , e ) ; } } | Find a specific artifact in a remote repository |
36,514 | private boolean copyArtifactIfRequired ( Artifact artifactToCopy , Path destinationDirectory ) throws MojoExecutionException { for ( String ignoredArtifact : ignoredArtifacts ) { Artifact artifactToIgnore = getArtifactResult ( new DefaultArtifact ( ignoredArtifact ) ) ; if ( artifactToCopy . getFile ( ) . getName ( ) . equals ( artifactToIgnore . getFile ( ) . getName ( ) ) ) { getLog ( ) . debug ( artifactToCopy . getFile ( ) . getName ( ) + " has not been copied over because it is in the ignore list." ) ; return false ; } } try { for ( Iterator < Artifact > iterator = copiedArtifacts . iterator ( ) ; iterator . hasNext ( ) ; ) { Artifact alreadyCopiedArtifact = iterator . next ( ) ; if ( artifactsAreMatchingTypes ( alreadyCopiedArtifact , artifactToCopy ) ) { if ( isArtifactIsOlderThanArtifact ( alreadyCopiedArtifact , artifactToCopy ) ) { Path artifactToDelete = Paths . get ( destinationDirectory . toString ( ) , alreadyCopiedArtifact . getFile ( ) . getName ( ) ) ; getLog ( ) . debug ( String . format ( "Deleting file:'%s'" , artifactToDelete ) ) ; Files . deleteIfExists ( artifactToDelete ) ; iterator . remove ( ) ; break ; } else { return false ; } } } Path desiredArtifact = Paths . get ( destinationDirectory . toString ( ) , artifactToCopy . getFile ( ) . getName ( ) ) ; if ( ! desiredArtifact . toFile ( ) . exists ( ) ) { getLog ( ) . debug ( String . format ( "Copying: %s to %s" , desiredArtifact . toString ( ) , destinationDirectory . toString ( ) ) ) ; Files . copy ( Paths . get ( artifactToCopy . getFile ( ) . getAbsolutePath ( ) ) , desiredArtifact ) ; } } catch ( IOException | InvalidVersionSpecificationException e ) { throw new MojoExecutionException ( e . getMessage ( ) , e ) ; } copiedArtifacts . add ( artifactToCopy ) ; return true ; } | Copy an Artifact to a directory |
36,515 | public List < String > buildArgumentsArray ( ) throws MojoExecutionException { if ( ! argumentList . contains ( TESTFILE_OPT ) && ! disableTests ) { throw new MojoExecutionException ( "No test(s) specified!" ) ; } List < String > argumentsArray = new ArrayList < > ( ) ; for ( JMeterCommandLineArguments argument : argumentList ) { switch ( argument ) { case NONGUI_OPT : argumentsArray . add ( NONGUI_OPT . getCommandLineArgument ( ) ) ; break ; case TESTFILE_OPT : argumentsArray . add ( TESTFILE_OPT . getCommandLineArgument ( ) ) ; argumentsArray . add ( testFile ) ; break ; case LOGFILE_OPT : argumentsArray . add ( LOGFILE_OPT . getCommandLineArgument ( ) ) ; argumentsArray . add ( resultsLogFileName ) ; break ; case JMETER_HOME_OPT : argumentsArray . add ( JMETER_HOME_OPT . getCommandLineArgument ( ) ) ; argumentsArray . add ( jMeterHome ) ; break ; case LOGLEVEL : argumentsArray . add ( LOGLEVEL . getCommandLineArgument ( ) ) ; argumentsArray . add ( overrideRootLogLevel . toString ( ) ) ; break ; case PROPFILE2_OPT : for ( String customPropertiesFile : customPropertiesFiles ) { argumentsArray . add ( PROPFILE2_OPT . getCommandLineArgument ( ) ) ; argumentsArray . add ( customPropertiesFile ) ; } break ; case REMOTE_OPT : argumentsArray . add ( REMOTE_OPT . getCommandLineArgument ( ) ) ; break ; case PROXY_HOST : argumentsArray . add ( PROXY_HOST . getCommandLineArgument ( ) ) ; argumentsArray . add ( proxyConfiguration . getHost ( ) ) ; break ; case PROXY_PORT : argumentsArray . add ( PROXY_PORT . getCommandLineArgument ( ) ) ; argumentsArray . add ( proxyConfiguration . getPort ( ) ) ; break ; case PROXY_USERNAME : argumentsArray . add ( PROXY_USERNAME . getCommandLineArgument ( ) ) ; argumentsArray . add ( proxyConfiguration . getUsername ( ) ) ; break ; case PROXY_PASSWORD : argumentsArray . add ( PROXY_PASSWORD . getCommandLineArgument ( ) ) ; argumentsArray . add ( proxyConfiguration . getPassword ( ) ) ; break ; case NONPROXY_HOSTS : argumentsArray . add ( NONPROXY_HOSTS . getCommandLineArgument ( ) ) ; argumentsArray . add ( proxyConfiguration . getHostExclusions ( ) ) ; break ; case REMOTE_STOP : argumentsArray . add ( REMOTE_STOP . getCommandLineArgument ( ) ) ; break ; case REMOTE_OPT_PARAM : argumentsArray . add ( REMOTE_OPT_PARAM . getCommandLineArgument ( ) ) ; argumentsArray . add ( remoteStartServerList ) ; break ; case JMLOGFILE_OPT : argumentsArray . add ( JMLOGFILE_OPT . getCommandLineArgument ( ) ) ; argumentsArray . add ( jmeterLogFileName ) ; break ; case REPORT_AT_END_OPT : argumentsArray . add ( REPORT_AT_END_OPT . getCommandLineArgument ( ) ) ; break ; case REPORT_OUTPUT_FOLDER_OPT : argumentsArray . add ( REPORT_OUTPUT_FOLDER_OPT . getCommandLineArgument ( ) ) ; argumentsArray . add ( reportDirectory ) ; break ; case SERVER_OPT : argumentsArray . add ( SERVER_OPT . getCommandLineArgument ( ) ) ; break ; case SYSTEM_PROPFILE : case JMETER_PROPERTY : case JMETER_GLOBAL_PROP : case SYSTEM_PROPERTY : case VERSION_OPT : case PROPFILE_OPT : case REPORT_GENERATING_OPT : case HELP_OPT : break ; } } return argumentsArray ; } | Generate an arguments array representing the command line options you want to send to JMeter . The order of the array is determined by the order the values in JMeterCommandLineArguments are defined . |
36,516 | public void doExecute ( ) throws MojoExecutionException { getLog ( ) . info ( " " ) ; getLog ( ) . info ( LINE_SEPARATOR ) ; getLog ( ) . info ( " S T A R T I N G J M E T E R S E R V E R " ) ; getLog ( ) . info ( LINE_SEPARATOR ) ; getLog ( ) . info ( String . format ( " Host: %s" , exportedRmiHostname ) ) ; getLog ( ) . info ( String . format ( " Port: %s" , serverPort ) ) ; startJMeterServer ( initializeJMeterArgumentsArray ( ) ) ; } | Load the JMeter server |
36,517 | public void doExecute ( ) throws MojoExecutionException { getLog ( ) . info ( " " ) ; getLog ( ) . info ( LINE_SEPARATOR ) ; getLog ( ) . info ( " P E R F O R M A N C E T E S T S" ) ; getLog ( ) . info ( LINE_SEPARATOR ) ; getLog ( ) . info ( " " ) ; if ( ! testFilesDirectory . exists ( ) ) { getLog ( ) . info ( "<testFilesDirectory>" + testFilesDirectory . getAbsolutePath ( ) + "</testFilesDirectory> does not exist..." ) ; getLog ( ) . info ( "Performance tests skipped!" ) ; getLog ( ) . info ( " " ) ; return ; } TestConfig testConfig = new TestConfig ( new File ( testConfigFile ) ) ; JMeterConfigurationHolder configuration = JMeterConfigurationHolder . getInstance ( ) ; remoteConfig . setPropertiesMap ( configuration . getPropertiesMap ( ) ) ; jMeterProcessJVMSettings . setHeadlessDefaultIfRequired ( ) ; copyFilesInTestDirectory ( testFilesDirectory , testFilesBuildDirectory ) ; TestManager jMeterTestManager = new TestManager ( ) . setBaseTestArgs ( computeJMeterArgumentsArray ( true , testConfig . getResultsOutputIsCSVFormat ( ) ) ) . setTestFilesDirectory ( testFilesBuildDirectory ) . setTestFilesIncluded ( testFilesIncluded ) . setTestFilesExcluded ( testFilesExcluded ) . setRemoteServerConfiguration ( remoteConfig ) . setSuppressJMeterOutput ( suppressJMeterOutput ) . setBinDir ( configuration . getWorkingDirectory ( ) ) . setJMeterProcessJVMSettings ( jMeterProcessJVMSettings ) . setRuntimeJarName ( configuration . getRuntimeJarName ( ) ) . setReportDirectory ( reportDirectory ) . setGenerateReports ( generateReports ) . setPostTestPauseInSeconds ( postTestPauseInSeconds ) ; if ( proxyConfig != null ) { getLog ( ) . info ( this . proxyConfig . toString ( ) ) ; } testConfig . setResultsFileLocations ( jMeterTestManager . executeTests ( ) ) ; testConfig . writeResultFilesConfigTo ( testConfigFile ) ; } | Run all the JMeter tests . |
36,518 | protected JMeterArgumentsArray computeJMeterArgumentsArray ( boolean disableGUI , boolean isCSVFormat ) throws MojoExecutionException { JMeterArgumentsArray testArgs = new JMeterArgumentsArray ( disableGUI , jmeterDirectory . getAbsolutePath ( ) ) . setResultsDirectory ( resultsDirectory . getAbsolutePath ( ) ) . setResultFileOutputFormatIsCSV ( isCSVFormat ) . setProxyConfig ( proxyConfig ) . setLogRootOverride ( overrideRootLogLevel ) . setLogsDirectory ( logsDirectory . getAbsolutePath ( ) ) . addACustomPropertiesFiles ( customPropertiesFiles ) ; if ( generateReports && disableGUI ) { testArgs . setReportsDirectory ( reportDirectory . getAbsolutePath ( ) ) ; } if ( testResultsTimestamp ) { testArgs . setResultsTimestamp ( true ) . appendTimestamp ( appendResultsTimestamp ) . setResultsFileNameDateFormat ( resultsFileNameDateFormat ) ; } return testArgs ; } | Generate the initial JMeter Arguments array that is used to create the command line that we pass to JMeter . |
36,519 | protected void loadMavenProxy ( ) { if ( null == settings ) { return ; } Proxy mvnProxy = settings . getActiveProxy ( ) ; if ( mvnProxy != null ) { ProxyConfiguration newProxyConfiguration = new ProxyConfiguration ( ) ; newProxyConfiguration . setHost ( mvnProxy . getHost ( ) ) ; newProxyConfiguration . setPort ( mvnProxy . getPort ( ) ) ; newProxyConfiguration . setUsername ( mvnProxy . getUsername ( ) ) ; newProxyConfiguration . setPassword ( mvnProxy . getPassword ( ) ) ; newProxyConfiguration . setHostExclusions ( mvnProxy . getNonProxyHosts ( ) ) ; proxyConfig = newProxyConfiguration ; getLog ( ) . info ( "Maven proxy loaded successfully" ) ; } else { getLog ( ) . warn ( "No maven proxy found, however useMavenProxy is set to true!" ) ; } } | Try to load the active maven proxy . |
36,520 | public static String humanReadableCommandLineOutput ( List < String > arguments ) { StringBuilder debugOutput = new StringBuilder ( ) ; for ( String argument : arguments ) { debugOutput . append ( argument ) . append ( " " ) ; } return debugOutput . toString ( ) . trim ( ) ; } | Build a human readable command line from the arguments set by the plugin |
36,521 | public static Boolean isNotSet ( String value ) { return null == value || value . isEmpty ( ) || value . trim ( ) . length ( ) == 0 ; } | Utility function to check if a String is defined and not empty |
36,522 | public static Boolean isNotSet ( File value ) { return null == value || value . toString ( ) . isEmpty ( ) || value . toString ( ) . trim ( ) . length ( ) == 0 ; } | Utility function to check if File is defined and not empty |
36,523 | public void doExecute ( ) throws MojoExecutionException { getLog ( ) . info ( " " ) ; getLog ( ) . info ( LINE_SEPARATOR ) ; getLog ( ) . info ( " S T A R T I N G J M E T E R G U I " ) ; getLog ( ) . info ( LINE_SEPARATOR ) ; startJMeterGUI ( initialiseJMeterArgumentsArray ( ) ) ; } | Load the JMeter GUI |
36,524 | private Properties loadPropertiesFile ( File propertiesFile ) throws MojoExecutionException { try ( FileInputStream propertiesFileInputStream = new FileInputStream ( propertiesFile ) ) { Properties loadedProperties = new Properties ( ) ; loadedProperties . load ( propertiesFileInputStream ) ; return loadedProperties ; } catch ( IOException e ) { throw new MojoExecutionException ( e . getMessage ( ) , e ) ; } } | Take a properties file and load it into a Properties Object |
36,525 | public void loadProvidedPropertiesIfAvailable ( File providedPropertiesFile , boolean replaceAllProperties ) throws MojoExecutionException { if ( providedPropertiesFile . exists ( ) ) { Properties providedPropertySet = loadPropertiesFile ( providedPropertiesFile ) ; if ( replaceAllProperties ) { this . properties = providedPropertySet ; } else { this . properties . putAll ( providedPropertySet ) ; } } } | Check if a file exists . If it does calculate if we need to merge it with existing properties or replace all existing properties . |
36,526 | public void addAndOverwriteProperties ( Map < String , String > additionalProperties ) { additionalProperties . values ( ) . removeAll ( Collections . singleton ( null ) ) ; for ( Map . Entry < String , String > additionalPropertiesMap : additionalProperties . entrySet ( ) ) { if ( ! additionalPropertiesMap . getValue ( ) . trim ( ) . isEmpty ( ) ) { properties . setProperty ( additionalPropertiesMap . getKey ( ) , additionalPropertiesMap . getValue ( ) ) ; warnUserOfPossibleErrors ( additionalPropertiesMap . getKey ( ) , properties ) ; } } } | Merge a Map of properties into our Properties object The additions will overwrite any existing properties |
36,527 | public void writePropertiesToFile ( File outputFile ) throws MojoExecutionException { stripOutReservedProperties ( ) ; if ( properties . isEmpty ( ) ) { return ; } try { try ( FileOutputStream writeOutFinalPropertiesFile = new FileOutputStream ( outputFile ) ) { properties . store ( writeOutFinalPropertiesFile , null ) ; writeOutFinalPropertiesFile . flush ( ) ; } } catch ( IOException e ) { throw new MojoExecutionException ( e . getMessage ( ) , e ) ; } } | Strip out any reserved properties and then write properties object to a file . |
36,528 | private void warnUserOfPossibleErrors ( String newKey , Properties baseProperties ) { for ( String key : baseProperties . stringPropertyNames ( ) ) { if ( ! key . equals ( newKey ) && key . equalsIgnoreCase ( newKey ) ) { LOGGER . warn ( "You have set a property called '{}' which is very similar to '{}'!" , newKey , key ) ; } } } | Print a warning out to the user to highlight potential typos in the properties they have set . |
36,529 | public boolean load ( String name , boolean verify ) { boolean loaded = false ; try { Platform platform = Platform . detect ( ) ; JarFile jar = new JarFile ( codeSource . getLocation ( ) . getPath ( ) , verify ) ; try { for ( String path : libCandidates ( platform , name ) ) { JarEntry entry = jar . getJarEntry ( path ) ; if ( entry == null ) continue ; File lib = extract ( name , jar . getInputStream ( entry ) ) ; System . load ( lib . getAbsolutePath ( ) ) ; lib . delete ( ) ; loaded = true ; break ; } } finally { jar . close ( ) ; } } catch ( Throwable e ) { loaded = false ; } return loaded ; } | Load a shared library and optionally verify the jar signatures . |
36,530 | private static File extract ( String name , InputStream is ) throws IOException { byte [ ] buf = new byte [ 4096 ] ; int len ; File lib = File . createTempFile ( name , "lib" ) ; FileOutputStream os = new FileOutputStream ( lib ) ; try { while ( ( len = is . read ( buf ) ) > 0 ) { os . write ( buf , 0 , len ) ; } } catch ( IOException e ) { lib . delete ( ) ; throw e ; } finally { os . close ( ) ; is . close ( ) ; } return lib ; } | Extract a jar entry to a temp file . |
36,531 | private List < String > libCandidates ( Platform platform , String name ) { List < String > candidates = new ArrayList < String > ( ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( libraryPath ) . append ( "/" ) ; sb . append ( platform . arch ) . append ( "/" ) ; sb . append ( platform . os ) . append ( "/" ) ; sb . append ( "lib" ) . append ( name ) ; switch ( platform . os ) { case darwin : candidates . add ( sb + ".dylib" ) ; candidates . add ( sb + ".jnilib" ) ; break ; case linux : case freebsd : candidates . add ( sb + ".so" ) ; break ; } return candidates ; } | Generate a list of candidate libraries for the supplied library name and suitable for the current platform . |
36,532 | public static byte [ ] decode ( char [ ] src , int [ ] table , char pad ) { int len = src . length ; if ( len == 0 ) return new byte [ 0 ] ; int padCount = ( src [ len - 1 ] == pad ? ( src [ len - 2 ] == pad ? 2 : 1 ) : 0 ) ; int bytes = ( len * 6 >> 3 ) - padCount ; int blocks = ( bytes / 3 ) * 3 ; byte [ ] dst = new byte [ bytes ] ; int si = 0 , di = 0 ; while ( di < blocks ) { int n = table [ src [ si ++ ] ] << 18 | table [ src [ si ++ ] ] << 12 | table [ src [ si ++ ] ] << 6 | table [ src [ si ++ ] ] ; dst [ di ++ ] = ( byte ) ( n >> 16 ) ; dst [ di ++ ] = ( byte ) ( n >> 8 ) ; dst [ di ++ ] = ( byte ) n ; } if ( di < bytes ) { int n = 0 ; switch ( len - si ) { case 4 : n |= table [ src [ si + 3 ] ] ; case 3 : n |= table [ src [ si + 2 ] ] << 6 ; case 2 : n |= table [ src [ si + 1 ] ] << 12 ; case 1 : n |= table [ src [ si ] ] << 18 ; } for ( int r = 16 ; di < bytes ; r -= 8 ) { dst [ di ++ ] = ( byte ) ( n >> r ) ; } } return dst ; } | Decode base64 chars to bytes using the supplied decode table and padding character . |
36,533 | public static char [ ] encode ( byte [ ] src , char [ ] table , char pad ) { int len = src . length ; if ( len == 0 ) return new char [ 0 ] ; int blocks = ( len / 3 ) * 3 ; int chars = ( ( len - 1 ) / 3 + 1 ) << 2 ; int tail = len - blocks ; if ( pad == 0 && tail > 0 ) chars -= 3 - tail ; char [ ] dst = new char [ chars ] ; int si = 0 , di = 0 ; while ( si < blocks ) { int n = ( src [ si ++ ] & 0xff ) << 16 | ( src [ si ++ ] & 0xff ) << 8 | ( src [ si ++ ] & 0xff ) ; dst [ di ++ ] = table [ ( n >>> 18 ) & 0x3f ] ; dst [ di ++ ] = table [ ( n >>> 12 ) & 0x3f ] ; dst [ di ++ ] = table [ ( n >>> 6 ) & 0x3f ] ; dst [ di ++ ] = table [ n & 0x3f ] ; } if ( tail > 0 ) { int n = ( src [ si ] & 0xff ) << 10 ; if ( tail == 2 ) n |= ( src [ ++ si ] & 0xff ) << 2 ; dst [ di ++ ] = table [ ( n >>> 12 ) & 0x3f ] ; dst [ di ++ ] = table [ ( n >>> 6 ) & 0x3f ] ; if ( tail == 2 ) dst [ di ++ ] = table [ n & 0x3f ] ; if ( pad != 0 ) { if ( tail == 1 ) dst [ di ++ ] = pad ; dst [ di ] = pad ; } } return dst ; } | Encode bytes to base64 chars using the supplied encode table and with optional padding . |
36,534 | public boolean load ( String name , boolean verify ) { boolean loaded ; try { System . loadLibrary ( name ) ; loaded = true ; } catch ( Throwable e ) { loaded = false ; } return loaded ; } | Load a shared library . |
36,535 | public Object createContext ( ApplicationRequest request , ApplicationResponse response ) { return new CookieContext ( request , response , mDomain , mPath , mIsSecure ) ; } | Creates a context for the templates . |
36,536 | public File [ ] getFiles ( ) { String path = mRequest . getParameter ( "path" ) ; if ( path == null ) { path = mApp . getInitParameter ( "defaultPath" ) ; } if ( path == null ) { path = "/" ; } File activefile = new File ( path ) ; if ( activefile . isDirectory ( ) ) { return activefile . listFiles ( ) ; } else { return null ; } } | Gets an array of files in the directory specified by the path query parameter . |
36,537 | public void clear ( ) { mPutLock . lock ( ) ; mPollLock . lock ( ) ; try { mSize . set ( 0 ) ; mHead = new Node ( null ) ; mTail = new Node ( null ) ; mHead . mNext = mTail ; } finally { mPollLock . unlock ( ) ; mPutLock . unlock ( ) ; } } | Clears the contents of the queue . This is a blocking operation . |
36,538 | public boolean remove ( Node < E > e ) { mPutLock . lock ( ) ; mPollLock . lock ( ) ; try { if ( e == null ) return false ; if ( e . mRemoved ) return false ; if ( mSize . get ( ) == 0 ) return false ; if ( e == mTail ) { removeTail ( ) ; return true ; } if ( e == mHead . mNext ) { removeHead ( ) ; return true ; } if ( mSize . get ( ) < 3 ) return false ; if ( e . mPrev == null || e . mNext == null ) return false ; e . mPrev . mNext = e . mNext ; e . mNext . mPrev = e . mPrev ; e . mRemoved = true ; mSize . decrementAndGet ( ) ; mNodePool . returnNode ( e ) ; return true ; } finally { mPollLock . unlock ( ) ; mPutLock . unlock ( ) ; } } | Removes a given Node handle . This is a blocking operation that runs in constant time . |
36,539 | public Object getComponent ( String role , String roleHint ) throws ComponentLookupException { return container . lookup ( role , roleHint ) ; } | Gets the component . |
36,540 | public void setTcpNoDelay ( boolean on ) throws SocketException { if ( mSocket != null ) { mSocket . setTcpNoDelay ( on ) ; } else { setOption ( 0 , on ? Boolean . TRUE : Boolean . FALSE ) ; } } | Option 0 . |
36,541 | public void setSoLinger ( boolean on , int linger ) throws SocketException { if ( mSocket != null ) { mSocket . setSoLinger ( on , linger ) ; } else { Object value ; if ( on ) { value = new Integer ( linger ) ; } else { value = Boolean . FALSE ; } setOption ( 1 , value ) ; } } | Option 1 . |
36,542 | public void setSoTimeout ( int timeout ) throws SocketException { if ( mSocket != null ) { mSocket . setSoTimeout ( timeout ) ; } else { setOption ( 2 , new Integer ( timeout ) ) ; } } | Option 2 . |
36,543 | public void setSendBufferSize ( int size ) throws SocketException { if ( mSocket != null ) { mSocket . setSendBufferSize ( size ) ; } else { setOption ( 3 , new Integer ( size ) ) ; } } | Option 3 . |
36,544 | public void setReceiveBufferSize ( int size ) throws SocketException { if ( mSocket != null ) { mSocket . setReceiveBufferSize ( size ) ; } else { setOption ( 4 , new Integer ( size ) ) ; } } | Option 4 . |
36,545 | CheckedSocket recycle ( ) { CheckedSocket s ; if ( mClosed ) { s = null ; } else { s = mSocket ; mSocket = null ; mClosed = true ; } return s ; } | Returns the internal wrapped socket or null if not connected . After calling recycle this LazySocket instance is closed . |
36,546 | public AppAdminLinks getAdminLinks ( ) { AppAdminLinks links = new AppAdminLinks ( mConfig . getName ( ) ) ; links . addAdminLink ( "Templates" , "/system/teaservlet/AdminTemplates" ) ; links . addAdminLink ( "Functions" , "/system/teaservlet/AdminFunctions" ) ; links . addAdminLink ( "Applications" , "/system/teaservlet/AdminApplications" ) ; links . addAdminLink ( "Logs" , "/system/teaservlet/LogViewer" ) ; links . addAdminLink ( "Servlet Engine" , "/system/teaservlet/AdminServletEngine" ) ; return links ; } | This implementation uses hard coded link information but other applications can dynamically determine their admin links . |
36,547 | public void init ( ServletConfig config ) throws ServletException { super . init ( config ) ; mServletConfig = config ; config . getServletContext ( ) . log ( "Initializing TeaServlet..." ) ; String ver = System . getProperty ( "java.version" ) ; if ( ver . startsWith ( "0." ) || ver . startsWith ( "1.2" ) || ver . startsWith ( "1.3" ) ) { config . getServletContext ( ) . log ( "The TeaServlet requires Java 1.4 or higher to run properly" ) ; } mServletContext = setServletContext ( config ) ; mServletName = setServletName ( config ) ; mProperties = new PropertyMap ( ) ; mSubstitutions = SubstitutionFactory . getDefaults ( ) ; mResourceFactory = new TeaServletResourceFactory ( config . getServletContext ( ) , mSubstitutions ) ; Enumeration < ? > e = config . getInitParameterNames ( ) ; while ( e . hasMoreElements ( ) ) { String key = ( String ) e . nextElement ( ) ; String value = SubstitutionFactory . substitute ( config . getInitParameter ( key ) ) ; if ( key . equals ( "debug" ) ) { mDebugEnabled = Boolean . parseBoolean ( value ) ; continue ; } mProperties . put ( key , value ) ; } loadDefaults ( ) ; discoverProperties ( ) ; createListeners ( ) ; createLog ( mServletContext ) ; mLog . applyProperties ( mProperties . subMap ( "log" ) ) ; createMemoryLog ( mLog ) ; mInstrumentationEnabled = mProperties . getBoolean ( "instrumentation.enabled" , true ) ; Initializer initializer = new Initializer ( ) ; if ( mProperties . getBoolean ( "startup.background" , false ) ) { mInitializer = Executors . newSingleThreadExecutor ( ) . submit ( initializer ) ; } else { initializer . call ( ) ; } } | Initializes the TeaServlet . Creates the logger and loads the user s application . |
36,548 | protected void doGet ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { if ( processStatus ( request , response ) ) { return ; } if ( ! isRunning ( ) ) { int errorCode = mProperties . getInt ( "startup.codes.error" , 503 ) ; response . sendError ( errorCode ) ; return ; } if ( mUseSpiderableRequest ) { request = new SpiderableRequest ( request , mQuerySeparator , mParameterSeparator , mValueSeparator ) ; } TeaServletTransaction tsTrans = getEngine ( ) . createTransaction ( request , response , true ) ; ApplicationRequest appRequest = tsTrans . getRequest ( ) ; ApplicationResponse appResponse = tsTrans . getResponse ( ) ; processTemplate ( appRequest , appResponse ) ; appResponse . finish ( ) ; response . flushBuffer ( ) ; } | Process the user s http get request . Process the template that maps to the URI that was hit . |
36,549 | private boolean processResource ( ApplicationRequest appRequest , ApplicationResponse appResponse ) throws IOException { String requestURI = null ; if ( ( requestURI = appRequest . getPathInfo ( ) ) == null ) { String context = appRequest . getContextPath ( ) ; requestURI = appRequest . getRequestURI ( ) ; if ( requestURI . startsWith ( context ) ) { requestURI = requestURI . substring ( context . length ( ) ) ; } } Asset asset = getEngine ( ) . getAssetEngine ( ) . getAsset ( requestURI ) ; if ( asset == null ) { return false ; } appResponse . setContentType ( asset . getMimeType ( ) ) ; int read = - 1 ; byte [ ] contents = new byte [ 1024 ] ; InputStream input = asset . getInputStream ( ) ; ServletOutputStream output = appResponse . getOutputStream ( ) ; while ( ( read = input . read ( contents ) ) >= 0 ) { output . write ( contents , 0 , read ) ; } appResponse . finish ( ) ; return true ; } | Inserts a plugin to expose parts of the teaservlet via the EngineAccess interface . |
36,550 | protected Object convertParameter ( String value , Class < ? > toType ) { if ( toType == Boolean . class ) { return ! "" . equals ( value ) ? new Boolean ( "true" . equals ( value ) ) : null ; } if ( toType == Integer . class ) { try { return new Integer ( value ) ; } catch ( NumberFormatException e ) { return null ; } } else if ( toType == Long . class ) { try { return new Long ( value ) ; } catch ( NumberFormatException e ) { return null ; } } else if ( toType == Float . class ) { try { return new Float ( value ) ; } catch ( NumberFormatException e ) { return null ; } } else if ( toType == Double . class ) { try { return new Double ( value ) ; } catch ( NumberFormatException e ) { return null ; } } else if ( toType == Number . class || toType == Object . class ) { try { return new Integer ( value ) ; } catch ( NumberFormatException e ) { } try { return new Long ( value ) ; } catch ( NumberFormatException e ) { } try { return new Double ( value ) ; } catch ( NumberFormatException e ) { return ( toType == Object . class ) ? value : null ; } } else { return null ; } } | Converts the given HTTP parameter value to the requested type so that it can be passed directly as a template parameter . This method is called if the template that is directly requested accepts non - String parameters and the request provides non - null values for those parameters . The template may request an array of values for a parameter in which case this method is called not to create the array but rather to convert any elements put into the array . |
36,551 | public static String replace ( String source , String pattern , String replacement ) { return replace ( source , pattern , replacement , 0 ) ; } | Replaces all exact matches of the given pattern in the source string with the provided replacement . |
36,552 | public void print ( Object obj ) throws IOException { if ( mOut != null ) { mOut . write ( toString ( obj ) ) ; } } | The standard context method implemented to write to the file . |
36,553 | public void setType ( Type type ) { Type actual = Type . preserveType ( this . getType ( ) , type ) ; mConversions . clear ( ) ; mExceptionPossible = false ; if ( actual != null ) { mConversions . add ( new Conversion ( null , actual , true ) ) ; } } | Sets the type of this expression clearing the conversion chain . |
36,554 | public void setInitialType ( Type type ) { Type initial = getInitialType ( ) ; Type actual = Type . preserveType ( initial , type ) ; if ( actual != null && ! actual . equals ( initial ) ) { if ( initial == null ) { setType ( actual ) ; } else { Iterator < Conversion > it = mConversions . iterator ( ) ; mConversions = new LinkedList < Conversion > ( ) ; mConversions . add ( new Conversion ( null , actual , true ) ) ; while ( it . hasNext ( ) ) { Conversion conv = ( Conversion ) it . next ( ) ; convertTo ( conv . getToType ( ) , conv . isCastPreferred ( ) ) ; } } } } | Sets the intial type in the conversion chain but does not clear the conversions . |
36,555 | public synchronized Token peekToken ( ) throws IOException { if ( mLookahead . empty ( ) ) { return mLookahead . push ( scanToken ( ) ) ; } else { return mLookahead . peek ( ) ; } } | Returns EOF as the last token . |
36,556 | private Token scanText ( int c ) throws IOException { c = mSource . read ( ) ; int startLine = mSource . getLineNumber ( ) ; int startPos = mSource . getStartPosition ( ) ; int endPos = mSource . getEndPosition ( ) ; StringBuilder buf = new StringBuilder ( 256 ) ; while ( c != - 1 ) { if ( c == SourceReader . ENTER_CODE ) { if ( mEmitSpecial ) { mLookahead . push ( makeStringToken ( Token . ENTER_CODE , mSource . getBeginTag ( ) ) ) ; } break ; } else if ( c == SourceReader . ENTER_TEXT ) { buf . append ( mSource . getEndTag ( ) ) ; } else { buf . append ( ( char ) c ) ; } if ( mSource . peek ( ) < 0 ) { endPos = mSource . getEndPosition ( ) ; } c = mSource . read ( ) ; } if ( c == - 1 ) { int length = buf . length ( ) ; int i ; for ( i = length - 1 ; i >= 0 ; i -- ) { if ( buf . charAt ( i ) > ' ' ) { break ; } } buf . setLength ( i + 1 ) ; } String str = buf . toString ( ) ; return new StringToken ( startLine , startPos , endPos , Token . STRING , str ) ; } | The ENTER_TEXT code has already been scanned when this is called . |
36,557 | public static void main ( String [ ] args ) throws Exception { Map map = getAllProperties ( Class . forName ( args [ 0 ] ) ) ; Iterator keys = map . keySet ( ) . iterator ( ) ; while ( keys . hasNext ( ) ) { String key = ( String ) keys . next ( ) ; PropertyDescriptor desc = ( PropertyDescriptor ) map . get ( key ) ; System . out . println ( key + " = " + desc ) ; } } | Test program . |
36,558 | public static Map getAllProperties ( Class clazz ) throws IntrospectionException { synchronized ( cPropertiesCache ) { Map properties ; Reference ref = ( Reference ) cPropertiesCache . get ( clazz ) ; if ( ref != null ) { properties = ( Map ) ref . get ( ) ; if ( properties != null ) { return properties ; } else { cPropertiesCache . remove ( clazz ) ; } } properties = Collections . unmodifiableMap ( createProperties ( clazz ) ) ; cPropertiesCache . put ( clazz , new SoftReference ( properties ) ) ; return properties ; } } | A function that returns a Map of all the available properties on a given class including write - only properties . The properties returned is mostly a superset of those returned from the standard JavaBeans Introspector except more properties are made available to interfaces . |
36,559 | static ConstantLongInfo make ( ConstantPool cp , long value ) { ConstantInfo ci = new ConstantLongInfo ( value ) ; return ( ConstantLongInfo ) cp . addConstant ( ci ) ; } | Will return either a new ConstantLongInfo object or one already in the constant pool . If it is a new ConstantLongInfo it will be inserted into the pool . |
36,560 | public Template parse ( ) throws IOException { Template t = parseTemplate ( ) ; if ( t != null ) { return t ; } return new Template ( new SourceInfo ( 0 , 0 , 0 ) , null , null , false , null , null ) ; } | Returns a parse tree by its root node . The parse tree is generated from tokens read from the scanner . Any errors encountered while parsing are delivered by dispatching an event . Add a compile listener in order to capture parse errors . |
36,561 | private IfStatement parseIfStatement ( Token token ) throws IOException { SourceInfo info = token . getSourceInfo ( ) ; Expression condition = parseExpression ( ) ; if ( ! ( condition instanceof ParenExpression ) ) { error ( "if.condition" , condition . getSourceInfo ( ) ) ; } Block thenPart = parseBlock ( ) ; Block elsePart = null ; token = peek ( ) ; if ( token . getID ( ) != Token . ELSE ) { info = info . setEndPosition ( thenPart . getSourceInfo ( ) ) ; } else { read ( ) ; token = peek ( ) ; if ( token . getID ( ) == Token . IF ) { elsePart = new Block ( parseIfStatement ( read ( ) ) ) ; } else { elsePart = parseBlock ( ) ; } info = info . setEndPosition ( elsePart . getSourceInfo ( ) ) ; } return new IfStatement ( info , condition , thenPart , elsePart ) ; } | When this is called the keyword if has already been read . |
36,562 | private ForeachStatement parseForeachStatement ( Token token ) throws IOException { SourceInfo info = token . getSourceInfo ( ) ; token = peek ( ) ; if ( token . getID ( ) == Token . LPAREN ) { read ( ) ; } else { error ( "foreach.lparen.expected" , token ) ; } VariableRef loopVar = parseLValue ( ) ; boolean foundASToken = false ; Token asToken = peek ( ) ; if ( asToken . getID ( ) == Token . AS ) { foundASToken = true ; read ( ) ; TypeName typeName = parseTypeName ( ) ; SourceInfo info2 = peek ( ) . getSourceInfo ( ) ; loopVar . setVariable ( new Variable ( info2 , loopVar . getName ( ) , typeName , true ) ) ; } token = peek ( ) ; if ( token . getID ( ) == Token . IN ) { read ( ) ; } else { error ( "foreach.in.expected" , token ) ; } Expression range = parseExpression ( ) ; Expression endRange = null ; token = peek ( ) ; if ( token . getID ( ) == Token . DOTDOT ) { read ( ) ; endRange = parseExpression ( ) ; token = peek ( ) ; } if ( endRange != null && foundASToken ) error ( "foreach.as.not.allowed" , asToken ) ; boolean reverse = false ; if ( token . getID ( ) == Token . REVERSE ) { read ( ) ; reverse = true ; token = peek ( ) ; } if ( token . getID ( ) == Token . RPAREN ) { read ( ) ; } else { error ( "foreach.rparen.expected" , token ) ; } Block body = parseBlock ( ) ; info = info . setEndPosition ( body . getSourceInfo ( ) ) ; return new ForeachStatement ( info , loopVar , range , endRange , reverse , body ) ; } | When this is called the keyword foreach has already been read . |
36,563 | private AssignmentStatement parseAssignmentStatement ( Token token ) throws IOException { SourceInfo info = token . getSourceInfo ( ) ; VariableRef lvalue = parseLValue ( token ) ; if ( peek ( ) . getID ( ) == Token . ASSIGN ) { read ( ) ; } else { error ( "assignment.equals.expected" , peek ( ) ) ; } Expression rvalue = parseExpression ( ) ; info = info . setEndPosition ( rvalue . getSourceInfo ( ) ) ; if ( peek ( ) . getID ( ) == Token . AS ) { read ( ) ; TypeName typeName = parseTypeName ( ) ; SourceInfo info2 = peek ( ) . getSourceInfo ( ) ; lvalue . setVariable ( new Variable ( info2 , lvalue . getName ( ) , typeName , true ) ) ; } return new AssignmentStatement ( info , lvalue , rvalue ) ; } | When this is called the identifier token has already been read . |
36,564 | private FunctionCallExpression parseFunctionCallExpression ( Token token ) throws IOException { Token next = peek ( ) ; if ( next . getID ( ) != Token . LPAREN ) { return null ; } SourceInfo info = token . getSourceInfo ( ) ; Name target = new Name ( info , token . getStringValue ( ) ) ; return parseCallExpression ( FunctionCallExpression . class , null , target , info ) ; } | a FunctionCallExpression . Token passed in must be an identifier . |
36,565 | public ConstantInfo getConstant ( int index ) { if ( mIndexedConstants == null ) { throw new ArrayIndexOutOfBoundsException ( "Constant pool indexes have not been assigned" ) ; } return ( ConstantInfo ) mIndexedConstants . get ( index ) ; } | Returns a constant from the pool by index or throws an exception if not found . If this constant pool has not yet been written or was not created by the read method indexes are not assigned . |
36,566 | public ConstantMethodInfo addConstantConstructor ( String className , TypeDesc [ ] params ) { return addConstantMethod ( className , "<init>" , null , params ) ; } | Get or create a constant from the constant pool representing a constructor in any class . |
36,567 | public ConstantInfo addConstant ( ConstantInfo constant ) { ConstantInfo info = ( ConstantInfo ) mConstants . get ( constant ) ; if ( info != null ) { return info ; } int entryCount = constant . getEntryCount ( ) ; if ( mIndexedConstants != null && mPreserveOrder ) { int size = mIndexedConstants . size ( ) ; mIndexedConstants . setSize ( size + entryCount ) ; mIndexedConstants . set ( size , constant ) ; } mConstants . put ( constant , constant ) ; mEntries += entryCount ; return constant ; } | Will only insert into the pool if the constant is not already in the pool . |
36,568 | public String doGet ( String host , String path , int port , Map < String , String > headers , int timeout ) throws UnknownHostException , ConnectException , IOException { return doHttpCall ( host , path , null , port , headers , timeout , false ) ; } | Perform an HTTP GET at the given path returning the results of the response . |
36,569 | public String doSecureGet ( String host , String path , int port , Map < String , String > headers , int timeout ) throws UnknownHostException , ConnectException , IOException { return doHttpCall ( host , path , null , port , headers , timeout , true ) ; } | Perform a secure HTTPS GET at the given path returning the results of the response . |
36,570 | public String doPost ( String host , String path , String postData , int port , Map < String , String > headers , int timeout ) throws UnknownHostException , ConnectException , IOException { return doHttpCall ( host , path , postData , port , headers , timeout , false ) ; } | Perform an HTTP POST at the given path sending in the given post data returning the results of the response . |
36,571 | public String doSecurePost ( String host , String path , String postData , int port , Map < String , String > headers , int timeout ) throws UnknownHostException , ConnectException , IOException { return doHttpCall ( host , path , postData , port , headers , timeout , true ) ; } | Perform a secure HTTPS POST at the given path sending in the given post data returning the results of the response . |
36,572 | public TypeDescription getArrayType ( ) { Class < ? > c = getTeaToolsUtils ( ) . getArrayType ( mType ) ; if ( mType == c ) { return this ; } return getTeaToolsUtils ( ) . createTypeDescription ( c ) ; } | Returns the array type . Returns this if it is not an array type . |
36,573 | public BeanInfo getBeanInfo ( ) { if ( mBeanInfo == null ) { try { mBeanInfo = getTeaToolsUtils ( ) . getBeanInfo ( mType ) ; } catch ( Exception e ) { return null ; } } return mBeanInfo ; } | Introspects a Java bean to learn about all its properties exposed methods and events . Returns null if the BeanInfo could not be created . |
36,574 | public PropertyDescriptor [ ] getPropertyDescriptors ( ) { BeanInfo info = getBeanInfo ( ) ; if ( info == null ) { return null ; } PropertyDescriptor [ ] pds = info . getPropertyDescriptors ( ) ; getTeaToolsUtils ( ) . sortPropertyDescriptors ( pds ) ; return pds ; } | Returns the type s PropertyDescriptors . |
36,575 | public MethodDescriptor [ ] getMethodDescriptors ( ) { BeanInfo info = getBeanInfo ( ) ; if ( info == null ) { return null ; } MethodDescriptor [ ] mds = info . getMethodDescriptors ( ) ; getTeaToolsUtils ( ) . sortMethodDescriptors ( mds ) ; return mds ; } | Returns the type s MethodDescriptors . |
36,576 | public final static byte reverseIfOpcode ( byte opcode ) { switch ( opcode ) { case IF_ACMPEQ : return IF_ACMPNE ; case IF_ACMPNE : return IF_ACMPEQ ; case IF_ICMPEQ : return IF_ICMPNE ; case IF_ICMPNE : return IF_ICMPEQ ; case IF_ICMPLT : return IF_ICMPGE ; case IF_ICMPGE : return IF_ICMPLT ; case IF_ICMPGT : return IF_ICMPLE ; case IF_ICMPLE : return IF_ICMPGT ; case IFEQ : return IFNE ; case IFNE : return IFEQ ; case IFLT : return IFGE ; case IFGE : return IFLT ; case IFGT : return IFLE ; case IFLE : return IFGT ; case IFNONNULL : return IFNULL ; case IFNULL : return IFNONNULL ; default : throw new IllegalArgumentException ( "Opcode not an if instruction: " + getMnemonic ( opcode ) ) ; } } | Reverses the condition for an if opcode . i . e . IFEQ is changed to IFNE . |
36,577 | public FunctionInfo [ ] getFunctions ( ) { ApplicationInfo [ ] AppInf = getApplications ( ) ; FunctionInfo [ ] funcArray = null ; try { MethodDescriptor [ ] methods = Introspector . getBeanInfo ( HttpContext . class ) . getMethodDescriptors ( ) ; List < FunctionInfo > funcList = new Vector < FunctionInfo > ( 50 ) ; for ( int i = 0 ; i < methods . length ; i ++ ) { MethodDescriptor m = methods [ i ] ; if ( m . getMethod ( ) . getDeclaringClass ( ) != Object . class && ! m . getMethod ( ) . getName ( ) . equals ( "print" ) && ! m . getMethod ( ) . getName ( ) . equals ( "toString" ) ) { funcList . add ( new FunctionInfo ( m , null ) ) ; } } for ( int i = 0 ; i < AppInf . length ; i ++ ) { FunctionInfo [ ] ctxFunctions = AppInf [ i ] . getContextFunctions ( ) ; for ( int j = 0 ; j < ctxFunctions . length ; j ++ ) { funcList . add ( ctxFunctions [ j ] ) ; } } funcArray = funcList . toArray ( new FunctionInfo [ funcList . size ( ) ] ) ; Arrays . sort ( funcArray ) ; } catch ( Exception ie ) { ie . printStackTrace ( ) ; } return funcArray ; } | Returns information about all functions available to the templates . |
36,578 | @ SuppressWarnings ( "unchecked" ) public TemplateWrapper [ ] getKnownTemplates ( ) { if ( mTemplateOrdering == null ) { setTemplateOrdering ( "name" ) ; } Comparator < TemplateWrapper > comparator = BeanComparator . forClass ( TemplateWrapper . class ) . orderBy ( "name" ) ; Set < TemplateWrapper > known = new TreeSet < TemplateWrapper > ( comparator ) ; TemplateLoader . Template [ ] loaded = mTeaServletEngine . getTemplateSource ( ) . getLoadedTemplates ( ) ; if ( loaded != null ) { for ( int j = 0 ; j < loaded . length ; j ++ ) { TeaServletAdmin . TemplateWrapper wrapper = new TemplateWrapper ( loaded [ j ] , TeaServletInvocationStats . getInstance ( ) . getStatistics ( loaded [ j ] . getName ( ) , null ) , TeaServletInvocationStats . getInstance ( ) . getStatistics ( loaded [ j ] . getName ( ) , "__substitution" ) , TeaServletRequestStats . getInstance ( ) . getStats ( loaded [ j ] . getName ( ) ) ) ; try { known . add ( wrapper ) ; } catch ( ClassCastException cce ) { mTeaServletEngine . getLog ( ) . warn ( cce ) ; } } } String [ ] allNames = mTeaServletEngine . getTemplateSource ( ) . getKnownTemplateNames ( ) ; if ( allNames != null ) { for ( int j = 0 ; j < allNames . length ; j ++ ) { TeaServletAdmin . TemplateWrapper wrapper = new TemplateWrapper ( allNames [ j ] , TeaServletInvocationStats . getInstance ( ) . getStatistics ( allNames [ j ] , null ) , TeaServletInvocationStats . getInstance ( ) . getStatistics ( allNames [ j ] , "__substitution" ) , TeaServletRequestStats . getInstance ( ) . getStats ( allNames [ j ] ) ) ; try { known . add ( wrapper ) ; } catch ( ClassCastException cce ) { mTeaServletEngine . getLog ( ) . warn ( cce ) ; } } } List < TemplateWrapper > v = new ArrayList < TemplateWrapper > ( known ) ; Collections . sort ( v , mTemplateOrdering ) ; return v . toArray ( new TemplateWrapper [ v . size ( ) ] ) ; } | Provides an ordered array of available templates using a handy wrapper class . |
36,579 | private HttpClient getTemplateServerClient ( String remoteSource ) throws IOException { int port = 80 ; String host = remoteSource . substring ( RemoteCompilationProvider . TEMPLATE_LOAD_PROTOCOL . length ( ) ) ; int portIndex = host . indexOf ( "/" ) ; if ( portIndex >= 0 ) { host = host . substring ( 0 , portIndex ) ; } portIndex = host . indexOf ( ":" ) ; if ( portIndex >= 0 ) { try { port = Integer . parseInt ( host . substring ( portIndex + 1 ) ) ; } catch ( NumberFormatException nfe ) { System . out . println ( "Invalid port number specified" ) ; } host = host . substring ( 0 , portIndex ) ; } SocketFactory factory = new PooledSocketFactory ( new PlainSocketFactory ( InetAddress . getByName ( host ) , port , 15000 ) ) ; return new HttpClient ( factory ) ; } | returns a socket connected to a host running the TemplateServerServlet |
36,580 | private static InetAddress [ ] getAllLocalInetAddresses ( final Log log ) throws SocketException { final List addresses = new ArrayList ( ) ; final Enumeration netInterfaces = NetworkInterface . getNetworkInterfaces ( ) ; while ( netInterfaces . hasMoreElements ( ) ) { final NetworkInterface ni = ( NetworkInterface ) netInterfaces . nextElement ( ) ; if ( log != null ) { log . debug ( "Found interface: " + ni . getName ( ) ) ; } final Enumeration ips = ni . getInetAddresses ( ) ; while ( ips . hasMoreElements ( ) ) { final InetAddress ip = ( InetAddress ) ips . nextElement ( ) ; if ( log != null ) { log . debug ( "Found ip: " + ip . getHostName ( ) + "/" + ip . getHostAddress ( ) + " on interface: " + ni . getName ( ) ) ; } if ( ! ip . isLoopbackAddress ( ) ) { if ( log != null ) { log . debug ( "Let's add this IP: " + ip . getCanonicalHostName ( ) ) ; } addresses . add ( ip ) ; } } } return ( InetAddress [ ] ) addresses . toArray ( new InetAddress [ addresses . size ( ) ] ) ; } | calling getHostName returns the IP . how do we get the host? |
36,581 | public LogEvent [ ] getLogEvents ( ) { if ( mLogEvents == null ) { return new LogEvent [ 0 ] ; } else { LogEvent [ ] events = new LogEvent [ mLogEvents . size ( ) ] ; return ( LogEvent [ ] ) mLogEvents . toArray ( events ) ; } } | Returns the lines that have been written to the log file . This is used by the admin functions . |
36,582 | public Template findTemplate ( String uri , HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { return findTemplate ( uri , request , response , getTemplateSource ( ) ) ; } | Finds a template based on the given URI . If path ends in a slash revert to loading default template . If default not found or not specified return null . |
36,583 | public HttpContext createHttpContext ( ApplicationRequest req , ApplicationResponse resp ) throws Exception { Template template = ( Template ) req . getTemplate ( ) ; return createHttpContext ( req , resp , template . getTemplateSource ( ) . getContextSource ( ) ) ; } | Lets external classes use the HttpContext for their own possibly malicious purposes . |
36,584 | private TeaServletTemplateSource createTemplateSource ( ContextSource contextSource ) { return TeaServletTemplateSource . createTemplateSource ( getServletContext ( ) , ( TeaServletContextSource ) contextSource , getProperties ( ) . subMap ( "template" ) , getLog ( ) ) ; } | Create a template source using the composite context passed to the method . |
36,585 | public synchronized Object put ( Object obj ) { if ( obj == null ) { return null ; } Entry tab [ ] = mTable ; int hash = hashCode ( obj ) ; int index = ( hash & 0x7FFFFFFF ) % tab . length ; for ( Entry e = tab [ index ] , prev = null ; e != null ; e = e . mNext ) { Object iobj = e . get ( ) ; if ( iobj == null ) { if ( prev != null ) { prev . mNext = e . mNext ; } else { tab [ index ] = e . mNext ; } mCount -- ; } else if ( e . mHash == hash && obj . getClass ( ) == iobj . getClass ( ) && equals ( obj , iobj ) ) { return iobj ; } else { prev = e ; } } if ( mCount >= mThreshold ) { cleanup ( ) ; } if ( mCount >= mThreshold ) { rehash ( ) ; tab = mTable ; index = ( hash & 0x7FFFFFFF ) % tab . length ; } tab [ index ] = new Entry ( obj , hash , tab [ index ] ) ; mCount ++ ; return obj ; } | Pass in a candidate flyweight object and get a unique instance from this set . The returned object will always be of the same type as that passed in . If the object passed in does not equal any object currently in the set it will be added to the set becoming a flyweight . |
36,586 | private String printTeaStackTraceLines ( TeaStackTraceLine [ ] lines ) { String result = "" ; for ( int line = 0 ; line < lines . length ; line ++ ) { if ( line > 0 ) { result += '\n' ; } result += lines [ line ] . toString ( ) ; } return result ; } | Prints the stack trace lines to a String . |
36,587 | private TeaStackTraceLine [ ] getTeaStackTraceLines ( Throwable t ) { StringWriter stackTraceGrabber = new StringWriter ( ) ; t . printStackTrace ( new PrintWriter ( stackTraceGrabber ) ) ; String stackTrace = stackTraceGrabber . toString ( ) ; int extensionIndex = stackTrace . lastIndexOf ( TEA_EXCEPTION ) ; boolean isTeaException = extensionIndex != - 1 ; if ( isTeaException ) { int endIndex = stackTrace . indexOf ( '\n' , extensionIndex ) ; int endRIndex = stackTrace . indexOf ( '\r' , extensionIndex ) ; if ( endRIndex > - 1 && endRIndex < endIndex ) endIndex = endRIndex ; if ( endIndex <= 0 ) { endIndex = stackTrace . length ( ) ; } stackTrace = stackTrace . substring ( 0 , endIndex ) ; List < TeaStackTraceLine > teaStackTraceLines = new ArrayList < TeaStackTraceLine > ( ) ; StringTokenizer tokenizer = new StringTokenizer ( stackTrace , "\n" ) ; while ( tokenizer . hasMoreElements ( ) ) { String line = ( String ) tokenizer . nextElement ( ) ; if ( line . indexOf ( TEA_EXCEPTION ) != - 1 ) { String tempLine = line ; int bracket = tempLine . indexOf ( '(' ) ; tempLine = tempLine . substring ( bracket + 1 ) ; bracket = tempLine . indexOf ( ')' ) ; tempLine = tempLine . substring ( 0 , bracket ) ; int colonIndex = tempLine . indexOf ( ':' ) ; String templateName = null ; Integer lineNumber = null ; if ( colonIndex >= 0 ) { templateName = tempLine . substring ( 0 , colonIndex ) ; try { lineNumber = new Integer ( tempLine . substring ( colonIndex + 1 ) ) ; } catch ( NumberFormatException nfe ) { lineNumber = null ; } } else { templateName = tempLine ; lineNumber = null ; } teaStackTraceLines . add ( new TeaStackTraceLine ( templateName , lineNumber , line ) ) ; } else { teaStackTraceLines . add ( new TeaStackTraceLine ( null , null , line ) ) ; } } return ( TeaStackTraceLine [ ] ) teaStackTraceLines . toArray ( new TeaStackTraceLine [ teaStackTraceLines . size ( ) ] ) ; } else { return null ; } } | Splits the stack trace into separate lines and extracts the template name and line number . |
36,588 | public String getName ( ) { String name = super . getName ( ) ; if ( name != null ) { if ( name . equals ( getParameterDescriptor ( ) . getDisplayName ( ) ) || name . length ( ) == 0 ) { name = null ; } } return name ; } | Returns the formal param name or null if the formal name is not available . |
36,589 | static ConstantNameAndTypeInfo make ( ConstantPool cp , String name , Descriptor type ) { ConstantInfo ci = new ConstantNameAndTypeInfo ( cp , name , type ) ; return ( ConstantNameAndTypeInfo ) cp . addConstant ( ci ) ; } | Will return either a new ConstantNameAndTypeInfo object or one already in the constant pool . If it is a new ConstantNameAndTypeInfo it will be inserted into the pool . |
36,590 | public TypeDescription getReturnType ( ) { if ( mReturnType == null ) { mReturnType = getTeaToolsUtils ( ) . createTypeDescription ( getMethod ( ) . getReturnType ( ) ) ; } return mReturnType ; } | Returns the method s return type |
36,591 | public < T > void add ( List < T > list , int index , T value ) { list . add ( index , value ) ; } | Insert the given value to the given list at the given index . This will insert the value at the index shifting the elements accordingly . |
36,592 | public < T > boolean addAll ( List < T > listToAddTo , Collection < ? extends T > collectionToAdd ) { return listToAddTo . addAll ( collectionToAdd ) ; } | Add all items of the given collection to the given list . |
36,593 | public < T > T set ( List < T > list , int index , T obj ) { return list . set ( index , obj ) ; } | Set the value at the given index in the given list . If the value is properly set the previous value will be returned . |
36,594 | public < T > List < T > subList ( List < T > list , int fromIndex , int toIndex ) { return list . subList ( fromIndex , toIndex ) ; } | Get a portion of the given list as a new list . |
36,595 | public Object [ ] toArray ( List < ? > list , Class < ? > arrayType ) { int [ ] dims = findArrayDimensions ( list , arrayType ) ; Object [ ] typedArray = ( Object [ ] ) Array . newInstance ( arrayType , dims ) ; return list . toArray ( typedArray ) ; } | Convert the given list to an array of the given array type . |
36,596 | public void addPlugin ( Plugin plugin ) { if ( ! mPluginMap . containsKey ( plugin . getName ( ) ) ) { mPluginMap . put ( plugin . getName ( ) , plugin ) ; PluginEvent event = new PluginEvent ( this , plugin ) ; firePluginAddedEvent ( event ) ; } } | Adds a Plugin to the PluginContext . Plugins that want to make themselves available to other Plugins should add themselves to the PluginContext through this method . All PluginListeners will be notified of the new addition . |
36,597 | public static int findReservedWordID ( StringBuilder word ) { char c = word . charAt ( 0 ) ; switch ( c ) { case 'a' : if ( matches ( word , "and" ) ) return AND ; if ( matches ( word , "as" ) ) return AS ; break ; case 'b' : if ( matches ( word , "break" ) ) return BREAK ; break ; case 'c' : if ( matches ( word , "call" ) ) return CALL ; if ( matches ( word , "class " ) ) return CLASS ; if ( matches ( word , "continue" ) ) return CONTINUE ; break ; case 'd' : if ( matches ( word , "define" ) ) return DEFINE ; break ; case 'e' : if ( matches ( word , "else" ) ) return ELSE ; break ; case 'f' : if ( matches ( word , "foreach" ) ) return FOREACH ; if ( matches ( word , "false" ) ) return FALSE ; break ; case 'i' : if ( matches ( word , "if" ) ) return IF ; if ( matches ( word , "import" ) ) return IMPORT ; if ( matches ( word , "in" ) ) return IN ; if ( matches ( word , "isa" ) ) return ISA ; break ; case 'n' : if ( matches ( word , "null" ) ) return NULL ; if ( matches ( word , "not" ) ) return NOT ; break ; case 'o' : if ( matches ( word , "or" ) ) return OR ; break ; case 'r' : if ( matches ( word , "reverse" ) ) return REVERSE ; break ; case 't' : if ( matches ( word , "true" ) ) return TRUE ; if ( matches ( word , "template" ) ) return TEMPLATE ; break ; } return UNKNOWN ; } | If the given StringBuilder starts with a valid token type its ID is returned . Otherwise the token ID UNKNOWN is returned . |
36,598 | private static boolean matches ( StringBuilder word , String val ) { int len = word . length ( ) ; if ( len != val . length ( ) ) return false ; for ( int index = 1 ; index < len ; index ++ ) { char cw = word . charAt ( index ) ; char cv = val . charAt ( index ) ; if ( cw != cv ) { return false ; } } return true ; } | Case sensitive match test . |
36,599 | public final void dump ( PrintStream out ) { out . println ( "Token [Code: " + getCode ( ) + "] [Image: " + getImage ( ) + "] [Value: " + getStringValue ( ) + "] [Id: " + getID ( ) + "] [start: " + mInfo . getStartPosition ( ) + "] [end " + mInfo . getEndPosition ( ) + "]" ) ; } | Dumps the contents of this Token . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.