idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
10,900 | private String parseDestinationHeader ( final WebdavRequest req , final WebdavResponse resp ) throws IOException { String destinationPath = req . getHeader ( "Destination" ) ; if ( destinationPath == null ) { resp . sendError ( WebdavStatus . SC_BAD_REQUEST ) ; return null ; } destinationPath = RequestUtil . URLDecode ( destinationPath , "UTF8" ) ; final int protocolIndex = destinationPath . indexOf ( "://" ) ; if ( protocolIndex >= 0 ) { final int firstSeparator = destinationPath . indexOf ( "/" , protocolIndex + 4 ) ; if ( firstSeparator < 0 ) { destinationPath = "/" ; } else { destinationPath = destinationPath . substring ( firstSeparator ) ; } } else { final String hostName = req . getServerName ( ) ; if ( ( hostName != null ) && ( destinationPath . startsWith ( hostName ) ) ) { destinationPath = destinationPath . substring ( hostName . length ( ) ) ; } final int portIndex = destinationPath . indexOf ( ":" ) ; if ( portIndex >= 0 ) { destinationPath = destinationPath . substring ( portIndex ) ; } if ( destinationPath . startsWith ( ":" ) ) { final int firstSeparator = destinationPath . indexOf ( "/" ) ; if ( firstSeparator < 0 ) { destinationPath = "/" ; } else { destinationPath = destinationPath . substring ( firstSeparator ) ; } } } destinationPath = normalize ( destinationPath ) ; final String contextPath = req . getContextPath ( ) ; if ( ( contextPath != null ) && ( destinationPath . startsWith ( contextPath ) ) ) { destinationPath = destinationPath . substring ( contextPath . length ( ) ) ; } final String pathInfo = req . getPathInfo ( ) ; if ( pathInfo != null ) { final String servletPath = req . getServicePath ( ) ; if ( ( servletPath != null ) && ( destinationPath . startsWith ( servletPath ) ) ) { destinationPath = destinationPath . substring ( servletPath . length ( ) ) ; } } return destinationPath ; } | Parses and normalizes the destination header . |
10,901 | public static < F extends Fragment > FragmentBundler < F > create ( F fragment ) { return new FragmentBundler < F > ( fragment ) ; } | Constructs a FragmentBundler for the provided Fragment instance |
10,902 | public static < F extends Fragment > FragmentBundler < F > create ( Class < F > klass ) { try { return create ( klass . newInstance ( ) ) ; } catch ( InstantiationException e ) { throw new IllegalArgumentException ( "Class must have a no-arguments constructor." ) ; } catch ( IllegalAccessException e ) { throw new IllegalArgumentException ( "Class must have a no-arguments constructor." ) ; } } | Constructs a FragmentBundler for the provided Fragment class |
10,903 | public void init ( ) { String fileName = null ; try { fileName = System . getProperty ( SYSTEM_PROPERTY ) ; if ( fileName == null ) { LOG . info ( "User file configuration not provided, reading default file." ) ; readConfiguration ( getClass ( ) . getResourceAsStream ( DEFAULT_FILE_NAME ) ) ; } else { try { FileInputStream stream = new FileInputStream ( fileName ) ; LOG . info ( "Reading configuration file: " + fileName ) ; readConfiguration ( stream ) ; } catch ( FileNotFoundException fnfe ) { LOG . info ( "Error using user provided configuration file, reading default file." ) ; readConfiguration ( getClass ( ) . getResourceAsStream ( DEFAULT_FILE_NAME ) ) ; } } } catch ( IOException ioe ) { LOG . error ( "Error reading provided " + fileName + " file" ) ; } } | Initializes configuration . |
10,904 | @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) public void addField ( String key , Object value ) { if ( this . body == null || Map . class . isAssignableFrom ( this . body . getClass ( ) ) == false ) { this . body = Maps . newLinkedHashMap ( ) ; } ( ( Map ) this . body ) . put ( key , value ) ; } | Add field to message body . |
10,905 | @ SuppressWarnings ( "rawtypes" ) public Object getField ( String key ) { if ( this . body == null || Map . class . isAssignableFrom ( this . body . getClass ( ) ) == false ) { return null ; } return ( ( Map ) this . body ) . get ( key ) ; } | Get field from message body . |
10,906 | public void writeProperty ( String name , String value ) { writeElement ( name , OPENING ) ; _buffer . append ( value ) ; writeElement ( name , CLOSING ) ; } | Write property to the XML . |
10,907 | public void writeData ( String data ) { _buffer . append ( "<![CDATA[" ) ; _buffer . append ( data ) ; _buffer . append ( "]]>" ) ; } | Write data . |
10,908 | public void processResponseEvent ( FireableEventType eventType , ResponseEvent event , XCAPResourceAdaptorActivityHandle handle ) { if ( tracer . isFineEnabled ( ) ) { tracer . fine ( "NEW RESPONSE EVENT" ) ; } try { sleeEndpoint . fireEvent ( handle , eventType , event , null , null ) ; } catch ( Exception e ) { tracer . severe ( "unable to fire event" , e ) ; } } | Receives an Event and sends it to the SLEE |
10,909 | protected void run ( List < TestDescription > selectedTests ) { mRunning = true ; mTotalTestCount = selectedTests . size ( ) ; mRunnerBean . run ( this , selectedTests ) ; } | Start running the tests |
10,910 | protected void runSelected ( ) { List < TestDescription > selectedTests = getSelectedTests ( ) ; if ( selectedTests != null ) { List < TestDescription > selectedTestsIncludedLeafs = new ArrayList < > ( ) ; for ( TestDescription desc : selectedTests ) { includeAllLeafs ( desc , selectedTestsIncludedLeafs ) ; } run ( selectedTestsIncludedLeafs ) ; } } | Execute the selected tests |
10,911 | public static boolean isValid ( final String value ) { if ( value == null ) { return true ; } if ( value . length ( ) == 0 ) { return false ; } try { InternetAddress . parse ( value , false ) ; return true ; } catch ( final AddressException ex ) { return false ; } } | Check that a given string is a well - formed email address . |
10,912 | public BaseJsonBo setSubAttr ( String attrName , String dPath , Object value ) { if ( value == null ) { return removeSubAttr ( attrName , dPath ) ; } Lock lock = lockForWrite ( ) ; try { JsonNode attr = cacheJsonObjs . get ( attrName ) ; if ( attr == null ) { String [ ] paths = DPathUtils . splitDpath ( dPath ) ; if ( paths [ 0 ] . matches ( "^\\[(.*?)\\]$" ) ) { setAttribute ( attrName , "[]" ) ; } else { setAttribute ( attrName , "{}" ) ; } attr = cacheJsonObjs . get ( attrName ) ; } JacksonUtils . setValue ( attr , dPath , value , true ) ; return ( BaseJsonBo ) setAttribute ( attrName , SerializationUtils . toJsonString ( attr ) , false ) ; } finally { lock . unlock ( ) ; } } | Set a sub - attribute . |
10,913 | public BaseJsonBo removeSubAttr ( String attrName , String dPath ) { Lock lock = lockForWrite ( ) ; try { JsonNode attr = cacheJsonObjs . get ( attrName ) ; JacksonUtils . deleteValue ( attr , dPath ) ; return ( BaseJsonBo ) setAttribute ( attrName , SerializationUtils . toJsonString ( attr ) , false ) ; } finally { lock . unlock ( ) ; } } | Remove a sub - attribute . |
10,914 | public void storePassword ( String account , CharSequence password ) { ByteBuffer pwBuf = UTF_8 . encode ( CharBuffer . wrap ( password ) ) ; byte [ ] pwBytes = new byte [ pwBuf . remaining ( ) ] ; pwBuf . get ( pwBytes ) ; int errorCode = storePassword0 ( account . getBytes ( UTF_8 ) , pwBytes ) ; Arrays . fill ( pwBytes , ( byte ) 0x00 ) ; Arrays . fill ( pwBuf . array ( ) , ( byte ) 0x00 ) ; if ( errorCode != OSSTATUS_SUCCESS ) { throw new JniException ( "Failed to store password. Error code " + errorCode ) ; } } | Associates the specified password with the specified key in the system keychain . |
10,915 | public char [ ] loadPassword ( String account ) { byte [ ] pwBytes = loadPassword0 ( account . getBytes ( UTF_8 ) ) ; if ( pwBytes == null ) { return null ; } else { CharBuffer pwBuf = UTF_8 . decode ( ByteBuffer . wrap ( pwBytes ) ) ; char [ ] pw = new char [ pwBuf . remaining ( ) ] ; pwBuf . get ( pw ) ; Arrays . fill ( pwBytes , ( byte ) 0x00 ) ; Arrays . fill ( pwBuf . array ( ) , ( char ) 0x00 ) ; return pw ; } } | Loads the password associated with the specified key from the system keychain . |
10,916 | public boolean deletePassword ( String account ) { int errorCode = deletePassword0 ( account . getBytes ( UTF_8 ) ) ; if ( errorCode == OSSTATUS_SUCCESS ) { return true ; } else if ( errorCode == OSSTATUS_NOT_FOUND ) { return false ; } else { throw new JniException ( "Failed to delete password. Error code " + errorCode ) ; } } | Deletes the password associated with the specified key from the system keychain . |
10,917 | private void actualInitReflections ( ) { ConfigurationBuilder configurationBuilder = configurationBuilder ( ) . setScanners ( getScanners ( ) ) . setMetadataAdapter ( new MetadataAdapterInMemory ( ) ) ; InMemoryFactory factory = new InMemoryFactory ( ) ; for ( ClasspathAbstractContainer < ? > i : this . classpath . entries ( ) ) { String name = i . name ( ) ; try { configurationBuilder . addUrls ( factory . createInMemoryResource ( name ) ) ; } catch ( MalformedURLException e ) { throw new KernelException ( "Malformed URL Exception" , e ) ; } } urls . addAll ( configurationBuilder . getUrls ( ) ) ; reflections = new Reflections ( configurationBuilder ) ; } | Its too soon to create reflections in the constructor |
10,918 | private void executeLock ( final ITransaction transaction , final WebdavRequest req , final WebdavResponse resp ) throws LockFailedException , IOException , WebdavException { if ( _macLockRequest ) { LOG . trace ( "DoLock.execute() : do workaround for user agent '" + _userAgent + "'" ) ; doMacLockRequestWorkaround ( transaction , req , resp ) ; } else { if ( getLockInformation ( transaction , req , resp ) ) { final int depth = getDepth ( req ) ; final int lockDuration = getTimeout ( transaction , req ) ; boolean lockSuccess = false ; if ( _exclusive ) { lockSuccess = _resourceLocks . exclusiveLock ( transaction , _path , _lockOwner , depth , lockDuration ) ; } else { lockSuccess = _resourceLocks . sharedLock ( transaction , _path , _lockOwner , depth , lockDuration ) ; } if ( lockSuccess ) { final LockedObject lo = _resourceLocks . getLockedObjectByPath ( transaction , _path ) ; if ( lo != null ) { generateXMLReport ( transaction , resp , lo ) ; } else { resp . sendError ( SC_INTERNAL_SERVER_ERROR ) ; } } else { sendLockFailError ( transaction , req , resp ) ; throw new LockFailedException ( ) ; } } else { resp . setContentType ( "text/xml; charset=UTF-8" ) ; resp . sendError ( SC_BAD_REQUEST ) ; } } } | Executes the LOCK |
10,919 | private int getTimeout ( final ITransaction transaction , final WebdavRequest req ) { int lockDuration = DEFAULT_TIMEOUT ; String lockDurationStr = req . getHeader ( "Timeout" ) ; if ( lockDurationStr == null ) { lockDuration = DEFAULT_TIMEOUT ; } else { final int commaPos = lockDurationStr . indexOf ( ',' ) ; if ( commaPos != - 1 ) { lockDurationStr = lockDurationStr . substring ( 0 , commaPos ) ; } if ( lockDurationStr . startsWith ( "Second-" ) ) { lockDuration = new Integer ( lockDurationStr . substring ( 7 ) ) . intValue ( ) ; } else { if ( lockDurationStr . equalsIgnoreCase ( "infinity" ) ) { lockDuration = MAX_TIMEOUT ; } else { try { lockDuration = new Integer ( lockDurationStr ) . intValue ( ) ; } catch ( final NumberFormatException e ) { lockDuration = MAX_TIMEOUT ; } } } if ( lockDuration <= 0 ) { lockDuration = DEFAULT_TIMEOUT ; } if ( lockDuration > MAX_TIMEOUT ) { lockDuration = MAX_TIMEOUT ; } } return lockDuration ; } | Ties to read the timeout from request |
10,920 | private void generateXMLReport ( final ITransaction transaction , final WebdavResponse resp , final LockedObject lo ) throws IOException { final HashMap < String , String > namespaces = new HashMap < String , String > ( ) ; namespaces . put ( "DAV:" , "D" ) ; resp . setStatus ( SC_OK ) ; resp . setContentType ( "text/xml; charset=UTF-8" ) ; final XMLWriter generatedXML = new XMLWriter ( resp . getWriter ( ) , namespaces ) ; generatedXML . writeXMLHeader ( ) ; generatedXML . writeElement ( "DAV::prop" , XMLWriter . OPENING ) ; generatedXML . writeElement ( "DAV::lockdiscovery" , XMLWriter . OPENING ) ; generatedXML . writeElement ( "DAV::activelock" , XMLWriter . OPENING ) ; generatedXML . writeElement ( "DAV::locktype" , XMLWriter . OPENING ) ; generatedXML . writeProperty ( "DAV::" + _type ) ; generatedXML . writeElement ( "DAV::locktype" , XMLWriter . CLOSING ) ; generatedXML . writeElement ( "DAV::lockscope" , XMLWriter . OPENING ) ; if ( _exclusive ) { generatedXML . writeProperty ( "DAV::exclusive" ) ; } else { generatedXML . writeProperty ( "DAV::shared" ) ; } generatedXML . writeElement ( "DAV::lockscope" , XMLWriter . CLOSING ) ; final int depth = lo . getLockDepth ( ) ; generatedXML . writeElement ( "DAV::depth" , XMLWriter . OPENING ) ; if ( depth == INFINITY ) { generatedXML . writeText ( "Infinity" ) ; } else { generatedXML . writeText ( String . valueOf ( depth ) ) ; } generatedXML . writeElement ( "DAV::depth" , XMLWriter . CLOSING ) ; generatedXML . writeElement ( "DAV::owner" , XMLWriter . OPENING ) ; generatedXML . writeElement ( "DAV::href" , XMLWriter . OPENING ) ; generatedXML . writeText ( _lockOwner ) ; generatedXML . writeElement ( "DAV::href" , XMLWriter . CLOSING ) ; generatedXML . writeElement ( "DAV::owner" , XMLWriter . CLOSING ) ; final long timeout = lo . getTimeoutMillis ( ) ; generatedXML . writeElement ( "DAV::timeout" , XMLWriter . OPENING ) ; generatedXML . writeText ( "Second-" + timeout / 1000 ) ; generatedXML . writeElement ( "DAV::timeout" , XMLWriter . CLOSING ) ; final String lockToken = lo . getID ( ) ; generatedXML . writeElement ( "DAV::locktoken" , XMLWriter . OPENING ) ; generatedXML . writeElement ( "DAV::href" , XMLWriter . OPENING ) ; generatedXML . writeText ( "opaquelocktoken:" + lockToken ) ; generatedXML . writeElement ( "DAV::href" , XMLWriter . CLOSING ) ; generatedXML . writeElement ( "DAV::locktoken" , XMLWriter . CLOSING ) ; generatedXML . writeElement ( "DAV::activelock" , XMLWriter . CLOSING ) ; generatedXML . writeElement ( "DAV::lockdiscovery" , XMLWriter . CLOSING ) ; generatedXML . writeElement ( "DAV::prop" , XMLWriter . CLOSING ) ; resp . addHeader ( "Lock-Token" , "<opaquelocktoken:" + lockToken + ">" ) ; generatedXML . sendData ( ) ; } | Generates the response XML with all lock information |
10,921 | private void doMacLockRequestWorkaround ( final ITransaction transaction , final WebdavRequest req , final WebdavResponse resp ) throws LockFailedException , IOException { LockedObject lo ; final int depth = getDepth ( req ) ; int lockDuration = getTimeout ( transaction , req ) ; if ( lockDuration < 0 || lockDuration > MAX_TIMEOUT ) { lockDuration = DEFAULT_TIMEOUT ; } boolean lockSuccess = false ; lockSuccess = _resourceLocks . exclusiveLock ( transaction , _path , _lockOwner , depth , lockDuration ) ; if ( lockSuccess ) { lo = _resourceLocks . getLockedObjectByPath ( transaction , _path ) ; if ( lo != null ) { generateXMLReport ( transaction , resp , lo ) ; } else { resp . sendError ( SC_INTERNAL_SERVER_ERROR ) ; } } else { sendLockFailError ( transaction , req , resp ) ; } } | Executes the lock for a Mac OS Finder client |
10,922 | private void sendLockFailError ( final ITransaction transaction , final WebdavRequest req , final WebdavResponse resp ) throws IOException { final Hashtable < String , WebdavStatus > errorList = new Hashtable < String , WebdavStatus > ( ) ; errorList . put ( _path , SC_LOCKED ) ; sendReport ( req , resp , errorList ) ; } | Sends an error report to the client |
10,923 | protected void invalidateCache ( T bo , CacheInvalidationReason reason ) { final String cacheKey = cacheKey ( bo ) ; switch ( reason ) { case CREATE : case UPDATE : putToCache ( getCacheName ( ) , cacheKey , bo ) ; case DELETE : removeFromCache ( getCacheName ( ) , cacheKey ) ; } } | Invalidate a BO from cache . |
10,924 | protected DaoResult delete ( Connection conn , T bo ) { if ( bo == null ) { return new DaoResult ( DaoOperationStatus . NOT_FOUND ) ; } int numRows = execute ( conn , calcSqlDeleteOne ( bo ) , rowMapper . valuesForColumns ( bo , rowMapper . getPrimaryKeyColumns ( ) ) ) ; DaoResult result = numRows > 0 ? new DaoResult ( DaoOperationStatus . SUCCESSFUL , bo ) : new DaoResult ( DaoOperationStatus . NOT_FOUND ) ; if ( numRows > 0 ) { invalidateCache ( bo , CacheInvalidationReason . DELETE ) ; } return result ; } | Delete an existing BO from storage . |
10,925 | protected T get ( Connection conn , BoId id ) { if ( id == null || id . values == null || id . values . length == 0 ) { return null ; } final String cacheKey = cacheKey ( id ) ; T bo = getFromCache ( getCacheName ( ) , cacheKey , typeClass ) ; if ( bo == null ) { bo = executeSelectOne ( rowMapper , conn , calcSqlSelectOne ( id ) , id . values ) ; putToCache ( getCacheName ( ) , cacheKey , bo ) ; } return bo ; } | Fetch an existing BO from storage by id . |
10,926 | @ SuppressWarnings ( "unchecked" ) protected T [ ] get ( Connection conn , BoId ... idList ) { T [ ] result = ( T [ ] ) Array . newInstance ( typeClass , idList != null ? idList . length : 0 ) ; if ( idList != null ) { for ( int i = 0 ; i < idList . length ; i ++ ) { result [ i ] = get ( conn , idList [ i ] ) ; } } return result ; } | Fetch list of existing BOs from storage by id . |
10,927 | protected Stream < T > getAll ( Connection conn ) { return executeSelectAsStream ( rowMapper , conn , true , calcSqlSelectAll ( ) ) ; } | Fetch all existing BOs from storage and return the result as a stream . |
10,928 | protected DaoResult update ( Connection conn , T bo ) { if ( bo == null ) { return new DaoResult ( DaoOperationStatus . NOT_FOUND ) ; } Savepoint savepoint = null ; try { try { String [ ] bindColumns = ArrayUtils . addAll ( rowMapper . getUpdateColumns ( ) , rowMapper . getPrimaryKeyColumns ( ) ) ; String colChecksum = rowMapper . getChecksumColumn ( ) ; if ( ! StringUtils . isBlank ( colChecksum ) ) { bindColumns = ArrayUtils . add ( bindColumns , colChecksum ) ; } savepoint = conn . getAutoCommit ( ) ? null : conn . setSavepoint ( ) ; int numRows = execute ( conn , calcSqlUpdateOne ( bo ) , rowMapper . valuesForColumns ( bo , bindColumns ) ) ; DaoResult result = numRows > 0 ? new DaoResult ( DaoOperationStatus . SUCCESSFUL , bo ) : new DaoResult ( DaoOperationStatus . NOT_FOUND ) ; if ( numRows > 0 ) { invalidateCache ( bo , CacheInvalidationReason . UPDATE ) ; } return result ; } catch ( DuplicatedValueException dke ) { if ( savepoint != null ) { conn . rollback ( savepoint ) ; } return new DaoResult ( DaoOperationStatus . DUPLICATED_VALUE ) ; } } catch ( SQLException e ) { throw new DaoException ( e ) ; } } | Update an existing BO . |
10,929 | protected DaoResult createOrUpdate ( Connection conn , T bo ) { if ( bo == null ) { return null ; } DaoResult result = create ( conn , bo ) ; DaoOperationStatus status = result . getStatus ( ) ; if ( status == DaoOperationStatus . DUPLICATED_VALUE || status == DaoOperationStatus . DUPLICATED_UNIQUE ) { result = update ( conn , bo ) ; } return result ; } | Create a new BO or update an existing one . |
10,930 | protected DaoResult updateOrCreate ( Connection conn , T bo ) { if ( bo == null ) { return new DaoResult ( DaoOperationStatus . NOT_FOUND ) ; } DaoResult result = update ( conn , bo ) ; DaoOperationStatus status = result . getStatus ( ) ; if ( status == DaoOperationStatus . NOT_FOUND ) { result = create ( conn , bo ) ; } return result ; } | Update an existing BO or create a new one . |
10,931 | public synchronized static Bitmap load ( InputStream is , int width , int height ) { BitmapFactory . Options opt = null ; try { opt = new BitmapFactory . Options ( ) ; if ( width > 0 && height > 0 ) { if ( is . markSupported ( ) ) { is . mark ( is . available ( ) ) ; opt . inJustDecodeBounds = true ; BitmapFactory . decodeStream ( is , null , opt ) ; opt . inSampleSize = calculateInSampleSize ( opt , width , height ) ; is . reset ( ) ; } } opt . inJustDecodeBounds = false ; opt . inPurgeable = true ; opt . inInputShareable = true ; return BitmapFactory . decodeStream ( new FlushedInputStream ( is ) , null , opt ) ; } catch ( Exception e ) { Log . e ( TAG , "" , e ) ; return null ; } finally { if ( is != null ) { try { is . close ( ) ; } catch ( IOException e ) { System . out . print ( e . toString ( ) ) ; } } opt = null ; } } | BitmapFactory fails to decode the InputStream . |
10,932 | public static boolean writeToFile ( Bitmap bmp , String fileName ) { if ( bmp == null || StringUtils . isNullOrEmpty ( fileName ) ) return false ; FileOutputStream fos = null ; try { fos = new FileOutputStream ( fileName ) ; bmp . compress ( CompressFormat . PNG , 100 , fos ) ; fos . flush ( ) ; fos . close ( ) ; } catch ( Exception e ) { return false ; } finally { if ( fos != null ) { try { fos . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } return true ; } | write bitmap to file . |
10,933 | public static final boolean isValid ( final String value ) { if ( value == null ) { return true ; } if ( ( value . length ( ) < 8 ) || ( value . length ( ) > 20 ) ) { return false ; } return true ; } | Check that a given string is an allowed password . |
10,934 | private void doResource ( HttpServletRequest req , HttpServletResponse resp ) throws IOException { boolean success = true ; String resource = ( String ) req . getParameter ( "id" ) ; if ( ! isEmpty ( resource ) ) { if ( resource . endsWith ( ".js" ) ) { resp . setContentType ( "text/javascript" ) ; } else if ( resource . endsWith ( ".css" ) ) { resp . setContentType ( "text/css" ) ; } else if ( resource . endsWith ( ".html" ) ) { resp . setContentType ( "text/html" ) ; } else { resp . setContentType ( "text/plain" ) ; } String contents = resourceLoader . getResource ( resource , resourceReplacements ) ; if ( contents != null ) { if ( resourceCacheHours > 0 ) { Calendar c = Calendar . getInstance ( ) ; c . add ( Calendar . HOUR , resourceCacheHours ) ; resp . setHeader ( "Cache-Control" , "public, must-revalidate" ) ; resp . setHeader ( "Expires" , new SimpleDateFormat ( "EEE, dd MMM yyyy HH:mm:ss zzz" ) . format ( c . getTime ( ) ) ) ; } else { resp . setHeader ( "Cache-Control" , "no-cache" ) ; } PrintWriter w = resp . getWriter ( ) ; w . print ( contents ) ; } else { success = false ; } } if ( ! success ) { resp . sendError ( 404 ) ; } } | Serve one of the static resources for the profiler UI . |
10,935 | private void doResults ( HttpServletRequest req , HttpServletResponse resp ) throws IOException , JsonGenerationException , JsonMappingException { Map < String , Object > result = new HashMap < String , Object > ( ) ; String requestIds = req . getParameter ( "ids" ) ; if ( ! isEmpty ( requestIds ) ) { List < Map < String , Object > > requests = new ArrayList < Map < String , Object > > ( ) ; for ( String requestId : requestIds . split ( "," ) ) { requestId = requestId . trim ( ) ; @ SuppressWarnings ( "unchecked" ) Map < String , Object > requestData = ( Map < String , Object > ) ms . get ( String . format ( MiniProfilerFilter . MEMCACHE_KEY_FORMAT_STRING , requestId ) ) ; if ( requestData != null ) { Map < String , Object > request = new HashMap < String , Object > ( ) ; request . put ( "id" , requestId ) ; request . put ( "redirect" , requestData . get ( "redirect" ) ) ; request . put ( "requestURL" , requestData . get ( "requestURL" ) ) ; request . put ( "timestamp" , requestData . get ( "timestamp" ) ) ; request . put ( "profile" , requestData . get ( "profile" ) ) ; if ( requestData . containsKey ( "appstatsId" ) ) { Map < String , Object > appstatsMap = MiniProfilerAppstats . getAppstatsDataFor ( ( String ) requestData . get ( "appstatsId" ) , maxStackFrames ) ; request . put ( "appstats" , appstatsMap != null ? appstatsMap : null ) ; } else { request . put ( "appstats" , null ) ; } requests . add ( request ) ; } } result . put ( "ok" , true ) ; result . put ( "requests" , requests ) ; } else { result . put ( "ok" , false ) ; } resp . setContentType ( "application/json" ) ; resp . setHeader ( "Cache-Control" , "no-cache" ) ; ObjectMapper jsonMapper = new ObjectMapper ( ) ; jsonMapper . writeValue ( resp . getOutputStream ( ) , result ) ; } | Generate the results for a set of requests in JSON format . |
10,936 | public static UrlBuilder getUrlBuilder ( final URL baseUrl ) { URL url = null ; try { url = new URL ( decode ( requireNonNull ( baseUrl ) . toString ( ) , defaultCharset ( ) . name ( ) ) ) ; } catch ( MalformedURLException | UnsupportedEncodingException e ) { throw new IllegalArgumentException ( new StringBuilder ( "Cannot create a URI from the provided URL: " ) . append ( baseUrl != null ? baseUrl . toString ( ) : "null" ) . toString ( ) , e ) ; } return new UrlBuilder ( url ) ; } | Convenient factory method that creates a new instance of this class . |
10,937 | public static Config loadStormConfig ( File targetFile ) throws IOException { Map < String , Object > yamlConfig = readYaml ( targetFile ) ; Config stormConf = convertYamlToStormConf ( yamlConfig ) ; if ( stormConf . containsKey ( INIT_CONFIG_KEY ) == false ) { String absolutePath = targetFile . getAbsolutePath ( ) ; stormConf . put ( INIT_CONFIG_KEY , absolutePath ) ; } return stormConf ; } | Generate storm config object from the yaml file at specified file . |
10,938 | public static Config convertYamlToStormConf ( Map < String , Object > yamlConf ) { Config stormConf = new Config ( ) ; for ( Entry < String , Object > targetConfigEntry : yamlConf . entrySet ( ) ) { stormConf . put ( targetConfigEntry . getKey ( ) , targetConfigEntry . getValue ( ) ) ; } return stormConf ; } | Convert config read from yaml file config to storm config object . |
10,939 | public static Map < String , Object > readYaml ( String filePath ) throws IOException { File targetFile = new File ( filePath ) ; Map < String , Object > configObject = readYaml ( targetFile ) ; return configObject ; } | Read yaml config object from the yaml file at specified path . |
10,940 | @ SuppressWarnings ( "unchecked" ) public static Map < String , Object > readYaml ( File targetFile ) throws IOException { Map < String , Object > configObject = null ; Yaml yaml = new Yaml ( ) ; InputStream inputStream = null ; InputStreamReader steamReader = null ; try { inputStream = new FileInputStream ( targetFile ) ; steamReader = new InputStreamReader ( inputStream , "UTF-8" ) ; configObject = ( Map < String , Object > ) yaml . load ( steamReader ) ; } catch ( ScannerException ex ) { throw new IOException ( ex ) ; } finally { IOUtils . closeQuietly ( inputStream ) ; } return configObject ; } | Read yaml config object from the yaml file at specified file . |
10,941 | public void doFilter ( ServletRequest sReq , ServletResponse sRes , FilterChain chain ) throws IOException , ServletException { HttpServletRequest req = ( HttpServletRequest ) sReq ; HttpServletResponse res = ( HttpServletResponse ) sRes ; if ( shouldProfile ( req . getRequestURI ( ) ) ) { String queryString = req . getQueryString ( ) ; String requestId = String . valueOf ( counter . incrementAndGet ( ) ) ; String redirectRequestIds = null ; if ( ! isEmpty ( queryString ) ) { String [ ] parts = queryString . split ( "&" ) ; for ( String part : parts ) { String [ ] nameValue = part . split ( "=" ) ; if ( REQUEST_ID_PARAM_REDIRECT . equals ( nameValue [ 0 ] ) ) { redirectRequestIds = nameValue [ 1 ] ; break ; } } } req . setAttribute ( REQUEST_ID_ATTRIBUTE , requestId ) ; res . addHeader ( REQUEST_ID_HEADER , redirectRequestIds != null ? redirectRequestIds + "," + requestId : requestId ) ; addIncludes ( req ) ; ResponseWrapper resWrapper = new ResponseWrapper ( res , requestId , redirectRequestIds ) ; MiniProfiler . Profile profile = null ; long startTime = System . currentTimeMillis ( ) ; MiniProfiler . start ( ) ; try { chain . doFilter ( sReq , resWrapper ) ; } finally { profile = MiniProfiler . stop ( ) ; } Map < String , Object > requestData = new HashMap < String , Object > ( ) ; requestData . put ( "requestURL" , req . getRequestURI ( ) + ( ( req . getQueryString ( ) != null ) ? "?" + req . getQueryString ( ) : "" ) ) ; requestData . put ( "timestamp" , startTime ) ; requestData . put ( "redirect" , resWrapper . getDidRedirect ( ) ) ; String appstatsId = resWrapper . getAppstatsId ( ) ; if ( appstatsId != null ) { requestData . put ( "appstatsId" , appstatsId ) ; } requestData . put ( "profile" , profile ) ; ms . put ( String . format ( MEMCACHE_KEY_FORMAT_STRING , requestId ) , requestData , Expiration . byDeltaSeconds ( dataExpiry ) ) ; } else { chain . doFilter ( sReq , sRes ) ; } } | If profiling is supposed to occur for the current request profile the request . Otherwise this filter does nothing . |
10,942 | public boolean shouldProfile ( String url ) { if ( url . startsWith ( servletURL ) ) { return false ; } if ( ! restrictedURLs . isEmpty ( ) ) { boolean matches = false ; for ( Pattern p : restrictedURLs ) { if ( p . matcher ( url ) . find ( ) ) { matches = true ; } } if ( ! matches ) { return false ; } } if ( restricted ) { if ( us . isUserLoggedIn ( ) ) { if ( restrictedToAdmins && ! us . isUserAdmin ( ) ) { return false ; } if ( ! restrictedEmails . isEmpty ( ) && ! restrictedEmails . contains ( us . getCurrentUser ( ) . getEmail ( ) ) ) { return false ; } } else { return false ; } } return true ; } | Whether the specified URL should be profiled given the current configuration of the filter . |
10,943 | public static String getShortDateString ( long time , String format ) { if ( format == null || format . isEmpty ( ) ) { format = "yyyy-MM-dd" ; } SimpleDateFormat smpf = new SimpleDateFormat ( format ) ; return smpf . format ( new Date ( time ) ) ; } | get formated date String |
10,944 | public void onMessage ( StreamMessage received ) { if ( this . reloadConfig && this . watcher != null ) { Map < String , Object > reloadedConfig = null ; try { reloadedConfig = this . watcher . readIfUpdated ( ) ; } catch ( IOException ex ) { String logFormat = "Config file reload failed. Skip reload config." ; logger . warn ( logFormat , ex ) ; } if ( reloadedConfig != null ) { onUpdate ( reloadedConfig ) ; } } this . executingKeyHistory = received . getHeader ( ) . getHistory ( ) ; this . responsed = false ; try { onExecute ( received ) ; } finally { clearExecuteStatus ( ) ; } if ( this . responsed == false ) { super . ack ( ) ; } } | Execute when receive message . |
10,945 | protected KeyHistory createKeyRecorededHistory ( KeyHistory history , Object messageKey ) { KeyHistory result = null ; if ( history == null ) { result = new KeyHistory ( ) ; } else { result = history . createDeepCopy ( ) ; } result . addKey ( messageKey . toString ( ) ) ; return result ; } | Create keyhistory from original key history and current message key . |
10,946 | public static CommandResult execCommand ( String command , boolean isRoot ) { return execCommand ( new String [ ] { command } , isRoot , true ) ; } | execute shell command default return result msg |
10,947 | public static CommandResult execCommand ( String command , boolean isRoot , boolean isNeedResultMsg ) { return execCommand ( new String [ ] { command } , isRoot , isNeedResultMsg ) ; } | execute shell command |
10,948 | protected void invalidateCacheEntry ( String spaceId , String key ) { if ( isCacheEnabled ( ) ) { removeFromCache ( getCacheName ( ) , calcCacheKey ( spaceId , key ) ) ; } } | Invalidate a cache entry . |
10,949 | protected void invalidateCacheEntry ( String spaceId , String key , Object data ) { if ( isCacheEnabled ( ) ) { putToCache ( getCacheName ( ) , calcCacheKey ( spaceId , key ) , data ) ; } } | Invalidate a cache entry due to updated content . |
10,950 | @ SuppressWarnings ( "rawtypes" ) public static Class inferParameterClass ( Class clazz , String methodName ) { Method [ ] methods = clazz . getMethods ( ) ; for ( Method method : methods ) { if ( method . getName ( ) . equals ( methodName ) && ! method . isBridge ( ) ) { Type [ ] types = method . getGenericParameterTypes ( ) ; for ( Type type : types ) { if ( type instanceof Class && ! ( ( Class ) type ) . isInterface ( ) ) { return ( ( Class ) type ) ; } } } } return null ; } | Given a concrete class and a method name it tries to infer the Class of the first parameter of the method |
10,951 | public static boolean check ( Context context , WebView mWebView , boolean showInstall ) { if ( context == null ) return false ; boolean flashPluginExist = isPluginExist ( context ) ; if ( mWebView != null ) { if ( ! flashPluginExist && showInstall ) { mWebView . addJavascriptInterface ( new AndroidBridge ( context ) , "android" ) ; String content = "<html>\n" + "<head></head>\n" + "<body>\n" + "<br/><br/>\n" + "\n" + "<h3>Sorry, We have found that you haven't installed adobe flash player's plugin!</h3>\n" + "\n" + "<p>\n" + "<h4>\n" + " You can click <a href=\"#\" onclick=\"window.android.goMarket()\"> <b> here</b></a> to\n" + " install it.</h4>\n" + "</p>\n" + "</body>\n" + "</html>\n" ; mWebView . loadData ( content , "text/html" , "UTF-8" ) ; } } return flashPluginExist ; } | check whether the flash can play or not . |
10,952 | private static String encodeBase64 ( final byte [ ] buffer ) { final int l = buffer . length ; final char [ ] out = new char [ l << 1 ] ; int j = 0 ; for ( int i = 0 ; i < l ; i ++ ) { out [ j ++ ] = DIGITS [ ( 0xF0 & buffer [ i ] ) >>> 4 ] ; out [ j ++ ] = DIGITS [ 0x0F & buffer [ i ] ] ; } return String . copyValueOf ( out ) ; } | Encodes a byte array base64 . |
10,953 | private static String createSecureRandom ( ) { try { final String no = "" + SECURE_RANDOM . nextInt ( ) ; final MessageDigest md = MessageDigest . getInstance ( "SHA-1" ) ; final byte [ ] digest = md . digest ( no . getBytes ( ) ) ; return encodeBase64 ( digest ) ; } catch ( final NoSuchAlgorithmException ex ) { throw new RuntimeException ( ex ) ; } } | Creates a encoded secure random string . |
10,954 | protected Query buildQuery ( String spaceId , String key ) { BooleanQuery . Builder builder = new BooleanQuery . Builder ( ) ; if ( ! StringUtils . isBlank ( spaceId ) ) { builder . add ( new TermQuery ( new Term ( FIELD_SPACE_ID , spaceId . trim ( ) ) ) , Occur . MUST ) ; } if ( ! StringUtils . isBlank ( key ) ) { builder . add ( new TermQuery ( new Term ( FIELD_KEY , key . trim ( ) ) ) , Occur . MUST ) ; } return builder . build ( ) ; } | Build query to match entry s space - id and key . |
10,955 | protected long doCount ( String spaceId ) throws IOException { TopDocs result = getIndexSearcher ( ) . search ( buildQuery ( spaceId , null ) , 1 ) ; return result != null ? result . totalHits : - 1 ; } | Count number of documents within a space . |
10,956 | public static boolean isValid ( final String value ) { if ( value == null ) { return true ; } if ( value . length ( ) == 0 ) { return false ; } final int space = value . indexOf ( ' ' ) ; if ( space == - 1 ) { return false ; } final String amount = value . substring ( 0 , space ) ; if ( ! ( amount . matches ( DECIMAL ) || amount . matches ( INTEGER ) ) ) { return false ; } final String currencyCode = value . substring ( space + 1 ) ; try { Currency . getInstance ( currencyCode ) ; } catch ( RuntimeException ex ) { return false ; } return true ; } | Check that a given string is a well - formed currency amount . |
10,957 | public final List < Change > diff ( final HourRanges toOther ) { ensureSingleDayOnly ( "from" , this ) ; ensureSingleDayOnly ( "to" , toOther ) ; final BitSet thisMinutes = this . toMinutes ( ) ; final BitSet otherMinutes = toOther . toMinutes ( ) ; final BitSet addedMinutes = new BitSet ( 1440 ) ; final BitSet removedMinutes = new BitSet ( 1440 ) ; for ( int i = 0 ; i < 1440 ; i ++ ) { if ( thisMinutes . get ( i ) && ! otherMinutes . get ( i ) ) { removedMinutes . set ( i ) ; } if ( ! thisMinutes . get ( i ) && otherMinutes . get ( i ) ) { addedMinutes . set ( i ) ; } } final List < Change > changes = new ArrayList < > ( ) ; if ( ! removedMinutes . isEmpty ( ) ) { final HourRanges removed = HourRanges . valueOf ( removedMinutes ) ; for ( final HourRange hr : removed ) { changes . add ( new Change ( ChangeType . REMOVED , hr ) ) ; } } if ( ! addedMinutes . isEmpty ( ) ) { final HourRanges added = HourRanges . valueOf ( addedMinutes ) ; for ( final HourRange hr : added ) { changes . add ( new Change ( ChangeType . ADDED , hr ) ) ; } } return changes ; } | Returns the difference when changing this opening hours to the other one . |
10,958 | public final HourRanges compress ( ) { final List < HourRanges > normalized = normalize ( ) ; if ( normalized . size ( ) == 1 ) { return valueOf ( normalized . get ( 0 ) . toMinutes ( ) ) ; } else if ( normalized . size ( ) == 2 ) { final HourRanges firstDay = valueOf ( normalized . get ( 0 ) . toMinutes ( ) ) ; final HourRanges secondDay = normalized . get ( 1 ) ; if ( secondDay . ranges . size ( ) != 1 ) { throw new IllegalStateException ( "Expected exactly 1 hour range for the seond day, but was " + secondDay . ranges . size ( ) + ": " + secondDay ) ; } final HourRange seondDayHR = secondDay . ranges . get ( 0 ) ; final List < HourRange > newRanges = new ArrayList < > ( ) ; int lastIdx = 0 ; if ( firstDay . ranges . size ( ) > 1 ) { lastIdx = firstDay . ranges . size ( ) - 1 ; newRanges . addAll ( firstDay . ranges . subList ( 0 , lastIdx ) ) ; } final HourRange firstDayHR = firstDay . ranges . get ( lastIdx ) ; newRanges . add ( firstDayHR . joinWithNextDay ( seondDayHR ) ) ; return new HourRanges ( newRanges . toArray ( new HourRange [ newRanges . size ( ) ] ) ) ; } else { throw new IllegalStateException ( "Normalized hour ranges returned an unexpected number of elements (" + normalized . size ( ) + "): " + normalized ) ; } } | Returns a compressed version of the |
10,959 | public static File resolve ( Class < ? > clazz , String path ) { URL url = clazz . getResource ( path ) ; if ( url == null ) { return null ; } File result ; try { result = Paths . get ( url . toURI ( ) ) . toFile ( ) ; } catch ( URISyntaxException ex ) { return null ; } return result ; } | Return target file path from class and resource s path . |
10,960 | public static Class < ? > resolveCaller ( ) { Class < ? > callerClass = null ; StackTraceElement [ ] stackTraces = Thread . currentThread ( ) . getStackTrace ( ) ; int stackSize = stackTraces . length ; for ( int stackIndex = 2 ; stackIndex < stackSize ; stackIndex ++ ) { StackTraceElement stackTrace = stackTraces [ stackIndex ] ; String callerClassName = stackTrace . getClassName ( ) ; if ( StringUtils . equals ( ResourceResolver . class . getName ( ) , callerClassName ) == false ) { try { callerClass = Class . forName ( callerClassName ) ; break ; } catch ( ClassNotFoundException ex ) { return null ; } } } return callerClass ; } | Return caller class calling this class s method . |
10,961 | protected String getCSS ( ) { String retVal = "body {\n" + " font-family: Arial, Helvetica, sans-serif;\n" + "}\n" + "h1 {\n" + " font-size: 1.5em;\n" + "}\n" + "th {\n" + " background-color: #9DACBF;\n" + "}\n" + "table {\n" + " border-top-style: solid;\n" + " border-right-style: solid;\n" + " border-bottom-style: solid;\n" + " border-left-style: solid;\n" + "}\n" + "td {\n" + " margin: 0px;\n" + " padding-top: 2px;\n" + " padding-right: 5px;\n" + " padding-bottom: 2px;\n" + " padding-left: 5px;\n" + "}\n" + "tr.even {\n" + " background-color: #CCCCCC;\n" + "}\n" + "tr.odd {\n" + " background-color: #FFFFFF;\n" + "}\n" + "" ; try { final ClassLoader cl = getClass ( ) . getClassLoader ( ) ; final InputStream iStream = cl . getResourceAsStream ( "webdav.css" ) ; if ( iStream != null ) { final StringBuilder out = new StringBuilder ( ) ; final byte [ ] b = new byte [ 4096 ] ; for ( int n ; ( n = iStream . read ( b ) ) != - 1 ; ) { out . append ( new String ( b , 0 , n ) ) ; } retVal = out . toString ( ) ; } } catch ( final Exception ex ) { LOG . error ( "Error in reading webdav.css" , ex ) ; } return retVal ; } | Return the CSS styles used to display the HTML representation of the webdav content . |
10,962 | public DayOfTheWeek next ( ) { if ( this == PH ) { return null ; } final int nextId = id + 1 ; if ( nextId == PH . id ) { return MON ; } for ( final DayOfTheWeek dow : ALL ) { if ( dow . id == nextId ) { return dow ; } } throw new IllegalStateException ( "Wasn't able to find next day for: " + this ) ; } | Returns the next day . |
10,963 | public DayOfTheWeek previous ( ) { if ( this == PH ) { return null ; } final int nextId = id - 1 ; for ( final DayOfTheWeek dow : ALL ) { if ( dow . id == nextId ) { return dow ; } } return SUN ; } | Returns the previous day . |
10,964 | public static boolean isValid ( final String dayOfTheWeek ) { if ( dayOfTheWeek == null ) { return true ; } for ( final DayOfTheWeek dow : ALL ) { if ( dow . value . equalsIgnoreCase ( dayOfTheWeek ) ) { return true ; } } return false ; } | Verifies if the string is a valid dayOfTheWeek . |
10,965 | public static DayOfTheWeek valueOf ( final DayOfWeek dayOfWeek ) { if ( dayOfWeek == null ) { return null ; } final int value = dayOfWeek . getValue ( ) ; for ( final DayOfTheWeek dow : ALL ) { if ( value == dow . id ) { return dow ; } } throw new IllegalArgumentException ( "Unknown day week: " + dayOfWeek ) ; } | Converts the instance into java time instance . |
10,966 | public static final WingsEndpoint getEndpoint ( Class < ? extends WingsEndpoint > endpointClazz ) throws IllegalStateException { if ( ! sIsInitialized ) { throw new IllegalStateException ( "Wings must be initialized. See Wings#init()." ) ; } WingsEndpoint selectedEndpoint = null ; for ( WingsEndpoint endpoint : sEndpoints ) { if ( endpointClazz . isInstance ( endpoint ) ) { selectedEndpoint = endpoint ; break ; } } return selectedEndpoint ; } | Gets the instance of a specific endpoint that Wings can share to . |
10,967 | public static void unsubscribe ( Object object ) throws IllegalStateException { if ( ! sIsInitialized ) { throw new IllegalStateException ( "Wings must be initialized. See Wings#init()." ) ; } WingsInjector . getBus ( ) . unregister ( object ) ; } | Unsubscribes to link state changes of the endpoints . |
10,968 | public static boolean share ( String filePath , Class < ? extends WingsEndpoint > endpointClazz ) throws IllegalStateException { if ( ! sIsInitialized ) { throw new IllegalStateException ( "Wings must be initialized. See Wings#init()." ) ; } WingsEndpoint endpoint = Wings . getEndpoint ( endpointClazz ) ; if ( endpoint != null ) { WingsEndpoint . LinkInfo linkInfo = endpoint . getLinkInfo ( ) ; if ( linkInfo != null && WingsInjector . getDatabase ( ) . createShareRequest ( filePath , new Destination ( linkInfo . mDestinationId , endpoint . getEndpointId ( ) ) ) ) { WingsService . startWakefulService ( WingsInjector . getApplicationContext ( ) ) ; return true ; } } return false ; } | Shares an image to the specified endpoint . The client is responsible for ensuring that the file exists and the endpoint is linked . |
10,969 | private static Consumer < ByteBuffer > unmapper ( ) { final Lookup lookup = lookup ( ) ; try { final Class < ? > unsafeClass = Class . forName ( "sun.misc.Unsafe" ) ; final MethodHandle unmapper = lookup . findVirtual ( unsafeClass , "invokeCleaner" , methodType ( void . class , ByteBuffer . class ) ) ; final Field f = unsafeClass . getDeclaredField ( "theUnsafe" ) ; f . setAccessible ( true ) ; final Object theUnsafe = f . get ( null ) ; return newBufferCleaner ( ByteBuffer . class , unmapper . bindTo ( theUnsafe ) ) ; } catch ( SecurityException se ) { LOG . error ( "Unmapping is not supported because of missing permissions. Please grant at least the following permissions: RuntimePermission(\"accessClassInPackage.sun.misc\") " + " and ReflectPermission(\"suppressAccessChecks\")" , se ) ; } catch ( ReflectiveOperationException | RuntimeException e ) { LOG . error ( "Unmapping is not supported." , e ) ; } return null ; } | This is adapted from org . apache . lucene . store . MMapDirectory |
10,970 | public Peer addPeer ( String url , String pem ) { Peer peer = new Peer ( url , pem , this ) ; this . peers . add ( peer ) ; return peer ; } | Add a peer given an endpoint specification . |
10,971 | public void setMemberServicesUrl ( String url , String pem ) throws CertificateException { this . setMemberServices ( new MemberServicesImpl ( url , pem ) ) ; } | Set the member services URL |
10,972 | public void setMemberServices ( MemberServices memberServices ) { this . memberServices = memberServices ; if ( memberServices instanceof MemberServicesImpl ) { this . cryptoPrimitives = ( ( MemberServicesImpl ) memberServices ) . getCrypto ( ) ; } } | Set the member service |
10,973 | public void eventHubConnect ( String peerUrl , String pem ) { this . eventHub . setPeerAddr ( peerUrl , pem ) ; this . eventHub . connect ( ) ; } | Set and connect to the peer to be used as the event source . |
10,974 | public Member getMember ( String name ) { if ( null == keyValStore ) throw new RuntimeException ( "No key value store was found. You must first call Chain.setKeyValStore" ) ; if ( null == memberServices ) throw new RuntimeException ( "No member services was found. You must first call Chain.setMemberServices or Chain.setMemberServicesUrl" ) ; Member member = ( Member ) members . get ( name ) ; if ( null != member ) return member ; member = new Member ( name , this ) ; member . restoreState ( ) ; return member ; } | Get the member with a given name |
10,975 | public Member register ( RegistrationRequest registrationRequest ) throws RegistrationException { Member member = getMember ( registrationRequest . getEnrollmentID ( ) ) ; member . register ( registrationRequest ) ; return member ; } | Register a user or other member type with the chain . |
10,976 | public Member enroll ( String name , String secret ) throws EnrollmentException { Member member = getMember ( name ) ; member . enroll ( secret ) ; members . put ( name , member ) ; return member ; } | Enroll a user or other identity which has already been registered . |
10,977 | public Member registerAndEnroll ( RegistrationRequest registrationRequest ) throws RegistrationException , EnrollmentException { Member member = getMember ( registrationRequest . getEnrollmentID ( ) ) ; member . registerAndEnroll ( registrationRequest ) ; return member ; } | Register and enroll a user or other member type . This assumes that a registrar with sufficient privileges has been set . |
10,978 | public Response sendTransaction ( Transaction tx ) { if ( this . peers . isEmpty ( ) ) { throw new NoValidPeerException ( String . format ( "chain %s has no peers" , getName ( ) ) ) ; } for ( Peer peer : peers ) { try { return peer . sendTransaction ( tx ) ; } catch ( PeerException exp ) { logger . info ( String . format ( "Failed sending transaction to peer:%s" , exp . getMessage ( ) ) ) ; } } throw new RuntimeException ( "No peer available to respond" ) ; } | Send a transaction to a peer . |
10,979 | protected Context getContext ( ) { if ( act != null ) { return act ; } if ( root != null ) { return root . getContext ( ) ; } return context ; } | Return the context of activity or view . |
10,980 | public void confirm ( final int title , final int message , final DialogInterface . OnClickListener onClickListener ) { final AlertDialog . Builder builder = new AlertDialog . Builder ( getContext ( ) ) ; builder . setTitle ( title ) . setIcon ( android . R . drawable . ic_dialog_info ) . setMessage ( message ) ; builder . setPositiveButton ( android . R . string . ok , new DialogInterface . OnClickListener ( ) { public void onClick ( final DialogInterface dialog , final int which ) { if ( onClickListener != null ) { onClickListener . onClick ( dialog , which ) ; } } } ) ; builder . setNegativeButton ( android . R . string . cancel , new DialogInterface . OnClickListener ( ) { public void onClick ( final DialogInterface dialog , final int which ) { if ( onClickListener != null ) { onClickListener . onClick ( dialog , which ) ; } } } ) ; builder . show ( ) ; } | Open a confirm dialog with title and message |
10,981 | public void dialog ( final int title , int list , DialogInterface . OnClickListener listener ) { AlertDialog . Builder builder = new AlertDialog . Builder ( getContext ( ) ) ; builder . setTitle ( title ) . setItems ( list , listener ) ; builder . create ( ) . show ( ) ; } | Open a dialog with single choice list |
10,982 | private CocoQuery CleanAllTask ( ) { for ( final CocoTask < ? > reference : taskpool . values ( ) ) { if ( reference != null ) { reference . cancel ( ) ; } } return this ; } | Cancle all the task in pool |
10,983 | public void startActivityForResult ( Class clz , int requestCode ) { act . startActivityForResult ( new Intent ( getContext ( ) , clz ) , requestCode ) ; } | Launch an activity for which you would like a result when it finished |
10,984 | public void initNames ( ) { localInitialize = true ; DateFormatSymbols dateFormatSymbols = new DateFormatSymbols ( locale ) ; String [ ] monthNames = dateFormatSymbols . getMonths ( ) ; if ( comboBox . getItemCount ( ) == 12 ) { comboBox . removeAllItems ( ) ; } for ( int i = 0 ; i < 12 ; i ++ ) { comboBox . addItem ( monthNames [ i ] ) ; } localInitialize = false ; comboBox . setSelectedIndex ( month ) ; } | Initializes the locale specific month names . |
10,985 | public void stateChanged ( ChangeEvent e ) { SpinnerNumberModel model = ( SpinnerNumberModel ) ( ( JSpinner ) e . getSource ( ) ) . getModel ( ) ; int value = model . getNumber ( ) . intValue ( ) ; boolean increase = ( value > oldSpinnerValue ) ? true : false ; oldSpinnerValue = value ; int month = getMonth ( ) ; if ( increase ) { month += 1 ; if ( month == 12 ) { month = 0 ; if ( yearChooser != null ) { int year = yearChooser . getYear ( ) ; year += 1 ; yearChooser . setYear ( year ) ; } } } else { month -= 1 ; if ( month == - 1 ) { month = 11 ; if ( yearChooser != null ) { int year = yearChooser . getYear ( ) ; year -= 1 ; yearChooser . setYear ( year ) ; } } } setMonth ( month ) ; } | Is invoked if the state of the spnner changes . |
10,986 | public void itemStateChanged ( ItemEvent e ) { if ( e . getStateChange ( ) == ItemEvent . SELECTED ) { int index = comboBox . getSelectedIndex ( ) ; if ( ( index >= 0 ) && ( index != month ) ) { setMonth ( index , false ) ; } } } | The ItemListener for the months . |
10,987 | private void setMonth ( int newMonth , boolean select ) { if ( ! initialized || localInitialize ) { return ; } int oldMonth = month ; month = newMonth ; if ( select ) { comboBox . setSelectedIndex ( month ) ; } if ( dayChooser != null ) { dayChooser . setMonth ( month ) ; } firePropertyChange ( "month" , oldMonth , month ) ; } | Sets the month attribute of the JMonthChooser object . Fires a property change month . |
10,988 | public void setEnabled ( boolean enabled ) { super . setEnabled ( enabled ) ; comboBox . setEnabled ( enabled ) ; if ( spinner != null ) { spinner . setEnabled ( enabled ) ; } } | Enable or disable the JMonthChooser . |
10,989 | public void setFont ( Font font ) { if ( comboBox != null ) { comboBox . setFont ( font ) ; } super . setFont ( font ) ; } | Sets the font for this component . |
10,990 | public void updateUI ( ) { final JSpinner testSpinner = new JSpinner ( ) ; if ( spinner != null ) { if ( "Windows" . equals ( UIManager . getLookAndFeel ( ) . getID ( ) ) ) { spinner . setBorder ( testSpinner . getBorder ( ) ) ; } else { spinner . setBorder ( new EmptyBorder ( 0 , 0 , 0 , 0 ) ) ; } } } | Updates the UI . |
10,991 | public static Proxy getProxy ( final boolean test ) throws IOException { int providerIndex = MyNumberUtils . randomIntBetween ( 0 , PROVIDERS . length - 1 ) ; IProxyProvider randomProvider = PROVIDERS [ providerIndex ] ; return getProxy ( randomProvider , test ) ; } | Get a Proxy |
10,992 | public static Proxy getProxy ( final IProxyProvider provider , final boolean test ) throws IOException { LOGGER . info ( "Getting proxy..." ) ; List < Proxy > proxies = provider . getProxies ( - 1 , false , true ) ; LOGGER . info ( "Total Proxies: " + proxies . size ( ) ) ; final CountDownLatch countDown = new CountDownLatch ( proxies . size ( ) ) ; final AtomicReference < Proxy > useProxy = new AtomicReference < > ( ) ; int threadCount = proxies . size ( ) > 10 ? 10 : proxies . size ( ) ; if ( threadCount <= 0 ) { threadCount = 1 ; } final ExecutorService testService = Executors . newFixedThreadPool ( threadCount ) ; for ( final Proxy proxy : proxies ) { Thread validate = new Thread ( ) { public void run ( ) { try { if ( test ) { if ( proxy . isBlackListed ( ) ) { return ; } proxy . updateStatus ( ) ; if ( ! proxy . isOnline ( ) ) { return ; } proxy . updateAnonymity ( ) ; if ( ! proxy . isAnonymous ( ) ) { return ; } } if ( useProxy . get ( ) == null ) { LOGGER . info ( "Using Proxy: " + proxy . toString ( ) ) ; useProxy . set ( proxy ) ; while ( countDown . getCount ( ) > 0 ) { countDown . countDown ( ) ; } } } catch ( Exception e ) { LOGGER . info ( "Proxy validation returned error: " + e . getClass ( ) . getName ( ) + " - " + e . getMessage ( ) ) ; } finally { countDown . countDown ( ) ; } } } ; testService . submit ( validate ) ; } try { countDown . await ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } testService . shutdownNow ( ) ; if ( useProxy . get ( ) == null ) { return getProxy ( test ) ; } return useProxy . get ( ) ; } | Get a Proxy using the given provider |
10,993 | public static Proxy ghostMySystemProperties ( boolean test ) throws IOException { LOGGER . info ( "Ghosting System Properties..." ) ; Proxy use = getProxy ( test ) ; if ( use != null ) { applyProxy ( use ) ; } return use ; } | Ghost the HTTP in the system properties |
10,994 | public static void applyUserAgent ( String agent ) { LOGGER . info ( "Applying agent: " + agent ) ; System . setProperty ( "http.agent" , agent ) ; System . setProperty ( "https.agent" , agent ) ; } | Apply User Agent |
10,995 | public synchronized static boolean isBlacklisted ( String ip ) { if ( blacklistCache == null || blacklistCache . isEmpty ( ) ) { blacklistCache = new HashSet < > ( ) ; for ( IBlackListProvider provider : BLACKLIST_PROVIDERS ) { try { blacklistCache . addAll ( provider . getIPs ( ) ) ; } catch ( IOException e ) { LOGGER . warn ( "Error fetching blacklist records" , e ) ; } } } return blacklistCache . contains ( ip ) ; } | Check if the IP is in a blacklist |
10,996 | public RuleSet getRuleTree ( String surt ) { RuleSet rules = new RuleSet ( ) ; rules . addAll ( getRulesWithExactSurt ( "(" ) ) ; boolean first = true ; for ( String search : new NewSurtTokenizer ( surt ) . getSearchList ( ) ) { if ( first ) { first = false ; rules . addAll ( getRulesWithSurtPrefix ( search ) ) ; } else { rules . addAll ( getRulesWithExactSurt ( search ) ) ; } } return rules ; } | Returns the rule tree for a given SURT . This is a sorted set of all rules equal or lower in specificity than the given SURT plus all rules on the path from this SURT to the root SURT ( . |
10,997 | public ISynchronizationPoint < Exception > compress ( Readable input , Writable output , int bufferSize , int maxBuffers , byte priority ) { Deflater deflater = new Deflater ( level , nowrap ) ; LimitWriteOperationsReuseBuffers limit = new LimitWriteOperationsReuseBuffers ( output , bufferSize , maxBuffers ) ; byte [ ] bufRead = new byte [ bufferSize ] ; ByteBuffer buffer = ByteBuffer . wrap ( bufRead ) ; AsyncWork < Integer , IOException > task = input . readAsync ( buffer ) ; SynchronizationPoint < Exception > end = new SynchronizationPoint < > ( ) ; task . listenAsync ( new Compress ( input , output , task , bufRead , deflater , limit , priority , end ) , true ) ; return end ; } | Compress from a Readable to a Writable . |
10,998 | public final void initializeLookAndFeels ( ) { try { LookAndFeelInfo [ ] lnfs = UIManager . getInstalledLookAndFeels ( ) ; boolean found = false ; for ( int i = 0 ; i < lnfs . length ; i ++ ) { if ( lnfs [ i ] . getName ( ) . equals ( "JGoodies Plastic 3D" ) ) { found = true ; } } if ( ! found ) { UIManager . installLookAndFeel ( "JGoodies Plastic 3D" , "com.jgoodies.looks.plastic.Plastic3DLookAndFeel" ) ; } UIManager . setLookAndFeel ( "com.jgoodies.looks.plastic.Plastic3DLookAndFeel" ) ; } catch ( Throwable t ) { try { UIManager . setLookAndFeel ( UIManager . getSystemLookAndFeelClassName ( ) ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } | Installs the JGoodies Look & Feels if available in classpath . |
10,999 | public static void main ( String [ ] s ) { WindowListener l = new WindowAdapter ( ) { public void windowClosing ( WindowEvent e ) { System . exit ( 0 ) ; } } ; JFrame frame = new JFrame ( "JCalendar Demo" ) ; frame . addWindowListener ( l ) ; JCalendarDemo demo = new JCalendarDemo ( ) ; demo . init ( ) ; frame . getContentPane ( ) . add ( demo ) ; frame . pack ( ) ; frame . setBounds ( 200 , 200 , ( int ) frame . getPreferredSize ( ) . getWidth ( ) + 20 , ( int ) frame . getPreferredSize ( ) . getHeight ( ) + 180 ) ; frame . setVisible ( true ) ; } | Creates a JFrame with a JCalendarDemo inside and can be used for testing . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.