idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
38,500
public static < T > void gauge ( MetricNameDetails nameDetails , final Callable < T > impl ) { gauge ( nameDetails , new Gauge < T > ( ) { public T getValue ( ) { try { return impl . call ( ) ; } catch ( Exception ex ) { throw new RuntimeException ( ex ) ; } } } ) ; }
This doesn t make a ton of sense given the above but it will likely be cleaner in Java8 . Also avoids having to catch an exception in a Gauge implementation .
38,501
public static byte [ ] [ ] getSplitKeys ( Pair < byte [ ] [ ] , byte [ ] [ ] > regionStartsEnds ) { byte [ ] [ ] starts = regionStartsEnds . getFirst ( ) ; List < byte [ ] > splitKeys = new ArrayList < byte [ ] > ( ) ; for ( int i = 1 ; i < starts . length ; i ++ ) { splitKeys . add ( starts [ i ] ) ; } return splitKeys . toArray ( new byte [ ] [ ] { } ) ; }
Get the non - null non - null non - zero - length row keys that divide the regions
38,502
private Map < BoxedByteArray , byte [ ] > processBatchCallresults ( List < Map . Entry < BoxedByteArray , T > > entries , Object [ ] objects ) { Map < BoxedByteArray , byte [ ] > successes = new HashMap < > ( ) ; for ( int i = 0 ; i < objects . length ; ++ i ) { if ( objects [ i ] != null && objects [ i ] instanceof Result ) { Result result = ( Result ) objects [ i ] ; byte [ ] value = result . getValue ( configuration . cf , HBaseDbHarness . QUALIFIER ) ; successes . put ( entries . get ( i ) . getKey ( ) , value ) ; } } return successes ; }
Converts the datacube request objects and an array of objects returned from an hbase batch call into the map we use to track success .
38,503
private Future < ? > runBatch ( Batch < T > batch ) throws InterruptedException { while ( true ) { try { runBatchMeter . mark ( ) ; if ( perRollupMetrics ) { batch . getMap ( ) . forEach ( ( addr , op ) -> { if ( addr . getSourceRollup ( ) . isPresent ( ) ) { updateRollupHistogram ( rollupWriteSize , addr . getSourceRollup ( ) . get ( ) , "rollupWriteSize" , op ) ; } } ) ; } return db . runBatchAsync ( batch , flushErrorHandler ) ; } catch ( FullQueueException e ) { asyncQueueBackoffMeter . mark ( ) ; log . debug ( "Async queue is full, retrying soon" ) ; Thread . sleep ( 100 ) ; } } }
Hand off a batch to the DbHarness layer retrying on FullQueueException .
38,504
public Future < ? > runBatchAsync ( Batch < T > batch , AfterExecute < T > afterExecute ) throws FullQueueException { try { synchronized ( batchesInFlight ) { batchesInFlight . add ( batch ) ; } return flushExecutor . submit ( new FlushWorkerRunnable ( batch , afterExecute ) ) ; } catch ( RejectedExecutionException ree ) { throw new FullQueueException ( ) ; } }
Hands off the given batch to the flush executor to be sent to the database soon . Doesn t throw IOException since batches are just asynchronously submitted for execution but will throw AsyncException if some previous batch had a RuntimeException .
38,505
public Batch < T > getWrites ( WriteBuilder writeBuilder , T op ) { Map < Address , T > outputMap = Maps . newHashMap ( ) ; for ( Rollup rollup : rollups ) { List < Set < byte [ ] > > coordSets = new ArrayList < Set < byte [ ] > > ( rollup . getComponents ( ) . size ( ) ) ; boolean dimensionHadNoBucket = false ; for ( DimensionAndBucketType dimAndBucketType : rollup . getComponents ( ) ) { Dimension < ? > dimension = dimAndBucketType . dimension ; BucketType bucketType = dimAndBucketType . bucketType ; SetMultimap < BucketType , byte [ ] > bucketsForDimension = writeBuilder . getBuckets ( ) . get ( dimension ) ; if ( bucketsForDimension == null || bucketsForDimension . isEmpty ( ) ) { dimensionHadNoBucket = true ; break ; } Set < byte [ ] > coords = bucketsForDimension . get ( bucketType ) ; if ( coords == null || coords . isEmpty ( ) ) { dimensionHadNoBucket = true ; break ; } coordSets . add ( coords ) ; } if ( dimensionHadNoBucket ) { log . debug ( "Skipping rollup due to dimension with no buckets" ) ; continue ; } Set < List < byte [ ] > > crossProduct = Sets . cartesianProduct ( coordSets ) ; for ( List < byte [ ] > crossProductTuple : crossProduct ) { Address outputAddress = new Address ( this , rollup ) ; for ( Dimension < ? > dimension : dims ) { outputAddress . at ( dimension , BucketTypeAndBucket . WILDCARD ) ; } for ( int i = 0 ; i < crossProductTuple . size ( ) ; i ++ ) { byte [ ] coord = crossProductTuple . get ( i ) ; Dimension < ? > dim = rollup . getComponents ( ) . get ( i ) . dimension ; BucketType bucketType = rollup . getComponents ( ) . get ( i ) . bucketType ; outputAddress . at ( dim , new BucketTypeAndBucket ( bucketType , coord ) ) ; } boolean shouldWrite = true ; if ( shouldWrite ) { outputMap . put ( outputAddress , op ) ; } } } return new Batch < T > ( outputMap ) ; }
Get a batch of writes that when applied to the database will make the change given by op .
38,506
public static List < Scan > scansThisCubeOnly ( byte [ ] keyPrefix , byte [ ] [ ] splitKeys ) throws IOException { Scan copyScan = new Scan ( ) ; copyScan . setCaching ( 5000 ) ; copyScan . setCacheBlocks ( false ) ; byte [ ] keyAfterCube = ArrayUtils . addAll ( keyPrefix , fiftyBytesFF ) ; List < Scan > scans = new ArrayList < Scan > ( ) ; Scan scanUnderConstruction = new Scan ( copyScan ) ; for ( byte [ ] splitKey : splitKeys ) { scanUnderConstruction . setStopRow ( splitKey ) ; Scan truncated = truncateScan ( scanUnderConstruction , keyPrefix , keyAfterCube ) ; if ( truncated != null ) { scans . add ( truncated ) ; } scanUnderConstruction = new Scan ( copyScan ) ; scanUnderConstruction . setStartRow ( splitKey ) ; } Scan truncated = truncateScan ( scanUnderConstruction , keyPrefix , keyAfterCube ) ; if ( truncated != null ) { scans . add ( truncated ) ; } return scans ; }
Get a collection of Scans one per region that cover the range of the table having the given key prefix . Thes will be used as the map task input splits .
38,507
private static final Scan truncateScan ( Scan scan , byte [ ] rangeStart , byte [ ] rangeEnd ) { byte [ ] scanStart = scan . getStartRow ( ) ; byte [ ] scanEnd = scan . getStopRow ( ) ; if ( scanEnd . length > 0 && bytesCompare ( scanEnd , rangeStart ) <= 0 ) { return null ; } else if ( scanStart . length > 0 && bytesCompare ( scanStart , rangeEnd ) >= 0 ) { return null ; } else { Scan truncated ; try { truncated = new Scan ( scan ) ; } catch ( IOException e ) { throw new RuntimeException ( ) ; } if ( scanStart . length == 0 || bytesCompare ( rangeStart , scanStart ) > 0 ) { truncated . setStartRow ( rangeStart ) ; } if ( scanEnd . length == 0 || bytesCompare ( rangeEnd , scanEnd ) < 0 ) { truncated . setStopRow ( rangeEnd ) ; } return truncated ; } }
Given a scan and a key range return a new Scan whose range is truncated to only include keys in that range . Returns null if the Scan does not overlap the given range .
38,508
@ SuppressWarnings ( "unchecked" ) public Future < ? > runBatchAsync ( Batch < T > batch , AfterExecute < T > afterExecute ) { for ( Map . Entry < Address , T > entry : batch . getMap ( ) . entrySet ( ) ) { Address address = entry . getKey ( ) ; T opFromBatch = entry . getValue ( ) ; BoxedByteArray mapKey ; try { mapKey = new BoxedByteArray ( address . toWriteKey ( idService ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } if ( commitType == CommitType . READ_COMBINE_CAS ) { int casRetriesRemaining = casRetries ; do { Optional < byte [ ] > oldBytes ; try { oldBytes = getRaw ( address ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } T newOp ; if ( oldBytes . isPresent ( ) ) { T oldOp = deserializer . fromBytes ( oldBytes . get ( ) ) ; newOp = ( T ) opFromBatch . add ( oldOp ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Combined " + oldOp + " and " + opFromBatch + " into " + newOp ) ; } } else { newOp = opFromBatch ; } if ( oldBytes . isPresent ( ) ) { if ( map . replace ( mapKey , oldBytes . get ( ) , newOp . serialize ( ) ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Successful CAS overwrite at key " + Hex . encodeHexString ( mapKey . bytes ) + " with " + Hex . encodeHexString ( newOp . serialize ( ) ) ) ; } break ; } } else { if ( map . putIfAbsent ( mapKey , newOp . serialize ( ) ) == null ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Successful CAS insert without existing key for key " + Hex . encodeHexString ( mapKey . bytes ) + " with " + Hex . encodeHexString ( newOp . serialize ( ) ) ) ; } break ; } } } while ( casRetriesRemaining -- > 0 ) ; if ( casRetriesRemaining == - 1 ) { RuntimeException e = new RuntimeException ( "CAS retries exhausted" ) ; afterExecute . afterExecute ( e ) ; throw e ; } } else if ( commitType == CommitType . OVERWRITE ) { map . put ( mapKey , opFromBatch . serialize ( ) ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Write of key " + Hex . encodeHexString ( mapKey . bytes ) ) ; } } else { throw new AssertionError ( "Unsupported commit type: " + commitType ) ; } } batch . reset ( ) ; afterExecute . afterExecute ( null ) ; return nullFuture ; }
Actually synchronous and not asyncronous which is allowed .
38,509
public ListMultimap < Iterator < T > , T > next ( ) { ListMultimap < Iterator < T > , T > results = ArrayListMultimap . create ( ) ; while ( true ) { HeapEntry heapEntry = heap . poll ( ) ; if ( heapEntry == null ) { break ; } results . put ( iterators . get ( heapEntry . fromIterator ) , heapEntry . item ) ; Iterator < T > sourceIterator = iterators . get ( heapEntry . fromIterator ) ; if ( hasNextWrapper ( sourceIterator ) ) { HeapEntry newEntry = new HeapEntry ( nextWrapper ( sourceIterator ) , heapEntry . fromIterator ) ; assert heap . comparator ( ) . compare ( newEntry , heapEntry ) >= 0 ; heap . add ( newEntry ) ; } HeapEntry peekHeap = heap . peek ( ) ; if ( peekHeap == null || heap . comparator ( ) . compare ( heapEntry , heap . peek ( ) ) != 0 ) { break ; } } if ( results . size ( ) == 0 ) { throw new NoSuchElementException ( ) ; } return results ; }
Get the next group of results that compare equal .
38,510
private T nextWrapper ( Iterator < T > it ) { try { if ( trace != null ) { trace . add ( new TraceEntry ( System . nanoTime ( ) , System . currentTimeMillis ( ) , NextOrHasNext . NEXT , debugLabels . get ( it ) ) ) ; } return it . next ( ) ; } catch ( RuntimeException e ) { logTrace ( ) ; throw e ; } }
Get and return the next value from an iterator and add a tracing record if enabled . Logs tracing info if a RuntimeException occurs .
38,511
private ObjectName createMetrics3Name ( String domain , String name ) throws MalformedObjectNameException { try { return new ObjectName ( domain , "name" , name ) ; } catch ( MalformedObjectNameException e ) { return new ObjectName ( domain , "name" , ObjectName . quote ( name ) ) ; } }
Default behavior of Metrics 3 library for fallback
38,512
@ SuppressWarnings ( "unchecked" ) private static Deserializer < ? > getDeserializer ( Configuration conf ) { String deserializerClassName = conf . get ( HBaseBackfillMerger . CONFKEY_DESERIALIZER ) ; if ( deserializerClassName == null ) { throw new RuntimeException ( "Configuration didn't set " + deserializerClassName ) ; } try { Class < ? > deserializerClass = Class . forName ( deserializerClassName ) ; if ( ! Deserializer . class . isAssignableFrom ( deserializerClass ) ) { final String errMsg = "The provided deserializer class " + conf . get ( HBaseBackfillMerger . CONFKEY_DESERIALIZER ) + "doesn't implement " + Deserializer . class . getName ( ) ; log . error ( errMsg ) ; } return ( ( Class < ? extends Deserializer < ? > > ) deserializerClass ) . newInstance ( ) ; } catch ( Exception e ) { log . error ( "Couldn't instantiate deserializer" , e ) ; throw new RuntimeException ( e ) ; } }
Get the deserializer class name from the job config instantiate it and return the instance .
38,513
public static byte [ ] intToBytesWithLen ( int x , int len ) { if ( len <= 4 ) { return trailingBytes ( intToBytes ( x ) , len ) ; } else { ByteBuffer bb = ByteBuffer . allocate ( len ) ; bb . position ( len - 4 ) ; bb . putInt ( x ) ; assert bb . remaining ( ) == 0 ; return bb . array ( ) ; } }
Write a big - endian integer into the least significant bytes of a byte array .
38,514
public static byte hashByteArray ( byte [ ] array , int startInclusive , int endExclusive ) { if ( array == null ) { return 0 ; } int range = endExclusive - startInclusive ; if ( range < 0 ) { throw new IllegalArgumentException ( startInclusive + " > " + endExclusive ) ; } int result = 1 ; for ( int i = startInclusive ; i < endExclusive ; i ++ ) { result = 31 * result + array [ i ] ; } return ( byte ) result ; }
A utility to allow hashing of a portion of an array without having to copy it .
38,515
public void close ( ) { if ( nativeProxy != 0 ) { new Task < Void > ( ) { public Void call ( ) { Native . unadvise ( nativeProxy ) ; return null ; } } . execute ( ) ; nativeProxy = 0 ; } }
Terminates the event subscription .
38,516
private static < T > EventInterfaceDescriptor < T > getDescriptor ( Class < T > t ) { EventInterfaceDescriptor < T > r = descriptors . get ( t ) ; if ( r == null ) { r = new EventInterfaceDescriptor < T > ( t ) ; descriptors . put ( t , r ) ; } return r ; }
Gets the descriptor for the given type .
38,517
private void collectGarbage ( ) { NativePointerPhantomReference toCollect ; while ( ( toCollect = ( NativePointerPhantomReference ) collectableObjects . poll ( ) ) != null ) { liveComObjects . remove ( toCollect ) ; toCollect . clear ( ) ; toCollect . releaseNative ( ) ; } }
Cleans up any left over references
38,518
private static String getTypeString ( IType t ) { if ( t == null ) return "null" ; IPtrType pt = t . queryInterface ( IPtrType . class ) ; if ( pt != null ) return getTypeString ( pt . getPointedAtType ( ) ) + "*" ; IPrimitiveType prim = t . queryInterface ( IPrimitiveType . class ) ; if ( prim != null ) return prim . getName ( ) ; ITypeDecl decl = t . queryInterface ( ITypeDecl . class ) ; if ( decl != null ) return decl . getName ( ) ; ISafeArrayType sa = t . queryInterface ( ISafeArrayType . class ) ; if ( sa != null ) { return "SAFEARRAY(" + getTypeString ( sa . getComponentType ( ) ) + ")" ; } return "N/A" ; }
Returns a human - readable identifier of the type but it s not necessarily a correct Java id .
38,519
public void commit ( ) throws IOException { if ( ! marked ) throw new IllegalStateException ( ) ; marked = false ; super . append ( buffer ) ; buffer . setLength ( 0 ) ; }
Write the pending data .
38,520
public void generate ( IWTypeLib lib ) throws BindingException , IOException { LibBinder tli = getTypeLibInfo ( lib ) ; if ( referenceResolver . suppress ( lib ) ) return ; if ( generatedTypeLibs . add ( tli ) ) tli . generate ( ) ; }
Call this method repeatedly to generate classes from each type library .
38,521
public void finish ( ) throws IOException { for ( Package pkg : packages . values ( ) ) { LibBinder lib1 = pkg . typeLibs . iterator ( ) . next ( ) ; if ( referenceResolver . suppress ( lib1 . lib ) ) continue ; IndentingWriter o = pkg . createWriter ( lib1 , "ClassFactory.java" ) ; lib1 . generateHeader ( o ) ; o . printJavadoc ( "Defines methods to create COM objects" ) ; o . println ( "public abstract class ClassFactory {" ) ; o . in ( ) ; o . println ( "private ClassFactory() {} // instanciation is not allowed" ) ; o . println ( ) ; for ( LibBinder lib : pkg . typeLibs ) { int len = lib . lib . count ( ) ; for ( int i = 0 ; i < len ; i ++ ) { ICoClassDecl t = lib . lib . getType ( i ) . queryInterface ( ICoClassDecl . class ) ; if ( t == null ) continue ; if ( ! t . isCreatable ( ) ) continue ; declareFactoryMethod ( o , t ) ; t . dispose ( ) ; } } o . out ( ) ; o . println ( "}" ) ; o . close ( ) ; } }
Finally call this method to wrap things up .
38,522
ITypeDecl getDefaultInterface ( ICoClassDecl t ) { final int count = t . countImplementedInterfaces ( ) ; for ( int i = 0 ; i < count ; i ++ ) { IImplementedInterfaceDecl impl = t . getImplementedInterface ( i ) ; if ( impl . isSource ( ) ) continue ; if ( impl . isDefault ( ) ) { IInterfaceDecl c = getCustom ( impl ) ; if ( c != null ) return c ; IDispInterfaceDecl d = impl . getType ( ) . queryInterface ( IDispInterfaceDecl . class ) ; if ( d != null ) { return d ; } } } Set < IInterfaceDecl > types = new HashSet < IInterfaceDecl > ( ) ; for ( int i = 0 ; i < count ; i ++ ) { IImplementedInterfaceDecl impl = t . getImplementedInterface ( i ) ; if ( impl . isSource ( ) ) continue ; IInterfaceDecl c = getCustom ( impl ) ; if ( c != null ) types . add ( c ) ; } if ( types . isEmpty ( ) ) return null ; Set < IInterfaceDecl > bases = new HashSet < IInterfaceDecl > ( ) ; for ( IInterfaceDecl ii : types ) { for ( int i = 0 ; i < ii . countBaseInterfaces ( ) ; i ++ ) bases . add ( ii . getBaseInterface ( i ) . queryInterface ( IInterfaceDecl . class ) ) ; } types . removeAll ( bases ) ; return types . iterator ( ) . next ( ) ; }
Returns the primary interface for the given co - class .
38,523
@ SuppressWarnings ( "unchecked" ) protected void messageParameters ( Object [ ] args ) { for ( int i = 0 ; i < args . length ; i ++ ) { if ( args [ i ] instanceof Holder && params [ i ] . getNoByRef ( ) != null ) { Holder h = ( Holder ) args [ i ] ; h . value = params [ i ] . getNoByRef ( ) . toNative ( h . value ) ; } else { args [ i ] = params [ i ] . toNative ( args [ i ] ) ; } } }
Converts the parameters to be more native friendly .
38,524
static NativeType getDefaultConversion ( Type t ) { if ( t instanceof Class ) { Class < ? > c = ( Class < ? > ) t ; NativeType r = defaultConversions . get ( c ) ; if ( r != null ) return r ; if ( Com4jObject . class . isAssignableFrom ( c ) ) return NativeType . ComObject ; if ( Enum . class . isAssignableFrom ( c ) ) return NativeType . Int32 ; if ( Buffer . class . isAssignableFrom ( c ) ) return NativeType . PVOID ; if ( Calendar . class . isAssignableFrom ( c ) ) return NativeType . Date ; if ( BigDecimal . class . isAssignableFrom ( c ) ) return NativeType . Currency ; if ( c . isArray ( ) ) return NativeType . SafeArray ; } if ( t instanceof ParameterizedType ) { ParameterizedType p = ( ParameterizedType ) t ; if ( p . getRawType ( ) == Holder . class ) { Type v = p . getActualTypeArguments ( ) [ 0 ] ; Class < ? > c = ( v instanceof Class ) ? ( Class < ? > ) v : null ; if ( c != null ) { if ( Com4jObject . class . isAssignableFrom ( c ) ) return NativeType . ComObject_ByRef ; if ( String . class == c ) return NativeType . BSTR_ByRef ; if ( Integer . class == c || Enum . class . isAssignableFrom ( c ) ) return NativeType . Int32_ByRef ; if ( Boolean . class == c ) return NativeType . VariantBool_ByRef ; if ( Buffer . class . isAssignableFrom ( c ) ) return NativeType . PVOID_ByRef ; if ( Double . class . isAssignableFrom ( c ) ) return NativeType . Double_ByRef ; if ( c . isArray ( ) ) return NativeType . SafeArray_ByRef ; } if ( v instanceof GenericArrayType ) { return NativeType . SafeArray_ByRef ; } } if ( p . getRawType ( ) == Iterator . class ) { return NativeType . ComObject ; } } throw new IllegalAnnotationException ( "no default conversion available for " + t ) ; }
Computes the default conversion for the given type .
38,525
public static < T extends Enum < T > > EnumDictionary < T > get ( Class < T > clazz ) { EnumDictionary < T > dic = registry . get ( clazz ) ; if ( dic == null ) { boolean sparse = ComEnum . class . isAssignableFrom ( clazz ) ; if ( sparse ) dic = new Sparse < T > ( clazz ) ; else dic = new Continuous < T > ( clazz ) ; registry . put ( clazz , dic ) ; } return dic ; }
Looks up a dictionary from an enum class .
38,526
static < T extends Enum < T > > T get ( Class < T > clazz , int v ) { return get ( clazz ) . constant ( v ) ; }
Convenience method to be invoked by JNI .
38,527
public static < T extends Com4jObject > T wrap ( final Class < T > primaryInterface , final long ptr ) throws ComException { return new Task < T > ( ) { public T call ( ) { return Wrapper . create ( primaryInterface , ptr ) ; } } . execute ( ) ; }
Wraps an externally obtained interface pointer into a COM wrapper object .
38,528
public static < T extends Com4jObject > T getActiveObject ( Class < T > primaryInterface , GUID clsid ) { return new GetActiveObjectTask < T > ( clsid , primaryInterface ) . execute ( ) ; }
Gets an already running object from the running object table .
38,529
public static < T extends Com4jObject > T getActiveObject ( Class < T > primaryInterface , String clsid ) { return getActiveObject ( primaryInterface , new GUID ( clsid ) ) ; }
Gets an already object from the running object table .
38,530
public static < T extends Com4jObject > T getObject ( Class < T > primaryInterface , String fileName , String progId ) { return new GetObjectTask < T > ( fileName , progId , primaryInterface ) . execute ( ) ; }
Returns a reference to a COM object primarily by loading a file .
38,531
public static GUID getIID ( Class < ? > _interface ) { IID iid = _interface . getAnnotation ( IID . class ) ; if ( iid == null ) throw new IllegalArgumentException ( _interface . getName ( ) + " doesn't have @IID annotation" ) ; return new GUID ( iid . value ( ) ) ; }
Gets the interface GUID associated with the given interface .
38,532
public Type getType ( ) { int varType = image . getInt ( 0 ) & 0xFFFF ; return EnumDictionary . get ( Type . class ) . constant ( varType ) ; }
Gets the type of the variant .
38,533
public String getParseableString ( ) { switch ( this . getType ( ) ) { case VT_I1 : case VT_I2 : case VT_I4 : case VT_INT : return Integer . toString ( this . intValue ( ) ) ; case VT_I8 : return Long . toString ( this . longValue ( ) ) ; case VT_R4 : return Float . toString ( this . floatValue ( ) ) ; case VT_R8 : return Double . toString ( this . doubleValue ( ) ) ; case VT_BSTR : return this . stringValue ( ) ; case VT_NULL : return "null" ; case VT_BOOL : return Boolean . toString ( this . booleanValue ( ) ) ; case VT_ERROR : return Integer . toHexString ( this . getError ( ) ) ; } System . err . println ( "Don't know how to print " + this . getType ( ) . name ( ) + " as an Java literal" ) ; return null ; }
Generates an String representation of this Variant that can be parsed .
38,534
public < T extends Com4jObject > T object ( final Class < T > type ) { ComThread t = thread != null ? thread : ComThread . get ( ) ; return t . execute ( new Task < T > ( ) { public T call ( ) { Com4jObject wrapper = convertTo ( Com4jObject . class ) ; if ( null == wrapper ) { return null ; } T ret = wrapper . queryInterface ( type ) ; wrapper . dispose ( ) ; return ret ; } } ) ; }
Reads this VARIANT as a COM interface pointer .
38,535
static Date toDate ( double d ) { GregorianCalendar ret = new GregorianCalendar ( 1899 , 11 , 30 ) ; int days = ( int ) d ; d -= days ; ret . add ( Calendar . DATE , days ) ; d *= 24 ; int hours = ( int ) d ; ret . add ( Calendar . HOUR , hours ) ; d -= hours ; d *= 60 ; int min = ( int ) d ; ret . add ( Calendar . MINUTE , min ) ; d -= min ; d *= 60 ; int secs = ( int ) d ; ret . add ( Calendar . SECOND , secs ) ; return ret . getTime ( ) ; }
Called from the native code to assist VT_DATE - > Date conversion .
38,536
private static String cutEOL ( String s ) { if ( s == null ) return "(Unknown error)" ; if ( s . endsWith ( "\r\n" ) ) return s . substring ( 0 , s . length ( ) - 2 ) ; else return s ; }
Cuts off the end of line characters .
38,537
private void fetch ( ) { next . clear ( ) ; next . thread = e . getComThread ( ) ; int r = e . next ( 1 , next ) ; if ( r == 0 ) { next = null ; e . dispose ( ) ; } }
Fetches the next element .
38,538
private int getReturnParam ( ) { for ( int i = 0 ; i < params . length ; i ++ ) { if ( params [ i ] . isRetval ( ) ) { return i ; } } int outIdx = - 1 ; for ( int i = 0 ; i < params . length ; i ++ ) { if ( params [ i ] . isOut ( ) && ! params [ i ] . isIn ( ) ) { if ( outIdx == - 1 ) { outIdx = i ; } else { return - 1 ; } } } return outIdx ; }
Returns the index of the return value parameter or - 1 if none .
38,539
private void declare ( IndentingWriter o , IParam p ) throws BindingException { TypeBinding vb = TypeBinding . bind ( g , p . getType ( ) , p . getName ( ) ) ; String javaType = vb . javaType ; if ( method . isVarArg ( ) && p == params [ params . length - 1 ] ) { if ( javaType . endsWith ( "[]" ) ) javaType = javaType . substring ( 0 , javaType . length ( ) - 2 ) + "..." ; } if ( p . isOptional ( ) ) { o . print ( "@Optional " ) ; } Variant defValue = p . getDefaultValue ( ) ; if ( defValue != null ) { try { o . print ( "@DefaultValue(\"" + defValue . stringValue ( ) + "\") " ) ; } catch ( ComException e ) { } } if ( p . isLCID ( ) ) { o . print ( "@LCID " ) ; } if ( ! vb . isDefault && needsMarshalAs ( ) ) { o . printf ( "@MarshalAs(NativeType.%1s) " , vb . nativeType . name ( ) ) ; } o . print ( javaType ) ; o . print ( ' ' ) ; declareParamName ( o , p ) ; }
Declares a parameter .
38,540
protected final void declareReturnType ( IndentingWriter o , List < IType > intermediates , boolean usesDefaltValues ) throws BindingException { generateAccessModifier ( o ) ; if ( returnType == null && intermediates == null ) { o . print ( "void " ) ; } else { TypeBinding retBinding = TypeBinding . bind ( g , returnType , null ) ; if ( ( ! retBinding . isDefault && needsMarshalAs ( ) ) || ( retParam != - 1 && ( params [ retParam ] . isIn ( ) || retParam != params . length - 1 ) ) || intermediates != null || usesDefaltValues ) { o . print ( "@ReturnValue(" ) ; o . beginCommaMode ( ) ; if ( ! retBinding . isDefault && needsMarshalAs ( ) ) { o . comma ( ) ; o . print ( "type=NativeType." + retBinding . nativeType . name ( ) ) ; } if ( retParam != - 1 && params [ retParam ] . isIn ( ) ) { o . comma ( ) ; o . print ( "inout=true" ) ; } if ( retParam != - 1 && retParam != params . length - 1 || usesDefaltValues ) { o . comma ( ) ; o . print ( "index=" + retParam ) ; } if ( intermediates != null ) { o . comma ( ) ; o . print ( "defaultPropertyThrough={" ) ; o . beginCommaMode ( ) ; for ( IType im : intermediates ) { TypeBinding vb = TypeBinding . bind ( g , im , null ) ; o . comma ( ) ; o . print ( vb . javaType ) ; o . print ( ".class" ) ; } o . endCommaMode ( ) ; o . print ( "}" ) ; } o . endCommaMode ( ) ; o . println ( ")" ) ; } o . print ( retBinding . javaType ) ; o . print ( ' ' ) ; } }
Declares the return type .
38,541
protected final IType getDispInterfaceReturnType ( ) { IType r = method . getReturnType ( ) ; IPrimitiveType pt = r . queryInterface ( IPrimitiveType . class ) ; if ( pt != null && pt . getVarType ( ) == VarType . VT_HRESULT ) { return null ; } return r ; }
Computes the return type for disp - only interface .
38,542
private void checkEnv ( ) throws MojoExecutionException { String osName = System . getProperty ( "os.name" ) ; if ( ! osName . startsWith ( "Windows" ) ) { getLog ( ) . warn ( "Wrong OS: " + osName ) ; throw new MojoExecutionException ( "Com4j can only be run on a Windows operating system, and you're running: " + osName ) ; } if ( ! outputDirectory . exists ( ) && ! outputDirectory . mkdirs ( ) ) { getLog ( ) . warn ( "outputDirectory couldn't be created" ) ; throw new MojoExecutionException ( "The output directory " + outputDirectory + " doesn't exist and couldn't be created." ) ; } }
Check the runtime environment .
38,543
private void validate ( ) throws MojoExecutionException { if ( ( file == null && libId == null ) || ( file != null && libId != null ) ) { getLog ( ) . warn ( "You specified <file> and <libId>. The <libId> always wins." ) ; } if ( file != null && ! file . exists ( ) ) { getLog ( ) . warn ( "Can't find file: " + file ) ; throw new MojoExecutionException ( "The native COM target file couldn't be found: " + file ) ; } }
Check the configuration from the pom . xml
38,544
static Version parseValidSemVer ( String version ) { VersionParser parser = new VersionParser ( version ) ; return parser . parseValidSemVer ( ) ; }
Parses the whole version including pre - release version and build metadata .
38,545
static NormalVersion parseVersionCore ( String versionCore ) { VersionParser parser = new VersionParser ( versionCore ) ; return parser . parseVersionCore ( ) ; }
Parses the version core .
38,546
static MetadataVersion parsePreRelease ( String preRelease ) { VersionParser parser = new VersionParser ( preRelease ) ; return parser . parsePreRelease ( ) ; }
Parses the pre - release version .
38,547
static MetadataVersion parseBuild ( String build ) { VersionParser parser = new VersionParser ( build ) ; return parser . parseBuild ( ) ; }
Parses the build metadata .
38,548
private Character consumeNextCharacter ( CharType ... expected ) { try { return chars . consume ( expected ) ; } catch ( UnexpectedElementException e ) { throw new UnexpectedCharacterException ( e ) ; } }
Tries to consume the next character in the stream .
38,549
private void ensureValidLookahead ( CharType ... expected ) { if ( ! chars . positiveLookahead ( expected ) ) { throw new UnexpectedCharacterException ( chars . lookahead ( 1 ) , chars . currentOffset ( ) , expected ) ; } }
Checks if the next character in the stream is valid .
38,550
public Expression parse ( String input ) { tokens = lexer . tokenize ( input ) ; Expression expr = parseSemVerExpression ( ) ; consumeNextToken ( EOI ) ; return expr ; }
Parses the SemVer Expressions .
38,551
private boolean isVersionFollowedBy ( ElementType < Token > type ) { EnumSet < Token . Type > expected = EnumSet . of ( NUMERIC , DOT ) ; Iterator < Token > it = tokens . iterator ( ) ; Token lookahead = null ; while ( it . hasNext ( ) ) { lookahead = it . next ( ) ; if ( ! expected . contains ( lookahead . type ) ) { break ; } } return type . isMatchedBy ( lookahead ) ; }
Determines if the version terminals are followed by the specified token type .
38,552
private Token consumeNextToken ( Token . Type ... expected ) { try { return tokens . consume ( expected ) ; } catch ( UnexpectedElementException e ) { throw new UnexpectedTokenException ( e ) ; } }
Tries to consume the next token in the stream .
38,553
Stream < Token > tokenize ( String input ) { List < Token > tokens = new ArrayList < Token > ( ) ; int tokenPos = 0 ; while ( ! input . isEmpty ( ) ) { boolean matched = false ; for ( Token . Type tokenType : Token . Type . values ( ) ) { Matcher matcher = tokenType . pattern . matcher ( input ) ; if ( matcher . find ( ) ) { matched = true ; input = matcher . replaceFirst ( "" ) ; if ( tokenType != Token . Type . WHITESPACE ) { tokens . add ( new Token ( tokenType , matcher . group ( ) , tokenPos ) ) ; } tokenPos += matcher . end ( ) ; break ; } } if ( ! matched ) { throw new LexerException ( input ) ; } } tokens . add ( new Token ( Token . Type . EOI , null , tokenPos ) ) ; return new Stream < Token > ( tokens . toArray ( new Token [ tokens . size ( ) ] ) ) ; }
Tokenizes the specified input string .
38,554
public Version incrementMajorVersion ( String preRelease ) { return new Version ( normal . incrementMajor ( ) , VersionParser . parsePreRelease ( preRelease ) ) ; }
Increments the major version and appends the pre - release version .
38,555
public Version incrementMinorVersion ( String preRelease ) { return new Version ( normal . incrementMinor ( ) , VersionParser . parsePreRelease ( preRelease ) ) ; }
Increments the minor version and appends the pre - release version .
38,556
public Version incrementPatchVersion ( String preRelease ) { return new Version ( normal . incrementPatch ( ) , VersionParser . parsePreRelease ( preRelease ) ) ; }
Increments the patch version and appends the pre - release version .
38,557
public Version setBuildMetadata ( String build ) { return new Version ( normal , preRelease , VersionParser . parseBuild ( build ) ) ; }
Sets the build metadata .
38,558
public int compareTo ( Version other ) { int result = normal . compareTo ( other . normal ) ; if ( result == 0 ) { result = preRelease . compareTo ( other . preRelease ) ; } return result ; }
Compares this version to the other version .
38,559
MetadataVersion increment ( ) { String [ ] ids = idents ; String lastId = ids [ ids . length - 1 ] ; if ( isInt ( lastId ) ) { int intId = Integer . parseInt ( lastId ) ; ids [ ids . length - 1 ] = String . valueOf ( ++ intId ) ; } else { ids = Arrays . copyOf ( ids , ids . length + 1 ) ; ids [ ids . length - 1 ] = String . valueOf ( 1 ) ; } return new MetadataVersion ( ids ) ; }
Increments the metadata version .
38,560
private int compareIdentifierArrays ( String [ ] otherIdents ) { int result = 0 ; int length = getLeastCommonArrayLength ( idents , otherIdents ) ; for ( int i = 0 ; i < length ; i ++ ) { result = compareIdentifiers ( idents [ i ] , otherIdents [ i ] ) ; if ( result != 0 ) { break ; } } return result ; }
Compares two arrays of identifiers .
38,561
private int getLeastCommonArrayLength ( String [ ] arr1 , String [ ] arr2 ) { return arr1 . length <= arr2 . length ? arr1 . length : arr2 . length ; }
Returns the size of the smallest array .
38,562
private int compareIdentifiers ( String ident1 , String ident2 ) { if ( isInt ( ident1 ) && isInt ( ident2 ) ) { return Integer . parseInt ( ident1 ) - Integer . parseInt ( ident2 ) ; } else { return ident1 . compareTo ( ident2 ) ; } }
Compares two identifiers .
38,563
private boolean isInt ( String str ) { try { Integer . parseInt ( str ) ; } catch ( NumberFormatException e ) { return false ; } return true ; }
Checks if the specified string is an integer .
38,564
public < T extends ElementType < E > > boolean positiveLookahead ( T ... expected ) { for ( ElementType < E > type : expected ) { if ( type . isMatchedBy ( lookahead ( 1 ) ) ) { return true ; } } return false ; }
Checks if the next element in this stream is of the expected types .
38,565
public < T extends ElementType < E > > boolean positiveLookaheadUntil ( int until , T ... expected ) { for ( int i = 1 ; i <= until ; i ++ ) { for ( ElementType < E > type : expected ) { if ( type . isMatchedBy ( lookahead ( i ) ) ) { return true ; } } } return false ; }
Checks if there is an element in this stream of the expected types until the specified position .
38,566
public Iterator < E > iterator ( ) { return new Iterator < E > ( ) { private int index = offset ; public boolean hasNext ( ) { return index < elements . length ; } public E next ( ) { if ( index >= elements . length ) { throw new NoSuchElementException ( ) ; } return elements [ index ++ ] ; } public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; }
Returns an iterator over elements that are left in this stream .
38,567
public void start ( int restartableId ) { stop ( restartableId ) ; requested . add ( restartableId ) ; restartableSubscriptions . put ( restartableId , restartables . get ( restartableId ) . call ( ) ) ; }
Starts the given restartable .
38,568
public void stop ( int restartableId ) { requested . remove ( ( Integer ) restartableId ) ; Subscription subscription = restartableSubscriptions . get ( restartableId ) ; if ( subscription != null ) subscription . unsubscribe ( ) ; }
Unsubscribes a restartable
38,569
public boolean isUnsubscribed ( int restartableId ) { Subscription subscription = restartableSubscriptions . get ( restartableId ) ; return subscription == null || subscription . isUnsubscribed ( ) ; }
Checks if a restartable is unsubscribed .
38,570
public Activity getActivity ( ) { Context context = getContext ( ) ; while ( ! ( context instanceof Activity ) && context instanceof ContextWrapper ) context = ( ( ContextWrapper ) context ) . getBaseContext ( ) ; if ( ! ( context instanceof Activity ) ) throw new IllegalStateException ( "Expected an activity context, got " + context . getClass ( ) . getSimpleName ( ) ) ; return ( Activity ) context ; }
Returns the unwrapped activity of the view or throws an exception .
38,571
public void push ( Fragment fragment ) { Fragment top = peek ( ) ; if ( top != null ) { manager . beginTransaction ( ) . setCustomAnimations ( R . anim . enter_from_right , R . anim . exit_to_left , R . anim . enter_from_left , R . anim . exit_to_right ) . remove ( top ) . add ( containerId , fragment , indexToTag ( manager . getBackStackEntryCount ( ) + 1 ) ) . addToBackStack ( null ) . commit ( ) ; } else { manager . beginTransaction ( ) . add ( containerId , fragment , indexToTag ( 0 ) ) . commit ( ) ; } manager . executePendingTransactions ( ) ; }
Pushes a fragment to the top of the stack .
38,572
public void replace ( Fragment fragment ) { manager . popBackStackImmediate ( null , FragmentManager . POP_BACK_STACK_INCLUSIVE ) ; manager . beginTransaction ( ) . replace ( containerId , fragment , indexToTag ( 0 ) ) . commit ( ) ; manager . executePendingTransactions ( ) ; }
Replaces stack contents with just one fragment .
38,573
@ SuppressWarnings ( "unchecked" ) public < T > T findCallback ( Fragment fragment , Class < T > callbackType ) { Fragment back = getBackFragment ( fragment ) ; if ( back != null && callbackType . isAssignableFrom ( back . getClass ( ) ) ) return ( T ) back ; if ( callbackType . isAssignableFrom ( activity . getClass ( ) ) ) return ( T ) activity ; return null ; }
Returns a back fragment if the fragment is of given class . If such fragment does not exist and activity implements the given class then the activity will be returned .
38,574
public void setCoilStatus ( int index , boolean b ) { if ( index < 0 ) { throw new IllegalArgumentException ( index + " < 0" ) ; } if ( index > coils . size ( ) ) { throw new IndexOutOfBoundsException ( index + " > " + coils . size ( ) ) ; } coils . setBit ( index , b ) ; }
Sets the status of the given coil .
38,575
private boolean responseIsInValid ( ) { if ( response == null ) { return true ; } else if ( ! response . isHeadless ( ) && validityCheck ) { return request . getTransactionID ( ) != response . getTransactionID ( ) ; } else { return false ; } }
Returns true if the response is not valid This can be if the response is null or the transaction ID of the request doesn t match the reponse
38,576
ModbusResponse updateResponseWithHeader ( ModbusResponse response , boolean ignoreFunctionCode ) { response . setHeadless ( isHeadless ( ) ) ; if ( ! isHeadless ( ) ) { response . setTransactionID ( getTransactionID ( ) ) ; response . setProtocolID ( getProtocolID ( ) ) ; } else { response . setHeadless ( ) ; } response . setUnitID ( getUnitID ( ) ) ; if ( ! ignoreFunctionCode ) { response . setFunctionCode ( getFunctionCode ( ) ) ; } return response ; }
Updates the response with the header information to match the request
38,577
public synchronized byte [ ] getBufferBytes ( ) { byte [ ] dest = new byte [ count ] ; System . arraycopy ( buf , 0 , dest , 0 , dest . length ) ; return dest ; }
Returns the underlying data being read .
38,578
public void initPool ( String name ) { running = true ; for ( int i = size ; -- i >= 0 ; ) { PoolThread thread = new PoolThread ( ) ; threadPool . add ( thread ) ; thread . setName ( String . format ( "%s Handler" , name ) ) ; thread . start ( ) ; } }
Initializes the pool populating it with n started threads .
38,579
public void close ( ) { if ( running ) { taskPool . clear ( ) ; running = false ; for ( PoolThread thread : threadPool ) { thread . interrupt ( ) ; } } }
Shutdown the pool of threads
38,580
public synchronized void setReconnecting ( boolean b ) { reconnecting = b ; if ( transaction != null ) { ( ( ModbusTCPTransaction ) transaction ) . setReconnecting ( b ) ; } }
Sets the flag that specifies whether to maintain a constant connection or reconnect for every transaction .
38,581
public void readData ( DataInput din ) throws IOException { int length = getDataLength ( ) ; for ( int i = 0 ; i < length ; i ++ ) { din . readByte ( ) ; } }
Read all of the data that can be read . This is an unsupported function so it may not be possible to know exactly how much data needs to be read .
38,582
public void setEncoding ( String enc ) { if ( ! ModbusUtil . isBlank ( enc ) && ( enc . equalsIgnoreCase ( Modbus . SERIAL_ENCODING_ASCII ) || enc . equalsIgnoreCase ( Modbus . SERIAL_ENCODING_RTU ) ) ) { encoding = enc ; } else { encoding = Modbus . DEFAULT_SERIAL_ENCODING ; } }
Sets the encoding to be used .
38,583
void checkValidity ( ) throws ModbusException { if ( request != null && response != null ) { if ( request . getUnitID ( ) != response . getUnitID ( ) ) { throw new ModbusIOException ( "Unit ID mismatch - Request [%s] Response [%s]" , request . getHexMessage ( ) , response . getHexMessage ( ) ) ; } if ( request . getFunctionCode ( ) != response . getFunctionCode ( ) ) { throw new ModbusIOException ( "Function code mismatch - Request [%s] Response [%s]" , request . getHexMessage ( ) , response . getHexMessage ( ) ) ; } } }
Checks the validity of the transaction by checking if the values of the response correspond to the values of the request .
38,584
public void toByteArray ( byte [ ] toBuf , int offset ) { int toLen = ( toBuf . length > count ) ? count : toBuf . length ; System . arraycopy ( buf , offset , toBuf , offset , toLen - offset ) ; }
Copy the buffered data to the given array .
38,585
public void makeSpace ( int sizeNeeded ) { int needed = count + sizeNeeded - buf . length ; if ( needed > 0 ) { bump ( needed ) ; } }
Ensure that at least the given number of bytes are available in the internal buffer .
38,586
private void readRequestData ( int byteCount , BytesOutputStream out ) throws IOException { byteCount += 2 ; byte inpBuf [ ] = new byte [ byteCount ] ; readBytes ( inpBuf , byteCount ) ; out . write ( inpBuf , 0 , byteCount ) ; }
Read the data for a request of a given fixed size
38,587
private void getRequest ( int function , BytesOutputStream out ) throws IOException { int byteCount ; byte inpBuf [ ] = new byte [ 256 ] ; try { if ( ( function & 0x80 ) == 0 ) { switch ( function ) { case Modbus . READ_EXCEPTION_STATUS : case Modbus . READ_COMM_EVENT_COUNTER : case Modbus . READ_COMM_EVENT_LOG : case Modbus . REPORT_SLAVE_ID : readRequestData ( 0 , out ) ; break ; case Modbus . READ_FIFO_QUEUE : readRequestData ( 2 , out ) ; break ; case Modbus . READ_MEI : readRequestData ( 3 , out ) ; break ; case Modbus . READ_COILS : case Modbus . READ_INPUT_DISCRETES : case Modbus . READ_MULTIPLE_REGISTERS : case Modbus . READ_INPUT_REGISTERS : case Modbus . WRITE_COIL : case Modbus . WRITE_SINGLE_REGISTER : readRequestData ( 4 , out ) ; break ; case Modbus . MASK_WRITE_REGISTER : readRequestData ( 6 , out ) ; break ; case Modbus . READ_FILE_RECORD : case Modbus . WRITE_FILE_RECORD : byteCount = readByte ( ) ; out . write ( byteCount ) ; readRequestData ( byteCount , out ) ; break ; case Modbus . WRITE_MULTIPLE_COILS : case Modbus . WRITE_MULTIPLE_REGISTERS : readBytes ( inpBuf , 4 ) ; out . write ( inpBuf , 0 , 4 ) ; byteCount = readByte ( ) ; out . write ( byteCount ) ; readRequestData ( byteCount , out ) ; break ; case Modbus . READ_WRITE_MULTIPLE : readRequestData ( 8 , out ) ; byteCount = readByte ( ) ; out . write ( byteCount ) ; readRequestData ( byteCount , out ) ; break ; default : throw new IOException ( String . format ( "getResponse unrecognised function code [%s]" , function ) ) ; } } } catch ( IOException e ) { throw new IOException ( "getResponse serial port exception" ) ; } }
getRequest - Read a request after the unit and function code
38,588
protected void writeMessageOut ( ModbusMessage msg ) throws ModbusIOException { try { int len ; synchronized ( byteOutputStream ) { clearInput ( ) ; byteOutputStream . reset ( ) ; msg . setHeadless ( ) ; msg . writeTo ( byteOutputStream ) ; len = byteOutputStream . size ( ) ; int [ ] crc = ModbusUtil . calculateCRC ( byteOutputStream . getBuffer ( ) , 0 , len ) ; byteOutputStream . writeByte ( crc [ 0 ] ) ; byteOutputStream . writeByte ( crc [ 1 ] ) ; writeBytes ( byteOutputStream . getBuffer ( ) , byteOutputStream . size ( ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Sent: {}" , ModbusUtil . toHex ( byteOutputStream . getBuffer ( ) , 0 , byteOutputStream . size ( ) ) ) ; } if ( echo ) { readEcho ( len + 2 ) ; } lastRequest = new byte [ len ] ; System . arraycopy ( byteOutputStream . getBuffer ( ) , 0 , lastRequest , 0 , len ) ; } } catch ( IOException ex ) { throw new ModbusIOException ( "I/O failed to write" ) ; } }
Writes the Modbus message to the comms port
38,589
protected ModbusResponse readResponseIn ( ) throws ModbusIOException { boolean done ; ModbusResponse response ; int dlength ; try { do { synchronized ( byteInputStream ) { int uid = readByte ( ) ; if ( uid != - 1 ) { int fc = readByte ( ) ; byteInputOutputStream . reset ( ) ; byteInputOutputStream . writeByte ( uid ) ; byteInputOutputStream . writeByte ( fc ) ; response = ModbusResponse . createModbusResponse ( fc ) ; response . setHeadless ( ) ; getResponse ( fc , byteInputOutputStream ) ; dlength = byteInputOutputStream . size ( ) - 2 ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Response: {}" , ModbusUtil . toHex ( byteInputOutputStream . getBuffer ( ) , 0 , dlength + 2 ) ) ; } byteInputStream . reset ( inBuffer , dlength ) ; int [ ] crc = ModbusUtil . calculateCRC ( inBuffer , 0 , dlength ) ; if ( ModbusUtil . unsignedByteToInt ( inBuffer [ dlength ] ) != crc [ 0 ] || ModbusUtil . unsignedByteToInt ( inBuffer [ dlength + 1 ] ) != crc [ 1 ] ) { logger . debug ( "CRC should be {}, {}" , crc [ 0 ] , crc [ 1 ] ) ; throw new IOException ( "CRC Error in received frame: " + dlength + " bytes: " + ModbusUtil . toHex ( byteInputStream . getBuffer ( ) , 0 , dlength ) ) ; } } else { throw new IOException ( "Error reading response" ) ; } byteInputStream . reset ( inBuffer , dlength ) ; response . readFrom ( byteInputStream ) ; done = true ; } } while ( ! done ) ; return response ; } catch ( IOException ex ) { throw new ModbusIOException ( "I/O exception - failed to read response for request [%s] - %s" , ModbusUtil . toHex ( lastRequest ) , ex . getMessage ( ) ) ; } }
readResponse - Read the bytes for the response from the slave .
38,590
public static synchronized ModbusSlave createUDPSlave ( InetAddress address , int port ) throws ModbusException { String key = ModbusSlaveType . UDP . getKey ( port ) ; if ( slaves . containsKey ( key ) ) { return slaves . get ( key ) ; } else { ModbusSlave slave = new ModbusSlave ( address , port , false ) ; slaves . put ( key , slave ) ; return slave ; } }
Creates a UDP modbus slave or returns the one already allocated to this port
38,591
public static synchronized ModbusSlave createSerialSlave ( SerialParameters serialParams ) throws ModbusException { ModbusSlave slave = null ; if ( serialParams == null ) { throw new ModbusException ( "Serial parameters are null" ) ; } else if ( ModbusUtil . isBlank ( serialParams . getPortName ( ) ) ) { throw new ModbusException ( "Serial port name is empty" ) ; } if ( slaves . containsKey ( serialParams . getPortName ( ) ) ) { slave = slaves . get ( serialParams . getPortName ( ) ) ; if ( ! serialParams . toString ( ) . equals ( slave . getSerialParams ( ) . toString ( ) ) ) { close ( slave ) ; slave = null ; } } if ( slave == null ) { slave = new ModbusSlave ( serialParams ) ; slaves . put ( serialParams . getPortName ( ) , slave ) ; return slave ; } return slave ; }
Creates a serial modbus slave or returns the one already allocated to this port
38,592
public static void close ( ModbusSlave slave ) { if ( slave != null ) { slave . closeListener ( ) ; slaves . remove ( slave . getType ( ) . getKey ( slave . getPort ( ) ) ) ; } }
Closes this slave and removes it from the running list
38,593
public static ModbusSlave getSlave ( String port ) { return ModbusUtil . isBlank ( port ) ? null : slaves . get ( port ) ; }
Returns the running slave listening on the given serial port
38,594
public static synchronized ModbusSlave getSlave ( AbstractModbusListener listener ) { for ( ModbusSlave slave : slaves . values ( ) ) { if ( slave . getListener ( ) . equals ( listener ) ) { return slave ; } } return null ; }
Returns the running slave that utilises the give listener
38,595
public synchronized byte [ ] getBuffer ( ) { byte [ ] dest = new byte [ buf . length ] ; System . arraycopy ( buf , 0 , dest , 0 , dest . length ) ; return dest ; }
Returns the reference to the output buffer .
38,596
public void setBitCount ( int count ) { bitCount = count ; discretes = new BitVector ( count ) ; setDataLength ( discretes . byteSize ( ) + 1 ) ; }
Sets the number of bits in this response .
38,597
public synchronized String [ ] getFields ( ) { String [ ] dest = new String [ fields . length ] ; System . arraycopy ( fields , 0 , dest , 0 , dest . length ) ; return dest ; }
Returns the array of strings that were read
38,598
public synchronized InputRegister [ ] getRegisters ( ) { InputRegister [ ] dest = new InputRegister [ registers . length ] ; System . arraycopy ( registers , 0 , dest , 0 , dest . length ) ; return dest ; }
Returns a reference to the array of input registers read .
38,599
public void setRegisters ( InputRegister [ ] registers ) { byteCount = registers . length * 2 ; setDataLength ( byteCount + 1 ) ; this . registers = Arrays . copyOf ( registers , registers . length ) ; }
Sets the entire block of registers for this response