Input: Replace variables with given pattern . [CODESPLIT] private String substituteVariables ( String template , String patternString , Map < String , String > variables ) { Pattern pattern = Pattern . compile ( patternString ) ; Matcher matcher = pattern . matcher ( template ) ; StringBuffer buffer = new StringBuffer ( ) ; while ( matcher . find ( ) ) { if ( variables . containsKey ( matcher . group ( 1 ) ) ) { String replacement = variables . get ( matcher . group ( 1 ) ) ; // quote to work properly with $ and {,} signs matcher . appendReplacement ( buffer , replacement != null ? Matcher . quoteReplacement ( replacement ) : "null" ) ; } } matcher . appendTail ( buffer ) ; return buffer . toString ( ) ; }


Input: Going through list of DTOs and parsing the markdown into HTML . Add header and footer to the big String . [CODESPLIT] private void processMarkdown ( List < MarkdownDTO > markdownDTOs , int options , final Map < String , Attributes > attributesMap ) throws MojoExecutionException { getLog ( ) . debug ( "Process Markdown" ) ; getLog ( ) . debug ( "inputEncoding: '" + getInputEncoding ( ) + "', outputEncoding: '" + getOutputEncoding ( ) + "'" ) ; //getLog().debug("parsingTimeout: " + getParsingTimeoutInMillis() + " ms"); getLog ( ) . debug ( "applyFiltering: " + applyFiltering ) ; MutableDataHolder flexmarkOptions = PegdownOptionsAdapter . flexmarkOptions ( options ) . toMutable ( ) ; ArrayList < Extension > extensions = new ArrayList < Extension > ( ) ; for ( Extension extension : flexmarkOptions . get ( Parser . EXTENSIONS ) ) { extensions . add ( extension ) ; } if ( transformRelativeMarkdownLinks ) { flexmarkOptions . set ( PageGeneratorExtension . INPUT_FILE_EXTENSIONS , inputFileExtensions ) ; extensions . add ( PageGeneratorExtension . create ( ) ) ; } if ( ! attributesMap . isEmpty ( ) ) { flexmarkOptions . set ( AttributesExtension . ATTRIBUTE_MAP , attributesMap ) ; extensions . add ( AttributesExtension . create ( ) ) ; } flexmarkOptions . set ( Parser . EXTENSIONS , extensions ) ; Parser parser = Parser . builder ( flexmarkOptions ) . build ( ) ; HtmlRenderer renderer = HtmlRenderer . builder ( flexmarkOptions ) . build ( ) ; for ( MarkdownDTO dto : markdownDTOs ) { getLog ( ) . debug ( "dto: " + dto ) ; try { String headerHtml = "" ; String footerHtml = "" ; try { if ( StringUtils . isNotEmpty ( headerHtmlFile ) ) { headerHtml = FileUtils . readFileToString ( new File ( headerHtmlFile ) , getInputEncoding ( ) ) ; headerHtml = addTitleToHtmlFile ( headerHtml , dto . title ) ; headerHtml = replaceVariables ( headerHtml , dto . substitutes ) ; headerHtml = updateRelativePaths ( headerHtml , dto . folderDepth ) ; } if ( StringUtils . isNotEmpty ( footerHtmlFile ) ) { footerHtml = FileUtils . readFileToString ( new File ( footerHtmlFile ) , getInputEncoding ( ) ) ; footerHtml = replaceVariables ( footerHtml , dto . substitutes ) ; footerHtml = updateRelativePaths ( footerHtml , dto . folderDepth ) ; } } catch ( FileNotFoundException e ) { if ( failIfFilesAreMissing ) { throw e ; } else { getLog ( ) . warn ( "header and/or footer file is missing." ) ; headerHtml = "" ; footerHtml = "" ; } } catch ( Exception e ) { throw new MojoExecutionException ( "Error while processing header/footer: " + e . getMessage ( ) , e ) ; } String markdown = FileUtils . readFileToString ( dto . markdownFile , getInputEncoding ( ) ) ; markdown = replaceVariables ( markdown , dto . substitutes ) ; // getLog().debug(markdown); String markdownAsHtml ; Node document = parser . parse ( markdown ) ; markdownAsHtml = renderer . render ( document ) ; String data = headerHtml + markdownAsHtml + footerHtml ; FileUtils . writeStringToFile ( dto . htmlFile , data , getOutputEncoding ( ) ) ; } catch ( MojoExecutionException e ) { throw e ; } catch ( IOException e ) { getLog ( ) . error ( "Error : " + e . getMessage ( ) , e ) ; throw new MojoExecutionException ( "Unable to write file " + e . getMessage ( ) , e ) ; } } }


Input: Get the first h1 for the title . [CODESPLIT] private String getTitle ( List < String > raw ) { if ( raw == null ) { return defaultTitle ; } String previousLine = "" ; for ( String line : raw ) { line = line . trim ( ) ; if ( line . startsWith ( "#" ) ) { line = line . replace ( "#" , "" ) ; return line ; } //Checking for Setext style headers. //Line is considered a match if it passes: //Starts with either = or - //It has the same number of characters as the previous line //It only contains - or = and nothing else. // //If there is a match we consider the previous line to be the title. if ( ( line . startsWith ( "=" ) && StringUtils . countMatches ( line , "=" ) == previousLine . length ( ) && line . matches ( "^=+$" ) ) || ( line . startsWith ( "-" ) && StringUtils . countMatches ( line , "-" ) == previousLine . length ( ) && line . matches ( "^-+$" ) ) ) { return previousLine ; } previousLine = line ; } return defaultTitle ; }


Input: Adds the title to the html file . [CODESPLIT] private String addTitleToHtmlFile ( String html , String title ) { if ( html == null ) { return html ; } if ( title != null ) { getLog ( ) . debug ( "Setting the title in the HTML file to: " + title ) ; return html . replaceFirst ( "titleToken" , title ) ; } else { getLog ( ) . debug ( "Title was null, setting the title in the HTML file to an empty string" ) ; return html . replaceFirst ( "titleToken" , "" ) ; } }


Input: Replace variables in the html file . [CODESPLIT] private String replaceVariables ( String initialContent , Map < String , String > variables ) { String newContent = initialContent ; // Only apply substitution if filtering is enabled and there is actually something to // substitute, otherwise just return the original content. if ( applyFiltering && newContent != null ) { newContent = newContent . replaceAll ( "\\{\\w*=.*}" , "" ) ; if ( variables != null ) { newContent = substituteVariables ( newContent , "\\$\\{(.+?)\\}" , variables ) ; } } return newContent ; }


Input: Update relative include paths corresponding to the markdown file s location in the folder structure . [CODESPLIT] private String updateRelativePaths ( String html , int folderDepth ) { if ( html == null ) { return html ; } getLog ( ) . debug ( "Updating relative paths in html includes (css, js)." ) ; return html . replaceAll ( "##SITE_BASE##" , getSiteBasePrefix ( folderDepth ) ) ; }


Input: Copy files from one dir to another based on file extensions . [CODESPLIT] private void copyFiles ( String fromDir , String toDir ) throws MojoExecutionException { getLog ( ) . debug ( "fromDir=" + fromDir + "; toDir=" + toDir ) ; try { File fromDirFile = new File ( fromDir ) ; if ( fromDirFile . exists ( ) ) { Iterator < File > files = FileUtils . iterateFiles ( new File ( fromDir ) , null , false ) ; while ( files . hasNext ( ) ) { File file = files . next ( ) ; if ( file . exists ( ) ) { FileUtils . copyFileToDirectory ( file , new File ( toDir ) ) ; } else { getLog ( ) . error ( "File '" + file . getAbsolutePath ( ) + "' does not exist. Skipping copy" ) ; } } } } catch ( IOException e ) { throw new MojoExecutionException ( "Unable to copy file " + e . getMessage ( ) , e ) ; } }


Input: This solves https : // issues . apache . org / jira / browse / MRESOURCES - 99 . <br / > BUT : <br / > This should be done different than defining those properties a second time cause they have already being defined in Maven Model Builder ( package org . apache . maven . model . interpolation ) via BuildTimestampValueSource . But those can t be found in the context which can be got from the maven core . <br / > A solution could be to put those values into the context by Maven core so they are accessible everywhere . ( I m not sure if this is a good idea ) . Better ideas are always welcome . <p > The problem at the moment is that maven core handles usage of properties and replacements in the model but does not the resource filtering which needed some of the properties . [CODESPLIT] private Properties addSeveralSpecialProperties ( ) { String timeStamp = new MavenBuildTimestamp ( new Date ( ) , timestampFormat ) . formattedTimestamp ( ) ; Properties additionalProperties = new Properties ( ) ; additionalProperties . put ( "mdpagegenerator.timestamp" , timeStamp ) ; if ( project . getBasedir ( ) != null ) { additionalProperties . put ( "project.baseUri" , project . getBasedir ( ) . getAbsoluteFile ( ) . toURI ( ) . toString ( ) ) ; } return additionalProperties ; }


Input: When retrieving more statements LRS will return full path .. the client will have part in the URI already so cut that off [CODESPLIT] protected String checkPath ( String path ) { if ( path . toLowerCase ( ) . contains ( "statements" ) && path . toLowerCase ( ) . contains ( "more" ) ) { int pathLength = this . _host . getPath ( ) . length ( ) ; return path . substring ( pathLength , path . length ( ) ) ; } return path ; }


Input: this will wrap the view which is added to the slider into another layout so we can then overlap the small and large view [CODESPLIT] private View wrapSliderContent ( View child , int index ) { //TODO !! if ( index == 1 && child . getId ( ) != - 1 ) { mLargeView = ( ViewGroup ) child ; mContainer = new ScrimInsetsRelativeLayout ( getContext ( ) ) ; mContainer . setGravity ( Gravity . START ) ; mContainer . setLayoutParams ( child . getLayoutParams ( ) ) ; mContainer . addView ( mLargeView , ViewGroup . LayoutParams . MATCH_PARENT , ViewGroup . LayoutParams . MATCH_PARENT ) ; mSmallView = new LinearLayout ( getContext ( ) ) ; mContainer . addView ( mSmallView , ViewGroup . LayoutParams . MATCH_PARENT , ViewGroup . LayoutParams . MATCH_PARENT ) ; mLargeView . setAlpha ( 0 ) ; mLargeView . setVisibility ( View . GONE ) ; //correct fitsSystemWindows handling mContainer . setFitsSystemWindows ( true ) ; mSmallView . setFitsSystemWindows ( true ) ; return mContainer ; } return child ; }


Input: animate to the large view [CODESPLIT] public void fadeUp ( int duration ) { //animate up mContainer . clearAnimation ( ) ; ResizeWidthAnimation anim = new ResizeWidthAnimation ( mContainer , mMaxWidth , new ApplyTransformationListener ( ) { @ Override public void applyTransformation ( int width ) { overlapViews ( width ) ; } } ) ; anim . setDuration ( duration ) ; mContainer . startAnimation ( anim ) ; }


Input: animate to the small view [CODESPLIT] public void fadeDown ( int duration ) { //fade down mContainer . clearAnimation ( ) ; ResizeWidthAnimation anim = new ResizeWidthAnimation ( mContainer , mMinWidth , new ApplyTransformationListener ( ) { @ Override public void applyTransformation ( int width ) { overlapViews ( width ) ; } } ) ; anim . setDuration ( duration ) ; mContainer . startAnimation ( anim ) ; }


Input: calculate the percentage to how many percent the slide is already visible [CODESPLIT] private float calculatePercentage ( int width ) { int absolute = mMaxWidth - mMinWidth ; int current = width - mMinWidth ; float percentage = 100.0f * current / absolute ; //we can assume that we are crossfaded if the percentage is > 90 mIsCrossfaded = percentage > 90 ; return percentage ; }


Input: overlap the views and provide the crossfade effect [CODESPLIT] private void overlapViews ( int width ) { if ( width == mWidth ) { return ; } //remember this width so it is't processed twice mWidth = width ; float percentage = calculatePercentage ( width ) ; float alpha = percentage / 100 ; mSmallView . setAlpha ( 1 ) ; mSmallView . setClickable ( false ) ; mLargeView . bringToFront ( ) ; mLargeView . setAlpha ( alpha ) ; mLargeView . setClickable ( true ) ; mLargeView . setVisibility ( alpha > 0.01f ? View . VISIBLE : View . GONE ) ; //notify the crossfadeListener if ( mCrossfadeListener != null ) { mCrossfadeListener . onCrossfade ( mContainer , calculatePercentage ( width ) , width ) ; } }


Input: The intent to launch the Activity . [CODESPLIT] protected < T extends Activity > Intent getLaunchIntent ( String targetPackage , Class < T > activityClass , BundleCreator bundleCreator ) { Intent intent = new Intent ( Intent . ACTION_MAIN ) ; intent . setClassName ( targetPackage , activityClass . getName ( ) ) ; intent . putExtras ( bundleCreator . createBundle ( ) ) ; intent . addFlags ( Intent . FLAG_ACTIVITY_NEW_TASK ) ; return intent ; }


Input: Launch the activity if needed . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) private void launchActivity ( ) { if ( activity != null && ActivityRunMode . SPECIFICATION . equals ( activityRunMode ) ) return ; String targetPackage = instrumentation . getTargetContext ( ) . getPackageName ( ) ; Intent intent = getLaunchIntent ( targetPackage , activityClass , bundleCreator ) ; activity = instrumentation . startActivitySync ( intent ) ; instrumentation . waitForIdleSync ( ) ; }


Input: getTodos Retrieves all todos a user can read . [CODESPLIT] public TodoListResponse getTodos ( String type , String status , UUID factSheetId , UUID userId , UUID workspaceId , Boolean getArchived , Integer size , Integer page ) throws ApiException { Object localVarPostBody = null ; // create path and map variables String localVarPath = "/todos" . replaceAll ( "\\{format\\}" , "json" ) ; // query params List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "type" , type ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "status" , status ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "factSheetId" , factSheetId ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "userId" , userId ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "workspaceId" , workspaceId ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "getArchived" , getArchived ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "size" , size ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "page" , page ) ) ; final String [ ] localVarAccepts = { "application/json" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { "application/json" } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { "token" } ; GenericType < TodoListResponse > localVarReturnType = new GenericType < TodoListResponse > ( ) { } ; return apiClient . invokeAPI ( localVarPath , "GET" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }


Input: getFactSheets Retrieves all Fact Sheets [CODESPLIT] public FactSheetListResponse getFactSheets ( String type , String relationTypes , Integer pageSize , String cursor , Boolean permissions ) throws ApiException { Object localVarPostBody = null ; // create path and map variables String localVarPath = "/factSheets" . replaceAll ( "\\{format\\}" , "json" ) ; // query params List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "type" , type ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "relationTypes" , relationTypes ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "pageSize" , pageSize ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "cursor" , cursor ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "permissions" , permissions ) ) ; final String [ ] localVarAccepts = { "application/json" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { "application/json" } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { "token" } ; GenericType < FactSheetListResponse > localVarReturnType = new GenericType < FactSheetListResponse > ( ) { } ; return apiClient . invokeAPI ( localVarPath , "GET" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }


Input: Set the connect timeout ( in milliseconds ) . A value of 0 means no timeout otherwise values must be between 1 and { [CODESPLIT] public ApiClient setConnectTimeout ( int connectionTimeout ) { this . connectionTimeout = connectionTimeout ; httpClient . property ( ClientProperties . CONNECT_TIMEOUT , connectionTimeout ) ; return this ; }


Input: Set the date format used to parse / format date parameters . [CODESPLIT] public ApiClient setDateFormat ( DateFormat dateFormat ) { this . dateFormat = dateFormat ; // also set the date format for model (de)serialization with Date properties this . json . setDateFormat ( ( DateFormat ) dateFormat . clone ( ) ) ; return this ; }


Input: Serialize the given Java object into string entity according the given Content - Type ( only JSON is supported for now ) . [CODESPLIT] public Entity < ? > serialize ( Object obj , Map < String , Object > formParams , String contentType ) throws ApiException { Entity < ? > entity = null ; if ( contentType . startsWith ( "multipart/form-data" ) ) { MultiPart multiPart = new MultiPart ( ) ; for ( Entry < String , Object > param : formParams . entrySet ( ) ) { if ( param . getValue ( ) instanceof File ) { File file = ( File ) param . getValue ( ) ; FormDataContentDisposition contentDisp = FormDataContentDisposition . name ( param . getKey ( ) ) . fileName ( file . getName ( ) ) . size ( file . length ( ) ) . build ( ) ; multiPart . bodyPart ( new FormDataBodyPart ( contentDisp , file , MediaType . APPLICATION_OCTET_STREAM_TYPE ) ) ; } else { FormDataContentDisposition contentDisp = FormDataContentDisposition . name ( param . getKey ( ) ) . build ( ) ; multiPart . bodyPart ( new FormDataBodyPart ( contentDisp , parameterToString ( param . getValue ( ) ) ) ) ; } } entity = Entity . entity ( multiPart , MediaType . MULTIPART_FORM_DATA_TYPE ) ; } else if ( contentType . startsWith ( "application/x-www-form-urlencoded" ) ) { Form form = new Form ( ) ; for ( Entry < String , Object > param : formParams . entrySet ( ) ) { form . param ( param . getKey ( ) , parameterToString ( param . getValue ( ) ) ) ; } entity = Entity . entity ( form , MediaType . APPLICATION_FORM_URLENCODED_TYPE ) ; } else { // We let jersey handle the serialization entity = Entity . entity ( obj , contentType ) ; } return entity ; }


Input: Deserialize response body to Java object according to the Content - Type . [CODESPLIT] public < T > T deserialize ( Response response , GenericType < T > returnType ) throws ApiException { // Handle file downloading. if ( returnType . equals ( File . class ) ) { @ SuppressWarnings ( "unchecked" ) T file = ( T ) downloadFileFromResponse ( response ) ; return file ; } String contentType = null ; List < Object > contentTypes = response . getHeaders ( ) . get ( "Content-Type" ) ; if ( contentTypes != null && ! contentTypes . isEmpty ( ) ) contentType = String . valueOf ( contentTypes . get ( 0 ) ) ; if ( contentType == null ) throw new ApiException ( 500 , "missing Content-Type in response" ) ; return response . readEntity ( returnType ) ; }


Input: Download file from the given response . [CODESPLIT] public File downloadFileFromResponse ( Response response ) throws ApiException { try { File file = prepareDownloadFile ( response ) ; Files . copy ( response . readEntity ( InputStream . class ) , file . toPath ( ) ) ; return file ; } catch ( IOException e ) { throw new ApiException ( e ) ; } }


Input: Invoke API by sending HTTP request with the given options . [CODESPLIT] public < T > T invokeAPI ( String path , String method , List < Pair > queryParams , Object body , Map < String , String > headerParams , Map < String , Object > formParams , String accept , String contentType , String [ ] authNames , GenericType < T > returnType ) throws ApiException { updateParamsForAuth ( new String [ ] { "token" , "apiKey" } /*authNames*/ , queryParams , headerParams ) ; // Not using `.target(this.basePath).path(path)` below, // to support (constant) query string in `path`, e.g. "/posts?draft=1" WebTarget target = httpClient . target ( this . basePath + path ) ; if ( queryParams != null ) { for ( Pair queryParam : queryParams ) { if ( queryParam . getValue ( ) != null ) { target = target . queryParam ( queryParam . getName ( ) , queryParam . getValue ( ) ) ; } } } Invocation . Builder invocationBuilder = target . request ( ) . accept ( accept ) ; for ( String key : headerParams . keySet ( ) ) { String value = headerParams . get ( key ) ; if ( value != null ) { invocationBuilder = invocationBuilder . header ( key , value ) ; } } for ( String key : defaultHeaderMap . keySet ( ) ) { if ( ! headerParams . containsKey ( key ) ) { String value = defaultHeaderMap . get ( key ) ; if ( value != null ) { invocationBuilder = invocationBuilder . header ( key , value ) ; } } } Entity < ? > entity = serialize ( body , formParams , contentType ) ; Response response = null ; if ( "GET" . equals ( method ) ) { response = invocationBuilder . get ( ) ; } else if ( "POST" . equals ( method ) ) { response = invocationBuilder . post ( entity ) ; } else if ( "PUT" . equals ( method ) ) { response = invocationBuilder . put ( entity ) ; } else if ( "DELETE" . equals ( method ) ) { response = invocationBuilder . delete ( ) ; } else { throw new ApiException ( 500 , "unknown method type " + method ) ; } statusCode = response . getStatusInfo ( ) . getStatusCode ( ) ; responseHeaders = buildResponseHeaders ( response ) ; if ( response . getStatus ( ) == Status . NO_CONTENT . getStatusCode ( ) ) { return null ; } else if ( response . getStatusInfo ( ) . getFamily ( ) . equals ( Status . Family . SUCCESSFUL ) ) { if ( returnType == null ) return null ; else return deserialize ( response , returnType ) ; } else { String message = "error" ; String respBody = null ; if ( response . hasEntity ( ) ) { try { respBody = String . valueOf ( response . readEntity ( String . class ) ) ; message = respBody ; } catch ( RuntimeException e ) { // e.printStackTrace(); } } throw new ApiException ( response . getStatus ( ) , message , buildResponseHeaders ( response ) , respBody ) ; } }


Input: Build the Client used to make HTTP requests . [CODESPLIT] private Client buildHttpClient ( boolean debugging ) { final ClientConfig clientConfig = new ClientConfig ( ) ; clientConfig . register ( MultiPartFeature . class ) ; clientConfig . register ( json ) ; clientConfig . register ( JacksonFeature . class ) ; if ( debugging ) { clientConfig . register ( LoggingFilter . class ) ; } return ClientBuilder . newClient ( clientConfig ) ; }


Input: createAccessControlEntity Creates an access control entity [CODESPLIT] public AccessControlEntityResponse createAccessControlEntity ( AccessControlEntity body ) throws ApiException { Object localVarPostBody = body ; // create path and map variables String localVarPath = "/models/accessControlEntities" . replaceAll ( "\\{format\\}" , "json" ) ; // query params List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; final String [ ] localVarAccepts = { "application/json" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { "application/json" } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { "token" } ; GenericType < AccessControlEntityResponse > localVarReturnType = new GenericType < AccessControlEntityResponse > ( ) { } ; return apiClient . invokeAPI ( localVarPath , "POST" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }


Input: updateDataModel Updates the data model for a workspace [CODESPLIT] public DataModelUpdateResponse updateDataModel ( DataModel body , Boolean force , String workspaceId ) throws ApiException { Object localVarPostBody = body ; // verify the required parameter 'body' is set if ( body == null ) { throw new ApiException ( 400 , "Missing the required parameter 'body' when calling updateDataModel" ) ; } // create path and map variables String localVarPath = "/models/dataModel" . replaceAll ( "\\{format\\}" , "json" ) ; // query params List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "force" , force ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "workspaceId" , workspaceId ) ) ; final String [ ] localVarAccepts = { "application/json" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { "application/json" } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { "token" } ; GenericType < DataModelUpdateResponse > localVarReturnType = new GenericType < DataModelUpdateResponse > ( ) { } ; return apiClient . invokeAPI ( localVarPath , "PUT" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }


Input: createFullExport Creates a full export of the workspace data or an export of the changelog depending on given type [CODESPLIT] public JobResponse createFullExport ( String exportType , String startDate , String endDate ) throws ApiException { Object localVarPostBody = null ; // create path and map variables String localVarPath = "/exports/fullExport" . replaceAll ( "\\{format\\}" , "json" ) ; // query params List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "exportType" , exportType ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "startDate" , startDate ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "endDate" , endDate ) ) ; final String [ ] localVarAccepts = { "application/json" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { "application/json" } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { } ; GenericType < JobResponse > localVarReturnType = new GenericType < JobResponse > ( ) { } ; return apiClient . invokeAPI ( localVarPath , "POST" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }


Input: getExports Lists all exports of the given type in the workspace of the authorized user [CODESPLIT] public ExportListResponse getExports ( String exportType , UUID userId , Integer pageSize , String cursor , String sorting , String sortDirection ) throws ApiException { Object localVarPostBody = null ; // create path and map variables String localVarPath = "/exports" . replaceAll ( "\\{format\\}" , "json" ) ; // query params List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "exportType" , exportType ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "userId" , userId ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "pageSize" , pageSize ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "cursor" , cursor ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "sorting" , sorting ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "sortDirection" , sortDirection ) ) ; final String [ ] localVarAccepts = { "application/json" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { } ; GenericType < ExportListResponse > localVarReturnType = new GenericType < ExportListResponse > ( ) { } ; return apiClient . invokeAPI ( localVarPath , "GET" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }


Input: Get state [CODESPLIT] @ ApiModelProperty ( example = "null" , required = true , value = "" ) public Map < String , Object > getState ( ) { return state ; }


Input: Specifies all urls needed to get an access token based on given host name and common url naming convention . [CODESPLIT] public ApiClientBuilder withTokenProviderHost ( String host ) { withOAuth2TokenUrl ( URI . create ( String . format ( "https://%s/services/mtm/v1/oauth2/token" , host ) ) ) ; return this ; }


Input: Sets your client Id and client Secret . [CODESPLIT] public ApiClientBuilder withClientCredentials ( String clientId , String clientSecret ) { this . clientId = clientId ; this . clientSecret = clientSecret ; return this ; }


Input: processGraphQLMultipart Processes GraphQL requests supporting multipart documents [CODESPLIT] public GraphQLResult processGraphQLMultipart ( String graphQLRequest , File file ) throws ApiException { Object localVarPostBody = null ; // verify the required parameter 'graphQLRequest' is set if ( graphQLRequest == null ) { throw new ApiException ( 400 , "Missing the required parameter 'graphQLRequest' when calling processGraphQLMultipart" ) ; } // verify the required parameter 'file' is set if ( file == null ) { throw new ApiException ( 400 , "Missing the required parameter 'file' when calling processGraphQLMultipart" ) ; } // create path and map variables String localVarPath = "/graphql/upload" . replaceAll ( "\\{format\\}" , "json" ) ; // query params List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; if ( graphQLRequest != null ) localVarFormParams . put ( "graphQLRequest" , graphQLRequest ) ; if ( file != null ) localVarFormParams . put ( "file" , file ) ; final String [ ] localVarAccepts = { "application/json" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { "multipart/form-data" } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { "token" } ; GenericType < GraphQLResult > localVarReturnType = new GenericType < GraphQLResult > ( ) { } ; return apiClient . invokeAPI ( localVarPath , "POST" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }


Input: Get params [CODESPLIT] @ ApiModelProperty ( example = "null" , required = true , value = "" ) public Map < String , String > getParams ( ) { return params ; }


Input: getBookmarks Retrieves all stored bookmarks a user can read . [CODESPLIT] public BookmarkListResponse getBookmarks ( String bookmarkType , String groupKey , String sharingType ) throws ApiException { Object localVarPostBody = null ; // verify the required parameter 'bookmarkType' is set if ( bookmarkType == null ) { throw new ApiException ( 400 , "Missing the required parameter 'bookmarkType' when calling getBookmarks" ) ; } // create path and map variables String localVarPath = "/bookmarks" . replaceAll ( "\\{format\\}" , "json" ) ; // query params List < Pair > localVarQueryParams = new ArrayList < Pair > ( ) ; Map < String , String > localVarHeaderParams = new HashMap < String , String > ( ) ; Map < String , Object > localVarFormParams = new HashMap < String , Object > ( ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "bookmarkType" , bookmarkType ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "groupKey" , groupKey ) ) ; localVarQueryParams . addAll ( apiClient . parameterToPairs ( "" , "sharingType" , sharingType ) ) ; final String [ ] localVarAccepts = { "application/json" } ; final String localVarAccept = apiClient . selectHeaderAccept ( localVarAccepts ) ; final String [ ] localVarContentTypes = { "application/json" } ; final String localVarContentType = apiClient . selectHeaderContentType ( localVarContentTypes ) ; String [ ] localVarAuthNames = new String [ ] { "token" } ; GenericType < BookmarkListResponse > localVarReturnType = new GenericType < BookmarkListResponse > ( ) { } ; return apiClient . invokeAPI ( localVarPath , "GET" , localVarQueryParams , localVarPostBody , localVarHeaderParams , localVarFormParams , localVarAccept , localVarContentType , localVarAuthNames , localVarReturnType ) ; }


Input: Maps Jena bindings defined by a variable name and a { @link org . apache . jena . graph . Node } to MarkLogic { @link com . marklogic . client . semantics . SPARQLQueryDefinition } bindings . [CODESPLIT] public static SPARQLQueryDefinition bindObject ( SPARQLQueryDefinition qdef , String variableName , Node objectNode ) { SPARQLBindings bindings = qdef . getBindings ( ) ; if ( objectNode . isURI ( ) ) { bindings . bind ( variableName , objectNode . getURI ( ) ) ; } else if ( objectNode . isLiteral ( ) ) { if ( ! "" . equals ( objectNode . getLiteralLanguage ( ) ) ) { String languageTag = objectNode . getLiteralLanguage ( ) ; bindings . bind ( variableName , objectNode . getLiteralLexicalForm ( ) , Locale . forLanguageTag ( languageTag ) ) ; } else if ( objectNode . getLiteralDatatype ( ) != null ) { try { String xsdType = objectNode . getLiteralDatatypeURI ( ) ; String fragment = new URI ( xsdType ) . getFragment ( ) ; bindings . bind ( variableName , objectNode . getLiteralLexicalForm ( ) , RDFTypes . valueOf ( fragment . toUpperCase ( ) ) ) ; } catch ( URISyntaxException e ) { throw new MarkLogicJenaException ( "Unrecognized binding type.  Use XSD only." , e ) ; } } else { // is this a hole, no type string? bindings . bind ( variableName , objectNode . getLiteralLexicalForm ( ) , RDFTypes . STRING ) ; } } qdef . setBindings ( bindings ) ; return qdef ; }


Input: / * [CODESPLIT] @ Override protected void addToDftGraph ( Node s , Node p , Node o ) { checkIsOpen ( ) ; Node s1 = skolemize ( s ) ; Node p1 = skolemize ( p ) ; Node o1 = skolemize ( o ) ; client . sinkQuad ( null , s1 , p1 , o1 ) ; }


Input: Merges triples into a graph on the MarkLogic server . mergeGraph () is NOT part of Jena s DatasetGraph interface . [CODESPLIT] public void mergeGraph ( Node graphName , Graph graph ) { checkIsOpen ( ) ; sync ( ) ; client . mergeGraph ( graphName . getURI ( ) , graph ) ; }


Input: Adds permissions to a graph . [CODESPLIT] public void addPermissions ( Node graphName , GraphPermissions permissions ) { checkIsOpen ( ) ; client . mergeGraphPermissions ( graphName . getURI ( ) , permissions ) ; }


Input: Sets the permissions on a graph . [CODESPLIT] public void writePermissions ( Node graphName , GraphPermissions permissions ) { checkIsOpen ( ) ; client . writeGraphPermissions ( graphName . getURI ( ) , permissions ) ; }


Input: Fluent setter for rulesets . [CODESPLIT] public MarkLogicDatasetGraph withRulesets ( SPARQLRuleset ... rulesets ) { if ( this . rulesets == null ) { this . rulesets = rulesets ; } else { Collection < SPARQLRuleset > collection = new ArrayList < SPARQLRuleset > ( ) ; collection . addAll ( Arrays . asList ( this . rulesets ) ) ; collection . addAll ( Arrays . asList ( rulesets ) ) ; this . rulesets = collection . toArray ( new SPARQLRuleset [ ] { } ) ; } return this ; }


Input: Close the connection and free resources [CODESPLIT] public void close ( ) { if ( writeBuffer != null ) { writeBuffer . cancel ( ) ; } if ( timer != null ) { timer . cancel ( ) ; } client = null ; }


Input: synchronization needed because of setting of page length [CODESPLIT] public synchronized InputStreamHandle executeSelect ( SPARQLQueryDefinition qdef , InputStreamHandle handle , Long offset , Long limit ) { if ( limit == null ) { this . sparqlQueryManager . clearPageLength ( ) ; } else { this . sparqlQueryManager . setPageLength ( limit ) ; } if ( offset != null ) { return this . sparqlQueryManager . executeSelect ( qdef , handle , offset , currentTransaction ) ; } else { return this . sparqlQueryManager . executeSelect ( qdef , handle , currentTransaction ) ; } }


Input: If timer is turned on ( periodicFlush = true in constructor ) this method puts a quad into the cache which is periodically sent to MarkLogic otherwise it sends the quad directly [CODESPLIT] public void sinkQuad ( Node g , Node s , Node p , Node o ) { if ( writeBuffer != null ) { writeBuffer . add ( g , s , p , o ) ; } else { Graph graph = GraphFactory . createDefaultGraph ( ) ; graph . add ( Triple . create ( s , p , o ) ) ; mergeGraph ( g . getURI ( ) , graph ) ; return ; } }


Input: Creates a MarkLogicDatasetGraph from an existing { @link com . marklogic . client . DatabaseClient } . [CODESPLIT] public static MarkLogicDatasetGraph createDatasetGraph ( DatabaseClient client ) { JenaDatabaseClient jenaClient = new JenaDatabaseClient ( client ) ; MarkLogicDatasetGraph datasetGraph = new MarkLogicDatasetGraph ( jenaClient ) ; MarkLogicQueryEngine . unregister ( ) ; MarkLogicQueryEngine . register ( ) ; MarkLogicUpdateEngine . unregister ( ) ; MarkLogicUpdateEngine . register ( ) ; return datasetGraph ; }


Input: Creates MarkLogicDatasetGraph from access parameters to a REST MarkLogic server . [CODESPLIT] static public MarkLogicDatasetGraph createDatasetGraph ( String host , int port , String user , String password , Authentication type ) { DatabaseClient client = DatabaseClientFactory . newClient ( host , port , user , password , type ) ; return MarkLogicDatasetGraphFactory . createDatasetGraph ( client ) ; }


Input: { [CODESPLIT] @ Override public String execute ( @ Nonnull String command , String ... arguments ) throws IOException , GMException , GMServiceException { PooledGMConnection connection = pool . borrowObject ( ) ; try { return connection . execute ( command , arguments ) ; } finally { pool . returnObject ( connection ) ; } }


Input: { [CODESPLIT] @ Override @ Nonnull public PooledGMConnection borrowObject ( ) throws GMServiceException { try { return super . borrowObject ( ) ; } catch ( GMServiceException e ) { throw e ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new GMServiceException ( e . getMessage ( ) , e ) ; } }


Input: { @inheritDoc } <p > This implementation delegates to super class but ensures that there is no other checked exception except { @link GMServiceException } will be thrown . [CODESPLIT] @ Override public void returnObject ( @ Nonnull PooledGMConnection connection ) throws GMServiceException { try { super . returnObject ( connection ) ; } catch ( GMServiceException e ) { throw e ; } catch ( RuntimeException e ) { throw e ; } catch ( Exception e ) { throw new GMServiceException ( e . getMessage ( ) , e ) ; } }


Input: { @inheritDoc } [CODESPLIT] @ Override protected int run ( @ Nonnull LinkedList < String > pArgs ) throws Exception { int rc ; try { String result = executor . execute ( pArgs ) ; if ( outputConsumer != null && result != null ) outputConsumer . consumeOutput ( stringToStream ( result ) ) ; rc = 0 ; } catch ( GMException e ) { if ( errorConsumer != null ) errorConsumer . consumeError ( stringToStream ( e . getMessage ( ) ) ) ; else throw e ; rc = 1 ; } finished ( rc ) ; return rc ; }


Input: Sets the path to GraphicsMagick executable . [CODESPLIT] public void setGMPath ( @ Nonnull String gmPath ) { if ( gmPath == null ) throw new NullPointerException ( "gmPath" ) ; factory = builder . buildFactory ( gmPath ) ; }


Input: { [CODESPLIT] @ Override public String execute ( @ Nonnull String command , String ... arguments ) throws GMException , GMServiceException , IOException { final GMConnection connection = getConnection ( ) ; try { return connection . execute ( command , arguments ) ; } finally { connection . close ( ) ; } }


Input: { [CODESPLIT] @ Override public String execute ( List < String > command ) throws GMException , GMServiceException , IOException { final GMConnection connection = getConnection ( ) ; try { return connection . execute ( command ) ; } finally { connection . close ( ) ; } }


Input: { @inheritDoc } [CODESPLIT] @ Override @ Nonnull public GMConnection getConnection ( ) throws GMServiceException { try { return new BasicGMConnection ( factory . getProcess ( ) ) ; } catch ( IOException e ) { throw new GMServiceException ( e . getMessage ( ) , e ) ; } }


Input: Limits the number of threads used by the GraphicsMagick process during execution . Note that no validation is made so ensure that the value is a non - positive integer presumably less than the maximum CPU cores on the host . [CODESPLIT] public GMOperation limitThreads ( final int threadsPerProcess ) { final List < String > args = getCmdArgs ( ) ; args . add ( "-limit" ) ; args . add ( "threads" ) ; args . add ( Integer . toString ( threadsPerProcess ) ) ; return this ; }


Input: Resize source to desired target dimensions using default resizing filter algorithm . [CODESPLIT] public GMOperation resize ( final int width , final int height , final Collection < GeometryAnnotation > annotations ) { final List < String > args = getCmdArgs ( ) ; args . add ( "-resize" ) ; args . add ( resample ( width , height , annotations ) ) ; return this ; }


Input: Rotates the image with empty triangles back - filled using default background color . [CODESPLIT] public GMOperation rotate ( final double degrees , final RotationAnnotation annotation ) { if ( annotation == null ) { throw new IllegalArgumentException ( "Rotation annotation must be defined" ) ; } final List < String > args = getCmdArgs ( ) ; args . add ( "-rotate" ) ; args . add ( String . format ( Locale . ENGLISH , "%.1f%s" , degrees , annotation . asAnnotation ( ) ) ) ; return this ; }


Input: Defines the gravity for geometry - based operations . See documentation for more details as this option works in conjunction with various options in different ways . [CODESPLIT] public GMOperation gravity ( final Gravity value ) { if ( value == null ) { throw new IllegalArgumentException ( "Gravity value must be defined" ) ; } gravity ( value . toString ( ) ) ; return this ; }


Input: Strips out ICC profiles . [CODESPLIT] public GMOperation stripProfiles ( ) { final List < String > args = getCmdArgs ( ) ; args . add ( "+profile" ) ; args . add ( "*" ) ; return this ; }


Input: Defines font for text overlay . [CODESPLIT] public GMOperation font ( final String style , final int size , final String color ) { if ( isBlank ( style ) ) { throw new IllegalArgumentException ( "Text font style must be defined" ) ; } if ( isBlank ( color ) ) { throw new IllegalArgumentException ( "Text font color must be defined" ) ; } font ( style ) ; pointsize ( size ) ; fill ( color ) ; return this ; }


Input: Draws text overlay on image with the upper - right corner defined by the { @code offsetX } and { @code offsetY } parameters . Note that { @link#gravity ( Gravity ) } will affect how the offset values are interpreted . [CODESPLIT] public GMOperation drawText ( final String text , final int offsetX , final int offsetY ) { if ( isBlank ( text ) ) { throw new IllegalArgumentException ( "Text string must be defined" ) ; } draw ( String . format ( Locale . ENGLISH , "text %d %d '%s'" , offsetX , offsetY , text ) ) ; return this ; }


Input: Specifies the source image to convert . [CODESPLIT] public GMOperation source ( final File file , @ CheckForNull final Integer width , @ CheckForNull final Integer height ) throws IOException { if ( file != null && ! file . exists ( ) ) { throw new IOException ( "Source file '" + file + "' does not exist" ) ; } if ( ( width != null ) && ( height != null ) && ( width > 0 ) && ( height > 0 ) ) { size ( width , height ) ; } return addImage ( file ) ; }


Input: Add image to operation . [CODESPLIT] public GMOperation addImage ( final File file ) { if ( file == null ) { throw new IllegalArgumentException ( "file must be defined" ) ; } getCmdArgs ( ) . add ( file . getPath ( ) ) ; return this ; }


Input: Add option - quality to the GraphicsMagick commandline ( see the documentation of GraphicsMagick for details ) . [CODESPLIT] public GMOperation quality ( double quality ) { final List < String > args = getCmdArgs ( ) ; args . add ( "-quality" ) ; args . add ( Double . toString ( quality ) ) ; return this ; }


Input: Time histogram . [CODESPLIT] public @ NotNull Histogram timeSeconds ( @ NotNull String name ) { return histograms . computeIfAbsent ( "vertx_" + name + "_time_seconds" , key -> register ( Histogram . build ( key , "Processing time in seconds" ) . labelNames ( "local_address" ) . create ( ) ) ) ; }


Input: HTTP requests gauge . [CODESPLIT] public @ NotNull Gauge httpRequests ( @ NotNull String name ) { return gauges . computeIfAbsent ( "vertx_" + name + "_requests" , key -> register ( Gauge . build ( key , "HTTP requests number" ) . labelNames ( "local_address" , "method" , "path" , "state" ) . create ( ) ) ) ; }


Input: Bytes counter . [CODESPLIT] public @ NotNull Counter bytes ( @ NotNull String name ) { return counters . computeIfAbsent ( "vertx_" + name + "_bytes" , key -> register ( Counter . build ( key , "Read/written bytes" ) . labelNames ( "local_address" , "type" ) . create ( ) ) ) ; }


Input: Parse a set of arguments and populate the target with the appropriate values . [CODESPLIT] public static List < String > parse ( Object target , String [ ] args ) { List < String > arguments = new ArrayList < String > ( ) ; arguments . addAll ( Arrays . asList ( args ) ) ; Class < ? > clazz ; if ( target instanceof Class ) { clazz = ( Class ) target ; } else { clazz = target . getClass ( ) ; try { BeanInfo info = Introspector . getBeanInfo ( clazz ) ; for ( PropertyDescriptor pd : info . getPropertyDescriptors ( ) ) { processProperty ( target , pd , arguments ) ; } } catch ( IntrospectionException e ) { // If its not a JavaBean we ignore it } } // Check fields of 'target' class and its superclasses for ( Class < ? > currentClazz = clazz ; currentClazz != null ; currentClazz = currentClazz . getSuperclass ( ) ) { for ( Field field : currentClazz . getDeclaredFields ( ) ) { processField ( target , field , arguments ) ; } } for ( String argument : arguments ) { if ( argument . startsWith ( "-" ) ) { throw new IllegalArgumentException ( "Invalid argument: " + argument ) ; } } return arguments ; }


Input: Generate usage information based on the target annotations . [CODESPLIT] public static void usage ( PrintStream errStream , Object target ) { Class < ? > clazz ; if ( target instanceof Class ) { clazz = ( Class ) target ; } else { clazz = target . getClass ( ) ; } errStream . println ( "Usage: " + clazz . getName ( ) ) ; for ( Class < ? > currentClazz = clazz ; currentClazz != null ; currentClazz = currentClazz . getSuperclass ( ) ) { for ( Field field : currentClazz . getDeclaredFields ( ) ) { fieldUsage ( errStream , target , field ) ; } } try { BeanInfo info = Introspector . getBeanInfo ( clazz ) ; for ( PropertyDescriptor pd : info . getPropertyDescriptors ( ) ) { propertyUsage ( errStream , target , pd ) ; } } catch ( IntrospectionException e ) { // If its not a JavaBean we ignore it } }


Input: Extracts and returns the time unit from a string . If the string doesn t include a unit it returns null . [CODESPLIT] public static TimeUnit extractTimeUnitFromString ( String timeString ) { timeString = timeString . toLowerCase ( ) ; if ( timeString . contains ( "minute" ) ) { return TimeUnit . MINUTES ; } else if ( timeString . contains ( "microsecond" ) ) { return TimeUnit . MICROSECONDS ; } else if ( timeString . contains ( "millisecond" ) ) { return TimeUnit . MILLISECONDS ; } else if ( timeString . contains ( "second" ) ) { return TimeUnit . SECONDS ; } else if ( timeString . contains ( "hour" ) ) { return TimeUnit . HOURS ; } else if ( timeString . toLowerCase ( ) . contains ( "day" ) ) { return TimeUnit . DAYS ; } else return null ; }


Input: Parse properties instead of String arguments . Any additional arguments need to be passed some other way . This is often used in a second pass when the property filename is passed on the command line . Because of required properties you must be careful to set them all in the property file . [CODESPLIT] public static void parse ( Object target , Properties arguments ) { Class clazz ; if ( target instanceof Class ) { clazz = ( Class ) target ; } else { clazz = target . getClass ( ) ; } for ( Field field : clazz . getDeclaredFields ( ) ) { processField ( target , field , arguments ) ; } try { BeanInfo info = Introspector . getBeanInfo ( clazz ) ; for ( PropertyDescriptor pd : info . getPropertyDescriptors ( ) ) { processProperty ( target , pd , arguments ) ; } } catch ( IntrospectionException e ) { // If its not a JavaBean we ignore it } }


Input: src : http : // stackoverflow . com / questions / 1399126 / java - util - zip - recreating - directory - structure [CODESPLIT] public static void zipDir ( File directory , File zipfile ) throws IOException { URI base = directory . toURI ( ) ; Deque < File > queue = new LinkedList < File > ( ) ; queue . push ( directory ) ; OutputStream out = new FileOutputStream ( zipfile ) ; Closeable res = out ; try { ZipOutputStream zout = new ZipOutputStream ( out ) ; res = zout ; while ( ! queue . isEmpty ( ) ) { directory = queue . pop ( ) ; for ( File kid : directory . listFiles ( ) ) { String name = base . relativize ( kid . toURI ( ) ) . getPath ( ) ; if ( kid . isDirectory ( ) ) { queue . push ( kid ) ; name = name . endsWith ( "/" ) ? name : name + "/" ; zout . putNextEntry ( new ZipEntry ( name ) ) ; } else { zout . putNextEntry ( new ZipEntry ( name ) ) ; copy ( kid , zout ) ; zout . closeEntry ( ) ; } } } } finally { res . close ( ) ; } }


Input: Execute a presentation file at a given url [CODESPLIT] static public void execute ( URL url ) throws SlideExecutionException { checkNotNull ( url ) ; ScreenRegion screenRegion = new DesktopScreenRegion ( ) ; Context context = new Context ( screenRegion ) ; execute ( url , context ) ; }


Input: Execute a presentation file at an URL using a specific { [CODESPLIT] static public void execute ( URL url , Context context ) throws SlideExecutionException { checkNotNull ( url ) ; checkNotNull ( context ) ; logger . debug ( "execute slides with context {}" , context ) ; SlidesReader reader = new PPTXSlidesReader ( ) ; List < Slide > slides ; try { slides = reader . read ( url ) ; } catch ( IOException e ) { throw new SlideExecutionException ( e ) ; } SlidesExecutor executor = new AutomationExecutor ( context ) ; executor . execute ( slides ) ; }


Input: Execute a presentation file [CODESPLIT] static public void execute ( File file ) throws SlideExecutionException { checkNotNull ( file ) ; try { execute ( file . toURI ( ) . toURL ( ) ) ; } catch ( MalformedURLException e ) { throw new SlideExecutionException ( e ) ; } }


Input: Interpret a presentation file as a list of executable actions [CODESPLIT] public static List < Action > interpret ( File file ) throws IOException { checkNotNull ( file ) ; Interpreter interpreter = new DefaultInterpreter ( ) ; SlidesReader reader = new PPTXSlidesReader ( ) ; List < Slide > slides ; slides = reader . read ( file ) ; List < Action > actions = Lists . newArrayList ( ) ; for ( Slide slide : slides ) { Action action = interpreter . interpret ( slide ) ; actions . add ( action ) ; logger . info ( "Action interpreted: {}" , action ) ; } return actions ; }


Input: detector . stop () ; [CODESPLIT] synchronized void setCurrentSlideIndex ( int i ) { this . index = i ; Slide slide = slides . get ( i ) ; viewer . setSlide ( slide ) ; viewer . setVisible ( true ) ; pending = true ; }


Input: Execute and wait for execution to finish [CODESPLIT] public void execute ( Context context ) throws ActionExecutionException { int count = 0 ; for ( Action action : getChildren ( ) ) { if ( ! isBackground ( action ) ) { count += 1 ; } } doneSignal = new CountDownLatch ( count ) ; List < Worker > workers = Lists . newArrayList ( ) ; for ( Action action : getChildren ( ) ) { final Context workerContxt = new Context ( context ) ; if ( ! isBackground ( action ) ) { Worker worker = new Worker ( action , workerContxt ) ; workers . add ( worker ) ; new Thread ( worker ) . start ( ) ; } else { Worker worker = new BackgroundWorker ( action , workerContxt ) ; new Thread ( worker ) . start ( ) ; } } try { doneSignal . await ( ) ; } catch ( InterruptedException e ) { } stop ( ) ; // if any of the worker did not succeed,  // rethrow the associated ActionExecutionException for ( Worker worker : workers ) { if ( ! worker . success ) { throw worker . exception ; } } }


Input: Argument : [CODESPLIT] public boolean step2 ( ) { Target target = new ImageTarget ( new File ( "image2.png" ) ) ; target . setMinScore ( DEFAULT_MINSCORE ) ; ScreenRegion loc = screenRegion . find ( target ) ; if ( loc != null ) { mouse . rightClick ( loc . getCenter ( ) ) ; return true ; } else { return false ; } }


Input: Argument : [CODESPLIT] public boolean step6 ( ) { Target target = new ImageTarget ( new File ( "image6.png" ) ) ; target . setMinScore ( DEFAULT_MINSCORE ) ; ScreenRegion loc = screenRegion . find ( target ) ; return loc == null ; }


Input: Argument : something to type [CODESPLIT] public boolean step7 ( ) { Target target = new ImageTarget ( new File ( "image7.png" ) ) ; target . setMinScore ( DEFAULT_MINSCORE ) ; ScreenRegion loc = screenRegion . find ( target ) ; if ( loc != null ) { mouse . click ( loc . getCenter ( ) ) ; keyboard . type ( "something to type" ) ; return true ; } else { return false ; } }


Input:
end constructor [CODESPLIT] private static boolean supportsDnD ( ) { // Static Boolean
 if ( supportsDnD == null ) { boolean support = false ; try { Class arbitraryDndClass = Class . forName ( "java.awt.dnd.DnDConstants" ) ; support = true ; } // end try
 catch ( Exception e ) { support = false ; } // end catch
 supportsDnD = new Boolean ( support ) ; } // end if: first time through
 return supportsDnD . booleanValue ( ) ; }


Input:
END 2007 - 09 - 12 Nathan Blomquist -- Linux ( KDE / Gnome ) support added . [CODESPLIT] private void makeDropTarget ( final java . io . PrintStream out , final java . awt . Component c , boolean recursive ) { // Make drop target
 final java . awt . dnd . DropTarget dt = new java . awt . dnd . DropTarget ( ) ; try { dt . addDropTargetListener ( dropListener ) ; } // end try
 catch ( java . util . TooManyListenersException e ) { e . printStackTrace ( ) ; log ( out , "FileDrop: Drop will not work due to previous error. Do you have another listener attached?" ) ; } // end catch
 // Listen for hierarchy changes and remove the drop target when the parent gets cleared out.
 c . addHierarchyListener ( new java . awt . event . HierarchyListener ( ) { public void hierarchyChanged ( java . awt . event . HierarchyEvent evt ) { log ( out , "FileDrop: Hierarchy changed." ) ; java . awt . Component parent = c . getParent ( ) ; if ( parent == null ) { c . setDropTarget ( null ) ; log ( out , "FileDrop: Drop target cleared from component." ) ; } // end if: null parent
 else { new java . awt . dnd . DropTarget ( c , dropListener ) ; log ( out , "FileDrop: Drop target added to component." ) ; } // end else: parent not null
 } // end hierarchyChanged
 } ) ; // end hierarchy listener
 if ( c . getParent ( ) != null ) new java . awt . dnd . DropTarget ( c , dropListener ) ; if ( recursive && ( c instanceof java . awt . Container ) ) { // Get the container
 java . awt . Container cont = ( java . awt . Container ) c ; // Get it's components
 java . awt . Component [ ] comps = cont . getComponents ( ) ; // Set it's components as listeners also
 for ( int i = 0 ; i < comps . length ; i ++ ) makeDropTarget ( out , comps [ i ] , recursive ) ; } // end if: recursively set components as listener
 }


Input:
Determine if the dragged data is a file list . [CODESPLIT] private boolean isDragOk ( final java . io . PrintStream out , final java . awt . dnd . DropTargetDragEvent evt ) { boolean ok = false ; // Get data flavors being dragged
 java . awt . datatransfer . DataFlavor [ ] flavors = evt . getCurrentDataFlavors ( ) ; // See if any of the flavors are a file list
 int i = 0 ; while ( ! ok && i < flavors . length ) { // BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
 // Is the flavor a file list?
 final DataFlavor curFlavor = flavors [ i ] ; if ( curFlavor . equals ( java . awt . datatransfer . DataFlavor . javaFileListFlavor ) || curFlavor . isRepresentationClassReader ( ) ) { ok = true ; } // END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added.
 i ++ ; } // end while: through flavors
 // If logging is enabled, show data flavors
 if ( out != null ) { if ( flavors . length == 0 ) log ( out , "FileDrop: no data flavors." ) ; for ( i = 0 ; i < flavors . length ; i ++ ) log ( out , flavors [ i ] . toString ( ) ) ; } // end if: logging enabled
 return ok ; } // end isDragOk
 /** Outputs <tt>message</tt> to <tt>out</tt> if it's not null. */ private static void log ( java . io . PrintStream out , String message ) { // Log message if requested
 if ( out != null ) out . println ( message ) ; } // end log
 /**
     * Removes the drag-and-drop hooks from the component and optionally
     * from the all children. You should call this if you add and remove
     * components after you've set up the drag-and-drop.
     * This will recursively unregister all components contained within
     * <var>c</var> if <var>c</var> is a {@link java.awt.Container}.
     *
     * @param c The component to unregister as a drop target
     * @since 1.0
     */ public static boolean remove  ( java . awt . Component c ) { return remove ( null , c , true ) ; } // end remove
 /**
     * Removes the drag-and-drop hooks from the component and optionally
     * from the all children. You should call this if you add and remove
     * components after you've set up the drag-and-drop.
     *
     * @param out Optional {@link java.io.PrintStream} for logging drag and drop messages
     * @param c The component to unregister
     * @param recursive Recursively unregister components within a container
     * @since 1.0
     */ public static boolean remove  ( java . io . PrintStream out , java . awt . Component c , boolean recursive ) { // Make sure we support dnd.
 if ( supportsDnD ( ) ) { log ( out , "FileDrop: Removing drag-and-drop hooks." ) ; c . setDropTarget ( null ) ; if ( recursive && ( c instanceof java . awt . Container ) ) { java . awt . Component [ ] comps = ( ( java . awt . Container ) c ) . getComponents ( ) ; for ( int i = 0 ; i < comps . length ; i ++ ) remove ( out , comps [ i ] , recursive ) ; return true ; } // end if: recursive
 else return false ; } // end if: supports DnD
 else return false ; } // end remove
 /* ********  I N N E R   I N T E R F A C E   L I S T E N E R  ******** */ /**
     * Implement this inner interface to listen for when files are dropped. For example
     * your class declaration may begin like this:
     *

     *      public class MyClass implements FileDrop.Listener
     *      ...
     *      public void filesDropped( java.io.File[] files )
     *      {
     *          ...
     *      }   // end filesDropped
     *      ...
     *

     *
     * @since 1.1
     */ public static interface Listener { /**
         * This method is called when files have been successfully dropped.
         *
         * @param files An array of <tt>File</tt>s that were dropped.
         * @since 1.0
         */ public abstract void filesDropped ( java . io . File [ ] files ) ; } // end inner-interface Listener
 /* ********  I N N E R   C L A S S  ******** */ /**
     * This is the event that is passed to the
     * {@link FileDropListener#filesDropped filesDropped(...)} method in
     * your {@link FileDropListener} when files are dropped onto
     * a registered drop target.
     *
     *
I'm releasing this code into the Public Domain. Enjoy.

     *
     * @author  Robert Harder
     * @author  rob@iharder.net
     * @version 1.2
     */ public static class Event extends java . util . EventObject { private java . io . File [ ] files ; /**
         * Constructs an {@link Event} with the array
         * of files that were dropped and the
         * {@link FileDrop} that initiated the event.
         *
         * @param files The array of files that were dropped
         * @source The event source
         * @since 1.1
         */ public Event ( java . io . File [ ] files , Object source ) { super ( source ) ; this . files = files ; } // end constructor
 /**
         * Returns an array of files that were dropped on a
         * registered drop target.
         *
         * @return array of files that were dropped
         * @since 1.1
         */ public java . io . File [ ] getFiles ( ) { return files ; } // end getFiles
 } // end inner class Event
 /* ********  I N N E R   C L A S S  ******** */ /**
     * At last an easy way to encapsulate your custom objects for dragging and dropping
     * in your Java programs!
     * When you need to create a {@link java.awt.datatransfer.Transferable} object,
     * use this class to wrap your object.
     * For example:
     *

     *      ...
     *      MyCoolClass myObj = new MyCoolClass();
     *      Transferable xfer = new TransferableObject( myObj );
     *      ...
     *

     * Or if you need to know when the data was actually dropped, like when you're
     * moving data out of a list, say, you can use the {@link TransferableObject.Fetcher}
     * inner class to return your object Just in Time.
     * For example:
     *

     *      ...
     *      final MyCoolClass myObj = new MyCoolClass();
     *
     *      TransferableObject.Fetcher fetcher = new TransferableObject.Fetcher()
     *      {   public Object getObject(){ return myObj; }
     *      }; // end fetcher
     *
     *      Transferable xfer = new TransferableObject( fetcher );
     *      ...
     *

     *
     * The {@link java.awt.datatransfer.DataFlavor} associated with
     * {@link TransferableObject} has the representation class
     * <tt>net.iharder.dnd.TransferableObject.class</tt> and MIME type
     * <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
     * This data flavor is accessible via the static
     * {@link #DATA_FLAVOR} property.
     *
     *
     *
I'm releasing this code into the Public Domain. Enjoy.

     *
     * @author  Robert Harder
     * @author  rob@iharder.net
     * @version 1.2
     */ public static class TransferableObject implements java . awt . datatransfer . Transferable { /**
         * The MIME type for {@link #DATA_FLAVOR} is
         * <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
         *
         * @since 1.1
         */ public final static String MIME_TYPE = "application/x-net.iharder.dnd.TransferableObject" ; /**
         * The default {@link java.awt.datatransfer.DataFlavor} for
         * {@link TransferableObject} has the representation class
         * <tt>net.iharder.dnd.TransferableObject.class</tt>
         * and the MIME type
         * <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
         *
         * @since 1.1
         */ public final static java . awt . datatransfer . DataFlavor DATA_FLAVOR = new java . awt . datatransfer . DataFlavor ( FileDrop . TransferableObject . class , MIME_TYPE ) ; private Fetcher fetcher ; private Object data ; private java . awt . datatransfer . DataFlavor customFlavor ; /**
         * Creates a new {@link TransferableObject} that wraps <var>data</var>.
         * Along with the {@link #DATA_FLAVOR} associated with this class,
         * this creates a custom data flavor with a representation class
         * determined from data.getClass() and the MIME type
         * <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
         *
         * @param data The data to transfer
         * @since 1.1
         */ public TransferableObject ( Object data ) { this . data = data ; this . customFlavor = new java . awt . datatransfer . DataFlavor ( data . getClass ( ) , MIME_TYPE ) ; } // end constructor
 /**
         * Creates a new {@link TransferableObject} that will return the
         * object that is returned by <var>fetcher</var>.
         * No custom data flavor is set other than the default
         * {@link #DATA_FLAVOR}.
         *
         * @see Fetcher
         * @param fetcher The {@link Fetcher} that will return the data object
         * @since 1.1
         */ public TransferableObject ( Fetcher fetcher ) { this . fetcher = fetcher ; } // end constructor
 /**
         * Creates a new {@link TransferableObject} that will return the
         * object that is returned by <var>fetcher</var>.
         * Along with the {@link #DATA_FLAVOR} associated with this class,
         * this creates a custom data flavor with a representation class <var>dataClass</var>
         * and the MIME type
         * <tt>application/x-net.iharder.dnd.TransferableObject</tt>.
         *
         * @see Fetcher
         * @param dataClass The {@link java.lang.Class} to use in the custom data flavor
         * @param fetcher The {@link Fetcher} that will return the data object
         * @since 1.1
         */ public TransferableObject ( Class dataClass , Fetcher fetcher ) { this . fetcher = fetcher ; this . customFlavor = new java . awt . datatransfer . DataFlavor ( dataClass , MIME_TYPE ) ; } // end constructor
 /**
         * Returns the custom {@link java.awt.datatransfer.DataFlavor} associated
         * with the encapsulated object or <tt>null</tt> if the {@link Fetcher}
         * constructor was used without passing a {@link java.lang.Class}.
         *
         * @return The custom data flavor for the encapsulated object
         * @since 1.1
         */ public java . awt . datatransfer . DataFlavor getCustomDataFlavor ( ) { return customFlavor ; } // end getCustomDataFlavor
 /* ********  T R A N S F E R A B L E   M E T H O D S  ******** */ /**
         * Returns a two- or three-element array containing first
         * the custom data flavor, if one was created in the constructors,
         * second the default {@link #DATA_FLAVOR} associated with
         * {@link TransferableObject}, and third the
         * {@link java.awt.datatransfer.DataFlavor.stringFlavor}.
         *
         * @return An array of supported data flavors
         * @since 1.1
         */ public java . awt . datatransfer . DataFlavor [ ] getTransferDataFlavors ( ) { if ( customFlavor != null ) return new java . awt . datatransfer . DataFlavor [ ] { customFlavor , DATA_FLAVOR , java . awt . datatransfer . DataFlavor . stringFlavor } ; // end flavors array
 else return new java . awt . datatransfer . DataFlavor [ ] { DATA_FLAVOR , java . awt . datatransfer . DataFlavor . stringFlavor } ; // end flavors array
 } // end getTransferDataFlavors
 /**
         * Returns the data encapsulated in this {@link TransferableObject}.
         * If the {@link Fetcher} constructor was used, then this is when
         * the {@link Fetcher#getObject getObject()} method will be called.
         * If the requested data flavor is not supported, then the
         * {@link Fetcher#getObject getObject()} method will not be called.
         *
         * @param flavor The data flavor for the data to return
         * @return The dropped data
         * @since 1.1
         */ public Object getTransferData ( java . awt . datatransfer . DataFlavor flavor ) throws java . awt . datatransfer . UnsupportedFlavorException , java . io . IOException { // Native object
 if ( flavor . equals ( DATA_FLAVOR ) ) return fetcher == null ? data : fetcher . getObject ( ) ; // String
 if ( flavor . equals ( java . awt . datatransfer . DataFlavor . stringFlavor ) ) return fetcher == null ? data . toString ( ) : fetcher . getObject ( ) . toString ( ) ; // We can't do anything else
 throw new java . awt . datatransfer . UnsupportedFlavorException ( flavor ) ; } // end getTransferData
 /**
         * Returns <tt>true</tt> if <var>flavor</var> is one of the supported
         * flavors. Flavors are supported using the equals(...) method.
         *
         * @param flavor The data flavor to check
         * @return Whether or not the flavor is supported
         * @since 1.1
         */ public boolean isDataFlavorSupported ( java . awt . datatransfer . DataFlavor flavor ) { // Native object
 if ( flavor . equals ( DATA_FLAVOR ) ) return true ; // String
 if ( flavor . equals ( java . awt . datatransfer . DataFlavor . stringFlavor ) ) return true ; // We can't do anything else
 return false ; } // end isDataFlavorSupported
 /* ********  I N N E R   I N T E R F A C E   F E T C H E R  ******** */ /**
         * Instead of passing your data directly to the {@link TransferableObject}
         * constructor, you may want to know exactly when your data was received
         * in case you need to remove it from its source (or do anyting else to it).
         * When the {@link #getTransferData getTransferData(...)} method is called
         * on the {@link TransferableObject}, the {@link Fetcher}'s
         * {@link #getObject getObject()} method will be called.
         *
         * @author Robert Harder
         * @copyright 2001
         * @version 1.1
         * @since 1.1
         */ public static interface Fetcher { /**
             * Return the object being encapsulated in the
             * {@link TransferableObject}.
             *
             * @return The dropped object
             * @since 1.1
             */ public abstract Object getObject ( ) ; } // end inner interface Fetcher
 } // end class TransferableObject
 }


Input: Execute and wait for execution to finish [CODESPLIT] public void execute ( Context context ) throws ActionExecutionException { Action action = checkNotNull ( getChild ( ) ) ; // start a timer that will set the timesup flag to true Timer timer = new Timer ( ) ; TimerTask task = new TimerTask ( ) { @ Override public void run ( ) { timesupFlag = true ; } } ; if ( timeout < Long . MAX_VALUE ) { timer . schedule ( task , timeout ) ; } ActionExecutionException exception = null ; timesupFlag = false ; stopFlag = false ; while ( ! timesupFlag && ! stopFlag ) { try { action . execute ( context ) ; return ; } catch ( ActionExecutionException e ) { exception = e ; } synchronized ( this ) { try { this . wait ( interval ) ; } catch ( InterruptedException e ) { } } } if ( timesupFlag ) { // execution does not succeed before timeout // rethrow the exception if ( exception != null ) throw exception ; } }


Input: sort a list of rectangles by their sizes in ascending order [CODESPLIT] static public List < Rectangle > sortBySize ( List < Rectangle > list ) { List < Rectangle > result = Lists . newArrayList ( ) ; Collections . sort ( list , new Comparator < Rectangle > ( ) { @ Override public int compare ( Rectangle r1 , Rectangle r2 ) { return ( r1 . height * r1 . width ) - ( r2 . height * r2 . width ) ; } } ) ; return result ; }


Input: } [CODESPLIT] private Action interpretAsBookmark ( Slide slide ) { SlideElement keywordElement = slide . select ( ) . isKeyword ( KeywordDictionary . BOOKMARK ) . first ( ) ; if ( keywordElement == null ) return null ; String text = keywordElement . getText ( ) ; if ( text . isEmpty ( ) ) { logger . error ( "No name is specified for the bookmark keyword" ) ; return null ; } slide . remove ( keywordElement ) ; BookmarkAction action = new BookmarkAction ( ) ; action . setName ( text ) ; return action ; }


Input: Create an object where each field represents an { @link Widget } that can be found and interacted with automatically [CODESPLIT] public static < T > T create ( Class < T > classToProxy ) { if ( ! classToProxy . isAnnotationPresent ( WidgetSlide . class ) ) // path to pptx file is not specified throw new RuntimeException ( "@Source annotation is missing in " + classToProxy + ". Need this to know where" + "to read slides" ) ; WidgetSlide source = classToProxy . getAnnotation ( WidgetSlide . class ) ; source . value ( ) ; //		if (source.url().isEmpty() > 0){ SlidesReader reader = new PPTXSlidesReader ( ) ; List < Slide > slides ; //		File file = new File(source.value()); try { if ( ! source . value ( ) . isEmpty ( ) ) { slides = reader . read ( new File ( source . value ( ) ) ) ; } else if ( ! source . url ( ) . isEmpty ( ) ) { slides = reader . read ( new URL ( source . url ( ) ) ) ; } else { throw new RuntimeException ( "@Source is not specified correctly" ) ; } } catch ( IOException e ) { // error in reading the slides from the given source  throw new RuntimeException ( e ) ; } DefaultSlideDriver driver ; if ( slides . size ( ) == 0 ) { // there is no slide found driver = new DefaultSlideDriver ( ) ; } else { driver = new DefaultSlideDriver ( slides . get ( 0 ) ) ; } T page = instantiatePage ( driver , classToProxy ) ; initElements ( driver , page ) ; return page ; }


Input: Render the given template string as a string based on the parameter values associated with this context [CODESPLIT] public String render ( String templateText ) { checkNotNull ( templateText ) ; ST st = new ST ( templateText ) ; for ( Map . Entry < String , Object > e : parameters . entrySet ( ) ) { st . add ( e . getKey ( ) , e . getValue ( ) ) ; } return st . render ( ) ; }


Input: Get the file of the slide rel for a slide number [CODESPLIT] File getSlideXMLRel ( int slideNumber ) { String filename = String . format ( "slide%d.xml.rels" , slideNumber ) ; return new File ( getRelationshipsDirectory ( ) , filename ) ; }


Input: Check the mouse action is within the screen region range . [CODESPLIT] protected boolean inRange ( NativeMouseEvent e ) { Rectangle r = screenRegion . getBounds ( ) ; r . x += screenOffsetX ; r . y += screenOffsetY ; int x = e . getX ( ) ; int y = e . getY ( ) ; return r . contains ( x , y ) ; }


Input: namely if they have the same x range they would intersect [CODESPLIT] public Selector overlapVerticallyWith ( final SlideElement element , final float minOverlapRatio ) { checkNotNull ( element ) ; final Rectangle r1 = element . getBounds ( ) ; r1 . x = 0 ; r1 . width = 1 ; elements = Collections2 . filter ( elements , new Predicate < SlideElement > ( ) { @ Override public boolean apply ( SlideElement e ) { if ( e == element ) { return false ; } if ( r1 . height == 0 ) { return false ; } Rectangle r2 = e . getBounds ( ) ; r2 . x = 0 ; r2 . width = 1 ; Rectangle intersection = r1 . intersection ( r2 ) ; float yOverlapRatio = 1f * intersection . height / r1 . height ; return yOverlapRatio > minOverlapRatio ; } } ) ; return this ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public void init ( ) { this . registerBeanDefinitionParser ( "inbound-channel-adapter" , new SnsInboundChannelAdapterParser ( ) ) ; this . registerBeanDefinitionParser ( "outbound-channel-adapter" , new SnsOutboundChannelAdapterParser ( ) ) ; this . registerBeanDefinitionParser ( "outbound-gateway" , new SnsOutboundGatewayParser ( ) ) ; this . registerBeanDefinitionParser ( "publish-subscribe-channel" , new SnsPublishSubscribeChannelParser ( ) ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public void init ( ) { this . registerBeanDefinitionParser ( "inbound-channel-adapter" , new SqsInboundChannelAdapterParser ( ) ) ; this . registerBeanDefinitionParser ( "outbound-channel-adapter" , new SqsOutboundChannelAdapterParser ( ) ) ; this . registerBeanDefinitionParser ( "outbound-gateway" , new SqsOutboundGatewayParser ( ) ) ; this . registerBeanDefinitionParser ( "channel" , new SqsChannelParser ( ) ) ; }


Input: Create a new { @link BeanDefinitionBuilder } for the class { @link SqsExecutor } . Initialize the wrapped { @link SqsExecutor } with common properties . [CODESPLIT] public static BeanDefinitionBuilder getSqsExecutorBuilder ( final Element element , final ParserContext parserContext ) { Assert . notNull ( element , "The provided element must not be null." ) ; Assert . notNull ( parserContext , "The provided parserContext must not be null." ) ; final BeanDefinitionBuilder sqsExecutorBuilder = BeanDefinitionBuilder . genericBeanDefinition ( SqsExecutor . class ) ; IntegrationNamespaceUtils . setValueIfAttributeDefined ( sqsExecutorBuilder , element , "queue-name" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( sqsExecutorBuilder , element , "queue" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( sqsExecutorBuilder , element , "aws-credentials-provider" ) ; IntegrationNamespaceUtils . setValueIfAttributeDefined ( sqsExecutorBuilder , element , "receive-message-wait-timeout" ) ; IntegrationNamespaceUtils . setValueIfAttributeDefined ( sqsExecutorBuilder , element , "region-id" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( sqsExecutorBuilder , element , "prefetch-count" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( sqsExecutorBuilder , element , "message-delay" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( sqsExecutorBuilder , element , "maximum-message-size" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( sqsExecutorBuilder , element , "message-retention-period" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( sqsExecutorBuilder , element , "visibility-timeout" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( sqsExecutorBuilder , element , "aws-client-configuration" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( sqsExecutorBuilder , element , "message-marshaller" ) ; IntegrationNamespaceUtils . setValueIfAttributeDefined ( sqsExecutorBuilder , element , "queue-url" ) ; return sqsExecutorBuilder ; }


Input: Create a new { @link BeanDefinitionBuilder } for the class { @link SnsExecutor } . Initialize the wrapped { @link SnsExecutor } with common properties . [CODESPLIT] public static BeanDefinitionBuilder getSnsExecutorBuilder ( final Element element , final ParserContext parserContext ) { Assert . notNull ( element , "The provided element must not be null." ) ; Assert . notNull ( parserContext , "The provided parserContext must not be null." ) ; final BeanDefinitionBuilder snsExecutorBuilder = BeanDefinitionBuilder . genericBeanDefinition ( SnsExecutor . class ) ; IntegrationNamespaceUtils . setValueIfAttributeDefined ( snsExecutorBuilder , element , "topic-name" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( snsExecutorBuilder , element , "sns-test-proxy" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( snsExecutorBuilder , element , "aws-credentials-provider" ) ; IntegrationNamespaceUtils . setValueIfAttributeDefined ( snsExecutorBuilder , element , "region-id" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( snsExecutorBuilder , element , "aws-client-configuration" ) ; IntegrationNamespaceUtils . setReferenceIfAttributeDefined ( snsExecutorBuilder , element , "message-marshaller" ) ; IntegrationNamespaceUtils . setValueIfAttributeDefined ( snsExecutorBuilder , element , "topic-arn" ) ; return snsExecutorBuilder ; }


Input: Verifies and sets the parameters . E . g . initializes the to be used [CODESPLIT] @ Override public void afterPropertiesSet ( ) { Assert . isTrue ( this . queueName != null || this . queueUrl != null , "Either queueName or queueUrl must not be empty." ) ; Assert . isTrue ( queue != null || awsCredentialsProvider != null , "Either queue or awsCredentialsProvider needs to be provided" ) ; if ( messageMarshaller == null ) { messageMarshaller = new JsonMessageMarshaller ( ) ; } if ( queue == null ) { if ( sqsClient == null ) { if ( awsClientConfiguration == null ) { sqsClient = new AmazonSQSClient ( awsCredentialsProvider ) ; } else { sqsClient = new AmazonSQSClient ( awsCredentialsProvider , awsClientConfiguration ) ; } } if ( regionId != null ) { sqsClient . setEndpoint ( String . format ( "sqs.%s.amazonaws.com" , regionId ) ) ; } if ( queueName != null ) { createQueueIfNotExists ( ) ; } addPermissions ( ) ; } }


Input: Executes the outbound Sqs Operation . [CODESPLIT] public Object executeOutboundOperation ( final Message < ? > message ) { try { String serializedMessage = messageMarshaller . serialize ( message ) ; if ( queue == null ) { SendMessageRequest request = new SendMessageRequest ( queueUrl , serializedMessage ) ; SendMessageResult result = sqsClient . sendMessage ( request ) ; log . debug ( "Message sent, Id:" + result . getMessageId ( ) ) ; } else { queue . add ( serializedMessage ) ; } } catch ( MessageMarshallerException e ) { log . error ( e . getMessage ( ) , e ) ; throw new MessagingException ( e . getMessage ( ) , e . getCause ( ) ) ; } return message . getPayload ( ) ; }


Input: Execute a retrieving ( polling ) Sqs operation . [CODESPLIT] public Message < ? > poll ( long timeout ) { Message < ? > message = null ; String payloadJSON = null ; com . amazonaws . services . sqs . model . Message qMessage = null ; int timeoutSeconds = ( timeout > 0 ? ( ( int ) ( timeout / 1000 ) ) : receiveMessageWaitTimeout ) ; destroyWaitTime = timeoutSeconds ; try { if ( queue == null ) { if ( prefetchQueue . isEmpty ( ) ) { ReceiveMessageRequest request = new ReceiveMessageRequest ( queueUrl ) . withWaitTimeSeconds ( timeoutSeconds ) . withMaxNumberOfMessages ( prefetchCount ) . withAttributeNames ( "All" ) ; ReceiveMessageResult result = sqsClient . receiveMessage ( request ) ; for ( com . amazonaws . services . sqs . model . Message sqsMessage : result . getMessages ( ) ) { prefetchQueue . offer ( sqsMessage ) ; } qMessage = prefetchQueue . poll ( ) ; } else { qMessage = prefetchQueue . remove ( ) ; } if ( qMessage != null ) { payloadJSON = qMessage . getBody ( ) ; // MD5 verification try { byte [ ] computedHash = Md5Utils . computeMD5Hash ( payloadJSON . getBytes ( "UTF-8" ) ) ; String hexDigest = new String ( Hex . encodeHex ( computedHash ) ) ; if ( ! hexDigest . equals ( qMessage . getMD5OfBody ( ) ) ) { payloadJSON = null ; // ignore this message log . warn ( "Dropped message due to MD5 checksum failure" ) ; } } catch ( Exception e ) { log . warn ( "Failed to verify MD5 checksum: " + e . getMessage ( ) , e ) ; } } } else { try { payloadJSON = queue . poll ( timeoutSeconds , TimeUnit . SECONDS ) ; } catch ( InterruptedException e ) { log . warn ( e . getMessage ( ) , e ) ; } } if ( payloadJSON != null ) { JSONObject qMessageJSON = new JSONObject ( payloadJSON ) ; if ( qMessageJSON . has ( SNS_MESSAGE_KEY ) ) { // posted from SNS payloadJSON = qMessageJSON . getString ( SNS_MESSAGE_KEY ) ; // XXX: other SNS attributes? } Message < ? > packet = null ; try { packet = messageMarshaller . deserialize ( payloadJSON ) ; } catch ( MessageMarshallerException marshallingException ) { throw new MessagingException ( marshallingException . getMessage ( ) , marshallingException . getCause ( ) ) ; } MessageBuilder < ? > builder = MessageBuilder . fromMessage ( packet ) ; if ( qMessage != null ) { builder . setHeader ( SqsHeaders . MSG_RECEIPT_HANDLE , qMessage . getReceiptHandle ( ) ) ; builder . setHeader ( SqsHeaders . AWS_MESSAGE_ID , qMessage . getMessageId ( ) ) ; for ( Map . Entry < String , String > e : qMessage . getAttributes ( ) . entrySet ( ) ) { if ( e . getKey ( ) . equals ( "ApproximateReceiveCount" ) ) { builder . setHeader ( SqsHeaders . RECEIVE_COUNT , Integer . valueOf ( e . getValue ( ) ) ) ; } else if ( e . getKey ( ) . equals ( "SentTimestamp" ) ) { builder . setHeader ( SqsHeaders . SENT_AT , new Date ( Long . valueOf ( e . getValue ( ) ) ) ) ; } else if ( e . getKey ( ) . equals ( "ApproximateFirstReceiveTimestamp" ) ) { builder . setHeader ( SqsHeaders . FIRST_RECEIVED_AT , new Date ( Long . valueOf ( e . getValue ( ) ) ) ) ; } else if ( e . getKey ( ) . equals ( "SenderId" ) ) { builder . setHeader ( SqsHeaders . SENDER_AWS_ID , e . getValue ( ) ) ; } else { builder . setHeader ( e . getKey ( ) , e . getValue ( ) ) ; } } } else { builder . setHeader ( SqsHeaders . MSG_RECEIPT_HANDLE , "" ) ; // to satisfy test conditions } message = builder . build ( ) ; } } catch ( JSONException e ) { log . warn ( e . getMessage ( ) , e ) ; } finally { destroyWaitTime = 0 ; } return message ; }


Input: Verifies and sets the parameters . E . g . initializes the to be used [CODESPLIT] @ Override public void afterPropertiesSet ( ) { Assert . isTrue ( this . topicName != null || this . topicArn != null , "Either topicName or topicArn must not be empty." ) ; Assert . isTrue ( snsTestProxy != null || awsCredentialsProvider != null , "Either snsTestProxy or awsCredentialsProvider needs to be provided" ) ; if ( messageMarshaller == null ) { messageMarshaller = new JsonMessageMarshaller ( ) ; } if ( snsTestProxy == null ) { if ( awsClientConfiguration == null ) { client = new AmazonSNSClient ( awsCredentialsProvider ) ; } else { client = new AmazonSNSClient ( awsCredentialsProvider , awsClientConfiguration ) ; } if ( regionId != null ) { client . setEndpoint ( String . format ( "sns.%s.amazonaws.com" , regionId ) ) ; } if ( topicArn == null ) { createTopicIfNotExists ( ) ; } processSubscriptions ( ) ; addPermissions ( ) ; } }


Input: Executes the outbound Sns Operation . [CODESPLIT] public Object executeOutboundOperation ( final Message < ? > message ) { try { String serializedMessage = messageMarshaller . serialize ( message ) ; if ( snsTestProxy == null ) { PublishRequest request = new PublishRequest ( ) ; PublishResult result = client . publish ( request . withTopicArn ( topicArn ) . withMessage ( serializedMessage ) ) ; log . debug ( "Published message to topic: " + result . getMessageId ( ) ) ; } else { snsTestProxy . dispatchMessage ( serializedMessage ) ; } } catch ( MessageMarshallerException e ) { log . error ( e . getMessage ( ) , e ) ; throw new MessagingException ( e . getMessage ( ) , e . getCause ( ) ) ; } return message . getPayload ( ) ; }


Input: e . g . / drivers / h2 / h2 - 1 . 3 . 162 . jar [CODESPLIT] static public String getManifestVersionNumber ( File file ) throws IOException { JarFile jar = new JarFile ( file ) ; Manifest manifest = jar . getManifest ( ) ; String versionNumber = null ; java . util . jar . Attributes attributes = manifest . getMainAttributes ( ) ; if ( attributes != null ) { Iterator it = attributes . keySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { Attributes . Name key = ( Attributes . Name ) it . next ( ) ; String keyword = key . toString ( ) ; if ( keyword . equals ( "Implementation-Version" ) || keyword . equals ( "Bundle-Version" ) ) { versionNumber = ( String ) attributes . get ( key ) ; break ; } } } jar . close ( ) ; if ( versionNumber == null || versionNumber . equals ( "" ) ) { return null ; } return versionNumber ; }


Input: Finds ( extracts if necessary ) a named executable for the runtime operating system and architecture . The executable should be a regular Java resource at the path / jne / [ os ] / [ arch ] / [ exe ] . The name of the file will be automatically adjusted for the target platform . For example on Windows to find the cat application this method will actually search for cat . exe . [CODESPLIT] synchronized static public File findExecutable ( String name , String targetName ) throws IOException { return findExecutable ( name , targetName , null ) ; }


Input: Finds ( or extracts ) a named executable for the runtime operating system and architecture . The executable should be a regular Java resource at the path / jne / [ os ] / [ arch ] / [ exe ] . [CODESPLIT] synchronized static public File findExecutable ( String name , Options options ) throws IOException { return findExecutable ( name , null , options ) ; }


Input: Finds ( or extracts ) a named executable for the runtime operating system and architecture . The executable should be a regular Java resource at the path / jne / [ os ] / [ arch ] / [ exe ] . [CODESPLIT] synchronized static public File findExecutable ( String name , String targetName , Options options ) throws IOException { if ( options == null ) { options = DEFAULT_OPTIONS ; } String fileName = options . createExecutableName ( name , options . getOperatingSystem ( ) ) ; String targetFileName = null ; if ( targetName != null ) { targetFileName = options . createExecutableName ( targetName , options . getOperatingSystem ( ) ) ; } // always search for specific arch first File file = find ( fileName , targetFileName , options , options . getOperatingSystem ( ) , options . getHardwareArchitecture ( ) ) ; // for x64 fallback to x86 if an exe was not found if ( file == null && options . isX32ExecutableFallback ( ) && options . getHardwareArchitecture ( ) == HardwareArchitecture . X64 ) { file = find ( fileName , targetFileName , options , options . getOperatingSystem ( ) , HardwareArchitecture . X32 ) ; } return file ; }


Input: Same as findExecutable but throws an exception if the executable was not found . [CODESPLIT] synchronized static public File requireExecutable ( String name , Options options ) throws IOException { return requireExecutable ( name , null , options ) ; }


Input: Same as findExecutable but throws an exception if the executable was not found . [CODESPLIT] synchronized static public File requireExecutable ( String name , String targetName , Options options ) throws IOException { File file = findExecutable ( name , targetName , options ) ; if ( file == null ) { throw new ResourceNotFoundException ( "Resource executable " + name + " not found" ) ; } return file ; }


Input: <p > Loads a dynamic library . Attempts to find ( extracts if necessary ) a named library for the runtime operating system and architecture . If the library was found as a resource and / or extracted it will then be loaded via System . load () . If the library was not found as a resource this method will simply fallback to System . loadLibrary () . Thus this method should be safe as a drop - in replacement for calls to System . loadLibrary () . < / p > <p > If including the library as a Java resource the resource path will be / jne / [ os ] / [ arch ] / [ lib ] . The name of the file will be automatically adjusted for the target platform . For example on Windows to find the cat library this method will search for cat . dll . On Linux to find the cat library this method will search for libcat . so . On Mac to find the cat library this method will search for libcat . dylib . < / p > [CODESPLIT] synchronized static public void loadLibrary ( String name , Options options , Integer majorVersion ) { // search for specific library File f = null ; try { f = findLibrary ( name , options , majorVersion ) ; } catch ( Exception e ) { log . debug ( "exception while finding library: " + e . getMessage ( ) ) ; throw new UnsatisfiedLinkError ( "Unable to cleanly find (or extract) library [" + name + "] as resource" ) ; } // temporarily prepend library path to load library if found if ( f != null ) { // since loading of dependencies of a library cannot dynamically happen // and the user would be required to provide a valid LD_LIBRARY_PATH when // launching the java process -- we don't need to do use loadLibrary // and can just tell it to load a specific library file log . debug ( "System.load(" + f . getAbsolutePath ( ) + ")" ) ; System . load ( f . getAbsolutePath ( ) ) ; } else { log . debug ( "falling back to System.loadLibrary(" + name + ")" ) ; // fallback to java method System . loadLibrary ( name ) ; } log . debug ( "library [" + name + "] loaded!" ) ; }


Input: Finds ( or extracts ) a named file . Will first attempt to locate the file for the runtime operating system and architecture then fallback to just the runtime operating system and finally fallback to the resource prefix . For example a file named resource . txt running on a JVM on x64 linux would search the following 3 resource paths : [CODESPLIT] synchronized static public File findFile ( String name , Options options ) throws IOException { if ( options == null ) { options = DEFAULT_OPTIONS ; } // 1. try with os & arch File file = JNE . find ( name , name , options , options . getOperatingSystem ( ) , options . getHardwareArchitecture ( ) ) ; // 2. try with os & any arch if ( file == null ) { file = JNE . find ( name , name , options , options . getOperatingSystem ( ) , HardwareArchitecture . ANY ) ; } // 3. try with os & any arch if ( file == null ) { file = JNE . find ( name , name , options , OperatingSystem . ANY , HardwareArchitecture . ANY ) ; } return file ; }


Input: Same as findFile but throws an exception if the file was not found . [CODESPLIT] synchronized static public File requireFile ( String name , Options options ) throws IOException { File file = findFile ( name , options ) ; if ( file == null ) { throw new ResourceNotFoundException ( "Resource file " + name + " not found" ) ; } return file ; }


Input: Underlying method used by findExecutable and loadLibrary to find and extract executables as needed . Although public it s NOT recommended to use this method unless you know what you re doing . [CODESPLIT] synchronized static public File find ( String fileName , String targetFileName , Options options , OperatingSystem os , HardwareArchitecture arch ) throws IOException { if ( options == null ) { options = DEFAULT_OPTIONS ; } if ( os == null || os == OperatingSystem . UNKNOWN ) { throw new ExtractException ( "Unable to detect operating system (e.g. Windows)" ) ; } if ( arch == null || arch == HardwareArchitecture . UNKNOWN ) { throw new ExtractException ( "Unable to detect hardware architecture (e.g. x86)" ) ; } if ( targetFileName == null ) { targetFileName = fileName ; } log . debug ( "finding fileName [" + fileName + "] targetFileName [" + targetFileName + "] os [" + os + "] arch [" + arch + "]..." ) ; //String resourcePath = options.getResourcePrefix() + "/" + os.name().toLowerCase() + "/" + arch.name().toLowerCase() + "/" + name; String resourcePath = options . createResourcePath ( os , arch , fileName ) ; log . debug ( "finding resource [" + resourcePath + "]" ) ; URL url = JNE . class . getResource ( resourcePath ) ; if ( url == null ) { log . debug ( "resource [" + resourcePath + "] not found" ) ; return null ; } // support for "file" and "jar" log . debug ( "resource found @ " + url ) ; if ( url . getProtocol ( ) . equals ( "jar" ) ) { log . debug ( "resource in jar; extracting file if necessary..." ) ; // in the case of where the app specifies an extract directory and // does not request deleteOnExit we need a way to detect if the  // executables changed from the previous app run -- we do this with // a very basic "hash" for an extracted resource. We basically combine // the path of the jar and manifest version of when the exe was extracted String versionHash = getJarVersionHashForResource ( url ) ; log . debug ( "version hash [" + versionHash + "]" ) ; // where should we extract the executable? File d = options . getExtractDir ( ) ; if ( d == null ) { d = getOrCreateTempDirectory ( options . isCleanupExtracted ( ) ) ; } else { // does the extract dir exist? if ( ! d . exists ( ) ) { d . mkdirs ( ) ; } if ( ! d . isDirectory ( ) ) { throw new ExtractException ( "Extract dir [" + d + "] is not a directory" ) ; } } log . debug ( "using dir [" + d + "]" ) ; // create both target exe and hash files File exeFile = new File ( d , targetFileName ) ; File exeHashFile = new File ( exeFile . getAbsolutePath ( ) + ".hash" ) ; // if file already exists verify its hash if ( exeFile . exists ( ) ) { log . debug ( "file already exists; verifying if hash matches" ) ; // verify the version hash still matches if ( ! exeHashFile . exists ( ) ) { // hash file missing -- we will force a new extract to be safe exeFile . delete ( ) ; } else { // hash file exists, verify it matches what we expect String existingHash = readFileToString ( exeHashFile ) ; if ( existingHash == null || ! existingHash . equals ( versionHash ) ) { log . debug ( "hash mismatch; deleting files; will freshly extract file" ) ; // hash mismatch -- will force an overwrite of both files exeFile . delete ( ) ; exeHashFile . delete ( ) ; } else { log . debug ( "hash matches; will use existing file" ) ; // hash match (exeFile and exeHashFile are both perrrrfect) //System.out.println("exe already extracted AND hash matched -- reusing same exe"); return exeFile ; } } } // does exe already exist? (previously extracted) if ( ! exeFile . exists ( ) ) { try { log . debug ( "extracting [" + url + "] to [" + exeFile + "]..." ) ; extractTo ( url , exeFile ) ; // set file to "executable" log . debug ( "setting to executable" ) ; exeFile . setExecutable ( true ) ; // create corrosponding hash file log . debug ( "writing hash file" ) ; writeStringToFile ( exeHashFile , versionHash ) ; // schedule files for deletion? if ( options . isCleanupExtracted ( ) ) { log . debug ( "scheduling file and hash for delete on exit" ) ; exeFile . deleteOnExit ( ) ; exeHashFile . deleteOnExit ( ) ; } } catch ( IOException e ) { log . debug ( "failed to extract file" ) ; throw new ExtractException ( "Unable to cleanly extract executable from jar" , e ) ; } } log . debug ( "returning [" + exeFile + "]" ) ; return exeFile ; } else if ( url . getProtocol ( ) . equals ( "file" ) ) { log . debug ( "resource in file" ) ; try { File exeFile = new File ( url . toURI ( ) ) ; if ( ! exeFile . canExecute ( ) ) { log . debug ( "setting file to executable" ) ; if ( ! exeFile . setExecutable ( true ) ) { log . debug ( "unable to cleanly set file to executable" ) ; throw new ExtractException ( "Executable was found but it cannot be set to execute [" + exeFile . getAbsolutePath ( ) + "]" ) ; } } log . debug ( "returning [" + exeFile + "]" ) ; return exeFile ; } catch ( URISyntaxException e ) { log . debug ( "uri syntax error" ) ; throw new ExtractException ( "Unable to create executable file from uri" , e ) ; } } else { throw new ExtractException ( "Unsupported executable resource protocol [" + url . getProtocol ( ) + "]" ) ; } }