idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
16,400 | public static void reset ( ) { SINGLETON = new HystrixMetricsPublisherFactory ( ) ; SINGLETON . commandPublishers . clear ( ) ; SINGLETON . threadPoolPublishers . clear ( ) ; SINGLETON . collapserPublishers . clear ( ) ; } | Resets the SINGLETON object . Clears all state from publishers . If new requests come in instances will be recreated . |
16,401 | public void clearCache ( CacheInvocationContext < CacheRemove > context ) { HystrixCacheKeyGenerator defaultCacheKeyGenerator = HystrixCacheKeyGenerator . getInstance ( ) ; String cacheName = context . getCacheAnnotation ( ) . commandKey ( ) ; HystrixGeneratedCacheKey hystrixGeneratedCacheKey = defaultCacheKeyGenerator . generateCacheKey ( context ) ; String key = hystrixGeneratedCacheKey . getCacheKey ( ) ; HystrixRequestCache . getInstance ( HystrixCommandKey . Factory . asKey ( cacheName ) , HystrixConcurrencyStrategyDefault . getInstance ( ) ) . clear ( key ) ; } | Clears the cache for a given cacheKey context . |
16,402 | public Object executeWithArgs ( ExecutionType executionType , Object [ ] args ) throws CommandActionExecutionException { if ( ExecutionType . ASYNCHRONOUS == executionType ) { Closure closure = AsyncClosureFactory . getInstance ( ) . createClosure ( metaHolder , method , object , args ) ; return executeClj ( closure . getClosureObj ( ) , closure . getClosureMethod ( ) ) ; } return execute ( object , method , args ) ; } | Invokes the method . Also private method also can be invoked . |
16,403 | private Object execute ( Object o , Method m , Object ... args ) throws CommandActionExecutionException { Object result = null ; try { m . setAccessible ( true ) ; if ( isCompileWeaving ( ) && metaHolder . getAjcMethod ( ) != null ) { result = invokeAjcMethod ( metaHolder . getAjcMethod ( ) , o , metaHolder , args ) ; } else { result = m . invoke ( o , args ) ; } } catch ( IllegalAccessException e ) { propagateCause ( e ) ; } catch ( InvocationTargetException e ) { propagateCause ( e ) ; } return result ; } | Invokes the method . |
16,404 | public void setMetricRegistry ( Object metricRegistry ) { if ( metricsTrackerFactory != null ) { throw new IllegalStateException ( "cannot use setMetricRegistry() and setMetricsTrackerFactory() together" ) ; } if ( metricRegistry != null ) { metricRegistry = getObjectOrPerformJndiLookup ( metricRegistry ) ; if ( ! safeIsAssignableFrom ( metricRegistry , "com.codahale.metrics.MetricRegistry" ) && ! ( safeIsAssignableFrom ( metricRegistry , "io.micrometer.core.instrument.MeterRegistry" ) ) ) { throw new IllegalArgumentException ( "Class must be instance of com.codahale.metrics.MetricRegistry or io.micrometer.core.instrument.MeterRegistry" ) ; } } this . metricRegistry = metricRegistry ; } | Set a MetricRegistry instance to use for registration of metrics used by HikariCP . |
16,405 | public void close ( ) { if ( isShutdown . getAndSet ( true ) ) { return ; } HikariPool p = pool ; if ( p != null ) { try { LOGGER . info ( "{} - Shutdown initiated..." , getPoolName ( ) ) ; p . shutdown ( ) ; LOGGER . info ( "{} - Shutdown completed." , getPoolName ( ) ) ; } catch ( InterruptedException e ) { LOGGER . warn ( "{} - Interrupted during closing" , getPoolName ( ) , e ) ; Thread . currentThread ( ) . interrupt ( ) ; } } } | Shutdown the DataSource and its associated pool . |
16,406 | public static Set < String > getPropertyNames ( final Class < ? > targetClass ) { HashSet < String > set = new HashSet < > ( ) ; Matcher matcher = GETTER_PATTERN . matcher ( "" ) ; for ( Method method : targetClass . getMethods ( ) ) { String name = method . getName ( ) ; if ( method . getParameterTypes ( ) . length == 0 && matcher . reset ( name ) . matches ( ) ) { name = name . replaceFirst ( "(get|is)" , "" ) ; try { if ( targetClass . getMethod ( "set" + name , method . getReturnType ( ) ) != null ) { name = Character . toLowerCase ( name . charAt ( 0 ) ) + name . substring ( 1 ) ; set . add ( name ) ; } } catch ( Exception e ) { } } } return set ; } | Get the bean - style property names for the specified object . |
16,407 | void handleMBeans ( final HikariPool hikariPool , final boolean register ) { if ( ! config . isRegisterMbeans ( ) ) { return ; } try { final MBeanServer mBeanServer = ManagementFactory . getPlatformMBeanServer ( ) ; final ObjectName beanConfigName = new ObjectName ( "com.zaxxer.hikari:type=PoolConfig (" + poolName + ")" ) ; final ObjectName beanPoolName = new ObjectName ( "com.zaxxer.hikari:type=Pool (" + poolName + ")" ) ; if ( register ) { if ( ! mBeanServer . isRegistered ( beanConfigName ) ) { mBeanServer . registerMBean ( config , beanConfigName ) ; mBeanServer . registerMBean ( hikariPool , beanPoolName ) ; } else { logger . error ( "{} - JMX name ({}) is already registered." , poolName , poolName ) ; } } else if ( mBeanServer . isRegistered ( beanConfigName ) ) { mBeanServer . unregisterMBean ( beanConfigName ) ; mBeanServer . unregisterMBean ( beanPoolName ) ; } } catch ( Exception e ) { logger . warn ( "{} - Failed to {} management beans." , poolName , ( register ? "register" : "unregister" ) , e ) ; } } | Register MBeans for HikariConfig and HikariPool . |
16,408 | private Connection newConnection ( ) throws Exception { final long start = currentTime ( ) ; Connection connection = null ; try { String username = config . getUsername ( ) ; String password = config . getPassword ( ) ; connection = ( username == null ) ? dataSource . getConnection ( ) : dataSource . getConnection ( username , password ) ; setupConnection ( connection ) ; lastConnectionFailure . set ( null ) ; return connection ; } catch ( Exception e ) { if ( connection != null ) { quietlyCloseConnection ( connection , "(Failed to create/setup connection)" ) ; } else if ( getLastConnectionFailure ( ) == null ) { logger . debug ( "{} - Failed to create/setup connection: {}" , poolName , e . getMessage ( ) ) ; } lastConnectionFailure . set ( e ) ; throw e ; } finally { if ( metricsTracker != null ) { metricsTracker . recordConnectionCreated ( elapsedMillis ( start ) ) ; } } } | Obtain connection from data source . |
16,409 | private void setupConnection ( final Connection connection ) throws ConnectionSetupException { try { if ( networkTimeout == UNINITIALIZED ) { networkTimeout = getAndSetNetworkTimeout ( connection , validationTimeout ) ; } else { setNetworkTimeout ( connection , validationTimeout ) ; } if ( connection . isReadOnly ( ) != isReadOnly ) { connection . setReadOnly ( isReadOnly ) ; } if ( connection . getAutoCommit ( ) != isAutoCommit ) { connection . setAutoCommit ( isAutoCommit ) ; } checkDriverSupport ( connection ) ; if ( transactionIsolation != defaultTransactionIsolation ) { connection . setTransactionIsolation ( transactionIsolation ) ; } if ( catalog != null ) { connection . setCatalog ( catalog ) ; } if ( schema != null ) { connection . setSchema ( schema ) ; } executeSql ( connection , config . getConnectionInitSql ( ) , true ) ; setNetworkTimeout ( connection , networkTimeout ) ; } catch ( SQLException e ) { throw new ConnectionSetupException ( e ) ; } } | Setup a connection initial state . |
16,410 | private void checkDefaultIsolation ( final Connection connection ) throws SQLException { try { defaultTransactionIsolation = connection . getTransactionIsolation ( ) ; if ( transactionIsolation == - 1 ) { transactionIsolation = defaultTransactionIsolation ; } } catch ( SQLException e ) { logger . warn ( "{} - Default transaction isolation level detection failed ({})." , poolName , e . getMessage ( ) ) ; if ( e . getSQLState ( ) != null && ! e . getSQLState ( ) . startsWith ( "08" ) ) { throw e ; } } } | Check the default transaction isolation of the Connection . |
16,411 | private void setQueryTimeout ( final Statement statement , final int timeoutSec ) { if ( isQueryTimeoutSupported != FALSE ) { try { statement . setQueryTimeout ( timeoutSec ) ; isQueryTimeoutSupported = TRUE ; } catch ( Exception e ) { if ( isQueryTimeoutSupported == UNINITIALIZED ) { isQueryTimeoutSupported = FALSE ; logger . info ( "{} - Failed to set query timeout for statement. ({})" , poolName , e . getMessage ( ) ) ; } } } } | Set the query timeout if it is supported by the driver . |
16,412 | private void executeSql ( final Connection connection , final String sql , final boolean isCommit ) throws SQLException { if ( sql != null ) { try ( Statement statement = connection . createStatement ( ) ) { statement . execute ( sql ) ; } if ( isIsolateInternalQueries && ! isAutoCommit ) { if ( isCommit ) { connection . commit ( ) ; } else { connection . rollback ( ) ; } } } } | Execute the user - specified init SQL . |
16,413 | private void setLoginTimeout ( final DataSource dataSource ) { if ( connectionTimeout != Integer . MAX_VALUE ) { try { dataSource . setLoginTimeout ( Math . max ( 1 , ( int ) MILLISECONDS . toSeconds ( 500L + connectionTimeout ) ) ) ; } catch ( Exception e ) { logger . info ( "{} - Failed to set login timeout for data source. ({})" , poolName , e . getMessage ( ) ) ; } } } | Set the loginTimeout on the specified DataSource . |
16,414 | private static < T > void generateProxyClass ( Class < T > primaryInterface , String superClassName , String methodBody ) throws Exception { String newClassName = superClassName . replaceAll ( "(.+)\\.(\\w+)" , "$1.Hikari$2" ) ; CtClass superCt = classPool . getCtClass ( superClassName ) ; CtClass targetCt = classPool . makeClass ( newClassName , superCt ) ; targetCt . setModifiers ( Modifier . FINAL ) ; System . out . println ( "Generating " + newClassName ) ; targetCt . setModifiers ( Modifier . PUBLIC ) ; Set < String > superSigs = new HashSet < > ( ) ; for ( CtMethod method : superCt . getMethods ( ) ) { if ( ( method . getModifiers ( ) & Modifier . FINAL ) == Modifier . FINAL ) { superSigs . add ( method . getName ( ) + method . getSignature ( ) ) ; } } Set < String > methods = new HashSet < > ( ) ; for ( Class < ? > intf : getAllInterfaces ( primaryInterface ) ) { CtClass intfCt = classPool . getCtClass ( intf . getName ( ) ) ; targetCt . addInterface ( intfCt ) ; for ( CtMethod intfMethod : intfCt . getDeclaredMethods ( ) ) { final String signature = intfMethod . getName ( ) + intfMethod . getSignature ( ) ; if ( superSigs . contains ( signature ) ) { continue ; } if ( methods . contains ( signature ) ) { continue ; } methods . add ( signature ) ; CtMethod method = CtNewMethod . copy ( intfMethod , targetCt , null ) ; String modifiedBody = methodBody ; CtMethod superMethod = superCt . getMethod ( intfMethod . getName ( ) , intfMethod . getSignature ( ) ) ; if ( ( superMethod . getModifiers ( ) & Modifier . ABSTRACT ) != Modifier . ABSTRACT && ! isDefaultMethod ( intf , intfMethod ) ) { modifiedBody = modifiedBody . replace ( "((cast) " , "" ) ; modifiedBody = modifiedBody . replace ( "delegate" , "super" ) ; modifiedBody = modifiedBody . replace ( "super)" , "super" ) ; } modifiedBody = modifiedBody . replace ( "cast" , primaryInterface . getName ( ) ) ; if ( isThrowsSqlException ( intfMethod ) ) { modifiedBody = modifiedBody . replace ( "method" , method . getName ( ) ) ; } else { modifiedBody = "{ return ((cast) delegate).method($$); }" . replace ( "method" , method . getName ( ) ) . replace ( "cast" , primaryInterface . getName ( ) ) ; } if ( method . getReturnType ( ) == CtClass . voidType ) { modifiedBody = modifiedBody . replace ( "return" , "" ) ; } method . setBody ( modifiedBody ) ; targetCt . addMethod ( method ) ; } } targetCt . getClassFile ( ) . setMajorVersion ( ClassFile . JAVA_8 ) ; targetCt . writeFile ( genDirectory + "target/classes" ) ; } | Generate Javassist Proxy Classes |
16,415 | public boolean add ( T element ) { if ( size < elementData . length ) { elementData [ size ++ ] = element ; } else { final int oldCapacity = elementData . length ; final int newCapacity = oldCapacity << 1 ; @ SuppressWarnings ( "unchecked" ) final T [ ] newElementData = ( T [ ] ) Array . newInstance ( clazz , newCapacity ) ; System . arraycopy ( elementData , 0 , newElementData , 0 , oldCapacity ) ; newElementData [ size ++ ] = element ; elementData = newElementData ; } return true ; } | Add an element to the tail of the FastList . |
16,416 | public T removeLast ( ) { T element = elementData [ -- size ] ; elementData [ size ] = null ; return element ; } | Remove the last element from the list . No bound check is performed so if this method is called on an empty list and ArrayIndexOutOfBounds exception will be thrown . |
16,417 | public void clear ( ) { for ( int i = 0 ; i < size ; i ++ ) { elementData [ i ] = null ; } size = 0 ; } | Clear the FastList . |
16,418 | public Connection getConnection ( final long hardTimeout ) throws SQLException { suspendResumeLock . acquire ( ) ; final long startTime = currentTime ( ) ; try { long timeout = hardTimeout ; do { PoolEntry poolEntry = connectionBag . borrow ( timeout , MILLISECONDS ) ; if ( poolEntry == null ) { break ; } final long now = currentTime ( ) ; if ( poolEntry . isMarkedEvicted ( ) || ( elapsedMillis ( poolEntry . lastAccessed , now ) > aliveBypassWindowMs && ! isConnectionAlive ( poolEntry . connection ) ) ) { closeConnection ( poolEntry , poolEntry . isMarkedEvicted ( ) ? EVICTED_CONNECTION_MESSAGE : DEAD_CONNECTION_MESSAGE ) ; timeout = hardTimeout - elapsedMillis ( startTime ) ; } else { metricsTracker . recordBorrowStats ( poolEntry , startTime ) ; return poolEntry . createProxyConnection ( leakTaskFactory . schedule ( poolEntry ) , now ) ; } } while ( timeout > 0L ) ; metricsTracker . recordBorrowTimeoutStats ( startTime ) ; throw createTimeoutException ( startTime ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; throw new SQLException ( poolName + " - Interrupted during connection acquisition" , e ) ; } finally { suspendResumeLock . release ( ) ; } } | Get a connection from the pool or timeout after the specified number of milliseconds . |
16,419 | public synchronized void shutdown ( ) throws InterruptedException { try { poolState = POOL_SHUTDOWN ; if ( addConnectionExecutor == null ) { return ; } logPoolState ( "Before shutdown " ) ; if ( houseKeeperTask != null ) { houseKeeperTask . cancel ( false ) ; houseKeeperTask = null ; } softEvictConnections ( ) ; addConnectionExecutor . shutdown ( ) ; addConnectionExecutor . awaitTermination ( getLoginTimeout ( ) , SECONDS ) ; destroyHouseKeepingExecutorService ( ) ; connectionBag . close ( ) ; final ExecutorService assassinExecutor = createThreadPoolExecutor ( config . getMaximumPoolSize ( ) , poolName + " connection assassinator" , config . getThreadFactory ( ) , new ThreadPoolExecutor . CallerRunsPolicy ( ) ) ; try { final long start = currentTime ( ) ; do { abortActiveConnections ( assassinExecutor ) ; softEvictConnections ( ) ; } while ( getTotalConnections ( ) > 0 && elapsedMillis ( start ) < SECONDS . toMillis ( 10 ) ) ; } finally { assassinExecutor . shutdown ( ) ; assassinExecutor . awaitTermination ( 10L , SECONDS ) ; } shutdownNetworkTimeoutExecutor ( ) ; closeConnectionExecutor . shutdown ( ) ; closeConnectionExecutor . awaitTermination ( 10L , SECONDS ) ; } finally { logPoolState ( "After shutdown " ) ; handleMBeans ( this , false ) ; metricsTracker . close ( ) ; } } | Shutdown the pool closing all idle connections and aborting or closing active connections . |
16,420 | public void evictConnection ( Connection connection ) { ProxyConnection proxyConnection = ( ProxyConnection ) connection ; proxyConnection . cancelLeakTask ( ) ; try { softEvictConnection ( proxyConnection . getPoolEntry ( ) , "(connection evicted by user)" , ! connection . isClosed ( ) ) ; } catch ( SQLException e ) { } } | Evict a Connection from the pool . |
16,421 | public void setMetricRegistry ( Object metricRegistry ) { if ( metricRegistry != null && safeIsAssignableFrom ( metricRegistry , "com.codahale.metrics.MetricRegistry" ) ) { setMetricsTrackerFactory ( new CodahaleMetricsTrackerFactory ( ( MetricRegistry ) metricRegistry ) ) ; } else if ( metricRegistry != null && safeIsAssignableFrom ( metricRegistry , "io.micrometer.core.instrument.MeterRegistry" ) ) { setMetricsTrackerFactory ( new MicrometerMetricsTrackerFactory ( ( MeterRegistry ) metricRegistry ) ) ; } else { setMetricsTrackerFactory ( null ) ; } } | Set a metrics registry to be used when registering metrics collectors . The HikariDataSource prevents this method from being called more than once . |
16,422 | public void setMetricsTrackerFactory ( MetricsTrackerFactory metricsTrackerFactory ) { if ( metricsTrackerFactory != null ) { this . metricsTracker = new MetricsTrackerDelegate ( metricsTrackerFactory . create ( config . getPoolName ( ) , getPoolStats ( ) ) ) ; } else { this . metricsTracker = new NopMetricsTrackerDelegate ( ) ; } } | Set the MetricsTrackerFactory to be used to create the IMetricsTracker instance used by the pool . |
16,423 | public void setHealthCheckRegistry ( Object healthCheckRegistry ) { if ( healthCheckRegistry != null ) { CodahaleHealthChecker . registerHealthChecks ( this , config , ( HealthCheckRegistry ) healthCheckRegistry ) ; } } | Set the health check registry to be used when registering health checks . Currently only Codahale health checks are supported . |
16,424 | void logPoolState ( String ... prefix ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "{} - {}stats (total={}, active={}, idle={}, waiting={})" , poolName , ( prefix . length > 0 ? prefix [ 0 ] : "" ) , getTotalConnections ( ) , getActiveConnections ( ) , getIdleConnections ( ) , getThreadsAwaitingConnection ( ) ) ; } } | Log the current pool state at debug level . |
16,425 | private PoolEntry createPoolEntry ( ) { try { final PoolEntry poolEntry = newPoolEntry ( ) ; final long maxLifetime = config . getMaxLifetime ( ) ; if ( maxLifetime > 0 ) { final long variance = maxLifetime > 10_000 ? ThreadLocalRandom . current ( ) . nextLong ( maxLifetime / 40 ) : 0 ; final long lifetime = maxLifetime - variance ; poolEntry . setFutureEol ( houseKeepingExecutorService . schedule ( ( ) -> { if ( softEvictConnection ( poolEntry , "(connection has passed maxLifetime)" , false ) ) { addBagItem ( connectionBag . getWaitingThreadCount ( ) ) ; } } , lifetime , MILLISECONDS ) ) ; } return poolEntry ; } catch ( ConnectionSetupException e ) { if ( poolState == POOL_NORMAL ) { logger . error ( "{} - Error thrown while acquiring connection from data source" , poolName , e . getCause ( ) ) ; lastConnectionFailure . set ( e ) ; } return null ; } catch ( SQLException e ) { if ( poolState == POOL_NORMAL ) { logger . debug ( "{} - Cannot acquire connection from data source" , poolName , e ) ; lastConnectionFailure . set ( new ConnectionSetupException ( e ) ) ; } return null ; } catch ( Exception e ) { if ( poolState == POOL_NORMAL ) { logger . error ( "{} - Error thrown while acquiring connection from data source" , poolName , e ) ; lastConnectionFailure . set ( new ConnectionSetupException ( e ) ) ; } return null ; } } | Creating new poolEntry . If maxLifetime is configured create a future End - of - life task with 2 . 5% variance from the maxLifetime time to ensure there is no massive die - off of Connections in the pool . |
16,426 | private void abortActiveConnections ( final ExecutorService assassinExecutor ) { for ( PoolEntry poolEntry : connectionBag . values ( STATE_IN_USE ) ) { Connection connection = poolEntry . close ( ) ; try { connection . abort ( assassinExecutor ) ; } catch ( Throwable e ) { quietlyCloseConnection ( connection , "(connection aborted during shutdown)" ) ; } finally { connectionBag . remove ( poolEntry ) ; } } } | Attempt to abort or close active connections . |
16,427 | private void checkFailFast ( ) { final long initializationTimeout = config . getInitializationFailTimeout ( ) ; if ( initializationTimeout < 0 ) { return ; } final long startTime = currentTime ( ) ; do { final PoolEntry poolEntry = createPoolEntry ( ) ; if ( poolEntry != null ) { if ( config . getMinimumIdle ( ) > 0 ) { connectionBag . add ( poolEntry ) ; logger . debug ( "{} - Added connection {}" , poolName , poolEntry . connection ) ; } else { quietlyCloseConnection ( poolEntry . close ( ) , "(initialization check complete and minimumIdle is zero)" ) ; } return ; } if ( getLastConnectionFailure ( ) instanceof ConnectionSetupException ) { throwPoolInitializationException ( getLastConnectionFailure ( ) . getCause ( ) ) ; } quietlySleep ( SECONDS . toMillis ( 1 ) ) ; } while ( elapsedMillis ( startTime ) < initializationTimeout ) ; if ( initializationTimeout > 0 ) { throwPoolInitializationException ( getLastConnectionFailure ( ) ) ; } } | If initializationFailFast is configured check that we have DB connectivity . |
16,428 | private void throwPoolInitializationException ( Throwable t ) { logger . error ( "{} - Exception during pool initialization." , poolName , t ) ; destroyHouseKeepingExecutorService ( ) ; throw new PoolInitializationException ( t ) ; } | Log the Throwable that caused pool initialization to fail and then throw a PoolInitializationException with that cause attached . |
16,429 | private PoolStats getPoolStats ( ) { return new PoolStats ( SECONDS . toMillis ( 1 ) ) { protected void update ( ) { this . pendingThreads = HikariPool . this . getThreadsAwaitingConnection ( ) ; this . idleConnections = HikariPool . this . getIdleConnections ( ) ; this . totalConnections = HikariPool . this . getTotalConnections ( ) ; this . activeConnections = HikariPool . this . getActiveConnections ( ) ; this . maxConnections = config . getMaximumPoolSize ( ) ; this . minConnections = config . getMinimumIdle ( ) ; } } ; } | Create a PoolStats instance that will be used by metrics tracking with a pollable resolution of 1 second . |
16,430 | public T borrow ( long timeout , final TimeUnit timeUnit ) throws InterruptedException { final List < Object > list = threadList . get ( ) ; for ( int i = list . size ( ) - 1 ; i >= 0 ; i -- ) { final Object entry = list . remove ( i ) ; @ SuppressWarnings ( "unchecked" ) final T bagEntry = weakThreadLocals ? ( ( WeakReference < T > ) entry ) . get ( ) : ( T ) entry ; if ( bagEntry != null && bagEntry . compareAndSet ( STATE_NOT_IN_USE , STATE_IN_USE ) ) { return bagEntry ; } } final int waiting = waiters . incrementAndGet ( ) ; try { for ( T bagEntry : sharedList ) { if ( bagEntry . compareAndSet ( STATE_NOT_IN_USE , STATE_IN_USE ) ) { if ( waiting > 1 ) { listener . addBagItem ( waiting - 1 ) ; } return bagEntry ; } } listener . addBagItem ( waiting ) ; timeout = timeUnit . toNanos ( timeout ) ; do { final long start = currentTime ( ) ; final T bagEntry = handoffQueue . poll ( timeout , NANOSECONDS ) ; if ( bagEntry == null || bagEntry . compareAndSet ( STATE_NOT_IN_USE , STATE_IN_USE ) ) { return bagEntry ; } timeout -= elapsedNanos ( start ) ; } while ( timeout > 10_000 ) ; return null ; } finally { waiters . decrementAndGet ( ) ; } } | The method will borrow a BagEntry from the bag blocking for the specified timeout if none are available . |
16,431 | public void requite ( final T bagEntry ) { bagEntry . setState ( STATE_NOT_IN_USE ) ; for ( int i = 0 ; waiters . get ( ) > 0 ; i ++ ) { if ( bagEntry . getState ( ) != STATE_NOT_IN_USE || handoffQueue . offer ( bagEntry ) ) { return ; } else if ( ( i & 0xff ) == 0xff ) { parkNanos ( MICROSECONDS . toNanos ( 10 ) ) ; } else { yield ( ) ; } } final List < Object > threadLocalList = threadList . get ( ) ; if ( threadLocalList . size ( ) < 50 ) { threadLocalList . add ( weakThreadLocals ? new WeakReference < > ( bagEntry ) : bagEntry ) ; } } | This method will return a borrowed object to the bag . Objects that are borrowed from the bag but never requited will result in a memory leak . |
16,432 | public void add ( final T bagEntry ) { if ( closed ) { LOGGER . info ( "ConcurrentBag has been closed, ignoring add()" ) ; throw new IllegalStateException ( "ConcurrentBag has been closed, ignoring add()" ) ; } sharedList . add ( bagEntry ) ; while ( waiters . get ( ) > 0 && bagEntry . getState ( ) == STATE_NOT_IN_USE && ! handoffQueue . offer ( bagEntry ) ) { yield ( ) ; } } | Add a new object to the bag for others to borrow . |
16,433 | public int getCount ( final int state ) { int count = 0 ; for ( IConcurrentBagEntry e : sharedList ) { if ( e . getState ( ) == state ) { count ++ ; } } return count ; } | Get a count of the number of items in the specified state at the time of this call . |
16,434 | public static void registerHealthChecks ( final HikariPool pool , final HikariConfig hikariConfig , final HealthCheckRegistry registry ) { final Properties healthCheckProperties = hikariConfig . getHealthCheckProperties ( ) ; final MetricRegistry metricRegistry = ( MetricRegistry ) hikariConfig . getMetricRegistry ( ) ; final long checkTimeoutMs = Long . parseLong ( healthCheckProperties . getProperty ( "connectivityCheckTimeoutMs" , String . valueOf ( hikariConfig . getConnectionTimeout ( ) ) ) ) ; registry . register ( MetricRegistry . name ( hikariConfig . getPoolName ( ) , "pool" , "ConnectivityCheck" ) , new ConnectivityHealthCheck ( pool , checkTimeoutMs ) ) ; final long expected99thPercentile = Long . parseLong ( healthCheckProperties . getProperty ( "expected99thPercentileMs" , "0" ) ) ; if ( metricRegistry != null && expected99thPercentile > 0 ) { SortedMap < String , Timer > timers = metricRegistry . getTimers ( ( name , metric ) -> name . equals ( MetricRegistry . name ( hikariConfig . getPoolName ( ) , "pool" , "Wait" ) ) ) ; if ( ! timers . isEmpty ( ) ) { final Timer timer = timers . entrySet ( ) . iterator ( ) . next ( ) . getValue ( ) ; registry . register ( MetricRegistry . name ( hikariConfig . getPoolName ( ) , "pool" , "Connection99Percent" ) , new Connection99Percent ( timer , expected99thPercentile ) ) ; } } } | Register Dropwizard health checks . |
16,435 | public static boolean safeIsAssignableFrom ( Object obj , String className ) { try { Class < ? > clazz = Class . forName ( className ) ; return clazz . isAssignableFrom ( obj . getClass ( ) ) ; } catch ( ClassNotFoundException ignored ) { return false ; } } | Checks whether an object is an instance of given type without throwing exception when the class is not loaded . |
16,436 | public static < T > T createInstance ( final String className , final Class < T > clazz , final Object ... args ) { if ( className == null ) { return null ; } try { Class < ? > loaded = UtilityElf . class . getClassLoader ( ) . loadClass ( className ) ; if ( args . length == 0 ) { return clazz . cast ( loaded . newInstance ( ) ) ; } Class < ? > [ ] argClasses = new Class < ? > [ args . length ] ; for ( int i = 0 ; i < args . length ; i ++ ) { argClasses [ i ] = args [ i ] . getClass ( ) ; } Constructor < ? > constructor = loaded . getConstructor ( argClasses ) ; return clazz . cast ( constructor . newInstance ( args ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } | Create and instance of the specified class using the constructor matching the specified arguments . |
16,437 | public static ThreadPoolExecutor createThreadPoolExecutor ( final int queueSize , final String threadName , ThreadFactory threadFactory , final RejectedExecutionHandler policy ) { if ( threadFactory == null ) { threadFactory = new DefaultThreadFactory ( threadName , true ) ; } LinkedBlockingQueue < Runnable > queue = new LinkedBlockingQueue < > ( queueSize ) ; ThreadPoolExecutor executor = new ThreadPoolExecutor ( 1 , 1 , 5 , SECONDS , queue , threadFactory , policy ) ; executor . allowCoreThreadTimeOut ( true ) ; return executor ; } | Create a ThreadPoolExecutor . |
16,438 | public static int getTransactionIsolation ( final String transactionIsolationName ) { if ( transactionIsolationName != null ) { try { final String upperCaseIsolationLevelName = transactionIsolationName . toUpperCase ( Locale . ENGLISH ) ; return IsolationLevel . valueOf ( upperCaseIsolationLevelName ) . getLevelId ( ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Invalid transaction isolation value: " + transactionIsolationName ) ; } } return - 1 ; } | Get the int value of a transaction isolation level by name . |
16,439 | public < T > EventPoller < T > newPoller ( DataProvider < T > dataProvider , Sequence ... gatingSequences ) { return EventPoller . newInstance ( dataProvider , this , new Sequence ( ) , cursor , gatingSequences ) ; } | Creates an event poller for this sequence that will use the supplied data provider and gating sequences . |
16,440 | public EventHandlerGroup < T > after ( final EventProcessor ... processors ) { for ( final EventProcessor processor : processors ) { consumerRepository . add ( processor ) ; } return new EventHandlerGroup < > ( this , consumerRepository , Util . getSequencesFor ( processors ) ) ; } | Create a group of event processors to be used as a dependency . |
16,441 | public < A > void publishEvents ( final EventTranslatorOneArg < T , A > eventTranslator , final A [ ] arg ) { ringBuffer . publishEvents ( eventTranslator , arg ) ; } | Publish a batch of events to the ring buffer . |
16,442 | private boolean hasBacklog ( ) { final long cursor = ringBuffer . getCursor ( ) ; for ( final Sequence consumer : consumerRepository . getLastSequenceInChain ( false ) ) { if ( cursor > consumer . get ( ) ) { return true ; } } return false ; } | Confirms if all messages have been consumed by all event processors |
16,443 | public RingBuffer < T > start ( final Executor executor ) { if ( ! started . compareAndSet ( false , true ) ) { throw new IllegalStateException ( "WorkerPool has already been started and cannot be restarted until halted." ) ; } final long cursor = ringBuffer . getCursor ( ) ; workSequence . set ( cursor ) ; for ( WorkProcessor < ? > processor : workProcessors ) { processor . getSequence ( ) . set ( cursor ) ; executor . execute ( processor ) ; } return ringBuffer ; } | Start the worker pool processing events in sequence . |
16,444 | private void notifyStart ( ) { if ( eventHandler instanceof LifecycleAware ) { try { ( ( LifecycleAware ) eventHandler ) . onStart ( ) ; } catch ( final Throwable ex ) { exceptionHandler . handleOnStartException ( ex ) ; } } } | Notifies the EventHandler when this processor is starting up |
16,445 | private void notifyShutdown ( ) { if ( eventHandler instanceof LifecycleAware ) { try { ( ( LifecycleAware ) eventHandler ) . onShutdown ( ) ; } catch ( final Throwable ex ) { exceptionHandler . handleOnShutdownException ( ex ) ; } } } | Notifies the EventHandler immediately prior to this processor shutting down |
16,446 | public long addAndGet ( final long increment ) { long currentValue ; long newValue ; do { currentValue = get ( ) ; newValue = currentValue + increment ; } while ( ! compareAndSet ( currentValue , newValue ) ) ; return newValue ; } | Atomically add the supplied value . |
16,447 | public static < E > RingBuffer < E > createMultiProducer ( EventFactory < E > factory , int bufferSize , WaitStrategy waitStrategy ) { MultiProducerSequencer sequencer = new MultiProducerSequencer ( bufferSize , waitStrategy ) ; return new RingBuffer < E > ( factory , sequencer ) ; } | Create a new multiple producer RingBuffer with the specified wait strategy . |
16,448 | public static < E > RingBuffer < E > createSingleProducer ( EventFactory < E > factory , int bufferSize , WaitStrategy waitStrategy ) { SingleProducerSequencer sequencer = new SingleProducerSequencer ( bufferSize , waitStrategy ) ; return new RingBuffer < E > ( factory , sequencer ) ; } | Create a new single producer RingBuffer with the specified wait strategy . |
16,449 | public static DecoderResult decode ( BitMatrix image , ResultPoint imageTopLeft , ResultPoint imageBottomLeft , ResultPoint imageTopRight , ResultPoint imageBottomRight , int minCodewordWidth , int maxCodewordWidth ) throws NotFoundException , FormatException , ChecksumException { BoundingBox boundingBox = new BoundingBox ( image , imageTopLeft , imageBottomLeft , imageTopRight , imageBottomRight ) ; DetectionResultRowIndicatorColumn leftRowIndicatorColumn = null ; DetectionResultRowIndicatorColumn rightRowIndicatorColumn = null ; DetectionResult detectionResult ; for ( boolean firstPass = true ; ; firstPass = false ) { if ( imageTopLeft != null ) { leftRowIndicatorColumn = getRowIndicatorColumn ( image , boundingBox , imageTopLeft , true , minCodewordWidth , maxCodewordWidth ) ; } if ( imageTopRight != null ) { rightRowIndicatorColumn = getRowIndicatorColumn ( image , boundingBox , imageTopRight , false , minCodewordWidth , maxCodewordWidth ) ; } detectionResult = merge ( leftRowIndicatorColumn , rightRowIndicatorColumn ) ; if ( detectionResult == null ) { throw NotFoundException . getNotFoundInstance ( ) ; } BoundingBox resultBox = detectionResult . getBoundingBox ( ) ; if ( firstPass && resultBox != null && ( resultBox . getMinY ( ) < boundingBox . getMinY ( ) || resultBox . getMaxY ( ) > boundingBox . getMaxY ( ) ) ) { boundingBox = resultBox ; } else { break ; } } detectionResult . setBoundingBox ( boundingBox ) ; int maxBarcodeColumn = detectionResult . getBarcodeColumnCount ( ) + 1 ; detectionResult . setDetectionResultColumn ( 0 , leftRowIndicatorColumn ) ; detectionResult . setDetectionResultColumn ( maxBarcodeColumn , rightRowIndicatorColumn ) ; boolean leftToRight = leftRowIndicatorColumn != null ; for ( int barcodeColumnCount = 1 ; barcodeColumnCount <= maxBarcodeColumn ; barcodeColumnCount ++ ) { int barcodeColumn = leftToRight ? barcodeColumnCount : maxBarcodeColumn - barcodeColumnCount ; if ( detectionResult . getDetectionResultColumn ( barcodeColumn ) != null ) { continue ; } DetectionResultColumn detectionResultColumn ; if ( barcodeColumn == 0 || barcodeColumn == maxBarcodeColumn ) { detectionResultColumn = new DetectionResultRowIndicatorColumn ( boundingBox , barcodeColumn == 0 ) ; } else { detectionResultColumn = new DetectionResultColumn ( boundingBox ) ; } detectionResult . setDetectionResultColumn ( barcodeColumn , detectionResultColumn ) ; int startColumn = - 1 ; int previousStartColumn = startColumn ; for ( int imageRow = boundingBox . getMinY ( ) ; imageRow <= boundingBox . getMaxY ( ) ; imageRow ++ ) { startColumn = getStartColumn ( detectionResult , barcodeColumn , imageRow , leftToRight ) ; if ( startColumn < 0 || startColumn > boundingBox . getMaxX ( ) ) { if ( previousStartColumn == - 1 ) { continue ; } startColumn = previousStartColumn ; } Codeword codeword = detectCodeword ( image , boundingBox . getMinX ( ) , boundingBox . getMaxX ( ) , leftToRight , startColumn , imageRow , minCodewordWidth , maxCodewordWidth ) ; if ( codeword != null ) { detectionResultColumn . setCodeword ( imageRow , codeword ) ; previousStartColumn = startColumn ; minCodewordWidth = Math . min ( minCodewordWidth , codeword . getWidth ( ) ) ; maxCodewordWidth = Math . max ( maxCodewordWidth , codeword . getWidth ( ) ) ; } } } return createDecoderResult ( detectionResult ) ; } | than it should be . This can happen if the scanner used a bad blackpoint . |
16,450 | private static DecoderResult createDecoderResultFromAmbiguousValues ( int ecLevel , int [ ] codewords , int [ ] erasureArray , int [ ] ambiguousIndexes , int [ ] [ ] ambiguousIndexValues ) throws FormatException , ChecksumException { int [ ] ambiguousIndexCount = new int [ ambiguousIndexes . length ] ; int tries = 100 ; while ( tries -- > 0 ) { for ( int i = 0 ; i < ambiguousIndexCount . length ; i ++ ) { codewords [ ambiguousIndexes [ i ] ] = ambiguousIndexValues [ i ] [ ambiguousIndexCount [ i ] ] ; } try { return decodeCodewords ( codewords , ecLevel , erasureArray ) ; } catch ( ChecksumException ignored ) { } if ( ambiguousIndexCount . length == 0 ) { throw ChecksumException . getChecksumInstance ( ) ; } for ( int i = 0 ; i < ambiguousIndexCount . length ; i ++ ) { if ( ambiguousIndexCount [ i ] < ambiguousIndexValues [ i ] . length - 1 ) { ambiguousIndexCount [ i ] ++ ; break ; } else { ambiguousIndexCount [ i ] = 0 ; if ( i == ambiguousIndexCount . length - 1 ) { throw ChecksumException . getChecksumInstance ( ) ; } } } } throw ChecksumException . getChecksumInstance ( ) ; } | This method deals with the fact that the decoding process doesn t always yield a single most likely value . The current error correction implementation doesn t deal with erasures very well so it s better to provide a value for these ambiguous codewords instead of treating it as an erasure . The problem is that we don t know which of the ambiguous values to choose . We try decode using the first value and if that fails we use another of the ambiguous values and try to decode again . This usually only happens on very hard to read and decode barcodes so decoding the normal barcodes is not affected by this . |
16,451 | private static void verifyCodewordCount ( int [ ] codewords , int numECCodewords ) throws FormatException { if ( codewords . length < 4 ) { throw FormatException . getFormatInstance ( ) ; } int numberOfCodewords = codewords [ 0 ] ; if ( numberOfCodewords > codewords . length ) { throw FormatException . getFormatInstance ( ) ; } if ( numberOfCodewords == 0 ) { if ( numECCodewords < codewords . length ) { codewords [ 0 ] = codewords . length - numECCodewords ; } else { throw FormatException . getFormatInstance ( ) ; } } } | Verify that all is OK with the codeword array . |
16,452 | public static String encodeECC200 ( String codewords , SymbolInfo symbolInfo ) { if ( codewords . length ( ) != symbolInfo . getDataCapacity ( ) ) { throw new IllegalArgumentException ( "The number of codewords does not match the selected symbol" ) ; } StringBuilder sb = new StringBuilder ( symbolInfo . getDataCapacity ( ) + symbolInfo . getErrorCodewords ( ) ) ; sb . append ( codewords ) ; int blockCount = symbolInfo . getInterleavedBlockCount ( ) ; if ( blockCount == 1 ) { String ecc = createECCBlock ( codewords , symbolInfo . getErrorCodewords ( ) ) ; sb . append ( ecc ) ; } else { sb . setLength ( sb . capacity ( ) ) ; int [ ] dataSizes = new int [ blockCount ] ; int [ ] errorSizes = new int [ blockCount ] ; for ( int i = 0 ; i < blockCount ; i ++ ) { dataSizes [ i ] = symbolInfo . getDataLengthForInterleavedBlock ( i + 1 ) ; errorSizes [ i ] = symbolInfo . getErrorLengthForInterleavedBlock ( i + 1 ) ; } for ( int block = 0 ; block < blockCount ; block ++ ) { StringBuilder temp = new StringBuilder ( dataSizes [ block ] ) ; for ( int d = block ; d < symbolInfo . getDataCapacity ( ) ; d += blockCount ) { temp . append ( codewords . charAt ( d ) ) ; } String ecc = createECCBlock ( temp . toString ( ) , errorSizes [ block ] ) ; int pos = 0 ; for ( int e = block ; e < errorSizes [ block ] * blockCount ; e += blockCount ) { sb . setCharAt ( symbolInfo . getDataCapacity ( ) + e , ecc . charAt ( pos ++ ) ) ; } } } return sb . toString ( ) ; } | Creates the ECC200 error correction for an encoded message . |
16,453 | void remask ( ) { if ( parsedFormatInfo == null ) { return ; } DataMask dataMask = DataMask . values ( ) [ parsedFormatInfo . getDataMask ( ) ] ; int dimension = bitMatrix . getHeight ( ) ; dataMask . unmaskBitMatrix ( bitMatrix , dimension ) ; } | Revert the mask removal done while reading the code words . The bit matrix should revert to its original state . |
16,454 | void mirror ( ) { for ( int x = 0 ; x < bitMatrix . getWidth ( ) ; x ++ ) { for ( int y = x + 1 ; y < bitMatrix . getHeight ( ) ; y ++ ) { if ( bitMatrix . get ( x , y ) != bitMatrix . get ( y , x ) ) { bitMatrix . flip ( y , x ) ; bitMatrix . flip ( x , y ) ; } } } } | Mirror the bit matrix in order to attempt a second reading . |
16,455 | public static CharSequence downloadViaHttp ( String uri , ContentType type ) throws IOException { return downloadViaHttp ( uri , type , Integer . MAX_VALUE ) ; } | Downloads the entire resource instead of part . |
16,456 | private boolean crossCheckDiagonal ( int centerI , int centerJ ) { int [ ] stateCount = getCrossCheckStateCount ( ) ; int i = 0 ; while ( centerI >= i && centerJ >= i && image . get ( centerJ - i , centerI - i ) ) { stateCount [ 2 ] ++ ; i ++ ; } if ( stateCount [ 2 ] == 0 ) { return false ; } while ( centerI >= i && centerJ >= i && ! image . get ( centerJ - i , centerI - i ) ) { stateCount [ 1 ] ++ ; i ++ ; } if ( stateCount [ 1 ] == 0 ) { return false ; } while ( centerI >= i && centerJ >= i && image . get ( centerJ - i , centerI - i ) ) { stateCount [ 0 ] ++ ; i ++ ; } if ( stateCount [ 0 ] == 0 ) { return false ; } int maxI = image . getHeight ( ) ; int maxJ = image . getWidth ( ) ; i = 1 ; while ( centerI + i < maxI && centerJ + i < maxJ && image . get ( centerJ + i , centerI + i ) ) { stateCount [ 2 ] ++ ; i ++ ; } while ( centerI + i < maxI && centerJ + i < maxJ && ! image . get ( centerJ + i , centerI + i ) ) { stateCount [ 3 ] ++ ; i ++ ; } if ( stateCount [ 3 ] == 0 ) { return false ; } while ( centerI + i < maxI && centerJ + i < maxJ && image . get ( centerJ + i , centerI + i ) ) { stateCount [ 4 ] ++ ; i ++ ; } if ( stateCount [ 4 ] == 0 ) { return false ; } return foundPatternDiagonal ( stateCount ) ; } | After a vertical and horizontal scan finds a potential finder pattern this method cross - cross - cross - checks by scanning down diagonally through the center of the possible finder pattern to see if the same proportion is detected . |
16,457 | private static double squaredDistance ( FinderPattern a , FinderPattern b ) { double x = a . getX ( ) - b . getX ( ) ; double y = a . getY ( ) - b . getY ( ) ; return x * x + y * y ; } | Get square of distance between a and b . |
16,458 | private static BitMatrix bitMatrixFromBitArray ( byte [ ] [ ] input , int margin ) { BitMatrix output = new BitMatrix ( input [ 0 ] . length + 2 * margin , input . length + 2 * margin ) ; output . clear ( ) ; for ( int y = 0 , yOutput = output . getHeight ( ) - margin - 1 ; y < input . length ; y ++ , yOutput -- ) { byte [ ] inputY = input [ y ] ; for ( int x = 0 ; x < input [ 0 ] . length ; x ++ ) { if ( inputY [ x ] == 1 ) { output . set ( x + margin , yOutput ) ; } } } return output ; } | This takes an array holding the values of the PDF 417 |
16,459 | private static byte [ ] [ ] rotateArray ( byte [ ] [ ] bitarray ) { byte [ ] [ ] temp = new byte [ bitarray [ 0 ] . length ] [ bitarray . length ] ; for ( int ii = 0 ; ii < bitarray . length ; ii ++ ) { int inverseii = bitarray . length - ii - 1 ; for ( int jj = 0 ; jj < bitarray [ 0 ] . length ; jj ++ ) { temp [ jj ] [ inverseii ] = bitarray [ ii ] [ jj ] ; } } return temp ; } | Takes and rotates the it 90 degrees |
16,460 | private static int toNarrowWidePattern ( int [ ] counters ) { int numCounters = counters . length ; int maxNarrowCounter = 0 ; int wideCounters ; do { int minCounter = Integer . MAX_VALUE ; for ( int counter : counters ) { if ( counter < minCounter && counter > maxNarrowCounter ) { minCounter = counter ; } } maxNarrowCounter = minCounter ; wideCounters = 0 ; int totalWideCountersWidth = 0 ; int pattern = 0 ; for ( int i = 0 ; i < numCounters ; i ++ ) { int counter = counters [ i ] ; if ( counter > maxNarrowCounter ) { pattern |= 1 << ( numCounters - 1 - i ) ; wideCounters ++ ; totalWideCountersWidth += counter ; } } if ( wideCounters == 3 ) { for ( int i = 0 ; i < numCounters && wideCounters > 0 ; i ++ ) { int counter = counters [ i ] ; if ( counter > maxNarrowCounter ) { wideCounters -- ; if ( ( counter * 2 ) >= totalWideCountersWidth ) { return - 1 ; } } } return pattern ; } } while ( wideCounters > 3 ) ; return - 1 ; } | per image when using some of our blackbox images . |
16,461 | private static List < ResultPoint [ ] > detect ( boolean multiple , BitMatrix bitMatrix ) { List < ResultPoint [ ] > barcodeCoordinates = new ArrayList < > ( ) ; int row = 0 ; int column = 0 ; boolean foundBarcodeInRow = false ; while ( row < bitMatrix . getHeight ( ) ) { ResultPoint [ ] vertices = findVertices ( bitMatrix , row , column ) ; if ( vertices [ 0 ] == null && vertices [ 3 ] == null ) { if ( ! foundBarcodeInRow ) { break ; } foundBarcodeInRow = false ; column = 0 ; for ( ResultPoint [ ] barcodeCoordinate : barcodeCoordinates ) { if ( barcodeCoordinate [ 1 ] != null ) { row = ( int ) Math . max ( row , barcodeCoordinate [ 1 ] . getY ( ) ) ; } if ( barcodeCoordinate [ 3 ] != null ) { row = Math . max ( row , ( int ) barcodeCoordinate [ 3 ] . getY ( ) ) ; } } row += ROW_STEP ; continue ; } foundBarcodeInRow = true ; barcodeCoordinates . add ( vertices ) ; if ( ! multiple ) { break ; } if ( vertices [ 2 ] != null ) { column = ( int ) vertices [ 2 ] . getX ( ) ; row = ( int ) vertices [ 2 ] . getY ( ) ; } else { column = ( int ) vertices [ 4 ] . getX ( ) ; row = ( int ) vertices [ 4 ] . getY ( ) ; } } return barcodeCoordinates ; } | Detects PDF417 codes in an image . Only checks 0 degree rotation |
16,462 | private static ResultPoint [ ] findVertices ( BitMatrix matrix , int startRow , int startColumn ) { int height = matrix . getHeight ( ) ; int width = matrix . getWidth ( ) ; ResultPoint [ ] result = new ResultPoint [ 8 ] ; copyToResult ( result , findRowsWithPattern ( matrix , height , width , startRow , startColumn , START_PATTERN ) , INDEXES_START_PATTERN ) ; if ( result [ 4 ] != null ) { startColumn = ( int ) result [ 4 ] . getX ( ) ; startRow = ( int ) result [ 4 ] . getY ( ) ; } copyToResult ( result , findRowsWithPattern ( matrix , height , width , startRow , startColumn , STOP_PATTERN ) , INDEXES_STOP_PATTERN ) ; return result ; } | Locate the vertices and the codewords area of a black blob using the Start and Stop patterns as locators . |
16,463 | public synchronized void openDriver ( SurfaceHolder holder ) throws IOException { OpenCamera theCamera = camera ; if ( theCamera == null ) { theCamera = OpenCameraInterface . open ( requestedCameraId ) ; if ( theCamera == null ) { throw new IOException ( "Camera.open() failed to return object from driver" ) ; } camera = theCamera ; } if ( ! initialized ) { initialized = true ; configManager . initFromCameraParameters ( theCamera ) ; if ( requestedFramingRectWidth > 0 && requestedFramingRectHeight > 0 ) { setManualFramingRect ( requestedFramingRectWidth , requestedFramingRectHeight ) ; requestedFramingRectWidth = 0 ; requestedFramingRectHeight = 0 ; } } Camera cameraObject = theCamera . getCamera ( ) ; Camera . Parameters parameters = cameraObject . getParameters ( ) ; String parametersFlattened = parameters == null ? null : parameters . flatten ( ) ; try { configManager . setDesiredCameraParameters ( theCamera , false ) ; } catch ( RuntimeException re ) { Log . w ( TAG , "Camera rejected parameters. Setting only minimal safe-mode parameters" ) ; Log . i ( TAG , "Resetting to saved camera params: " + parametersFlattened ) ; if ( parametersFlattened != null ) { parameters = cameraObject . getParameters ( ) ; parameters . unflatten ( parametersFlattened ) ; try { cameraObject . setParameters ( parameters ) ; configManager . setDesiredCameraParameters ( theCamera , true ) ; } catch ( RuntimeException re2 ) { Log . w ( TAG , "Camera rejected even safe-mode parameters! No configuration" ) ; } } } cameraObject . setPreviewDisplay ( holder ) ; } | Opens the camera driver and initializes the hardware parameters . |
16,464 | public synchronized void closeDriver ( ) { if ( camera != null ) { camera . getCamera ( ) . release ( ) ; camera = null ; framingRect = null ; framingRectInPreview = null ; } } | Closes the camera driver if still in use . |
16,465 | public synchronized Rect getFramingRect ( ) { if ( framingRect == null ) { if ( camera == null ) { return null ; } Point screenResolution = configManager . getScreenResolution ( ) ; if ( screenResolution == null ) { return null ; } int width = findDesiredDimensionInRange ( screenResolution . x , MIN_FRAME_WIDTH , MAX_FRAME_WIDTH ) ; int height = findDesiredDimensionInRange ( screenResolution . y , MIN_FRAME_HEIGHT , MAX_FRAME_HEIGHT ) ; int leftOffset = ( screenResolution . x - width ) / 2 ; int topOffset = ( screenResolution . y - height ) / 2 ; framingRect = new Rect ( leftOffset , topOffset , leftOffset + width , topOffset + height ) ; Log . d ( TAG , "Calculated framing rect: " + framingRect ) ; } return framingRect ; } | Calculates the framing rect which the UI should draw to show the user where to place the barcode . This target helps with alignment as well as forces the user to hold the device far enough away to ensure the image will be in focus . |
16,466 | public synchronized void setManualFramingRect ( int width , int height ) { if ( initialized ) { Point screenResolution = configManager . getScreenResolution ( ) ; if ( width > screenResolution . x ) { width = screenResolution . x ; } if ( height > screenResolution . y ) { height = screenResolution . y ; } int leftOffset = ( screenResolution . x - width ) / 2 ; int topOffset = ( screenResolution . y - height ) / 2 ; framingRect = new Rect ( leftOffset , topOffset , leftOffset + width , topOffset + height ) ; Log . d ( TAG , "Calculated manual framing rect: " + framingRect ) ; framingRectInPreview = null ; } else { requestedFramingRectWidth = width ; requestedFramingRectHeight = height ; } } | Allows third party apps to specify the scanning rectangle dimensions rather than determine them automatically based on screen resolution . |
16,467 | public PlanarYUVLuminanceSource buildLuminanceSource ( byte [ ] data , int width , int height ) { Rect rect = getFramingRectInPreview ( ) ; if ( rect == null ) { return null ; } return new PlanarYUVLuminanceSource ( data , width , height , rect . left , rect . top , rect . width ( ) , rect . height ( ) , false ) ; } | A factory method to build the appropriate LuminanceSource object based on the format of the preview buffers as described by Camera . Parameters . |
16,468 | public BitArray getBlackRow ( int y , BitArray row ) throws NotFoundException { return binarizer . getBlackRow ( y , row ) ; } | Converts one row of luminance data to 1 bit data . May actually do the conversion or return cached data . Callers should assume this method is expensive and call it as seldom as possible . This method is intended for decoding 1D barcodes and may choose to apply sharpening . |
16,469 | public URIParsedResult parse ( Result result ) { String rawText = getMassagedText ( result ) ; if ( rawText . startsWith ( "URL:" ) || rawText . startsWith ( "URI:" ) ) { return new URIParsedResult ( rawText . substring ( 4 ) . trim ( ) , null ) ; } rawText = rawText . trim ( ) ; if ( ! isBasicallyValidURI ( rawText ) || isPossiblyMaliciousURI ( rawText ) ) { return null ; } return new URIParsedResult ( rawText , null ) ; } | query path or nothing |
16,470 | public AztecDetectorResult detect ( boolean isMirror ) throws NotFoundException { Point pCenter = getMatrixCenter ( ) ; ResultPoint [ ] bullsEyeCorners = getBullsEyeCorners ( pCenter ) ; if ( isMirror ) { ResultPoint temp = bullsEyeCorners [ 0 ] ; bullsEyeCorners [ 0 ] = bullsEyeCorners [ 2 ] ; bullsEyeCorners [ 2 ] = temp ; } extractParameters ( bullsEyeCorners ) ; BitMatrix bits = sampleGrid ( image , bullsEyeCorners [ shift % 4 ] , bullsEyeCorners [ ( shift + 1 ) % 4 ] , bullsEyeCorners [ ( shift + 2 ) % 4 ] , bullsEyeCorners [ ( shift + 3 ) % 4 ] ) ; ResultPoint [ ] corners = getMatrixCornerPoints ( bullsEyeCorners ) ; return new AztecDetectorResult ( bits , corners , compact , nbDataBlocks , nbLayers ) ; } | Detects an Aztec Code in an image . |
16,471 | private void extractParameters ( ResultPoint [ ] bullsEyeCorners ) throws NotFoundException { if ( ! isValid ( bullsEyeCorners [ 0 ] ) || ! isValid ( bullsEyeCorners [ 1 ] ) || ! isValid ( bullsEyeCorners [ 2 ] ) || ! isValid ( bullsEyeCorners [ 3 ] ) ) { throw NotFoundException . getNotFoundInstance ( ) ; } int length = 2 * nbCenterLayers ; int [ ] sides = { sampleLine ( bullsEyeCorners [ 0 ] , bullsEyeCorners [ 1 ] , length ) , sampleLine ( bullsEyeCorners [ 1 ] , bullsEyeCorners [ 2 ] , length ) , sampleLine ( bullsEyeCorners [ 2 ] , bullsEyeCorners [ 3 ] , length ) , sampleLine ( bullsEyeCorners [ 3 ] , bullsEyeCorners [ 0 ] , length ) } ; shift = getRotation ( sides , length ) ; long parameterData = 0 ; for ( int i = 0 ; i < 4 ; i ++ ) { int side = sides [ ( shift + i ) % 4 ] ; if ( compact ) { parameterData <<= 7 ; parameterData += ( side >> 1 ) & 0x7F ; } else { parameterData <<= 10 ; parameterData += ( ( side >> 2 ) & ( 0x1f << 5 ) ) + ( ( side >> 1 ) & 0x1F ) ; } } int correctedData = getCorrectedParameterData ( parameterData , compact ) ; if ( compact ) { nbLayers = ( correctedData >> 6 ) + 1 ; nbDataBlocks = ( correctedData & 0x3F ) + 1 ; } else { nbLayers = ( correctedData >> 11 ) + 1 ; nbDataBlocks = ( correctedData & 0x7FF ) + 1 ; } } | Extracts the number of data layers and data blocks from the layer around the bull s eye . |
16,472 | private static int getCorrectedParameterData ( long parameterData , boolean compact ) throws NotFoundException { int numCodewords ; int numDataCodewords ; if ( compact ) { numCodewords = 7 ; numDataCodewords = 2 ; } else { numCodewords = 10 ; numDataCodewords = 4 ; } int numECCodewords = numCodewords - numDataCodewords ; int [ ] parameterWords = new int [ numCodewords ] ; for ( int i = numCodewords - 1 ; i >= 0 ; -- i ) { parameterWords [ i ] = ( int ) parameterData & 0xF ; parameterData >>= 4 ; } try { ReedSolomonDecoder rsDecoder = new ReedSolomonDecoder ( GenericGF . AZTEC_PARAM ) ; rsDecoder . decode ( parameterWords , numECCodewords ) ; } catch ( ReedSolomonException ignored ) { throw NotFoundException . getNotFoundInstance ( ) ; } int result = 0 ; for ( int i = 0 ; i < numDataCodewords ; i ++ ) { result = ( result << 4 ) + parameterWords [ i ] ; } return result ; } | Corrects the parameter bits using Reed - Solomon algorithm . |
16,473 | private BitMatrix sampleGrid ( BitMatrix image , ResultPoint topLeft , ResultPoint topRight , ResultPoint bottomRight , ResultPoint bottomLeft ) throws NotFoundException { GridSampler sampler = GridSampler . getInstance ( ) ; int dimension = getDimension ( ) ; float low = dimension / 2.0f - nbCenterLayers ; float high = dimension / 2.0f + nbCenterLayers ; return sampler . sampleGrid ( image , dimension , dimension , low , low , high , low , high , high , low , high , topLeft . getX ( ) , topLeft . getY ( ) , topRight . getX ( ) , topRight . getY ( ) , bottomRight . getX ( ) , bottomRight . getY ( ) , bottomLeft . getX ( ) , bottomLeft . getY ( ) ) ; } | Creates a BitMatrix by sampling the provided image . topLeft topRight bottomRight and bottomLeft are the centers of the squares on the diagonal just outside the bull s eye . |
16,474 | private int sampleLine ( ResultPoint p1 , ResultPoint p2 , int size ) { int result = 0 ; float d = distance ( p1 , p2 ) ; float moduleSize = d / size ; float px = p1 . getX ( ) ; float py = p1 . getY ( ) ; float dx = moduleSize * ( p2 . getX ( ) - p1 . getX ( ) ) / d ; float dy = moduleSize * ( p2 . getY ( ) - p1 . getY ( ) ) / d ; for ( int i = 0 ; i < size ; i ++ ) { if ( image . get ( MathUtils . round ( px + i * dx ) , MathUtils . round ( py + i * dy ) ) ) { result |= 1 << ( size - i - 1 ) ; } } return result ; } | Samples a line . |
16,475 | private int getColor ( Point p1 , Point p2 ) { float d = distance ( p1 , p2 ) ; float dx = ( p2 . getX ( ) - p1 . getX ( ) ) / d ; float dy = ( p2 . getY ( ) - p1 . getY ( ) ) / d ; int error = 0 ; float px = p1 . getX ( ) ; float py = p1 . getY ( ) ; boolean colorModel = image . get ( p1 . getX ( ) , p1 . getY ( ) ) ; int iMax = ( int ) Math . ceil ( d ) ; for ( int i = 0 ; i < iMax ; i ++ ) { px += dx ; py += dy ; if ( image . get ( MathUtils . round ( px ) , MathUtils . round ( py ) ) != colorModel ) { error ++ ; } } float errRatio = error / d ; if ( errRatio > 0.1f && errRatio < 0.9f ) { return 0 ; } return ( errRatio <= 0.1f ) == colorModel ? 1 : - 1 ; } | Gets the color of a segment |
16,476 | private Point getFirstDifferent ( Point init , boolean color , int dx , int dy ) { int x = init . getX ( ) + dx ; int y = init . getY ( ) + dy ; while ( isValid ( x , y ) && image . get ( x , y ) == color ) { x += dx ; y += dy ; } x -= dx ; y -= dy ; while ( isValid ( x , y ) && image . get ( x , y ) == color ) { x += dx ; } x -= dx ; while ( isValid ( x , y ) && image . get ( x , y ) == color ) { y += dy ; } y -= dy ; return new Point ( x , y ) ; } | Gets the coordinate of the first point with a different color in the given direction |
16,477 | private static ResultPoint [ ] expandSquare ( ResultPoint [ ] cornerPoints , int oldSide , int newSide ) { float ratio = newSide / ( 2.0f * oldSide ) ; float dx = cornerPoints [ 0 ] . getX ( ) - cornerPoints [ 2 ] . getX ( ) ; float dy = cornerPoints [ 0 ] . getY ( ) - cornerPoints [ 2 ] . getY ( ) ; float centerx = ( cornerPoints [ 0 ] . getX ( ) + cornerPoints [ 2 ] . getX ( ) ) / 2.0f ; float centery = ( cornerPoints [ 0 ] . getY ( ) + cornerPoints [ 2 ] . getY ( ) ) / 2.0f ; ResultPoint result0 = new ResultPoint ( centerx + ratio * dx , centery + ratio * dy ) ; ResultPoint result2 = new ResultPoint ( centerx - ratio * dx , centery - ratio * dy ) ; dx = cornerPoints [ 1 ] . getX ( ) - cornerPoints [ 3 ] . getX ( ) ; dy = cornerPoints [ 1 ] . getY ( ) - cornerPoints [ 3 ] . getY ( ) ; centerx = ( cornerPoints [ 1 ] . getX ( ) + cornerPoints [ 3 ] . getX ( ) ) / 2.0f ; centery = ( cornerPoints [ 1 ] . getY ( ) + cornerPoints [ 3 ] . getY ( ) ) / 2.0f ; ResultPoint result1 = new ResultPoint ( centerx + ratio * dx , centery + ratio * dy ) ; ResultPoint result3 = new ResultPoint ( centerx - ratio * dx , centery - ratio * dy ) ; return new ResultPoint [ ] { result0 , result1 , result2 , result3 } ; } | Expand the square represented by the corner points by pushing out equally in all directions |
16,478 | private ResultPoint findCornerFromCenter ( int centerX , int deltaX , int left , int right , int centerY , int deltaY , int top , int bottom , int maxWhiteRun ) throws NotFoundException { int [ ] lastRange = null ; for ( int y = centerY , x = centerX ; y < bottom && y >= top && x < right && x >= left ; y += deltaY , x += deltaX ) { int [ ] range ; if ( deltaX == 0 ) { range = blackWhiteRange ( y , maxWhiteRun , left , right , true ) ; } else { range = blackWhiteRange ( x , maxWhiteRun , top , bottom , false ) ; } if ( range == null ) { if ( lastRange == null ) { throw NotFoundException . getNotFoundInstance ( ) ; } if ( deltaX == 0 ) { int lastY = y - deltaY ; if ( lastRange [ 0 ] < centerX ) { if ( lastRange [ 1 ] > centerX ) { return new ResultPoint ( lastRange [ deltaY > 0 ? 0 : 1 ] , lastY ) ; } return new ResultPoint ( lastRange [ 0 ] , lastY ) ; } else { return new ResultPoint ( lastRange [ 1 ] , lastY ) ; } } else { int lastX = x - deltaX ; if ( lastRange [ 0 ] < centerY ) { if ( lastRange [ 1 ] > centerY ) { return new ResultPoint ( lastX , lastRange [ deltaX < 0 ? 0 : 1 ] ) ; } return new ResultPoint ( lastX , lastRange [ 0 ] ) ; } else { return new ResultPoint ( lastX , lastRange [ 1 ] ) ; } } } lastRange = range ; } throw NotFoundException . getNotFoundInstance ( ) ; } | Attempts to locate a corner of the barcode by scanning up down left or right from a center point which should be within the barcode . |
16,479 | private int [ ] blackWhiteRange ( int fixedDimension , int maxWhiteRun , int minDim , int maxDim , boolean horizontal ) { int center = ( minDim + maxDim ) / 2 ; int start = center ; while ( start >= minDim ) { if ( horizontal ? image . get ( start , fixedDimension ) : image . get ( fixedDimension , start ) ) { start -- ; } else { int whiteRunStart = start ; do { start -- ; } while ( start >= minDim && ! ( horizontal ? image . get ( start , fixedDimension ) : image . get ( fixedDimension , start ) ) ) ; int whiteRunSize = whiteRunStart - start ; if ( start < minDim || whiteRunSize > maxWhiteRun ) { start = whiteRunStart ; break ; } } } start ++ ; int end = center ; while ( end < maxDim ) { if ( horizontal ? image . get ( end , fixedDimension ) : image . get ( fixedDimension , end ) ) { end ++ ; } else { int whiteRunStart = end ; do { end ++ ; } while ( end < maxDim && ! ( horizontal ? image . get ( end , fixedDimension ) : image . get ( fixedDimension , end ) ) ) ; int whiteRunSize = end - whiteRunStart ; if ( end >= maxDim || whiteRunSize > maxWhiteRun ) { end = whiteRunStart ; break ; } } } end -- ; return end > start ? new int [ ] { start , end } : null ; } | Computes the start and end of a region of pixels either horizontally or vertically that could be part of a Data Matrix barcode . |
16,480 | private static void decodeHanziSegment ( BitSource bits , StringBuilder result , int count ) throws FormatException { if ( count * 13 > bits . available ( ) ) { throw FormatException . getFormatInstance ( ) ; } byte [ ] buffer = new byte [ 2 * count ] ; int offset = 0 ; while ( count > 0 ) { int twoBytes = bits . readBits ( 13 ) ; int assembledTwoBytes = ( ( twoBytes / 0x060 ) << 8 ) | ( twoBytes % 0x060 ) ; if ( assembledTwoBytes < 0x00A00 ) { assembledTwoBytes += 0x0A1A1 ; } else { assembledTwoBytes += 0x0A6A1 ; } buffer [ offset ] = ( byte ) ( ( assembledTwoBytes >> 8 ) & 0xFF ) ; buffer [ offset + 1 ] = ( byte ) ( assembledTwoBytes & 0xFF ) ; offset += 2 ; count -- ; } try { result . append ( new String ( buffer , StringUtils . GB2312 ) ) ; } catch ( UnsupportedEncodingException ignored ) { throw FormatException . getFormatInstance ( ) ; } } | See specification GBT 18284 - 2000 |
16,481 | private static void changeNetworkWEP ( WifiManager wifiManager , WifiParsedResult wifiResult ) { WifiConfiguration config = changeNetworkCommon ( wifiResult ) ; config . wepKeys [ 0 ] = quoteNonHex ( wifiResult . getPassword ( ) , 10 , 26 , 58 ) ; config . wepTxKeyIndex = 0 ; config . allowedAuthAlgorithms . set ( WifiConfiguration . AuthAlgorithm . SHARED ) ; config . allowedKeyManagement . set ( WifiConfiguration . KeyMgmt . NONE ) ; config . allowedGroupCiphers . set ( WifiConfiguration . GroupCipher . TKIP ) ; config . allowedGroupCiphers . set ( WifiConfiguration . GroupCipher . CCMP ) ; config . allowedGroupCiphers . set ( WifiConfiguration . GroupCipher . WEP40 ) ; config . allowedGroupCiphers . set ( WifiConfiguration . GroupCipher . WEP104 ) ; updateNetwork ( wifiManager , config ) ; } | Adding a WEP network |
16,482 | private static void changeNetworkWPA ( WifiManager wifiManager , WifiParsedResult wifiResult ) { WifiConfiguration config = changeNetworkCommon ( wifiResult ) ; config . preSharedKey = quoteNonHex ( wifiResult . getPassword ( ) , 64 ) ; config . allowedAuthAlgorithms . set ( WifiConfiguration . AuthAlgorithm . OPEN ) ; config . allowedProtocols . set ( WifiConfiguration . Protocol . WPA ) ; config . allowedProtocols . set ( WifiConfiguration . Protocol . RSN ) ; config . allowedKeyManagement . set ( WifiConfiguration . KeyMgmt . WPA_PSK ) ; config . allowedKeyManagement . set ( WifiConfiguration . KeyMgmt . WPA_EAP ) ; config . allowedPairwiseCiphers . set ( WifiConfiguration . PairwiseCipher . TKIP ) ; config . allowedPairwiseCiphers . set ( WifiConfiguration . PairwiseCipher . CCMP ) ; config . allowedGroupCiphers . set ( WifiConfiguration . GroupCipher . TKIP ) ; config . allowedGroupCiphers . set ( WifiConfiguration . GroupCipher . CCMP ) ; updateNetwork ( wifiManager , config ) ; } | Adding a WPA or WPA2 network |
16,483 | private static void changeNetworkUnEncrypted ( WifiManager wifiManager , WifiParsedResult wifiResult ) { WifiConfiguration config = changeNetworkCommon ( wifiResult ) ; config . allowedKeyManagement . set ( WifiConfiguration . KeyMgmt . NONE ) ; updateNetwork ( wifiManager , config ) ; } | Adding an open unsecured network |
16,484 | private static String convertToQuotedString ( String s ) { if ( s == null || s . isEmpty ( ) ) { return null ; } if ( s . charAt ( 0 ) == '"' && s . charAt ( s . length ( ) - 1 ) == '"' ) { return s ; } return '\"' + s + '\"' ; } | Encloses the incoming string inside double quotes if it isn t already quoted . |
16,485 | public CharSequence getDisplayContents ( ) { WifiParsedResult wifiResult = ( WifiParsedResult ) getResult ( ) ; return wifiResult . getSsid ( ) + " (" + wifiResult . getNetworkEncryption ( ) + ')' ; } | Display the name of the network and the network type to the user . |
16,486 | private static float crossProductZ ( ResultPoint pointA , ResultPoint pointB , ResultPoint pointC ) { float bX = pointB . x ; float bY = pointB . y ; return ( ( pointC . x - bX ) * ( pointA . y - bY ) ) - ( ( pointC . y - bY ) * ( pointA . x - bX ) ) ; } | Returns the z component of the cross product between vectors BC and BA . |
16,487 | private void encodeContentsFromZXingIntent ( Intent intent ) { String formatString = intent . getStringExtra ( Intents . Encode . FORMAT ) ; format = null ; if ( formatString != null ) { try { format = BarcodeFormat . valueOf ( formatString ) ; } catch ( IllegalArgumentException iae ) { } } if ( format == null || format == BarcodeFormat . QR_CODE ) { String type = intent . getStringExtra ( Intents . Encode . TYPE ) ; if ( type != null && ! type . isEmpty ( ) ) { this . format = BarcodeFormat . QR_CODE ; encodeQRCodeContents ( intent , type ) ; } } else { String data = intent . getStringExtra ( Intents . Encode . DATA ) ; if ( data != null && ! data . isEmpty ( ) ) { contents = data ; displayContents = data ; title = activity . getString ( R . string . contents_text ) ; } } } | but we use platform specific code like PhoneNumberUtils so it can t . |
16,488 | private void encodeContentsFromShareIntent ( Intent intent ) throws WriterException { if ( intent . hasExtra ( Intent . EXTRA_STREAM ) ) { encodeFromStreamExtra ( intent ) ; } else { encodeFromTextExtras ( intent ) ; } } | Handles send intents from multitude of Android applications |
16,489 | private void encodeFromStreamExtra ( Intent intent ) throws WriterException { format = BarcodeFormat . QR_CODE ; Bundle bundle = intent . getExtras ( ) ; if ( bundle == null ) { throw new WriterException ( "No extras" ) ; } Uri uri = bundle . getParcelable ( Intent . EXTRA_STREAM ) ; if ( uri == null ) { throw new WriterException ( "No EXTRA_STREAM" ) ; } byte [ ] vcard ; String vcardString ; try ( InputStream stream = activity . getContentResolver ( ) . openInputStream ( uri ) ) { if ( stream == null ) { throw new WriterException ( "Can't open stream for " + uri ) ; } ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; byte [ ] buffer = new byte [ 2048 ] ; int bytesRead ; while ( ( bytesRead = stream . read ( buffer ) ) > 0 ) { baos . write ( buffer , 0 , bytesRead ) ; } vcard = baos . toByteArray ( ) ; vcardString = new String ( vcard , 0 , vcard . length , StandardCharsets . UTF_8 ) ; } catch ( IOException ioe ) { throw new WriterException ( ioe ) ; } Log . d ( TAG , "Encoding share intent content:" ) ; Log . d ( TAG , vcardString ) ; Result result = new Result ( vcardString , vcard , null , BarcodeFormat . QR_CODE ) ; ParsedResult parsedResult = ResultParser . parseResult ( result ) ; if ( ! ( parsedResult instanceof AddressBookParsedResult ) ) { throw new WriterException ( "Result was not an address" ) ; } encodeQRCodeContents ( ( AddressBookParsedResult ) parsedResult ) ; if ( contents == null || contents . isEmpty ( ) ) { throw new WriterException ( "No content to encode" ) ; } } | Handles send intents from the Contacts app retrieving a contact as a VCARD . |
16,490 | private void setCounters ( BitArray row ) throws NotFoundException { counterLength = 0 ; int i = row . getNextUnset ( 0 ) ; int end = row . getSize ( ) ; if ( i >= end ) { throw NotFoundException . getNotFoundInstance ( ) ; } boolean isWhite = true ; int count = 0 ; while ( i < end ) { if ( row . get ( i ) != isWhite ) { count ++ ; } else { counterAppend ( count ) ; count = 1 ; isWhite = ! isWhite ; } i ++ ; } counterAppend ( count ) ; } | Records the size of all runs of white and black pixels starting with white . This is just like recordPattern except it records all the counters and uses our builtin counters member for storage . |
16,491 | public Result decode ( BinaryBitmap image , Map < DecodeHintType , ? > hints ) throws NotFoundException , FormatException { try { return doDecode ( image , hints ) ; } catch ( NotFoundException nfe ) { boolean tryHarder = hints != null && hints . containsKey ( DecodeHintType . TRY_HARDER ) ; if ( tryHarder && image . isRotateSupported ( ) ) { BinaryBitmap rotatedImage = image . rotateCounterClockwise ( ) ; Result result = doDecode ( rotatedImage , hints ) ; Map < ResultMetadataType , ? > metadata = result . getResultMetadata ( ) ; int orientation = 270 ; if ( metadata != null && metadata . containsKey ( ResultMetadataType . ORIENTATION ) ) { orientation = ( orientation + ( Integer ) metadata . get ( ResultMetadataType . ORIENTATION ) ) % 360 ; } result . putMetadata ( ResultMetadataType . ORIENTATION , orientation ) ; ResultPoint [ ] points = result . getResultPoints ( ) ; if ( points != null ) { int height = rotatedImage . getHeight ( ) ; for ( int i = 0 ; i < points . length ; i ++ ) { points [ i ] = new ResultPoint ( height - points [ i ] . getY ( ) - 1 , points [ i ] . getX ( ) ) ; } } return result ; } else { throw nfe ; } } } | Note that we don t try rotation without the try harder flag even if rotation was supported . |
16,492 | protected static void recordPattern ( BitArray row , int start , int [ ] counters ) throws NotFoundException { int numCounters = counters . length ; Arrays . fill ( counters , 0 , numCounters , 0 ) ; int end = row . getSize ( ) ; if ( start >= end ) { throw NotFoundException . getNotFoundInstance ( ) ; } boolean isWhite = ! row . get ( start ) ; int counterPosition = 0 ; int i = start ; while ( i < end ) { if ( row . get ( i ) != isWhite ) { counters [ counterPosition ] ++ ; } else { if ( ++ counterPosition == numCounters ) { break ; } else { counters [ counterPosition ] = 1 ; isWhite = ! isWhite ; } } i ++ ; } if ( ! ( counterPosition == numCounters || ( counterPosition == numCounters - 1 && i == end ) ) ) { throw NotFoundException . getNotFoundInstance ( ) ; } } | Records the size of successive runs of white and black pixels in a row starting at a given point . The values are recorded in the given array and the number of runs recorded is equal to the size of the array . If the row starts on a white pixel at the given start point then the first count recorded is the run of white pixels starting from that point ; likewise it is the count of a run of black pixels if the row begin on a black pixels at that point . |
16,493 | public BitMatrix getBlackMatrix ( ) throws NotFoundException { if ( matrix != null ) { return matrix ; } LuminanceSource source = getLuminanceSource ( ) ; int width = source . getWidth ( ) ; int height = source . getHeight ( ) ; if ( width >= MINIMUM_DIMENSION && height >= MINIMUM_DIMENSION ) { byte [ ] luminances = source . getMatrix ( ) ; int subWidth = width >> BLOCK_SIZE_POWER ; if ( ( width & BLOCK_SIZE_MASK ) != 0 ) { subWidth ++ ; } int subHeight = height >> BLOCK_SIZE_POWER ; if ( ( height & BLOCK_SIZE_MASK ) != 0 ) { subHeight ++ ; } int [ ] [ ] blackPoints = calculateBlackPoints ( luminances , subWidth , subHeight , width , height ) ; BitMatrix newMatrix = new BitMatrix ( width , height ) ; calculateThresholdForBlock ( luminances , subWidth , subHeight , width , height , blackPoints , newMatrix ) ; matrix = newMatrix ; } else { matrix = super . getBlackMatrix ( ) ; } return matrix ; } | Calculates the final BitMatrix once for all requests . This could be called once from the constructor instead but there are some advantages to doing it lazily such as making profiling easier and not doing heavy lifting when callers don t expect it . |
16,494 | private static void thresholdBlock ( byte [ ] luminances , int xoffset , int yoffset , int threshold , int stride , BitMatrix matrix ) { for ( int y = 0 , offset = yoffset * stride + xoffset ; y < BLOCK_SIZE ; y ++ , offset += stride ) { for ( int x = 0 ; x < BLOCK_SIZE ; x ++ ) { if ( ( luminances [ offset + x ] & 0xFF ) <= threshold ) { matrix . set ( xoffset + x , yoffset + y ) ; } } } } | Applies a single threshold to a block of pixels . |
16,495 | private int mapIndexToAction ( int index ) { if ( index < buttonCount ) { int count = - 1 ; for ( int x = 0 ; x < MAX_BUTTON_COUNT ; x ++ ) { if ( fields [ x ] ) { count ++ ; } if ( count == index ) { return x ; } } } return - 1 ; } | positions based on which fields are present in this barcode . |
16,496 | public CharSequence getDisplayContents ( ) { AddressBookParsedResult result = ( AddressBookParsedResult ) getResult ( ) ; StringBuilder contents = new StringBuilder ( 100 ) ; ParsedResult . maybeAppend ( result . getNames ( ) , contents ) ; int namesLength = contents . length ( ) ; String pronunciation = result . getPronunciation ( ) ; if ( pronunciation != null && ! pronunciation . isEmpty ( ) ) { contents . append ( "\n(" ) ; contents . append ( pronunciation ) ; contents . append ( ')' ) ; } ParsedResult . maybeAppend ( result . getTitle ( ) , contents ) ; ParsedResult . maybeAppend ( result . getOrg ( ) , contents ) ; ParsedResult . maybeAppend ( result . getAddresses ( ) , contents ) ; String [ ] numbers = result . getPhoneNumbers ( ) ; if ( numbers != null ) { for ( String number : numbers ) { if ( number != null ) { ParsedResult . maybeAppend ( formatPhone ( number ) , contents ) ; } } } ParsedResult . maybeAppend ( result . getEmails ( ) , contents ) ; ParsedResult . maybeAppend ( result . getURLs ( ) , contents ) ; String birthday = result . getBirthday ( ) ; if ( birthday != null && ! birthday . isEmpty ( ) ) { long date = parseDate ( birthday ) ; if ( date >= 0L ) { ParsedResult . maybeAppend ( DateFormat . getDateInstance ( DateFormat . MEDIUM ) . format ( date ) , contents ) ; } } ParsedResult . maybeAppend ( result . getNote ( ) , contents ) ; if ( namesLength > 0 ) { Spannable styled = new SpannableString ( contents . toString ( ) ) ; styled . setSpan ( new StyleSpan ( Typeface . BOLD ) , 0 , namesLength , 0 ) ; return styled ; } else { return contents . toString ( ) ; } } | Overriden so we can hyphenate phone numbers format birthdays and bold the name . |
16,497 | private static void formatNames ( Iterable < List < String > > names ) { if ( names != null ) { for ( List < String > list : names ) { String name = list . get ( 0 ) ; String [ ] components = new String [ 5 ] ; int start = 0 ; int end ; int componentIndex = 0 ; while ( componentIndex < components . length - 1 && ( end = name . indexOf ( ';' , start ) ) >= 0 ) { components [ componentIndex ] = name . substring ( start , end ) ; componentIndex ++ ; start = end + 1 ; } components [ componentIndex ] = name . substring ( start ) ; StringBuilder newName = new StringBuilder ( 100 ) ; maybeAppendComponent ( components , 3 , newName ) ; maybeAppendComponent ( components , 1 , newName ) ; maybeAppendComponent ( components , 2 , newName ) ; maybeAppendComponent ( components , 0 , newName ) ; maybeAppendComponent ( components , 4 , newName ) ; list . set ( 0 , newName . toString ( ) . trim ( ) ) ; } } } | Formats name fields of the form Public ; John ; Q . ; Reverend ; III into a form like Reverend John Q . Public III . |
16,498 | byte [ ] getScaledRow ( int scale ) { byte [ ] output = new byte [ row . length * scale ] ; for ( int i = 0 ; i < output . length ; i ++ ) { output [ i ] = row [ i / scale ] ; } return output ; } | This function scales the row |
16,499 | static int applyMaskPenaltyRule4 ( ByteMatrix matrix ) { int numDarkCells = 0 ; byte [ ] [ ] array = matrix . getArray ( ) ; int width = matrix . getWidth ( ) ; int height = matrix . getHeight ( ) ; for ( int y = 0 ; y < height ; y ++ ) { byte [ ] arrayY = array [ y ] ; for ( int x = 0 ; x < width ; x ++ ) { if ( arrayY [ x ] == 1 ) { numDarkCells ++ ; } } } int numTotalCells = matrix . getHeight ( ) * matrix . getWidth ( ) ; int fivePercentVariances = Math . abs ( numDarkCells * 2 - numTotalCells ) * 10 / numTotalCells ; return fivePercentVariances * N4 ; } | Apply mask penalty rule 4 and return the penalty . Calculate the ratio of dark cells and give penalty if the ratio is far from 50% . It gives 10 penalty for 5% distance . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.