idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
32,800
public void setAnnounceInterval ( int announceInterval ) { if ( announceInterval <= 0 ) { this . stop ( true ) ; return ; } if ( this . myAnnounceInterval == announceInterval ) { return ; } logger . trace ( "Setting announce interval to {}s per tracker request." , announceInterval ) ; this . myAnnounceInterval = announceInterval ; }
Set the announce interval .
32,801
public TrackerClient getCurrentTrackerClient ( AnnounceableInformation torrent ) { final URI uri = getURIForTorrent ( torrent ) ; if ( uri == null ) return null ; return this . clients . get ( uri . toString ( ) ) ; }
Returns the current tracker client used for announces .
32,802
public static BEValue bdecode ( ByteBuffer data ) throws IOException { return BDecoder . bdecode ( new ByteArrayInputStream ( data . array ( ) ) ) ; }
Decode a B - encoded byte buffer .
32,803
public BEValue bdecode ( ) throws IOException { if ( this . getNextIndicator ( ) == - 1 ) return null ; if ( this . indicator >= '0' && this . indicator <= '9' ) return this . bdecodeBytes ( ) ; else if ( this . indicator == 'i' ) return this . bdecodeNumber ( ) ; else if ( this . indicator == 'l' ) return this . bdecodeList ( ) ; else if ( this . indicator == 'd' ) return this . bdecodeMap ( ) ; else throw new InvalidBEncodingException ( "Unknown indicator '" + this . indicator + "'" ) ; }
Gets the next indicator and returns either null when the stream has ended or b - decodes the rest of the stream and returns the appropriate BEValue encoded object .
32,804
public BEValue bdecodeBytes ( ) throws IOException { int c = this . getNextIndicator ( ) ; int num = c - '0' ; if ( num < 0 || num > 9 ) throw new InvalidBEncodingException ( "Number expected, not '" + ( char ) c + "'" ) ; this . indicator = 0 ; c = this . read ( ) ; int i = c - '0' ; while ( i >= 0 && i <= 9 ) { num = num * 10 + i ; c = this . read ( ) ; i = c - '0' ; } if ( c != ':' ) { throw new InvalidBEncodingException ( "Colon expected, not '" + ( char ) c + "'" ) ; } return new BEValue ( read ( num ) ) ; }
Returns the next b - encoded value on the stream and makes sure it is a byte array .
32,805
public BEValue bdecodeNumber ( ) throws IOException { int c = this . getNextIndicator ( ) ; if ( c != 'i' ) { throw new InvalidBEncodingException ( "Expected 'i', not '" + ( char ) c + "'" ) ; } this . indicator = 0 ; c = this . read ( ) ; if ( c == '0' ) { c = this . read ( ) ; if ( c == 'e' ) return new BEValue ( BigInteger . ZERO ) ; else throw new InvalidBEncodingException ( "'e' expected after zero," + " not '" + ( char ) c + "'" ) ; } char [ ] chars = new char [ 256 ] ; int off = 0 ; if ( c == '-' ) { c = this . read ( ) ; if ( c == '0' ) throw new InvalidBEncodingException ( "Negative zero not allowed" ) ; chars [ off ] = '-' ; off ++ ; } if ( c < '1' || c > '9' ) throw new InvalidBEncodingException ( "Invalid Integer start '" + ( char ) c + "'" ) ; chars [ off ] = ( char ) c ; off ++ ; c = this . read ( ) ; int i = c - '0' ; while ( i >= 0 && i <= 9 ) { chars [ off ] = ( char ) c ; off ++ ; c = read ( ) ; i = c - '0' ; } if ( c != 'e' ) throw new InvalidBEncodingException ( "Integer should end with 'e'" ) ; String s = new String ( chars , 0 , off ) ; return new BEValue ( new BigInteger ( s ) ) ; }
Returns the next b - encoded value on the stream and makes sure it is a number .
32,806
public BEValue bdecodeList ( ) throws IOException { int c = this . getNextIndicator ( ) ; if ( c != 'l' ) { throw new InvalidBEncodingException ( "Expected 'l', not '" + ( char ) c + "'" ) ; } this . indicator = 0 ; List < BEValue > result = new ArrayList < BEValue > ( ) ; c = this . getNextIndicator ( ) ; while ( c != 'e' ) { result . add ( this . bdecode ( ) ) ; c = this . getNextIndicator ( ) ; } this . indicator = 0 ; return new BEValue ( result ) ; }
Returns the next b - encoded value on the stream and makes sure it is a list .
32,807
public boolean validate ( SharedTorrent torrent , Piece piece ) throws IOException { logger . trace ( "Validating {}..." , this ) ; byte [ ] pieceBytes = data . array ( ) ; final byte [ ] calculatedHash = TorrentUtils . calculateSha1Hash ( pieceBytes ) ; this . valid = Arrays . equals ( calculatedHash , this . hash ) ; logger . trace ( "validating result of piece {} is {}" , this . index , this . valid ) ; return this . isValid ( ) ; }
Validates this piece .
32,808
private ByteBuffer _read ( long offset , long length , ByteBuffer buffer ) throws IOException { if ( offset + length > this . length ) { throw new IllegalArgumentException ( "Piece#" + this . index + " overrun (" + offset + " + " + length + " > " + this . length + ") !" ) ; } int position = buffer . position ( ) ; byte [ ] bytes = this . pieceStorage . readPiecePart ( this . index , ( int ) offset , ( int ) length ) ; buffer . put ( bytes ) ; buffer . rewind ( ) ; buffer . limit ( bytes . length + position ) ; return buffer ; }
Internal piece data read function .
32,809
public ByteBuffer read ( long offset , int length , ByteBuffer block ) throws IllegalArgumentException , IllegalStateException , IOException { if ( ! this . valid ) { throw new IllegalStateException ( "Attempting to read an " + "known-to-be invalid piece!" ) ; } return this . _read ( offset , length , block ) ; }
Read a piece block from the underlying byte storage .
32,810
public void record ( ByteBuffer block , int offset ) { if ( this . data == null ) { this . data = ByteBuffer . allocate ( ( int ) this . length ) ; } int pos = block . position ( ) ; this . data . position ( offset ) ; this . data . put ( block ) ; block . position ( pos ) ; }
Record the given block at the given offset in this piece .
32,811
public int compareTo ( Piece other ) { if ( this . equals ( other ) ) { return 0 ; } else if ( this . seen == other . seen ) { return new Integer ( this . index ) . compareTo ( other . index ) ; } else if ( this . seen < other . seen ) { return - 1 ; } else { return 1 ; } }
Piece comparison function for ordering pieces based on their availability .
32,812
public void addPeer ( TrackedPeer peer ) { this . peers . put ( new PeerUID ( peer . getAddress ( ) , this . getHexInfoHash ( ) ) , peer ) ; }
Add a peer exchanging on this torrent .
32,813
public List < Peer > getSomePeers ( Peer peer ) { List < Peer > peers = new LinkedList < Peer > ( ) ; List < TrackedPeer > candidates = new LinkedList < TrackedPeer > ( this . peers . values ( ) ) ; Collections . shuffle ( candidates ) ; int count = 0 ; for ( TrackedPeer candidate : candidates ) { if ( peer != null && peer . looksLike ( candidate ) ) { continue ; } if ( count ++ > this . answerPeers ) { break ; } peers . add ( candidate ) ; } return peers ; }
Get a list of peers we can return in an announce response for this torrent .
32,814
public static TrackedTorrent load ( File torrent ) throws IOException { TorrentMetadata torrentMetadata = new TorrentParser ( ) . parseFromFile ( torrent ) ; return new TrackedTorrent ( torrentMetadata . getInfoHash ( ) ) ; }
Load a tracked torrent from the given torrent file .
32,815
public TorrentManager addTorrent ( String dotTorrentFilePath , String downloadDirPath ) throws IOException { return addTorrent ( dotTorrentFilePath , downloadDirPath , FairPieceStorageFactory . INSTANCE ) ; }
Adds torrent to storage validate downloaded files and start seeding and leeching the torrent
32,816
public TorrentManager addTorrent ( String dotTorrentFilePath , String downloadDirPath , List < TorrentListener > listeners ) throws IOException { return addTorrent ( dotTorrentFilePath , downloadDirPath , FairPieceStorageFactory . INSTANCE , listeners ) ; }
Adds torrent to storage with specified listeners validate downloaded files and start seeding and leeching the torrent
32,817
public TorrentManager addTorrent ( TorrentMetadataProvider metadataProvider , PieceStorage pieceStorage ) throws IOException { return addTorrent ( metadataProvider , pieceStorage , Collections . < TorrentListener > emptyList ( ) ) ; }
Adds torrent to storage with any storage and metadata source
32,818
public TorrentManager addTorrent ( TorrentMetadataProvider metadataProvider , PieceStorage pieceStorage , List < TorrentListener > listeners ) throws IOException { TorrentMetadata torrentMetadata = metadataProvider . getTorrentMetadata ( ) ; EventDispatcher eventDispatcher = new EventDispatcher ( ) ; for ( TorrentListener listener : listeners ) { eventDispatcher . addListener ( listener ) ; } final LoadedTorrentImpl loadedTorrent = new LoadedTorrentImpl ( new TorrentStatistic ( ) , metadataProvider , torrentMetadata , pieceStorage , eventDispatcher ) ; if ( pieceStorage . isFinished ( ) ) { loadedTorrent . getTorrentStatistic ( ) . setLeft ( 0 ) ; } else { long left = calculateLeft ( pieceStorage , torrentMetadata ) ; loadedTorrent . getTorrentStatistic ( ) . setLeft ( left ) ; } eventDispatcher . multicaster ( ) . validationComplete ( pieceStorage . getAvailablePieces ( ) . cardinality ( ) , torrentMetadata . getPiecesCount ( ) ) ; this . torrentsStorage . addTorrent ( loadedTorrent . getTorrentHash ( ) . getHexInfoHash ( ) , loadedTorrent ) ; forceAnnounceAndLogError ( loadedTorrent , pieceStorage . isFinished ( ) ? COMPLETED : STARTED ) ; logger . debug ( String . format ( "Added torrent %s (%s)" , loadedTorrent , loadedTorrent . getTorrentHash ( ) . getHexInfoHash ( ) ) ) ; return new TorrentManagerImpl ( eventDispatcher , loadedTorrent . getTorrentHash ( ) ) ; }
Adds torrent to storage with any storage metadata source and specified listeners
32,819
public void removeTorrent ( String torrentHash ) { logger . debug ( "Stopping seeding " + torrentHash ) ; final Pair < SharedTorrent , LoadedTorrent > torrents = torrentsStorage . remove ( torrentHash ) ; SharedTorrent torrent = torrents . first ( ) ; if ( torrent != null ) { torrent . setClientState ( ClientState . DONE ) ; torrent . closeFully ( ) ; } List < SharingPeer > peers = getPeersForTorrent ( torrentHash ) ; for ( SharingPeer peer : peers ) { peer . unbind ( true ) ; } sendStopEvent ( torrents . second ( ) , torrentHash ) ; }
Removes specified torrent from storage .
32,820
public boolean isSeed ( String hexInfoHash ) { SharedTorrent t = this . torrentsStorage . getTorrent ( hexInfoHash ) ; return t != null && t . isComplete ( ) ; }
Tells whether we are a seed for the torrent we re sharing .
32,821
public void handleAnnounceResponse ( int interval , int complete , int incomplete , String hexInfoHash ) { final SharedTorrent sharedTorrent = this . torrentsStorage . getTorrent ( hexInfoHash ) ; if ( sharedTorrent != null ) { sharedTorrent . setSeedersCount ( complete ) ; sharedTorrent . setLastAnnounceTime ( System . currentTimeMillis ( ) ) ; } setAnnounceInterval ( interval ) ; }
Handle an announce response event .
32,822
public void handleDiscoveredPeers ( List < Peer > peers , String hexInfoHash ) { if ( peers . size ( ) == 0 ) return ; SharedTorrent torrent = torrentsStorage . getTorrent ( hexInfoHash ) ; if ( torrent != null && torrent . isFinished ( ) ) return ; final LoadedTorrent announceableTorrent = torrentsStorage . getLoadedTorrent ( hexInfoHash ) ; if ( announceableTorrent == null ) { logger . info ( "announceable torrent {} is not found in storage. Maybe it was removed" , hexInfoHash ) ; return ; } if ( announceableTorrent . getPieceStorage ( ) . isFinished ( ) ) return ; logger . debug ( "Got {} peer(s) ({}) for {} in tracker response" , new Object [ ] { peers . size ( ) , Arrays . toString ( peers . toArray ( ) ) , hexInfoHash } ) ; Map < PeerUID , Peer > uniquePeers = new HashMap < PeerUID , Peer > ( ) ; for ( Peer peer : peers ) { final PeerUID peerUID = new PeerUID ( peer . getAddress ( ) , hexInfoHash ) ; if ( uniquePeers . containsKey ( peerUID ) ) continue ; uniquePeers . put ( peerUID , peer ) ; } for ( Map . Entry < PeerUID , Peer > e : uniquePeers . entrySet ( ) ) { PeerUID peerUID = e . getKey ( ) ; Peer peer = e . getValue ( ) ; boolean alreadyConnectedToThisPeer = peersStorage . getSharingPeer ( peerUID ) != null ; if ( alreadyConnectedToThisPeer ) { logger . debug ( "skipping peer {}, because we already connected to this peer" , peer ) ; continue ; } ConnectionListener connectionListener = new OutgoingConnectionListener ( this , announceableTorrent . getTorrentHash ( ) , peer . getIp ( ) , peer . getPort ( ) ) ; logger . debug ( "trying to connect to the peer {}" , peer ) ; boolean connectTaskAdded = this . myConnectionManager . offerConnect ( new ConnectTask ( peer . getIp ( ) , peer . getPort ( ) , connectionListener , new SystemTimeService ( ) . now ( ) , Constants . DEFAULT_CONNECTION_TIMEOUT_MILLIS ) , 1 , TimeUnit . SECONDS ) ; if ( ! connectTaskAdded ) { logger . info ( "can not connect to peer {}. Unable to add connect task to connection manager" , peer ) ; } } }
Handle the discovery of new peers .
32,823
public static String byteArrayToHexString ( byte [ ] bytes ) { char [ ] hexChars = new char [ bytes . length * 2 ] ; for ( int j = 0 ; j < bytes . length ; j ++ ) { int v = bytes [ j ] & 0xFF ; hexChars [ j * 2 ] = HEX_SYMBOLS [ v >>> 4 ] ; hexChars [ j * 2 + 1 ] = HEX_SYMBOLS [ v & 0x0F ] ; } return new String ( hexChars ) ; }
Convert a byte string to a string containing an hexadecimal representation of the original data .
32,824
@ ConditionalOnMissingBean ( ZookeeperHealthIndicator . class ) @ ConditionalOnBean ( CuratorFramework . class ) @ ConditionalOnEnabledHealthIndicator ( "zookeeper" ) public ZookeeperHealthIndicator zookeeperHealthIndicator ( CuratorFramework curator ) { return new ZookeeperHealthIndicator ( curator ) ; }
If there is an active curator if the zookeeper health endpoint is enabled and if a health indicator hasn t already been added by a user add one .
32,825
private void createProxies ( ) { source = createProxy ( sourceType ) ; destination = createProxy ( destinationType ) ; for ( VisitedMapping mapping : visitedMappings ) { createAccessorProxies ( source , mapping . sourceAccessors ) ; createAccessorProxies ( destination , mapping . destinationAccessors ) ; } }
Creates the source and destination proxy models .
32,826
private void validateRecordedMapping ( ) { if ( currentMapping . destinationMutators == null || currentMapping . destinationMutators . isEmpty ( ) ) errors . missingDestination ( ) ; else if ( options . skipType == 0 && ( currentMapping . sourceAccessors == null || currentMapping . sourceAccessors . isEmpty ( ) ) && currentMapping . destinationMutators . get ( currentMapping . destinationMutators . size ( ) - 1 ) . getPropertyType ( ) . equals ( PropertyType . FIELD ) && options . converter == null && ! options . mapFromSource && sourceConstant == null ) errors . missingSource ( ) ; else if ( options . skipType == 2 && options . condition != null ) errors . conditionalSkipWithoutSource ( ) ; }
Validates the current mapping that was recorded via a MapExpression .
32,827
@ SuppressWarnings ( "unchecked" ) static < T > TypeInfoImpl < T > typeInfoFor ( Class < T > sourceType , InheritingConfiguration configuration ) { TypeInfoKey pair = new TypeInfoKey ( sourceType , configuration ) ; TypeInfoImpl < T > typeInfo = ( TypeInfoImpl < T > ) cache . get ( pair ) ; if ( typeInfo == null ) { synchronized ( cache ) { typeInfo = ( TypeInfoImpl < T > ) cache . get ( pair ) ; if ( typeInfo == null ) { typeInfo = new TypeInfoImpl < T > ( null , sourceType , configuration ) ; cache . put ( pair , typeInfo ) ; } } } return typeInfo ; }
Returns a statically cached TypeInfoImpl instance for the given criteria .
32,828
public static boolean mightContainsProperties ( Class < ? > type ) { return type != Object . class && type != String . class && type != Date . class && type != Calendar . class && ! Primitives . isPrimitive ( type ) && ! Iterables . isIterable ( type ) && ! Types . isGroovyType ( type ) ; }
Returns whether the type might contains properties or not .
32,829
private void mergeMappings ( TypeMap < ? , ? > destinationMap ) { for ( Mapping mapping : destinationMap . getMappings ( ) ) { InternalMapping internalMapping = ( InternalMapping ) mapping ; mergedMappings . add ( internalMapping . createMergedCopy ( propertyNameInfo . getSourceProperties ( ) , propertyNameInfo . getDestinationProperties ( ) ) ) ; } }
Merges mappings from an existing TypeMap into the type map under construction .
32,830
private boolean isConvertable ( Mapping mapping ) { if ( mapping == null || mapping . getProvider ( ) != null || ! ( mapping instanceof PropertyMapping ) ) return false ; PropertyMapping propertyMapping = ( PropertyMapping ) mapping ; boolean hasSupportConverter = converterStore . getFirstSupported ( propertyMapping . getLastSourceProperty ( ) . getType ( ) , mapping . getLastDestinationProperty ( ) . getType ( ) ) != null ; boolean hasSupportTypeMap = typeMapStore . get ( propertyMapping . getLastSourceProperty ( ) . getType ( ) , mapping . getLastDestinationProperty ( ) . getType ( ) , null ) != null ; return hasSupportConverter || hasSupportTypeMap ; }
Indicates whether the mapping represents a PropertyMapping that is convertible to the destination type .
32,831
static void mapAutomatically ( ) { Order order = createOrder ( ) ; ModelMapper modelMapper = new ModelMapper ( ) ; OrderDTO orderDTO = modelMapper . map ( order , OrderDTO . class ) ; assertOrdersEqual ( order , orderDTO ) ; }
This example demonstrates how ModelMapper automatically maps properties from Order to OrderDTO .
32,832
static void mapExplicitly ( ) { Order order = createOrder ( ) ; ModelMapper modelMapper = new ModelMapper ( ) ; modelMapper . addMappings ( new PropertyMap < Order , OrderDTO > ( ) { protected void configure ( ) { map ( ) . setBillingStreet ( source . getBillingAddress ( ) . getStreet ( ) ) ; map ( source . billingAddress . getCity ( ) , destination . billingCity ) ; } } ) ; OrderDTO orderDTO = modelMapper . map ( order , OrderDTO . class ) ; assertOrdersEqual ( order , orderDTO ) ; }
This example demonstrates how ModelMapper can be used to explicitly map properties from an Order to OrderDTO .
32,833
public static < T > Collection < T > createCollection ( MappingContext < ? , Collection < T > > context ) { if ( context . getDestinationType ( ) . isInterface ( ) ) if ( SortedSet . class . isAssignableFrom ( context . getDestinationType ( ) ) ) return new TreeSet < T > ( ) ; else if ( Set . class . isAssignableFrom ( context . getDestinationType ( ) ) ) return new HashSet < T > ( ) ; else return new ArrayList < T > ( ) ; return context . getMappingEngine ( ) . createDestination ( context ) ; }
Creates a collection based on the destination type .
32,834
public static String format ( String heading , Collection < ErrorMessage > errorMessages ) { @ SuppressWarnings ( "resource" ) Formatter fmt = new Formatter ( ) . format ( heading ) . format ( ":%n%n" ) ; int index = 1 ; boolean displayCauses = getOnlyCause ( errorMessages ) == null ; for ( ErrorMessage errorMessage : errorMessages ) { fmt . format ( "%s) %s%n" , index ++ , errorMessage . getMessage ( ) ) ; Throwable cause = errorMessage . getCause ( ) ; if ( displayCauses && cause != null ) { StringWriter writer = new StringWriter ( ) ; cause . printStackTrace ( new PrintWriter ( writer ) ) ; fmt . format ( "Caused by: %s" , writer . getBuffer ( ) ) ; } fmt . format ( "%n" ) ; } if ( errorMessages . size ( ) == 1 ) fmt . format ( "1 error" ) ; else fmt . format ( "%s errors" , errorMessages . size ( ) ) ; return fmt . toString ( ) ; }
Returns the formatted message for an exception with the specified messages .
32,835
public Map < String , Accessor > getAccessors ( ) { if ( accessors == null ) synchronized ( this ) { if ( accessors == null ) accessors = PropertyInfoSetResolver . resolveAccessors ( source , type , configuration ) ; } return accessors ; }
Lazily initializes and gets accessors .
32,836
public Map < String , Mutator > getMutators ( ) { if ( mutators == null ) synchronized ( this ) { if ( mutators == null ) mutators = PropertyInfoSetResolver . resolveMutators ( type , configuration ) ; } return mutators ; }
Lazily initializes and gets mutators .
32,837
static synchronized Accessor accessorFor ( Class < ? > type , Method method , Configuration configuration , String name ) { PropertyInfoKey key = new PropertyInfoKey ( type , name , configuration ) ; Accessor accessor = ACCESSOR_CACHE . get ( key ) ; if ( accessor == null ) { accessor = new MethodAccessor ( type , method , name ) ; ACCESSOR_CACHE . put ( key , accessor ) ; } return accessor ; }
Returns an Accessor for the given accessor method . The method must be externally validated to ensure that it accepts zero arguments and does not return void . class .
32,838
static synchronized FieldPropertyInfo fieldPropertyFor ( Class < ? > type , Field field , Configuration configuration , String name ) { PropertyInfoKey key = new PropertyInfoKey ( type , name , configuration ) ; FieldPropertyInfo fieldPropertyInfo = FIELD_CACHE . get ( key ) ; if ( fieldPropertyInfo == null ) { fieldPropertyInfo = new FieldPropertyInfo ( type , field , name ) ; FIELD_CACHE . put ( key , fieldPropertyInfo ) ; } return fieldPropertyInfo ; }
Returns a FieldPropertyInfo instance for the given field .
32,839
static synchronized Mutator mutatorFor ( Class < ? > type , Method method , Configuration configuration , String name ) { PropertyInfoKey key = new PropertyInfoKey ( type , name , configuration ) ; Mutator mutator = MUTATOR_CACHE . get ( key ) ; if ( mutator == null ) { mutator = new MethodMutator ( type , method , name ) ; MUTATOR_CACHE . put ( key , mutator ) ; } return mutator ; }
Returns a Mutator instance for the given mutator method . The method must be externally validated to ensure that it accepts one argument and returns void . class .
32,840
@ SuppressWarnings ( "unchecked" ) public static int getLength ( Object iterable ) { Assert . state ( isIterable ( iterable . getClass ( ) ) ) ; return iterable . getClass ( ) . isArray ( ) ? Array . getLength ( iterable ) : ( ( Collection < Object > ) iterable ) . size ( ) ; }
Gets the length of an iterable .
32,841
@ SuppressWarnings ( "unchecked" ) public static Iterator < Object > iterator ( Object iterable ) { Assert . state ( isIterable ( iterable . getClass ( ) ) ) ; return iterable . getClass ( ) . isArray ( ) ? new ArrayIterator ( iterable ) : ( ( Iterable < Object > ) iterable ) . iterator ( ) ; }
Creates a iterator from given iterable .
32,842
@ SuppressWarnings ( "unchecked" ) public static Object getElement ( Object iterable , int index ) { if ( iterable . getClass ( ) . isArray ( ) ) return getElementFromArrary ( iterable , index ) ; if ( iterable instanceof Collection ) return getElementFromCollection ( ( Collection < Object > ) iterable , index ) ; return null ; }
Gets the element from an iterable with given index .
32,843
public static Object getElementFromArrary ( Object array , int index ) { try { return Array . get ( array , index ) ; } catch ( ArrayIndexOutOfBoundsException e ) { return null ; } }
Gets the element from an array with given index .
32,844
public static Object getElementFromCollection ( Collection < Object > collection , int index ) { if ( collection . size ( ) < index + 1 ) return null ; if ( collection instanceof List ) return ( ( List < Object > ) collection ) . get ( index ) ; Iterator < Object > iterator = collection . iterator ( ) ; for ( int i = 0 ; i < index ; i ++ ) { iterator . next ( ) ; } return iterator . next ( ) ; }
Gets the element from a collection with given index .
32,845
public synchronized String version ( ) throws IOException { if ( this . version == null ) { Process p = runFunc . run ( ImmutableList . of ( path , "-version" ) ) ; try { BufferedReader r = wrapInReader ( p ) ; this . version = r . readLine ( ) ; CharStreams . copy ( r , CharStreams . nullWriter ( ) ) ; throwOnError ( p ) ; } finally { p . destroy ( ) ; } } return version ; }
Returns the version string for this binary .
32,846
public List < String > path ( List < String > args ) throws IOException { return ImmutableList . < String > builder ( ) . add ( path ) . addAll ( args ) . build ( ) ; }
Returns the full path to the binary with arguments appended .
32,847
public static URI checkValidStream ( URI uri ) throws IllegalArgumentException { String scheme = checkNotNull ( uri ) . getScheme ( ) ; scheme = checkNotNull ( scheme , "URI is missing a scheme" ) . toLowerCase ( ) ; if ( rtps . contains ( scheme ) ) { return uri ; } if ( udpTcp . contains ( scheme ) ) { if ( uri . getPort ( ) == - 1 ) { throw new IllegalArgumentException ( "must set port when using udp or tcp scheme" ) ; } return uri ; } throw new IllegalArgumentException ( "not a valid output URL, must use rtp/tcp/udp scheme" ) ; }
Checks if the URI is valid for streaming to .
32,848
public void read ( NutDataInputStream in , long startcode ) throws IOException { this . startcode = startcode ; forwardPtr = in . readVarLong ( ) ; if ( forwardPtr > 4096 ) { long expected = in . getCRC ( ) ; checksum = in . readInt ( ) ; if ( checksum != expected ) { throw new IOException ( String . format ( "invalid header checksum %X want %X" , expected , checksum ) ) ; } } in . resetCRC ( ) ; end = in . offset ( ) + forwardPtr - 4 ; }
End byte of packet
32,849
public EncodingOptions buildOptions ( ) { return new EncodingOptions ( new MainEncodingOptions ( format , startOffset , duration ) , new AudioEncodingOptions ( audio_enabled , audio_codec , audio_channels , audio_sample_rate , audio_sample_format , audio_bit_rate , audio_quality ) , new VideoEncodingOptions ( video_enabled , video_codec , video_frame_rate , video_width , video_height , video_bit_rate , video_frames , video_filter , video_preset ) ) ; }
Returns a representation of this Builder that can be safely serialised .
32,850
protected void readFileId ( ) throws IOException { byte [ ] b = new byte [ HEADER . length ] ; in . readFully ( b ) ; if ( ! Arrays . equals ( b , HEADER ) ) { throw new IOException ( "file_id_string does not match. got: " + new String ( b , Charsets . ISO_8859_1 ) ) ; } }
Read the magic at the beginning of the file .
32,851
protected long readReservedHeaders ( ) throws IOException { long startcode = in . readStartCode ( ) ; while ( Startcode . isPossibleStartcode ( startcode ) && isKnownStartcode ( startcode ) ) { new Packet ( ) . read ( in , startcode ) ; startcode = in . readStartCode ( ) ; } return startcode ; }
Read headers we don t know how to parse yet returning the next startcode .
32,852
public void read ( ) throws IOException { readFileId ( ) ; in . resetCRC ( ) ; long startcode = in . readStartCode ( ) ; while ( true ) { header = new MainHeaderPacket ( ) ; if ( ! Startcode . MAIN . equalsCode ( startcode ) ) { throw new IOException ( String . format ( "expected main header found: 0x%X" , startcode ) ) ; } header . read ( in , startcode ) ; startcode = readReservedHeaders ( ) ; streams . clear ( ) ; for ( int i = 0 ; i < header . streamCount ; i ++ ) { if ( ! Startcode . STREAM . equalsCode ( startcode ) ) { throw new IOException ( String . format ( "expected stream header found: 0x%X" , startcode ) ) ; } StreamHeaderPacket streamHeader = new StreamHeaderPacket ( ) ; streamHeader . read ( in , startcode ) ; Stream stream = new Stream ( header , streamHeader ) ; streams . add ( stream ) ; listener . stream ( stream ) ; startcode = readReservedHeaders ( ) ; } while ( Startcode . INFO . equalsCode ( startcode ) ) { new Packet ( ) . read ( in , startcode ) ; startcode = readReservedHeaders ( ) ; } if ( Startcode . INDEX . equalsCode ( startcode ) ) { new Packet ( ) . read ( in , startcode ) ; startcode = in . readStartCode ( ) ; } while ( ! Startcode . MAIN . equalsCode ( startcode ) ) { if ( Startcode . SYNCPOINT . equalsCode ( startcode ) ) { new Packet ( ) . read ( in , startcode ) ; startcode = in . readStartCode ( ) ; } if ( Startcode . isPossibleStartcode ( startcode ) ) { throw new IOException ( "expected framecode, found " + Startcode . toString ( startcode ) ) ; } Frame f = new Frame ( ) ; f . read ( this , in , ( int ) startcode ) ; listener . frame ( f ) ; try { startcode = readReservedHeaders ( ) ; } catch ( java . io . EOFException e ) { return ; } } } }
Demux the inputstream
32,853
public T setVideoFrameRate ( Fraction frame_rate ) { this . video_enabled = true ; this . video_frame_rate = checkNotNull ( frame_rate ) ; return getThis ( ) ; }
Sets the video s frame rate
32,854
public T addMetaTag ( String key , String value ) { checkValidKey ( key ) ; checkNotEmpty ( value , "value must not be empty" ) ; meta_tags . add ( "-metadata" ) ; meta_tags . add ( key + "=" + value ) ; return getThis ( ) ; }
Add metadata on output streams . Which keys are possible depends on the used codec .
32,855
public T setAudioChannels ( int channels ) { checkArgument ( channels > 0 , "channels must be positive" ) ; this . audio_enabled = true ; this . audio_channels = channels ; return getThis ( ) ; }
Sets the number of audio channels
32,856
public T setAudioSampleRate ( int sample_rate ) { checkArgument ( sample_rate > 0 , "sample rate must be positive" ) ; this . audio_enabled = true ; this . audio_sample_rate = sample_rate ; return getThis ( ) ; }
Sets the Audio sample rate for example 44_000 .
32,857
public T setStartOffset ( long offset , TimeUnit units ) { checkNotNull ( units ) ; this . startOffset = units . toMillis ( offset ) ; return getThis ( ) ; }
Decodes but discards input until the offset .
32,858
public T setDuration ( long duration , TimeUnit units ) { checkNotNull ( units ) ; this . duration = units . toMillis ( duration ) ; return getThis ( ) ; }
Stop writing the output after duration is reached .
32,859
public T setAudioPreset ( String preset ) { this . audio_enabled = true ; this . audio_preset = checkNotEmpty ( preset , "audio preset must not be empty" ) ; return getThis ( ) ; }
Sets a audio preset to use .
32,860
public T setSubtitlePreset ( String preset ) { this . subtitle_enabled = true ; this . subtitle_preset = checkNotEmpty ( preset , "subtitle preset must not be empty" ) ; return getThis ( ) ; }
Sets a subtitle preset to use .
32,861
public int readVarInt ( ) throws IOException { boolean more ; int result = 0 ; do { int b = in . readUnsignedByte ( ) ; more = ( b & 0x80 ) == 0x80 ; result = 128 * result + ( b & 0x7F ) ; } while ( more ) ; return result ; }
Read a simple var int up to 32 bits
32,862
public long readVarLong ( ) throws IOException { boolean more ; long result = 0 ; do { int b = in . readUnsignedByte ( ) ; more = ( b & 0x80 ) == 0x80 ; result = 128 * result + ( b & 0x7F ) ; } while ( more ) ; return result ; }
Read a simple var int up to 64 bits
32,863
public byte [ ] readVarArray ( ) throws IOException { int len = ( int ) readVarLong ( ) ; byte [ ] result = new byte [ len ] ; in . read ( result ) ; return result ; }
Read a array with a varint prefixed length
32,864
public long readStartCode ( ) throws IOException { byte frameCode = in . readByte ( ) ; if ( frameCode != 'N' ) { return ( long ) ( frameCode & 0xff ) ; } byte [ ] buffer = new byte [ 8 ] ; buffer [ 0 ] = frameCode ; readFully ( buffer , 1 , 7 ) ; return ( ( ( long ) buffer [ 0 ] << 56 ) + ( ( long ) ( buffer [ 1 ] & 255 ) << 48 ) + ( ( long ) ( buffer [ 2 ] & 255 ) << 40 ) + ( ( long ) ( buffer [ 3 ] & 255 ) << 32 ) + ( ( long ) ( buffer [ 4 ] & 255 ) << 24 ) + ( ( buffer [ 5 ] & 255 ) << 16 ) + ( ( buffer [ 6 ] & 255 ) << 8 ) + ( ( buffer [ 7 ] & 255 ) << 0 ) ) ; }
Returns the start code OR frame_code if the code doesn t start with N
32,865
public static StreamSpecifier stream ( StreamSpecifierType type , int index ) { checkNotNull ( type ) ; return new StreamSpecifier ( type . toString ( ) + ":" + index ) ; }
Matches the stream number stream_index of this type .
32,866
public static StreamSpecifier tag ( String key , String value ) { checkValidKey ( key ) ; checkNotNull ( value ) ; return new StreamSpecifier ( "m:" + key + ":" + value ) ; }
Matches streams with the metadata tag key having the specified value .
32,867
protected boolean parseLine ( String line ) { line = checkNotNull ( line ) . trim ( ) ; if ( line . isEmpty ( ) ) { return false ; } final String [ ] args = line . split ( "=" , 2 ) ; if ( args . length != 2 ) { return false ; } final String key = checkNotNull ( args [ 0 ] ) ; final String value = checkNotNull ( args [ 1 ] ) ; switch ( key ) { case "frame" : frame = Long . parseLong ( value ) ; return false ; case "fps" : fps = Fraction . getFraction ( value ) ; return false ; case "bitrate" : if ( value . equals ( "N/A" ) ) { bitrate = - 1 ; } else { bitrate = FFmpegUtils . parseBitrate ( value ) ; } return false ; case "total_size" : if ( value . equals ( "N/A" ) ) { total_size = - 1 ; } else { total_size = Long . parseLong ( value ) ; } return false ; case "out_time_ms" : return false ; case "out_time" : out_time_ns = fromTimecode ( value ) ; return false ; case "dup_frames" : dup_frames = Long . parseLong ( value ) ; return false ; case "drop_frames" : drop_frames = Long . parseLong ( value ) ; return false ; case "speed" : if ( value . equals ( "N/A" ) ) { speed = - 1 ; } else { speed = Float . parseFloat ( value . replace ( "x" , "" ) ) ; } return false ; case "progress" : status = Status . of ( value ) ; return true ; default : if ( key . startsWith ( "stream_" ) ) { } else { LOG . warn ( "skipping unhandled key: {} = {}" , key , value ) ; } return false ; } }
Parses values from the line into this object .
32,868
static URI createUri ( String scheme , InetAddress address , int port ) throws URISyntaxException { checkNotNull ( address ) ; return new URI ( scheme , null , InetAddresses . toUriString ( address ) , port , null , null , null ) ; }
Creates a URL to parse to FFmpeg based on the scheme address and port .
32,869
public synchronized void start ( ) { if ( thread != null ) { throw new IllegalThreadStateException ( "Parser already started" ) ; } String name = getThreadName ( ) + "(" + getUri ( ) . toString ( ) + ")" ; CountDownLatch startSignal = new CountDownLatch ( 1 ) ; Runnable runnable = getRunnable ( startSignal ) ; thread = new Thread ( runnable , name ) ; thread . start ( ) ; try { startSignal . await ( ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } }
Starts the ProgressParser waiting for progress .
32,870
public static long parseBitrate ( String bitrate ) { if ( "N/A" . equals ( bitrate ) ) { return - 1 ; } Matcher m = BITRATE_REGEX . matcher ( bitrate ) ; if ( ! m . find ( ) ) { throw new IllegalArgumentException ( "Invalid bitrate '" + bitrate + "'" ) ; } return ( long ) ( Float . parseFloat ( m . group ( 1 ) ) * 1000 ) ; }
Converts a string representation of bitrate to a long of bits per second
32,871
public static int waitForWithTimeout ( final Process p , long timeout , TimeUnit unit ) throws TimeoutException { ProcessThread t = new ProcessThread ( p ) ; t . start ( ) ; try { unit . timedJoin ( t , timeout ) ; } catch ( InterruptedException e ) { t . interrupt ( ) ; Thread . currentThread ( ) . interrupt ( ) ; } if ( ! t . hasFinished ( ) ) { throw new TimeoutException ( "Process did not finish within timeout" ) ; } return t . exitValue ( ) ; }
Waits until a process finishes or a timeout occurs
32,872
public T get ( ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { if ( ex == null ) { return type ; } if ( ex instanceof InvalidBucketNameException ) { throw ( InvalidBucketNameException ) ex ; } else if ( ex instanceof NoSuchAlgorithmException ) { throw ( NoSuchAlgorithmException ) ex ; } else if ( ex instanceof InsufficientDataException ) { throw ( InsufficientDataException ) ex ; } else if ( ex instanceof IOException ) { throw ( IOException ) ex ; } else if ( ex instanceof InvalidKeyException ) { throw ( InvalidKeyException ) ex ; } else if ( ex instanceof NoResponseException ) { throw ( NoResponseException ) ex ; } else if ( ex instanceof XmlPullParserException ) { throw ( XmlPullParserException ) ex ; } else if ( ex instanceof ErrorResponseException ) { throw ( ErrorResponseException ) ex ; } else { throw ( InternalException ) ex ; } }
Returns given Type if exception is null else respective exception is thrown .
32,873
private boolean isValidEndpoint ( String endpoint ) { if ( InetAddressValidator . getInstance ( ) . isValid ( endpoint ) ) { return true ; } if ( endpoint . length ( ) < 1 || endpoint . length ( ) > 253 ) { return false ; } for ( String label : endpoint . split ( "\\." ) ) { if ( label . length ( ) < 1 || label . length ( ) > 63 ) { return false ; } if ( ! ( label . matches ( "^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$" ) ) ) { return false ; } } return true ; }
Returns true if given endpoint is valid else false .
32,874
private void checkBucketName ( String name ) throws InvalidBucketNameException { if ( name == null ) { throw new InvalidBucketNameException ( NULL_STRING , "null bucket name" ) ; } if ( name . length ( ) < 3 || name . length ( ) > 63 ) { String msg = "bucket name must be at least 3 and no more than 63 characters long" ; throw new InvalidBucketNameException ( name , msg ) ; } if ( name . matches ( "\\.\\." ) ) { String msg = "bucket name cannot contain successive periods. For more information refer " + "http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html" ; throw new InvalidBucketNameException ( name , msg ) ; } if ( ! name . matches ( "^[a-z0-9][a-z0-9\\.\\-]+[a-z0-9]$" ) ) { String msg = "bucket name does not follow Amazon S3 standards. For more information refer " + "http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html" ; throw new InvalidBucketNameException ( name , msg ) ; } }
Validates if given bucket name is DNS compatible .
32,875
public void setTimeout ( long connectTimeout , long writeTimeout , long readTimeout ) { this . httpClient = this . httpClient . newBuilder ( ) . connectTimeout ( connectTimeout , TimeUnit . MILLISECONDS ) . writeTimeout ( writeTimeout , TimeUnit . MILLISECONDS ) . readTimeout ( readTimeout , TimeUnit . MILLISECONDS ) . build ( ) ; }
Sets HTTP connect write and read timeouts . A value of 0 means no timeout otherwise values must be between 1 and Integer . MAX_VALUE when converted to milliseconds .
32,876
@ SuppressFBWarnings ( value = "SIC" , justification = "Should not be used in production anyways." ) public void ignoreCertCheck ( ) throws NoSuchAlgorithmException , KeyManagementException { final TrustManager [ ] trustAllCerts = new TrustManager [ ] { new X509TrustManager ( ) { public void checkClientTrusted ( X509Certificate [ ] chain , String authType ) throws CertificateException { } public void checkServerTrusted ( X509Certificate [ ] chain , String authType ) throws CertificateException { } public X509Certificate [ ] getAcceptedIssuers ( ) { return new X509Certificate [ ] { } ; } } } ; final SSLContext sslContext = SSLContext . getInstance ( "SSL" ) ; sslContext . init ( null , trustAllCerts , new java . security . SecureRandom ( ) ) ; final SSLSocketFactory sslSocketFactory = sslContext . getSocketFactory ( ) ; this . httpClient = this . httpClient . newBuilder ( ) . sslSocketFactory ( sslSocketFactory , ( X509TrustManager ) trustAllCerts [ 0 ] ) . hostnameVerifier ( new HostnameVerifier ( ) { public boolean verify ( String hostname , SSLSession session ) { return true ; } } ) . build ( ) ; }
Ignores check on server certificate for HTTPS connection .
32,877
private boolean shouldOmitPortInHostHeader ( HttpUrl url ) { return ( url . scheme ( ) . equals ( "http" ) && url . port ( ) == 80 ) || ( url . scheme ( ) . equals ( "https" ) && url . port ( ) == 443 ) ; }
Checks whether port should be omitted in Host header .
32,878
private HttpResponse execute ( Method method , String region , String bucketName , String objectName , Map < String , String > headerMap , Map < String , String > queryParamMap , Object body , int length ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { if ( headerMap != null ) { headerMap = normalizeHeaders ( headerMap ) ; } Multimap < String , String > queryParamMultiMap = null ; if ( queryParamMap != null ) { queryParamMultiMap = Multimaps . forMap ( queryParamMap ) ; } Multimap < String , String > headerMultiMap = null ; if ( headerMap != null ) { headerMultiMap = Multimaps . forMap ( headerMap ) ; } return executeReq ( method , region , bucketName , objectName , headerMultiMap , queryParamMultiMap , body , length ) ; }
Executes given request parameters .
32,879
private void updateRegionCache ( String bucketName ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { if ( bucketName != null && this . accessKey != null && this . secretKey != null && ! BucketRegionCache . INSTANCE . exists ( bucketName ) ) { Map < String , String > queryParamMap = new HashMap < > ( ) ; queryParamMap . put ( "location" , null ) ; HttpResponse response = execute ( Method . GET , US_EAST_1 , bucketName , "/" , null , queryParamMap , null , 0 ) ; XmlPullParser xpp = xmlPullParserFactory . newPullParser ( ) ; String location = null ; try ( ResponseBody body = response . body ( ) ) { xpp . setInput ( body . charStream ( ) ) ; while ( xpp . getEventType ( ) != XmlPullParser . END_DOCUMENT ) { if ( xpp . getEventType ( ) == XmlPullParser . START_TAG && "LocationConstraint" . equals ( xpp . getName ( ) ) ) { xpp . next ( ) ; location = getText ( xpp ) ; break ; } xpp . next ( ) ; } } String region ; if ( location == null ) { region = US_EAST_1 ; } else { if ( "EU" . equals ( location ) ) { region = "eu-west-1" ; } else { region = location ; } } BucketRegionCache . INSTANCE . set ( bucketName , region ) ; } }
Updates Region cache for given bucket .
32,880
private String getRegion ( String bucketName ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { String region ; if ( this . region == null || "" . equals ( this . region ) ) { updateRegionCache ( bucketName ) ; region = BucketRegionCache . INSTANCE . region ( bucketName ) ; } else { region = this . region ; } return region ; }
Computes region of a given bucket name . If set this . region is considered . Otherwise resort to the server location API .
32,881
private String getText ( XmlPullParser xpp ) throws XmlPullParserException { if ( xpp . getEventType ( ) == XmlPullParser . TEXT ) { return xpp . getText ( ) ; } return null ; }
Returns text of given XML element .
32,882
private HttpResponse executeGet ( String bucketName , String objectName , Map < String , String > headerMap , Map < String , String > queryParamMap ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { return execute ( Method . GET , getRegion ( bucketName ) , bucketName , objectName , headerMap , queryParamMap , null , 0 ) ; }
Executes GET method for given request parameters .
32,883
private HttpResponse executeHead ( String bucketName , String objectName , Map < String , String > headerMap ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { HttpResponse response = execute ( Method . HEAD , getRegion ( bucketName ) , bucketName , objectName , headerMap , null , null , 0 ) ; response . body ( ) . close ( ) ; return response ; }
Executes HEAD method for given request parameters .
32,884
private HttpResponse executeDelete ( String bucketName , String objectName , Map < String , String > queryParamMap ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { HttpResponse response = execute ( Method . DELETE , getRegion ( bucketName ) , bucketName , objectName , null , queryParamMap , null , 0 ) ; response . body ( ) . close ( ) ; return response ; }
Executes DELETE method for given request parameters .
32,885
private HttpResponse executePost ( String bucketName , String objectName , Map < String , String > headerMap , Map < String , String > queryParamMap , Object data ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { return execute ( Method . POST , getRegion ( bucketName ) , bucketName , objectName , headerMap , queryParamMap , data , 0 ) ; }
Executes POST method for given request parameters .
32,886
public String getObjectUrl ( String bucketName , String objectName ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { Request request = createRequest ( Method . GET , bucketName , objectName , getRegion ( bucketName ) , null , null , null , null , 0 ) ; HttpUrl url = request . url ( ) ; return url . toString ( ) ; }
Gets object s URL in given bucket . The URL is ONLY useful to retrieve the object s data if the object has public read permissions .
32,887
public void copyObject ( String bucketName , String objectName , String destBucketName ) throws InvalidKeyException , InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , NoResponseException , ErrorResponseException , InternalException , IOException , XmlPullParserException , InvalidArgumentException { copyObject ( bucketName , objectName , destBucketName , null , null , null ) ; }
Copy a source object into a new destination object with same object name .
32,888
public String getPresignedObjectUrl ( Method method , String bucketName , String objectName , Integer expires , Map < String , String > reqParams ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException , InvalidExpiresRangeException { if ( expires < 1 || expires > DEFAULT_EXPIRY_TIME ) { throw new InvalidExpiresRangeException ( expires , "expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME ) ; } byte [ ] body = null ; if ( method == Method . PUT || method == Method . POST ) { body = new byte [ 0 ] ; } Multimap < String , String > queryParamMap = null ; if ( reqParams != null ) { queryParamMap = HashMultimap . create ( ) ; for ( Map . Entry < String , String > m : reqParams . entrySet ( ) ) { queryParamMap . put ( m . getKey ( ) , m . getValue ( ) ) ; } } String region = getRegion ( bucketName ) ; Request request = createRequest ( method , bucketName , objectName , region , null , queryParamMap , null , body , 0 ) ; HttpUrl url = Signer . presignV4 ( request , region , accessKey , secretKey , expires ) ; return url . toString ( ) ; }
Returns a presigned URL string with given HTTP method expiry time and custom request params for a specific object in the bucket .
32,889
public String presignedGetObject ( String bucketName , String objectName , Integer expires , Map < String , String > reqParams ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException , InvalidExpiresRangeException { return getPresignedObjectUrl ( Method . GET , bucketName , objectName , expires , reqParams ) ; }
Returns an presigned URL to download the object in the bucket with given expiry time with custom request params .
32,890
public String presignedGetObject ( String bucketName , String objectName , Integer expires ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException , InvalidExpiresRangeException { return presignedGetObject ( bucketName , objectName , expires , null ) ; }
Returns an presigned URL to download the object in the bucket with given expiry time .
32,891
public String presignedPutObject ( String bucketName , String objectName , Integer expires ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException , InvalidExpiresRangeException { return getPresignedObjectUrl ( Method . PUT , bucketName , objectName , expires , null ) ; }
Returns a presigned URL to upload an object in the bucket with given expiry time .
32,892
public void removeObject ( String bucketName , String objectName ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException , InvalidArgumentException { if ( ( bucketName == null ) || ( bucketName . isEmpty ( ) ) ) { throw new InvalidArgumentException ( "bucket name cannot be empty" ) ; } if ( ( objectName == null ) || ( objectName . isEmpty ( ) ) ) { throw new InvalidArgumentException ( "object name cannot be empty" ) ; } executeDelete ( bucketName , objectName , null ) ; }
Removes an object from a bucket .
32,893
public Iterable < Result < Item > > listObjects ( final String bucketName ) throws XmlPullParserException { return listObjects ( bucketName , null ) ; }
Lists object information in given bucket .
32,894
public Iterable < Result < Item > > listObjects ( final String bucketName , final String prefix ) throws XmlPullParserException { return listObjects ( bucketName , prefix , true ) ; }
Lists object information in given bucket and prefix .
32,895
public List < Bucket > listBuckets ( ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { HttpResponse response = executeGet ( null , null , null , null ) ; ListAllMyBucketsResult result = new ListAllMyBucketsResult ( ) ; result . parseXml ( response . body ( ) . charStream ( ) ) ; response . body ( ) . close ( ) ; return result . buckets ( ) ; }
Returns all bucket information owned by the current user .
32,896
public boolean bucketExists ( String bucketName ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { try { executeHead ( bucketName , null ) ; return true ; } catch ( ErrorResponseException e ) { if ( e . errorResponse ( ) . errorCode ( ) != ErrorCode . NO_SUCH_BUCKET ) { throw e ; } } return false ; }
Checks if given bucket exist and is having read access .
32,897
public void makeBucket ( String bucketName ) throws InvalidBucketNameException , RegionConflictException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { this . makeBucket ( bucketName , null ) ; }
Creates a bucket with default region .
32,898
public void makeBucket ( String bucketName , String region ) throws InvalidBucketNameException , RegionConflictException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { if ( region == null ) { region = this . region ; } if ( this . region != null && ! this . region . equals ( region ) ) { throw new RegionConflictException ( "passed region conflicts with the one previously specified" ) ; } String configString ; if ( region == null || US_EAST_1 . equals ( region ) ) { region = US_EAST_1 ; configString = "" ; } else { CreateBucketConfiguration config = new CreateBucketConfiguration ( region ) ; configString = config . toString ( ) ; } HttpResponse response = executePut ( bucketName , null , null , null , region , configString , 0 ) ; response . body ( ) . close ( ) ; }
Creates a bucket with given region .
32,899
private String putObject ( String bucketName , String objectName , int length , Object data , String uploadId , int partNumber , Map < String , String > headerMap ) throws InvalidBucketNameException , NoSuchAlgorithmException , InsufficientDataException , IOException , InvalidKeyException , NoResponseException , XmlPullParserException , ErrorResponseException , InternalException { HttpResponse response = null ; Map < String , String > queryParamMap = null ; if ( partNumber > 0 && uploadId != null && ! "" . equals ( uploadId ) ) { queryParamMap = new HashMap < > ( ) ; queryParamMap . put ( "partNumber" , Integer . toString ( partNumber ) ) ; queryParamMap . put ( UPLOAD_ID , uploadId ) ; } response = executePut ( bucketName , objectName , headerMap , queryParamMap , data , length ) ; response . body ( ) . close ( ) ; return response . header ( ) . etag ( ) ; }
Executes put object and returns ETag of the object .