idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
24,800
public boolean hasContactToAtom ( Point3d [ ] iAtoms , Point3d [ ] jAtoms , Point3d query , double cutoff ) { for ( int i : iIndices ) { double distance = iAtoms [ i ] . distance ( query ) ; if ( distance < cutoff ) return true ; } if ( jAtoms != null ) { for ( int i : jIndices ) { double distance = jAtoms [ i ] . distance ( query ) ; if ( distance < cutoff ) return true ; } } return false ; }
Tests whether any atom in this cell has a contact with the specified query atom
24,801
public static void showMultipleAligmentPanel ( MultipleAlignment multAln , AbstractAlignmentJmol jmol ) throws StructureException { MultipleAligPanel me = new MultipleAligPanel ( multAln , jmol ) ; JFrame frame = new JFrame ( ) ; frame . setDefaultCloseOperation ( JFrame . DISPOSE_ON_CLOSE ) ; frame . setTitle ( jmol . getTitle ( ) ) ; me . setPreferredSize ( new Dimension ( me . getCoordManager ( ) . getPreferredWidth ( ) , me . getCoordManager ( ) . getPreferredHeight ( ) ) ) ; JMenuBar menu = MenuCreator . getAlignmentPanelMenu ( frame , me , null , multAln ) ; frame . setJMenuBar ( menu ) ; JScrollPane scroll = new JScrollPane ( me ) ; scroll . setAutoscrolls ( true ) ; MultipleStatusDisplay status = new MultipleStatusDisplay ( me ) ; me . addAlignmentPositionListener ( status ) ; Box vBox = Box . createVerticalBox ( ) ; vBox . add ( scroll ) ; vBox . add ( status ) ; frame . getContentPane ( ) . add ( vBox ) ; frame . pack ( ) ; frame . setVisible ( true ) ; frame . addWindowListener ( me ) ; frame . addWindowListener ( status ) ; }
Creates a new Frame with the MultipleAlignment Sequence Panel . The panel can communicate with the Jmol 3D visualization by selecting the aligned residues of every structure .
24,802
public static MultipleAlignmentJmol display ( MultipleAlignment multAln ) throws StructureException { List < Atom [ ] > rotatedAtoms = MultipleAlignmentDisplay . getRotatedAtoms ( multAln ) ; MultipleAlignmentJmol jmol = new MultipleAlignmentJmol ( multAln , rotatedAtoms ) ; jmol . setTitle ( jmol . getStructure ( ) . getPDBHeader ( ) . getTitle ( ) ) ; return jmol ; }
Display a MultipleAlignment with a JmolPanel . New structures are downloaded if they were not cached in the alignment and they are entirely transformed here with the superposition information in the Multiple Alignment .
24,803
public static List < Domain > suggestDomains ( Structure s ) throws StructureException { Atom [ ] ca = StructureTools . getRepresentativeAtomArray ( s ) ; return suggestDomains ( ca ) ; }
Suggest domains for a protein structure
24,804
public static List < Domain > suggestDomains ( Atom [ ] ca ) throws StructureException { GetDistanceMatrix distMaxCalculator = new GetDistanceMatrix ( ) ; PDPDistanceMatrix pdpMatrix = distMaxCalculator . getDistanceMatrix ( ca ) ; Domain dom = new Domain ( ) ; Chain c = ca [ 0 ] . getGroup ( ) . getChain ( ) ; dom . setId ( "D" + c . getStructure ( ) . getPDBCode ( ) + c . getId ( ) + "1" ) ; dom . setSize ( ca . length ) ; dom . setNseg ( 1 ) ; dom . getSegmentAtPos ( 0 ) . setFrom ( 0 ) ; dom . getSegmentAtPos ( 0 ) . setTo ( ca . length - 1 ) ; CutSites cutSites = new CutSites ( ) ; CutDomain cutDomain = new CutDomain ( ca , pdpMatrix ) ; cutDomain . cutDomain ( dom , cutSites , pdpMatrix ) ; List < Domain > domains = cutDomain . getDomains ( ) ; domains = ClusterDomains . cluster ( domains , pdpMatrix ) ; ShortSegmentRemover . cleanup ( domains ) ; return domains ; }
Suggest domains for a set of Calpha atoms
24,805
public static void showStructure ( Structure structure ) throws ClassNotFoundException , NoSuchMethodException , InvocationTargetException , IllegalAccessException , InstantiationException { Class < ? > structureAlignmentJmol = Class . forName ( strucAligJmol ) ; Object strucAligJ = structureAlignmentJmol . newInstance ( ) ; Method setS = structureAlignmentJmol . getMethod ( "setStructure" , new Class [ ] { Structure . class } ) ; setS . invoke ( strucAligJ , structure ) ; }
Shows a structure in Jmol
24,806
public void notifyShutdown ( ) { if ( pdpprovider != null ) { if ( pdpprovider instanceof RemotePDPProvider ) { RemotePDPProvider remotePDP = ( RemotePDPProvider ) pdpprovider ; remotePDP . flushCache ( ) ; } } ScopDatabase scopInstallation = ScopFactory . getSCOP ( ) ; if ( scopInstallation != null ) { if ( scopInstallation instanceof CachedRemoteScopInstallation ) { CachedRemoteScopInstallation cacheScop = ( CachedRemoteScopInstallation ) scopInstallation ; cacheScop . flushCache ( ) ; } } }
Send a signal to the cache that the system is shutting down . Notifies underlying SerializableCache instances to flush themselves ...
24,807
public Structure getStructureForPdbId ( String pdbId ) throws IOException , StructureException { if ( pdbId == null ) return null ; if ( pdbId . length ( ) != 4 ) { throw new StructureException ( "Unrecognized PDB ID: " + pdbId ) ; } while ( checkLoading ( pdbId ) ) { try { Thread . sleep ( 100 ) ; } catch ( InterruptedException e ) { logger . error ( e . getMessage ( ) ) ; } } Structure s ; if ( useMmtf ) { logger . debug ( "loading from mmtf" ) ; s = loadStructureFromMmtfByPdbId ( pdbId ) ; } else if ( useMmCif ) { logger . debug ( "loading from mmcif" ) ; s = loadStructureFromCifByPdbId ( pdbId ) ; } else { logger . debug ( "loading from pdb" ) ; s = loadStructureFromPdbByPdbId ( pdbId ) ; } return s ; }
Loads a structure directly by PDB ID
24,808
private static JFrame showDotPlotJFrame ( AFPChain afpChain ) { DotPlotPanel dotplot = new DotPlotPanel ( afpChain ) ; String title = String . format ( "Dot plot of %s vs. %s" , afpChain . getName1 ( ) , afpChain . getName2 ( ) ) ; JFrame frame = new JFrame ( title ) ; frame . addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent e ) { JFrame f = ( JFrame ) e . getSource ( ) ; f . setVisible ( false ) ; f . dispose ( ) ; } } ) ; frame . getContentPane ( ) . add ( dotplot ) ; frame . pack ( ) ; frame . setVisible ( true ) ; return frame ; }
Helper function to create and display a JFrame with a single DotPlotPanel
24,809
public void toPDB ( StringBuffer buf ) { buf . append ( "SSBOND " ) ; buf . append ( String . format ( "%3d" , serNum ) ) ; buf . append ( String . format ( " CYS %s %4s%1s " , chainID1 , resnum1 , insCode1 ) ) ; buf . append ( String . format ( " CYS %s %4s%1s " , chainID2 , resnum2 , insCode2 ) ) ; }
Append the PDB representation of this SSBOND to the provided StringBuffer
24,810
public Double getSurvivalTimePercentile ( String group , double percentile ) { StrataInfo si = sfi . getStrataInfoHashMap ( ) . get ( group ) ; ArrayList < Double > percentage = si . getSurv ( ) ; Integer percentileIndex = null ; for ( int i = 0 ; i < percentage . size ( ) ; i ++ ) { if ( percentage . get ( i ) == percentile ) { if ( i + 1 < percentage . size ( ) ) { percentileIndex = i + 1 ; } break ; } else if ( percentage . get ( i ) < percentile ) { percentileIndex = i ; break ; } } if ( percentileIndex != null ) { return si . getTime ( ) . get ( percentileIndex ) ; } else { return null ; } }
To get the median percentile for a particular group pass the value of . 50 .
24,811
public void setSurvivalData ( ArrayList < String > title , SurvFitInfo sfi , Double userSetMaxTime ) { this . title = title ; LinkedHashMap < String , StrataInfo > strataInfoHashMap = sfi . getStrataInfoHashMap ( ) ; Double mTime = null ; for ( StrataInfo si : strataInfoHashMap . values ( ) ) { for ( double t : si . getTime ( ) ) { if ( mTime == null || t > mTime ) { mTime = t ; } } } int evenCheck = Math . round ( mTime . floatValue ( ) ) ; if ( evenCheck % 2 == 1 ) { evenCheck = evenCheck + 1 ; } this . maxTime = evenCheck ; if ( userSetMaxTime != null && userSetMaxTime > maxTime ) { this . maxTime = userSetMaxTime ; } this . sfi = sfi ; if ( sfi . getStrataInfoHashMap ( ) . size ( ) == 1 ) { return ; } this . repaint ( ) ; }
Allow setting of points in the figure where weighted correction has been done and percentage has already been calculated .
24,812
public void setSurvivalData ( ArrayList < String > title , LinkedHashMap < String , ArrayList < CensorStatus > > survivalData , Boolean useWeighted ) throws Exception { this . setSurvivalData ( title , survivalData , null , useWeighted ) ; }
The data will set the max time which will result in off time points for tick marks
24,813
public void saveSurvivalData ( String fileName ) throws Exception { FileWriter fw = new FileWriter ( fileName ) ; fw . write ( "index\tTIME\tSTATUS\tGROUP\r\n" ) ; int index = 0 ; for ( String group : survivalData . keySet ( ) ) { ArrayList < CensorStatus > sd = survivalData . get ( group ) ; for ( CensorStatus cs : sd ) { String line = index + "\t" + cs . time + "\t" + cs . censored + "\t" + cs . group + "\r\n" ; index ++ ; fw . write ( line ) ; } } fw . close ( ) ; }
Save data from survival curve to text file
24,814
private int getTimeX ( double value ) { double d = left + ( ( ( right - left ) * value ) / ( maxTime - minTime ) ) ; return ( int ) d ; }
Get the X coordinate based on a time value
24,815
private int getPercentageY ( double value ) { value = 1.0 - value ; double d = top + ( ( ( bottom - top ) * value ) / ( maxPercentage - minPercentage ) ) ; return ( int ) d ; }
Get the Y coordinate based on percent value 0 . 0 - 1 . 0
24,816
public void savePNGKMNumRisk ( String fileName ) { if ( fileName . startsWith ( "null" ) || fileName . startsWith ( "Null" ) || fileName . startsWith ( "NULL" ) ) { return ; } this . fileName = fileName ; NumbersAtRiskPanel numbersAtRiskPanel = new NumbersAtRiskPanel ( ) ; numbersAtRiskPanel . setKaplanMeierFigure ( this ) ; numbersAtRiskPanel . setSize ( this . getWidth ( ) , numbersAtRiskPanel . getHeight ( ) ) ; BufferedImage imageKM = new BufferedImage ( this . getWidth ( ) , this . getHeight ( ) , BufferedImage . TYPE_INT_RGB ) ; Graphics2D graphics2D = imageKM . createGraphics ( ) ; this . paint ( graphics2D ) ; BufferedImage imageNumRisk = new BufferedImage ( numbersAtRiskPanel . getWidth ( ) , numbersAtRiskPanel . getHeight ( ) , BufferedImage . TYPE_INT_RGB ) ; Graphics2D graphics2DNumRisk = imageNumRisk . createGraphics ( ) ; numbersAtRiskPanel . paint ( graphics2DNumRisk ) ; BufferedImage image = new BufferedImage ( numbersAtRiskPanel . getWidth ( ) , numbersAtRiskPanel . getHeight ( ) + this . getHeight ( ) , BufferedImage . TYPE_INT_RGB ) ; Graphics2D g = image . createGraphics ( ) ; g . drawImage ( imageKM , 0 , 0 , null ) ; g . drawImage ( imageNumRisk , 0 , this . getHeight ( ) , null ) ; try { ImageIO . write ( image , "png" , new File ( fileName ) ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } }
Combine the KM and Num risk into one image
24,817
public BatchStubRunner batchStubRunner ( ) { StubRunnerOptionsBuilder builder = builder ( ) ; if ( this . props . getProxyHost ( ) != null ) { builder . withProxy ( this . props . getProxyHost ( ) , this . props . getProxyPort ( ) ) ; } StubRunnerOptions stubRunnerOptions = builder . build ( ) ; BatchStubRunner batchStubRunner = new BatchStubRunnerFactory ( stubRunnerOptions , this . provider . get ( stubRunnerOptions ) , this . contractVerifierMessaging != null ? this . contractVerifierMessaging : new NoOpStubMessages ( ) ) . buildBatchStubRunner ( ) ; RunningStubs runningStubs = batchStubRunner . runStubs ( ) ; registerPort ( runningStubs ) ; return batchStubRunner ; }
Bean that initializes stub runners runs them and on shutdown closes them . Upon its instantiation JAR with stubs is downloaded and unpacked to a temporary folder and WireMock server are started for each of those stubs
24,818
public void updateContractProject ( String projectName , Path rootStubsFolder ) { File clonedRepo = this . gitContractsRepo . clonedRepo ( this . stubRunnerOptions . stubRepositoryRoot ) ; GitStubDownloaderProperties properties = new GitStubDownloaderProperties ( this . stubRunnerOptions . stubRepositoryRoot , this . stubRunnerOptions ) ; copyStubs ( projectName , rootStubsFolder , clonedRepo ) ; GitRepo gitRepo = new GitRepo ( clonedRepo , properties ) ; String msg = StubRunnerPropertyUtils . getProperty ( this . stubRunnerOptions . getProperties ( ) , GIT_COMMIT_MESSAGE ) ; GitRepo . CommitResult commit = gitRepo . commit ( clonedRepo , commitMessage ( projectName , msg ) ) ; if ( commit == GitRepo . CommitResult . EMPTY ) { log . info ( "There were no changes to commit. Won't push the changes" ) ; return ; } String attempts = StubRunnerPropertyUtils . getProperty ( this . stubRunnerOptions . getProperties ( ) , GIT_ATTEMPTS_NO_PROP ) ; int intAttempts = StringUtils . hasText ( attempts ) ? Integer . parseInt ( attempts ) : DEFAULT_ATTEMPTS_NO ; String wait = StubRunnerPropertyUtils . getProperty ( this . stubRunnerOptions . getProperties ( ) , GIT_WAIT_BETWEEN_ATTEMPTS ) ; long longWait = StringUtils . hasText ( wait ) ? Long . parseLong ( wait ) : DEFAULT_WAIT_BETWEEN_ATTEMPTS ; tryToPushCurrentBranch ( clonedRepo , gitRepo , intAttempts , longWait ) ; }
Merges the folder with stubs with the project containing contracts .
24,819
static int getRandomInt ( int min , int max , Random random ) { int maxForRandom = max - min + 1 ; return random . nextInt ( maxForRandom ) + min ; }
Generates a random number within the given bounds .
24,820
public String generate ( ) { StringBuilder builder = new StringBuilder ( ) ; int counter = 0 ; generate ( builder , this . automaton . getInitialState ( ) , counter ) ; return builder . toString ( ) ; }
Generates a random String that is guaranteed to match the regular expression passed to the constructor .
24,821
private static String fromSystemPropOrEnv ( String prop ) { String resolvedProp = System . getProperty ( prop ) ; if ( StringUtils . hasText ( resolvedProp ) ) { return resolvedProp ; } return System . getenv ( prop ) ; }
system prop takes precedence over env var
24,822
public byte [ ] getBody ( ) { if ( this . cachedBody == null || this . cachedBody . length == 0 ) { try { if ( this . request instanceof MockHttpServletRequest ) { this . cachedBody = ( ( MockHttpServletRequest ) this . request ) . getContentAsByteArray ( ) ; return this . cachedBody ; } byte [ ] body = toByteArray ( this . request . getInputStream ( ) ) ; boolean isGzipped = hasGzipEncoding ( ) || Gzip . isGzipped ( body ) ; this . cachedBody = isGzipped ? Gzip . unGzip ( body ) : body ; } catch ( IOException ioe ) { throw new RuntimeException ( ioe ) ; } } return this . cachedBody ; }
Something s wrong with reading the body from request
24,823
File cloneProject ( URI projectUri ) { try { log . info ( "Cloning repo from [" + projectUri + "] to [" + this . basedir + "]" ) ; Git git = cloneToBasedir ( projectUri , this . basedir ) ; if ( git != null ) { git . close ( ) ; } File clonedRepo = git . getRepository ( ) . getWorkTree ( ) ; log . info ( "Cloned repo to [" + clonedRepo + "]" ) ; return clonedRepo ; } catch ( Exception e ) { throw new IllegalStateException ( "Exception occurred while cloning repo" , e ) ; } }
Clones the project .
24,824
void checkout ( File project , String branch ) { try { String currentBranch = currentBranch ( project ) ; if ( currentBranch . equals ( branch ) ) { log . info ( "Won't check out the same branch. Skipping" ) ; return ; } log . info ( "Checking out branch [" + branch + "]" ) ; checkoutBranch ( project , branch ) ; log . info ( "Successfully checked out the branch [" + branch + "]" ) ; } catch ( Exception e ) { throw new IllegalStateException ( e ) ; } }
Checks out a branch for a project .
24,825
void pull ( File project ) { try { try ( Git git = this . gitFactory . open ( project ) ) { PullCommand command = this . gitFactory . pull ( git ) ; command . setRebase ( true ) . call ( ) ; } } catch ( Exception e ) { throw new IllegalStateException ( e ) ; } }
Pulls changes for the project .
24,826
CommitResult commit ( File project , String message ) { try ( Git git = this . gitFactory . open ( file ( project ) ) ) { git . add ( ) . addFilepattern ( "." ) . call ( ) ; git . commit ( ) . setAllowEmpty ( false ) . setMessage ( message ) . call ( ) ; log . info ( "Commited successfully with message [" + message + "]" ) ; return CommitResult . SUCCESSFUL ; } catch ( EmptyCommitException e ) { log . info ( "There were no changes detected. Will not commit an empty commit" ) ; return CommitResult . EMPTY ; } catch ( Exception e ) { throw new IllegalStateException ( e ) ; } }
Performs a commit .
24,827
void pushCurrentBranch ( File project ) { try ( Git git = this . gitFactory . open ( file ( project ) ) ) { this . gitFactory . push ( git ) . call ( ) ; } catch ( Exception e ) { throw new IllegalStateException ( e ) ; } }
Pushes the commits od current branch .
24,828
protected Map < String , Helper > helpers ( ) { Map < String , Helper > helpers = new HashMap < > ( ) ; helpers . put ( HandlebarsJsonPathHelper . NAME , new HandlebarsJsonPathHelper ( ) ) ; helpers . put ( HandlebarsEscapeHelper . NAME , new HandlebarsEscapeHelper ( ) ) ; return helpers ; }
Override this if you want to register your own helpers .
24,829
public static byte [ ] fileToBytes ( Object testClass , String relativePath ) { try { URL url = testClass . getClass ( ) . getResource ( relativePath ) ; if ( url == null ) { throw new FileNotFoundException ( relativePath ) ; } return Files . readAllBytes ( Paths . get ( url . toURI ( ) ) ) ; } catch ( IOException | URISyntaxException ex ) { throw new IllegalStateException ( ex ) ; } }
Helper method to convert a file to bytes .
24,830
public static String valueFromXPath ( Document parsedXml , String path ) { XPath xPath = XPathFactory . newInstance ( ) . newXPath ( ) ; try { return xPath . evaluate ( path , parsedXml . getDocumentElement ( ) ) ; } catch ( XPathExpressionException exception ) { LOG . error ( "Incorrect xpath provided: " + path , exception ) ; throw new IllegalArgumentException ( ) ; } }
Helper method to retrieve XML node value with provided xPath .
24,831
public File unpackedDownloadedContracts ( ContractVerifierConfigProperties config ) { File contractsDirectory = unpackAndDownloadContracts ( ) ; updatePropertiesWithInclusion ( contractsDirectory , config ) ; return contractsDirectory ; }
Downloads JAR containing all the contracts . Plugin configuration gets updated with the inclusion pattern for the downloaded contracts . The JAR with the contracts contains all the contracts for all the projects . We re interested only in its subset .
24,832
public CollectionAssert allElementsMatch ( String regex ) { isNotNull ( ) ; isNotEmpty ( ) ; for ( Object anActual : this . actual ) { if ( anActual == null ) { failWithMessageRelatedToRegex ( regex , anActual ) ; } String value = anActual . toString ( ) ; if ( ! value . matches ( regex ) ) { failWithMessageRelatedToRegex ( regex , value ) ; } } return this ; }
Asserts all elements of the collection whether they match a regular expression .
24,833
public CollectionAssert hasFlattenedSizeGreaterThanOrEqualTo ( int size ) { isNotNull ( ) ; int flattenedSize = flattenedSize ( 0 , this . actual ) ; if ( ! ( flattenedSize >= size ) ) { failWithMessage ( "The flattened size <%s> is not greater or equal to <%s>" , flattenedSize , size ) ; } return this ; }
Flattens the collection and checks whether size is greater than or equal to the provided value .
24,834
public CollectionAssert hasFlattenedSizeLessThanOrEqualTo ( int size ) { isNotNull ( ) ; int flattenedSize = flattenedSize ( 0 , this . actual ) ; if ( ! ( flattenedSize <= size ) ) { failWithMessage ( "The flattened size <%s> is not less or equal to <%s>" , flattenedSize , size ) ; } return this ; }
Flattens the collection and checks whether size is less than or equal to the provided value .
24,835
public CollectionAssert hasFlattenedSizeBetween ( int lowerBound , int higherBound ) { isNotNull ( ) ; int flattenedSize = flattenedSize ( 0 , this . actual ) ; if ( ! ( flattenedSize >= lowerBound && flattenedSize <= higherBound ) ) { failWithMessage ( "The flattened size <%s> is not between <%s> and <%s>" , flattenedSize , lowerBound , higherBound ) ; } return this ; }
Flattens the collection and checks whether size is between the provided value .
24,836
public CollectionAssert hasSizeGreaterThanOrEqualTo ( int size ) { isNotNull ( ) ; int actualSize = size ( this . actual ) ; if ( ! ( actualSize >= size ) ) { failWithMessage ( "The size <%s> is not greater or equal to <%s>" , actualSize , size ) ; } return this ; }
Checks whether size is greater than or equal to the provided value .
24,837
public CollectionAssert hasSizeLessThanOrEqualTo ( int size ) { isNotNull ( ) ; int actualSize = size ( this . actual ) ; if ( ! ( actualSize <= size ) ) { failWithMessage ( "The size <%s> is not less or equal to <%s>" , actualSize , size ) ; } return this ; }
Checks whether size is less than or equal to the provided value .
24,838
public CollectionAssert hasSizeBetween ( int lowerBound , int higherBound ) { isNotNull ( ) ; int size = size ( this . actual ) ; if ( ! ( size >= lowerBound && size <= higherBound ) ) { failWithMessage ( "The size <%s> is not between <%s> and <%s>" , size , lowerBound , higherBound ) ; } return this ; }
Checks whether size is between the provided value .
24,839
public static List < StubConfiguration > fromString ( Collection < String > collection , String defaultClassifier ) { List < StubConfiguration > stubs = new ArrayList < > ( ) ; for ( String config : collection ) { if ( StringUtils . hasText ( config ) ) { stubs . add ( StubSpecification . parse ( config , defaultClassifier ) . stub ) ; } } return stubs ; }
The string is expected to be a map with entry called stubs that contains a list of Strings in the format
24,840
public boolean groupIdAndArtifactMatches ( String ivyNotationAsString ) { String [ ] parts = ivyNotationFrom ( ivyNotationAsString ) ; String groupId = parts [ 0 ] ; String artifactId = parts [ 1 ] ; if ( groupId == null ) { return this . artifactId . equals ( artifactId ) ; } return this . groupId . equals ( groupId ) && this . artifactId . equals ( artifactId ) ; }
Checks if ivy notation matches group and artifact ids .
24,841
public static < T > List < T > load ( final Class < T > type , final ClassLoader classLoader ) { final List < T > loaded = new ArrayList < > ( ) ; final Iterator < T > iterator = ServiceLoader . load ( type , classLoader ) . iterator ( ) ; while ( hasNextSafely ( iterator ) ) { try { final T next = iterator . next ( ) ; loaded . add ( next ) ; LOGGER . debug ( "Found {}" , type ) ; } catch ( Exception e ) { LOGGER . error ( "Could not load {}: {}" , type , e ) ; } } return loaded ; }
Load implementation by given type .
24,842
public void start ( final String uuid ) { Objects . requireNonNull ( uuid , "step uuid" ) ; context . get ( ) . push ( uuid ) ; }
Adds new uuid .
24,843
public Optional < String > stop ( ) { final LinkedList < String > uuids = context . get ( ) ; if ( ! uuids . isEmpty ( ) ) { return Optional . of ( uuids . pop ( ) ) ; } return Optional . empty ( ) ; }
Removes latest added uuid . Ignores empty context .
24,844
private void tryHandleNamedLink ( final String tagString ) { final String namedLinkPatternString = PLAIN_LINK + "\\.(\\w+-?)+=(\\w+(-|_)?)+" ; final Pattern namedLinkPattern = Pattern . compile ( namedLinkPatternString , Pattern . CASE_INSENSITIVE ) ; if ( namedLinkPattern . matcher ( tagString ) . matches ( ) ) { final String type = tagString . split ( COMPOSITE_TAG_DELIMITER ) [ 0 ] . split ( "[.]" ) [ 1 ] ; final String name = tagString . split ( COMPOSITE_TAG_DELIMITER ) [ 1 ] ; getScenarioLinks ( ) . add ( ResultsUtils . createLink ( null , name , null , type ) ) ; } else { LOGGER . warn ( "Composite named tag {} does not match regex {}. Skipping" , tagString , namedLinkPatternString ) ; } }
Handle composite named links .
24,845
public static String getParametersAsString ( final Object ... parameters ) { if ( parameters == null || parameters . length == 0 ) { return "" ; } final StringBuilder builder = new StringBuilder ( ) ; builder . append ( '[' ) ; for ( int i = 0 ; i < parameters . length ; i ++ ) { builder . append ( arrayToString ( parameters [ i ] ) ) ; if ( i < parameters . length - 1 ) { builder . append ( ", " ) ; } } return builder . append ( ']' ) . toString ( ) ; }
Convert array of given parameters to sting .
24,846
public void startPrepareFixture ( final String containerUuid , final String uuid , final FixtureResult result ) { storage . getContainer ( containerUuid ) . ifPresent ( container -> { synchronized ( storage ) { container . getBefores ( ) . add ( result ) ; } } ) ; notifier . beforeFixtureStart ( result ) ; startFixture ( uuid , result ) ; notifier . afterFixtureStart ( result ) ; }
Start a new prepare fixture with given parent .
24,847
public void startTearDownFixture ( final String containerUuid , final String uuid , final FixtureResult result ) { storage . getContainer ( containerUuid ) . ifPresent ( container -> { synchronized ( storage ) { container . getAfters ( ) . add ( result ) ; } } ) ; notifier . beforeFixtureStart ( result ) ; startFixture ( uuid , result ) ; notifier . afterFixtureStart ( result ) ; }
Start a new tear down fixture with given parent .
24,848
private void startFixture ( final String uuid , final FixtureResult result ) { storage . put ( uuid , result ) ; result . setStage ( Stage . RUNNING ) ; result . setStart ( System . currentTimeMillis ( ) ) ; threadContext . clear ( ) ; threadContext . start ( uuid ) ; }
Start a new fixture with given uuid .
24,849
public void updateFixture ( final String uuid , final Consumer < FixtureResult > update ) { final Optional < FixtureResult > found = storage . getFixture ( uuid ) ; if ( ! found . isPresent ( ) ) { LOGGER . error ( "Could not update test fixture: test fixture with uuid {} not found" , uuid ) ; return ; } final FixtureResult fixture = found . get ( ) ; notifier . beforeFixtureUpdate ( fixture ) ; update . accept ( fixture ) ; notifier . afterFixtureUpdate ( fixture ) ; }
Updates fixture by given uuid .
24,850
public void stopFixture ( final String uuid ) { final Optional < FixtureResult > found = storage . getFixture ( uuid ) ; if ( ! found . isPresent ( ) ) { LOGGER . error ( "Could not stop test fixture: test fixture with uuid {} not found" , uuid ) ; return ; } final FixtureResult fixture = found . get ( ) ; notifier . beforeFixtureStop ( fixture ) ; fixture . setStage ( Stage . FINISHED ) ; fixture . setStop ( System . currentTimeMillis ( ) ) ; storage . remove ( uuid ) ; threadContext . clear ( ) ; notifier . afterFixtureStop ( fixture ) ; }
Stops fixture by given uuid .
24,851
public void startStep ( final String parentUuid , final String uuid , final StepResult result ) { notifier . beforeStepStart ( result ) ; result . setStage ( Stage . RUNNING ) ; result . setStart ( System . currentTimeMillis ( ) ) ; threadContext . start ( uuid ) ; storage . put ( uuid , result ) ; storage . get ( parentUuid , WithSteps . class ) . ifPresent ( parentStep -> { synchronized ( storage ) { parentStep . getSteps ( ) . add ( result ) ; } } ) ; notifier . afterStepStart ( result ) ; }
Start a new step as child of specified parent .
24,852
public void updateStep ( final String uuid , final Consumer < StepResult > update ) { final Optional < StepResult > found = storage . getStep ( uuid ) ; if ( ! found . isPresent ( ) ) { LOGGER . error ( "Could not update step: step with uuid {} not found" , uuid ) ; return ; } final StepResult step = found . get ( ) ; notifier . beforeStepUpdate ( step ) ; update . accept ( step ) ; notifier . afterStepUpdate ( step ) ; }
Updates step by specified uuid .
24,853
public void stopStep ( final String uuid ) { final Optional < StepResult > found = storage . getStep ( uuid ) ; if ( ! found . isPresent ( ) ) { LOGGER . error ( "Could not stop step: step with uuid {} not found" , uuid ) ; return ; } final StepResult step = found . get ( ) ; notifier . beforeStepStop ( step ) ; step . setStage ( Stage . FINISHED ) ; step . setStop ( System . currentTimeMillis ( ) ) ; storage . remove ( uuid ) ; threadContext . stop ( ) ; notifier . afterStepStop ( step ) ; }
Stops step by given uuid .
24,854
public void addAttachment ( final String name , final String type , final String fileExtension , final InputStream stream ) { writeAttachment ( prepareAttachment ( name , type , fileExtension ) , stream ) ; }
Adds attachment to current running test or step .
24,855
public static List < Link > getLinks ( final AnnotatedElement annotatedElement ) { final List < Link > result = new ArrayList < > ( ) ; result . addAll ( extractLinks ( annotatedElement , io . qameta . allure . Link . class , ResultsUtils :: createLink ) ) ; result . addAll ( extractLinks ( annotatedElement , io . qameta . allure . Issue . class , ResultsUtils :: createLink ) ) ; result . addAll ( extractLinks ( annotatedElement , io . qameta . allure . TmsLink . class , ResultsUtils :: createLink ) ) ; return result ; }
Returns links created from Allure annotations specified on annotated element .
24,856
public static List < Link > getLinks ( final Collection < Annotation > annotations ) { final List < Link > result = new ArrayList < > ( ) ; result . addAll ( extractLinks ( annotations , io . qameta . allure . Link . class , ResultsUtils :: createLink ) ) ; result . addAll ( extractLinks ( annotations , io . qameta . allure . Issue . class , ResultsUtils :: createLink ) ) ; result . addAll ( extractLinks ( annotations , io . qameta . allure . TmsLink . class , ResultsUtils :: createLink ) ) ; return result ; }
Returns links from given annotations .
24,857
public static Set < Label > getLabels ( final Collection < Annotation > annotations ) { return annotations . stream ( ) . flatMap ( AnnotationUtils :: extractRepeatable ) . map ( AnnotationUtils :: getMarks ) . flatMap ( Collection :: stream ) . collect ( Collectors . toSet ( ) ) ; }
Returns labels from given annotations .
24,858
public boolean isRunning ( ) { try { client . get ( "/" ) ; return true ; } catch ( IOException e ) { LOGGER . debug ( "isRunning()" , e ) ; return false ; } }
Get the current status of the Jenkins end - point by pinging it .
24,859
public View getView ( FolderJob folder , String name ) throws IOException { try { View resultView = client . get ( UrlUtils . toViewBaseUrl ( folder , name ) + "/" , View . class ) ; resultView . setClient ( client ) ; for ( Job job : resultView . getJobs ( ) ) { job . setClient ( client ) ; } for ( View view : resultView . getViews ( ) ) { view . setClient ( client ) ; } return resultView ; } catch ( HttpResponseException e ) { LOGGER . debug ( "getView(folder={}, name={}) status={}" , folder , name , e . getStatusCode ( ) ) ; if ( e . getStatusCode ( ) == HttpStatus . SC_NOT_FOUND ) { return null ; } throw e ; } }
Get a single view object from the given folder
24,860
public JobWithDetails getJob ( String jobName ) throws IOException { return getJob ( null , UrlUtils . toFullJobPath ( jobName ) ) ; }
Get a single Job from the server .
24,861
public JobWithDetails getJob ( FolderJob folder , String jobName ) throws IOException { try { JobWithDetails job = client . get ( UrlUtils . toJobBaseUrl ( folder , jobName ) , JobWithDetails . class ) ; job . setClient ( client ) ; return job ; } catch ( HttpResponseException e ) { LOGGER . debug ( "getJob(folder={}, jobName={}) status={}" , folder , jobName , e . getStatusCode ( ) ) ; if ( e . getStatusCode ( ) == HttpStatus . SC_NOT_FOUND ) { return null ; } throw e ; } }
Get a single Job from the given folder .
24,862
public JenkinsServer createView ( String viewName , String viewXml ) throws IOException { return createView ( null , viewName , viewXml , false ) ; }
Create a view on the server using the provided xml
24,863
public JenkinsServer createView ( String viewName , String viewXml , Boolean crumbFlag ) throws IOException { return createView ( null , viewName , viewXml , crumbFlag ) ; }
Create a view on the server using the provided xml .
24,864
public String getJobXml ( FolderJob folder , String jobName ) throws IOException { return client . get ( UrlUtils . toJobBaseUrl ( folder , jobName ) + "/config.xml" ) ; }
Get the xml description of an existing job .
24,865
public LabelWithDetails getLabel ( String labelName ) throws IOException { return client . get ( "/label/" + EncodingUtils . encode ( labelName ) , LabelWithDetails . class ) ; }
Get the description of an existing Label
24,866
public JenkinsServer updateView ( String viewName , String viewXml ) throws IOException { return this . updateView ( viewName , viewXml , true ) ; }
Update the xml description of an existing view
24,867
public JenkinsServer enableJob ( String jobName , boolean crumbFlag ) throws IOException { client . post ( "/job/" + EncodingUtils . encode ( jobName ) + "/enable" , crumbFlag ) ; return this ; }
Enable a job from Jenkins .
24,868
public String runScript ( String script , boolean crumbFlag ) throws IOException { return client . post_text ( "/scriptText" , "script=" + script , ContentType . APPLICATION_FORM_URLENCODED , crumbFlag ) ; }
Runs the provided groovy script on the server and returns the result .
24,869
public JenkinsServer restart ( Boolean crumbFlag ) throws IOException { try { client . post ( "/restart" , crumbFlag ) ; } catch ( org . apache . http . client . ClientProtocolException e ) { LOGGER . error ( "restart()" , e ) ; } return this ; }
Restart Jenkins without waiting for any existing build to complete
24,870
protected static HttpClientBuilder addAuthentication ( final HttpClientBuilder builder , final URI uri , final String username , String password ) { if ( isNotBlank ( username ) ) { CredentialsProvider provider = new BasicCredentialsProvider ( ) ; AuthScope scope = new AuthScope ( uri . getHost ( ) , uri . getPort ( ) , "realm" ) ; UsernamePasswordCredentials credentials = new UsernamePasswordCredentials ( username , password ) ; provider . setCredentials ( scope , credentials ) ; builder . setDefaultCredentialsProvider ( provider ) ; builder . addInterceptorFirst ( new PreemptiveAuth ( ) ) ; } return builder ; }
Add authentication to supplied builder .
24,871
public static String getJenkinsVersion ( final HttpResponse response ) { final Header [ ] hdrs = response . getHeaders ( "X-Jenkins" ) ; return hdrs . length == 0 ? "" : hdrs [ 0 ] . getValue ( ) ; }
Get Jenkins version from supplied response if any .
24,872
public Optional < Build > getBuildByNumber ( final int buildNumber ) { return builds . stream ( ) . filter ( isBuildNumberEqualTo ( buildNumber ) ) . findFirst ( ) ; }
Get a build by the given buildNumber .
24,873
public static String toJobBaseUrl ( final FolderJob folder , final String jobName ) { final StringBuilder sb = new StringBuilder ( DEFAULT_BUFFER_SIZE ) ; sb . append ( UrlUtils . toBaseUrl ( folder ) ) ; if ( sb . charAt ( sb . length ( ) - 1 ) != '/' ) sb . append ( '/' ) ; sb . append ( "job/" ) ; final String [ ] jobNameParts = jobName . split ( "/" ) ; for ( int i = 0 ; i < jobNameParts . length ; i ++ ) { sb . append ( EncodingUtils . encode ( jobNameParts [ i ] ) ) ; if ( i != jobNameParts . length - 1 ) sb . append ( '/' ) ; } return sb . toString ( ) ; }
Helper to create the base url for a job with or without a given folder
24,874
public static String toViewBaseUrl ( final FolderJob folder , final String name ) { final StringBuilder sb = new StringBuilder ( DEFAULT_BUFFER_SIZE ) ; final String base = UrlUtils . toBaseUrl ( folder ) ; sb . append ( base ) ; if ( ! base . endsWith ( "/" ) ) sb . append ( '/' ) ; sb . append ( "view/" ) . append ( EncodingUtils . encode ( name ) ) ; return sb . toString ( ) ; }
Helper to create the base url for a view with or without a given folder
24,875
public static String toFullJobPath ( final String jobName ) { final String [ ] parts = jobName . split ( "/" ) ; if ( parts . length == 1 ) return parts [ 0 ] ; final StringBuilder sb = new StringBuilder ( DEFAULT_BUFFER_SIZE ) ; for ( int i = 0 ; i < parts . length ; i ++ ) { sb . append ( parts [ i ] ) ; if ( i != parts . length - 1 ) sb . append ( "/job/" ) ; } return sb . toString ( ) ; }
Parses the provided job name for folders to get the full path for the job .
24,876
public static URI toJsonApiUri ( final URI uri , final String context , final String path ) { String p = path ; if ( ! p . matches ( "(?i)https?://.*" ) ) p = join ( context , p ) ; if ( ! p . contains ( "?" ) ) { p = join ( p , "api/json" ) ; } else { final String [ ] components = p . split ( "\\?" , 2 ) ; p = join ( components [ 0 ] , "api/json" ) + "?" + components [ 1 ] ; } return uri . resolve ( "/" ) . resolve ( p . replace ( " " , "%20" ) ) ; }
Create a JSON URI from the supplied parameters .
24,877
public static URI toNoApiUri ( final URI uri , final String context , final String path ) { final String p = path . matches ( "(?i)https?://.*" ) ? path : join ( context , path ) ; return uri . resolve ( "/" ) . resolve ( p ) ; }
Create a URI from the supplied parameters .
24,878
public String getFileFromWorkspace ( String fileName ) throws IOException { InputStream is = client . getFile ( URI . create ( url + "/ws/" + fileName ) ) ; ByteArrayOutputStream result = new ByteArrayOutputStream ( ) ; byte [ ] buffer = new byte [ 1024 ] ; int length ; while ( ( length = is . read ( buffer ) ) != - 1 ) { result . write ( buffer , 0 , length ) ; } return result . toString ( "UTF-8" ) ; }
Get a file from workspace .
24,879
public QueueReference build ( ) throws IOException { ExtractHeader location = client . post ( url + "build" , null , ExtractHeader . class , false ) ; return new QueueReference ( location . getLocation ( ) ) ; }
Trigger a build without parameters
24,880
public QueueReference build ( Map < String , String > params , Map < String , File > fileParams ) throws IOException { return build ( params , fileParams , false ) ; }
Trigger a parameterized build with file parameters
24,881
public QueueReference build ( Map < String , String > params , Map < String , File > fileParams , boolean crumbFlag ) throws IOException { String qs = params . entrySet ( ) . stream ( ) . map ( s -> s . getKey ( ) + "=" + s . getValue ( ) ) . collect ( Collectors . joining ( "&" ) ) ; ExtractHeader location = client . post ( url + "buildWithParameters?" + qs , null , ExtractHeader . class , fileParams , crumbFlag ) ; return new QueueReference ( location . getLocation ( ) ) ; }
Trigger a parameterized build with file parameters and crumbFlag
24,882
public static void main ( String ... args ) { System . out . println ( "Display parameters as parsed by Maven (in canonical form) and comparison result:" ) ; if ( args . length == 0 ) { return ; } ComparableVersion prev = null ; int i = 1 ; for ( String version : args ) { ComparableVersion c = new ComparableVersion ( version ) ; if ( prev != null ) { int compare = prev . compareTo ( c ) ; System . out . println ( " " + prev . toString ( ) + ' ' + ( ( compare == 0 ) ? "==" : ( ( compare < 0 ) ? "<" : ">" ) ) + ' ' + version ) ; } System . out . println ( String . valueOf ( i ++ ) + ". " + version + " == " + c . getCanonical ( ) ) ; prev = c ; } }
Main to test version parsing and comparison .
24,883
public Map < String , Job > getJobs ( ) { return jobs . stream ( ) . map ( SET_CLIENT ( this . client ) ) . collect ( Collectors . toMap ( k -> k . getName ( ) , Function . identity ( ) ) ) ; }
Get a list of all the defined jobs in this folder
24,884
public Job getJob ( String name ) { return jobs . stream ( ) . map ( SET_CLIENT ( this . client ) ) . filter ( item -> item . getName ( ) . equals ( name ) ) . findAny ( ) . orElseThrow ( ( ) -> new IllegalArgumentException ( "Job with name " + name + " does not exist." ) ) ; }
Get a job in this folder by name
24,885
public void streamConsoleOutput ( final BuildConsoleStreamListener listener , final int poolingInterval , final int poolingTimeout , boolean crumbFlag ) throws InterruptedException , IOException { final long startTime = System . currentTimeMillis ( ) ; final long timeoutTime = startTime + ( poolingTimeout * 1000 ) ; int bufferOffset = 0 ; while ( true ) { Thread . sleep ( poolingInterval * 1000 ) ; ConsoleLog consoleLog = null ; consoleLog = getConsoleOutputText ( bufferOffset , crumbFlag ) ; String logString = consoleLog . getConsoleLog ( ) ; if ( logString != null && ! logString . isEmpty ( ) ) { listener . onData ( logString ) ; } if ( consoleLog . getHasMoreData ( ) ) { bufferOffset = consoleLog . getCurrentBufferSize ( ) ; } else { listener . finished ( ) ; break ; } long currentTime = System . currentTimeMillis ( ) ; if ( currentTime > timeoutTime ) { LOGGER . warn ( "Pooling for build {0} for {2} timeout! Check if job stuck in jenkins" , BuildWithDetails . this . getDisplayName ( ) , BuildWithDetails . this . getNumber ( ) ) ; break ; } } }
Stream build console output log as text using BuildConsoleStreamListener Method can be used to asynchronously obtain logs for running build .
24,886
public ConsoleLog getConsoleOutputText ( int bufferOffset , boolean crumbFlag ) throws IOException { List < NameValuePair > formData = new ArrayList < > ( ) ; formData . add ( new BasicNameValuePair ( "start" , Integer . toString ( bufferOffset ) ) ) ; String path = getUrl ( ) + "logText/progressiveText" ; HttpResponse httpResponse = client . post_form_with_result ( path , formData , crumbFlag ) ; Header moreDataHeader = httpResponse . getFirstHeader ( MORE_DATA_HEADER ) ; Header textSizeHeader = httpResponse . getFirstHeader ( TEXT_SIZE_HEADER ) ; String response = EntityUtils . toString ( httpResponse . getEntity ( ) ) ; boolean hasMoreData = false ; if ( moreDataHeader != null ) { hasMoreData = Boolean . TRUE . toString ( ) . equals ( moreDataHeader . getValue ( ) ) ; } Integer currentBufferSize = bufferOffset ; if ( textSizeHeader != null ) { try { currentBufferSize = Integer . parseInt ( textSizeHeader . getValue ( ) ) ; } catch ( NumberFormatException e ) { LOGGER . warn ( "Cannot parse buffer size for job {0} build {1}. Using current offset!" , this . getDisplayName ( ) , this . getNumber ( ) ) ; } } return new ConsoleLog ( response , hasMoreData , currentBufferSize ) ; }
Get build console output log as text . Use this method to periodically obtain logs from jenkins and skip chunks that were already received
24,887
public BuildChangeSet getChangeSet ( ) { BuildChangeSet result ; if ( changeSet != null ) { result = changeSet ; } else if ( changeSets != null && ! changeSets . isEmpty ( ) ) { result = changeSets . get ( 0 ) ; } else { result = null ; } return result ; }
Returns the change set of a build if available .
24,888
public List < BuildChangeSet > getChangeSets ( ) { List < BuildChangeSet > result ; if ( changeSets != null ) { result = changeSets ; } else if ( changeSet != null ) { result = Collections . singletonList ( changeSet ) ; } else { result = null ; } return result ; }
Returns the complete list of change sets for all checkout the build has performed . If no checkouts have been performed returns null .
24,889
public String Stop ( boolean crumbFlag ) throws HttpResponseException , IOException { try { return client . get ( url + "stop" ) ; } catch ( HttpResponseException ex ) { if ( ex . getStatusCode ( ) == HttpStatus . SC_METHOD_NOT_ALLOWED ) { stopPost ( crumbFlag ) ; return "" ; } throw ex ; } }
Stops the build which is currently in progress . This version takes in a crumbFlag . In some cases an error is thrown which reads No valid crumb was included in the request . This stop method is used incase those issues occur
24,890
public static String getExtension ( String uri ) { if ( uri == null ) { return null ; } int dot = uri . lastIndexOf ( "." ) ; if ( dot >= 0 ) { return uri . substring ( dot ) ; } else { return "" ; } }
Gets the extension of a file name like . png or . jpg .
24,891
public static Uri getUri ( Context context , File file ) { if ( file != null ) { return FileProvider . getUriForFile ( context , FILE_PROVIDER_AUTHORITY , file ) ; } return null ; }
Convert File into Uri .
24,892
public static File getFile ( Context context , Uri uri ) { if ( uri != null ) { String path = getPath ( context , uri ) ; if ( path != null && isLocal ( path ) ) { return new File ( path ) ; } } return null ; }
Convert Uri into File if possible .
24,893
public static String getReadableFileSize ( int size ) { final int BYTES_IN_KILOBYTES = 1024 ; final DecimalFormat dec = new DecimalFormat ( "###.#" ) ; final String KILOBYTES = " KB" ; final String MEGABYTES = " MB" ; final String GIGABYTES = " GB" ; float fileSize = 0 ; String suffix = KILOBYTES ; if ( size > BYTES_IN_KILOBYTES ) { fileSize = size / BYTES_IN_KILOBYTES ; if ( fileSize > BYTES_IN_KILOBYTES ) { fileSize = fileSize / BYTES_IN_KILOBYTES ; if ( fileSize > BYTES_IN_KILOBYTES ) { fileSize = fileSize / BYTES_IN_KILOBYTES ; suffix = GIGABYTES ; } else { suffix = MEGABYTES ; } } } return String . valueOf ( dec . format ( fileSize ) + suffix ) ; }
Get the file size in a human - readable string .
24,894
public static Bitmap getThumbnail ( Context context , File file ) { return getThumbnail ( context , getUri ( context , file ) , getMimeType ( file ) ) ; }
Attempt to retrieve the thumbnail of given File from the MediaStore . This should not be called on the UI thread .
24,895
public static Intent createGetContentIntent ( ) { final Intent intent = new Intent ( Intent . ACTION_GET_CONTENT ) ; intent . setType ( "*/*" ) ; intent . addCategory ( Intent . CATEGORY_OPENABLE ) ; return intent ; }
Get the Intent for selecting content to be used in an Intent Chooser .
24,896
private void requestPermissions ( int mediaType ) { if ( ContextCompat . checkSelfPermission ( this , Manifest . permission . WRITE_EXTERNAL_STORAGE ) != PackageManager . PERMISSION_GRANTED ) { if ( mediaType == TYPE_IMAGE ) { ActivityCompat . requestPermissions ( this , new String [ ] { Manifest . permission . WRITE_EXTERNAL_STORAGE } , MY_PERMISSIONS_REQUEST_WRITE_STORAGE ) ; } else { ActivityCompat . requestPermissions ( this , new String [ ] { Manifest . permission . WRITE_EXTERNAL_STORAGE } , MY_PERMISSIONS_REQUEST_WRITE_STORAGE_VID ) ; } } else { if ( mediaType == TYPE_IMAGE ) { dispatchTakePictureIntent ( ) ; } else if ( mediaType == TYPE_VIDEO ) { dispatchTakeVideoIntent ( ) ; } } }
Request Permission for writing to External Storage in 6 . 0 and up
24,897
public void onActivityResult ( int requestCode , int resultCode , Intent data ) { super . onActivityResult ( requestCode , resultCode , data ) ; if ( requestCode == REQUEST_TAKE_CAMERA_PHOTO && resultCode == Activity . RESULT_OK ) { new ImageCompressionAsyncTask ( this ) . execute ( mCurrentPhotoPath , Environment . getExternalStoragePublicDirectory ( Environment . DIRECTORY_PICTURES ) + "/Silicompressor/images" ) ; } else if ( requestCode == REQUEST_TAKE_VIDEO && resultCode == RESULT_OK ) { if ( data . getData ( ) != null ) { File f = new File ( Environment . getExternalStoragePublicDirectory ( Environment . DIRECTORY_MOVIES ) + "/Silicompressor/videos" ) ; if ( f . mkdirs ( ) || f . isDirectory ( ) ) new VideoCompressAsyncTask ( this ) . execute ( mCurrentPhotoPath , f . getPath ( ) ) ; } } }
Method which will process the captured image
24,898
public static SiliCompressor with ( Context context ) { if ( singleton == null ) { synchronized ( SiliCompressor . class ) { if ( singleton == null ) { singleton = new Builder ( context ) . build ( ) ; } } } return singleton ; }
initialise the class and set the context
24,899
public String compress ( String imagePath , File destination , boolean deleteSourceImage ) { String compressedImagePath = compressImage ( imagePath , destination ) ; if ( deleteSourceImage ) { boolean isdeleted = deleteImageFile ( imagePath ) ; Log . d ( LOG_TAG , ( isdeleted ) ? "Source image file deleted" : "Error: Source image file not deleted." ) ; } return compressedImagePath ; }
Compress the image at with the specified path and return the filepath of the compressed image .