idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
23,000 | public static void rotateImage ( File input , File output , String format , int degrees ) throws IOException { BufferedImage inputImage = ImageIO . read ( input ) ; Graphics2D g = ( Graphics2D ) inputImage . getGraphics ( ) ; g . drawImage ( inputImage , 0 , 0 , null ) ; AffineTransform at = new AffineTransform ( ) ; // scale image //at.scale(2.0, 2.0); // rotate 45 degrees around image center at . rotate ( degrees * Math . PI / 180.0 , inputImage . getWidth ( ) / 2.0 , inputImage . getHeight ( ) / 2.0 ) ; //at.rotate(Math.toRadians(degrees), inputImage.getWidth() / 2.0, inputImage.getHeight() / 2.0); /* * translate to make sure the rotation doesn't cut off any image data */ AffineTransform translationTransform ; translationTransform = findTranslation ( at , inputImage ) ; at . preConcatenate ( translationTransform ) ; // instantiate and apply transformation filter BufferedImageOp bio = new AffineTransformOp ( at , AffineTransformOp . TYPE_BILINEAR ) ; BufferedImage destinationBI = bio . filter ( inputImage , null ) ; ImageIO . write ( destinationBI , format , output ) ; } | Rotate a file a given number of degrees | 289 | 9 |
23,001 | public void close ( ) { try { if ( is != null ) is . close ( ) ; } catch ( IOException e ) { log . error ( null , e ) ; throw new RuntimeException ( e ) ; } isClosed = true ; } | Closes the Workbook manually . | 53 | 7 |
23,002 | public Iterable < String > toCSV ( ) { checkState ( ! isClosed , WORKBOOK_CLOSED ) ; Joiner joiner = Joiner . on ( "," ) . useForNull ( "" ) ; Iterable < String > CSVIterable = Iterables . transform ( sheet , item -> joiner . join ( rowToList ( item , true ) ) ) ; return hasHeader ? Iterables . skip ( CSVIterable , 1 ) : CSVIterable ; } | Converts the spreadsheet to CSV by a String Iterable . | 106 | 12 |
23,003 | public Iterable < List < String > > toLists ( ) { checkState ( ! isClosed , WORKBOOK_CLOSED ) ; Iterable < List < String > > listsIterable = Iterables . transform ( sheet , item -> { return rowToList ( item ) ; } ) ; return hasHeader ? Iterables . skip ( listsIterable , 1 ) : listsIterable ; } | Converts the spreadsheet to String Lists by a List Iterable . | 84 | 13 |
23,004 | public Iterable < String [ ] > toArrays ( ) { checkState ( ! isClosed , WORKBOOK_CLOSED ) ; Iterable < String [ ] > arraysIterable = Iterables . transform ( sheet , item -> { List < String > list = rowToList ( item ) ; return list . toArray ( new String [ list . size ( ) ] ) ; } ) ; return hasHeader ? Iterables . skip ( arraysIterable , 1 ) : arraysIterable ; } | Converts the spreadsheet to String Arrays by an Array Iterable . | 104 | 14 |
23,005 | public Iterable < Map < String , String > > toMaps ( ) { checkState ( ! isClosed , WORKBOOK_CLOSED ) ; checkState ( hasHeader , NO_HEADER ) ; return Iterables . skip ( Iterables . transform ( sheet , item -> { Map < String , String > map = newLinkedHashMap ( ) ; List < String > row = rowToList ( item ) ; for ( int i = 0 ; i < getHeader ( ) . size ( ) ; i ++ ) { map . put ( getHeader ( ) . get ( i ) , row . get ( i ) ) ; } return map ; } ) , 1 ) ; } | Converts the spreadsheet to Maps by a Map Iterable . All Maps are implemented by LinkedHashMap which implies the order of all fields is kept . | 143 | 31 |
23,006 | @ SuppressWarnings ( "unchecked" ) @ Override public void start ( final Listener < ? > listener , final Infrastructure infra ) throws MessageTransportException { this . listener = ( Listener < Object > ) listener ; } | A receiver is started with a Listener and a threading model . | 52 | 14 |
23,007 | @ SuppressWarnings ( { "rawtypes" , "unchecked" } ) @ Override public synchronized void start ( final Listener listener , final Infrastructure infra ) { if ( listener == null ) throw new IllegalArgumentException ( "Cannot pass null to " + BlockingQueueReceiver . class . getSimpleName ( ) + ".setListener" ) ; if ( this . listener != null ) throw new IllegalStateException ( "Cannot set a new Listener (" + SafeString . objectDescription ( listener ) + ") on a " + BlockingQueueReceiver . class . getSimpleName ( ) + " when there's one already set (" + SafeString . objectDescription ( this . listener ) + ")" ) ; this . listener = listener ; infra . getThreadingModel ( ) . runDaemon ( this , "BQReceiver-" + address . toString ( ) ) ; } | A BlockingQueueAdaptor requires a MessageTransportListener to be set in order to adapt a client side . | 194 | 23 |
23,008 | public static void unwindMessages ( final Object message , final List < Object > messages ) { if ( message instanceof Iterable ) { @ SuppressWarnings ( "rawtypes" ) final Iterator it = ( ( Iterable ) message ) . iterator ( ) ; while ( it . hasNext ( ) ) unwindMessages ( it . next ( ) , messages ) ; } else messages . add ( message ) ; } | Return values from invoke s may be Iterables in which case there are many messages to be sent out . | 91 | 21 |
23,009 | private Set < Integer > perNodeRelease ( final C thisNodeAddress , final C [ ] currentState , final int nodeCount , final int nodeRank ) { final int numberIShouldHave = howManyShouldIHave ( totalNumShards , nodeCount , minNodes , nodeRank ) ; // destinationsAcquired reflects what we already have according to the currentState final List < Integer > destinationsAcquired = buildDestinationsAcquired ( thisNodeAddress , currentState ) ; final int numHad = destinationsAcquired . size ( ) ; final Set < Integer > ret = new HashSet <> ( ) ; if ( destinationsAcquired . size ( ) > numberIShouldHave ) { // there's some to remove. final Random random = new Random ( ) ; while ( destinationsAcquired . size ( ) > numberIShouldHave ) { final int index = random . nextInt ( destinationsAcquired . size ( ) ) ; ret . add ( destinationsAcquired . remove ( index ) ) ; } } if ( LOGGER . isTraceEnabled ( ) && ret . size ( ) > 0 ) LOGGER . trace ( thisNodeAddress . toString ( ) + " removing shards " + ret + " because I have " + numHad + " but shouldn't have more than " + numberIShouldHave + "." ) ; return ret ; } | go through and determine which nodes to give up ... if any | 293 | 12 |
23,010 | private boolean registerAndConfirmIfImIt ( ) throws ClusterInfoException { // reset the subdir watcher final Collection < String > imItSubdirs = utils . persistentGetSubdir ( utils . leaderDir , this ) ; // "there can be only one" if ( imItSubdirs . size ( ) > 1 ) throw new ClusterInfoException ( "This is IMPOSSIBLE. There's more than one subdir of " + utils . leaderDir + ". They include " + imItSubdirs ) ; // make sure it's still mine. @ SuppressWarnings ( "unchecked" ) final C registered = ( C ) session . getData ( utils . masterDetermineDir , null ) ; return utils . thisNodeAddress . equals ( registered ) ; // am I it, or not? } | whether or not imIt and return that . | 180 | 9 |
23,011 | @ Override public void send ( final Object message ) throws MessageTransportException { if ( shutdown . get ( ) ) throw new MessageTransportException ( "send called on shutdown queue." ) ; if ( blocking ) { while ( true ) { try { queue . put ( message ) ; if ( statsCollector != null ) statsCollector . messageSent ( message ) ; break ; } catch ( final InterruptedException ie ) { if ( shutdown . get ( ) ) throw new MessageTransportException ( "Shutting down durring send." ) ; } } } else { if ( ! queue . offer ( message ) ) { if ( statsCollector != null ) statsCollector . messageNotSent ( ) ; throw new MessageTransportException ( "Failed to queue message due to capacity." ) ; } else if ( statsCollector != null ) statsCollector . messageSent ( message ) ; } } | Send a message into the BlockingQueueAdaptor . | 190 | 11 |
23,012 | public static < A extends Annotation > List < AnnotatedClass < A > > allTypeAnnotations ( final Class < ? > clazz , final Class < A > annotation , final boolean recurse ) { final List < AnnotatedClass < A > > ret = new ArrayList <> ( ) ; final A curClassAnnotation = clazz . getAnnotation ( annotation ) ; if ( curClassAnnotation != null ) ret . add ( new AnnotatedClass < A > ( clazz , curClassAnnotation ) ) ; if ( ! recurse ) return ret ; final Class < ? > superClazz = clazz . getSuperclass ( ) ; if ( superClazz != null ) ret . addAll ( allTypeAnnotations ( superClazz , annotation , recurse ) ) ; // Now do the interfaces. final Class < ? > [ ] ifaces = clazz . getInterfaces ( ) ; if ( ifaces != null && ifaces . length > 0 ) Arrays . stream ( ifaces ) . forEach ( iface -> ret . addAll ( allTypeAnnotations ( iface , annotation , recurse ) ) ) ; return ret ; } | Get all annotation on the given class plus all annotations on the parent classes | 249 | 14 |
23,013 | private final void cleanupAfterExceptionDuringNodeDirCheck ( ) { if ( nodeDirectory != null ) { // attempt to remove the node directory try { if ( session . exists ( nodeDirectory , this ) ) { session . rmdir ( nodeDirectory ) ; } nodeDirectory = null ; } catch ( final ClusterInfoException cie2 ) { } } } | called from the catch clauses in checkNodeDirectory | 74 | 9 |
23,014 | public Cluster destination ( final String ... destinations ) { final String applicationName = clusterId . applicationName ; return destination ( Arrays . stream ( destinations ) . map ( d -> new ClusterId ( applicationName , d ) ) . toArray ( ClusterId [ ] :: new ) ) ; } | Set the list of explicit destination that outgoing messages should be limited to . | 60 | 14 |
23,015 | void setAppName ( final String appName ) { if ( clusterId . applicationName != null && ! clusterId . applicationName . equals ( appName ) ) throw new IllegalStateException ( "Restting the application name on a cluster is not allowed." ) ; clusterId = new ClusterId ( appName , clusterId . clusterName ) ; } | This is called from Node | 73 | 5 |
23,016 | protected String getName ( final String key ) { return MetricRegistry . name ( DropwizardClusterStatsCollector . class , "cluster" , clusterId . applicationName , clusterId . clusterName , key ) ; } | protected access for testing purposes | 50 | 5 |
23,017 | @ SuppressWarnings ( "unchecked" ) @ Override public T newInstance ( ) throws DempsyException { return wrap ( ( ) -> ( T ) cloneMethod . invoke ( prototype ) ) ; } | Creates a new instance from the prototype . | 45 | 9 |
23,018 | @ Override public void activate ( final T instance , final Object key ) throws DempsyException { wrap ( ( ) -> activationMethod . invoke ( instance , key ) ) ; } | Invokes the activation method of the passed instance . | 37 | 10 |
23,019 | @ Override public boolean invokeEvictable ( final T instance ) throws DempsyException { return isEvictionSupported ( ) ? ( Boolean ) wrap ( ( ) -> evictableMethod . invoke ( instance ) ) : false ; } | Invokes the evictable method on the provided instance . If the evictable is not implemented returns false . | 48 | 21 |
23,020 | public JobDetail getJobDetail ( OutputInvoker outputInvoker ) { JobBuilder jobBuilder = JobBuilder . newJob ( OutputJob . class ) ; JobDetail jobDetail = jobBuilder . build ( ) ; jobDetail . getJobDataMap ( ) . put ( OUTPUT_JOB_NAME , outputInvoker ) ; return jobDetail ; } | Gets the job detail . | 80 | 6 |
23,021 | public Trigger getSimpleTrigger ( TimeUnit timeUnit , int timeInterval ) { SimpleScheduleBuilder simpleScheduleBuilder = null ; simpleScheduleBuilder = SimpleScheduleBuilder . simpleSchedule ( ) ; switch ( timeUnit ) { case MILLISECONDS : simpleScheduleBuilder . withIntervalInMilliseconds ( timeInterval ) . repeatForever ( ) ; break ; case SECONDS : simpleScheduleBuilder . withIntervalInSeconds ( timeInterval ) . repeatForever ( ) ; break ; case MINUTES : simpleScheduleBuilder . withIntervalInMinutes ( timeInterval ) . repeatForever ( ) ; break ; case HOURS : simpleScheduleBuilder . withIntervalInHours ( timeInterval ) . repeatForever ( ) ; break ; case DAYS : simpleScheduleBuilder . withIntervalInHours ( timeInterval * 24 ) . repeatForever ( ) ; break ; default : simpleScheduleBuilder . withIntervalInSeconds ( 1 ) . repeatForever ( ) ; //default 1 sec } Trigger simpleTrigger = TriggerBuilder . newTrigger ( ) . withSchedule ( simpleScheduleBuilder ) . build ( ) ; return simpleTrigger ; } | Gets the simple trigger . | 260 | 6 |
23,022 | public Trigger getCronTrigger ( String cronExpression ) { CronScheduleBuilder cronScheduleBuilder = null ; Trigger cronTrigger = null ; try { cronScheduleBuilder = CronScheduleBuilder . cronSchedule ( cronExpression ) ; cronScheduleBuilder . withMisfireHandlingInstructionFireAndProceed ( ) ; TriggerBuilder < Trigger > cronTtriggerBuilder = TriggerBuilder . newTrigger ( ) ; cronTtriggerBuilder . withSchedule ( cronScheduleBuilder ) ; cronTrigger = cronTtriggerBuilder . build ( ) ; } catch ( Exception pe ) { logger . error ( "Error occurred while builiding the cronTrigger : " + pe . getMessage ( ) , pe ) ; } return cronTrigger ; } | Gets the cron trigger . | 170 | 7 |
23,023 | public static < T > ListenableFuture < T > createListenableFuture ( ValueSourceFuture < T > valueSourceFuture ) { if ( valueSourceFuture instanceof ListenableFutureBackedValueSourceFuture ) { return ( ( ListenableFutureBackedValueSourceFuture < T > ) valueSourceFuture ) . getWrappedFuture ( ) ; } else { return new ValueSourceFutureBackedListenableFuture <> ( valueSourceFuture ) ; } } | Creates listenable future from ValueSourceFuture . We have to send all Future API calls to ValueSourceFuture . | 94 | 23 |
23,024 | public static < T > ApiFuture < T > createApiFuture ( ValueSourceFuture < T > valueSourceFuture ) { if ( valueSourceFuture instanceof ApiFutureBackedValueSourceFuture ) { return ( ( ApiFutureBackedValueSourceFuture < T > ) valueSourceFuture ) . getWrappedFuture ( ) ; } else { return new ValueSourceFutureBackedApiFuture <> ( valueSourceFuture ) ; } } | Creates api future from ValueSourceFuture . We have to send all Future API calls to ValueSourceFuture . | 94 | 22 |
23,025 | private void getLastChild ( ) { // nodekey of the root of the current subtree final long parent = getNode ( ) . getDataKey ( ) ; // traverse tree in pre order to the leftmost leaf of the subtree and // push // all nodes to the stack if ( ( ( ITreeStructData ) getNode ( ) ) . hasFirstChild ( ) ) { while ( ( ( ITreeStructData ) getNode ( ) ) . hasFirstChild ( ) ) { mStack . push ( getNode ( ) . getDataKey ( ) ) ; moveTo ( ( ( ITreeStructData ) getNode ( ) ) . getFirstChildKey ( ) ) ; } // traverse all the siblings of the leftmost leave and all their // descendants and push all of them to the stack while ( ( ( ITreeStructData ) getNode ( ) ) . hasRightSibling ( ) ) { mStack . push ( getNode ( ) . getDataKey ( ) ) ; moveTo ( ( ( ITreeStructData ) getNode ( ) ) . getRightSiblingKey ( ) ) ; getLastChild ( ) ; } // step up the path till the root of the current subtree and process // all // right siblings and their descendants on each step if ( getNode ( ) . hasParent ( ) && ( getNode ( ) . getParentKey ( ) != parent ) ) { mStack . push ( getNode ( ) . getDataKey ( ) ) ; while ( getNode ( ) . hasParent ( ) && ( getNode ( ) . getParentKey ( ) != parent ) ) { moveTo ( getNode ( ) . getParentKey ( ) ) ; // traverse all the siblings of the leftmost leave and all // their // descendants and push all of them to the stack while ( ( ( ITreeStructData ) getNode ( ) ) . hasRightSibling ( ) ) { moveTo ( ( ( ITreeStructData ) getNode ( ) ) . getRightSiblingKey ( ) ) ; getLastChild ( ) ; mStack . push ( getNode ( ) . getDataKey ( ) ) ; } } // set transaction to the node in the subtree that is last in // document // order moveTo ( mStack . pop ( ) ) ; } } } | Moves the transaction to the node in the current subtree that is last in document order and pushes all other node key on a stack . At the end the stack contains all node keys except for the last one in reverse document order . | 482 | 47 |
23,026 | public static JaxRx getInstance ( final String impl ) { final String path = Systems . getSystems ( ) . get ( impl ) ; if ( path == null ) { throw new JaxRxException ( 404 , "Unknown implementation: " + impl ) ; } JaxRx jaxrx = INSTANCES . get ( path ) ; if ( jaxrx == null ) { try { jaxrx = ( JaxRx ) Class . forName ( path ) . newInstance ( ) ; INSTANCES . put ( path , jaxrx ) ; } catch ( final Exception ex ) { throw new JaxRxException ( ex ) ; } } return jaxrx ; } | Returns the instance for the specified implementation . If the system is unknown throws an exception . | 149 | 17 |
23,027 | public void add ( final String prefix , final String uri ) { if ( prefix == null ) { defaultNS = uri ; } addToMap ( prefix , uri ) ; } | Add a namespace to the maps | 39 | 6 |
23,028 | public void appendNsName ( final StringBuilder sb , final QName nm ) { String uri = nm . getNamespaceURI ( ) ; String abbr ; if ( ( defaultNS != null ) && uri . equals ( defaultNS ) ) { abbr = null ; } else { abbr = keyUri . get ( uri ) ; if ( abbr == null ) { abbr = uri ; } } if ( abbr != null ) { sb . append ( abbr ) ; sb . append ( ":" ) ; } sb . append ( nm . getLocalPart ( ) ) ; } | Append the name with abbreviated namespace . | 133 | 9 |
23,029 | public static String generate ( final int length ) { final StringBuilder password = new StringBuilder ( length ) ; double pik = random . nextDouble ( ) ; // random number [0,1] long ranno = ( long ) ( pik * sigma ) ; // weight by sum of frequencies long sum = 0 ; outer : for ( int c1 = 0 ; c1 < 26 ; c1 ++ ) { for ( int c2 = 0 ; c2 < 26 ; c2 ++ ) { for ( int c3 = 0 ; c3 < 26 ; c3 ++ ) { sum += get ( c1 , c2 , c3 ) ; if ( sum > ranno ) { password . append ( alphabet . charAt ( c1 ) ) ; password . append ( alphabet . charAt ( c2 ) ) ; password . append ( alphabet . charAt ( c3 ) ) ; break outer ; // Found start. } } } } // Now do a random walk. int nchar = 3 ; while ( nchar < length ) { final int c1 = alphabet . indexOf ( password . charAt ( nchar - 2 ) ) ; final int c2 = alphabet . indexOf ( password . charAt ( nchar - 1 ) ) ; sum = 0 ; for ( int c3 = 0 ; c3 < 26 ; c3 ++ ) { sum += get ( c1 , c2 , c3 ) ; } if ( sum == 0 ) { break ; } pik = random . nextDouble ( ) ; ranno = ( long ) ( pik * sum ) ; sum = 0 ; for ( int c3 = 0 ; c3 < 26 ; c3 ++ ) { sum += get ( c1 , c2 , c3 ) ; if ( sum > ranno ) { password . append ( alphabet . charAt ( c3 ) ) ; break ; } } nchar ++ ; } return password . toString ( ) ; } | Generates a new password . | 413 | 6 |
23,030 | public void parseQuery ( ) throws TTXPathException { // get first token, ignore all white spaces do { mToken = mScanner . nextToken ( ) ; } while ( mToken . getType ( ) == TokenType . SPACE ) ; // parse the query according to the rules specified in the XPath 2.0 REC parseExpression ( ) ; // after the parsing of the expression no token must be left if ( mToken . getType ( ) != TokenType . END ) { throw new IllegalStateException ( "The query has not been processed completely." ) ; } } | Starts parsing the query . | 122 | 6 |
23,031 | private boolean isReservedKeyword ( ) { final String content = mToken . getContent ( ) ; return isKindTest ( ) || "item" . equals ( content ) || "if" . equals ( content ) || "empty-sequence" . equals ( content ) || "typeswitch" . equals ( content ) ; } | Although XPath is supposed to have no reserved words some keywords are not allowed as function names in an unprefixed form because expression syntax takes precedence . | 69 | 29 |
23,032 | private boolean isForwardAxis ( ) { final String content = mToken . getContent ( ) ; return ( mToken . getType ( ) == TokenType . TEXT && ( "child" . equals ( content ) || ( "descendant" . equals ( content ) || "descendant-or-self" . equals ( content ) || "attribute" . equals ( content ) || "self" . equals ( content ) || "following" . equals ( content ) || "following-sibling" . equals ( content ) || "namespace" . equals ( content ) ) ) ) ; } | Checks if a given token represents a ForwardAxis . | 126 | 12 |
23,033 | private void consume ( final TokenType mType , final boolean mIgnoreWhitespace ) { if ( ! is ( mType , mIgnoreWhitespace ) ) { // error found by parser - stopping throw new IllegalStateException ( "Wrong token after " + mScanner . begin ( ) + " at position " + mScanner . getPos ( ) + " found " + mToken . getType ( ) + " expected " + mType + "." ) ; } } | Consumes a token . Tests if it really has the expected type and if not returns an error message . Otherwise gets a new token from the scanner . If that new token is of type whitespace and the ignoreWhitespace parameter is true a new token is retrieved until the current token is not of type whitespace . | 104 | 64 |
23,034 | private void consume ( final String mName , final boolean mIgnoreWhitespace ) { if ( ! is ( mName , mIgnoreWhitespace ) ) { // error found by parser - stopping throw new IllegalStateException ( "Wrong token after " + mScanner . begin ( ) + " found " + mToken . getContent ( ) + ". Expected " + mName ) ; } } | Consumes a token . Tests if it really has the expected name and if not returns an error message . Otherwise gets a new token from the scanner . If that new token is of type whitespace and the ignoreWhitespace parameter is true a new token is retrieved until the current token is not of type whitespace . | 87 | 64 |
23,035 | private boolean is ( final String mName , final boolean mIgnoreWhitespace ) { if ( ! mName . equals ( mToken . getContent ( ) ) ) { return false ; } if ( mToken . getType ( ) == TokenType . COMP || mToken . getType ( ) == TokenType . EQ || mToken . getType ( ) == TokenType . N_EQ || mToken . getType ( ) == TokenType . PLUS || mToken . getType ( ) == TokenType . MINUS || mToken . getType ( ) == TokenType . STAR ) { return is ( mToken . getType ( ) , mIgnoreWhitespace ) ; } else { return is ( TokenType . TEXT , mIgnoreWhitespace ) ; } } | Returns true or false if a token has the expected name . If the token has the given name it gets a new token from the scanner . If that new token is of type whitespace and the ignoreWhitespace parameter is true a new token is retrieved until the current token is not of type whitespace . | 166 | 62 |
23,036 | private boolean is ( final TokenType mType , final boolean mIgnoreWhitespace ) { if ( mType != mToken . getType ( ) ) { return false ; } do { // scan next token mToken = mScanner . nextToken ( ) ; } while ( mIgnoreWhitespace && mToken . getType ( ) == TokenType . SPACE ) ; return true ; } | Returns true or false if a token has the expected type . If so a new token is retrieved from the scanner . If that new token is of type whitespace and the ignoreWhitespace parameter is true a new token is retrieved until the current token is not of type whitespace . | 84 | 57 |
23,037 | public String newIndex ( final String name , final String mappingPath ) throws IndexException { try { final String newName = name + newIndexSuffix ( ) ; final IndicesAdminClient idx = getAdminIdx ( ) ; final CreateIndexRequestBuilder cirb = idx . prepareCreate ( newName ) ; final File f = new File ( mappingPath ) ; final byte [ ] sbBytes = Streams . copyToByteArray ( f ) ; cirb . setSource ( sbBytes ) ; final CreateIndexRequest cir = cirb . request ( ) ; final ActionFuture < CreateIndexResponse > af = idx . create ( cir ) ; /*resp = */ af . actionGet ( ) ; //index(new UpdateInfo()); info ( "Index created" ) ; return newName ; } catch ( final ElasticsearchException ese ) { // Failed somehow error ( ese ) ; return null ; } catch ( final IndexException ie ) { throw ie ; } catch ( final Throwable t ) { error ( t ) ; throw new IndexException ( t ) ; } } | create a new index and return its name . No alias will point to the new index . | 229 | 18 |
23,038 | public List < String > purgeIndexes ( final Set < String > prefixes ) throws IndexException { final Set < IndexInfo > indexes = getIndexInfo ( ) ; final List < String > purged = new ArrayList <> ( ) ; if ( Util . isEmpty ( indexes ) ) { return purged ; } purge : for ( final IndexInfo ii : indexes ) { final String idx = ii . getIndexName ( ) ; if ( ! hasPrefix ( idx , prefixes ) ) { continue purge ; } /* Don't delete those pointed to by any aliases */ if ( ! Util . isEmpty ( ii . getAliases ( ) ) ) { continue purge ; } purged . add ( idx ) ; } deleteIndexes ( purged ) ; return purged ; } | Remove any index that doesn t have an alias and starts with the given prefix | 169 | 15 |
23,039 | public int swapIndex ( final String index , final String alias ) throws IndexException { //IndicesAliasesResponse resp = null; try { /* index is the index we were just indexing into */ final IndicesAdminClient idx = getAdminIdx ( ) ; final GetAliasesRequestBuilder igarb = idx . prepareGetAliases ( alias ) ; final ActionFuture < GetAliasesResponse > getAliasesAf = idx . getAliases ( igarb . request ( ) ) ; final GetAliasesResponse garesp = getAliasesAf . actionGet ( ) ; final ImmutableOpenMap < String , List < AliasMetaData > > aliasesmeta = garesp . getAliases ( ) ; final IndicesAliasesRequestBuilder iarb = idx . prepareAliases ( ) ; final Iterator < String > it = aliasesmeta . keysIt ( ) ; while ( it . hasNext ( ) ) { final String indexName = it . next ( ) ; for ( final AliasMetaData amd : aliasesmeta . get ( indexName ) ) { if ( amd . getAlias ( ) . equals ( alias ) ) { iarb . removeAlias ( indexName , alias ) ; } } } iarb . addAlias ( index , alias ) ; final ActionFuture < IndicesAliasesResponse > af = idx . aliases ( iarb . request ( ) ) ; /*resp = */ af . actionGet ( ) ; return 0 ; } catch ( final ElasticsearchException ese ) { // Failed somehow error ( ese ) ; return - 1 ; } catch ( final IndexException ie ) { throw ie ; } catch ( final Throwable t ) { throw new IndexException ( t ) ; } } | Changes the givenm alias to refer tot eh supplied index name | 363 | 12 |
23,040 | public Collection < DavChild > syncReport ( final BasicHttpClient cl , final String path , final String syncToken , final Collection < QName > props ) throws Throwable { final StringWriter sw = new StringWriter ( ) ; final XmlEmit xml = getXml ( ) ; addNs ( xml , WebdavTags . namespace ) ; xml . startEmit ( sw ) ; /* <?xml version="1.0" encoding="utf-8" ?> <D:sync-collection xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav"> <D:sync-token/> <D:prop> <D:getetag/> </D:prop> </D:sync-collection> */ xml . openTag ( WebdavTags . syncCollection ) ; if ( syncToken == null ) { xml . emptyTag ( WebdavTags . syncToken ) ; } else { xml . property ( WebdavTags . syncToken , syncToken ) ; } xml . property ( WebdavTags . synclevel , "1" ) ; xml . openTag ( WebdavTags . prop ) ; xml . emptyTag ( WebdavTags . getetag ) ; if ( props != null ) { for ( final QName pr : props ) { if ( pr . equals ( WebdavTags . getetag ) ) { continue ; } addNs ( xml , pr . getNamespaceURI ( ) ) ; xml . emptyTag ( pr ) ; } } xml . closeTag ( WebdavTags . prop ) ; xml . closeTag ( WebdavTags . syncCollection ) ; final byte [ ] content = sw . toString ( ) . getBytes ( ) ; final int res = sendRequest ( cl , "REPORT" , path , depth0 , "text/xml" , // contentType, content . length , // contentLen, content ) ; if ( res == HttpServletResponse . SC_NOT_FOUND ) { return null ; } final int SC_MULTI_STATUS = 207 ; // not defined for some reason if ( res != SC_MULTI_STATUS ) { if ( debug ( ) ) { debug ( "Got response " + res + " for path " + path ) ; } //throw new Exception("Got response " + res + " for path " + path); return null ; } final Document doc = parseContent ( cl . getResponseBodyAsStream ( ) ) ; final Element root = doc . getDocumentElement ( ) ; /* <!ELEMENT multistatus (response+, responsedescription?) > */ expect ( root , WebdavTags . multistatus ) ; return processResponses ( getChildren ( root ) , null ) ; } | Do a synch report on the targeted collection . | 595 | 10 |
23,041 | protected void addNs ( final XmlEmit xml , final String val ) throws Throwable { if ( xml . getNameSpace ( val ) == null ) { xml . addNs ( new NameSpace ( val , null ) , false ) ; } } | Add a namespace | 53 | 3 |
23,042 | protected Document parseContent ( final InputStream in ) throws Throwable { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; DocumentBuilder builder = factory . newDocumentBuilder ( ) ; return builder . parse ( new InputSource ( new InputStreamReader ( in ) ) ) ; } | Parse the content and return the DOM representation . | 71 | 10 |
23,043 | public Element parseError ( final InputStream in ) { try { final Document doc = parseContent ( in ) ; final Element root = doc . getDocumentElement ( ) ; expect ( root , WebdavTags . error ) ; final List < Element > els = getChildren ( root ) ; if ( els . size ( ) != 1 ) { return null ; } return els . get ( 0 ) ; } catch ( final Throwable ignored ) { return null ; } } | Parse a DAV error response | 100 | 6 |
23,044 | private static Element createResultElement ( final Document document ) { final Element ttResponse = document . createElementNS ( "http://jaxrx.org/" , "result" ) ; ttResponse . setPrefix ( "jaxrx" ) ; return ttResponse ; } | This method creates the TreeTank response XML element . | 60 | 10 |
23,045 | public static StreamingOutput buildResponseOfDomLR ( final IStorage pDatabase , final IBackendFactory pStorageFac , final IRevisioning pRevision ) { final StreamingOutput sOutput = new StreamingOutput ( ) { @ Override public void write ( final OutputStream output ) throws IOException , WebApplicationException { Document document ; try { document = createSurroundingXMLResp ( ) ; final Element resElement = RESTResponseHelper . createResultElement ( document ) ; List < Element > collections ; try { collections = RESTResponseHelper . createCollectionElementDBs ( pDatabase , document , pStorageFac , pRevision ) ; } catch ( final TTException exce ) { throw new WebApplicationException ( exce ) ; } for ( final Element resource : collections ) { resElement . appendChild ( resource ) ; } document . appendChild ( resElement ) ; final DOMSource domSource = new DOMSource ( document ) ; final StreamResult streamResult = new StreamResult ( output ) ; final Transformer transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; transformer . transform ( domSource , streamResult ) ; } catch ( final ParserConfigurationException exce ) { throw new WebApplicationException ( exce ) ; } catch ( final TransformerConfigurationException exce ) { throw new WebApplicationException ( exce ) ; } catch ( final TransformerFactoryConfigurationError exce ) { throw new WebApplicationException ( exce ) ; } catch ( final TransformerException exce ) { throw new WebApplicationException ( exce ) ; } } } ; return sOutput ; } | This method builds the overview for the resources and collection we offer in our implementation . | 327 | 16 |
23,046 | public static String getUrl ( final HttpServletRequest request ) { try { final StringBuffer sb = request . getRequestURL ( ) ; if ( sb != null ) { return sb . toString ( ) ; } // Presumably portlet - see what happens with uri return request . getRequestURI ( ) ; } catch ( Throwable t ) { return "BogusURL.this.is.probably.a.portal" ; } } | Returns the String url from the request . | 98 | 8 |
23,047 | protected void logSessionCounts ( final HttpSession sess , final boolean start ) { StringBuffer sb ; String appname = getAppName ( sess ) ; Counts ct = getCounts ( appname ) ; if ( start ) { sb = new StringBuffer ( "SESSION-START:" ) ; } else { sb = new StringBuffer ( "SESSION-END:" ) ; } sb . append ( getSessionId ( sess ) ) ; sb . append ( ":" ) ; sb . append ( appname ) ; sb . append ( ":" ) ; sb . append ( ct . activeSessions ) ; sb . append ( ":" ) ; sb . append ( ct . totalSessions ) ; sb . append ( ":" ) ; sb . append ( Runtime . getRuntime ( ) . freeMemory ( ) / ( 1024 * 1024 ) ) ; sb . append ( "M:" ) ; sb . append ( Runtime . getRuntime ( ) . totalMemory ( ) / ( 1024 * 1024 ) ) ; sb . append ( "M" ) ; info ( sb . toString ( ) ) ; } | Log the session counters for applications that maintain them . | 254 | 10 |
23,048 | private String getSessionId ( final HttpSession sess ) { try { if ( sess == null ) { return "NO-SESSIONID" ; } else { return sess . getId ( ) ; } } catch ( Throwable t ) { return "SESSION-ID-EXCEPTION" ; } } | Get the session id for the loggers . | 68 | 9 |
23,049 | public void checkBrowserType ( final HttpServletRequest request ) { String reqpar = request . getParameter ( getBrowserTypeRequestName ( ) ) ; if ( reqpar != null ) { if ( reqpar . equals ( "!" ) ) { // Go back to unsticky browser type setBrowserTypeSticky ( false ) ; } else { setBrowserType ( reqpar ) ; setBrowserTypeSticky ( false ) ; } } reqpar = request . getParameter ( getBrowserTypeStickyRequestName ( ) ) ; if ( reqpar != null ) { if ( reqpar . equals ( "!" ) ) { // Go back to unsticky browser type setBrowserTypeSticky ( false ) ; } else { setBrowserType ( reqpar ) ; setBrowserTypeSticky ( true ) ; } } } | Allow user to explicitly set the browser type . | 173 | 9 |
23,050 | public void checkContentType ( final HttpServletRequest request ) { String reqpar = request . getParameter ( getContentTypeRequestName ( ) ) ; if ( reqpar != null ) { if ( reqpar . equals ( "!" ) ) { // Go back to unsticky content type setContentTypeSticky ( false ) ; } else { setContentType ( reqpar ) ; setContentTypeSticky ( false ) ; } } reqpar = request . getParameter ( getContentTypeStickyRequestName ( ) ) ; if ( reqpar != null ) { if ( reqpar . equals ( "!" ) ) { // Go back to unsticky content type setContentTypeSticky ( false ) ; } else { setContentType ( reqpar ) ; setContentTypeSticky ( true ) ; } } } | Allow user to explicitly set the content type . | 173 | 9 |
23,051 | public void checkContentName ( final HttpServletRequest request ) { String reqpar = request . getParameter ( getContentNameRequestName ( ) ) ; // Set to null if not found. setContentName ( reqpar ) ; } | Allow user to explicitly set the filename of the content . | 50 | 11 |
23,052 | public void checkSkinName ( final HttpServletRequest request ) { String reqpar = request . getParameter ( getSkinNameRequestName ( ) ) ; if ( reqpar != null ) { if ( reqpar . equals ( "!" ) ) { // Go back to unsticky SkinName setSkinNameSticky ( false ) ; } else { setSkinName ( reqpar ) ; setSkinNameSticky ( false ) ; } } reqpar = request . getParameter ( getSkinNameStickyRequestName ( ) ) ; if ( reqpar != null ) { if ( reqpar . equals ( "!" ) ) { // Go back to unsticky SkinName setSkinNameSticky ( false ) ; } else { setSkinName ( reqpar ) ; setSkinNameSticky ( true ) ; } } } | Allow user to explicitly set the skin name . | 173 | 9 |
23,053 | public void checkRefreshXslt ( final HttpServletRequest request ) { String reqpar = request . getParameter ( getRefreshXSLTRequestName ( ) ) ; if ( reqpar == null ) { return ; } if ( reqpar . equals ( "yes" ) ) { setForceXSLTRefresh ( true ) ; } if ( reqpar . equals ( "always" ) ) { setForceXSLTRefreshAlways ( true ) ; } if ( reqpar . equals ( "!" ) ) { setForceXSLTRefreshAlways ( false ) ; } } | Allow user to indicate how we should refresh the xslt . | 127 | 13 |
23,054 | public void checkNoXSLT ( final HttpServletRequest request ) { String reqpar = request . getParameter ( getNoXSLTRequestName ( ) ) ; if ( reqpar != null ) { if ( reqpar . equals ( "!" ) ) { // Go back to unsticky noXslt setNoXSLTSticky ( false ) ; } else { setNoXSLT ( true ) ; } } reqpar = request . getParameter ( getNoXSLTStickyRequestName ( ) ) ; if ( reqpar != null ) { if ( reqpar . equals ( "!" ) ) { // Go back to unsticky noXslt setNoXSLTSticky ( false ) ; } else { setNoXSLT ( true ) ; setNoXSLTSticky ( true ) ; } } } | Allow user to suppress XSLT transform for one request . Used for debugging - provides the raw xml . | 182 | 21 |
23,055 | public static Map < Long , LogEntry > getBranchLog ( String [ ] branches , long startRevision , long endRevision , String baseUrl , String user , String pwd ) throws IOException , SAXException { try ( InputStream inStr = getBranchLogStream ( branches , startRevision , endRevision , baseUrl , user , pwd ) ) { return new SVNLogFileParser ( branches ) . parseContent ( inStr ) ; } catch ( SAXException e ) { throw new SAXException ( "While parsing branch-log of " + Arrays . toString ( branches ) + ", start: " + startRevision + ", end: " + endRevision + " with user " + user , e ) ; } } | Retrieve the XML - log of changes on the given branch in a specified range of revisions . | 162 | 19 |
23,056 | public static InputStream getRemoteFileContent ( String file , long revision , String baseUrl , String user , String pwd ) throws IOException { // svn cat -r 666 file CommandLine cmdLine = new CommandLine ( SVN_CMD ) ; cmdLine . addArgument ( CMD_CAT ) ; addDefaultArguments ( cmdLine , user , pwd ) ; cmdLine . addArgument ( "-r" ) ; cmdLine . addArgument ( Long . toString ( revision ) ) ; cmdLine . addArgument ( baseUrl + file ) ; return ExecutionHelper . getCommandResult ( cmdLine , new File ( "." ) , 0 , 120000 ) ; } | Retrieve the contents of a file from the web - interface of the SVN server . | 148 | 18 |
23,057 | public static boolean branchExists ( String branch , String baseUrl ) { CommandLine cmdLine = new CommandLine ( SVN_CMD ) ; cmdLine . addArgument ( CMD_LOG ) ; cmdLine . addArgument ( OPT_XML ) ; addDefaultArguments ( cmdLine , null , null ) ; cmdLine . addArgument ( "-r" ) ; cmdLine . addArgument ( "HEAD:HEAD" ) ; cmdLine . addArgument ( baseUrl + branch ) ; try ( InputStream inStr = ExecutionHelper . getCommandResult ( cmdLine , new File ( "." ) , 0 , 120000 ) ) { return true ; } catch ( IOException e ) { log . log ( Level . FINE , "Branch " + branch + " not found or other error" , e ) ; return false ; } } | Check if the given branch already exists | 183 | 7 |
23,058 | public static long getBranchRevision ( String branch , String baseUrl ) throws IOException { CommandLine cmdLine = new CommandLine ( SVN_CMD ) ; cmdLine . addArgument ( CMD_LOG ) ; cmdLine . addArgument ( OPT_XML ) ; addDefaultArguments ( cmdLine , null , null ) ; cmdLine . addArgument ( "-v" ) ; cmdLine . addArgument ( "-r0:HEAD" ) ; cmdLine . addArgument ( "--stop-on-copy" ) ; cmdLine . addArgument ( "--limit" ) ; cmdLine . addArgument ( "1" ) ; cmdLine . addArgument ( baseUrl + branch ) ; try ( InputStream inStr = ExecutionHelper . getCommandResult ( cmdLine , new File ( "." ) , 0 , 120000 ) ) { String xml = IOUtils . toString ( inStr , "UTF-8" ) ; log . info ( "XML:\n" + xml ) ; // read the revision Matcher matcher = Pattern . compile ( "copyfrom-rev=\"([0-9]+)\"" ) . matcher ( xml ) ; if ( ! matcher . find ( ) ) { throw new IOException ( "Could not find copyfrom-rev entry in xml: " + xml ) ; } log . info ( "Found copyfrom-rev: " + matcher . group ( 1 ) ) ; return Long . parseLong ( matcher . group ( 1 ) ) ; } } | Return the revision from which the branch was branched off . | 331 | 13 |
23,059 | public static long getLastRevision ( String branch , String baseUrl , String user , String pwd ) throws IOException { CommandLine cmdLine = new CommandLine ( SVN_CMD ) ; cmdLine . addArgument ( "info" ) ; addDefaultArguments ( cmdLine , user , pwd ) ; cmdLine . addArgument ( baseUrl + branch ) ; try ( InputStream inStr = ExecutionHelper . getCommandResult ( cmdLine , new File ( "." ) , 0 , 120000 ) ) { String info = IOUtils . toString ( inStr , "UTF-8" ) ; log . info ( "Info:\n" + info ) ; /* svn info http://... Repository Root: https://svn-lnz.emea.cpwr.corp/svn/dev Repository UUID: 35fb04cf-4f84-b44d-92fa-8d0d0442729e Revision: 390864 Node Kind: directory */ // read the revision Matcher matcher = Pattern . compile ( "Revision: ([0-9]+)" ) . matcher ( info ) ; if ( ! matcher . find ( ) ) { throw new IOException ( "Could not find Revision entry in info-output: " + info ) ; } log . info ( "Found rev: " + matcher . group ( 1 ) + " for branch " + branch ) ; return Long . parseLong ( matcher . group ( 1 ) ) ; } } | Return the last revision of the given branch . Uses the full svn repository if branch is | 324 | 18 |
23,060 | public static InputStream getPendingCheckins ( File directory ) throws IOException { CommandLine cmdLine = new CommandLine ( SVN_CMD ) ; cmdLine . addArgument ( CMD_STATUS ) ; addDefaultArguments ( cmdLine , null , null ) ; return ExecutionHelper . getCommandResult ( cmdLine , directory , - 1 , 120000 ) ; } | Performs a svn status and returns the list of changes in the svn tree at the given directory in the format that the svn command provides them . | 81 | 32 |
23,061 | public static InputStream recordMerge ( File directory , String branchName , long ... revisions ) throws IOException { // svn merge -c 3328 --record-only ^/calc/trunk CommandLine cmdLine = new CommandLine ( SVN_CMD ) ; cmdLine . addArgument ( CMD_MERGE ) ; addDefaultArguments ( cmdLine , null , null ) ; cmdLine . addArgument ( "--record-only" ) ; cmdLine . addArgument ( "-c" ) ; StringBuilder revs = new StringBuilder ( ) ; for ( long revision : revisions ) { revs . append ( revision ) . append ( "," ) ; } cmdLine . addArgument ( revs . toString ( ) ) ; // leads to "non-inheritable merges" // cmdLine.addArgument("--depth"); // cmdLine.addArgument("empty"); cmdLine . addArgument ( "^" + branchName ) ; //cmdLine.addArgument("."); // current dir return ExecutionHelper . getCommandResult ( cmdLine , directory , 0 , 120000 ) ; } | Record a manual merge from one branch to the local working directory . | 243 | 13 |
23,062 | public static boolean verifyNoPendingChanges ( File directory ) throws IOException { log . info ( "Checking that there are no pending changes on trunk-working copy" ) ; try ( InputStream inStr = getPendingCheckins ( directory ) ) { List < String > lines = IOUtils . readLines ( inStr , "UTF-8" ) ; if ( lines . size ( ) > 0 ) { log . info ( "Found the following checkouts:\n" + ArrayUtils . toString ( lines . toArray ( ) , "\n" ) ) ; return true ; } } return false ; } | Check if there are pending changes on the branch returns true if changes are found . | 133 | 16 |
23,063 | public static MergeResult mergeRevision ( long revision , File directory , String branch , String baseUrl ) throws IOException { // svn merge -r 1288:1351 http://svn.example.com/myrepos/branch CommandLine cmdLine = new CommandLine ( SVN_CMD ) ; cmdLine . addArgument ( CMD_MERGE ) ; addDefaultArguments ( cmdLine , null , null ) ; cmdLine . addArgument ( "-x" ) ; cmdLine . addArgument ( "-uw --ignore-eol-style" ) ; // unified-diff and ignore all whitespace changes cmdLine . addArgument ( "--accept" ) ; cmdLine . addArgument ( "postpone" ) ; cmdLine . addArgument ( "-c" ) ; cmdLine . addArgument ( Long . toString ( revision ) ) ; cmdLine . addArgument ( baseUrl + branch ) ; try ( InputStream result = ExecutionHelper . getCommandResult ( cmdLine , directory , 0 , 120000 ) ) { String output = extractResult ( result ) ; boolean foundActualMerge = false ; boolean foundConflict = false ; // check if only svn-properties were updated for ( String line : output . split ( "\n" ) ) { // ignore the comments about what is done if ( line . startsWith ( "--- " ) ) { continue ; } if ( line . length ( ) >= 4 && line . substring ( 0 , 4 ) . contains ( "C" ) ) { // C..Conflict foundConflict = true ; log . info ( "Found conflict!" ) ; break ; } else if ( ! line . startsWith ( " U " ) && ! line . startsWith ( " G " ) ) { // U..Updated, G..Merged, on second position means "property", any other change is an actual merge foundActualMerge = true ; log . info ( "Found actual merge: " + line ) ; } } log . info ( "Svn-Merge reported:\n" + output ) ; if ( foundConflict ) { return MergeResult . Conflicts ; } if ( ! foundActualMerge ) { log . info ( "Only mergeinfo updates found after during merge." ) ; return MergeResult . OnlyMergeInfo ; } } return MergeResult . Normal ; } | Merge the given revision and return true if only mergeinfo changes were done on trunk . | 507 | 18 |
23,064 | public static String getMergedRevisions ( File directory , String ... branches ) throws IOException { // we could also use svn mergeinfo --show-revs merged ^/trunk ^/branches/test CommandLine cmdLine ; cmdLine = new CommandLine ( SVN_CMD ) ; cmdLine . addArgument ( "propget" ) ; addDefaultArguments ( cmdLine , null , null ) ; cmdLine . addArgument ( "svn:mergeinfo" ) ; StringBuilder MERGED_REVISIONS_BUILD = new StringBuilder ( ) ; try ( InputStream ignoreStr = ExecutionHelper . getCommandResult ( cmdLine , directory , 0 , 120000 ) ) { List < String > lines = IOUtils . readLines ( ignoreStr , "UTF-8" ) ; for ( String line : lines ) { for ( String source : branches ) { if ( line . startsWith ( source + ":" ) ) { log . info ( "Found merged revisions for branch: " + source ) ; MERGED_REVISIONS_BUILD . append ( "," ) . append ( line . substring ( source . length ( ) + 1 ) ) ; // + 1 for ":" break ; } } } } String MERGED_REVISIONS = StringUtils . removeStart ( MERGED_REVISIONS_BUILD . toString ( ) , "," ) ; if ( MERGED_REVISIONS . equals ( "" ) ) { throw new IllegalStateException ( "Could not read merged revision with command " + cmdLine + " in directory " + directory ) ; } // expand ranges r1-r2 into separate numbers for easier search in the string later on List < Long > revList = new ArrayList <> ( ) ; String [ ] revs = MERGED_REVISIONS . split ( "," ) ; for ( String rev : revs ) { if ( rev . contains ( "-" ) ) { String [ ] revRange = rev . split ( "-" ) ; if ( revRange . length != 2 ) { throw new IllegalStateException ( "Expected to have start and end of range, but had: " + rev ) ; } for ( long r = Long . parseLong ( revRange [ 0 ] ) ; r <= Long . parseLong ( revRange [ 1 ] ) ; r ++ ) { revList . add ( r ) ; } } else { // non-inheritable merge adds a "*" to the rev, see https://groups.google.com/forum/?fromgroups=#!topic/subversion-svn/ArXTv1rUk5w rev = StringUtils . removeEnd ( rev , "*" ) ; revList . add ( Long . parseLong ( rev ) ) ; } } return revList . toString ( ) ; } | Retrieve a list of all merged revisions . | 609 | 9 |
23,065 | public static void revertAll ( File directory ) throws IOException { log . info ( "Reverting SVN Working copy at " + directory ) ; CommandLine cmdLine = new CommandLine ( SVN_CMD ) ; cmdLine . addArgument ( CMD_REVERT ) ; addDefaultArguments ( cmdLine , null , null ) ; cmdLine . addArgument ( OPT_DEPTH ) ; cmdLine . addArgument ( INFINITY ) ; cmdLine . addArgument ( directory . getAbsolutePath ( ) ) ; try ( InputStream result = ExecutionHelper . getCommandResult ( cmdLine , directory , 0 , 120000 ) ) { log . info ( "Svn-RevertAll reported:\n" + extractResult ( result ) ) ; } } | Revert all changes pending in the given SVN Working Copy . | 168 | 14 |
23,066 | public static void cleanup ( File directory ) throws IOException { log . info ( "Cleaning SVN Working copy at " + directory ) ; CommandLine cmdLine = new CommandLine ( SVN_CMD ) ; cmdLine . addArgument ( "cleanup" ) ; addDefaultArguments ( cmdLine , null , null ) ; try ( InputStream result = ExecutionHelper . getCommandResult ( cmdLine , directory , 0 , 360000 ) ) { log . info ( "Svn-Cleanup reported:\n" + extractResult ( result ) ) ; } } | Run svn cleanup on the given working copy . | 121 | 10 |
23,067 | public static InputStream checkout ( String url , File directory , String user , String pwd ) throws IOException { if ( ! directory . exists ( ) && ! directory . mkdirs ( ) ) { throw new IOException ( "Could not create new working copy directory at " + directory ) ; } CommandLine cmdLine = new CommandLine ( SVN_CMD ) ; cmdLine . addArgument ( "co" ) ; addDefaultArguments ( cmdLine , user , pwd ) ; cmdLine . addArgument ( url ) ; cmdLine . addArgument ( directory . toString ( ) ) ; // allow up to two hour for new checkouts return ExecutionHelper . getCommandResult ( cmdLine , directory , - 1 , 2 * 60 * 60 * 1000 ) ; } | Performs a SVN Checkout of the given URL to the given directory | 165 | 15 |
23,068 | public static void copyBranch ( String base , String branch , long revision , String baseUrl ) throws IOException { log . info ( "Copying branch " + base + AT_REVISION + revision + " to branch " + branch ) ; CommandLine cmdLine = new CommandLine ( SVN_CMD ) ; cmdLine . addArgument ( "cp" ) ; addDefaultArguments ( cmdLine , null , null ) ; if ( revision > 0 ) { cmdLine . addArgument ( "-r" + revision ) ; } cmdLine . addArgument ( "-m" ) ; cmdLine . addArgument ( "Branch automatically created from " + base + ( revision > 0 ? AT_REVISION + revision : "" ) ) ; cmdLine . addArgument ( baseUrl + base ) ; cmdLine . addArgument ( baseUrl + branch ) ; /* svn copy -r123 http://svn.example.com/repos/calc/trunk \ http://svn.example.com/repos/calc/branches/my-calc-branch */ try ( InputStream result = ExecutionHelper . getCommandResult ( cmdLine , new File ( "." ) , 0 , 120000 ) ) { log . info ( "Svn-Copy reported:\n" + extractResult ( result ) ) ; } } | Make a branch by calling the svn cp operation . | 292 | 11 |
23,069 | public ConfigurationStore getStore ( ) throws ConfigException { if ( store != null ) { return store ; } String uriStr = getConfigUri ( ) ; if ( uriStr == null ) { getPfile ( ) ; String configPname = getConfigPname ( ) ; if ( configPname == null ) { throw new ConfigException ( "Either a uri or property name must be specified" ) ; } uriStr = pfile . getProperty ( configPname ) ; if ( uriStr == null ) { /* If configPname ends with ".confuri" we'll take the preceding segment as a possible directory */ if ( configPname . endsWith ( ".confuri" ) ) { final int lastDotpos = configPname . length ( ) - 8 ; final int pos = configPname . lastIndexOf ( ' ' , lastDotpos - 1 ) ; if ( pos > 0 ) { uriStr = configPname . substring ( pos + 1 , lastDotpos ) ; } } } if ( uriStr == null ) { throw new ConfigException ( "No property with name \"" + configPname + "\"" ) ; } } try { URI uri = new URI ( uriStr ) ; String scheme = uri . getScheme ( ) ; if ( scheme == null ) { // Possible non-absolute path String path = uri . getPath ( ) ; File f = new File ( path ) ; if ( ! f . isAbsolute ( ) && configBase != null ) { path = configBase + path ; } uri = new URI ( path ) ; scheme = uri . getScheme ( ) ; } if ( ( scheme == null ) || ( scheme . equals ( "file" ) ) ) { String path = uri . getPath ( ) ; if ( getPathSuffix ( ) != null ) { if ( ! path . endsWith ( File . separator ) ) { path += File . separator ; } path += getPathSuffix ( ) + File . separator ; } store = new ConfigurationFileStore ( path ) ; return store ; } throw new ConfigException ( "Unsupported ConfigurationStore: " + uri ) ; } catch ( URISyntaxException use ) { throw new ConfigException ( use ) ; } } | Get a ConfigurationStore based on the uri or property value . | 496 | 13 |
23,070 | protected String loadOnlyConfig ( final Class < T > cl ) { try { /* Load up the config */ ConfigurationStore cs = getStore ( ) ; List < String > configNames = cs . getConfigs ( ) ; if ( configNames . isEmpty ( ) ) { error ( "No configuration on path " + cs . getLocation ( ) ) ; return "No configuration on path " + cs . getLocation ( ) ; } if ( configNames . size ( ) != 1 ) { error ( "1 and only 1 configuration allowed" ) ; return "1 and only 1 configuration allowed" ; } String configName = configNames . iterator ( ) . next ( ) ; cfg = getConfigInfo ( cs , configName , cl ) ; if ( cfg == null ) { error ( "Unable to read configuration" ) ; return "Unable to read configuration" ; } setConfigName ( configName ) ; return null ; } catch ( Throwable t ) { error ( "Failed to load configuration: " + t . getLocalizedMessage ( ) ) ; error ( t ) ; return "failed" ; } } | Load the configuration if we only expect one and we don t care or know what it s called . | 236 | 20 |
23,071 | public static StorageConfiguration deserialize ( final File pFile ) throws TTIOException { try { FileReader fileReader = new FileReader ( new File ( pFile , Paths . ConfigBinary . getFile ( ) . getName ( ) ) ) ; JsonReader jsonReader = new JsonReader ( fileReader ) ; jsonReader . beginObject ( ) ; jsonReader . nextName ( ) ; File file = new File ( jsonReader . nextString ( ) ) ; jsonReader . endObject ( ) ; jsonReader . close ( ) ; fileReader . close ( ) ; return new StorageConfiguration ( file ) ; } catch ( IOException ioexc ) { throw new TTIOException ( ioexc ) ; } } | Generate a StorageConfiguration out of a file . | 151 | 10 |
23,072 | @ ConfInfo ( dontSave = true ) public String getProperty ( final Collection < String > col , final String name ) { String key = name + "=" ; for ( String p : col ) { if ( p . startsWith ( key ) ) { return p . substring ( key . length ( ) ) ; } } return null ; } | Get a property stored as a String name = val | 72 | 10 |
23,073 | public void removeProperty ( final Collection < String > col , final String name ) { try { String v = getProperty ( col , name ) ; if ( v == null ) { return ; } col . remove ( name + "=" + v ) ; } catch ( Throwable t ) { throw new RuntimeException ( t ) ; } } | Remove a property stored as a String name = val | 70 | 10 |
23,074 | @ SuppressWarnings ( "unchecked" ) public < L extends List > L setListProperty ( final L list , final String name , final String val ) { removeProperty ( list , name ) ; return addListProperty ( list , name , val ) ; } | Set a property | 57 | 3 |
23,075 | public void toXml ( final Writer wtr ) throws ConfigException { try { XmlEmit xml = new XmlEmit ( ) ; xml . addNs ( new NameSpace ( ns , "BW" ) , true ) ; xml . startEmit ( wtr ) ; dump ( xml , false ) ; xml . flush ( ) ; } catch ( ConfigException cfe ) { throw cfe ; } catch ( Throwable t ) { throw new ConfigException ( t ) ; } } | Output to a writer | 104 | 4 |
23,076 | public ConfigBase fromXml ( final InputStream is , final Class cl ) throws ConfigException { try { return fromXml ( parseXml ( is ) , cl ) ; } catch ( final ConfigException ce ) { throw ce ; } catch ( final Throwable t ) { throw new ConfigException ( t ) ; } } | XML root element must have type attribute if cl is null | 68 | 12 |
23,077 | public ConfigBase fromXml ( final Element rootEl , final Class cl ) throws ConfigException { try { final ConfigBase cb = ( ConfigBase ) getObject ( rootEl , cl ) ; if ( cb == null ) { // Can't do this return null ; } for ( final Element el : XmlUtil . getElementsArray ( rootEl ) ) { populate ( el , cb , null , null ) ; } return cb ; } catch ( final ConfigException ce ) { throw ce ; } catch ( final Throwable t ) { throw new ConfigException ( t ) ; } } | XML root element must have type attribute | 127 | 8 |
23,078 | public void setPath ( final String ideal , final String actual ) { synchronized ( transformers ) { pathMap . put ( ideal , actual ) ; } } | Set ideal to actual mapping . | 32 | 6 |
23,079 | public static void initLogging ( ) throws IOException { sendCommonsLogToJDKLog ( ) ; try ( InputStream resource = Thread . currentThread ( ) . getContextClassLoader ( ) . getResourceAsStream ( "logging.properties" ) ) { // apply configuration if ( resource != null ) { try { LogManager . getLogManager ( ) . readConfiguration ( resource ) ; } finally { resource . close ( ) ; } } // apply a default format to the log handlers here before throwing an exception further down Logger log = Logger . getLogger ( "" ) ; // NOSONAR - local logger used on purpose here for ( Handler handler : log . getHandlers ( ) ) { handler . setFormatter ( new DefaultFormatter ( ) ) ; } if ( resource == null ) { throw new IOException ( "Did not find a file 'logging.properties' in the classpath" ) ; } } } | Initialize Logging from a file logging . properties which needs to be found in the classpath . | 200 | 20 |
23,080 | public void add ( final ITreeData paramNodeX , final ITreeData paramNodeY ) throws TTIOException { mMapping . put ( paramNodeX , paramNodeY ) ; mReverseMapping . put ( paramNodeY , paramNodeX ) ; updateSubtreeMap ( paramNodeX , mRtxNew ) ; updateSubtreeMap ( paramNodeY , mRtxOld ) ; } | Adds the matching x - > y . | 88 | 8 |
23,081 | public long containedChildren ( final ITreeData paramNodeX , final ITreeData paramNodeY ) throws TTIOException { assert paramNodeX != null ; assert paramNodeY != null ; long retVal = 0 ; mRtxOld . moveTo ( paramNodeX . getDataKey ( ) ) ; for ( final AbsAxis axis = new DescendantAxis ( mRtxOld , true ) ; axis . hasNext ( ) ; axis . next ( ) ) { retVal += mIsInSubtree . get ( paramNodeY , partner ( mRtxOld . getNode ( ) ) ) ? 1 : 0 ; } return retVal ; } | Counts the number of child nodes in the subtrees of x and y that are also in the matching . | 141 | 22 |
23,082 | public static List < String > fixPath ( final String path ) throws ServletException { if ( path == null ) { return null ; } String decoded ; try { decoded = URLDecoder . decode ( path , "UTF8" ) ; } catch ( Throwable t ) { throw new ServletException ( "bad path: " + path ) ; } if ( decoded == null ) { return ( null ) ; } /** Make any backslashes into forward slashes. */ if ( decoded . indexOf ( ' ' ) >= 0 ) { decoded = decoded . replace ( ' ' , ' ' ) ; } /** Ensure a leading '/' */ if ( ! decoded . startsWith ( "/" ) ) { decoded = "/" + decoded ; } /** Remove all instances of '//'. */ while ( decoded . contains ( "//" ) ) { decoded = decoded . replaceAll ( "//" , "/" ) ; } /** Somewhere we may have /./ or /../ */ final StringTokenizer st = new StringTokenizer ( decoded , "/" ) ; ArrayList < String > al = new ArrayList < String > ( ) ; while ( st . hasMoreTokens ( ) ) { String s = st . nextToken ( ) ; if ( s . equals ( "." ) ) { // ignore } else if ( s . equals ( ".." ) ) { // Back up 1 if ( al . size ( ) == 0 ) { // back too far return null ; } al . remove ( al . size ( ) - 1 ) ; } else { al . add ( s ) ; } } return al ; } | Return a path broken into its elements after . and .. are removed . If the parameter path attempts to go above the root we return null . | 349 | 28 |
23,083 | protected Object readJson ( final InputStream is , final Class cl , final HttpServletResponse resp ) throws ServletException { if ( is == null ) { return null ; } try { return getMapper ( ) . readValue ( is , cl ) ; } catch ( Throwable t ) { resp . setStatus ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR ) ; if ( debug ( ) ) { error ( t ) ; } throw new ServletException ( t ) ; } } | Parse the request body and return the object . | 111 | 10 |
23,084 | public static String timeToReadable ( long millis , String suffix ) { StringBuilder builder = new StringBuilder ( ) ; boolean haveDays = false ; if ( millis > ONE_DAY ) { millis = handleTime ( builder , millis , ONE_DAY , "day" , "s" ) ; haveDays = true ; } boolean haveHours = false ; if ( millis >= ONE_HOUR ) { millis = handleTime ( builder , millis , ONE_HOUR , "h" , "" ) ; haveHours = true ; } if ( ( ! haveDays || ! haveHours ) && millis >= ONE_MINUTE ) { millis = handleTime ( builder , millis , ONE_MINUTE , "min" , "" ) ; } if ( ! haveDays && ! haveHours && millis >= ONE_SECOND ) { /*millis =*/ handleTime ( builder , millis , ONE_SECOND , "s" , "" ) ; } if ( builder . length ( ) > 0 ) { // cut off trailing ", " builder . setLength ( builder . length ( ) - 2 ) ; builder . append ( suffix ) ; } return builder . toString ( ) ; } | Format the given number of milliseconds as readable string optionally appending a suffix . | 256 | 15 |
23,085 | public static synchronized XMLEventReader createFileReader ( final File paramFile ) throws IOException , XMLStreamException { final XMLInputFactory factory = XMLInputFactory . newInstance ( ) ; factory . setProperty ( XMLInputFactory . SUPPORT_DTD , false ) ; final InputStream in = new FileInputStream ( paramFile ) ; return factory . createXMLEventReader ( in ) ; } | Create a new StAX reader on a file . | 84 | 10 |
23,086 | public static synchronized XMLEventReader createStringReader ( final String paramString ) throws IOException , XMLStreamException { final XMLInputFactory factory = XMLInputFactory . newInstance ( ) ; factory . setProperty ( XMLInputFactory . SUPPORT_DTD , false ) ; final InputStream in = new ByteArrayInputStream ( paramString . getBytes ( ) ) ; return factory . createXMLEventReader ( in ) ; } | Create a new StAX reader on a string . | 90 | 10 |
23,087 | public String simpleGet ( String url ) throws IOException { final AtomicReference < String > str = new AtomicReference <> ( ) ; simpleGetInternal ( url , inputStream -> { try { str . set ( IOUtils . toString ( inputStream , "UTF-8" ) ) ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } } , null ) ; return str . get ( ) ; } | Perform a simple get - operation and return the resulting String . | 94 | 13 |
23,088 | public byte [ ] simpleGetBytes ( String url ) throws IOException { final AtomicReference < byte [ ] > bytes = new AtomicReference <> ( ) ; simpleGetInternal ( url , inputStream -> { try { bytes . set ( IOUtils . toByteArray ( inputStream ) ) ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } } , null ) ; return bytes . get ( ) ; } | Perform a simple get - operation and return the resulting byte - array . | 94 | 15 |
23,089 | public void simpleGet ( String url , Consumer < InputStream > consumer ) throws IOException { simpleGetInternal ( url , consumer , null ) ; } | Perform a simple get - operation and passes the resulting InputStream to the given Consumer | 31 | 17 |
23,090 | public static String retrieveData ( String url , String user , String password , int timeoutMs ) throws IOException { try ( HttpClientWrapper wrapper = new HttpClientWrapper ( user , password , timeoutMs ) ) { return wrapper . simpleGet ( url ) ; } } | Small helper method to simply query the URL without password and return the resulting data . | 59 | 16 |
23,091 | public static HttpEntity checkAndFetch ( HttpResponse response , String url ) throws IOException { int statusCode = response . getStatusLine ( ) . getStatusCode ( ) ; if ( statusCode > 206 ) { String msg = "Had HTTP StatusCode " + statusCode + " for request: " + url + ", response: " + response . getStatusLine ( ) . getReasonPhrase ( ) + "\n" + StringUtils . abbreviate ( IOUtils . toString ( response . getEntity ( ) . getContent ( ) , "UTF-8" ) , 1024 ) ; log . warning ( msg ) ; throw new IOException ( msg ) ; } return response . getEntity ( ) ; } | Helper method to check the status code of the response and throw an IOException if it is an error or moved state . | 155 | 24 |
23,092 | public void createResource ( final InputStream inputStream , final String resourceName ) throws JaxRxException { synchronized ( resourceName ) { if ( inputStream == null ) { throw new JaxRxException ( 400 , "Bad user request" ) ; } else { try { shred ( inputStream , resourceName ) ; } catch ( final TTException exce ) { throw new JaxRxException ( exce ) ; } } } } | This method is responsible to create a new database . | 92 | 10 |
23,093 | public void add ( final InputStream input , final String resource ) throws JaxRxException { synchronized ( resource ) { try { shred ( input , resource ) ; } catch ( final TTException exce ) { throw new JaxRxException ( exce ) ; } } } | This method is responsible to add a new XML document to a collection . | 57 | 14 |
23,094 | public void deleteResource ( final String resourceName ) throws WebApplicationException { synchronized ( resourceName ) { try { mDatabase . truncateResource ( new SessionConfiguration ( resourceName , null ) ) ; } catch ( TTException e ) { throw new WebApplicationException ( e ) ; } } } | This method is responsible to delete an existing database . | 61 | 10 |
23,095 | public long getLastRevision ( final String resourceName ) throws JaxRxException , TTException { long lastRevision ; if ( mDatabase . existsResource ( resourceName ) ) { ISession session = null ; try { session = mDatabase . getSession ( new SessionConfiguration ( resourceName , StandardSettings . KEY ) ) ; lastRevision = session . getMostRecentVersion ( ) ; } catch ( final Exception globExcep ) { throw new JaxRxException ( globExcep ) ; } finally { session . close ( ) ; } } else { throw new JaxRxException ( 404 , "Resource not found" ) ; } return lastRevision ; } | This method reads the existing database and offers the last revision id of the database | 145 | 15 |
23,096 | private void serializIt ( final String resource , final Long revision , final OutputStream output , final boolean nodeid ) throws JaxRxException , TTException { // Connection to treetank, creating a session ISession session = null ; // INodeReadTrx rtx = null; try { session = mDatabase . getSession ( new SessionConfiguration ( resource , StandardSettings . KEY ) ) ; // and creating a transaction // if (revision == null) { // rtx = session.beginReadTransaction(); // } else { // rtx = session.beginReadTransaction(revision); // } final XMLSerializerBuilder builder ; if ( revision == null ) builder = new XMLSerializerBuilder ( session , output ) ; else builder = new XMLSerializerBuilder ( session , output , revision ) ; builder . setREST ( nodeid ) ; builder . setID ( nodeid ) ; builder . setDeclaration ( false ) ; final XMLSerializer serializer = builder . build ( ) ; serializer . call ( ) ; } catch ( final Exception exce ) { throw new JaxRxException ( exce ) ; } finally { // closing the treetank storage WorkerHelper . closeRTX ( null , session ) ; } } | The XML serializer to a given tnk file . | 260 | 12 |
23,097 | public void revertToRevision ( final String resourceName , final long backToRevision ) throws JaxRxException , TTException { ISession session = null ; INodeWriteTrx wtx = null ; boolean abort = false ; try { session = mDatabase . getSession ( new SessionConfiguration ( resourceName , StandardSettings . KEY ) ) ; wtx = new NodeWriteTrx ( session , session . beginBucketWtx ( ) , HashKind . Rolling ) ; wtx . revertTo ( backToRevision ) ; wtx . commit ( ) ; } catch ( final TTException exce ) { abort = true ; throw new JaxRxException ( exce ) ; } finally { WorkerHelper . closeWTX ( abort , wtx , session ) ; } } | This method reverts the latest revision data to the requested . | 164 | 12 |
23,098 | private String discover ( final String url ) throws TimezonesException { /* For the moment we'll try to find it via .well-known. We may have to * use DNS SRV lookups */ // String domain = hi.getHostname(); // int lpos = domain.lastIndexOf("."); //int lpos2 = domain.lastIndexOf(".", lpos - 1); // if (lpos2 > 0) { // domain = domain.substring(lpos2 + 1); //} String realUrl ; try { /* See if it's a real url */ new URL ( url ) ; realUrl = url ; } catch ( final Throwable t ) { realUrl = "https://" + url + "/.well-known/timezone" ; } for ( int redirects = 0 ; redirects < 10 ; redirects ++ ) { try ( CloseableHttpResponse hresp = doCall ( realUrl , "capabilities" , null , null ) ) { if ( ( status == HttpServletResponse . SC_MOVED_PERMANENTLY ) || ( status == HttpServletResponse . SC_MOVED_TEMPORARILY ) || ( status == HttpServletResponse . SC_TEMPORARY_REDIRECT ) ) { //boolean permanent = rcode == HttpServletResponse.SC_MOVED_PERMANENTLY; final String newLoc = HttpUtil . getFirstHeaderValue ( hresp , "location" ) ; if ( newLoc != null ) { if ( debug ( ) ) { debug ( "Got redirected to " + newLoc + " from " + url ) ; } final int qpos = newLoc . indexOf ( "?" ) ; if ( qpos < 0 ) { realUrl = newLoc ; } else { realUrl = newLoc . substring ( 0 , qpos ) ; } // Try again continue ; } } if ( status != HttpServletResponse . SC_OK ) { // The response is invalid and did not provide the new location for // the resource. Report an error or possibly handle the response // like a 404 Not Found error. error ( "================================================" ) ; error ( "================================================" ) ; error ( "================================================" ) ; error ( "Got response " + status + ", from " + realUrl ) ; error ( "================================================" ) ; error ( "================================================" ) ; error ( "================================================" ) ; throw new TimezonesException ( TimezonesException . noPrimary , "Got response " + status + ", from " + realUrl ) ; } /* Should have a capabilities record. */ try { capabilities = om . readValue ( hresp . getEntity ( ) . getContent ( ) , CapabilitiesType . class ) ; } catch ( final Throwable t ) { // Bad data - we'll just go with the url for the moment? error ( t ) ; } return realUrl ; } catch ( final TimezonesException tze ) { throw tze ; } catch ( final Throwable t ) { if ( debug ( ) ) { error ( t ) ; } throw new TimezonesException ( t ) ; } } if ( debug ( ) ) { error ( "Too many redirects: Got response " + status + ", from " + realUrl ) ; } throw new TimezonesException ( "Too many redirects on " + realUrl ) ; } | See if we have a url for the service . If not discover the real one . | 728 | 17 |
23,099 | @ Override protected void emitEndElement ( final INodeReadTrx paramRTX ) { try { indent ( ) ; mOut . write ( ECharsForSerializing . OPEN_SLASH . getBytes ( ) ) ; mOut . write ( paramRTX . nameForKey ( ( ( ITreeNameData ) paramRTX . getNode ( ) ) . getNameKey ( ) ) . getBytes ( ) ) ; mOut . write ( ECharsForSerializing . CLOSE . getBytes ( ) ) ; if ( mIndent ) { mOut . write ( ECharsForSerializing . NEWLINE . getBytes ( ) ) ; } } catch ( final IOException exc ) { exc . printStackTrace ( ) ; } } | Emit end element . | 162 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.