idx int64 0 165k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
147,800 | public static < T > T callConstructor ( Class < T > klass ) { return callConstructor ( klass , new Class < ? > [ 0 ] , new Object [ 0 ] ) ; } | Call the no - arg constructor for the given class |
147,801 | public static < T > T callConstructor ( Class < T > klass , Object [ ] args ) { Class < ? > [ ] klasses = new Class [ args . length ] ; for ( int i = 0 ; i < args . length ; i ++ ) klasses [ i ] = args [ i ] . getClass ( ) ; return callConstructor ( klass , klasses , args ) ; } | Call the constructor for the given class inferring the correct types for the arguments . This could be confusing if there are multiple constructors with the same number of arguments and the values themselves don t disambiguate . |
147,802 | public static < T > Object callMethod ( Object obj , Class < T > c , String name , Class < ? > [ ] classes , Object [ ] args ) { try { Method m = getMethod ( c , name , classes ) ; return m . invoke ( obj , args ) ; } catch ( InvocationTargetException e ) { throw getCause ( e ) ; } catch ( IllegalAccessException e ) { ... | Call the named method |
147,803 | public static < T > Method getMethod ( Class < T > c , String name , Class < ? > ... argTypes ) { try { return c . getMethod ( name , argTypes ) ; } catch ( NoSuchMethodException e ) { throw new IllegalArgumentException ( e ) ; } } | Get the named method from the class |
147,804 | public static List < Versioned < byte [ ] > > pruneNonReplicaEntries ( List < Versioned < byte [ ] > > vals , List < Integer > keyReplicas , MutableBoolean didPrune ) { List < Versioned < byte [ ] > > prunedVals = new ArrayList < Versioned < byte [ ] > > ( vals . size ( ) ) ; for ( Versioned < byte [ ] > val : vals ) {... | Remove all non replica clock entries from the list of versioned values provided |
147,805 | public byte [ ] toBytes ( T object ) { try { ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ; ObjectOutputStream out = new ObjectOutputStream ( stream ) ; out . writeObject ( object ) ; return stream . toByteArray ( ) ; } catch ( IOException e ) { throw new SerializationException ( e ) ; } } | Transform the given object into an array of bytes |
147,806 | @ SuppressWarnings ( "unchecked" ) public T toObject ( byte [ ] bytes ) { try { return ( T ) new ObjectInputStream ( new ByteArrayInputStream ( bytes ) ) . readObject ( ) ; } catch ( IOException e ) { throw new SerializationException ( e ) ; } catch ( ClassNotFoundException c ) { throw new SerializationException ( c ) ... | Transform the given bytes into an object . |
147,807 | public boolean isCompleteRequest ( final ByteBuffer buffer ) throws VoldemortException { DataInputStream inputStream = new DataInputStream ( new ByteBufferBackedInputStream ( buffer ) ) ; try { byte opCode = inputStream . readByte ( ) ; inputStream . readUTF ( ) ; getRoutingType ( inputStream ) ; switch ( opCode ) { ca... | This is pretty ugly . We end up mimicking the request logic here so this needs to stay in sync with handleRequest . |
147,808 | synchronized public V put ( K key , V value ) { V oldValue = this . get ( key ) ; try { super . put ( key , value ) ; writeBack ( key , value ) ; return oldValue ; } catch ( Exception e ) { super . put ( key , oldValue ) ; writeBack ( key , oldValue ) ; throw new VoldemortException ( "Failed to put(" + key + ", " + val... | Updates the value in HashMap and writeBack as Atomic step |
147,809 | public void update ( int number ) { byte [ ] numberInBytes = new byte [ ByteUtils . SIZE_OF_INT ] ; ByteUtils . writeInt ( numberInBytes , number , 0 ) ; update ( numberInBytes ) ; } | Update the underlying buffer using the integer |
147,810 | public void update ( short number ) { byte [ ] numberInBytes = new byte [ ByteUtils . SIZE_OF_SHORT ] ; ByteUtils . writeShort ( numberInBytes , number , 0 ) ; update ( numberInBytes ) ; } | Update the underlying buffer using the short |
147,811 | public synchronized boolean tryDelegateSlop ( Node node ) { if ( asyncCallbackShouldSendhint ) { return false ; } else { slopDestinations . put ( node , true ) ; return true ; } } | Try to delegate the responsibility of sending slops to master |
147,812 | public synchronized boolean tryDelegateResponseHandling ( Response < ByteArray , Object > response ) { if ( responseHandlingCutoff ) { return false ; } else { responseQueue . offer ( response ) ; this . notifyAll ( ) ; return true ; } } | try to delegate the master to handle the response |
147,813 | public synchronized Response < ByteArray , Object > responseQueuePoll ( long timeout , TimeUnit timeUnit ) throws InterruptedException { long timeoutMs = timeUnit . toMillis ( timeout ) ; long timeoutWallClockMs = System . currentTimeMillis ( ) + timeoutMs ; while ( responseQueue . isEmpty ( ) && System . currentTimeMi... | poll the response queue for response |
147,814 | private void setProperties ( Properties properties ) { Props props = new Props ( properties ) ; if ( props . containsKey ( ClientConfig . ENABLE_JMX_PROPERTY ) ) { this . setEnableJmx ( props . getBoolean ( ClientConfig . ENABLE_JMX_PROPERTY ) ) ; } if ( props . containsKey ( ClientConfig . BOOTSTRAP_URLS_PROPERTY ) ) ... | Set the values using the specified Properties object . |
147,815 | private void setProperties ( Properties properties ) { Props props = new Props ( properties ) ; if ( props . containsKey ( BOOTSTRAP_URLS_PROPERTY ) ) { setBootstrapURLs ( props . getList ( BOOTSTRAP_URLS_PROPERTY ) ) ; } if ( props . containsKey ( FAT_CLIENTS_CONFIG_SOURCE ) ) { setFatClientConfigSource ( StoreClientC... | Set the values using the specified Properties object |
147,816 | public CoordinatorConfig setBootstrapURLs ( List < String > bootstrapUrls ) { this . bootstrapURLs = Utils . notNull ( bootstrapUrls ) ; if ( this . bootstrapURLs . size ( ) <= 0 ) throw new IllegalArgumentException ( "Must provide at least one bootstrap URL." ) ; return this ; } | Sets the bootstrap URLs used by the different Fat clients inside the Coordinator |
147,817 | private void sendOneAsyncHint ( final ByteArray slopKey , final Versioned < byte [ ] > slopVersioned , final List < Node > nodesToTry ) { Node nodeToHostHint = null ; boolean foundNode = false ; while ( nodesToTry . size ( ) > 0 ) { nodeToHostHint = nodesToTry . remove ( 0 ) ; if ( ! failedNodes . contains ( nodeToHost... | A callback that handles requestComplete event from NIO selector manager Will try any possible nodes and pass itself as callback util all nodes are exhausted |
147,818 | public Iterable < V > sorted ( Iterator < V > input ) { ExecutorService executor = new ThreadPoolExecutor ( this . numThreads , this . numThreads , 1000L , TimeUnit . MILLISECONDS , new SynchronousQueue < Runnable > ( ) , new CallerRunsPolicy ( ) ) ; final AtomicInteger count = new AtomicInteger ( 0 ) ; final List < Fi... | Produce an iterator over the input values in sorted order . Sorting will occur in the fixed space configured in the constructor data will be dumped to disk as necessary . |
147,819 | private void processResponse ( Response < ByteArray , Object > response , Pipeline pipeline ) { if ( response == null ) { logger . warn ( "RoutingTimedout on waiting for async ops; parallelResponseToWait: " + numNodesPendingResponse + "; preferred-1: " + ( preferred - 1 ) + "; quorumOK: " + quorumSatisfied + "; zoneOK:... | Process the response by reporting proper log and feeding failure detectors |
147,820 | private boolean isZonesSatisfied ( ) { boolean zonesSatisfied = false ; if ( pipelineData . getZonesRequired ( ) == null ) { zonesSatisfied = true ; } else { int numZonesSatisfied = pipelineData . getZoneResponses ( ) . size ( ) ; if ( numZonesSatisfied >= ( pipelineData . getZonesRequired ( ) + 1 ) ) { zonesSatisfied ... | Check if zone count policy is satisfied |
147,821 | public ClientConfig setIdleConnectionTimeout ( long idleConnectionTimeout , TimeUnit unit ) { if ( idleConnectionTimeout <= 0 ) { this . idleConnectionTimeoutMs = - 1 ; } else { if ( unit . toMinutes ( idleConnectionTimeout ) < 10 ) { throw new IllegalArgumentException ( "idleConnectionTimeout should be minimum of 10 m... | Set the timeout for idle connections . Voldemort client caches all connections to the Voldemort server . This setting allows the a connection to be dropped if it is idle for more than this time . |
147,822 | public ClientConfig setNodeBannagePeriod ( int nodeBannagePeriod , TimeUnit unit ) { this . failureDetectorBannagePeriod = unit . toMillis ( nodeBannagePeriod ) ; return this ; } | The period of time to ban a node that gives an error on an operation . |
147,823 | public ClientConfig setThreadIdleTime ( long threadIdleTime , TimeUnit unit ) { this . threadIdleMs = unit . toMillis ( threadIdleTime ) ; return this ; } | The amount of time to keep an idle client thread alive |
147,824 | public void close ( SocketDestination destination ) { factory . setLastClosedTimestamp ( destination ) ; queuedPool . reset ( destination ) ; } | Reset the pool of resources for a specific destination . Idle resources will be destroyed . Checked out resources that are subsequently checked in will be destroyed . Newly created resources can be checked in to reestablish resources for the specific destination . |
147,825 | public void close ( ) { if ( stats != null ) { try { if ( this . jmxEnabled ) JmxUtils . unregisterMbean ( getAggregateMetricName ( ) ) ; } catch ( Exception e ) { } stats . close ( ) ; } factory . close ( ) ; queuedPool . close ( ) ; } | Permanently close the ClientRequestExecutor pool . Resources subsequently checked in will be destroyed . |
147,826 | public static String readFileContents ( FileSystem fs , Path path , int bufferSize ) throws IOException { if ( bufferSize <= 0 ) return new String ( ) ; FSDataInputStream input = fs . open ( path ) ; byte [ ] buffer = new byte [ bufferSize ] ; ByteArrayOutputStream stream = new ByteArrayOutputStream ( ) ; while ( true ... | Given a filesystem path and buffer - size read the file contents and presents it as a string |
147,827 | public static FileStatus [ ] getDataChunkFiles ( FileSystem fs , Path path , final int partitionId , final int replicaType ) throws IOException { return fs . listStatus ( path , new PathFilter ( ) { public boolean accept ( Path input ) { if ( input . getName ( ) . matches ( "^" + Integer . toString ( partitionId ) + "_... | Given a filesystem and path to a node gets all the files which belong to a partition and replica type |
147,828 | private boolean isSatisfied ( ) { if ( pipelineData . getZonesRequired ( ) != null ) { return ( ( pipelineData . getSuccesses ( ) >= required ) && ( pipelineData . getZoneResponses ( ) . size ( ) >= ( pipelineData . getZonesRequired ( ) + 1 ) ) ) ; } else { return pipelineData . getSuccesses ( ) >= required ; } } | Checks whether every property except preferred is satisfied |
147,829 | public int getCrossZonePartitionStoreMoves ( ) { int xzonePartitionStoreMoves = 0 ; for ( RebalanceTaskInfo info : batchPlan ) { Node donorNode = finalCluster . getNodeById ( info . getDonorId ( ) ) ; Node stealerNode = finalCluster . getNodeById ( info . getStealerId ( ) ) ; if ( donorNode . getZoneId ( ) != stealerNo... | Determines total number of partition - stores moved across zones . |
147,830 | protected int getDonorId ( StoreRoutingPlan currentSRP , StoreRoutingPlan finalSRP , int stealerZoneId , int stealerNodeId , int stealerPartitionId ) { int stealerZoneNAry = finalSRP . getZoneNaryForNodesPartition ( stealerZoneId , stealerNodeId , stealerPartitionId ) ; int donorZoneId ; if ( currentSRP . zoneNAryExist... | Decide which donor node to steal from . This is a policy implementation . I . e . in the future additional policies could be considered . At that time this method should be overridden in a sub - class or a policy object ought to implement this algorithm . |
147,831 | protected void handleExceptions ( MessageEvent messageEvent , Exception exception ) { logger . error ( "Unknown exception. Internal Server Error." , exception ) ; writeErrorResponse ( messageEvent , HttpResponseStatus . INTERNAL_SERVER_ERROR , "Internal Server Error" ) ; } | Exceptions specific to each operation is handled in the corresponding subclass . At this point we don t know the reason behind this exception . |
147,832 | public static void writeErrorResponse ( MessageEvent messageEvent , HttpResponseStatus status , String message ) { HttpResponse response = new DefaultHttpResponse ( HTTP_1_1 , status ) ; response . setHeader ( CONTENT_TYPE , "text/plain; charset=UTF-8" ) ; response . setContent ( ChannelBuffers . copiedBuffer ( "Failur... | Writes all error responses to the client . |
147,833 | public boolean parseAndValidateRequest ( ) { boolean result = false ; if ( ! super . parseAndValidateRequest ( ) || ! hasVectorClock ( this . isVectorClockOptional ) || ! hasContentLength ( ) || ! hasContentType ( ) ) { result = false ; } else { result = true ; } return result ; } | Validations specific to PUT |
147,834 | protected boolean hasContentLength ( ) { boolean result = false ; String contentLength = this . request . getHeader ( RestMessageHeaders . CONTENT_LENGTH ) ; if ( contentLength != null ) { try { Long . parseLong ( contentLength ) ; result = true ; } catch ( NumberFormatException nfe ) { logger . error ( "Exception when... | Retrieves and validates the content length from the REST request . |
147,835 | protected boolean hasContentType ( ) { boolean result = false ; if ( this . request . getHeader ( RestMessageHeaders . CONTENT_TYPE ) != null ) { result = true ; } else { logger . error ( "Error when validating put request. Missing Content-Type header." ) ; RestErrorHandler . writeErrorResponse ( this . messageEvent , ... | Retrieves and validates the content type from the REST requests |
147,836 | private void parseValue ( ) { ChannelBuffer content = this . request . getContent ( ) ; this . parsedValue = new byte [ content . capacity ( ) ] ; content . readBytes ( parsedValue ) ; } | Retrieve the value from the REST request body . |
147,837 | private void handleIOException ( IOException e , String action , int attempt ) throws VoldemortException , InterruptedException { if ( e . getMessage ( ) . contains ( "Filesystem closed" ) || ExceptionUtils . recursiveClassEquals ( e , AccessControlException . class ) ) { throw new VoldemortException ( "Got an IOExcept... | This function is intended to detect the subset of IOException which are not considered recoverable in which case we want to bubble up the exception instead of retrying . |
147,838 | private boolean setAvailable ( NodeStatus nodeStatus , boolean isAvailable ) { synchronized ( nodeStatus ) { boolean previous = nodeStatus . isAvailable ( ) ; nodeStatus . setAvailable ( isAvailable ) ; nodeStatus . setLastChecked ( getConfig ( ) . getTime ( ) . getMilliseconds ( ) ) ; return previous ; } } | We need to distinguish the case where we re newly available and the case where we re already available . So we check the node status before we update it and return it to the caller . |
147,839 | public static void acceptsDir ( OptionParser parser ) { parser . acceptsAll ( Arrays . asList ( OPT_D , OPT_DIR ) , "directory path for input/output" ) . withRequiredArg ( ) . describedAs ( "dir-path" ) . ofType ( String . class ) ; } | Adds OPT_D | OPT_DIR option to OptionParser with one argument . |
147,840 | public static void acceptsFile ( OptionParser parser ) { parser . acceptsAll ( Arrays . asList ( OPT_F , OPT_FILE ) , "file path for input/output" ) . withRequiredArg ( ) . describedAs ( "file-path" ) . ofType ( String . class ) ; } | Adds OPT_F | OPT_FILE option to OptionParser with one argument . |
147,841 | public static void acceptsFormat ( OptionParser parser ) { parser . accepts ( OPT_FORMAT , "format of key or entry, could be hex, json or binary" ) . withRequiredArg ( ) . describedAs ( "hex | json | binary" ) . ofType ( String . class ) ; } | Adds OPT_FORMAT option to OptionParser with one argument . |
147,842 | public static void acceptsNodeSingle ( OptionParser parser ) { parser . acceptsAll ( Arrays . asList ( OPT_N , OPT_NODE ) , "node id" ) . withRequiredArg ( ) . describedAs ( "node-id" ) . ofType ( Integer . class ) ; } | Adds OPT_N | OPT_NODE option to OptionParser with one argument . |
147,843 | public static void acceptsUrl ( OptionParser parser ) { parser . acceptsAll ( Arrays . asList ( OPT_U , OPT_URL ) , "bootstrap url" ) . withRequiredArg ( ) . describedAs ( "url" ) . ofType ( String . class ) ; } | Adds OPT_U | OPT_URL option to OptionParser with one argument . |
147,844 | public static void acceptsZone ( OptionParser parser ) { parser . acceptsAll ( Arrays . asList ( OPT_Z , OPT_ZONE ) , "zone id" ) . withRequiredArg ( ) . describedAs ( "zone-id" ) . ofType ( Integer . class ) ; } | Adds OPT_Z | OPT_ZONE option to OptionParser with one argument . |
147,845 | public static void acceptsHex ( OptionParser parser ) { parser . acceptsAll ( Arrays . asList ( OPT_X , OPT_HEX ) , "fetch key/entry by key value of hex type" ) . withRequiredArg ( ) . describedAs ( "key-list" ) . withValuesSeparatedBy ( ',' ) . ofType ( String . class ) ; } | Adds OPT_X | OPT_HEX option to OptionParser with multiple arguments . |
147,846 | public static void acceptsJson ( OptionParser parser ) { parser . acceptsAll ( Arrays . asList ( OPT_J , OPT_JSON ) , "fetch key/entry by key value of json type" ) . withRequiredArg ( ) . describedAs ( "key-list" ) . withValuesSeparatedBy ( ',' ) . ofType ( String . class ) ; } | Adds OPT_J | OPT_JSON option to OptionParser with multiple arguments . |
147,847 | public static void acceptsNodeMultiple ( OptionParser parser ) { parser . acceptsAll ( Arrays . asList ( OPT_N , OPT_NODE ) , "node id list" ) . withRequiredArg ( ) . describedAs ( "node-id-list" ) . withValuesSeparatedBy ( ',' ) . ofType ( Integer . class ) ; } | Adds OPT_N | OPT_NODE option to OptionParser with multiple arguments . |
147,848 | public static void acceptsPartition ( OptionParser parser ) { parser . acceptsAll ( Arrays . asList ( OPT_P , OPT_PARTITION ) , "partition id list" ) . withRequiredArg ( ) . describedAs ( "partition-id-list" ) . withValuesSeparatedBy ( ',' ) . ofType ( Integer . class ) ; } | Adds OPT_P | OPT_PARTITION option to OptionParser with multiple arguments . |
147,849 | public static void checkRequired ( OptionSet options , String opt ) throws VoldemortException { List < String > opts = Lists . newArrayList ( ) ; opts . add ( opt ) ; checkRequired ( options , opts ) ; } | Checks if the required option exists . |
147,850 | public static void checkRequired ( OptionSet options , String opt1 , String opt2 ) throws VoldemortException { List < String > opts = Lists . newArrayList ( ) ; opts . add ( opt1 ) ; opts . add ( opt2 ) ; checkRequired ( options , opts ) ; } | Checks if there s exactly one option that exists among all possible opts . |
147,851 | public static void checkRequired ( OptionSet options , List < String > opts ) throws VoldemortException { List < String > optCopy = Lists . newArrayList ( ) ; for ( String opt : opts ) { if ( options . has ( opt ) ) { optCopy . add ( opt ) ; } } if ( optCopy . size ( ) < 1 ) { System . err . println ( "Please specify o... | Checks if there s exactly one option that exists among all opts . |
147,852 | protected void registerRequest ( RestRequestValidator requestValidator , ChannelHandlerContext ctx , MessageEvent messageEvent ) { CompositeVoldemortRequest < ByteArray , byte [ ] > requestObject = requestValidator . constructCompositeVoldemortRequestObject ( ) ; if ( requestObject != null ) { DynamicTimeoutStoreClient... | Constructs a valid request and passes it on to the next handler . It also creates the StoreClient object corresponding to the store name specified in the REST request . |
147,853 | public void handleExceptions ( MessageEvent messageEvent , Exception exception ) { if ( exception instanceof InvalidMetadataException ) { logger . error ( "Exception when deleting. The requested key does not exist in this partition" , exception ) ; writeErrorResponse ( messageEvent , HttpResponseStatus . REQUESTED_RANG... | Handle exceptions thrown by the storage . Exceptions specific to DELETE go here . Pass other exceptions to the parent class . |
147,854 | public void recordPutTimeAndSize ( long timeNS , long valueSize , long keySize ) { recordTime ( Tracked . PUT , timeNS , 0 , valueSize , keySize , 0 ) ; } | Record the duration of a put operation along with the size of the values returned . |
147,855 | public void recordGetAllTime ( long timeNS , int requested , int returned , long totalValueBytes , long totalKeyBytes ) { recordTime ( Tracked . GET_ALL , timeNS , requested - returned , totalValueBytes , totalKeyBytes , requested ) ; } | Record the duration of a get_all operation along with how many values were requested how may were actually returned and the size of the values returned . |
147,856 | private void recordTime ( Tracked op , long timeNS , long numEmptyResponses , long valueSize , long keySize , long getAllAggregateRequests ) { counters . get ( op ) . addRequest ( timeNS , numEmptyResponses , valueSize , keySize , getAllAggregateRequests ) ; if ( logger . isTraceEnabled ( ) && ! storeName . contains ( ... | Method to service public recording APIs |
147,857 | public static List < String > getCommaSeparatedStringValues ( String paramValue , String type ) { List < String > commaSeparatedProps = Lists . newArrayList ( ) ; for ( String url : Utils . COMMA_SEP . split ( paramValue . trim ( ) ) ) if ( url . trim ( ) . length ( ) > 0 ) commaSeparatedProps . add ( url ) ; if ( comm... | Given the comma separated list of properties as a string splits it multiple strings |
147,858 | private synchronized void initializeFatClient ( String storeName , Properties storeClientProps ) { updateCoordinatorMetadataWithLatestState ( ) ; logger . info ( "Creating a Fat client for store: " + storeName ) ; SocketStoreClientFactory fatClientFactory = getFatClientFactory ( this . coordinatorConfig . getBootstrapU... | Initialize the fat client for the given store . |
147,859 | synchronized public void completeTask ( int taskId , int partitionStoresMigrated ) { tasksInFlight . remove ( taskId ) ; numTasksCompleted ++ ; numPartitionStoresMigrated += partitionStoresMigrated ; updateProgressBar ( ) ; } | Called whenever a rebalance task completes . This means one task is done and some number of partition stores have been migrated . |
147,860 | synchronized public String getPrettyProgressBar ( ) { StringBuilder sb = new StringBuilder ( ) ; double taskRate = numTasksCompleted / ( double ) totalTaskCount ; double partitionStoreRate = numPartitionStoresMigrated / ( double ) totalPartitionStoreCount ; long deltaTimeMs = System . currentTimeMillis ( ) - startTimeM... | Construct a pretty string documenting progress for this batch plan thus far . |
147,861 | protected void progressInfoMessage ( final String tag ) { if ( logger . isInfoEnabled ( ) ) { long totalTimeS = ( System . currentTimeMillis ( ) - startTimeMs ) / Time . MS_PER_SECOND ; logger . info ( tag + " : scanned " + scanned + " and fetched " + fetched + " for store '" + storageEngine . getName ( ) + "' partitio... | Progress info message |
147,862 | protected void sendMessage ( DataOutputStream outputStream , Message message ) throws IOException { long startNs = System . nanoTime ( ) ; ProtoUtils . writeMessage ( outputStream , message ) ; if ( streamStats != null ) { streamStats . reportNetworkTime ( operation , Utils . elapsedTimeNs ( startNs , System . nanoTime... | Helper method to send message on outputStream and account for network time stats . |
147,863 | protected void reportStorageOpTime ( long startNs ) { if ( streamStats != null ) { streamStats . reportStreamingScan ( operation ) ; streamStats . reportStorageTime ( operation , Utils . elapsedTimeNs ( startNs , System . nanoTime ( ) ) ) ; } } | Helper method to track storage operations & time via StreamingStats . |
147,864 | public void awaitStartupCompletion ( ) { try { Object obj = startedStatusQueue . take ( ) ; if ( obj instanceof Throwable ) throw new VoldemortException ( ( Throwable ) obj ) ; } catch ( InterruptedException e ) { } } | Blocks until the server has started successfully or an exception is thrown . |
147,865 | protected synchronized void streamingSlopPut ( ByteArray key , Versioned < byte [ ] > value , String storeName , int failedNodeId ) throws IOException { Slop slop = new Slop ( storeName , Slop . Operation . PUT , key , value . getValue ( ) , null , failedNodeId , new Date ( ) ) ; ByteArray slopKey = slop . makeKey ( ) ... | This is a method to stream slops to slop store when a node is detected faulty in a streaming session |
147,866 | @ SuppressWarnings ( "rawtypes" ) private void synchronousInvokeCallback ( Callable call ) { Future future = streamingSlopResults . submit ( call ) ; try { future . get ( ) ; } catch ( InterruptedException e1 ) { logger . error ( "Callback failed" , e1 ) ; throw new VoldemortException ( "Callback failed" ) ; } catch ( ... | Helper method to synchronously invoke a callback |
147,867 | protected void handleResponse ( int responseCode , InputStream inputStream ) { BufferedReader rd = null ; try { rd = new BufferedReader ( new InputStreamReader ( inputStream ) ) ; StringBuilder sb = new StringBuilder ( ) ; String line ; while ( ( line = rd . readLine ( ) ) != null ) { sb . append ( line ) ; } log . inf... | Can be overridden if you want to replace or supplement the debug handling for responses . |
147,868 | @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) protected void addStoreToSession ( String store ) { Exception initializationException = null ; storeNames . add ( store ) ; for ( Node node : nodesToStream ) { SocketDestination destination = null ; SocketAndStreams sands = null ; try { destination = new SocketDestina... | Add another store destination to an existing streaming session |
147,869 | @ SuppressWarnings ( { } ) public synchronized void removeStoreFromSession ( List < String > storeNameToRemove ) { logger . info ( "closing the Streaming session for a few stores" ) ; commitToVoldemort ( storeNameToRemove ) ; cleanupSessions ( storeNameToRemove ) ; } | Remove a list of stores from the session |
147,870 | @ SuppressWarnings ( { "rawtypes" , "unchecked" } ) public void blacklistNode ( int nodeId ) { Collection < Node > nodesInCluster = adminClient . getAdminClientCluster ( ) . getNodes ( ) ; if ( blackListedNodes == null ) { blackListedNodes = new ArrayList ( ) ; } blackListedNodes . add ( nodeId ) ; for ( Node node : no... | mark a node as blacklisted |
147,871 | @ SuppressWarnings ( { "unchecked" , "rawtypes" , "unused" } ) private void commitToVoldemort ( List < String > storeNamesToCommit ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Trying to commit to Voldemort" ) ; } boolean hasError = false ; if ( nodesToStream == null || nodesToStream . size ( ) == 0 ) { if... | Flush the network buffer and write all entries to the serve . then wait for an ack from the server . This is a blocking call . It is invoked on every Commit batch size of entries It is also called on the close session call |
147,872 | @ SuppressWarnings ( { "rawtypes" , "unchecked" } ) private void cleanupSessions ( List < String > storeNamesToCleanUp ) { logger . info ( "Performing cleanup" ) ; for ( String store : storeNamesToCleanUp ) { for ( Node node : nodesToStream ) { try { SocketAndStreams sands = nodeIdStoreToSocketAndStreams . get ( new Pa... | Helper method to Close all open socket connections and checkin back to the pool |
147,873 | private static List < Integer > stripNodeIds ( List < Node > nodeList ) { List < Integer > nodeidList = new ArrayList < Integer > ( ) ; if ( nodeList != null ) { for ( Node node : nodeList ) { nodeidList . add ( node . getId ( ) ) ; } } return nodeidList ; } | Helper method to get a list of node ids . |
147,874 | private static List < Node > difference ( List < Node > listA , List < Node > listB ) { if ( listA != null && listB != null ) listA . removeAll ( listB ) ; return listA ; } | Computes A - B |
147,875 | public static void main ( String [ ] args ) { if ( args . length != 2 ) { System . out . println ( "Usage: SchemaEvolutionValidator pathToOldSchema pathToNewSchema" ) ; return ; } Schema oldSchema ; Schema newSchema ; try { oldSchema = Schema . parse ( new File ( args [ 0 ] ) ) ; } catch ( Exception ex ) { oldSchema = ... | This main method provides an easy command line tool to compare two schemas . |
147,876 | public static void validateAllAvroSchemas ( SerializerDefinition avroSerDef ) { Map < Integer , String > schemaVersions = avroSerDef . getAllSchemaInfoVersions ( ) ; if ( schemaVersions . size ( ) < 1 ) { throw new VoldemortException ( "No schema specified" ) ; } for ( Map . Entry < Integer , String > entry : schemaVer... | Given an AVRO serializer definition validates if all the avro schemas are valid i . e parseable . |
147,877 | public int getPartition ( byte [ ] key , byte [ ] value , int numReduceTasks ) { try { int partitionId = ByteUtils . readInt ( value , ByteUtils . SIZE_OF_INT ) ; int magicNumber = partitionId ; if ( getSaveKeys ( ) && ! buildPrimaryReplicasOnly ) { int replicaType = ( int ) ByteUtils . readBytes ( value , 2 * ByteUtil... | This function computes which reduce task to shuffle a record to . |
147,878 | private void initFileStreams ( int chunkId ) { if ( chunksHandled . add ( chunkId ) ) { try { this . indexFileSizeInBytes [ chunkId ] = 0L ; this . valueFileSizeInBytes [ chunkId ] = 0L ; this . checkSumDigestIndex [ chunkId ] = CheckSum . getInstance ( checkSumType ) ; this . checkSumDigestValue [ chunkId ] = CheckSum... | The MapReduce framework should operate sequentially so thread safety shouldn t be a problem . |
147,879 | public boolean parseAndValidateRequest ( ) { if ( ! super . parseAndValidateRequest ( ) ) { return false ; } isGetVersionRequest = hasGetVersionRequestHeader ( ) ; if ( isGetVersionRequest && this . parsedKeys . size ( ) > 1 ) { RestErrorHandler . writeErrorResponse ( messageEvent , HttpResponseStatus . BAD_REQUEST , "... | Validations specific to GET and GET ALL |
147,880 | public static Map < String , String > getMetadataFromSequenceFile ( FileSystem fs , Path path ) { try { Configuration conf = new Configuration ( ) ; conf . setInt ( "io.file.buffer.size" , 4096 ) ; SequenceFile . Reader reader = new SequenceFile . Reader ( fs , path , new Configuration ( ) ) ; SequenceFile . Metadata m... | Read the metadata from a hadoop SequenceFile |
147,881 | private void recordBackupSet ( File backupDir ) throws IOException { String [ ] filesInEnv = env . getHome ( ) . list ( ) ; SimpleDateFormat format = new SimpleDateFormat ( "yyyy_MM_dd_kk_mm_ss" ) ; String recordFileName = "backupset-" + format . format ( new Date ( ) ) ; File recordFile = new File ( backupDir , record... | Records the list of backedup files into a text file |
147,882 | private void cleanStaleFiles ( File backupDir , AsyncOperationStatus status ) { String [ ] filesInEnv = env . getHome ( ) . list ( ) ; String [ ] filesInBackupDir = backupDir . list ( ) ; if ( filesInEnv != null && filesInBackupDir != null ) { HashSet < String > envFileSet = new HashSet < String > ( ) ; for ( String fi... | For recovery from the latest consistent snapshot we should clean up the old files from the previous backup set else we will fill the disk with useless log files |
147,883 | private void verifiedCopyFile ( File sourceFile , File destFile ) throws IOException { if ( ! destFile . exists ( ) ) { destFile . createNewFile ( ) ; } FileInputStream source = null ; FileOutputStream destination = null ; LogVerificationInputStream verifyStream = null ; try { source = new FileInputStream ( sourceFile ... | Copies the jdb log files with additional verification of the checksums . |
147,884 | public List < Integer > getReplicatingPartitionList ( int index ) { List < Node > preferenceNodesList = new ArrayList < Node > ( getNumReplicas ( ) ) ; List < Integer > replicationPartitionsList = new ArrayList < Integer > ( getNumReplicas ( ) ) ; HashMap < Integer , Integer > requiredRepFactor = new HashMap < Integer ... | Get the replication partitions list for the given partition . |
147,885 | private boolean checkZoneRequirement ( HashMap < Integer , Integer > requiredRepFactor , int zoneId ) { if ( requiredRepFactor . containsKey ( zoneId ) ) { if ( requiredRepFactor . get ( zoneId ) == 0 ) { return false ; } else { requiredRepFactor . put ( zoneId , requiredRepFactor . get ( zoneId ) - 1 ) ; return true ;... | Check if we still need more nodes from the given zone and reduce the zoneReplicationFactor count accordingly . |
147,886 | public static void acceptsUrlMultiple ( OptionParser parser ) { parser . acceptsAll ( Arrays . asList ( OPT_U , OPT_URL ) , "coordinator bootstrap urls" ) . withRequiredArg ( ) . describedAs ( "url-list" ) . withValuesSeparatedBy ( ',' ) . ofType ( String . class ) ; } | Adds OPT_U | OPT_URL option to OptionParser with multiple arguments . |
147,887 | public static String [ ] copyArrayCutFirst ( String [ ] arr ) { if ( arr . length > 1 ) { String [ ] arrCopy = new String [ arr . length - 1 ] ; System . arraycopy ( arr , 1 , arrCopy , 0 , arrCopy . length ) ; return arrCopy ; } else { return new String [ 0 ] ; } } | Utility function that copies a string array except for the first element |
147,888 | public static String [ ] copyArrayAddFirst ( String [ ] arr , String add ) { String [ ] arrCopy = new String [ arr . length + 1 ] ; arrCopy [ 0 ] = add ; System . arraycopy ( arr , 0 , arrCopy , 1 , arr . length ) ; return arrCopy ; } | Utility function that copies a string array and add another string to first |
147,889 | @ SuppressWarnings ( "unchecked" ) public void put ( String key , Versioned < Object > value ) { writeLock . lock ( ) ; try { if ( this . storeNames . contains ( key ) || key . equals ( STORES_KEY ) ) { List < StoreDefinition > storeDefinitions = ( List < StoreDefinition > ) value . getValue ( ) ; StoreDefinitionUtils ... | helper function to convert strings to bytes as needed . |
147,890 | @ SuppressWarnings ( "unchecked" ) public void updateStoreDefinitions ( Versioned < byte [ ] > valueBytes ) { writeLock . lock ( ) ; try { Versioned < String > value = new Versioned < String > ( ByteUtils . getString ( valueBytes . getValue ( ) , "UTF-8" ) , valueBytes . getVersion ( ) ) ; Versioned < Object > valueObj... | Function to update store definitions . Unlike the put method this function does not delete any existing state . It only updates the state of the stores specified in the given stores . xml |
147,891 | public void put ( ByteArray keyBytes , Versioned < byte [ ] > valueBytes , byte [ ] transforms ) throws VoldemortException { writeLock . lock ( ) ; try { String key = ByteUtils . getString ( keyBytes . get ( ) , "UTF-8" ) ; Versioned < String > value = new Versioned < String > ( ByteUtils . getString ( valueBytes . get... | A write through put to inner - store . |
147,892 | private HashMap < String , StoreDefinition > makeStoreDefinitionMap ( List < StoreDefinition > storeDefs ) { HashMap < String , StoreDefinition > storeDefMap = new HashMap < String , StoreDefinition > ( ) ; for ( StoreDefinition storeDef : storeDefs ) storeDefMap . put ( storeDef . getName ( ) , storeDef ) ; return sto... | Returns the list of store defs as a map |
147,893 | private void updateRoutingStrategies ( Cluster cluster , List < StoreDefinition > storeDefs ) { writeLock . lock ( ) ; try { VectorClock clock = new VectorClock ( ) ; if ( metadataCache . containsKey ( ROUTING_STRATEGY_KEY ) ) clock = ( VectorClock ) metadataCache . get ( ROUTING_STRATEGY_KEY ) . getVersion ( ) ; logge... | Changes to cluster OR store definition metadata results in routing strategies changing . These changes need to be propagated to all the listeners . |
147,894 | public void addRebalancingState ( final RebalanceTaskInfo stealInfo ) { writeLock . lock ( ) ; try { if ( ByteUtils . getString ( get ( SERVER_STATE_KEY , null ) . get ( 0 ) . getValue ( ) , "UTF-8" ) . compareTo ( VoldemortState . NORMAL_SERVER . toString ( ) ) == 0 ) { put ( SERVER_STATE_KEY , VoldemortState . REBALA... | Add the steal information to the rebalancer state |
147,895 | public void deleteRebalancingState ( RebalanceTaskInfo stealInfo ) { writeLock . lock ( ) ; try { RebalancerState rebalancerState = getRebalancerState ( ) ; if ( ! rebalancerState . remove ( stealInfo ) ) throw new IllegalArgumentException ( "Couldn't find " + stealInfo + " in " + rebalancerState + " while deleting" ) ... | Delete the partition steal information from the rebalancer state |
147,896 | public void setOfflineState ( boolean setToOffline ) { writeLock . lock ( ) ; try { String currentState = ByteUtils . getString ( get ( SERVER_STATE_KEY , null ) . get ( 0 ) . getValue ( ) , "UTF-8" ) ; if ( setToOffline ) { if ( currentState . equals ( VoldemortState . NORMAL_SERVER . toString ( ) ) ) { put ( SERVER_S... | change server state between OFFLINE_SERVER and NORMAL_SERVER |
147,897 | public void addStoreDefinition ( StoreDefinition storeDef ) { writeLock . lock ( ) ; try { if ( this . storeNames . contains ( storeDef . getName ( ) ) ) { throw new VoldemortException ( "Store already exists !" ) ; } StoreDefinitionUtils . validateSchemaAsNeeded ( storeDef ) ; StoreDefinitionsMapper mapper = new Store... | Function to add a new Store to the Metadata store . This involves |
147,898 | public void deleteStoreDefinition ( String storeName ) { writeLock . lock ( ) ; try { if ( ! this . storeNames . contains ( storeName ) ) { throw new VoldemortException ( "Requested store to be deleted does not exist !" ) ; } this . storeDefinitionsStorageEngine . delete ( storeName , null ) ; this . metadataCache . re... | Function to delete the specified store from Metadata store . This involves |
147,899 | public boolean isValidStore ( String name ) { readLock . lock ( ) ; try { if ( this . storeNames . contains ( name ) ) { return true ; } return false ; } finally { readLock . unlock ( ) ; } } | Utility function to validate if the given store name exists in the store name list managed by MetadataStore . This is used by the Admin service for validation before serving a get - metadata request . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.