idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
18,700
@ Requires ( { "contextLocal >= 0" , "checkInvariantsLocal >= 0" } ) @ Ensures ( "result != null" ) protected Label enterBusySection ( ) { Label skip = new Label ( ) ; loadLocal ( contextLocal ) ; invokeVirtual ( CONTRACT_CONTEXT_TYPE , TRY_ENTER_CONTRACT_METHOD ) ; ifZCmp ( EQ , skip ) ; return skip ; }
Marks the beginning of a busy section . A busy section is skipped if the context is already busy .
18,701
@ Requires ( { "contextLocal >= 0" , "skip != null" } ) protected void leaveBusySection ( Label skip ) { loadLocal ( contextLocal ) ; invokeVirtual ( CONTRACT_CONTEXT_TYPE , LEAVE_CONTRACT_METHOD ) ; mark ( skip ) ; }
Marks the end of a busy section .
18,702
@ Ensures ( { "contextLocal >= 0" , "checkInvariantsLocal >= 0" } ) protected void enterContractedMethod ( ) { contextLocal = newLocal ( CONTRACT_CONTEXT_TYPE ) ; checkInvariantsLocal = newLocal ( Type . BOOLEAN_TYPE ) ; invokeStatic ( CONTRACT_RUNTIME_TYPE , GET_CONTEXT_METHOD ) ; dup ( ) ; storeLocal ( contextLocal ) ; if ( statik ) { loadThisClass ( ) ; } else { loadThis ( ) ; } invokeVirtual ( CONTRACT_CONTEXT_TYPE , TRY_ENTER_METHOD ) ; storeLocal ( checkInvariantsLocal ) ; }
Retrieves busy state of the current object .
18,703
@ Requires ( "contextLocal >= 0" ) protected void leaveContractedMethod ( ) { Label skip = new Label ( ) ; loadLocal ( checkInvariantsLocal ) ; ifZCmp ( EQ , skip ) ; loadLocal ( contextLocal ) ; if ( statik ) { loadThisClass ( ) ; } else { loadThis ( ) ; } invokeVirtual ( CONTRACT_CONTEXT_TYPE , LEAVE_METHOD ) ; mark ( skip ) ; }
Cancels busy state of the current object .
18,704
public void configure ( ConfigParams config ) throws ConfigException { ConfigParams dependencies = config . getSection ( "dependencies" ) ; for ( String name : dependencies . keySet ( ) ) { String locator = dependencies . get ( name ) ; if ( locator == null ) continue ; try { Descriptor descriptor = Descriptor . fromString ( locator ) ; if ( descriptor != null ) _dependencies . put ( name , descriptor ) ; else _dependencies . put ( name , locator ) ; } catch ( Exception ex ) { _dependencies . put ( name , locator ) ; } } }
Configures the component with specified parameters .
18,705
private Object find ( String name ) { if ( name == null ) throw new NullPointerException ( "Dependency name cannot be null" ) ; if ( _references == null ) throw new NullPointerException ( "References shall be set" ) ; return _dependencies . get ( name ) ; }
Gets a dependency locator by its name .
18,706
public Object getOneOptional ( String name ) { Object locator = find ( name ) ; return locator != null ? _references . getOneOptional ( locator ) : null ; }
Gets one optional dependency by its name .
18,707
public < T > T getOneOptional ( Class < T > type , String name ) { Object locator = find ( name ) ; return locator != null ? _references . getOneOptional ( type , locator ) : null ; }
Gets one optional dependency by its name and matching to the specified type .
18,708
public Object getOneRequired ( String name ) throws ReferenceException { Object locator = find ( name ) ; if ( locator == null ) throw new ReferenceException ( null , name ) ; return _references . getOneRequired ( locator ) ; }
Gets one required dependency by its name . At least one dependency must present . If the dependency was found it throws a ReferenceException
18,709
public < T > T getOneRequired ( Class < T > type , String name ) throws ReferenceException { Object locator = find ( name ) ; if ( locator == null ) throw new ReferenceException ( null , name ) ; return _references . getOneRequired ( type , locator ) ; }
Gets one required dependency by its name and matching to the specified type . At least one dependency must present . If the dependency was found it throws a ReferenceException
18,710
public List < Object > find ( String name , boolean required ) throws ReferenceException { if ( name == null || name . length ( ) == 0 ) { throw new NullPointerException ( name ) ; } Object locator = find ( name ) ; if ( locator == null ) { if ( required ) { throw new ReferenceException ( null , name ) ; } return null ; } return _references . find ( locator , required ) ; }
Finds all matching dependencies by their name .
18,711
@ SuppressWarnings ( "unchecked" ) public < T > List < T > find ( Class < T > type , String name , boolean required ) throws ReferenceException { if ( name == null || name . length ( ) == 0 ) { throw new NullPointerException ( name ) ; } Object locator = find ( name ) ; if ( locator == null ) { if ( required ) { throw new ReferenceException ( null , name ) ; } return null ; } return ( List < T > ) _references . find ( locator , required ) ; }
Finds all matching dependencies by their name and matching to the specified type .
18,712
public SubCommandSet add ( SubCommand < SubCommandDef > subCommand ) { if ( subCommandMap . containsKey ( subCommand . getName ( ) ) ) { throw new IllegalArgumentException ( "SubCommand with name " + subCommand . getName ( ) + " already exists" ) ; } this . subCommands . add ( subCommand ) ; this . subCommandMap . put ( subCommand . getName ( ) , subCommand ) ; for ( String alias : subCommand . getAliases ( ) ) { if ( subCommandMap . containsKey ( alias ) ) { throw new IllegalArgumentException ( "SubCommand (" + subCommand . getName ( ) + ") alias " + alias + " already exists" ) ; } this . subCommandMap . put ( alias , subCommand ) ; } return this ; }
Add a sub - command to the sub - command - set .
18,713
public final SubCommandSet addAll ( SubCommand < SubCommandDef > ... subCommands ) { for ( SubCommand < SubCommandDef > subCommand : subCommands ) { add ( subCommand ) ; } return this ; }
Add a set of sub - commands to the sub - command - set .
18,714
public void printUsage ( OutputStream out , String name , boolean showHidden ) { printUsage ( new PrintWriter ( new OutputStreamWriter ( out , UTF_8 ) ) , name , showHidden ) ; }
Print the option usage list for the command .
18,715
public String getSingleLineUsage ( String name ) { for ( SubCommand < SubCommandDef > cmd : subCommands ) { if ( name . equals ( cmd . getName ( ) ) ) { return cmd . getArgumentParser ( cmd . newInstance ( ) ) . getSingleLineUsage ( ) ; } } throw new ArgumentException ( "No such " + getName ( ) + " " + name ) ; }
Get the single line usage string for a given sub - command .
18,716
public Bits encodePPM ( String text , int context ) { final String original = text ; if ( ! text . endsWith ( "\u0000" ) ) text += END_OF_STRING ; ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; BitOutputStream out = new BitOutputStream ( buffer ) ; String contextStr = "" ; try { while ( ! text . isEmpty ( ) ) { String right = getRight ( contextStr , context ) ; TrieNode fromNode = inner . matchPredictor ( right ) ; String prefix = fromNode . getString ( ) ; TrieNode toNode = fromNode . traverse ( text ) ; int segmentChars = toNode . getDepth ( ) - fromNode . getDepth ( ) ; if ( toNode . hasChildren ( ) ) { if ( prefix . isEmpty ( ) && 0 == segmentChars ) { Optional < ? extends TrieNode > child = toNode . getChild ( ESCAPE ) ; assert child . isPresent ( ) ; toNode = child . get ( ) ; } else { toNode = toNode . getChild ( FALLBACK ) . get ( ) ; } } Interval interval = fromNode . intervalTo ( toNode ) ; Bits segmentData = interval . toBits ( ) ; if ( verbose ) { System . out . println ( String . format ( "Using context \"%s\", encoded \"%s\" (%s chars) as %s -> %s" , fromNode . getDebugString ( ) , toNode . getDebugString ( fromNode ) , segmentChars , interval , segmentData ) ) ; } out . write ( segmentData ) ; if ( 0 == segmentChars ) { if ( prefix . isEmpty ( ) ) { char exotic = text . charAt ( 0 ) ; out . write ( exotic ) ; if ( verbose ) { System . out . println ( String . format ( "Writing exotic character %s -> %s" , exotic , new Bits ( exotic , 16 ) ) ) ; } text = text . substring ( 1 ) ; } else if ( toNode . getChar ( ) == FALLBACK ) { contextStr = prefix . substring ( 1 ) ; } else { throw new RuntimeException ( "Cannot encode " + text . substring ( 0 , 1 ) ) ; } } else { contextStr += text . substring ( 0 , segmentChars ) ; text = text . substring ( segmentChars ) ; } } out . flush ( ) ; Bits bits = new Bits ( buffer . toByteArray ( ) , out . getTotalBitsWritten ( ) ) ; return bits ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
Encode ppm bits .
18,717
private String getNamedTagText ( final Element element , final String tagName ) { Element foundElement = XmlElementUtil . getFirstElementByTagName ( element , tagName ) ; if ( foundElement == null ) { return "" ; } else { return foundElement . getTextContent ( ) ; } }
Returns the text value of the named child element if it exists
18,718
public boolean contains ( final String category , final String checkId ) { return ( rules . containsKey ( getRuleKey ( category , checkId ) ) ) ; }
Returns if the rule set contains a rule for the specified category and id
18,719
public FxCopRule getRule ( final String category , final String checkId ) { String key = getRuleKey ( category , checkId ) ; FxCopRule rule = null ; if ( rules . containsKey ( key ) ) { rule = rules . get ( key ) ; } return rule ; }
Returns the specified rule if it exists
18,720
public static boolean isPrefixFreeCode ( final Set < Bits > keySet ) { final TreeSet < Bits > check = new TreeSet < Bits > ( ) ; for ( final Bits code : keySet ) { final Bits ceiling = check . ceiling ( code ) ; if ( null != ceiling && ( ceiling . startsWith ( code ) || code . startsWith ( ceiling ) ) ) { return false ; } final Bits floor = check . floor ( code ) ; if ( null != floor && ( floor . startsWith ( code ) || code . startsWith ( floor ) ) ) { return false ; } check . add ( code ) ; } return true ; }
Is prefix free code boolean .
18,721
public T decode ( final BitInputStream in ) throws IOException { Bits remainder = in . readAhead ( 0 ) ; Entry < Bits , T > entry = this . forwardIndex . floorEntry ( remainder ) ; while ( entry == null || ! remainder . startsWith ( entry . getKey ( ) ) ) { remainder = in . readAhead ( ) ; entry = this . forwardIndex . floorEntry ( remainder ) ; } in . read ( entry . getKey ( ) . bitLength ) ; return entry . getValue ( ) ; }
Decode t .
18,722
public Entry < Bits , T > decode ( final Bits data ) { if ( null == data ) { throw new IllegalArgumentException ( ) ; } Entry < Bits , T > entry = this . forwardIndex . floorEntry ( data ) ; if ( entry != null && ! data . startsWith ( entry . getKey ( ) ) ) { entry = null ; } return entry ; }
Decode entry .
18,723
public Bits encode ( final T key ) { final Bits bits = this . reverseIndex . get ( key ) ; assert null != bits || this . verifyIndexes ( ) ; return bits ; }
Encode bits .
18,724
public SortedMap < Bits , T > getCodes ( final Bits fromKey ) { final Bits next = fromKey . next ( ) ; final SortedMap < Bits , T > subMap = null == next ? this . forwardIndex . tailMap ( fromKey ) : this . forwardIndex . subMap ( fromKey , next ) ; return subMap ; }
Gets codes .
18,725
public boolean verifyIndexes ( ) { if ( ! isPrefixFreeCode ( this . forwardIndex . keySet ( ) ) ) { return false ; } for ( final Entry < Bits , T > e : this . forwardIndex . entrySet ( ) ) { if ( ! e . getKey ( ) . equals ( this . reverseIndex . get ( e . getValue ( ) ) ) ) { return false ; } if ( ! e . getValue ( ) . equals ( this . forwardIndex . get ( e . getKey ( ) ) ) ) { return false ; } } for ( final Entry < T , Bits > e : this . reverseIndex . entrySet ( ) ) { if ( ! e . getKey ( ) . equals ( this . forwardIndex . get ( e . getValue ( ) ) ) ) { return false ; } if ( ! e . getValue ( ) . equals ( this . reverseIndex . get ( e . getKey ( ) ) ) ) { return false ; } } return this . reverseIndex . size ( ) == this . forwardIndex . size ( ) ; }
Verify indexes boolean .
18,726
public static ServiceInstance toServiceInstance ( ModelServiceInstance modelInstance ) { if ( modelInstance == null ) throw new NullPointerException ( ) ; Map < String , String > meta = new HashMap < > ( ) ; if ( modelInstance . getMetadata ( ) != null ) { for ( Entry < String , String > en : modelInstance . getMetadata ( ) . entrySet ( ) ) { meta . put ( en . getKey ( ) , en . getValue ( ) ) ; } } return new ServiceInstance ( modelInstance . getServiceName ( ) , modelInstance . getUri ( ) , modelInstance . isMonitorEnabled ( ) , modelInstance . getStatus ( ) , modelInstance . getAddress ( ) , meta , modelInstance . getPort ( ) , modelInstance . getTls_port ( ) , modelInstance . getProtocol ( ) ) ; }
Convert a ModelServiceInstance to a ServiceInstance object .
18,727
public static ServiceInstance11 toServiceInstance11 ( ModelServiceInstance11 modelInstance ) { if ( modelInstance == null ) throw new NullPointerException ( ) ; Map < String , String > meta = new HashMap < > ( ) ; if ( modelInstance . getMetadata ( ) != null ) { for ( Entry < String , String > en : modelInstance . getMetadata ( ) . entrySet ( ) ) { meta . put ( en . getKey ( ) , en . getValue ( ) ) ; } } return new ServiceInstance11 ( modelInstance . getServiceName ( ) , modelInstance . getInstanceId ( ) , modelInstance . getUri ( ) , modelInstance . isMonitorEnabled ( ) , modelInstance . getStatus ( ) , modelInstance . getAddress ( ) , modelInstance . getPort ( ) , meta ) ; }
convert v1 . 1 modelServiceInstance to serviceInstance
18,728
public static ModelServiceInstance copyModelInstFrom ( ModelServiceInstance original ) { ModelServiceInstance copied = new ModelServiceInstance ( ) ; copied . setServiceName ( original . getServiceName ( ) ) ; copied . setAddress ( original . getAddress ( ) ) ; copied . setStatus ( original . getStatus ( ) ) ; copied . setUri ( original . getUri ( ) ) ; copied . setId ( original . getId ( ) ) ; copied . setInstanceId ( original . getInstanceId ( ) ) ; copied . setMonitorEnabled ( original . isMonitorEnabled ( ) ) ; copied . setCreateTime ( original . getCreateTime ( ) ) ; copied . setModifiedTime ( original . getModifiedTime ( ) ) ; copied . setHeartbeatTime ( original . getHeartbeatTime ( ) ) ; Map < String , String > newMeta = new HashMap < > ( ) ; Map < String , String > oldMeta = original . getMetadata ( ) ; if ( oldMeta != null ) newMeta . putAll ( oldMeta ) ; copied . setMetadata ( newMeta ) ; return copied ; }
Create new copy of ModelServiceInstance from the original one .
18,729
private void read ( ) throws IOException , GrammarException { try { logger . debug ( "Read grammar file..." ) ; logger . debug ( "Starting lexer..." ) ; Lexer lexer = new RegExpLexer ( uhuraGrammar ) ; TokenStream tokenStream = lexer . lex ( SourceCode . read ( reader , new UnspecifiedSourceCodeLocation ( ) ) ) ; logger . debug ( "Starting parser..." ) ; parse ( tokenStream ) ; logger . debug ( "done reading grammar file." ) ; } catch ( LexerException e ) { logger . error ( e . getMessage ( ) , e ) ; throw new IOException ( e . getMessage ( ) , e ) ; } catch ( ParserException e ) { logger . error ( e . getMessage ( ) , e ) ; throw new IOException ( e . getMessage ( ) , e ) ; } }
This is the central reading routine which starts all sub routines like lexer parser and converter .
18,730
private void parse ( TokenStream tokenStream ) throws ParserException { try { Parser parser = new SLR1Parser ( uhuraGrammar ) ; parserTree = parser . parse ( tokenStream ) ; } catch ( GrammarException e ) { logger . error ( e . getMessage ( ) , e ) ; throw new RuntimeException ( "UhuraGrammar is broken!!!" ) ; } }
This method does the parsing and reacts appropriately to any exceptions .
18,731
public static ConfigParser getParserForName ( String name ) { int lastDot = name . lastIndexOf ( "." ) ; if ( lastDot < 0 ) { throw new ConfigException ( "No file suffix in name: " + name ) ; } String suffix = name . substring ( lastDot ) ; switch ( suffix . toLowerCase ( ) ) { case ".toml" : case ".ini" : return new TomlConfigParser ( ) ; case ".json" : return new JsonConfigParser ( ) ; case ".properties" : return new PropertiesConfigParser ( ) ; default : throw new ConfigException ( "Unknown config file suffix: " + suffix ) ; } }
Get the parser that matches the file format associated with the given file suffix . The given string must include the last . in order to be valid .
18,732
public static double asDouble ( Object value ) { if ( value instanceof Number ) { return ( ( Number ) value ) . doubleValue ( ) ; } else if ( value instanceof Numeric ) { return ( ( Numeric ) value ) . asInteger ( ) ; } else if ( value instanceof CharSequence ) { try { return Double . parseDouble ( value . toString ( ) ) ; } catch ( NumberFormatException nfe ) { throw new IncompatibleValueException ( "Unable to parse string \"" + Strings . escape ( value . toString ( ) ) + "\" to a double" , nfe ) ; } } throw new IncompatibleValueException ( "Unable to convert " + value . getClass ( ) . getSimpleName ( ) + " to a double" ) ; }
Convert the value to a souble .
18,733
public static Date asDate ( Object value ) { if ( value instanceof Date ) { return ( Date ) value ; } else if ( value instanceof CharSequence ) { String date = value . toString ( ) . trim ( ) ; try { LocalDateTime time ; if ( date . endsWith ( "Z" ) ) { time = LocalDateTime . parse ( ( CharSequence ) value , DateTimeFormatter . ISO_INSTANT . withZone ( Clock . systemUTC ( ) . getZone ( ) ) ) ; } else { time = LocalDateTime . parse ( ( CharSequence ) value , DateTimeFormatter . ISO_OFFSET_DATE_TIME . withZone ( Clock . systemUTC ( ) . getZone ( ) ) ) ; } return new Date ( time . atZone ( Clock . systemUTC ( ) . getZone ( ) ) . toInstant ( ) . toEpochMilli ( ) ) ; } catch ( RuntimeException e ) { throw new ConfigException ( e , "Unable to parse date: " + e . getMessage ( ) ) ; } } else if ( value instanceof Long ) { return new Date ( ( Long ) value ) ; } else if ( value instanceof Integer ) { return new Date ( ( ( Integer ) value ) . longValue ( ) * 1000L ) ; } else { throw new IncompatibleValueException ( "Unable to convert " + value . getClass ( ) . getSimpleName ( ) + " to a date" ) ; } }
Convert the value to a date .
18,734
public static String [ ] asStringArray ( Object value ) { List < String > collection = asCollection ( value ) . stream ( ) . map ( ConfigUtil :: asString ) . collect ( Collectors . toList ( ) ) ; return collection . toArray ( new String [ collection . size ( ) ] ) ; }
Make collection into a string array .
18,735
public static boolean [ ] asBooleanArray ( Collection collection ) { boolean [ ] result = new boolean [ collection . size ( ) ] ; int i = 0 ; for ( Object c : collection ) { result [ i ++ ] = asBoolean ( c ) ; } return result ; }
Make collection into a boolean array .
18,736
public static int [ ] asIntegerArray ( Collection collection ) { int [ ] result = new int [ collection . size ( ) ] ; int i = 0 ; for ( Object c : collection ) { result [ i ++ ] = asInteger ( c ) ; } return result ; }
Make collection into an integer array .
18,737
public static long [ ] asLongArray ( Collection collection ) { long [ ] result = new long [ collection . size ( ) ] ; int i = 0 ; for ( Object c : collection ) { result [ i ++ ] = asLong ( c ) ; } return result ; }
Make collection into a long array .
18,738
public static double [ ] asDoubleArray ( Collection collection ) { double [ ] result = new double [ collection . size ( ) ] ; int i = 0 ; for ( Object c : collection ) { result [ i ++ ] = asDouble ( c ) ; } return result ; }
Make collection into a double array .
18,739
public static String getLayerName ( Supplier < Config > layer ) { String str = layer . toString ( ) ; if ( str . contains ( "$$Lambda$" ) ) { return String . format ( "InMemorySupplier{%s}" , layer . get ( ) . getClass ( ) . getSimpleName ( ) ) ; } return str ; }
Get the layer name based on the supplier .
18,740
public boolean isInGroup ( final String other ) { return ParserRegistry . getParser ( group ) . getGroup ( ) . equals ( ParserRegistry . getParser ( other ) . getGroup ( ) ) ; }
Returns whether this parser is in the specified group .
18,741
public < T > T markPropertyAsSet ( String property , T value ) { setProperties . add ( property ) ; return value ; }
Marks the specified property as set and returns the value given as the second argument . This is meant to be used as a one - liner .
18,742
public int add ( String fragments ) { if ( fragments == null ) { return 0 ; } final String [ ] splitFragments = fragments . replaceFirst ( "^\\/" , "" ) . split ( "\\/" , - 1 ) ; final int n = splitFragments . length ; for ( int i = 0 ; i < n ; i ++ ) { pathFragments . add ( splitFragments [ i ] ) ; } return n ; }
Adds the path fragments contained in the specified string . This method performs no escaping so reserved JSON Pointer characters should already be escaped .
18,743
public void unbind ( ValidationSession session , ValidationObject validationObject , Map < ValidationObject , ProxyObject > boundMap ) { if ( validationObject == null ) { return ; } ProxyObject proxyObject = session . getProxyObject ( validationObject ) ; Map < String , ProxyField > fieldMap = proxyObject . getFieldMap ( ) ; for ( String fieldName : fieldMap . keySet ( ) ) { if ( fieldName != null ) { final ClassMetadata classMetadata = m_validationEngine . getClassMetadata ( validationObject . getClass ( ) ) ; final PropertyMetadata fieldMetadata = classMetadata . getField ( fieldName ) ; if ( fieldMetadata == null ) { continue ; } ProxyField proxyField = proxyObject . getProxyField ( fieldName ) ; Method getter = proxyField . getGetter ( ) ; if ( getter . getReturnType ( ) . isAssignableFrom ( List . class ) ) { try { @ SuppressWarnings ( "unchecked" ) final List < ValidationObject > validationObjects = ( List < ValidationObject > ) getter . invoke ( validationObject , new Object [ ] { } ) ; for ( ValidationObject child : validationObjects ) { m_validationEngine . unbind ( session , proxyField , child , boundMap ) ; if ( child != null ) { child . setValidationSession ( null ) ; } } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } continue ; } if ( m_validationEngine . getClassMetadata ( getter . getReturnType ( ) ) != null ) { try { ValidationObject child = ( ValidationObject ) getter . invoke ( validationObject , new Object [ ] { } ) ; m_validationEngine . unbind ( session , proxyField , child , boundMap ) ; if ( child != null ) { child . setValidationSession ( null ) ; } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } continue ; } } } }
Unbind the given object . We have to locate any attached objects and unbind them first .
18,744
void registerAndConnect ( SocketChannel sock , InetSocketAddress addr ) throws IOException { selectionKey = sock . register ( selector , SelectionKey . OP_CONNECT ) ; boolean immediateConnect = sock . connect ( addr ) ; if ( LOGGER . isTraceEnabled ( ) ) { LOGGER . trace ( "Connect to host=" + addr . getHostName ( ) + ", hostString=" + addr . getHostString ( ) + ", port=" + addr . getPort ( ) + ", all=" + addr . getAddress ( ) + ", local=" + sock . socket ( ) . getLocalSocketAddress ( ) ) ; } if ( immediateConnect ) { onConnectSucceeded ( ) ; } }
Register a SocketChannel and connect the remote address .
18,745
SocketChannel createSock ( ) throws IOException { SocketChannel sock ; sock = SocketChannel . open ( ) ; sock . configureBlocking ( false ) ; sock . socket ( ) . setSoLinger ( false , - 1 ) ; sock . socket ( ) . setTcpNoDelay ( true ) ; return sock ; }
Create a SocketChannel .
18,746
protected void readLength ( ) throws IOException { int len = incomingBuffer . getInt ( ) ; if ( LOGGER . isTraceEnabled ( ) ) { LOGGER . trace ( "Read length in client - " + len ) ; } if ( len < 0 || len >= DirectoryConnection . packetLen ) { throw new IOException ( "Packet len" + len + " is out of range!" ) ; } incomingBuffer = ByteBuffer . allocate ( len ) ; }
Read the buffer message length .
18,747
private void doSocketConnect ( InetSocketAddress addr ) throws IOException { SocketChannel sock = createSock ( ) ; registerAndConnect ( sock , addr ) ; }
Do the Socket connect .
18,748
private void onConnectSucceeded ( ) { LOGGER . info ( "Accepted the connection." ) ; isConnected = true ; isConnecting = false ; enableReadOnly ( ) ; synchronized ( connectHolder ) { connectHolder . notifyAll ( ) ; } }
On the socked connected .
18,749
private void onConnectFailed ( ) { LOGGER . info ( "Socket failed" ) ; isConnecting = false ; isConnected = false ; cleanup ( ) ; synchronized ( connectHolder ) { connectHolder . notifyAll ( ) ; } }
On the socket connect failed .
18,750
public static OutputStream create ( final int port , final File path , final String mimeType ) throws IOException { return new com . simiacryptus . util . StreamNanoHTTPD ( port , mimeType , path ) . init ( ) . dataReciever ; }
Create output stream .
18,751
public void addAsyncHandler ( final String path , final String mimeType , final Consumer < OutputStream > logic , final boolean async ) { addSessionHandler ( path , com . simiacryptus . util . StreamNanoHTTPD . asyncHandler ( pool , mimeType , logic , async ) ) ; }
Add async handler .
18,752
public Function < IHTTPSession , Response > addSessionHandler ( final String path , final Function < IHTTPSession , Response > value ) { return customHandlers . put ( path , value ) ; }
Add session handler function .
18,753
public com . simiacryptus . util . StreamNanoHTTPD init ( ) throws IOException { com . simiacryptus . util . StreamNanoHTTPD . this . start ( 30000 ) ; new Thread ( ( ) -> { try { Thread . sleep ( 100 ) ; if ( null != gatewayUri ) Desktop . getDesktop ( ) . browse ( gatewayUri ) ; } catch ( final Exception e ) { e . printStackTrace ( ) ; } } ) . start ( ) ; return this ; }
Init stream nano httpd .
18,754
public final boolean strEquals ( byte [ ] a , int aOff , int aLen ) { if ( aLen != len ) { return false ; } for ( int i = 0 ; i < len ; ++ i ) { if ( a [ aOff + i ] != fb [ off + i ] ) { return false ; } } return true ; }
Checks if the slice is equal to a portion of a given byte array .
18,755
public void set ( final String name , final String value ) { other . put ( name , value ) ; }
Set configuration values dynamically
18,756
public Properties asProperties ( ) { final Properties props = new Properties ( ) ; other . forEach ( props :: setProperty ) ; props . setProperty ( "bootstrap.servers" , bootstrapServers ) ; return props ; }
Get all configuration values in a Properties object
18,757
protected int count ( final T key ) { final AtomicInteger counter = this . map . get ( key ) ; if ( null == counter ) { return 0 ; } return counter . get ( ) ; }
Count int .
18,758
public List < T > getList ( ) { final ArrayList < T > list = new ArrayList < T > ( ) ; for ( final Entry < T , AtomicInteger > e : this . map . entrySet ( ) ) { for ( int i = 0 ; i < e . getValue ( ) . get ( ) ; i ++ ) { list . add ( e . getKey ( ) ) ; } } return list ; }
Gets list .
18,759
public Map < T , Integer > getMap ( ) { return Maps . transformEntries ( this . map , new EntryTransformer < T , AtomicInteger , Integer > ( ) { public Integer transformEntry ( final T key , final AtomicInteger value ) { return value . get ( ) ; } } ) ; }
Gets map .
18,760
public void registerService ( ProvidedServiceInstance serviceInstance , ServiceInstanceHealth registryHealth ) { if ( serviceInstance . isMonitorEnabled ( ) == false ) { throw new ServiceException ( ErrorCode . SERVICE_INSTANCE_HEALTH_ERROR ) ; } registerService ( serviceInstance ) ; }
Register a ProvidedServiceInstance with the ServiceInstanceHealth callback .
18,761
public void updateServiceUri ( String serviceName , String providerId , String uri ) { getServiceDirectoryClient ( ) . updateInstanceUri ( serviceName , providerId , uri , disableOwnerError ) ; }
Update the uri attribute of the ProvidedServiceInstance The ProvidedServiceInstance is uniquely identified by serviceName and providerId
18,762
public void unregisterService ( String serviceName , String providerId ) { getServiceDirectoryClient ( ) . unregisterInstance ( serviceName , providerId , disableOwnerError ) ; }
Unregister a ProvidedServiceInstance The ProvidedServiceInstance is uniquely identified by serviceName and providerId
18,763
public boolean migrate ( Version targetVersion ) { printRunHeader ( "MIGRATE" ) ; StopWatch stopWatch = new StopWatch ( ) ; stopWatch . start ( ) ; boolean success = false ; try { transform ( targetVersion ) ; success = true ; } catch ( TransformationException | InvalidSequenceException e ) { e . printStackTrace ( System . err ) ; } stopWatch . stop ( ) ; printRunFooter ( success , stopWatch ) ; return success ; }
Runs the migration to a specified version .
18,764
protected BuildHistory createBuildHistory ( ) { AbstractBuild < ? , ? > lastFinishedBuild = getLastFinishedBuild ( ) ; if ( lastFinishedBuild == null ) { return new NullBuildHistory ( ) ; } else { return createHistory ( lastFinishedBuild ) ; } }
Creates the build history .
18,765
public ServiceInstance vote ( ) { List < ModelServiceInstance > instances = getServiceInstanceList ( ) ; if ( instances == null || instances . isEmpty ( ) ) { return null ; } int i = index . getAndIncrement ( ) ; int pos = i % instances . size ( ) ; ModelServiceInstance instance = instances . get ( pos ) ; return ServiceInstanceUtils . transferFromModelServiceInstance ( instance ) ; }
Vote a ServiceInstance based on the LoadBalancer algorithm .
18,766
public void addRootGroup ( final Group nextRootGroup ) { this . getRootGroups ( ) . add ( nextRootGroup ) ; RepositoryConnection conn = null ; try { conn = this . repository . getConnection ( ) ; conn . begin ( ) ; this . storeGroup ( nextRootGroup , conn , true ) ; conn . commit ( ) ; } catch ( final RepositoryException e ) { this . log . error ( "Found exception while storing root group" , e ) ; if ( conn != null ) { try { conn . rollback ( ) ; } catch ( final RepositoryException e1 ) { this . log . error ( "Found exception while trying to roll back connection" , e1 ) ; } } } finally { if ( conn != null ) { try { conn . close ( ) ; } catch ( final RepositoryException e ) { this . log . error ( "Found exception closing repository connection" , e ) ; } } } }
Adds a fully populated root group to the underlying repository including a statement indicating that this group is a root group .
18,767
protected RestletUtilUser buildRestletUserFromSparqlResult ( final String userIdentifier , final BindingSet bindingSet ) { String userEmail = bindingSet . getValue ( "userEmail" ) . stringValue ( ) ; char [ ] userSecret = null ; if ( bindingSet . hasBinding ( "userSecret" ) ) { userSecret = bindingSet . getValue ( "userSecret" ) . stringValue ( ) . toCharArray ( ) ; } String userFirstName = null ; if ( bindingSet . hasBinding ( "userFirstName" ) ) { userFirstName = bindingSet . getValue ( "userFirstName" ) . stringValue ( ) ; } String userLastName = null ; if ( bindingSet . hasBinding ( "userLastName" ) ) { userLastName = bindingSet . getValue ( "userLastName" ) . stringValue ( ) ; } return new RestletUtilUser ( userIdentifier , userSecret , userFirstName , userLastName , userEmail ) ; }
Builds a RestletUtilUser from the data retrieved in a SPARQL result .
18,768
protected String buildSparqlQueryToFindUser ( final String userIdentifier , boolean findAllUsers ) { if ( ! findAllUsers && userIdentifier == null ) { throw new NullPointerException ( "User identifier was null" ) ; } final StringBuilder query = new StringBuilder ( ) ; query . append ( " SELECT ?userIdentifier ?userUri ?userSecret ?userFirstName ?userLastName ?userEmail " ) ; query . append ( " WHERE " ) ; query . append ( " { " ) ; query . append ( " ?userUri a " ) ; query . append ( RenderUtils . getSPARQLQueryString ( SesameRealmConstants . OAS_USER ) ) ; query . append ( " . " ) ; query . append ( " ?userUri " ) ; query . append ( RenderUtils . getSPARQLQueryString ( SesameRealmConstants . OAS_USERIDENTIFIER ) ) ; query . append ( " ?userIdentifier . " ) ; query . append ( " OPTIONAL{ ?userUri " ) ; query . append ( RenderUtils . getSPARQLQueryString ( SesameRealmConstants . OAS_USERSECRET ) ) ; query . append ( " ?userSecret . } " ) ; query . append ( " OPTIONAL{ ?userUri " ) ; query . append ( RenderUtils . getSPARQLQueryString ( SesameRealmConstants . OAS_USERFIRSTNAME ) ) ; query . append ( " ?userFirstName . } " ) ; query . append ( " OPTIONAL{ ?userUri " ) ; query . append ( RenderUtils . getSPARQLQueryString ( SesameRealmConstants . OAS_USERLASTNAME ) ) ; query . append ( " ?userLastName . } " ) ; query . append ( " OPTIONAL{ ?userUri " ) ; query . append ( RenderUtils . getSPARQLQueryString ( SesameRealmConstants . OAS_USEREMAIL ) ) ; query . append ( " ?userEmail . } " ) ; if ( ! findAllUsers ) { query . append ( " FILTER(str(?userIdentifier) = \"" + RenderUtils . escape ( userIdentifier ) + "\") " ) ; } query . append ( " } " ) ; return query . toString ( ) ; }
Builds a SPARQL query to retrieve details of a RestletUtilUser . This method could be overridden to search for other information regarding a user .
18,769
public Set < Role > findRoles ( final Set < Group > userGroups ) { final Set < Role > result = new HashSet < Role > ( ) ; for ( final RoleMapping mapping : this . getRoleMappings ( ) ) { final Object source = mapping . getSource ( ) ; if ( ( userGroups != null ) && userGroups . contains ( source ) ) { result . add ( mapping . getTarget ( ) ) ; } } return result ; }
Finds the roles mapped to given user groups .
18,770
public List < Group > getRootGroups ( ) { List < Group > results = this . cachedRootGroups ; if ( results == null ) { synchronized ( this ) { results = this . cachedRootGroups ; if ( results == null ) { results = new ArrayList < Group > ( ) ; RepositoryConnection conn = null ; try { conn = this . getRepository ( ) . getConnection ( ) ; final RepositoryResult < Statement > rootGroupStatements = conn . getStatements ( null , RDF . TYPE , SesameRealmConstants . OAS_ROOTGROUP , true , this . getContexts ( ) ) ; try { while ( rootGroupStatements . hasNext ( ) ) { final Statement nextRootGroupStatement = rootGroupStatements . next ( ) ; if ( nextRootGroupStatement . getSubject ( ) instanceof URI ) { final URI nextRootGroupUri = ( URI ) nextRootGroupStatement . getSubject ( ) ; results . add ( this . createGroupHierarchy ( null , conn , nextRootGroupUri ) ) ; } else { this . log . warn ( "Not including root group as it did not have a URI identifier: {}" , nextRootGroupStatement ) ; } } } finally { rootGroupStatements . close ( ) ; } } catch ( final RepositoryException e ) { this . log . error ( "Found exception while trying to get root groups" , e ) ; } finally { try { if ( conn != null ) { conn . close ( ) ; } } catch ( final RepositoryException e ) { this . log . error ( "Found unexpected exception while closing repository connection" , e ) ; } } this . cachedRootGroups = results ; } } } return results ; }
Returns the modifiable list of root groups .
18,771
public List < RestletUtilUser > getUsers ( ) { List < RestletUtilUser > result = new ArrayList < RestletUtilUser > ( ) ; RepositoryConnection conn = null ; try { conn = this . repository . getConnection ( ) ; final String query = this . buildSparqlQueryToFindUser ( null , true ) ; this . log . debug ( "findUser: query={}" , query ) ; final TupleQuery tupleQuery = conn . prepareTupleQuery ( QueryLanguage . SPARQL , query ) ; final TupleQueryResult queryResult = tupleQuery . evaluate ( ) ; try { while ( queryResult . hasNext ( ) ) { final BindingSet bindingSet = queryResult . next ( ) ; Binding binding = bindingSet . getBinding ( "userIdentifier" ) ; result . add ( this . buildRestletUserFromSparqlResult ( binding . getValue ( ) . stringValue ( ) , bindingSet ) ) ; } } finally { queryResult . close ( ) ; } } catch ( final RepositoryException e ) { throw new RuntimeException ( "Failure finding user in repository" , e ) ; } catch ( final MalformedQueryException e ) { throw new RuntimeException ( "Failure finding user in repository" , e ) ; } catch ( final QueryEvaluationException e ) { throw new RuntimeException ( "Failure finding user in repository" , e ) ; } finally { try { conn . close ( ) ; } catch ( final RepositoryException e ) { this . log . error ( "Failure to close connection" , e ) ; } } return Collections . unmodifiableList ( result ) ; }
Returns an unmodifiable list of users .
18,772
private void storeGroup ( final Group nextGroup , final RepositoryConnection conn , final boolean isRootGroup ) throws RepositoryException { if ( conn . hasStatement ( null , SesameRealmConstants . OAS_GROUPNAME , this . vf . createLiteral ( nextGroup . getName ( ) ) , true , this . getContexts ( ) ) ) { throw new RuntimeException ( "A user with the given identifier already exists. Cannot add a new user with that identifier." ) ; } final URI nextGroupUUID = this . vf . createURI ( "urn:oas:group:" , nextGroup . getName ( ) + ":" + UUID . randomUUID ( ) . toString ( ) ) ; conn . add ( this . vf . createStatement ( nextGroupUUID , RDF . TYPE , SesameRealmConstants . OAS_GROUP ) , this . getContexts ( ) ) ; if ( isRootGroup ) { conn . add ( this . vf . createStatement ( nextGroupUUID , RDF . TYPE , SesameRealmConstants . OAS_ROOTGROUP ) , this . getContexts ( ) ) ; } conn . add ( this . vf . createStatement ( nextGroupUUID , SesameRealmConstants . OAS_GROUPNAME , this . vf . createLiteral ( nextGroup . getName ( ) ) ) , this . getContexts ( ) ) ; conn . add ( this . vf . createStatement ( nextGroupUUID , SesameRealmConstants . OAS_GROUPDESCRIPTION , this . vf . createLiteral ( nextGroup . getDescription ( ) ) ) , this . getContexts ( ) ) ; conn . add ( this . vf . createStatement ( nextGroupUUID , SesameRealmConstants . OAS_GROUPINHERITINGROLES , this . vf . createLiteral ( nextGroup . isInheritingRoles ( ) ) ) , this . getContexts ( ) ) ; for ( final User nextUser : nextGroup . getMemberUsers ( ) ) { if ( this . findUser ( nextUser . getIdentifier ( ) ) == null ) { final URI nextUserUri = this . addUser ( nextUser ) ; } } if ( ! nextGroup . getMemberGroups ( ) . isEmpty ( ) ) { for ( final Group nextMemberGroup : nextGroup . getMemberGroups ( ) ) { this . storeGroup ( nextMemberGroup , conn , false ) ; } } }
Stores the group including a root group statement if rootGroup is true .
18,773
public void unmap ( final Group group , final Role role ) { this . unmap ( role , SesameRealmConstants . OAS_ROLEMAPPEDGROUP , group . getName ( ) ) ; }
Unmaps a group defined in a component from a role defined in the application .
18,774
public void unmap ( final RestletUtilUser user , final Role role ) { this . unmap ( role , SesameRealmConstants . OAS_ROLEMAPPEDUSER , user . getIdentifier ( ) ) ; }
Unmaps a user defined in a component from a role defined in the application .
18,775
@ SuppressWarnings ( "unchecked" ) public static < T > T shallowCopy ( T original ) { Class < ? extends T > clazz = ( Class < ? extends T > ) original . getClass ( ) ; BeanClass < ? extends T > beanClass = ( BeanClass < ? extends T > ) classes . get ( clazz ) ; if ( beanClass == null ) { beanClass = BeanClass . buildFrom ( clazz ) ; classes . put ( clazz , beanClass ) ; } return shallowCopyHelper ( original , beanClass ) ; }
Requires a no - args constructor
18,776
public static Writer append ( Writer writer , String string ) { try { writer . append ( string ) ; writer . flush ( ) ; return writer ; } catch ( IOException e ) { return JMExceptionManager . handleExceptionAndReturn ( log , e , "append" , ( ) -> writer , string ) ; } }
Append writer .
18,777
public static Writer appendLine ( Writer writer , String line ) { return append ( writer , line + JMString . LINE_SEPARATOR ) ; }
Append line writer .
18,778
public static Writer buildBufferedAppendWriter ( Path path , Charset charset ) { try { if ( JMPath . notExists ( path ) ) JMPathOperation . createFileWithParentDirectories ( path ) ; return Files . newBufferedWriter ( path , charset , StandardOpenOption . APPEND ) ; } catch ( IOException e ) { return JMExceptionManager . handleExceptionAndReturnNull ( log , e , "buildBufferedAppendWriter" , path , charset ) ; } }
Build buffered append writer writer .
18,779
public static boolean writeString ( String inputString , File targetFile ) { if ( ! targetFile . exists ( ) ) { try { Files . write ( targetFile . toPath ( ) , inputString . getBytes ( ) ) ; } catch ( IOException e ) { return JMExceptionManager . handleExceptionAndReturnFalse ( log , e , "writeString" , inputString , targetFile ) ; } } return true ; }
Write string boolean .
18,780
public static boolean createEmptyFile ( File file ) { try { file . getParentFile ( ) . mkdirs ( ) ; return file . createNewFile ( ) ; } catch ( Exception e ) { return JMExceptionManager . handleExceptionAndReturnFalse ( log , e , "createEmptyFile" , file ) ; } }
Create empty file boolean .
18,781
public static String [ ] getArgs ( final String patternString , final String sourceString , final String [ ] keywordPrecedence ) { log . debug ( "Util getArgs String[] with pattern: " + patternString + " and sourceStr: " + sourceString ) ; String [ ] rtn = null ; ArrayList < String > argsList = null ; String patternCopy = new String ( patternString ) ; if ( keywordPrecedence != null && StringUtils . startsWithAny ( patternString , keywordPrecedence ) ) { for ( String s : keywordPrecedence ) { patternCopy = StringUtils . removeStart ( patternCopy , s ) ; } patternCopy = "(?:" + StringUtils . join ( keywordPrecedence , "|" ) + ")" + patternCopy ; } final Pattern pattern = Pattern . compile ( patternCopy ) ; final Matcher matcher = pattern . matcher ( sourceString ) ; final int groupCount = matcher . groupCount ( ) ; if ( matcher . find ( ) ) { for ( int i = 1 ; i <= groupCount ; i ++ ) { final String arg = matcher . group ( i ) ; if ( arg != null ) { if ( argsList == null ) { argsList = new ArrayList < String > ( ) ; } argsList . add ( arg ) ; } } } if ( argsList != null ) { rtn = argsList . toArray ( new String [ argsList . size ( ) ] ) ; if ( log . isDebugEnabled ( ) ) { final StringBuilder buf = new StringBuilder ( ) ; buf . append ( "returning args: " ) ; for ( final String s : argsList ) { buf . append ( "[" ) . append ( s ) . append ( "] " ) ; } log . debug ( buf . toString ( ) ) ; } } return rtn ; }
- could they be combined ??
18,782
public static String escape ( CharSequence string ) { StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < string . length ( ) ; ++ i ) { char c = string . charAt ( i ) ; switch ( c ) { case '\b' : builder . append ( '\\' ) . append ( 'b' ) ; break ; case '\t' : builder . append ( '\\' ) . append ( 't' ) ; break ; case '\n' : builder . append ( '\\' ) . append ( 'n' ) ; break ; case '\f' : builder . append ( '\\' ) . append ( 'f' ) ; break ; case '\r' : builder . append ( '\\' ) . append ( 'r' ) ; break ; case '"' : case '\'' : builder . append ( '\\' ) . append ( c ) ; break ; case '\\' : builder . append ( '\\' ) . append ( '\\' ) ; break ; default : if ( c < 32 || c == 127 ) { builder . append ( String . format ( "\\%03o" , ( int ) c ) ) ; } else if ( ! isConsolePrintable ( c ) || Character . isHighSurrogate ( c ) || Character . isLowSurrogate ( c ) ) { builder . append ( String . format ( "\\u%04x" , ( int ) c ) ) ; } else { builder . append ( c ) ; } break ; } } return builder . toString ( ) ; }
Properly java - escape the string for printing to console .
18,783
public static String escape ( char c ) { switch ( c ) { case '\b' : return "\\b" ; case '\t' : return "\\t" ; case '\n' : return "\\n" ; case '\f' : return "\\f" ; case '\r' : return "\\r" ; case '"' : return "\\\"" ; case '\'' : return "\\'" ; case '\\' : return "\\\\" ; default : if ( c < 32 || c == 127 ) { return String . format ( "\\%03o" , ( int ) c ) ; } else if ( ! isConsolePrintable ( c ) || isHighSurrogate ( c ) || isLowSurrogate ( c ) ) { return String . format ( "\\u%04x" , ( int ) c ) ; } return String . valueOf ( c ) ; } }
Escape a single character . It is escaped into a string as it may become more than one char when escaped .
18,784
public static String join ( String delimiter , Object ... values ) { if ( values . length == 1 ) { Class < ? > type = values [ 0 ] . getClass ( ) ; if ( char [ ] . class . equals ( type ) ) { return joinP ( delimiter , ( char [ ] ) values [ 0 ] ) ; } else if ( int [ ] . class . equals ( type ) ) { return joinP ( delimiter , ( int [ ] ) values [ 0 ] ) ; } else if ( long [ ] . class . equals ( type ) ) { return joinP ( delimiter , ( long [ ] ) values [ 0 ] ) ; } else if ( double [ ] . class . equals ( type ) ) { return joinP ( delimiter , ( double [ ] ) values [ 0 ] ) ; } else if ( boolean [ ] . class . equals ( type ) ) { return joinP ( delimiter , ( boolean [ ] ) values [ 0 ] ) ; } } StringBuilder builder = new StringBuilder ( ) ; boolean first = true ; for ( Object value : values ) { if ( first ) { first = false ; } else { builder . append ( delimiter ) ; } builder . append ( Objects . toString ( value ) ) ; } return builder . toString ( ) ; }
Join set of arbitrary values with delimiter .
18,785
public static < T > String join ( String delimiter , Collection < T > strings ) { StringBuilder builder = new StringBuilder ( ) ; boolean first = true ; for ( T o : strings ) { if ( first ) { first = false ; } else { builder . append ( delimiter ) ; } builder . append ( Objects . toString ( o ) ) ; } return builder . toString ( ) ; }
Join collection with delimiter .
18,786
public static String times ( String s , int num ) { StringBuilder builder = new StringBuilder ( ) ; for ( int i = 0 ; i < num ; ++ i ) { builder . append ( s ) ; } return builder . toString ( ) ; }
Multiply a string N times .
18,787
public static String camelCase ( String name ) { StringBuilder builder = new StringBuilder ( ) ; String [ ] parts = CAMEL_CASE_DELIMITER . split ( name ) ; for ( String part : parts ) { if ( part . isEmpty ( ) ) { continue ; } builder . append ( capitalize ( part ) ) ; } return builder . toString ( ) ; }
Format a name as CamelCase . The name is split on non - alphabet non - numeric chars and joined with each part capitalized . This is also called PascalCase . There is in this instance no assumptions on the name itself other than it contains some alphabet characters . Any uppercase letters in the name will be kept as uppercase so that a CamelCase name will stay CamelCase through this call .
18,788
public static String c_case ( String prefix , String name , String suffix ) { StringBuilder builder = new StringBuilder ( prefix . length ( ) + name . length ( ) + 5 ) ; builder . append ( prefix ) ; boolean lastUpper = true ; for ( char c : name . toCharArray ( ) ) { if ( Character . isUpperCase ( c ) ) { if ( ! lastUpper ) { builder . append ( '_' ) ; } lastUpper = true ; } else if ( c == '_' || c == '.' || c == '-' ) { builder . append ( '_' ) ; lastUpper = true ; continue ; } else if ( ! Character . isDigit ( c ) ) { lastUpper = false ; } builder . append ( Character . toLowerCase ( c ) ) ; } builder . append ( suffix ) ; return builder . toString ( ) ; }
Format a prefixed name as c_case . The prefix is kept verbatim while the name has a _ character inserted before each upper - case letter not including the first character . Then the whole thing is lower - cased .
18,789
public static String asString ( Collection < ? > collection ) { if ( collection == null ) { return NULL ; } StringBuilder builder = new StringBuilder ( ) ; builder . append ( '[' ) ; boolean first = true ; for ( Object item : collection ) { if ( first ) { first = false ; } else { builder . append ( ',' ) ; } builder . append ( asString ( item ) ) ; } builder . append ( ']' ) ; return builder . toString ( ) ; }
Make a printable string from a collection using the tools here .
18,790
public static String asString ( Map < ? , ? > map ) { if ( map == null ) { return NULL ; } StringBuilder builder = new StringBuilder ( ) ; builder . append ( '{' ) ; boolean first = true ; for ( Map . Entry < ? , ? > entry : map . entrySet ( ) ) { if ( first ) { first = false ; } else { builder . append ( ',' ) ; } builder . append ( asString ( entry . getKey ( ) ) ) . append ( ':' ) . append ( asString ( entry . getValue ( ) ) ) ; } builder . append ( '}' ) ; return builder . toString ( ) ; }
Make a minimal printable string value from a typed map .
18,791
public static String asString ( Object o ) { if ( o == null ) { return NULL ; } else if ( o instanceof Stringable ) { return ( ( Stringable ) o ) . asString ( ) ; } else if ( o instanceof Numeric ) { return String . format ( "%d" , ( ( Numeric ) o ) . asInteger ( ) ) ; } else if ( o instanceof CharSequence ) { return String . format ( "\"%s\"" , escape ( ( CharSequence ) o ) ) ; } else if ( o instanceof Double ) { return asString ( ( ( Double ) o ) . doubleValue ( ) ) ; } else if ( o instanceof Collection ) { return asString ( ( Collection < ? > ) o ) ; } else if ( o instanceof Map ) { return asString ( ( Map < ? , ? > ) o ) ; } else { return o . toString ( ) ; } }
Make an object into a string using the typed tools here .
18,792
public static int commonPrefix ( String text1 , String text2 ) { int n = Math . min ( text1 . length ( ) , text2 . length ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( text1 . charAt ( i ) != text2 . charAt ( i ) ) { return i ; } } return n ; }
Determine the common prefix of two strings
18,793
public static int commonSuffix ( String text1 , String text2 ) { int text1_length = text1 . length ( ) ; int text2_length = text2 . length ( ) ; int n = Math . min ( text1_length , text2_length ) ; for ( int i = 1 ; i <= n ; i ++ ) { if ( text1 . charAt ( text1_length - i ) != text2 . charAt ( text2_length - i ) ) { return i - 1 ; } } return n ; }
Determine the common suffix of two strings
18,794
public static int commonOverlap ( String text1 , String text2 ) { int text1_length = text1 . length ( ) ; int text2_length = text2 . length ( ) ; if ( text1_length == 0 || text2_length == 0 ) { return 0 ; } if ( text1_length > text2_length ) { text1 = text1 . substring ( text1_length - text2_length ) ; } else if ( text1_length < text2_length ) { text2 = text2 . substring ( 0 , text1_length ) ; } int text_length = Math . min ( text1_length , text2_length ) ; if ( text1 . equals ( text2 ) ) { return text_length ; } int best = 0 ; int length = 1 ; while ( true ) { String pattern = text1 . substring ( text_length - length ) ; int found = text2 . indexOf ( pattern ) ; if ( found == - 1 ) { return best ; } length += found ; if ( found == 0 || text1 . substring ( text_length - length ) . equals ( text2 . substring ( 0 , length ) ) ) { best = length ; length ++ ; } } }
Determine if the suffix of one string is the prefix of another .
18,795
public static String getThreadName ( String name ) { if ( name == null || name . isEmpty ( ) ) { return SD_THREAD_PREFIX + nextIndex ( ) ; } return SD_THREAD_PREFIX + name + "_" + nextIndex ( ) ; }
Get the SD prefixed thread name .
18,796
private static Thread doThread ( Runnable runnable , String name , boolean deamon ) { String realname = getThreadName ( name ) ; Thread t = new Thread ( runnable ) ; t . setName ( realname ) ; t . setDaemon ( deamon ) ; return t ; }
Generate the Thread .
18,797
public Result find ( String rowKey , List < String > returnFields , QueryOptions options ) throws IOException { Get get = new Get ( rowKey . getBytes ( ) ) ; if ( returnFields != null ) { for ( String field : returnFields ) { String [ ] parts = field . split ( ":" ) ; get . addColumn ( parts [ 0 ] . getBytes ( ) , parts [ 1 ] . getBytes ( ) ) ; } } else { getReturnFields ( get , options ) ; } int maxVersions = ( options != null ) ? options . getInt ( "maxVersions" , 0 ) : 0 ; if ( maxVersions > 0 ) { get . setMaxVersions ( maxVersions ) ; } return table . get ( get ) ; }
Returns the result from a query to a single row performed using a Get object from HBase API .
18,798
public Iterator < Result > find ( String startRow , String endRow , List < String > returnFields , QueryOptions options ) throws IOException { Scan scan = new Scan ( startRow . getBytes ( ) , endRow . getBytes ( ) ) ; if ( returnFields != null ) { for ( String field : returnFields ) { String [ ] parts = field . split ( ":" ) ; scan . addColumn ( parts [ 0 ] . getBytes ( ) , parts [ 1 ] . getBytes ( ) ) ; } } else { getReturnFields ( scan , options ) ; } int maxVersions = ( options != null ) ? options . getInt ( "maxVersions" , 0 ) : 0 ; if ( maxVersions > 0 ) { scan . setMaxVersions ( maxVersions ) ; } int limit = ( options != null ) ? options . getInt ( "limit" , 0 ) : 0 ; if ( limit > 0 ) { scan . setFilter ( new PageFilter ( limit ) ) ; } String sort = ( options != null ) ? options . getString ( "sort" ) : null ; if ( sort != null ) { if ( sort . equalsIgnoreCase ( "asc" ) ) { scan . setReversed ( false ) ; } else if ( sort . equalsIgnoreCase ( "desc" ) ) { scan . setReversed ( true ) ; } } ResultScanner scanres = table . getScanner ( scan ) ; return scanres . iterator ( ) ; }
Returns the results from a query to multiple rows performed using a Scan object from HBase API .
18,799
public static String getResultUrl ( final String group ) { if ( group == null ) { return RESULT_URL ; } else { return PLUGIN_ID + ParserRegistry . getUrl ( group ) + RESULT_URL_SUFFIX ; } }
Returns the URL of the warning results for the specified parser .