idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
20,900 | public void blocker ( String blockerClass ) throws ClassNotFoundException , InstantiationException , IllegalAccessException { blockers . add ( Class . forName ( BLOCKER_PACKAGE + blockerClass ) . newInstance ( ) ) ; blockerNames . add ( blockerClass ) ; expt = null ; } | Load a blocker . | 64 | 4 |
20,901 | public void blocker ( String blockerClass , String param , String value ) throws ClassNotFoundException , InstantiationException , IllegalAccessException , InvocationTargetException , NoSuchMethodException { Blocker blocker = ( Blocker ) Class . forName ( BLOCKER_PACKAGE + blockerClass ) . newInstance ( ) ; // upperCase the first letter of param param = param . substring ( 0 , 1 ) . toUpperCase ( ) + param . substring ( 1 , param . length ( ) ) ; Method m = blocker . getClass ( ) . getMethod ( "set" + param , new Class [ ] { Boolean . class } ) ; m . invoke ( blocker , new Object [ ] { Boolean . valueOf ( value ) } ) ; blockers . add ( blocker ) ; blockerNames . add ( blockerClass ) ; expt = null ; } | Load a blocker with optional boolean value | 182 | 7 |
20,902 | public void compute ( ) { if ( ! computable ) { throw new RuntimeException ( "can't re-'compute' experiment results after a 'restore'" ) ; } expt = new MatchExpt [ blockers . size ( ) ] [ learners . size ( ) ] [ datasets . size ( ) ] ; for ( int i = 0 ; i < blockers . size ( ) ; i ++ ) { Blocker blocker = ( Blocker ) blockers . get ( i ) ; for ( int j = 0 ; j < learners . size ( ) ; j ++ ) { StringDistanceLearner distance = ( StringDistanceLearner ) learners . get ( j ) ; for ( int k = 0 ; k < datasets . size ( ) ; k ++ ) { MatchData dataset = ( MatchData ) datasets . get ( k ) ; expt [ i ] [ j ] [ k ] = new MatchExpt ( dataset , distance , blocker ) ; } } } } | Compute learners . | 200 | 4 |
20,903 | public void table ( String what ) throws NoSuchMethodException , IllegalAccessException , InvocationTargetException { PrintfFormat dfmt = new PrintfFormat ( "Dataset %2d:" ) ; PrintfFormat fmt = new PrintfFormat ( " %9.5f " ) ; PrintfFormat nfmt = new PrintfFormat ( " %11s" ) ; if ( expt == null ) compute ( ) ; for ( int i = 0 ; i < blockerNames . size ( ) ; i ++ ) { System . out . println ( "\nblocker: " + blockerNames . get ( i ) + "\n" ) ; System . out . print ( " " ) ; for ( int j = 0 ; j < learnerNames . size ( ) ; j ++ ) { String s = ( String ) learnerNames . get ( j ) ; if ( s . length ( ) > 11 ) s = s . substring ( 0 , 11 ) ; System . out . print ( nfmt . sprintf ( s ) ) ; } System . out . println ( ) ; double [ ] average = new double [ learnerNames . size ( ) ] ; for ( int k = 0 ; k < datasetNames . size ( ) ; k ++ ) { System . out . print ( dfmt . sprintf ( k + 1 ) ) ; for ( int j = 0 ; j < learnerNames . size ( ) ; j ++ ) { Method m = MatchExpt . class . getMethod ( what , new Class [ ] { } ) ; Double d = ( Double ) m . invoke ( expt [ i ] [ j ] [ k ] , new Object [ ] { } ) ; System . out . print ( fmt . sprintf ( d ) ) ; average [ j ] += d . doubleValue ( ) ; } System . out . print ( "\n" ) ; } System . out . print ( " Average:" ) ; for ( int j = 0 ; j < learnerNames . size ( ) ; j ++ ) { System . out . print ( fmt . sprintf ( average [ j ] / datasetNames . size ( ) ) ) ; } System . out . print ( "\n\n" ) ; } } | Show a table of some expt - wide numeric measurement . | 473 | 12 |
20,904 | public void save ( String file ) throws IOException , FileNotFoundException { ObjectOutputStream oos = new ObjectOutputStream ( new FileOutputStream ( file ) ) ; oos . writeObject ( blockerNames ) ; oos . writeObject ( datasetNames ) ; oos . writeObject ( learnerNames ) ; oos . writeObject ( expt ) ; oos . close ( ) ; } | Save current experimental data to a file | 85 | 7 |
20,905 | public void restore ( String file ) throws IOException , FileNotFoundException , ClassNotFoundException { ObjectInputStream ois = new ObjectInputStream ( new FileInputStream ( file ) ) ; blockerNames = ( List ) ois . readObject ( ) ; datasetNames = ( List ) ois . readObject ( ) ; learnerNames = ( List ) ois . readObject ( ) ; expt = ( MatchExpt [ ] [ ] [ ] ) ois . readObject ( ) ; computable = false ; ois . close ( ) ; } | Restore experimental data previously saved toa file . It will be possible to analyze this data with table commands and etc but not to perform additional experiments . | 119 | 30 |
20,906 | public void runScript ( String configFileName ) { int lineNum = 0 ; try { BufferedReader in = new BufferedReader ( new FileReader ( configFileName ) ) ; String line ; while ( ( line = in . readLine ( ) ) != null ) { lineNum ++ ; if ( ! line . startsWith ( "#" ) ) { String command = null ; List args = new ArrayList ( ) ; StringTokenizer tok = new StringTokenizer ( line ) ; if ( tok . hasMoreTokens ( ) ) { command = tok . nextToken ( ) ; } while ( tok . hasMoreTokens ( ) ) { args . add ( tok . nextToken ( ) ) ; } if ( command != null ) { if ( echoCommands ) System . out . println ( "exec: " + line ) ; execCommand ( command , args ) ; } } } } catch ( Exception e ) { System . out . println ( "Error: " + configFileName + " line " + lineNum + ": " + e . toString ( ) ) ; e . printStackTrace ( ) ; return ; } } | Load commands from a file and execute them . | 244 | 9 |
20,907 | private void execCommand ( String command , List args ) throws NoSuchMethodException , IllegalAccessException , InvocationTargetException { Class [ ] template = new Class [ args . size ( ) ] ; for ( int i = 0 ; i < args . size ( ) ; i ++ ) { template [ i ] = String . class ; } Method m = MatchExptScript . class . getMethod ( command , template ) ; m . invoke ( this , args . toArray ( new String [ 0 ] ) ) ; } | execute a single command | 108 | 4 |
20,908 | public StringWrapper prepare ( String s ) { BagOfTokens bag = new BagOfTokens ( s , tokenizer . tokenize ( s ) ) ; // reweight by -log( freq/collectionSize ) double normalizer = 0.0 ; for ( Iterator i = bag . tokenIterator ( ) ; i . hasNext ( ) ; ) { Token tok = ( Token ) i . next ( ) ; if ( collectionSize > 0 ) { Integer dfInteger = ( Integer ) documentFrequency . get ( tok ) ; // set previously unknown words to df==1, which gives them a high value double df = dfInteger == null ? 1.0 : dfInteger . intValue ( ) ; double w = - Math . log ( df / collectionSize ) ; bag . setWeight ( tok , w ) ; } else { bag . setWeight ( tok , Math . log ( 10 ) ) ; } } return bag ; } | Preprocess a string by finding tokens and giving them appropriate weights | 199 | 12 |
20,909 | public static String format ( String msg , Object ... args ) { if ( args == null || args . length == 0 ) return msg ; StringBuilder sb = new StringBuilder ( ) ; int argId = 0 ; for ( int i = 0 ; i < msg . length ( ) ; i ++ ) { final char c = msg . charAt ( i ) ; if ( c == ' ' && msg . charAt ( i + 1 ) == ' ' ) { if ( args . length > argId ) { Object val = args [ argId ++ ] ; if ( val == null ) sb . append ( "null" ) ; else sb . append ( val . toString ( ) ) ; } else { sb . append ( "{{MISSING ARG}}" ) ; } i ++ ; } else { sb . append ( c ) ; } } return sb . toString ( ) ; } | Similar to Slf4J logger | 193 | 7 |
20,910 | public Token [ ] tokenize ( String input ) { Token [ ] initialTokens = innerTokenizer . tokenize ( input ) ; List tokens = new ArrayList ( ) ; for ( int i = 0 ; i < initialTokens . length ; i ++ ) { Token tok = initialTokens [ i ] ; String str = "^" + tok . getValue ( ) + "$" ; if ( keepOldTokens ) tokens . add ( intern ( str ) ) ; for ( int lo = 0 ; lo < str . length ( ) ; lo ++ ) { for ( int len = minNGramSize ; len <= maxNGramSize ; len ++ ) { if ( lo + len < str . length ( ) ) { tokens . add ( innerTokenizer . intern ( str . substring ( lo , lo + len ) ) ) ; } } } } return ( Token [ ] ) tokens . toArray ( new BasicToken [ tokens . size ( ) ] ) ; } | Return tokenized version of a string . Tokens are all character n - grams that are part of a token produced by the inner tokenizer . | 203 | 28 |
20,911 | public FSArray getCategories ( ) { if ( Descriptor_Type . featOkTst && ( ( Descriptor_Type ) jcasType ) . casFeat_categories == null ) jcasType . jcas . throwFeatMissing ( "categories" , "de.julielab.jules.types.wikipedia.Descriptor" ) ; return ( FSArray ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Descriptor_Type ) jcasType ) . casFeatCode_categories ) ) ) ; } | getter for categories - gets List of Wikipedia categories associated with a Wikipedia page . | 144 | 16 |
20,912 | public void setCategories ( FSArray v ) { if ( Descriptor_Type . featOkTst && ( ( Descriptor_Type ) jcasType ) . casFeat_categories == null ) jcasType . jcas . throwFeatMissing ( "categories" , "de.julielab.jules.types.wikipedia.Descriptor" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( Descriptor_Type ) jcasType ) . casFeatCode_categories , jcasType . ll_cas . ll_getFSRef ( v ) ) ; } | setter for categories - sets List of Wikipedia categories associated with a Wikipedia page . | 140 | 16 |
20,913 | public Title getCategories ( int i ) { if ( Descriptor_Type . featOkTst && ( ( Descriptor_Type ) jcasType ) . casFeat_categories == null ) jcasType . jcas . throwFeatMissing ( "categories" , "de.julielab.jules.types.wikipedia.Descriptor" ) ; jcasType . jcas . checkArrayBounds ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Descriptor_Type ) jcasType ) . casFeatCode_categories ) , i ) ; return ( Title ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefArrayValue ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Descriptor_Type ) jcasType ) . casFeatCode_categories ) , i ) ) ) ; } | indexed getter for categories - gets an indexed value - List of Wikipedia categories associated with a Wikipedia page . | 215 | 22 |
20,914 | public void setCategories ( int i , Title v ) { if ( Descriptor_Type . featOkTst && ( ( Descriptor_Type ) jcasType ) . casFeat_categories == null ) jcasType . jcas . throwFeatMissing ( "categories" , "de.julielab.jules.types.wikipedia.Descriptor" ) ; jcasType . jcas . checkArrayBounds ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Descriptor_Type ) jcasType ) . casFeatCode_categories ) , i ) ; jcasType . ll_cas . ll_setRefArrayValue ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Descriptor_Type ) jcasType ) . casFeatCode_categories ) , i , jcasType . ll_cas . ll_getFSRef ( v ) ) ; } | indexed setter for categories - sets an indexed value - List of Wikipedia categories associated with a Wikipedia page . | 213 | 22 |
20,915 | public FSArray getOutgoingLinks ( ) { if ( Descriptor_Type . featOkTst && ( ( Descriptor_Type ) jcasType ) . casFeat_outgoingLinks == null ) jcasType . jcas . throwFeatMissing ( "outgoingLinks" , "de.julielab.jules.types.wikipedia.Descriptor" ) ; return ( FSArray ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Descriptor_Type ) jcasType ) . casFeatCode_outgoingLinks ) ) ) ; } | getter for outgoingLinks - gets List of outgoing links pointing to other Wikipedia pages starting at a Wikipedia page . | 148 | 22 |
20,916 | public void setOutgoingLinks ( FSArray v ) { if ( Descriptor_Type . featOkTst && ( ( Descriptor_Type ) jcasType ) . casFeat_outgoingLinks == null ) jcasType . jcas . throwFeatMissing ( "outgoingLinks" , "de.julielab.jules.types.wikipedia.Descriptor" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( Descriptor_Type ) jcasType ) . casFeatCode_outgoingLinks , jcasType . ll_cas . ll_getFSRef ( v ) ) ; } | setter for outgoingLinks - sets List of outgoing links pointing to other Wikipedia pages starting at a Wikipedia page . | 144 | 22 |
20,917 | public Title getOutgoingLinks ( int i ) { if ( Descriptor_Type . featOkTst && ( ( Descriptor_Type ) jcasType ) . casFeat_outgoingLinks == null ) jcasType . jcas . throwFeatMissing ( "outgoingLinks" , "de.julielab.jules.types.wikipedia.Descriptor" ) ; jcasType . jcas . checkArrayBounds ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Descriptor_Type ) jcasType ) . casFeatCode_outgoingLinks ) , i ) ; return ( Title ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefArrayValue ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Descriptor_Type ) jcasType ) . casFeatCode_outgoingLinks ) , i ) ) ) ; } | indexed getter for outgoingLinks - gets an indexed value - List of outgoing links pointing to other Wikipedia pages starting at a Wikipedia page . | 220 | 28 |
20,918 | public void setOutgoingLinks ( int i , Title v ) { if ( Descriptor_Type . featOkTst && ( ( Descriptor_Type ) jcasType ) . casFeat_outgoingLinks == null ) jcasType . jcas . throwFeatMissing ( "outgoingLinks" , "de.julielab.jules.types.wikipedia.Descriptor" ) ; jcasType . jcas . checkArrayBounds ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Descriptor_Type ) jcasType ) . casFeatCode_outgoingLinks ) , i ) ; jcasType . ll_cas . ll_setRefArrayValue ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Descriptor_Type ) jcasType ) . casFeatCode_outgoingLinks ) , i , jcasType . ll_cas . ll_getFSRef ( v ) ) ; } | indexed setter for outgoingLinks - sets an indexed value - List of outgoing links pointing to other Wikipedia pages starting at a Wikipedia page . | 218 | 28 |
20,919 | public StringArray getRedirects ( ) { if ( Descriptor_Type . featOkTst && ( ( Descriptor_Type ) jcasType ) . casFeat_redirects == null ) jcasType . jcas . throwFeatMissing ( "redirects" , "de.julielab.jules.types.wikipedia.Descriptor" ) ; return ( StringArray ) ( jcasType . ll_cas . ll_getFSForRef ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Descriptor_Type ) jcasType ) . casFeatCode_redirects ) ) ) ; } | getter for redirects - gets List of redirects pointing to a Wikipedia page . | 148 | 17 |
20,920 | public void setRedirects ( StringArray v ) { if ( Descriptor_Type . featOkTst && ( ( Descriptor_Type ) jcasType ) . casFeat_redirects == null ) jcasType . jcas . throwFeatMissing ( "redirects" , "de.julielab.jules.types.wikipedia.Descriptor" ) ; jcasType . ll_cas . ll_setRefValue ( addr , ( ( Descriptor_Type ) jcasType ) . casFeatCode_redirects , jcasType . ll_cas . ll_getFSRef ( v ) ) ; } | setter for redirects - sets List of redirects pointing to a Wikipedia page . | 144 | 17 |
20,921 | public String getRedirects ( int i ) { if ( Descriptor_Type . featOkTst && ( ( Descriptor_Type ) jcasType ) . casFeat_redirects == null ) jcasType . jcas . throwFeatMissing ( "redirects" , "de.julielab.jules.types.wikipedia.Descriptor" ) ; jcasType . jcas . checkArrayBounds ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Descriptor_Type ) jcasType ) . casFeatCode_redirects ) , i ) ; return jcasType . ll_cas . ll_getStringArrayValue ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Descriptor_Type ) jcasType ) . casFeatCode_redirects ) , i ) ; } | indexed getter for redirects - gets an indexed value - List of redirects pointing to a Wikipedia page . | 199 | 23 |
20,922 | public void setRedirects ( int i , String v ) { if ( Descriptor_Type . featOkTst && ( ( Descriptor_Type ) jcasType ) . casFeat_redirects == null ) jcasType . jcas . throwFeatMissing ( "redirects" , "de.julielab.jules.types.wikipedia.Descriptor" ) ; jcasType . jcas . checkArrayBounds ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Descriptor_Type ) jcasType ) . casFeatCode_redirects ) , i ) ; jcasType . ll_cas . ll_setStringArrayValue ( jcasType . ll_cas . ll_getRefValue ( addr , ( ( Descriptor_Type ) jcasType ) . casFeatCode_redirects ) , i , v ) ; } | indexed setter for redirects - sets an indexed value - List of redirects pointing to a Wikipedia page . | 203 | 23 |
20,923 | public java . util . List < Object > getRid ( ) { if ( rid == null ) { rid = new ArrayList < Object > ( ) ; } return this . rid ; } | Gets the value of the rid property . | 40 | 9 |
20,924 | public static Pipeline parse ( File scriptFile , List < String > replacementVars ) throws ParseException , IOException { checkArgument ( scriptFile . exists ( ) , "could not find pipeline script file at " + scriptFile . getAbsolutePath ( ) ) ; return parse ( FileUtils . readLines ( scriptFile ) , scriptFile . getParent ( ) , replacementVars ) ; } | Parses a pipeline script file . | 86 | 8 |
20,925 | public static Pipeline parse ( List < String > scriptLines , String parentFilePath , List < String > replacementVars ) throws ParseException , IOException { if ( replacementVars == null ) replacementVars = new ArrayList < String > ( ) ; // parse Pipeline pipeline = parseAndDispatch ( scriptLines , new Pipeline ( ) , parentFilePath , replacementVars ) ; // verify pipeline not empty if ( pipeline . crd == null ) LOG . warn ( "no CollectionReader defined in this pipeline" ) ; // throw new ParseException( // "no collection reader defined in this pipeline script", -1); if ( pipeline . aeds . isEmpty ( ) ) throw new ParseException ( "no analysis engines defined in this pipeline script, at least define one" , - 1 ) ; return pipeline ; } | Parses lines from a pipeline script . | 174 | 9 |
20,926 | private static void parsePython ( IteratorWithPrevious < String > it , Pipeline pipeline ) throws ParseException { String script = "" ; while ( it . hasNext ( ) ) { String current = it . next ( ) ; if ( StringUtils . isBlank ( current ) ) break ; script += current + "\n" ; } if ( script . length ( ) < 3 ) throw new ParseException ( "empty script" , - 1 ) ; try { AnalysisEngineDescription aed = AnalysisEngineFactory . createEngineDescription ( JythonAnnotator2 . class , JythonAnnotator2 . SCRIPT_STRING , script ) ; pipeline . addAe ( aed ) ; } catch ( ResourceInitializationException e ) { throw new ParseException ( "could not create aed with script, " + e . getMessage ( ) , - 1 ) ; } } | Parses inline raw Python code and executes it with Jython | 187 | 13 |
20,927 | private static void parseJava ( IteratorWithPrevious < String > it , Pipeline pipeline ) throws ParseException { String script = "" ; while ( it . hasNext ( ) ) { String current = it . next ( ) ; if ( isBlank ( current ) ) break ; script += current + "\n" ; } if ( script . length ( ) < 3 ) throw new ParseException ( "empty script" , - 1 ) ; try { pipeline . aeds . add ( createEngineDescription ( BeanshellAnnotator . class , SCRIPT_STRING , script ) ) ; } catch ( ResourceInitializationException e ) { throw new ParseException ( "could not create aed with script " + script , - 1 ) ; } } | Parses inline raw java code and executes it with Beanshell | 157 | 13 |
20,928 | private static void parseInclude ( String line , Pipeline pipeline , String parentFilePath , List < String > cliArgs ) throws ParseException { LOG . info ( "+-parsing include line '{}'" , line ) ; String includeName = line . replaceFirst ( "include: " , "" ) . trim ( ) ; File includeFile = null ; if ( includeName . startsWith ( "/" ) ) { includeFile = new File ( includeName ) ; } else { includeFile = new File ( parentFilePath , includeName ) ; } if ( ! includeFile . exists ( ) ) { String didYouMean = "" ; if ( new File ( parentFilePath , "../" + includeName ) . exists ( ) ) { didYouMean = "\ndid you mean: '../" + includeName + "'" ; } else if ( new File ( parentFilePath , includeName . replaceFirst ( "\\.\\./" , "" ) ) . exists ( ) ) { didYouMean = "\ndid you mean: '" + includeName . replaceFirst ( "\\.\\./" , "" ) + "'" ; } throw new ParseException ( "include file does not exist (" + includeFile . getAbsolutePath ( ) + ") " + didYouMean , - 1 ) ; } try { List < String > includeStr = FileUtils . readLines ( includeFile ) ; includeStr . add ( "" ) ; includeStr . add ( "" ) ; parseAndDispatch ( includeStr , pipeline , includeFile . getParentFile ( ) . getAbsolutePath ( ) , cliArgs ) ; } catch ( IOException e ) { throw new ParseException ( "cannot read include file (" + includeFile . getAbsolutePath ( ) + ")" , - 1 ) ; } } | parse include commands | 393 | 3 |
20,929 | private static void validateParams ( List < Object > params , Class < ? > classz ) { // skip validation if not uimafit if ( ! JCasAnnotator_ImplBase . class . isAssignableFrom ( classz ) && ! JCasCollectionReader_ImplBase . class . isAssignableFrom ( // classz ) ) { LOG . warn ( " +- Could not validate parameters in {}. You might want to check it manually." , classz . getName ( ) ) ; return ; } for ( int i = 0 ; i < params . size ( ) ; i = i + 2 ) { String paramName = ( String ) params . get ( i ) ; try { // add fields from superclass as well Set < Field > fields = newHashSet ( classz . getDeclaredFields ( ) ) ; fields . addAll ( newHashSet ( classz . getSuperclass ( ) . getDeclaredFields ( ) ) ) ; List < String > paramNames = new ArrayList < String > ( ) ; for ( Field f : fields ) { if ( f . isAnnotationPresent ( ConfigurationParameter . class ) ) { ConfigurationParameter confParam = f . getAnnotation ( ConfigurationParameter . class ) ; paramNames . add ( confParam . name ( ) ) ; } } if ( ! paramNames . contains ( paramName ) ) { LOG . warn ( " +-XXXXXXXXX Could not find parameter '{}' in {}. You should check it." , paramName , classz . getName ( ) ) ; LOG . warn ( " +-XXXXXXXXX Available parameters are:\n" , join ( paramNames , "\n" ) ) ; } } catch ( SecurityException e ) { LOG . error ( "could not validate params for " + classz . getSimpleName ( ) , e ) ; } } } | check that this ae or cr has the right parameters | 396 | 11 |
20,930 | protected static String debugText ( String heading , Authentication auth , Collection < ConfigAttribute > config , Object resource , int decision ) { StringBuilder sb = new StringBuilder ( heading ) ; sb . append ( ": " ) ; if ( auth != null ) { sb . append ( auth . getName ( ) ) ; } if ( config != null ) { Collection < ConfigAttribute > atts = config ; if ( atts != null && atts . size ( ) > 0 ) { sb . append ( " [" ) ; for ( ConfigAttribute att : atts ) { sb . append ( att . getAttribute ( ) ) ; sb . append ( "," ) ; } sb . replace ( sb . length ( ) - 1 , sb . length ( ) , "]" ) ; } } if ( resource != null ) { sb . append ( " resource: [" ) ; sb . append ( resource . toString ( ) ) ; sb . append ( "]" ) ; } sb . append ( " => decision: " + decision ) ; return sb . toString ( ) ; } | This is small debug utility available to voters in this package . | 237 | 12 |
20,931 | public S3TaskClient get ( String storeId ) throws ContentStoreException { ContentStore contentStore = contentStoreManager . getContentStore ( storeId ) ; return new S3TaskClientImpl ( contentStore ) ; } | Retrieve an S3TaskClient | 46 | 7 |
20,932 | public static void addFileToZipOutputStream ( File file , ZipOutputStream zipOs ) throws IOException { String fileName = file . getName ( ) ; try ( FileInputStream fos = new FileInputStream ( file ) ) { ZipEntry zipEntry = new ZipEntry ( fileName ) ; zipEntry . setSize ( file . length ( ) ) ; zipEntry . setTime ( System . currentTimeMillis ( ) ) ; zipOs . putNextEntry ( zipEntry ) ; byte [ ] buf = new byte [ 1024 ] ; int bytesRead ; while ( ( bytesRead = fos . read ( buf ) ) > 0 ) { zipOs . write ( buf , 0 , bytesRead ) ; } zipOs . closeEntry ( ) ; fos . close ( ) ; } } | Adds the specified file to the zip output stream . | 168 | 10 |
20,933 | private void checkStorageState ( StorageException e ) { if ( e . getCause ( ) instanceof AmazonS3Exception ) { String errorCode = ( ( AmazonS3Exception ) e . getCause ( ) ) . getErrorCode ( ) ; if ( INVALID_OBJECT_STATE . equals ( errorCode ) ) { String message = "The storage state of this content item " + "does not allow for this action to be taken. To resolve " + "this issue: 1. Request that this content item be " + "retrieved from offline storage 2. Wait (retrieval may " + "take up to 5 hours) 3. Retry this request" ; throw new StorageStateException ( message , e ) ; } } } | Recognize and handle exceptions due to content which resides in Glacier but has not been retrieved for access . | 157 | 21 |
20,934 | private URI generateAsynchronously ( String account , String spaceId , String storeId , String format ) throws Exception { StorageProviderType providerType = getStorageProviderType ( storeId ) ; InputStream manifest = manifestResource . getManifest ( account , storeId , spaceId , format ) ; String contentId = MessageFormat . format ( "generated-manifests/manifest-{0}_{1}_{2}.txt{3}" , spaceId , providerType . name ( ) . toLowerCase ( ) , DateUtil . convertToString ( System . currentTimeMillis ( ) , DateFormat . PLAIN_FORMAT ) , ".gz" ) ; String adminSpace = "x-duracloud-admin" ; URI uri = buildURI ( adminSpace , contentId ) ; StorageProvider provider = storageProviderFactory . getStorageProvider ( ) ; executor . execute ( ( ) -> { try { boolean gzip = true ; // write file to disk File file = IOUtil . writeStreamToFile ( manifest , gzip ) ; // upload to the default storage provider with retries uploadManifestToDefaultStorageProvider ( format , adminSpace , contentId , file , provider , gzip ) ; } catch ( Exception ex ) { log . error ( "failed to generate manifest for space: spaceId=" + spaceId + ", storeId=" + storeId + " : " + ex . getMessage ( ) , ex ) ; } } ) ; return uri ; } | Generates a manifest file asynchronously and uploads to DuraCloud | 316 | 15 |
20,935 | @ Override public List < StorageAccount > getStorageAccounts ( ) { List < StorageAccount > accts = new ArrayList <> ( ) ; Iterator < String > ids = getAccountManager ( ) . getStorageAccountIds ( ) ; while ( ids . hasNext ( ) ) { accts . add ( getAccountManager ( ) . getStorageAccount ( ids . next ( ) ) ) ; } return accts ; } | This method returns all of the registered storage accounts . | 98 | 10 |
20,936 | @ Override public StorageProvider getStorageProvider ( String storageAccountId ) throws StorageException { // If no store ID is provided, retrieves the primary store ID storageAccountId = checkStorageAccountId ( storageAccountId ) ; if ( storageProviders . containsKey ( storageAccountId ) ) { return storageProviders . get ( storageAccountId ) ; } StorageAccountManager storageAccountManager = getAccountManager ( ) ; StorageAccount account = storageAccountManager . getStorageAccount ( storageAccountId ) ; if ( account == null ) { throw new NotFoundException ( "No store exists with ID " + storageAccountId ) ; } String username = account . getUsername ( ) ; String password = account . getPassword ( ) ; StorageProviderType type = account . getType ( ) ; StorageProvider storageProvider = null ; if ( type . equals ( StorageProviderType . AMAZON_S3 ) ) { storageProvider = new S3StorageProvider ( username , password , account . getOptions ( ) ) ; } else if ( type . equals ( StorageProviderType . AMAZON_GLACIER ) ) { storageProvider = new GlacierStorageProvider ( username , password , account . getOptions ( ) ) ; } else if ( type . equals ( StorageProviderType . IRODS ) ) { storageProvider = new IrodsStorageProvider ( username , password , account . getOptions ( ) ) ; } else if ( type . equals ( StorageProviderType . CHRONOPOLIS ) ) { storageProvider = new ChronopolisStorageProvider ( username , password ) ; } else if ( type . equals ( StorageProviderType . TEST_RETRY ) ) { storageProvider = new MockRetryStorageProvider ( ) ; } else if ( type . equals ( StorageProviderType . TEST_VERIFY_CREATE ) ) { storageProvider = new MockVerifyCreateStorageProvider ( ) ; } else if ( type . equals ( StorageProviderType . TEST_VERIFY_DELETE ) ) { storageProvider = new MockVerifyDeleteStorageProvider ( ) ; } else { throw new StorageException ( "Unsupported storage provider type (" + type . name ( ) + ") associated with storage account (" + storageAccountId + "): unable to create" ) ; } StorageProvider auditProvider = new AuditStorageProvider ( storageProvider , storageAccountManager . getAccountName ( ) , storageAccountId , type . getName ( ) , userUtil , auditQueue ) ; if ( storageProvider instanceof StorageProviderBase ) { ( ( StorageProviderBase ) storageProvider ) . setWrappedStorageProvider ( auditProvider ) ; } StorageProvider aclProvider = new ACLStorageProvider ( auditProvider , notifier , contextUtil ) ; StorageProvider brokeredProvider = new BrokeredStorageProvider ( statelessProvider , aclProvider , type , storageAccountId ) ; storageProviders . put ( storageAccountId , brokeredProvider ) ; return brokeredProvider ; } | Retrieves a particular storage provider based on the storage account ID . If no storage ID is provided use the primary storage provider account If no storage account can be found with the given ID throw NotFoundException | 618 | 41 |
20,937 | @ Override public void expireStorageProvider ( String storageAccountId ) { storageAccountId = checkStorageAccountId ( storageAccountId ) ; log . info ( "Expiring storage provider connection! Storage account id: {}" , storageAccountId ) ; storageProviders . remove ( storageAccountId ) ; } | Removes a particular storage provider from the cache which will require that the connection be recreated on the next call . | 64 | 23 |
20,938 | public void initialize ( DuraStoreInitConfig initConfig , String instanceHost , String instancePort , String accountId ) throws StorageException { this . initConfig = initConfig ; storageAccountManager . initialize ( initConfig . getStorageAccounts ( ) ) ; storageAccountManager . setEnvironment ( instanceHost , instancePort , accountId ) ; } | Initializes DuraStore with account information necessary to connect to Storage Providers . | 71 | 16 |
20,939 | public int getAttempts ( ) { String attempts = this . properties . get ( "attempts" ) ; if ( attempts == null ) { attempts = "0" ; } return Integer . parseInt ( attempts ) ; } | The number of completed attempts to process this task . | 47 | 10 |
20,940 | public String performTask ( String taskParameters ) { GetSignedCookiesUrlTaskParameters taskParams = GetSignedCookiesUrlTaskParameters . deserialize ( taskParameters ) ; String spaceId = taskParams . getSpaceId ( ) ; String ipAddress = taskParams . getIpAddress ( ) ; int minutesToExpire = taskParams . getMinutesToExpire ( ) ; if ( minutesToExpire <= 0 ) { minutesToExpire = DEFAULT_MINUTES_TO_EXPIRE ; } String redirectUrl = taskParams . getRedirectUrl ( ) ; log . info ( "Performing " + TASK_NAME + " task with parameters: spaceId=" + spaceId + ", minutesToExpire=" + minutesToExpire + ", ipAddress=" + ipAddress + ", redirectUrl=" + redirectUrl ) ; // Will throw if bucket does not exist String bucketName = unwrappedS3Provider . getBucketName ( spaceId ) ; // Ensure that streaming service is on checkThatStreamingServiceIsEnabled ( spaceId , TASK_NAME ) ; // Retrieve the existing distribution for the given space DistributionSummary existingDist = getExistingDistribution ( bucketName ) ; if ( null == existingDist ) { throw new UnsupportedTaskException ( TASK_NAME , "The " + TASK_NAME + " task can only be used after a space " + "has been configured to enable secure streaming. Use " + StorageTaskConstants . ENABLE_STREAMING_TASK_NAME + " to enable secure streaming on this space." ) ; } String domainName = existingDist . getDomainName ( ) ; // Define expiration date/time Calendar expireCalendar = Calendar . getInstance ( ) ; expireCalendar . add ( Calendar . MINUTE , minutesToExpire ) ; Map < String , String > signedCookies = new HashMap <> ( ) ; try { File cfKeyPathFile = getCfKeyPathFile ( this . cfKeyPath ) ; // Generate signed cookies CloudFrontCookieSigner . CookiesForCustomPolicy cookies = CloudFrontCookieSigner . getCookiesForCustomPolicy ( SignerUtils . Protocol . https , domainName , cfKeyPathFile , "*" , cfKeyId , expireCalendar . getTime ( ) , null , ipAddress ) ; signedCookies . put ( cookies . getPolicy ( ) . getKey ( ) , cookies . getPolicy ( ) . getValue ( ) ) ; signedCookies . put ( cookies . getSignature ( ) . getKey ( ) , cookies . getSignature ( ) . getValue ( ) ) ; signedCookies . put ( cookies . getKeyPairId ( ) . getKey ( ) , cookies . getKeyPairId ( ) . getValue ( ) ) ; } catch ( InvalidKeySpecException | IOException e ) { throw new RuntimeException ( "Error encountered attempting to create signed cookies in task " + TASK_NAME + ": " + e . getMessage ( ) , e ) ; } String token = storeCookies ( signedCookies , domainName , redirectUrl ) ; GetSignedCookiesUrlTaskResult taskResult = new GetSignedCookiesUrlTaskResult ( ) ; taskResult . setSignedCookiesUrl ( "https://" + domainName + "/cookies?token=" + token ) ; String toReturn = taskResult . serialize ( ) ; log . info ( "Result of " + TASK_NAME + " task: " + toReturn ) ; return toReturn ; } | Create and store signed cookies | 773 | 5 |
20,941 | public void run ( ) { try { while ( ! complete ) { ContentItem contentItem = new Retrier ( 5 , 4000 , 2 ) . execute ( ( ) -> { return source . getNextContentItem ( ) ; } ) ; if ( contentItem == null ) { break ; } while ( ! retrieveContent ( contentItem ) ) { sleep ( 1000 ) ; } } } catch ( Exception ex ) { logger . error ( "Failed to run to completion" , ex ) ; } finally { shutdown ( ) ; } } | Begins the content retrieval process | 110 | 6 |
20,942 | public void shutdown ( ) { logger . info ( "Closing Retrieval Manager" ) ; workerPool . shutdown ( ) ; try { workerPool . awaitTermination ( 30 , TimeUnit . MINUTES ) ; } catch ( InterruptedException e ) { // Exit wait on interruption } complete = true ; } | Stops the retrieval no further files will be retrieved after those which are in progress have completed . | 66 | 19 |
20,943 | public String serialize ( T obj ) { try { Marshaller marshaller = context . createMarshaller ( ) ; marshaller . setProperty ( Marshaller . JAXB_FORMATTED_OUTPUT , true ) ; StringWriter writer = new StringWriter ( ) ; marshaller . marshal ( obj , writer ) ; return writer . toString ( ) ; } catch ( JAXBException e ) { throw new XmlSerializationException ( "Exception encountered " + "serializing report: " + getErrorMsg ( e ) , e ) ; } } | Serializes the data stored within a java bean to XML . The bean and any ancillary beans should include JAXB binding annotations . | 123 | 28 |
20,944 | public T deserialize ( String xml ) { if ( xml == null || xml . equals ( "" ) ) { throw new RuntimeException ( "XML cannot be null or empty" ) ; } else { return deserialize ( new StreamSource ( new StringReader ( xml ) ) ) ; } } | De - serializes XML into an object structure . | 63 | 10 |
20,945 | public T deserialize ( InputStream stream ) { if ( stream == null ) { throw new RuntimeException ( "Stream cannot be null" ) ; } else { return deserialize ( new StreamSource ( stream ) ) ; } } | De - serializes XML from an InputStream into an object structure . | 49 | 14 |
20,946 | public Map < String , String > getSpaceProperties ( String spaceId ) { Map < String , String > spaceProps = new HashMap < String , String > ( ) ; Map < String , String > allProps = getAllSpaceProperties ( spaceId ) ; // ONLY include non-ACL properties. for ( String name : allProps . keySet ( ) ) { if ( ! name . startsWith ( PROPERTIES_SPACE_ACL ) ) { spaceProps . put ( name , allProps . get ( name ) ) ; } } return spaceProps ; } | This method returns all of the space properties EXCEPT the ACLs | 129 | 13 |
20,947 | public void setNewSpaceProperties ( String spaceId , Map < String , String > spaceProperties ) { setNewSpaceProperties ( spaceId , spaceProperties , getSpaceACLs ( spaceId ) ) ; } | Sets the properties on this space . Maintains the current ACL settings . | 48 | 16 |
20,948 | public void setNewSpaceProperties ( String spaceId , Map < String , String > spaceProperties , Map < String , AclType > spaceACLs ) { // Add ACLs to the properties list spaceProperties . putAll ( packACLs ( spaceACLs ) ) ; boolean success = false ; int maxLoops = 6 ; for ( int loops = 0 ; ! success && loops < maxLoops ; loops ++ ) { try { doSetSpaceProperties ( spaceId , spaceProperties ) ; success = true ; } catch ( NotFoundException e ) { success = false ; } } if ( ! success ) { throw new StorageException ( "Properties for space " + spaceId + " could not be created. " + "The space cannot be found." ) ; } } | Sets the properties of this space . Note that this method is intentionally not exposed to users as it is not meant to be used for user properties but only for system - level properties . The names and values need to be kept short and the overall number of properties needs to be tightly limited or there will be issues due to provider - specific limitation . | 170 | 69 |
20,949 | public void deleteSpaceSync ( String spaceId ) { log . debug ( "deleteSpaceSync(" + spaceId + ")" ) ; throwIfSpaceNotExist ( spaceId ) ; Map < String , String > allProps = getAllSpaceProperties ( spaceId ) ; allProps . put ( "is-delete" , "true" ) ; doSetSpaceProperties ( spaceId , allProps ) ; SpaceDeleteWorker deleteWorker = getSpaceDeleteWorker ( spaceId ) ; deleteWorker . run ( ) ; } | This method is only intended to be used by tests! | 117 | 11 |
20,950 | @ GET public Response getSupportedTasks ( @ QueryParam ( "storeID" ) String storeID ) { String msg = "getting suppported tasks(" + storeID + ")" ; try { TaskProvider taskProvider = taskProviderFactory . getTaskProvider ( storeID ) ; List < String > supportedTasks = taskProvider . getSupportedTasks ( ) ; String responseText = SerializationUtil . serializeList ( supportedTasks ) ; return responseOkXml ( msg , responseText ) ; } catch ( Exception e ) { return responseBad ( msg , e , INTERNAL_SERVER_ERROR ) ; } } | Gets a listing of supported tasks for a given provider | 133 | 11 |
20,951 | @ Path ( "/{taskName}" ) @ POST public Response performTask ( @ PathParam ( "taskName" ) String taskName , @ QueryParam ( "storeID" ) String storeID ) { String msg = "performing task(" + taskName + ", " + storeID + ")" ; String taskParameters = null ; try { taskParameters = getTaskParameters ( ) ; } catch ( Exception e ) { return responseBad ( msg , e , INTERNAL_SERVER_ERROR ) ; } try { TaskProvider taskProvider = taskProviderFactory . getTaskProvider ( storeID ) ; String responseText = taskProvider . performTask ( taskName , taskParameters ) ; return responseOk ( msg , responseText ) ; } catch ( UnsupportedTaskException e ) { return responseBad ( msg , e , BAD_REQUEST ) ; } catch ( UnauthorizedException e ) { return responseBad ( msg , e , FORBIDDEN ) ; } catch ( StorageStateException e ) { return responseBad ( msg , e , CONFLICT ) ; } catch ( ServerConflictException e ) { return responseBad ( msg , e , Response . Status . CONFLICT ) ; } catch ( Exception e ) { return responseBad ( msg , e , INTERNAL_SERVER_ERROR ) ; } } | Performs a task | 275 | 4 |
20,952 | @ Override public RetrievedContent getContent ( String spaceID , String contentID , String storeID , String range ) throws InvalidRequestException , ResourceException { try { StorageProvider storage = storageProviderFactory . getStorageProvider ( storeID ) ; return storage . getContent ( spaceID , contentID , range ) ; } catch ( NotFoundException e ) { throw new ResourceNotFoundException ( "get content" , spaceID , contentID , e ) ; } catch ( StorageStateException e ) { throw new ResourceStateException ( "get content" , spaceID , contentID , e ) ; } catch ( IllegalArgumentException e ) { throw new InvalidRequestException ( e . getMessage ( ) ) ; } catch ( Exception e ) { storageProviderFactory . expireStorageProvider ( storeID ) ; throw new ResourceException ( "get content" , spaceID , contentID , e ) ; } } | Retrieves content from a space . | 188 | 8 |
20,953 | @ Override public Map < String , String > getContentProperties ( String spaceID , String contentID , String storeID ) throws ResourceException { try { StorageProvider storage = storageProviderFactory . getStorageProvider ( storeID ) ; return storage . getContentProperties ( spaceID , contentID ) ; } catch ( NotFoundException e ) { throw new ResourceNotFoundException ( "get properties for content" , spaceID , contentID , e ) ; } catch ( Exception e ) { storageProviderFactory . expireStorageProvider ( storeID ) ; throw new ResourceException ( "get properties for content" , spaceID , contentID , e ) ; } } | Retrieves the properties of a piece of content . | 138 | 11 |
20,954 | @ Override public void updateContentProperties ( String spaceID , String contentID , String contentMimeType , Map < String , String > userProperties , String storeID ) throws ResourceException { validateProperties ( userProperties , "update properties for content" , spaceID , contentID ) ; try { StorageProvider storage = storageProviderFactory . getStorageProvider ( storeID ) ; // Update content properties if ( userProperties != null ) { storage . setContentProperties ( spaceID , contentID , userProperties ) ; } } catch ( NotFoundException e ) { throw new ResourceNotFoundException ( "update properties for content" , spaceID , contentID , e ) ; } catch ( StorageStateException e ) { throw new ResourceStateException ( "update properties for content" , spaceID , contentID , e ) ; } catch ( Exception e ) { storageProviderFactory . expireStorageProvider ( storeID ) ; throw new ResourceException ( "update properties for content" , spaceID , contentID , e ) ; } } | Updates the properties of a piece of content . | 219 | 10 |
20,955 | @ Override public String addContent ( String spaceID , String contentID , InputStream content , String contentMimeType , Map < String , String > userProperties , long contentSize , String checksum , String storeID ) throws ResourceException , InvalidIdException , ResourcePropertiesInvalidException { IdUtil . validateContentId ( contentID ) ; validateProperties ( userProperties , "add content" , spaceID , contentID ) ; try { StorageProvider storage = storageProviderFactory . getStorageProvider ( storeID ) ; try { // overlay new properties on top of older extended properties // so that old tags and custom properties are preserved. // c.f. https://jira.duraspace.org/browse/DURACLOUD-757 Map < String , String > oldUserProperties = storage . getContentProperties ( spaceID , contentID ) ; //remove all non extended properties if ( userProperties != null ) { oldUserProperties . putAll ( userProperties ) ; //use old mimetype if none specified. String oldMimetype = oldUserProperties . remove ( StorageProvider . PROPERTIES_CONTENT_MIMETYPE ) ; if ( contentMimeType == null || contentMimeType . trim ( ) == "" ) { contentMimeType = oldMimetype ; } oldUserProperties = StorageProviderUtil . removeCalculatedProperties ( oldUserProperties ) ; } userProperties = oldUserProperties ; } catch ( NotFoundException ex ) { // do nothing - no properties to update // since file did not previous exist. } return storage . addContent ( spaceID , contentID , contentMimeType , userProperties , contentSize , checksum , content ) ; } catch ( NotFoundException e ) { throw new ResourceNotFoundException ( "add content" , spaceID , contentID , e ) ; } catch ( ChecksumMismatchException e ) { throw new ResourceChecksumException ( "add content" , spaceID , contentID , e ) ; } catch ( Exception e ) { storageProviderFactory . expireStorageProvider ( storeID ) ; throw new ResourceException ( "add content" , spaceID , contentID , e ) ; } } | Adds content to a space . | 483 | 6 |
20,956 | public void initializeNotifiers ( Collection < NotificationConfig > notificationConfigs ) { for ( NotificationConfig config : notificationConfigs ) { for ( Notifier notifier : notifiers ) { if ( notifier . getNotificationType ( ) . name ( ) . equalsIgnoreCase ( config . getType ( ) ) ) { notifier . initialize ( config ) ; } } } } | Initializes notifiers using the provided configuration . It is expected that there will be exactly one config for each notifier type . - If there is more than one config for a given type the last configuration of that type in the list will win . - If there is a type not represented in the config list then all notifiers of that type will remain uninitialized . | 80 | 73 |
20,957 | public void sendNotification ( NotificationType type , String subject , String message , String ... destinations ) { for ( Notifier notifier : notifiers ) { if ( notifier . getNotificationType ( ) . equals ( type ) ) { notifier . notify ( subject , message , destinations ) ; } } } | Sends a notification through all configured notifiers of a given type . | 65 | 14 |
20,958 | public void sendAdminNotification ( NotificationType type , String subject , String message ) { for ( Notifier notifier : notifiers ) { if ( notifier . getNotificationType ( ) . equals ( type ) ) { notifier . notifyAdmins ( subject , message ) ; } } } | Sends a notification to system administrators through all configured notifiers of a given type . | 62 | 17 |
20,959 | public String storeData ( String cookieData ) { try { String token = generateToken ( ) ; ensureSpaceExists ( ) ; s3StorageProvider . addHiddenContent ( this . hiddenSpaceName , token , Constants . MEDIA_TYPE_APPLICATION_JSON , IOUtil . writeStringToStream ( cookieData ) ) ; return token ; } catch ( Exception e ) { throw new DuraCloudRuntimeException ( e ) ; } } | Stores string data and returns a token by which that data can be retrieved | 95 | 15 |
20,960 | public String retrieveData ( String token ) { try { RetrievedContent data = this . s3StorageProvider . getContent ( this . hiddenSpaceName , token ) ; return IOUtil . readStringFromStream ( data . getContentStream ( ) ) ; } catch ( NotFoundException ex ) { return null ; } catch ( Exception ex ) { throw new DuraCloudRuntimeException ( ex ) ; } } | Retrieves string data given its token . | 85 | 9 |
20,961 | protected Map < String , String > retrieveToFile ( File localFile , RetrievalListener listener ) throws IOException { try { contentStream = new Retrier ( 5 , 4000 , 3 ) . execute ( ( ) -> { return source . getSourceContent ( contentItem , listener ) ; } ) ; } catch ( Exception ex ) { throw new IOException ( ex ) ; } try ( InputStream inStream = contentStream . getStream ( ) ; OutputStream outStream = new FileOutputStream ( localFile ) ; ) { IOUtils . copyLarge ( inStream , outStream ) ; } catch ( IOException e ) { try { deleteFile ( localFile ) ; } catch ( IOException ioe ) { logger . error ( "Exception deleting local file " + localFile . getAbsolutePath ( ) + " due to: " + ioe . getMessage ( ) ) ; } throw e ; } if ( ! checksumsMatch ( localFile , contentStream . getChecksum ( ) ) ) { deleteFile ( localFile ) ; throw new IOException ( "Calculated checksum value for retrieved " + "file does not match properties checksum." ) ; } // Set time stamps if ( applyTimestamps ) { applyTimestamps ( contentStream , localFile ) ; } return contentStream . getProperties ( ) ; } | Transfers the remote file stream to the local file | 284 | 11 |
20,962 | public void generateSchema ( Class ... classes ) throws JAXBException , IOException { if ( ! baseDir . exists ( ) ) { baseDir . mkdirs ( ) ; } JAXBContext context = JAXBContext . newInstance ( classes ) ; context . generateSchema ( this ) ; } | Generates an XML Schema which includes the given classes | 69 | 11 |
20,963 | @ Override public Result createOutput ( String namespaceUri , String defaultFileName ) throws IOException { if ( null == fileName ) { fileName = defaultFileName ; } return new StreamResult ( new File ( baseDir , fileName ) ) ; } | Called by the schema generation process . There is no need to call this method directly . | 55 | 18 |
20,964 | public synchronized boolean handleChangedFile ( ChangedFile changedFile ) { File watchDir = getWatchDir ( changedFile . getFile ( ) ) ; SyncWorker worker = new SyncWorker ( changedFile , watchDir , endpoint ) ; try { addToWorkerList ( worker ) ; workerPool . execute ( worker ) ; return true ; } catch ( RejectedExecutionException e ) { workerList . remove ( worker ) ; return false ; } } | Notifies the SyncManager that a file has changed | 95 | 10 |
20,965 | protected int calculateBufferSize ( long maxChunkSize ) { final int KB = 1000 ; // Ensure maxChunkSize falls on 1-KB boundaries. if ( maxChunkSize % KB != 0 ) { String m = "MaxChunkSize must be multiple of " + KB + ": " + maxChunkSize ; log . error ( m ) ; throw new DuraCloudRuntimeException ( m ) ; } // Find maximum block factor less than or equal to 8-KB. long size = maxChunkSize ; for ( int i = 1 ; i <= maxChunkSize ; i ++ ) { // MaxChunkSize must be divisible by buffer size if ( ( maxChunkSize % i == 0 ) && ( ( maxChunkSize / i ) <= ( 8 * KB ) ) ) { size = maxChunkSize / i ; break ; } } log . debug ( "Buf size: " + size + " for maxChunkSize: " + maxChunkSize ) ; return ( int ) size ; } | This method finds the maximum 1 - KB divisor of arg maxChunkSize that is less than 8 - KB . It also ensures that arg maxChunkSize is a multiple of 1 - KB otherwise the stream buffering would lose bytes if the maxChunkSize was not divisible by the buffer size . Additionally by making the buffer multiples of 1 - KB ensures efficient block - writing . | 219 | 81 |
20,966 | protected DistributionSummary getExistingDistribution ( String bucketName ) { List < DistributionSummary > dists = getAllExistingWebDistributions ( bucketName ) ; if ( dists . isEmpty ( ) ) { return null ; } else { return dists . get ( 0 ) ; } } | Returns the first streaming web distribution associated with a given bucket | 63 | 11 |
20,967 | protected List < DistributionSummary > getAllExistingWebDistributions ( String bucketName ) { List < DistributionSummary > distListForBucket = new ArrayList <> ( ) ; DistributionList distList = cfClient . listDistributions ( new ListDistributionsRequest ( ) ) . getDistributionList ( ) ; List < DistributionSummary > webDistList = distList . getItems ( ) ; while ( distList . isTruncated ( ) ) { distList = cfClient . listDistributions ( new ListDistributionsRequest ( ) . withMarker ( distList . getNextMarker ( ) ) ) . getDistributionList ( ) ; webDistList . addAll ( distList . getItems ( ) ) ; } for ( DistributionSummary distSummary : webDistList ) { if ( isDistFromBucket ( bucketName , distSummary ) ) { distListForBucket . add ( distSummary ) ; } } return distListForBucket ; } | Determines if a streaming distribution already exists for a given bucket | 209 | 13 |
20,968 | protected void checkThatStreamingServiceIsEnabled ( String spaceId , String taskName ) { // Verify that streaming is enabled Map < String , String > spaceProperties = s3Provider . getSpaceProperties ( spaceId ) ; if ( ! spaceProperties . containsKey ( HLS_STREAMING_HOST_PROP ) ) { throw new UnsupportedTaskException ( taskName , "The " + taskName + " task can only be used after a space " + "has been configured to enable HLS streaming. Use " + StorageTaskConstants . ENABLE_HLS_TASK_NAME + " to enable HLS streaming on this space." ) ; } } | Determines if a streaming distribution exists for a given space | 146 | 12 |
20,969 | @ Override public Iterator < String > getSpaces ( ) { ConnectOperation co = new ConnectOperation ( host , port , username , password , zone ) ; log . trace ( "Listing spaces" ) ; try { return listDirectories ( baseDirectory , co . getConnection ( ) ) ; } catch ( IOException e ) { log . error ( "Could not connect to iRODS" , e ) ; throw new StorageException ( e ) ; } } | Return a list of irods spaces . IRODS spaces are directories under the baseDirectory of this provider . | 99 | 23 |
20,970 | @ Override public void createSpace ( String spaceId ) { ConnectOperation co = new ConnectOperation ( host , port , username , password , zone ) ; try { IrodsOperations io = new IrodsOperations ( co ) ; io . mkdir ( baseDirectory + "/" + spaceId ) ; log . trace ( "Created space/directory: " + baseDirectory + "/" + spaceId ) ; } catch ( IOException e ) { log . error ( "Could not connect to iRODS" , e ) ; throw new StorageException ( e ) ; } } | Create a new directory under the baseDirectory | 122 | 8 |
20,971 | public static ChunksManifest createManifestFrom ( ChunksManifestDocument doc ) { ChunksManifestType manifestType = doc . getChunksManifest ( ) ; HeaderType headerType = manifestType . getHeader ( ) ; ChunksManifest . ManifestHeader header = createHeaderFromElement ( headerType ) ; ChunksType chunksType = manifestType . getChunks ( ) ; List < ChunksManifestBean . ManifestEntry > entries = createEntriesFromElement ( chunksType ) ; ChunksManifestBean manifestBean = new ChunksManifestBean ( ) ; manifestBean . setHeader ( header ) ; manifestBean . setEntries ( entries ) ; return new ChunksManifest ( manifestBean ) ; } | This method binds a ChunksManifest xml document to a ChunksManifest object | 161 | 17 |
20,972 | public long loadBackup ( ) { long backupTime = - 1 ; File [ ] backupDirFiles = getSortedBackupDirFiles ( ) ; if ( backupDirFiles . length > 0 ) { File latestBackup = backupDirFiles [ 0 ] ; try { backupTime = Long . parseLong ( latestBackup . getName ( ) ) ; changedList . restore ( latestBackup , this . contentDirs ) ; } catch ( NumberFormatException e ) { logger . error ( "Unable to load changed list backup. File in " + "changed list backup dir has invalid name: " + latestBackup . getName ( ) ) ; backupTime = - 1 ; } } return backupTime ; } | Attempts to reload the changed list from a backup file . If there are no backup files or the backup file cannot be read returns - 1 otherwise the backup file is loaded and the time the backup file was written is returned . | 151 | 44 |
20,973 | public void run ( ) { while ( continueBackup ) { if ( changedListVersion < changedList . getVersion ( ) ) { cleanupBackupDir ( SAVED_BACKUPS ) ; String filename = String . valueOf ( System . currentTimeMillis ( ) ) ; File persistFile = new File ( backupDir , filename ) ; backingUp = true ; changedListVersion = changedList . persist ( persistFile ) ; backingUp = false ; } sleepAndCheck ( backupFrequency ) ; } } | Runs the backup manager . Writes out files which are a backups of the changed list based on the set backup frequency . Retains SAVED_BACKUPS number of backup files removes the rest . | 108 | 42 |
20,974 | public synchronized ChangedFile reserve ( ) { if ( fileList . isEmpty ( ) || shutdown ) { return null ; } String key = fileList . keySet ( ) . iterator ( ) . next ( ) ; ChangedFile changedFile = fileList . remove ( key ) ; reservedFiles . put ( key , changedFile ) ; incrementVersion ( ) ; fireChangedEventAsync ( ) ; return changedFile ; } | Retrieves a changed file for processing and removes it from the list of unreserved files . Returns null if there are no changed files in the list . | 85 | 31 |
20,975 | public long persist ( File persistFile ) { try { FileOutputStream fileStream = new FileOutputStream ( persistFile ) ; ObjectOutputStream oStream = new ObjectOutputStream ( ( fileStream ) ) ; long persistVersion ; Map < String , ChangedFile > fileListCopy ; synchronized ( this ) { fileListCopy = ( Map < String , ChangedFile > ) fileList . clone ( ) ; fileListCopy . putAll ( reservedFiles ) ; persistVersion = listVersion ; } oStream . writeObject ( fileListCopy ) ; oStream . close ( ) ; return persistVersion ; } catch ( IOException e ) { throw new RuntimeException ( "Unable to persist File Changed List:" + e . getMessage ( ) , e ) ; } } | Writes out the current state of the ChangeList to the given file . | 158 | 15 |
20,976 | public synchronized void restore ( File persistFile , List < File > contentDirs ) { try { FileInputStream fileStream = new FileInputStream ( persistFile ) ; ObjectInputStream oStream = new ObjectInputStream ( fileStream ) ; log . info ( "Restoring changed list from backup: {}" , persistFile . getAbsolutePath ( ) ) ; synchronized ( this ) { LinkedHashMap < String , ChangedFile > fileListFromDisk = ( LinkedHashMap < String , ChangedFile > ) oStream . readObject ( ) ; //remove files in change list that are not in the content dir list. if ( contentDirs != null && ! contentDirs . isEmpty ( ) ) { Iterator < Entry < String , ChangedFile > > entries = fileListFromDisk . entrySet ( ) . iterator ( ) ; while ( entries . hasNext ( ) ) { Entry < String , ChangedFile > entry = entries . next ( ) ; ChangedFile file = entry . getValue ( ) ; boolean watched = false ; for ( File contentDir : contentDirs ) { if ( file . getFile ( ) . getAbsolutePath ( ) . startsWith ( contentDir . getAbsolutePath ( ) ) && ! this . fileExclusionManager . isExcluded ( file . getFile ( ) ) ) { watched = true ; break ; } } if ( ! watched ) { entries . remove ( ) ; } } } this . fileList = fileListFromDisk ; } oStream . close ( ) ; } catch ( Exception e ) { throw new RuntimeException ( "Unable to restore File Changed List:" + e . getMessage ( ) , e ) ; } } | Restores the state of the ChangedList using the given backup file | 355 | 13 |
20,977 | private Response addSpacePropertiesToResponse ( ResponseBuilder response , String spaceID , String storeID ) throws ResourceException { Map < String , String > properties = spaceResource . getSpaceProperties ( spaceID , storeID ) ; return addPropertiesToResponse ( response , properties ) ; } | Adds the properties of a space as header values to the response | 61 | 12 |
20,978 | private Response addSpaceACLsToResponse ( ResponseBuilder response , String spaceID , String storeID ) throws ResourceException { Map < String , String > aclProps = new HashMap < String , String > ( ) ; Map < String , AclType > acls = spaceResource . getSpaceACLs ( spaceID , storeID ) ; for ( String key : acls . keySet ( ) ) { aclProps . put ( key , acls . get ( key ) . name ( ) ) ; } return addPropertiesToResponse ( response , aclProps ) ; } | Adds the ACLs of a space as header values to the response . | 131 | 14 |
20,979 | @ Path ( "/acl/{spaceID}" ) @ POST public Response updateSpaceACLs ( @ PathParam ( "spaceID" ) String spaceID , @ QueryParam ( "storeID" ) String storeID ) { String msg = "update space ACLs(" + spaceID + ", " + storeID + ")" ; try { log . debug ( msg ) ; return doUpdateSpaceACLs ( spaceID , storeID ) ; } catch ( ResourceNotFoundException e ) { return responseNotFound ( msg , e , NOT_FOUND ) ; } catch ( ResourceException e ) { return responseBad ( msg , e , INTERNAL_SERVER_ERROR ) ; } catch ( Exception e ) { return responseBad ( msg , e , INTERNAL_SERVER_ERROR ) ; } } | This method sets the ACLs associated with a space . Only values included in the ACLs headers will be updated others will be removed . | 172 | 27 |
20,980 | @ Override public ChunksManifest write ( String spaceId , ChunkableContent chunkable , Map < String , String > contentProperties ) throws NotFoundException { return write ( spaceId , chunkable , contentProperties , true ) ; } | This method implements the ContentWriter interface for writing content to a DataStore . In this case the DataStore is durastore . | 53 | 26 |
20,981 | @ Override public String writeSingle ( String spaceId , String chunkChecksum , ChunkInputStream chunk , Map < String , String > properties ) throws NotFoundException { log . debug ( "writeSingle: " + spaceId + ", " + chunk . getChunkId ( ) ) ; createSpaceIfNotExist ( spaceId ) ; addChunk ( spaceId , chunkChecksum , chunk , properties , true ) ; log . debug ( "written: " + spaceId + ", " + chunk . getChunkId ( ) ) ; return chunk . getMD5 ( ) ; } | This method writes a single chunk to the DataStore . | 128 | 11 |
20,982 | public String getSpaces ( String storeID ) throws ResourceException { Element spacesElem = new Element ( "spaces" ) ; try { StorageProvider storage = storageProviderFactory . getStorageProvider ( storeID ) ; Iterator < String > spaces = storage . getSpaces ( ) ; while ( spaces . hasNext ( ) ) { String spaceID = spaces . next ( ) ; Element spaceElem = new Element ( "space" ) ; spaceElem . setAttribute ( "id" , spaceID ) ; spacesElem . addContent ( spaceElem ) ; } } catch ( Exception e ) { storageProviderFactory . expireStorageProvider ( storeID ) ; throw new ResourceException ( "Error attempting to build spaces XML" , e ) ; } Document doc = new Document ( spacesElem ) ; XMLOutputter xmlConverter = new XMLOutputter ( ) ; return xmlConverter . outputString ( doc ) ; } | Provides a listing of all spaces for a customer . Open spaces are always included in the list closed spaces are included based on user authorization . | 198 | 28 |
20,983 | public String getSpaceContents ( String spaceID , String storeID , String prefix , long maxResults , String marker ) throws ResourceException { Element spaceElem = new Element ( "space" ) ; spaceElem . setAttribute ( "id" , spaceID ) ; try { StorageProvider storage = storageProviderFactory . getStorageProvider ( storeID ) ; List < String > contents = storage . getSpaceContentsChunked ( spaceID , prefix , maxResults , marker ) ; if ( contents != null ) { for ( String contentItem : contents ) { Element contentElem = new Element ( "item" ) ; contentElem . setText ( contentItem ) ; spaceElem . addContent ( contentElem ) ; } } } catch ( NotFoundException e ) { throw new ResourceNotFoundException ( "build space XML for" , spaceID , e ) ; } catch ( Exception e ) { storageProviderFactory . expireStorageProvider ( storeID ) ; throw new ResourceException ( "build space XML for" , spaceID , e ) ; } Document doc = new Document ( spaceElem ) ; XMLOutputter xmlConverter = new XMLOutputter ( ) ; return xmlConverter . outputString ( doc ) ; } | Gets a listing of the contents of a space . | 260 | 11 |
20,984 | public void addSpace ( String spaceID , Map < String , AclType > userACLs , String storeID ) throws ResourceException , InvalidIdException { IdUtil . validateSpaceId ( spaceID ) ; try { StorageProvider storage = storageProviderFactory . getStorageProvider ( storeID ) ; storage . createSpace ( spaceID ) ; waitForSpaceCreation ( storage , spaceID ) ; updateSpaceACLs ( spaceID , userACLs , storeID ) ; } catch ( NotFoundException e ) { throw new InvalidIdException ( e . getMessage ( ) ) ; } catch ( Exception e ) { storageProviderFactory . expireStorageProvider ( storeID ) ; throw new ResourceException ( "add space" , spaceID , e ) ; } } | Adds a space . | 163 | 4 |
20,985 | public void updateSpaceACLs ( String spaceID , Map < String , AclType > spaceACLs , String storeID ) throws ResourceException { try { StorageProvider storage = storageProviderFactory . getStorageProvider ( storeID ) ; if ( null != spaceACLs ) { storage . setSpaceACLs ( spaceID , spaceACLs ) ; } } catch ( NotFoundException e ) { throw new ResourceNotFoundException ( "update space ACLs for" , spaceID , e ) ; } catch ( Exception e ) { storageProviderFactory . expireStorageProvider ( storeID ) ; throw new ResourceException ( "update space ACLs for" , spaceID , e ) ; } } | Updates the ACLs of a space . | 149 | 9 |
20,986 | public void deleteSpace ( String spaceID , String storeID ) throws ResourceException { try { StorageProvider storage = storageProviderFactory . getStorageProvider ( storeID ) ; storage . deleteSpace ( spaceID ) ; } catch ( NotFoundException e ) { throw new ResourceNotFoundException ( "delete space" , spaceID , e ) ; } catch ( Exception e ) { storageProviderFactory . expireStorageProvider ( storeID ) ; throw new ResourceException ( "delete space" , spaceID , e ) ; } } | Deletes a space removing all included content . | 108 | 9 |
20,987 | public UserDetails loadUserByUsername ( String username ) throws UsernameNotFoundException { UserDetails userDetails = usersTable . get ( username ) ; if ( null == userDetails ) { throw new UsernameNotFoundException ( username ) ; } return userDetails ; } | This method retrieves UserDetails for all users from a flat file in DuraCloud . | 55 | 18 |
20,988 | public List < SecurityUserBean > getUsers ( ) { List < SecurityUserBean > users = new ArrayList < SecurityUserBean > ( ) ; for ( DuracloudUserDetails user : this . usersTable . values ( ) ) { SecurityUserBean bean = createUserBean ( user ) ; users . add ( bean ) ; } return users ; } | This method returns all of the non - system - defined users . | 79 | 13 |
20,989 | public static ByteArrayInputStream storeProperties ( Map < String , String > propertiesMap ) throws StorageException { // Pull out known computed values propertiesMap . remove ( StorageProvider . PROPERTIES_SPACE_COUNT ) ; // Serialize Map byte [ ] properties = null ; try { String serializedProperties = serializeMap ( propertiesMap ) ; properties = serializedProperties . getBytes ( "UTF-8" ) ; } catch ( Exception e ) { String err = "Could not store properties" + " due to error: " + e . getMessage ( ) ; throw new StorageException ( err ) ; } ByteArrayInputStream is = new ByteArrayInputStream ( properties ) ; return is ; } | Converts properties stored in a Map into a stream for storage purposes . | 152 | 14 |
20,990 | public static String compareChecksum ( StorageProvider provider , String spaceId , String contentId , String checksum ) throws StorageException { String providerChecksum = provider . getContentProperties ( spaceId , contentId ) . get ( StorageProvider . PROPERTIES_CONTENT_CHECKSUM ) ; return compareChecksum ( providerChecksum , spaceId , contentId , checksum ) ; } | Determines if the checksum for a particular piece of content stored in a StorageProvider matches the expected checksum value . | 88 | 25 |
20,991 | public static String compareChecksum ( String providerChecksum , String spaceId , String contentId , String checksum ) throws ChecksumMismatchException { if ( ! providerChecksum . equals ( checksum ) ) { String err = "Content " + contentId + " was added to space " + spaceId + " but the checksum, either provided or computed " + "enroute, (" + checksum + ") does not match the checksum " + "computed by the storage provider (" + providerChecksum + "). This content should be retransmitted." ; log . warn ( err ) ; throw new ChecksumMismatchException ( err , NO_RETRY ) ; } return providerChecksum ; } | Determines if two checksum values are equal | 157 | 10 |
20,992 | public static boolean contains ( Iterator < String > iterator , String value ) { if ( iterator == null || value == null ) { return false ; } while ( iterator . hasNext ( ) ) { if ( value . equals ( iterator . next ( ) ) ) { return true ; } } return false ; } | Determines if a String value is included in a Iterated list . The iteration is only run as far as necessary to determine if the value is included in the underlying list . | 64 | 36 |
20,993 | public static long count ( Iterator < String > iterator ) { if ( iterator == null ) { return 0 ; } long count = 0 ; while ( iterator . hasNext ( ) ) { ++ count ; iterator . next ( ) ; } return count ; } | Determines the number of elements in an iteration . | 53 | 11 |
20,994 | public static List < String > getList ( Iterator < String > iterator ) { List < String > contents = new ArrayList < String > ( ) ; while ( iterator . hasNext ( ) ) { contents . add ( iterator . next ( ) ) ; } return contents ; } | Creates a list of all of the items in an iteration . Be wary of using this for Iterations of very long lists . | 58 | 26 |
20,995 | public static Map < String , String > createContentProperties ( String absolutePath , String creator ) { Map < String , String > props = new HashMap < String , String > ( ) ; if ( creator != null && creator . trim ( ) . length ( ) > 0 ) { props . put ( StorageProvider . PROPERTIES_CONTENT_CREATOR , creator ) ; } props . put ( StorageProvider . PROPERTIES_CONTENT_FILE_PATH , absolutePath ) ; try { Path path = FileSystems . getDefault ( ) . getPath ( absolutePath ) ; BasicFileAttributes bfa = Files . readAttributes ( path , BasicFileAttributes . class ) ; String creationDate = DateUtil . convertToStringLong ( bfa . creationTime ( ) . toMillis ( ) ) ; props . put ( StorageProvider . PROPERTIES_CONTENT_FILE_CREATED , creationDate ) ; String lastAccessed = DateUtil . convertToStringLong ( bfa . lastAccessTime ( ) . toMillis ( ) ) ; props . put ( StorageProvider . PROPERTIES_CONTENT_FILE_LAST_ACCESSED , lastAccessed ) ; String modified = DateUtil . convertToStringLong ( bfa . lastModifiedTime ( ) . toMillis ( ) ) ; props . put ( StorageProvider . PROPERTIES_CONTENT_FILE_MODIFIED , modified ) ; } catch ( IOException ex ) { log . error ( "Failed to read basic file attributes from " + absolutePath + ": " + ex . getMessage ( ) , ex ) ; } return props ; } | Generates a map of all client - side default content properties to be added with new content . | 353 | 19 |
20,996 | public static Map < String , String > removeCalculatedProperties ( Map < String , String > contentProperties ) { if ( contentProperties != null ) { contentProperties = new HashMap <> ( contentProperties ) ; // Remove calculated properties contentProperties . remove ( StorageProvider . PROPERTIES_CONTENT_MD5 ) ; contentProperties . remove ( StorageProvider . PROPERTIES_CONTENT_CHECKSUM ) ; contentProperties . remove ( StorageProvider . PROPERTIES_CONTENT_MODIFIED ) ; contentProperties . remove ( StorageProvider . PROPERTIES_CONTENT_SIZE ) ; } return contentProperties ; } | Returns a new map with the calculated properties removed . If null null is returned . | 144 | 16 |
20,997 | public void setSpaceLifecycle ( String bucketName , BucketLifecycleConfiguration config ) { boolean success = false ; int maxLoops = 6 ; for ( int loops = 0 ; ! success && loops < maxLoops ; loops ++ ) { try { s3Client . deleteBucketLifecycleConfiguration ( bucketName ) ; s3Client . setBucketLifecycleConfiguration ( bucketName , config ) ; success = true ; } catch ( NotFoundException e ) { success = false ; wait ( loops ) ; } } if ( ! success ) { throw new StorageException ( "Lifecycle policy for bucket " + bucketName + " could not be applied. The space cannot be found." ) ; } } | Sets a lifecycle policy on an S3 bucket based on the given configuration | 151 | 16 |
20,998 | public String addHiddenContent ( String spaceId , String contentId , String contentMimeType , InputStream content ) { log . debug ( "addHiddenContent(" + spaceId + ", " + contentId + ", " + contentMimeType + ")" ) ; // Will throw if bucket does not exist String bucketName = getBucketName ( spaceId ) ; // Wrap the content in order to be able to retrieve a checksum if ( contentMimeType == null || contentMimeType . equals ( "" ) ) { contentMimeType = DEFAULT_MIMETYPE ; } ObjectMetadata objMetadata = new ObjectMetadata ( ) ; objMetadata . setContentType ( contentMimeType ) ; PutObjectRequest putRequest = new PutObjectRequest ( bucketName , contentId , content , objMetadata ) ; putRequest . setStorageClass ( DEFAULT_STORAGE_CLASS ) ; putRequest . setCannedAcl ( CannedAccessControlList . Private ) ; try { PutObjectResult putResult = s3Client . putObject ( putRequest ) ; return putResult . getETag ( ) ; } catch ( AmazonClientException e ) { String err = "Could not add content " + contentId + " with type " + contentMimeType + " to S3 bucket " + bucketName + " due to error: " + e . getMessage ( ) ; throw new StorageException ( err , e , NO_RETRY ) ; } } | Adds content to a hidden space . | 315 | 7 |
20,999 | public String getBucketName ( String spaceId ) { // Determine if there is an existing bucket that matches this space ID. // The bucket name may use any access key ID as the prefix, so there is // no way to know the exact bucket name up front. List < Bucket > buckets = listAllBuckets ( ) ; for ( Bucket bucket : buckets ) { String bucketName = bucket . getName ( ) ; spaceId = spaceId . replace ( "." , "[.]" ) ; if ( bucketName . matches ( "(" + HIDDEN_SPACE_PREFIX + ")?[\\w]{20}[.]" + spaceId ) ) { return bucketName ; } } throw new NotFoundException ( "No S3 bucket found matching spaceID: " + spaceId ) ; } | Gets the name of an existing bucket based on a space ID . If no bucket with this spaceId exists throws a NotFoundException | 173 | 27 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.