idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
29,700 | public boolean execUpdateByRawSQL ( String updateRawSQL ) { boolean retVal = false ; log ( "#execUpdateByRawSQL updateRawSQL=" + updateRawSQL ) ; final Connection conn = createConnection ( ) ; try { Statement stmt = null ; conn . setAutoCommit ( false ) ; stmt = conn . createStatement ( ) ; stmt . executeUpdate ( updateRawSQL ) ; conn . commit ( ) ; retVal = true ; } catch ( SQLException e ) { loge ( "#execUpdateByRawSQL" , e ) ; retVal = false ; } finally { try { conn . close ( ) ; } catch ( SQLException e ) { retVal = false ; loge ( "#execUpdateByRawSQL" , e ) ; } } return retVal ; } | Execute raw SQL for update |
29,701 | public boolean execInsertIgnoreDuplicate ( D6Model [ ] modelObjects ) { final D6Inex includeExcludeColumnNames = null ; return execInsert ( modelObjects , includeExcludeColumnNames , true ) ; } | Insert the specified model object into the DB ignoring duplicated entry |
29,702 | public < T extends D6Model > T [ ] execSelectTable ( Class < T > modelClazz ) { final DBTable dbTable = modelClazz . getAnnotation ( DBTable . class ) ; final String dbTableName = dbTable . tableName ( ) ; return ( T [ ] ) execSelectTable ( "SELECT * FROM " + dbTableName , modelClazz ) ; } | Execute select statement and returns the all lines of rows corresponding to the specified model class as array of Objects |
29,703 | public < T extends D6Model > T [ ] execSelectTable ( String preparedSql , Class < T > modelClazz ) { return execSelectTable ( preparedSql , null , modelClazz ) ; } | Execute select statement for the single table . |
29,704 | private void setObject ( int parameterIndex , PreparedStatement preparedStmt , Object value ) throws SQLException { preparedStmt . setObject ( parameterIndex , value ) ; } | Set object to the preparedStatement |
29,705 | private < T extends D6Model > T [ ] toArray ( List < Object > objectList , Class < T > modelClazz ) { if ( objectList == null ) { return ( T [ ] ) Array . newInstance ( modelClazz , 0 ) ; } final T [ ] resultObjects = objectList . toArray ( ( T [ ] ) Array . newInstance ( modelClazz , 0 ) ) ; return resultObjects ; } | returns Object array from Object List |
29,706 | public Object [ ] getAsModel ( Map < Class < ? > , List < Object > > o , Class < ? extends D6Model > modelClazz ) { return toArray ( o . get ( modelClazz ) , modelClazz ) ; } | convert result into ModelObject from the result of execSelectWithJoin |
29,707 | private Connection createConnection ( ) { if ( mConnInfo != null ) { DBConnCreator dbConnCreator = new DBConnCreator ( mConnInfo ) ; Connection conn = dbConnCreator . createDBConnection ( ) ; return conn ; } else if ( mDbcpPropertyFile != null ) { Properties properties = new Properties ( ) ; InputStream is = Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( mDbcpPropertyFile ) ; try { properties . load ( is ) ; DataSource ds ; ds = BasicDataSourceFactory . createDataSource ( properties ) ; Connection conn = ds . getConnection ( ) ; return conn ; } catch ( IOException e ) { e . printStackTrace ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } return null ; } | Get the DB connection |
29,708 | public void start ( Xid xid , int flags ) throws XAException { try { if ( xid == null ) { throw new XAException ( XAException . XAER_INVAL ) ; } if ( flags == TMRESUME ) { this . xaConnection . resumeTransactionalBranch ( xid ) ; } else if ( flags == TMJOIN || flags == TMNOFLAGS ) { this . xaConnection . startTransactionalBranch ( xid ) ; } LOG . debug ( "PhynixxXAResource[" + this . getId ( ) + "]:start xid='" + xid + "' flags='" + ConstantsPrinter . getXAResourceMessage ( flags ) + "'" + " Connected to " + this . xaConnection ) ; this . setTimeOutActive ( true ) ; } catch ( XAException xaExc ) { LOG . error ( "PhynixxXAResource[" + this . getId ( ) + "]:start xid='" + xid + "' flags='" + ConstantsPrinter . getXAResourceMessage ( flags ) + "'" + " ERROR " + ConstantsPrinter . getXAErrorCode ( xaExc . errorCode ) ) ; throw xaExc ; } catch ( Exception ex ) { LOG . error ( "PhynixxXAResource.start(" + xid + "," + flags + ") on XAResourceProgressState " + this . xaId + " :: " + ex + "\n" + ExceptionUtils . getStackTrace ( ex ) ) ; throw new DelegatedRuntimeException ( "start(" + xid + "," + flags + ") on XAResourceProgressState " + this . xaId , ex ) ; } } | transaction branch is interchangeably with transaction context |
29,709 | public int prepare ( Xid xid ) throws XAException { try { LOG . debug ( "PhynixxXAResource[" + this . getId ( ) + "]:prepare prepare to perform a commit for XID=" + xid ) ; XATransactionalBranch < C > transactionalBranch = this . xaConnection . toGlobalTransactionBranch ( ) ; if ( xid == null ) { LOG . error ( "No XID" ) ; throw new XAException ( XAException . XAER_INVAL ) ; } if ( transactionalBranch == null ) { LOG . error ( "XAConnection is not associated to a global Transaction" ) ; throw new XAException ( XAException . XAER_PROTO ) ; } if ( ! transactionalBranch . getXid ( ) . equals ( xid ) ) { LOG . error ( "XAResource " + this + " isnt't active for XID=" + xid ) ; throw new XAException ( XAException . XAER_PROTO ) ; } int retVal = transactionalBranch . prepare ( ) ; if ( retVal == XAResource . XA_RDONLY ) { this . xaConnection . closeTransactionalBranch ( xid ) ; } return retVal ; } catch ( XAException xaExc ) { LOG . error ( "PhynixxXAResource[" + this . getId ( ) + "]:prepare xid='" + xid + " ERROR " + ConstantsPrinter . getXAErrorCode ( xaExc . errorCode ) ) ; throw xaExc ; } catch ( Exception ex ) { LOG . error ( "PhynixxXAResource.prepare(" + xid + ") on XAResourceProgressState " + this . xaId + " :: " + ex + "\n" + ExceptionUtils . getStackTrace ( ex ) ) ; throw new DelegatedRuntimeException ( "prepare(" + xid + ") on XAResourceProgressState " + this . xaId , ex ) ; } } | finds the transactional branch of the current XAResource associated with die XID |
29,710 | public void end ( Xid xid , int flags ) throws XAException { try { LOG . debug ( "PhynixxXAResource:end" ) ; LOG . debug ( "PhynixxXAResource[" + this . getId ( ) + "]:end xid='" + xid + "' flags='" + ConstantsPrinter . getXAResourceMessage ( flags ) + "'" ) ; if ( xid == null ) { LOG . error ( "No XID" ) ; throw new XAException ( XAException . XAER_INVAL ) ; } XATransactionalBranch < C > transactionalBranch = this . xaConnection . toGlobalTransactionBranch ( ) ; if ( transactionalBranch == null ) { LOG . error ( "XAConnection is not associated to a global Transaction" ) ; throw new XAException ( XAException . XAER_PROTO ) ; } if ( ! transactionalBranch . getXid ( ) . equals ( xid ) ) { LOG . error ( "XAResource " + this + " isnt't active for XID=" + xid ) ; throw new XAException ( XAException . XAER_PROTO ) ; } if ( flags == TMSUSPEND ) { this . xaConnection . suspendTransactionalBranch ( xid ) ; } else if ( flags == TMSUCCESS ) { if ( transactionalBranch . isXAProtocolFinished ( ) ) { transactionalBranch . close ( ) ; LOG . debug ( "XAResource " + this + " closed gracefully " ) ; } } else if ( flags == TMFAIL ) { transactionalBranch . setRollbackOnly ( true ) ; } } catch ( XAException xaExc ) { LOG . error ( "PhynixxXAResource[" + this . getId ( ) + "]:end xid='" + xid + "' flags='" + ConstantsPrinter . getXAResourceMessage ( flags ) + "'" + " ERROR " + ConstantsPrinter . getXAErrorCode ( xaExc . errorCode ) ) ; throw xaExc ; } catch ( Exception ex ) { LOG . error ( "PhynixxXAResource.end(" + xid + "," + flags + ") on XAResourceProgressState " + this . xaId + " :: " + ex + "\n" + ExceptionUtils . getStackTrace ( ex ) ) ; throw new DelegatedRuntimeException ( "end(" + xid + "," + flags + ") on XAResourceProgressState " + this . xaId , ex ) ; } } | This method ends the work performed on behalf of a transaction branch . |
29,711 | public void forget ( Xid xid ) throws XAException { try { LOG . debug ( "PhynixxXAResource[" + this . getId ( ) + "]:forget forget with Xid" ) ; if ( xid == null ) throw new XAException ( XAException . XAER_INVAL ) ; XATransactionalBranch < C > transactionalBranch = this . xaConnection . toGlobalTransactionBranch ( ) ; if ( transactionalBranch == null ) { return ; } this . xaConnection . closeTransactionalBranch ( xid ) ; this . xaConnection . close ( ) ; } finally { this . setTimeOutActive ( false ) ; } } | finds the transactional branch of the current XAResource associated with die XID and closes it without commit or explicit rollback |
29,712 | public boolean isSameRM ( XAResource xaResource ) throws XAException { if ( this . equals ( xaResource ) ) { LOG . debug ( "PhynixxXAResource[" + this . getId ( ) + "]:isSameRM isSameRM" ) ; return true ; } if ( ! ( xaResource instanceof PhynixxXAResource ) ) { LOG . debug ( "PhynixxXAResource[" + this . getId ( ) + "]:isSameRM not isSameRM" ) ; return false ; } @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) PhynixxXAResource < C > sampleXARes = ( PhynixxXAResource ) xaResource ; try { if ( xaResourceFactory . equals ( sampleXARes . xaResourceFactory ) ) { LOG . debug ( "PhynixxXAResource[" + this . getId ( ) + "]:isSameRM isSameRM (equal XAResourceFactory)" ) ; return true ; } else { LOG . debug ( "PhynixxXAResource[" + this . getId ( ) + "]:isSameRM not isSameRM (not equal XAResourceFactory)" ) ; return false ; } } catch ( Exception ex ) { LOG . error ( "PhynixxXAResource.isSameRM(" + sampleXARes . xaId + ") on XAResourceProgressState " + this . xaId + " :: " + ex + "\n" + ExceptionUtils . getStackTrace ( ex ) ) ; throw new DelegatedRuntimeException ( "isSameRM(" + sampleXARes . xaId + ") on XAResourceProgressState " + this . xaId , ex ) ; } } | This method is called to determine if the resource manager instance represented by the target object is the same as the resource manager instance represented by the parameter xares . |
29,713 | public void close ( ) { if ( this . xaConnection != null ) { this . xaConnection . doClose ( ) ; } this . closed = true ; this . notifyClosed ( ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "PhynixxXAResource[" + this . getId ( ) + "]:closed " ) ; } } | finds the transactional branch of the current XAResource associated with die XID Close this XA XAResourceProgressState . All depending Connection are closed |
29,714 | public Xid [ ] recover ( int flags ) throws XAException { LOG . info ( "PhynixxXAResource[" + this . getId ( ) + "]:recover recover flags=" + ConstantsPrinter . getXAResourceMessage ( flags ) ) ; if ( flags != TMSTARTRSCAN && flags != TMENDRSCAN && flags != TMNOFLAGS ) { throw new XAException ( XAException . XAER_INVAL ) ; } Xid [ ] retval = null ; retval = this . xaResourceFactory . recover ( ) ; return retval ; } | the system is recovered by the xaResourceFactory representing the persistence management system |
29,715 | private String [ ] getMembersValues ( Node attribute ) { List < String > actions = new ArrayList < String > ( ) ; NodeList actionNodes = attribute . getChildNodes ( ) ; for ( int j = 0 ; j < actionNodes . getLength ( ) ; j ++ ) { Node actionNode = actionNodes . item ( j ) ; if ( actionNode . getNodeName ( ) . equals ( "member" ) ) { actions . add ( provider . getTextValue ( actionNode ) ) ; } } if ( actions . size ( ) == 0 ) { return null ; } return actions . toArray ( new String [ actions . size ( ) ] ) ; } | Gets single text values from a member set . |
29,716 | private Metric toMetric ( Node node ) { if ( node == null ) { return null ; } Metric metric = new Metric ( ) ; NodeList attributes = node . getChildNodes ( ) ; for ( int i = 0 ; i < attributes . getLength ( ) ; i ++ ) { Node attribute = attributes . item ( i ) ; String name = attribute . getNodeName ( ) ; if ( name . equals ( "MetricName" ) ) { metric . setName ( provider . getTextValue ( attribute ) ) ; } else if ( name . equals ( "Namespace" ) ) { metric . setNamespace ( provider . getTextValue ( attribute ) ) ; } else if ( name . equals ( "Dimensions" ) ) { Map < String , String > dimensions = toMetadata ( attribute . getChildNodes ( ) ) ; if ( dimensions != null ) { metric . addMetadata ( dimensions ) ; } } } return metric ; } | Converts the given node to a Metric object . |
29,717 | private Map < String , String > toMetadata ( NodeList blocks ) { Map < String , String > dimensions = new HashMap < String , String > ( ) ; for ( int i = 0 ; i < blocks . getLength ( ) ; i ++ ) { Node dimensionNode = blocks . item ( i ) ; if ( dimensionNode . getNodeName ( ) . equals ( "member" ) ) { String dimensionName = null ; String dimensionValue = null ; NodeList dimensionAttributes = dimensionNode . getChildNodes ( ) ; for ( int j = 0 ; j < dimensionAttributes . getLength ( ) ; j ++ ) { Node attribute = dimensionAttributes . item ( j ) ; String name = attribute . getNodeName ( ) ; if ( name . equals ( "Name" ) ) { dimensionName = provider . getTextValue ( attribute ) ; } else if ( name . equals ( "Value" ) ) { dimensionValue = provider . getTextValue ( attribute ) ; } } if ( dimensionName != null ) { dimensions . put ( dimensionName , dimensionValue ) ; } } } if ( dimensions . size ( ) == 0 ) { return null ; } return dimensions ; } | Converts the given NodeList to a metadata map . |
29,718 | private Map < String , String > getMetricFilterParameters ( MetricFilterOptions options ) { if ( options == null ) { return null ; } Map < String , String > parameters = new HashMap < String , String > ( ) ; AWSCloud . addValueIfNotNull ( parameters , "MetricName" , options . getMetricName ( ) ) ; AWSCloud . addValueIfNotNull ( parameters , "Namespace" , options . getMetricNamespace ( ) ) ; AWSCloud . addIndexedParameters ( parameters , "Dimensions.member." , options . getMetricMetadata ( ) ) ; if ( parameters . size ( ) == 0 ) { return null ; } return parameters ; } | Creates map of parameters based on the MetricFilterOptions . |
29,719 | private Map < String , String > getAlarmFilterParameters ( AlarmFilterOptions options ) { if ( options == null ) { return null ; } Map < String , String > parameters = new HashMap < String , String > ( ) ; if ( options . getStateValue ( ) != null ) { AWSCloud . addValueIfNotNull ( parameters , "StateValue" , options . getStateValue ( ) . name ( ) ) ; } AWSCloud . addIndexedParameters ( parameters , "AlarmNames.member." , options . getAlarmNames ( ) ) ; if ( parameters . size ( ) == 0 ) { return null ; } return parameters ; } | Creates map of parameters based on the AlarmFilterOptions . |
29,720 | private String getCloudWatchUrl ( ) { return ( "https://monitoring." + provider . getContext ( ) . getRegionId ( ) + AWSCloud . getRegionSuffix ( provider . getContext ( ) . getRegionId ( ) ) ) ; } | Returns the cloudwatch endpoint url . |
29,721 | public static DropboxAuthentication build ( String appKey , String appSecret ) { DropboxClientBuilder builder = new DropboxClientBuilder ( appKey , appSecret ) ; builder . requestToken = builder . service . getRequestToken ( ) ; return builder ; } | Build authenticator to application with specified appKey and appSecret . |
29,722 | public MaybeNode get ( int index ) { if ( index == 0 ) { final OMElement first = element . getFirstElement ( ) ; return factory ( ) . newNode ( first , pathBuilder ( ) . withPart ( "any" ) . atIndex ( 0 ) ) ; } return NodeFactory . noneNode ( pathBuilder ( ) . atIndex ( index ) ) ; } | If index is 0 it will return the first child element else it returns the NONE_NODE . |
29,723 | public WriteRequest add ( Series series , DataPoint datapoint ) { WritableDataPoint mdp = new WritableDataPoint ( series , datapoint . getTimestamp ( ) , datapoint . getValue ( ) ) ; data . add ( mdp ) ; return this ; } | Adds a DataPoint to the request for a Series . |
29,724 | public static AnnotatorCache getInstance ( ) { if ( INSTANCE == null ) { synchronized ( AnnotatorCache . class ) { if ( INSTANCE == null ) { INSTANCE = new AnnotatorCache ( ) ; } } } return INSTANCE ; } | Gets the instance of the cache . |
29,725 | public void configure ( ) { LOGGER . info ( "configure()" ) ; calculators = new ArrayList < > ( ) ; if ( fieldExtractorEnabled ) { fieldExtractor = new FieldExtractor ( schema ) ; calculators . add ( fieldExtractor ) ; } if ( completenessMeasurementEnabled ) { completenessCalculator = new CompletenessCalculator ( schema ) ; completenessCalculator . collectFields ( completenessCollectFields ) ; completenessCalculator . setExistence ( fieldExistenceMeasurementEnabled ) ; completenessCalculator . setCardinality ( fieldCardinalityMeasurementEnabled ) ; calculators . add ( completenessCalculator ) ; } if ( tfIdfMeasurementEnabled ) { tfidfCalculator = new TfIdfCalculator ( schema ) ; if ( solrConfiguration != null ) { tfidfCalculator . setSolrConfiguration ( solrConfiguration ) ; } else { throw new IllegalArgumentException ( "If TF-IDF measurement is enabled, Solr configuration should not be null." ) ; } tfidfCalculator . enableTermCollection ( collectTfIdfTerms ) ; calculators . add ( tfidfCalculator ) ; } if ( problemCatalogMeasurementEnabled ) { if ( schema instanceof EdmSchema ) { ProblemCatalog problemCatalog = new ProblemCatalog ( ( EdmSchema ) schema ) ; new LongSubject ( problemCatalog ) ; new TitleAndDescriptionAreSame ( problemCatalog ) ; new EmptyStrings ( problemCatalog ) ; calculators . add ( problemCatalog ) ; } } if ( languageMeasurementEnabled ) { languageCalculator = new LanguageCalculator ( schema ) ; calculators . add ( languageCalculator ) ; } if ( multilingualSaturationMeasurementEnabled ) { multilingualSaturationCalculator = new MultilingualitySaturationCalculator ( schema ) ; if ( saturationExtendedResult ) { multilingualSaturationCalculator . setResultType ( MultilingualitySaturationCalculator . ResultTypes . EXTENDED ) ; } calculators . add ( multilingualSaturationCalculator ) ; } if ( uniquenessMeasurementEnabled ) { if ( solrClient == null && solrConfiguration == null ) { throw new IllegalArgumentException ( "If Uniqueness measurement is enabled, Solr configuration should not be null." ) ; } if ( solrClient == null ) { solrClient = new DefaultSolrClient ( solrConfiguration ) ; } calculators . add ( new UniquenessCalculator ( solrClient , schema ) ) ; } } | Run the configuration based on the previously set flags . |
29,726 | protected < T extends XmlFieldInstance > String measureWithGenerics ( String jsonRecord ) throws InvalidJsonException { changed ( ) ; cache = new JsonPathCache < > ( jsonRecord ) ; List < String > items = new ArrayList < > ( ) ; for ( Calculator calculator : getCalculators ( ) ) { calculator . measure ( cache ) ; items . add ( calculator . getCsv ( false , compressionLevel ) ) ; } return StringUtils . join ( items , "," ) ; } | The generic version of measure . |
29,727 | public void collectTfIdfTerms ( boolean collectTfIdfTerms ) { if ( this . collectTfIdfTerms != collectTfIdfTerms ) { this . collectTfIdfTerms = collectTfIdfTerms ; changed = true ; if ( tfidfCalculator != null ) { tfidfCalculator . enableTermCollection ( collectTfIdfTerms ) ; } } } | Sets the flag whether the measurement should collect each individual terms with their Term Ferquency and Invers Document Frequency scores . |
29,728 | public Map < String , Object > getResults ( ) { Map < String , Object > results = new LinkedHashMap < > ( ) ; for ( Calculator calculator : calculators ) { results . putAll ( calculator . getResultMap ( ) ) ; } return results ; } | Returns the result map . |
29,729 | public String parse ( String argument ) throws CommandLineException { File file = new File ( argument ) ; try { Assert . isTrue ( file . exists ( ) , "File '" + file + "' does not exist" ) ; Assert . isFalse ( file . isDirectory ( ) , "File '" + file + "' is a directory" ) ; Assert . isTrue ( file . canRead ( ) , "File '" + file + "' cannot be read" ) ; } catch ( IllegalArgumentException e ) { throw new CommandLineException ( e . getMessage ( ) ) ; } return file . getAbsolutePath ( ) ; } | Expects file that is available and readable |
29,730 | public < T > List < T > apply ( final List < T > objects ) { List < T > results = new ArrayList < T > ( ) ; if ( objects == null || objects . size ( ) == 0 ) { return results ; } int size = objects . size ( ) ; int fromIndex = getOffset ( ) ; int toIndex = fromIndex + getCount ( ) ; if ( size < toIndex ) { toIndex = size ; } if ( fromIndex >= size || toIndex == fromIndex ) { } else { results . addAll ( objects . subList ( fromIndex , toIndex ) ) ; } return results ; } | Extracts a range from the specified object list according to this LIMIT constraint . |
29,731 | public static ImmutableSet < File > findJarFiles ( ClassLoader first , ClassLoader ... rest ) throws IOException { Scanner scanner = new Scanner ( ) ; Map < URI , ClassLoader > map = Maps . newLinkedHashMap ( ) ; for ( ClassLoader classLoader : Lists . asList ( first , rest ) ) { map . putAll ( getClassPathEntries ( classLoader ) ) ; } for ( Map . Entry < URI , ClassLoader > entry : map . entrySet ( ) ) { scanner . scan ( entry . getKey ( ) , entry . getValue ( ) ) ; } return scanner . jarFiles ( ) ; } | Returns a list of jar files reachable from the given class loaders . |
29,732 | public static Map < String , Preset > autoConfigure ( ) throws MnoConfigurationException { String host = MnoPropertiesHelper . readEnvironment ( "MNO_DEVPL_HOST" , "https://developer.maestrano.com" ) ; String apiPath = MnoPropertiesHelper . readEnvironment ( "MNO_DEVPL_API_PATH" , "/api/config/v1" ) ; String apiKey = MnoPropertiesHelper . readEnvironment ( "MNO_DEVPL_ENV_KEY" ) ; String apiSecret = MnoPropertiesHelper . readEnvironment ( "MNO_DEVPL_ENV_SECRET" ) ; return autoConfigure ( host , apiPath , apiKey , apiSecret ) ; } | Method to fetch configuration from the dev - platform using environment variable . |
29,733 | public static Map < String , Preset > autoConfigure ( String devPlatformPropertiesFile ) throws MnoConfigurationException { Properties properties = loadProperties ( devPlatformPropertiesFile ) ; Properties trimProperties = MnoPropertiesHelper . trimProperties ( properties ) ; return autoConfigure ( trimProperties ) ; } | Method to fetch configuration from the dev - platform using a properties file . |
29,734 | public static Map < String , Preset > autoConfigure ( Properties properties ) throws MnoConfigurationException { DevPlatform devplatformConfiguration = new DevPlatform ( properties ) ; return autoconfigure ( devplatformConfiguration ) ; } | Method to fetch configuration from the dev - platform using a properties . |
29,735 | public static Preset reloadConfiguration ( String marketplace , Properties props ) throws MnoConfigurationException { Preset preset = new Preset ( marketplace , props ) ; configurations . put ( marketplace , preset ) ; return preset ; } | reload the configuration for the given preset and overload the existing one if any |
29,736 | public static Preset get ( String marketplace ) throws MnoConfigurationException { Preset maestrano = configurations . get ( marketplace ) ; if ( maestrano == null ) { throw new MnoConfigurationException ( "Maestrano was not configured for marketplace: " + marketplace + ". Maestrano.configure(" + marketplace + ") needs to have been called once." ) ; } return maestrano ; } | return the Maestrano Instance for the given preset |
29,737 | public static Properties loadProperties ( String filePath ) throws MnoConfigurationException { Properties properties = new Properties ( ) ; InputStream input = getInputStreamFromClassPathOrFile ( filePath ) ; try { properties . load ( input ) ; } catch ( IOException e ) { throw new MnoConfigurationException ( "Could not load properties file: " + filePath , e ) ; } finally { IOUtils . closeQuietly ( input ) ; } return properties ; } | load Properties from a filePath in the classPath or absolute |
29,738 | public void close ( ) throws IOException { final MapAppender appender = mapAppender ; if ( appender != null ) { appender . close ( ) ; } mapAppender = null ; recordCache = null ; } | Closes underlying output stream and writes nulls to all the internal fields . No metrics should be written from any other thread when this object is closed . |
29,739 | private String footprint ( Test test ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( test . getCategory ( ) ) . append ( test . getName ( ) ) . append ( test . getFlags ( ) ) ; for ( String tag : test . getTags ( ) ) { sb . append ( tag ) ; } for ( String ticket : test . getTickets ( ) ) { sb . append ( ticket ) ; } for ( Map . Entry < String , String > entry : test . getData ( ) . entrySet ( ) ) { sb . append ( entry . getKey ( ) ) . append ( entry . getValue ( ) ) ; } return FootprintGenerator . footprint ( sb . toString ( ) ) ; } | Compute the footprint for a test |
29,740 | public void close ( ) { proc . destroy ( ) ; try { inStream . close ( ) ; outStream . close ( ) ; errStream . close ( ) ; } catch ( IOException ignored ) { } inStream = null ; outStream = null ; errStream = null ; proc = null ; } | Cleanly kills the process . |
29,741 | public static String toFormattedString ( LongArrayND array , String format ) { if ( array == null ) { return "null" ; } StringBuilder sb = new StringBuilder ( ) ; Iterable < MutableIntTuple > iterable = IntTupleIterables . lexicographicalIterable ( array . getSize ( ) ) ; IntTuple previous = null ; for ( IntTuple coordinates : iterable ) { if ( previous != null ) { int c = Utils . countDifferences ( previous , coordinates ) ; for ( int i = 0 ; i < c - 1 ; i ++ ) { sb . append ( "\n" ) ; } } long value = array . get ( coordinates ) ; sb . append ( String . format ( format + ", " , value ) ) ; previous = coordinates ; } return sb . toString ( ) ; } | Creates a formatted representation of the given array . After each dimension a newline character will be inserted . |
29,742 | protected void logInParams ( I params ) { String s = "" ; if ( params != null ) { s = inToString ( params ) ; } if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "Request params: " + s ) ; } else if ( LOG . isDebugEnabled ( ) ) { if ( s . length ( ) > 4000 ) s = s . substring ( 0 , 4000 ) + "..." ; LOG . debug ( "Request params: " + s ) ; } } | Log input params |
29,743 | protected void logOut ( O out ) { String s = "" ; if ( out != null ) { s = outToString ( out ) ; } if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( "Process result: " + s ) ; } else if ( LOG . isDebugEnabled ( ) ) { if ( s . length ( ) > 4000 ) s = s . substring ( 0 , 4000 ) + "..." ; LOG . debug ( "Process result: " + s ) ; } } | Log output data |
29,744 | public void request ( final String method , final HttpServletRequest request , final HttpServletResponse response ) throws ServletException , IOException { String id = null ; try { requests . set ( request ) ; id = Session . start ( getSessionId ( request , response ) ) ; long t = System . currentTimeMillis ( ) ; try { String requestId = UUID . randomUUID ( ) . toString ( ) ; MDC . put ( "requestId" , requestId ) ; logRequest ( method , request ) ; I params = parseInput ( request ) ; logInParams ( params ) ; checkAccess ( method , params , request ) ; O out = process ( method , params , request , response ) ; if ( out != null ) { logOut ( out ) ; formatOutput ( out , false , request , response ) ; } } catch ( Throwable e ) { logError ( e ) ; try { O out = transformError ( e , request , response ) ; formatOutput ( out , true , request , response ) ; } catch ( Exception ex ) { LOG . error ( "Error preparing exception output" , ex ) ; } } logResult ( System . currentTimeMillis ( ) - t ) ; } finally { requests . remove ( ) ; Session . end ( id ) ; } } | Main method that makes request processing . Called from DispatcherServlet |
29,745 | private String createCSV ( ) { String csvData = null ; if ( isAggregate ( ) ) csvData = createAggregatedProjectCSV ( ) ; else csvData = createMultiProjectCSV ( ) ; return csvData ; } | Performs all the steps necessary for retrieving Sonar data and convert them into CSV . |
29,746 | private String createMultiProjectCSV ( ) { String csvData = null ; List < IProject > projects = null ; IProject project = null ; if ( isProjectKeyProvided ( ) ) { project = getExtractor ( ) . getProject ( getProjectKey ( ) ) ; projects = new ArrayList < IProject > ( ) ; projects . add ( project ) ; } else if ( isProjectKeyPatternProvided ( ) ) { projects = getExtractor ( ) . getProjects ( getProjectKeyPattern ( ) ) ; } else { projects = getExtractor ( ) . getAllProjects ( ) ; } csvData = getConverter ( ) . getCSVData ( projects , getMeasureObjects ( ) , isCleanValues ( ) , isSurroundFields ( ) ) ; LOG_INFO . info ( "Retrieved projects and generated CSV data." ) ; return csvData ; } | Create CSV by using all the projects provided . |
29,747 | void prepare ( ) { if ( getMeasures ( ) == null || getMeasures ( ) . isEmpty ( ) ) setMeasureObjects ( Arrays . asList ( HLAMeasure . values ( ) ) ) ; else setMeasureObjects ( HLAMeasure . convert ( getMeasures ( ) ) ) ; if ( getUserName ( ) != null && ! getUserName ( ) . isEmpty ( ) ) setExtractor ( SonarHLAFactory . getExtractor ( getHostUrl ( ) , getUserName ( ) , getPassword ( ) ) ) ; else setExtractor ( SonarHLAFactory . getExtractor ( getHostUrl ( ) ) ) ; setConverter ( SonarHLAFactory . getConverterInstance ( ) ) ; LOG . info ( "Initialized " + getMeasureObjects ( ) . size ( ) + " measures." ) ; } | Prepare and initialize necessary internal values before actually accessing Sonar - HLA . |
29,748 | public Episode getEpisodeInfo ( String showID , String seasonId , String episodeId ) throws TVRageException { if ( ! isValidString ( showID ) || ! isValidString ( seasonId ) || ! isValidString ( episodeId ) ) { return new Episode ( ) ; } StringBuilder tvrageURL = buildURL ( API_EPISODE_INFO , showID ) ; tvrageURL . append ( "&ep=" ) . append ( seasonId ) ; tvrageURL . append ( "x" ) . append ( episodeId ) ; return TVRageParser . getEpisodeInfo ( tvrageURL . toString ( ) ) ; } | Get the information for a specific episode |
29,749 | public EpisodeList getEpisodeList ( String showID ) throws TVRageException { if ( ! isValidString ( showID ) ) { return new EpisodeList ( ) ; } String tvrageURL = buildURL ( API_EPISODE_LIST , showID ) . toString ( ) ; return TVRageParser . getEpisodeList ( tvrageURL ) ; } | Get the episode information for all episodes for a show |
29,750 | public ShowInfo getShowInfo ( int showID ) throws TVRageException { if ( showID == 0 ) { return new ShowInfo ( ) ; } String tvrageURL = buildURL ( API_SHOWINFO , Integer . toString ( showID ) ) . toString ( ) ; List < ShowInfo > showList = TVRageParser . getShowInfo ( tvrageURL ) ; if ( showList . isEmpty ( ) ) { return new ShowInfo ( ) ; } else { return showList . get ( 0 ) ; } } | Search for the show using the show ID |
29,751 | public ShowInfo getShowInfo ( String showID ) throws TVRageException { int id = NumberUtils . toInt ( showID , 0 ) ; if ( id > 0 ) { return getShowInfo ( id ) ; } else { return new ShowInfo ( ) ; } } | Get the show information using the show ID |
29,752 | public List < ShowInfo > searchShow ( String showName ) throws TVRageException { if ( ! isValidString ( showName ) ) { return new ArrayList < > ( ) ; } String tvrageURL = buildURL ( API_SEARCH , showName ) . toString ( ) ; return TVRageParser . getSearchShow ( tvrageURL ) ; } | Search for the show using the show name |
29,753 | private StringBuilder buildURL ( String urlParameter , String urlData ) { StringBuilder tvrageURL = new StringBuilder ( ) ; tvrageURL . append ( API_SITE ) ; tvrageURL . append ( urlParameter ) ; tvrageURL . append ( "?key=" ) ; tvrageURL . append ( apiKey ) ; tvrageURL . append ( "&" ) ; if ( urlParameter . equalsIgnoreCase ( API_SEARCH ) ) { tvrageURL . append ( "show=" ) . append ( urlData ) ; } else if ( urlParameter . equalsIgnoreCase ( API_SHOWINFO ) ) { tvrageURL . append ( "sid=" ) . append ( urlData ) ; } else if ( urlParameter . equalsIgnoreCase ( API_EPISODE_LIST ) ) { tvrageURL . append ( "sid=" ) . append ( urlData ) ; } else if ( urlParameter . equalsIgnoreCase ( API_EPISODE_INFO ) ) { tvrageURL . append ( "sid=" ) . append ( urlData ) ; } else { return new StringBuilder ( UNKNOWN ) ; } LOG . trace ( "Search URL: {}" , tvrageURL ) ; return tvrageURL ; } | Build the API web URL for the process |
29,754 | public static boolean isValidString ( String testString ) { return StringUtils . isNotBlank ( testString ) && ( ! testString . equalsIgnoreCase ( TVRageApi . UNKNOWN ) ) ; } | Check the string passed to see if it contains a value . |
29,755 | private static void warn ( Object scope , String propertyPath ) { if ( scope == null ) { log . warn ( "Null object scope while searching for property |%s|." , propertyPath ) ; } else { log . warn ( "Null value for |%s#%s|." , scope . getClass ( ) , propertyPath ) ; } } | Record warning message to class logger . |
29,756 | public static < T > T getService ( String name , Class < T > clazz ) throws NamingException { Object object = SingletonHolder . locator . context . lookup ( name ) ; if ( object != null ) { return clazz . cast ( object ) ; } return null ; } | Locates a service given its JNDI name and automatically casts its reference to the appropriate class as specified by the caller . |
29,757 | public void stopForwardToServer ( final String ruleId , final String serverId ) throws InternalException , CloudException { if ( serverId == null ) throw new InternalException ( "Parameter serverId cannot be null" ) ; final AzureRuleIdParts azureRuleIdParts = AzureRuleIdParts . fromString ( ruleId ) ; PersistentVMRoleModel persistentVMRoleModel = getVMRole ( serverId ) ; if ( persistentVMRoleModel == null ) throw new InternalException ( "Cannot find Azure virtual machine with id: " + serverId ) ; CollectionUtils . filter ( persistentVMRoleModel . getConfigurationSets ( ) . get ( 0 ) . getInputEndpoints ( ) , new Predicate ( ) { public boolean evaluate ( Object object ) { PersistentVMRoleModel . InputEndpoint inputEndpoint = ( PersistentVMRoleModel . InputEndpoint ) object ; return ! azureRuleIdParts . equals ( new AzureRuleIdParts ( serverId , inputEndpoint . getProtocol ( ) , inputEndpoint . getLocalPort ( ) ) ) ; } } ) ; updateVMRole ( serverId , persistentVMRoleModel ) ; } | Removes the specified forwarding rule from the address with which it is associated . |
29,758 | public void endTiming ( ) { if ( _callback != null ) { float elapsed = System . currentTimeMillis ( ) - _start ; _callback . endTiming ( _counter , elapsed ) ; } } | Ends timing of an execution block calculates elapsed time and updates the associated counter . |
29,759 | public static File getDataDir ( ) { final File dir ; if ( SystemUtils . IS_OS_WINDOWS ) { dir = new File ( System . getenv ( "APPDATA" ) , "LittleShoot" ) ; } else if ( SystemUtils . IS_OS_MAC_OSX ) { dir = new File ( "/Library/Application\\ Support/LittleShoot" ) ; } else { dir = getLittleShootDir ( ) ; } if ( dir . isDirectory ( ) || dir . mkdirs ( ) ) return dir ; LOG . error ( "Not a directory: {}" , dir ) ; return new File ( SystemUtils . USER_HOME , ".littleshoot" ) ; } | Gets the directory to use for LittleShoot data . |
29,760 | public static String nativeCall ( final String ... commands ) { LOG . info ( "Running '{}'" , Arrays . asList ( commands ) ) ; final ProcessBuilder pb = new ProcessBuilder ( commands ) ; try { final Process process = pb . start ( ) ; final InputStream is = process . getInputStream ( ) ; final String data = IOUtils . toString ( is ) ; LOG . info ( "Completed native call: '{}'\nResponse: '" + data + "'" , Arrays . asList ( commands ) ) ; return data ; } catch ( final IOException e ) { LOG . error ( "Error running commands: " + Arrays . asList ( commands ) , e ) ; return "" ; } } | Makes a native call with the specified commands returning the result . |
29,761 | public static byte [ ] combine ( final Collection < byte [ ] > arrays ) { int length = 0 ; for ( final byte [ ] array : arrays ) { length += array . length ; } final byte [ ] joinedArray = new byte [ length ] ; int position = 0 ; for ( final byte [ ] array : arrays ) { System . arraycopy ( array , 0 , joinedArray , position , array . length ) ; position += array . length ; } return joinedArray ; } | Combines the specified arrays into a single array . |
29,762 | public InclusMultiPos < E , L , R > inclus ( Boolean left , Boolean right ) { this . inclusive [ 0 ] = checkNotNull ( left ) ; this . inclusive [ 1 ] = checkNotNull ( right ) ; return this ; } | Set whether the results contain the left and right borders Default are both exclusive . |
29,763 | public static Map < File , Exception > addFolderToClasspath ( File folder ) throws ReflectiveOperationException { return ReflectionUtil . addFolderToClasspath ( folder , jarAndZips ) ; } | Adds all jars and zips in the folder to the classpath |
29,764 | public static Map < File , Exception > addFolderToClasspath ( File folder , FileFilter fileFilter ) throws ReflectiveOperationException { Map < File , Exception > ret = Maps . newHashMap ( ) ; URLClassLoader sysURLClassLoader = ( URLClassLoader ) ClassLoader . getSystemClassLoader ( ) ; Class < ? extends URLClassLoader > classLoaderClass = URLClassLoader . class ; Method method = classLoaderClass . getDeclaredMethod ( "addURL" , URL . class ) ; method . setAccessible ( true ) ; for ( File f : folder . listFiles ( fileFilter ) ) { try { method . invoke ( sysURLClassLoader , f . toURI ( ) . toURL ( ) ) ; } catch ( ReflectiveOperationException | IOException e ) { ret . put ( f , e ) ; } } return ret ; } | Adds all files in the folder that the FileFilter accepts to the classpath |
29,765 | public static boolean classHasAnnotation ( Class clazz , Class < ? extends Annotation > annotation ) { try { Set < Class > hierarchy = ReflectionUtil . flattenHierarchy ( clazz ) ; for ( Class c : hierarchy ) { if ( c . isAnnotationPresent ( annotation ) ) return true ; } } catch ( Throwable t ) { t . printStackTrace ( ) ; } return false ; } | Returns true if that class or any of its supertypes has the annotation |
29,766 | private static Processor getProcessor ( Opcode opcode ) { switch ( opcode ) { case NOT_EMPTY : return NOT_EPMTY_PROCESSOR ; case EQUALS : if ( EQUALS_PROCESSOR == null ) { EQUALS_PROCESSOR = new EqualsProcessor ( ) ; } return EQUALS_PROCESSOR ; case LESS_THAN : if ( LESS_THAN_PROCESSOR == null ) { LESS_THAN_PROCESSOR = new LessThanProcessor ( ) ; } return LESS_THAN_PROCESSOR ; case GREATER_THAN : if ( GREATER_THAN_PROCESSOR == null ) { GREATER_THAN_PROCESSOR = new GreaterThanProcessor ( ) ; } return GREATER_THAN_PROCESSOR ; default : throw new BugError ( "Unsupported opcode |%s|." , opcode ) ; } } | Operator processor factory . Returned processor instance is a singleton that is reused on running virtual machine . |
29,767 | public static ClassLoader getDefaultClassLoader ( Class < ? > clazz ) { ClassLoader classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( classLoader == null ) { classLoader = clazz . getClassLoader ( ) ; } return classLoader ; } | Determines the default classloader . That is context class loader if defined or else classloader which loaded the given class . |
29,768 | public CommandOption < T > longCommand ( String longName ) { Assert . notNullOrEmptyTrimmed ( longName , "Missing long name!" ) ; longName = StringUtils . trim ( longName ) ; Assert . isTrue ( command . length ( ) <= longName . length ( ) , "Long name can't be shorter than command name!" ) ; String compare = StringUtils . sanitizeWhitespace ( longName ) ; Assert . isTrue ( longName . equals ( compare ) , "Option long name can not contain whitespace characters!" ) ; longCommand = longName ; return this ; } | Sets long command name |
29,769 | public CommandOption < T > setting ( String name ) { Assert . notNullOrEmptyTrimmed ( name , "Missing setting name" ) ; name = StringUtils . trim ( name ) ; String compare = StringUtils . sanitizeWhitespace ( name ) ; Assert . isTrue ( name . equals ( compare ) , "Setting name can not contain whitespace characters!" ) ; setting = name ; return this ; } | Sets command option setting key to be output when set if not set short command option name is used instead |
29,770 | public CommandOption < T > defaultsTo ( Object aDefault ) { if ( aDefault == null ) { defaultValue = null ; return this ; } boolean isCorrectType ; if ( type instanceof ParameterizedType ) { isCorrectType = ( ( Class ) ( ( ParameterizedType ) type ) . getRawType ( ) ) . isInstance ( aDefault ) ; } else { isCorrectType = ( ( Class ) type ) . isInstance ( aDefault ) ; } if ( ! isCorrectType ) { throw new IllegalArgumentException ( "Expected default setting of type: " + type . getTypeName ( ) + ", but was provided: " + aDefault . getClass ( ) . getName ( ) ) ; } defaultValue = ( T ) aDefault ; return this ; } | Sets command option default value |
29,771 | public boolean is ( CommandOption option ) { if ( option == null ) { return false ; } return StringUtils . equals ( getCommand ( ) , option . getCommand ( ) ) || StringUtils . equals ( getLongCommand ( ) , option . getLongCommand ( ) ) || StringUtils . equals ( getSetting ( ) , option . getSetting ( ) ) ; } | Compares against other option |
29,772 | public boolean containsLemma ( String lemma ) { return ! Strings . isNullOrEmpty ( lemma ) && db . containsLemma ( lemma . toLowerCase ( ) ) ; } | Contains lemma . |
29,773 | public double distance ( Synset synset1 , Synset synset2 ) { Preconditions . checkNotNull ( synset1 ) ; Preconditions . checkNotNull ( synset2 ) ; if ( synset1 . equals ( synset2 ) ) { return 0d ; } List < Synset > path = shortestPath ( synset1 , synset2 ) ; return path . isEmpty ( ) ? Double . POSITIVE_INFINITY : path . size ( ) - 1 ; } | Calculates the distance between synsets . |
29,774 | public WordNetRelation getRelation ( Sense from , Sense to ) { if ( from == null || to == null ) { return null ; } return db . getRelation ( from , to ) ; } | Gets relation . |
29,775 | public synchronized int read ( final byte buf [ ] , final int off , final int len ) throws IOException { while ( this . currentRecord . needsData ( ) ) { final byte [ ] data = new byte [ len ] ; final int read = this . inputStream . read ( data ) ; if ( read == - 1 ) { return read ; } lastBuffer = ByteBuffer . wrap ( data , 0 , read ) ; this . currentRecord . addData ( lastBuffer ) ; } final int bytesRead = this . currentRecord . drainData ( buf , off , len ) ; if ( ! this . currentRecord . hasMoreData ( ) ) { LOG . info ( "Resetting app record" ) ; this . currentRecord = new InputRecord ( readKey ) ; if ( lastBuffer != null ) { this . currentRecord . addData ( lastBuffer ) ; } else { LOG . warn ( "No existing buffer?" ) ; } } return bytesRead ; } | Read up to len bytes into this buffer starting at off . If the layer above needs more data it asks for more so we are responsible only for blocking to fill at most one buffer and returning - 1 on non - fault EOF status . |
29,776 | public CList parse ( UseExtension operationRegister , Properties properties , String infixExpression , Object ... values ) throws ParseException { pUsedExtensions = null ; this . usedExtensions = operationRegister ; this . properties = properties ; return parse ( infixExpression , values ) ; } | Parse infix string expression with additional properties |
29,777 | public CList parse ( String infixExpression , Object ... values ) throws ParseException { LinkedHashMap < String , Num > vNames = mapValues ( infixExpression , values ) ; return parse ( infixExpression , vNames ) ; } | Parse infix string expression |
29,778 | private LinkedHashMap < String , Num > mapValues ( String infix , Object ... values ) { LinkedHashMap < String , Num > vNames = null ; int remain = 0 ; Matcher mat = pVariableNames . matcher ( infix ) ; while ( mat . find ( ) ) { if ( vNames == null ) vNames = new LinkedHashMap < String , Num > ( ) ; String vName = mat . group ( ) ; if ( ! vNames . containsKey ( vName ) ) { remain ++ ; Num num = findValue ( vName , true , values ) ; vNames . put ( vName , num ) ; if ( num != null ) remain -- ; } } if ( vNames != null ) { int lastPos = 0 ; for ( Entry < String , Num > entry : vNames . entrySet ( ) ) { if ( entry . getValue ( ) == null ) { for ( int i = lastPos ; i < values . length ; i ++ ) { Object v = values [ i ] ; if ( v != null ) { if ( v instanceof Num ) { Num n = ( Num ) v ; if ( n . getName ( ) == null ) entry . setValue ( n ) ; else if ( n . getName ( ) . equals ( entry . getValue ( ) ) ) entry . setValue ( n ) ; } else entry . setValue ( Num . toNum ( v ) ) ; values [ i ] = null ; lastPos = i ; remain -- ; } } } } } if ( remain > 0 && vNames != null ) { StringBuilder sb = new StringBuilder ( ) ; int c = 0 ; for ( Entry < String , Num > entry : vNames . entrySet ( ) ) { if ( entry . getValue ( ) == null ) { if ( c ++ > 0 ) sb . append ( ", " ) ; sb . append ( entry . getKey ( ) ) ; } } throw new CalculatorException ( "Undefined values for expression (" + infix + ") variables: " + sb . toString ( ) ) ; } return vNames ; } | map variable names from expression with values |
29,779 | private int countOccurrences ( String haystack , char needle ) { int count = 0 ; for ( int i = 0 ; i < haystack . length ( ) ; i ++ ) { if ( haystack . charAt ( i ) == needle ) count ++ ; } return count ; } | Count how many time needle appears in haystack |
29,780 | public int search ( String text ) { int i = pattern . length ( ) - 1 ; int j = pattern . length ( ) - 1 ; while ( i < text . length ( ) ) { if ( pattern . charAt ( j ) == text . charAt ( i ) ) { if ( j == 0 ) { return i ; } j -- ; i -- ; } else { i += pattern . length ( ) - j - 1 + Math . max ( j - last [ text . charAt ( i ) ] , match [ j ] ) ; j = pattern . length ( ) - 1 ; } } return - 1 ; } | Searching the pattern in the text |
29,781 | @ SuppressWarnings ( "unchecked" ) public T addHeader ( final String name , final String value ) { List < String > values = new ArrayList < String > ( ) ; values . add ( value ) ; this . headers . put ( name , values ) ; return ( T ) this ; } | Adds a single header value to the Message . |
29,782 | @ SuppressWarnings ( "unchecked" ) public T setHeaders ( final Map < String , List < String > > headers ) { this . headers = headers ; return ( T ) this ; } | Sets all of the headers in one call . |
29,783 | public static final String encodeString ( String string , String encoding ) throws RuntimeException { return StringConverter . byteToHex ( digestString ( string , encoding ) ) ; } | Retrieves a hexidecimal character sequence representing the MD5 digest of the specified character sequence using the specified encoding to first convert the character sequence into a byte sequence . If the specified encoding is null then ISO - 8859 - 1 is assumed |
29,784 | public static byte [ ] digestString ( String string , String encoding ) throws RuntimeException { byte [ ] data ; if ( encoding == null ) { encoding = "ISO-8859-1" ; } try { data = string . getBytes ( encoding ) ; } catch ( UnsupportedEncodingException x ) { throw new RuntimeException ( x . toString ( ) ) ; } return digestBytes ( data ) ; } | Retrieves a byte sequence representing the MD5 digest of the specified character sequence using the specified encoding to first convert the character sequence into a byte sequence . If the specified encoding is null then ISO - 8859 - 1 is assumed . |
29,785 | public static final byte [ ] digestBytes ( byte [ ] data ) throws RuntimeException { synchronized ( MD5 . class ) { if ( md5 == null ) { try { md5 = MessageDigest . getInstance ( "MD5" ) ; } catch ( NoSuchAlgorithmException e ) { throw new RuntimeException ( e . toString ( ) ) ; } } return md5 . digest ( data ) ; } } | Retrieves a byte sequence representing the MD5 digest of the specified byte sequence . |
29,786 | public void tag ( Annotation sentence ) { SequenceInput < Annotation > sequenceInput = new SequenceInput < > ( sentence . tokens ( ) ) ; Labeling result = labeler . label ( featurizer . extractSequence ( sequenceInput . iterator ( ) ) ) ; for ( int i = 0 ; i < sentence . tokenLength ( ) ; ) { if ( result . getLabel ( i ) . equals ( "O" ) ) { i ++ ; } else { Annotation start = sentence . tokenAt ( i ) ; String type = result . getLabel ( i ) . substring ( 2 ) ; i ++ ; while ( i < sentence . tokenLength ( ) && result . getLabel ( i ) . startsWith ( "I-" ) ) { i ++ ; } Annotation end = sentence . tokenAt ( i - 1 ) ; HString span = start . union ( end ) ; Annotation entity = sentence . document ( ) . annotationBuilder ( ) . type ( annotationType ) . bounds ( span ) . createAttached ( ) ; entity . put ( annotationType . getTagAttribute ( ) , annotationType . getTagAttribute ( ) . getValueType ( ) . decode ( type ) ) ; } } } | Tag labeling result . |
29,787 | public String decrypt ( String cipherText ) throws MissingParameterException { if ( StringUtils . isBlank ( cipherText ) ) { throw new MissingParameterException ( "Missing parameter: cipherText" ) ; } return stringEncryptor . decrypt ( cipherText ) ; } | Method which will decrypt a string . |
29,788 | public String encrypt ( String clearText ) throws MissingParameterException { if ( StringUtils . isBlank ( clearText ) ) { throw new MissingParameterException ( "Missing parameter: clearText" ) ; } return stringEncryptor . encrypt ( clearText ) ; } | Method which will encrypt a string . |
29,789 | public byte [ ] decrypt ( byte [ ] cipherBytes ) throws MissingParameterException { if ( cipherBytes == null || cipherBytes . length == 0 ) { throw new MissingParameterException ( "Missing parameter: cipherBytes" ) ; } return byteEncryptor . decrypt ( cipherBytes ) ; } | Method which will decrypt an array of bytes . |
29,790 | public final void enableRenaming ( final String picturePath ) { HBox hb = new HBox ( ) ; ImageView iv = getIcon ( picturePath ) ; iv . setOnMouseClicked ( new EventHandler < Event > ( ) { public void handle ( Event mouseEvent ) { if ( ( ( MouseEvent ) mouseEvent ) . getButton ( ) . equals ( MouseButton . PRIMARY ) ) { if ( ( ( MouseEvent ) mouseEvent ) . getClickCount ( ) == 2 ) { TextInputDialog input = new TextInputDialog ( textProperty ( ) . get ( ) ) ; input . setTitle ( MessagesUtil . getString ( "dajlab.change_tab_title" ) ) ; input . setContentText ( null ) ; input . setHeaderText ( MessagesUtil . getString ( "dajlab.change_tab_text" ) ) ; input . setGraphic ( null ) ; Optional < String > ret = input . showAndWait ( ) ; if ( ret . isPresent ( ) && StringUtils . isNoneBlank ( ret . get ( ) ) ) { updateTitle ( ret . get ( ) ) ; } } } } } ) ; hb . getChildren ( ) . add ( iv ) ; setGraphic ( hb ) ; } | If used this method allows the renaming of a tab by the user with a double - click on the icon of the tab . It seems there is no mouse event on a Tab title that s why an icon should be used . |
29,791 | protected ImageView getIcon ( final String picturePath ) { ImageView iv = null ; if ( picturePath == null ) { iv = new ImageView ( new Image ( DEFAULT_ICON ) ) ; } else { iv = new ImageView ( new Image ( picturePath ) ) ; } iv . setPreserveRatio ( true ) ; iv . setFitHeight ( 20 ) ; return iv ; } | Return a picture node from the path . |
29,792 | @ SuppressWarnings ( "unused" ) final void startRecording ( ) { if ( firstTime ) { Object obj ; doStartRecording ( ) ; obj = new Object ( ) ; AllocationStats stats = stopRecording ( 1 ) ; if ( stats . getAllocationCount ( ) != 1 || stats . getAllocationSize ( ) < 1 ) { throw new IllegalStateException ( String . format ( "The allocation recording infrastructure appears to be broken. " + "Expected to find exactly one allocation of a java/lang/Object instead found %s" , stats ) ) ; } firstTime = false ; } doStartRecording ( ) ; } | Clears the prior state and starts a new recording . Supressing warnings on object created that is not used . |
29,793 | public static boolean hasDigit ( String str ) { final Pattern pattern = Pattern . compile ( "[0-9]" ) ; final Matcher matcher = pattern . matcher ( str ) ; while ( matcher . find ( ) ) { return true ; } return false ; } | Returns true if this string contains digits false otherwise . |
29,794 | public static String pad ( String rawString , int length , char padChar ) { String padded = rawString ; String padFiller = null ; if ( padded . length ( ) == length ) { return padded ; } if ( padded . length ( ) < length ) { StringBuffer buff = new StringBuffer ( length ) ; for ( int i = buff . length ( ) ; i < length ; i ++ ) { buff . append ( padChar ) ; } padFiller = buff . toString ( ) ; padded = rawString + padFiller ; return padded . substring ( 0 , length ) ; } else { return padded . substring ( 0 , length ) ; } } | Pad string with a character at end of text . |
29,795 | public static String upperCaseFirst ( String str ) { if ( str == null || str . equals ( EMPTY ) ) { return str ; } return Character . toUpperCase ( str . charAt ( 0 ) ) + str . substring ( 1 ) ; } | Upper case the first character of the supplied string . |
29,796 | public static String join ( Collection < ? > collection , String separator ) { return StringUtils . join ( collection , separator ) ; } | Join a collection or list of elements using the separator provided . For example this could be used to join a list of strings by a comma i . e . . |
29,797 | private void setProgressBarValue ( int value , int maximum ) { this . progressBar . setIndeterminate ( false ) ; if ( this . progressBar . getMaximum ( ) != maximum ) { this . progressBar . setMaximum ( maximum ) ; } this . progressBar . setValue ( value ) ; } | Updates the progress bar on this dialog . |
29,798 | private static void buildPath ( HashMap m , String p ) { boolean isEvent = false ; if ( p . contains ( "@" ) ) { String [ ] components = p . split ( "@" ) ; int cl = components . length ; buildNestedBuckets ( m , components [ 0 ] ) ; if ( cl == 2 ) { if ( p . contains ( "!" ) ) isEvent = true ; HashMap pointer = traverseToPoint ( m , components [ 0 ] ) ; String d ; if ( isEvent ) { String [ ] temp = components [ 1 ] . split ( "!" ) ; d = temp [ 0 ] ; } else { d = components [ 1 ] ; } if ( ! pointer . containsKey ( d ) ) pointer . put ( d , new ArrayList ( ) ) ; } } } | Creates a nested path if not already present in the map . This does not support multipath definitions . Please split prior to sending the path to this function . |
29,799 | private static void buildNestedBuckets ( HashMap m , String p ) { String [ ] components = p . split ( ":" ) ; int cl = components . length ; if ( cl == 1 ) { if ( ! m . containsKey ( components [ 0 ] ) ) m . put ( components [ 0 ] , new HashMap ( ) ) ; } else { HashMap temp = m ; for ( int i = 0 ; i < cl ; i ++ ) { if ( ! temp . containsKey ( components [ i ] ) ) temp . put ( components [ i ] , new HashMap ( ) ) ; temp = ( HashMap ) temp . get ( components [ i ] ) ; } } } | A helper method to created the nested bucket structure . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.