private int getColor(int scrollX, int position) {
        int itemWithPadding = (int) (itemWidth + dividerSize);
        float proportion = Math.abs(((1f * scrollX % itemWithPadding) / 2) / (itemWithPadding / 2f));
        if(proportion > .5) {
            proportion = (proportion - .5f);
        } else {
            proportion = .5f - proportion;
        }
        proportion *= 2;

        int defaultColor;
        int selectedColor;

        if(pressedItem == position) {
            defaultColor = textColor.getColorForState(new int[] { android.R.attr.state_pressed }, textColor.getDefaultColor());
            selectedColor = textColor.getColorForState(new int[] { android.R.attr.state_pressed, android.R.attr.state_selected }, defaultColor);
        } else {
            defaultColor = textColor.getDefaultColor();
            selectedColor = textColor.getColorForState(new int[] { android.R.attr.state_selected }, defaultColor);
        }
        return (Integer) new ArgbEvaluator().evaluate(proportion, selectedColor, defaultColor);
    }

private int getColor ( int scrollX , int position ) { int itemWithPadding = ( int ) ( itemWidth + dividerSize ) ; float proportion = Math . abs ( ( ( 1f * scrollX % itemWithPadding ) / 2 ) / ( itemWithPadding / 2f ) ) ; if ( proportion > .5 ) { proportion = ( proportion - .5f ) ; } else { proportion = .5f - proportion ; } proportion *= 2 ; int defaultColor ; int selectedColor ; if ( pressedItem == position ) { defaultColor = textColor . getColorForState ( new int [ ] { android . R . attr . state_pressed } , textColor . getDefaultColor ( ) ) ; selectedColor = textColor . getColorForState ( new int [ ] { android . R . attr . state_pressed , android . R . attr . state_selected } , defaultColor ) ; } else { defaultColor = textColor . getDefaultColor ( ) ; selectedColor = textColor . getColorForState ( new int [ ] { android . R . attr . state_selected } , defaultColor ) ; } return ( Integer ) new ArgbEvaluator ( ) . evaluate ( proportion , selectedColor , defaultColor ) ; }

Calculates color for specific position on time picker
@param scrollX
@return


private void setTextSize(float size) {
        if(size != textPaint.getTextSize()) {
            textPaint.setTextSize(size);

            requestLayout();
            invalidate();
        }
    }

private void setTextSize ( float size ) { if ( size != textPaint . getTextSize ( ) ) { textPaint . setTextSize ( size ) ; requestLayout ( ) ; invalidate ( ) ; } }

Sets text size for items
@param size New item text size in px.


private int getInBoundsX(int x) {

        if(x < 0) {
            x = 0;
        } else if(x > ((itemWidth + (int) dividerSize) * (values.length - 1))) {
            x = ((itemWidth + (int) dividerSize) * (values.length - 1));
        }
        return x;
    }

private int getInBoundsX ( int x ) { if ( x < 0 ) { x = 0 ; } else if ( x > ( ( itemWidth + ( int ) dividerSize ) * ( values . length - 1 ) ) ) { x = ( ( itemWidth + ( int ) dividerSize ) * ( values . length - 1 ) ) ; } return x ; }

Calculates x scroll position that is still in range of view scroller
@param x Scroll position to calculate.
@return {param x} if is within bounds of over scroller, otherwise it will return min/max
value of scoll position.


private String getIntro() {
        try {
            InputStream introStream = MyRemoteLibrary.class.getResourceAsStream("__intro__.txt");
            StringWriter writer = new StringWriter();
            IOUtils.copy(introStream, writer, Charset.defaultCharset());
            return writer.toString();
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

private String getIntro ( ) { try { InputStream introStream = MyRemoteLibrary . class . getResourceAsStream ( "__intro__.txt" ) ; StringWriter writer = new StringWriter ( ) ; IOUtils . copy ( introStream , writer , Charset . defaultCharset ( ) ) ; return writer . toString ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }

The introduction is stored in a text file resource because it is easier to edit than String constants.

The introduction is stored in a text file resource because it is easier to edit than String constants .


public String[] get_keyword_names() {
        try {
            String[] names = servlet.getLibrary().getKeywordNames();
            if (names == null || names.length == 0)
                throw new RuntimeException("No keywords found in the test library");
            String[] newNames = Arrays.copyOf(names, names.length + 1);
            newNames[names.length] = "stop_remote_server";
            return newNames;
        } catch (Throwable e) {
            log.warn("", e);
            throw new RuntimeException(e);
        }
    }

public
String
[
]
get_keyword_names
(
)
{
try
{
String
[
]
names
=
servlet
.
getLibrary
(
)
.
getKeywordNames
(
)
;
if
(
names
==
||
names
.
length
==
0
)
throw
new
RuntimeException
(
"No keywords found in the test library"
)
;
String
[
]
newNames
=
Arrays
.
copyOf
(
names
,
names
.
length
+
1
)
;
newNames
[
names
.
length
]
=
"stop_remote_server"
;
return
newNames
;
}
catch
(
Throwable
e
)
{
log
.
warn
(
""
,
e
)
;
throw
new
RuntimeException
(
e
)
;
}
}

Get an array containing the names of the keywords that the library
implements.

@return String array containing keyword names in the library

Get an array containing the names of the keywords that the library implements .


public String[] get_keyword_arguments(String keyword) {
        if (keyword.equalsIgnoreCase("stop_remote_server")) {
            return new String[0];
        }
        try {
            String[] args = servlet.getLibrary().getKeywordArguments(keyword);
            return args == null ? new String[0] : args;
        } catch (Throwable e) {
            log.warn("", e);
            throw new RuntimeException(e);
        }
    }

public String [ ] get_keyword_arguments ( String keyword ) { if ( keyword . equalsIgnoreCase ( "stop_remote_server" ) ) { return new String [ 0 ] ; } try { String [ ] args = servlet . getLibrary ( ) . getKeywordArguments ( keyword ) ; return args == null ? new String [ 0 ] : args ; } catch ( Throwable e ) { log . warn ( "" , e ) ; throw new RuntimeException ( e ) ; } }

Get an array of argument specifications for the given keyword.

@param keyword
The keyword to lookup.
@return A string array of argument specifications for the given keyword.

Get an array of argument specifications for the given keyword .


public String get_keyword_documentation(String keyword) {
        if (keyword.equalsIgnoreCase("stop_remote_server")) {
            return "Stops the remote server.\n\nThe server may be configured so that users cannot stop it.";
        }
        try {
            String doc = servlet.getLibrary().getKeywordDocumentation(keyword);
            return doc == null ? "" : doc;
        } catch (Throwable e) {
            log.warn("", e);
            throw new RuntimeException(e);
        }
    }

Get documentation for given keyword.

@param keyword
The keyword to get documentation for.
@return A documentation string for the given keyword.


public static void main(String[] args) throws Exception {
        configureLogging();
        CommandLineHelper helper = new CommandLineHelper(args);
        if (helper.getHelpRequested()) {
            System.out.print(helper.getUsage());
            System.exit(0);
        }
        RemoteServer remoteServer = new RemoteServer();
        String error = helper.getError();
        if (error == null) {
            try {
                for (String path : helper.getLibraryMap().keySet())
                    remoteServer.putLibrary(path, helper.getLibraryMap().get(path));
            } catch (IllegalPathException e) {
                error = e.getMessage();
            }
        }
        if (error != null) {
            System.out.println("Error: " + error);
            System.out.println();
            System.out.println(helper.getUsage());
            System.exit(1);
        }
        remoteServer.setPort(helper.getPort());
        remoteServer.setAllowStop(helper.getAllowStop());
        remoteServer.setHost(helper.getHost());
        remoteServer.start();
    }

public
static
void
main
(
String
[
]
args
)
throws
Exception
{
configureLogging
(
)
;
CommandLineHelper
helper
=
new
CommandLineHelper
(
args
)
;
if
(
helper
.
getHelpRequested
(
)
)
{
System
.
out
.
print
(
helper
.
getUsage
(
)
)
;
System
.
exit
(
0
)
;
}
RemoteServer
remoteServer
=
new
RemoteServer
(
)
;
String
error
=
helper
.
getError
(
)
;
if
(
error
==
)
{
try
{
for
(
String
path
:
helper
.
getLibraryMap
(
)
.
keySet
(
)
)
remoteServer
.
putLibrary
(
path
,
helper
.
getLibraryMap
(
)
.
get
(
path
)
)
;
}
catch
(
IllegalPathException
e
)
{
error
=
e
.
getMessage
(
)
;
}
}
if
(
error
!=
)
{
System
.
out
.
println
(
"Error: "
+
error
)
;
System
.
out
.
println
(
)
;
System
.
out
.
println
(
helper
.
getUsage
(
)
)
;
System
.
exit
(
1
)
;
}
remoteServer
.
setPort
(
helper
.
getPort
(
)
)
;
remoteServer
.
setAllowStop
(
helper
.
getAllowStop
(
)
)
;
remoteServer
.
setHost
(
helper
.
getHost
(
)
)
;
remoteServer
.
start
(
)
;
}

Main method for command line usage.

@param args
@throws Exception


public void stop(int timeoutMS) throws Exception {
        log.info("Robot Framework remote server stopping");
        if (timeoutMS > 0) {
            server.setGracefulShutdown(timeoutMS);
            Thread stopper = new Thread() {
                @Override
                public void run() {
                    try {
                        server.stop();
                    } catch (Throwable e) {
                        log.error(String.format("Failed to stop the server: %s", e.getMessage()), e);
                    }
                }
            };
            stopper.start();
        } else {
            server.stop();
        }
    }

A non-blocking method for stopping the remote server that allows requests
to complete within the given timeout before shutting down the server. New
connections will not be accepted after calling this.

@param timeoutMS
the milliseconds to wait for existing request to complete
before stopping the server

A non - blocking method for stopping the remote server that allows requests to complete within the given timeout before shutting down the server . New connections will not be accepted after calling this .


public void start() throws Exception {
        log.info("Robot Framework remote server starting");
        server.start();
        log.info(String.format("Robot Framework remote server started on port %d.", getLocalPort()));
    }

Starts the remote server. Add test libraries first before calling this.

@throws Exception

Starts the remote server . Add test libraries first before calling this .


public String convertPropertiesFromFileToJson(String pathToFile, String... includeDomainKeys) throws ReadInputException, ParsePropertiesException {
        return convertPropertiesFromFileToJson(new File(pathToFile), includeDomainKeys);
    }

public String convertPropertiesFromFileToJson ( String pathToFile , String ... includeDomainKeys ) throws ReadInputException , ParsePropertiesException { return convertPropertiesFromFileToJson ( new File ( pathToFile ) , includeDomainKeys ) ; }

Generate Json by given path to file with properties with only included domain keys.

@param pathToFile        path to File
@param includeDomainKeys domain head keys which should be parsed to json

example properties:

object1.field1=value1

object1.field2=value2

someObject2.field2=value3

filter "object1"

will parse only nested domain for "object1"

@return simple String with json
@throws ReadInputException       when cannot find file
@throws ParsePropertiesException when structure of properties is not compatible with json structure

Generate Json by given path to file with properties with only included domain keys .


public String convertPropertiesFromFileToJson(File file, String... includeDomainKeys) throws ReadInputException, ParsePropertiesException {
        try {
            InputStream targetStream = new FileInputStream(file);
            return convertToJson(targetStream, includeDomainKeys);
        } catch (FileNotFoundException e) {
            throw new ReadInputException(e);
        }
    }

public String convertPropertiesFromFileToJson ( File file , String ... includeDomainKeys ) throws ReadInputException , ParsePropertiesException { try { InputStream targetStream = new FileInputStream ( file ) ; return convertToJson ( targetStream , includeDomainKeys ) ; } catch ( FileNotFoundException e ) { throw new ReadInputException ( e ) ; } }

Generate Json by given file with properties with only included domain keys.

@param file              file with properties
@param includeDomainKeys domain head keys which should be parsed to json

example properties:

object1.field1=value1

object1.field2=value2

someObject2.field2=value3

filter "object1"

will parse only nested domain for "object1"

@return simple String with json
@throws ReadInputException       when cannot find file
@throws ParsePropertiesException when structure of properties is not compatible with json structure

Generate Json by given file with properties with only included domain keys .


public String convertToJson(InputStream inputStream, String... includeDomainKeys) throws ReadInputException, ParsePropertiesException {
        return convertToJson(inputStreamToProperties(inputStream), includeDomainKeys);
    }

public String convertToJson ( InputStream inputStream , String ... includeDomainKeys ) throws ReadInputException , ParsePropertiesException { return convertToJson ( inputStreamToProperties ( inputStream ) , includeDomainKeys ) ; }

generate Json by given InputStream and given filter.

@param inputStream       InputStream with properties
@param includeDomainKeys domain head keys which should be parsed to json

example properties:

object1.field1=value1

object1.field2=value2

someObject2.field2=value3

filter "object1"

will parse only nested domain for "object1"

@return simple String with json
@throws ReadInputException       when cannot find file
@throws ParsePropertiesException when structure of properties is not compatible with json structure

generate Json by given InputStream and given filter .


public String convertToJson(Properties properties) throws ParsePropertiesException {
        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            if (!(entry.getKey() instanceof String)) {
                throw new ParsePropertiesException(format(PROPERTY_KEY_NEEDS_TO_BE_STRING_TYPE,
                                                          entry.getKey().getClass(),
                                                          entry.getKey() == null ? "null" : entry.getKey()));
            }
        }
        return convertFromValuesAsObjectMap(propertiesToMap(properties));
    }

public String convertToJson ( Properties properties ) throws ParsePropertiesException { for ( Map . Entry < Object , Object > entry : properties . entrySet ( ) ) { if ( ! ( entry . getKey ( ) instanceof String ) ) { throw new ParsePropertiesException ( format ( PROPERTY_KEY_NEEDS_TO_BE_STRING_TYPE , entry . getKey ( ) . getClass ( ) , entry . getKey ( ) == null ? "null" : entry . getKey ( ) ) ) ; } } return convertFromValuesAsObjectMap ( propertiesToMap ( properties ) ) ; }

generate Json by given Java Properties

@param properties Java Properties
@return simple String with json
@throws ParsePropertiesException when structure of properties is not compatible with json structure


public String convertToJson(Map<String, String> properties) throws ParsePropertiesException {
        return convertFromValuesAsObjectMap(stringValueMapToObjectValueMap(properties));

    }

public String convertToJson ( Map < String , String > properties ) throws ParsePropertiesException { return convertFromValuesAsObjectMap ( stringValueMapToObjectValueMap ( properties ) ) ; }

generate Json by given Map<String,String>

@param properties Java Map with properties
@return simple String with json
@throws ParsePropertiesException when structure of properties is not compatible with json structure

generate Json by given Map&lt ; String String&gt ;


public String convertFromValuesAsObjectMap(Map<String, Object> properties) throws ParsePropertiesException {
        ObjectJsonType coreObjectJsonType = new ObjectJsonType();
        for (String propertiesKey : getAllKeysFromProperties(properties)) {
            addFieldsToJsonObject(properties, coreObjectJsonType, propertiesKey);
        }
        return prettifyOfJson(coreObjectJsonType.toStringJson());
    }

public String convertFromValuesAsObjectMap ( Map < String , Object > properties ) throws ParsePropertiesException { ObjectJsonType coreObjectJsonType = new ObjectJsonType ( ) ; for ( String propertiesKey : getAllKeysFromProperties ( properties ) ) { addFieldsToJsonObject ( properties , coreObjectJsonType , propertiesKey ) ; } return prettifyOfJson ( coreObjectJsonType . toStringJson ( ) ) ; }

generate Json by given Map<String,Object>

@param properties Java Map with properties
@return simple String with json
@throws ParsePropertiesException when structure of properties is not compatible with json structure

generate Json by given Map&lt ; String Object&gt ;


public String convertFromValuesAsObjectMap(Map<String, Object> properties, String... includeDomainKeys) throws ParsePropertiesException {
        Map<String, Object> filteredProperties = new HashMap<>();
        for (String key : properties.keySet()) {
            for (String requiredKey : includeDomainKeys) {
                checkKey(properties, filteredProperties, key, requiredKey);
            }
        }
        return convertFromValuesAsObjectMap(filteredProperties);
    }

public String convertFromValuesAsObjectMap ( Map < String , Object > properties , String ... includeDomainKeys ) throws ParsePropertiesException { Map < String , Object > filteredProperties = new HashMap <> ( ) ; for ( String key : properties . keySet ( ) ) { for ( String requiredKey : includeDomainKeys ) { checkKey ( properties , filteredProperties , key , requiredKey ) ; } } return convertFromValuesAsObjectMap ( filteredProperties ) ; }

generate Json by given Map<String,String> and given filter

@param properties        Java Map with properties
@param includeDomainKeys domain head keys which should be parsed to json

example properties:

object1.field1=value1

object1.field2=value2

someObject2.field2=value3

filter "object1"

will parse only nested domain for "object1"

@return simple String with json
@throws ParsePropertiesException when structure of properties is not compatible with json structure

generate Json by given Map&lt ; String String&gt ; and given filter


public String convertToJson(Properties properties, String... includeDomainKeys) throws ParsePropertiesException {
        return convertFromValuesAsObjectMap(propertiesToMap(properties), includeDomainKeys);
    }

public String convertToJson ( Properties properties , String ... includeDomainKeys ) throws ParsePropertiesException { return convertFromValuesAsObjectMap ( propertiesToMap ( properties ) , includeDomainKeys ) ; }

generate Json by given Java Properties and given filter

@param properties        Java Properties
@param includeDomainKeys domain head keys which should be parsed to json

example properties:

object1.field1=value1

object1.field2=value2

someObject2.field2=value3

filter "object1"

will parse only nested domain for "object1"

@param includeDomainKeys domain head keys which should be parsed to json
@return Simple String with json
@throws ParsePropertiesException when structure of properties is not compatible with json structure


protected static int getShadowRadius(Drawable shadow, Drawable circle) {
        int radius = 0;

        if (shadow != null && circle != null) {
            Rect rect = new Rect();
            radius = (circle.getIntrinsicWidth() + (shadow.getPadding(rect) ? rect.left + rect.right : 0)) / 2;
        }

        return Math.max(1, radius);
    }

protected static int getShadowRadius ( Drawable shadow , Drawable circle ) { int radius = 0 ; if ( shadow != null && circle != null ) { Rect rect = new Rect ( ) ; radius = ( circle . getIntrinsicWidth ( ) + ( shadow . getPadding ( rect ) ? rect . left + rect . right : 0 ) ) / 2 ; } return Math . max ( 1 , radius ) ; }

Calculates required radius of shadow.

@param shadow underlay drawable
@param circle overlay drawable
@return calculated radius, always >= 1


public static Builder<OcspFetcher> builder() {
        return new Builder<>(new BuildHandler<OcspFetcher>() {
            @Override
            public OcspFetcher build(Properties properties) {
                return new ApacheOcspFetcher(properties);
            }
        });
    }

public static Builder < OcspFetcher > builder ( ) { return new Builder <> ( new BuildHandler < OcspFetcher > ( ) { @ Override public OcspFetcher build ( Properties properties ) { return new ApacheOcspFetcher ( properties ) ; } } ) ; }

Builder to create an instance of OcspFetcher using Apache HttpClient for connectivity.

@return Prepared fetcher.

Builder to create an instance of OcspFetcher using Apache HttpClient for connectivity .


protected X509Certificate findIntermediate(X509Certificate certificate) throws OcspException {
        for (X509Certificate issuer : properties.get(INTERMEDIATES))
            if (issuer.getSubjectX500Principal().equals(certificate.getIssuerX500Principal()))
                return issuer;

        throw new OcspException("Unable to find issuer '%s'.", certificate.getIssuerX500Principal().getName());
    }

protected
X509Certificate
findIntermediate
(
X509Certificate
certificate
)
throws
OcspException
{
for
(
X509Certificate
issuer
:
properties
.
get
(
INTERMEDIATES
)
)
if
(
issuer
.
getSubjectX500Principal
(
)
.
equals
(
certificate
.
getIssuerX500Principal
(
)
)
)
return
issuer
;
throw
new
OcspException
(
"Unable to find issuer '%s'."
,
certificate
.
getIssuerX500Principal
(
)
.
getName
(
)
)
;
}

Method for finding issuer by provided issuers in properties given an issued certificate.

@param certificate Issued certificate.
@return Issuer of the issued certificate.
@throws OcspException Thrown when no issuer is found.

Method for finding issuer by provided issuers in properties given an issued certificate .


@Override
    public void execute() throws MojoExecutionException {
        // First, if filtering is enabled, perform that using the Maven magic
        if (applyFiltering) {
            performMavenPropertyFiltering(new File(inputDirectory), filteredOutputDirectory, getInputEncoding());
            inputDirectory = filteredOutputDirectory.getAbsolutePath();
        }

        getLog().info("Pre-processing markdown files from input directory: " + inputDirectory);
        preprocessMarkdownFiles(new File(inputDirectory));

        if (!markdownDTOs.isEmpty()) {
            getLog().info("Process Pegdown extension options");
            int options = getPegdownExtensions(pegdownExtensions);
            final Map<String, Attributes> attributesMap = processAttributes(attributes);

            getLog().info("Parse Markdown to HTML");
            processMarkdown(markdownDTOs, options, attributesMap);
        }

        // FIXME: This will possibly overwrite any filtering updates made in the maven property filtering step above
        if (StringUtils.isNotEmpty(copyDirectories)) {
            getLog().info("Copy files from directories");
            for (String dir : copyDirectories.split(",")) {
                for ( Entry<String, String> copyAction : getFoldersToCopy(inputDirectory, outputDirectory, dir).entrySet()){
                    copyFiles(copyAction.getKey(), copyAction.getValue());
                }
            }
        }
    }

Execute the maven plugin.

@throws MojoExecutionException Something went wrong


@SuppressWarnings("UnusedReturnValue")
    private boolean preprocessMarkdownFiles(File inputDirectory) throws MojoExecutionException {
        getLog().debug("Read files from: " + inputDirectory);

        try {
            if (!inputDirectory.exists()) {
                getLog().info("There is no input folder for the project. Skipping.");
                return false;
            }
            int baseDepth = StringUtils.countMatches(inputDirectory.getAbsolutePath(), File.separator);

            // Reading just the markdown dir and sub dirs if recursive option set
            List<File> markdownFiles = getFilesAsArray(FileUtils.iterateFiles(inputDirectory, getInputFileExtensions(), recursiveInput));

            for (File file : markdownFiles) {
                getLog().debug("File getName() " + file.getName());
                getLog().debug("File getAbsolutePath() " + file.getAbsolutePath());
                getLog().debug("File getPath() " + file.getPath());

                MarkdownDTO dto = new MarkdownDTO();
                dto.markdownFile = file;

                dto.folderDepth = StringUtils.countMatches(file.getAbsolutePath(), File.separator) - (baseDepth + 1);

                if (alwaysUseDefaultTitle) {
                    dto.title = defaultTitle;
                } else {
                    List<String> raw = FileUtils.readLines(file, getInputEncoding());
                    dto.title = getTitle(raw);
                }

                if (applyFiltering) {
                    for (String line : FileUtils.readLines(file, getInputEncoding())) {
                        if (isVariableLine(line)) {
                            String key = line.replaceAll("(^\\{)|(=.*)", "");
                            String value = line.replaceAll("(^\\{(.*?)=)|(}$)", "");
                            getLog().debug("Substitute: '" + key + "' -> '" + value + "'");
                            dto.substitutes.put(key, value);
                        }
                    }
                }

                String inputFileExtension = FilenameUtils.getExtension(file.getName());
                dto.htmlFile = new File(
                        recursiveInput
                                ? outputDirectory + File.separator + file.getParentFile().getPath().substring(inputDirectory.getPath().length()) + File.separator + file.getName().replaceAll(
                                "." + inputFileExtension,
                                ".html"
                        )
                                : outputDirectory + File.separator + file.getName().replaceAll("." + inputFileExtension, ".html")
                );

                getLog().debug("File htmlFile() " + dto.htmlFile);

                markdownDTOs.add(dto);
            }
        } catch (IOException e) {
            throw new MojoExecutionException("Unable to load file " + e.getMessage(), e);
        }

        return true;
    }

Read Markdown files from directory.

@return boolean
Is there files to read
@throws MojoExecutionException Unable to load file


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();
    }

Replace variables with given pattern.

@param template      String to replace
@param patternString regexp pattern
@param variables     variables to find
@return result


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;
    }

Get the first h1 for the title.

@param raw The markdown as a list of strings
@return The first # h1 in the Markdown file


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", "");
        }
    }

Adds the title to the html file.

@param html  The HTML string
@param title The title


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;
    }

Replace variables in the html file.

@param initialContent html
@param variables      variable map
@return the updated html


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));
    }

Update relative include paths corresponding to the markdown file's location in the folder structure.

@param html        The HTML string
@param folderDepth Current markdown file's folder depth

Update relative include paths corresponding to the markdown file s location in the folder structure .


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);
        }
    }

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
)
,
,
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
)
;
}
}

Copy files from one dir to another based on file extensions.

@param fromDir the directory to copy from
@param toDir   the directory to copy to
@throws MojoExecutionException Unable to copy file

Copy files from one dir to another based on file extensions .


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;
    }

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 ; }

When retrieving 'more' statements, LRS will return full path..the client will have part in the URI already so cut that off

When retrieving more statements LRS will return full path .. the client will have part in the URI already so cut that off


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;
    }

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
;
}

this will wrap the view which is added to the slider into another layout so we can then overlap the small and large view

@param child
@param index
@return


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);
    }

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
)
;
}

animate to the large view

@param duration


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);
    }

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
)
;
}

animate to the small view

@param duration


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;
    }

calculate the percentage to how many percent the slide is already visible

@param width
@return


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);
        }
    }

overlap the views and provide the crossfade effect

@param width


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;
  }

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 ; }

The intent to launch the Activity.

@param targetPackage The package of the Activity.
@param activityClass The Activity class send the intent to.
@param bundleCreator Bundle creator instance that will give a bundle to the activity.
@param <T> The specific Activity type.
@return The intent to start the activity.


@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();
  }

@ 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 ( ) ; }


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);
      }

public
TodoListResponse
getTodos
(
String
type
,
String
status
,
UUID
factSheetId
,
UUID
userId
,
UUID
workspaceId
,
Boolean
getArchived
,
Integer
size
,
Integer
page
)
throws
ApiException
{
Object
localVarPostBody
=
;
// 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
)
;
}

getTodos
Retrieves all todos a user can read.
@param type Specifies the todo type (optional)
@param status Specifies the todo status (optional)
@param factSheetId Specifies the ID of the Fact Sheet the todo is connected to - only works with manual Todos (optional)
@param userId Specify the user Id for the user to look for (optional)
@param workspaceId Id of the workspace to get the TodoItems from. (optional)
@param getArchived If set to true, then todos associated with archived factsheets are retrieved as well (optional, default to false)
@param size Specifies the number of Todos to get, (optional, default to 10)
@param page Specifies the page of Todos to get, (optional, default to 1)
@return TodoListResponse
@throws ApiException if fails to make API call

getTodos Retrieves all todos a user can read .


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);
      }

public
FactSheetListResponse
getFactSheets
(
String
type
,
String
relationTypes
,
Integer
pageSize
,
String
cursor
,
Boolean
permissions
)
throws
ApiException
{
Object
localVarPostBody
=
;
// 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
)
;
}

getFactSheets
Retrieves all Fact Sheets
@param type Only list Fact Sheets with this type (optional)
@param relationTypes Comma separated list of relation types to show on the Fact Sheets (optional)
@param pageSize Number of Fact Sheets to return, maximum is 100 (optional, default to 40)
@param cursor Marks the position of the first element that should be returned (optional)
@param permissions Show a permission field for the Fact Sheet (optional, default to false)
@return FactSheetListResponse
@throws ApiException if fails to make API call


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);
    }
  }

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 ) ; } }

Download file from the given response.
@throws ApiException If fail to read file content from response and write to disk


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);
  }

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 ) ; }

Build the Client used to make HTTP requests.

Build the Client used to make HTTP requests .


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);
      }

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
)
;
}

createAccessControlEntity
Creates an access control entity
@param body New access control entity (optional)
@return AccessControlEntityResponse
@throws ApiException if fails to make API call


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);
      }

updateDataModel
Updates the data model for a workspace
@param body the data model for the workspace (required)
@param force whether changes should be forced (optional, default to false)
@param workspaceId  (optional)
@return DataModelUpdateResponse
@throws ApiException if fails to make API call


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);
      }

public
JobResponse
createFullExport
(
String
exportType
,
String
startDate
,
String
endDate
)
throws
ApiException
{
Object
localVarPostBody
=
;
// 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
)
;
}

createFullExport
Creates a full export of the workspace data, or an export of the changelog, depending on given type
@param exportType The type of the export, must be either SNAPSHOT, AUDIT_LOG or AUDIT_LOG_LEGACY (optional)
@param startDate The start date of the audit log export in ISO-8601 format. (optional)
@param endDate The end date of the audit log export in ISO-8601 format. If left empty today is assumed (optional)
@return JobResponse
@throws ApiException if fails to make API call

createFullExport Creates a full export of the workspace data or an export of the changelog depending on given type


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);
      }

public
ExportListResponse
getExports
(
String
exportType
,
UUID
userId
,
Integer
pageSize
,
String
cursor
,
String
sorting
,
String
sortDirection
)
throws
ApiException
{
Object
localVarPostBody
=
;
// 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
)
;
}

getExports
Lists all exports of the given type in the workspace of the authorized user
@param exportType Comma separated list of types of exports to return, if left empty AUDIT_LOG and SNAPSHOT, and AUDIT_LOG_LEGACY exports are returned (optional)
@param userId Retrieve exports initiated by the given user (optional)
@param pageSize Number of Exports to return, maximum is 100 (optional, default to 40)
@param cursor Marks the position of the first element that should be returned (optional)
@param sorting the field to sort the results by (optional, default to createdAt)
@param sortDirection the direction of the sorting (optional, default to ASC)
@return ExportListResponse
@throws ApiException if fails to make API call


public ApiClientBuilder withTokenProviderHost(String host) {
        withOAuth2TokenUrl(URI.create(String.format("https://%s/services/mtm/v1/oauth2/token", host)));
        return this;
    }

Specifies all urls needed to get an access token based on given host name and common url naming convention.

@param host
@return

Specifies all urls needed to get an access token based on given host name and common url naming convention .


public ApiClientBuilder withClientCredentials(String clientId, String clientSecret) {
        this.clientId = clientId;
        this.clientSecret = clientSecret;
        return this;
    }

public ApiClientBuilder withClientCredentials ( String clientId , String clientSecret ) { this . clientId = clientId ; this . clientSecret = clientSecret ; return this ; }

Sets your client Id and client Secret.

@param clientId
@param clientSecret
@return


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);
      }

processGraphQLMultipart
Processes GraphQL requests, supporting multipart documents
@param graphQLRequest  (required)
@param file  (required)
@return GraphQLResult
@throws ApiException if fails to make API call

processGraphQLMultipart Processes GraphQL requests supporting multipart documents


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);
      }

getBookmarks
Retrieves all stored bookmarks a user can read.
@param bookmarkType Specifies the bookmark type (required)
@param groupKey A key used to separate bookmarks within the same query type (optional)
@param sharingType Specifies the sharing type which the returned bookmarks need to have (optional)
@return BookmarkListResponse
@throws ApiException if fails to make API call

getBookmarks Retrieves all stored bookmarks a user can read .


public void addPermissions(Node graphName, GraphPermissions permissions) {
        checkIsOpen();
        client.mergeGraphPermissions(graphName.getURI(), permissions);
    }

public void addPermissions ( Node graphName , GraphPermissions permissions ) { checkIsOpen ( ) ; client . mergeGraphPermissions ( graphName . getURI ( ) , permissions ) ; }

Adds permissions to a graph.

@param graphName
the node with the graph's name.
@param permissions
A {@link com.marklogic.client.semantics.GraphPermissions}
object holding the graph's permissions.


public void writePermissions(Node graphName, GraphPermissions permissions) {
        checkIsOpen();
        client.writeGraphPermissions(graphName.getURI(), permissions);
    }

public void writePermissions ( Node graphName , GraphPermissions permissions ) { checkIsOpen ( ) ; client . writeGraphPermissions ( graphName . getURI ( ) , permissions ) ; }

Sets the permissions on a graph.

@param graphName
the node with the graph's name.
@param permissions
A {@link com.marklogic.client.semantics.GraphPermissions}
object holding the graph's permissions.


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;
    }

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 ; }

Fluent setter for rulesets.

@param rulesets
Zero-or-more rulesets to apply to queries.
@return The MarkLogicDatasetGraph, with rulesets set.


public void close() {
        if (writeBuffer != null) {
            writeBuffer.cancel();
        }
        if (timer != null) {
            timer.cancel();
        }
        client = null;
    }

public void close ( ) { if ( writeBuffer != null ) { writeBuffer . cancel ( ) ; } if ( timer != null ) { timer . cancel ( ) ; } client = null ; }


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);
        }
    }

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 ) ; } }

synchronization needed because of setting of page length


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);
    }

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 ) ; }

Creates MarkLogicDatasetGraph from access parameters to a REST MarkLogic
server.

@param host
the host with the REST server
@param port
the port for the REST server
@param user
the user with read, write, or administrative privileges
@param password
the password for the user
@param type
the type of authentication applied to the request
@return A MarkLogicDatasetGraph instance wrapping MarkLogic.

Creates MarkLogicDatasetGraph from access parameters to a REST MarkLogic server .


public GMOperation limitThreads(final int threadsPerProcess) {
        final List<String> args = getCmdArgs();
        args.add("-limit");
        args.add("threads");
        args.add(Integer.toString(threadsPerProcess));
        return this;
    }

public GMOperation limitThreads ( final int threadsPerProcess ) { final List < String > args = getCmdArgs ( ) ; args . add ( "-limit" ) ; args . add ( "threads" ) ; args . add ( Integer . toString ( threadsPerProcess ) ) ; return this ; }

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.

@param threadsPerProcess
Number of threads to use per process.
@return Builder object for chained options setup.

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 .


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;
    }

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 ; }

Resize source to desired target dimensions, using default resizing filter algorithm.

@param width
Length in pixels of the target image's width.
@param height
Length in pixels of the target image's height.
@param annotations
Geometry annotations to define how the {@code width} and {@code height} options are to be interpreted.
@return Builder object for chained options setup.

Resize source to desired target dimensions using default resizing filter algorithm .


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;
    }

public
GMOperation
rotate
(
final
double
degrees
,
final
RotationAnnotation
annotation
)
{
if
(
annotation
==
)
{
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
;
}

Rotates the image, with empty triangles back-filled using default background color.

@param degrees
The angle by which the image should be rotated. Positive numbers indicate clockwise direction;
negative numbers indicate counterclockwise direction.
@param annotation
Rotate annotation to define when rotation should happen.
@return Builder object for chained options setup.

Rotates the image with empty triangles back - filled using default background color .


public GMOperation gravity(final Gravity value) {
        if (value == null) {
            throw new IllegalArgumentException("Gravity value must be defined");
        }
        gravity(value.toString());
        return this;
    }

public
GMOperation
gravity
(
final
Gravity
value
)
{
if
(
value
==
)
{
throw
new
IllegalArgumentException
(
"Gravity value must be defined"
)
;
}
gravity
(
value
.
toString
(
)
)
;
return
this
;
}

Defines the gravity for geometry-based operations. See documentation for more details, as this option works in
conjunction with various options in different ways.

@param value
Gravity value to use, defining the coordinate system to use.
@return Builder object for chained options setup.

Defines the gravity for geometry - based operations . See documentation for more details as this option works in conjunction with various options in different ways .


public GMOperation stripProfiles() {
        final List<String> args = getCmdArgs();
        args.add("+profile");
        args.add("*");
        return this;
    }

public GMOperation stripProfiles ( ) { final List < String > args = getCmdArgs ( ) ; args . add ( "+profile" ) ; args . add ( "*" ) ; return this ; }

Strips out ICC profiles.

@return Builder object for chained options setup.


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;
    }

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
;
}

Defines font for text overlay.

@param style
Text font style (system-dependent based on installed fonts).
@param size
Text point size.
@param color
Text color, either named or {@code #RGB} variant.
@return Builder object for chained options setup.


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);
    }

public
GMOperation
source
(
final
File
file
,
@
CheckForNull
final
Integer
width
,
@
CheckForNull
final
Integer
height
)
throws
IOException
{
if
(
file
!=
&&
!
file
.
exists
(
)
)
{
throw
new
IOException
(
"Source file '"
+
file
+
"' does not exist"
)
;
}
if
(
(
width
!=
)
&&
(
height
!=
)
&&
(
width
>
0
)
&&
(
height
>
0
)
)
{
size
(
width
,
height
)
;
}
return
addImage
(
file
)
;
}

Specifies the source image to convert.

@param file
Source image file to convert.
@param width
Length in pixels of the source image's width; if {@code null} or negative, the in-memory size
definition is omitted. Optional.
@param height
Length in pixels of the source image's height; if {@code null} or negative, the in-memory size
definition is omitted. Optional.
@return Builder object for chained options setup.
@throws IOException
when the source file does not exist.


public GMOperation addImage(final File file) {
        if (file == null) {
            throw new IllegalArgumentException("file must be defined");
        }
        getCmdArgs().add(file.getPath());
        return this;
    }

public
GMOperation
addImage
(
final
File
file
)
{
if
(
file
==
)
{
throw
new
IllegalArgumentException
(
"file must be defined"
)
;
}
getCmdArgs
(
)
.
add
(
file
.
getPath
(
)
)
;
return
this
;
}

Add image to operation.

@param file
image file to be added.
@return Builder object for chained options setup.


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;
    }

Parse a set of arguments and populate the target with the appropriate values.

@param target Either an instance or a class
@param args   The arguments you want to parse and populate
@return The list of arguments that were not consumed

Parse a set of arguments and populate the target with the appropriate values .


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
        }
    }

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
!=
;
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
}
}

Generate usage information based on the target annotations.

@param errStream A {@link java.io.PrintStream} to print the usage information to.
@param target An instance or class.

Generate usage information based on the target annotations .


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;
	}

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 ; }

Extracts and returns the time unit from a string. If the string
doesn't include a unit, it returns null.
@param timeString the string that contains a time unit
@return the extracted time unit. If the string
doesn't include a unit, it returns null.

Extracts and returns the time unit from a string . If the string doesn t include a unit it returns null .


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
        }
    }

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
}
}

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.

@param target    Either an instance or a class
@param arguments The properties that contain the arguments

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 .


static public void execute(URL url) throws SlideExecutionException {
		checkNotNull(url);
		ScreenRegion screenRegion = new DesktopScreenRegion();
		Context context = new Context(screenRegion);
		execute(url, context);
	}

static public void execute ( URL url ) throws SlideExecutionException { checkNotNull ( url ) ; ScreenRegion screenRegion = new DesktopScreenRegion ( ) ; Context context = new Context ( screenRegion ) ; execute ( url , context ) ; }

Execute a presentation file at a given url

@param url	url to download the file
@throws SlideExecutionException


static public void execute(File file) throws SlideExecutionException {
		checkNotNull(file);
		try {
			execute(file.toURI().toURL());
		} catch (MalformedURLException e) {
			throw new SlideExecutionException(e);
		}
	}

static public void execute ( File file ) throws SlideExecutionException { checkNotNull ( file ) ; try { execute ( file . toURI ( ) . toURL ( ) ) ; } catch ( MalformedURLException e ) { throw new SlideExecutionException ( e ) ; } }

Execute a presentation file
@param file	the presentation file
@throws SlideExecutionException


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;
	}

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
;
}

Interpret a presentation file as a list of executable actions
@param file	the presentation file
@return	a list of {@link Action}
@throws IOException


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;
	}

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 ; }

sort a list of rectangles by their sizes in ascending order


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();
	}

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 ( ) ; }

Render the given template string as a string based on the parameter values
associated with this context

@param templateText	the template string
@return	the rendered string


File getSlideXMLRel(int slideNumber){
		String filename = String.format("slide%d.xml.rels", slideNumber);
		return new File(getRelationshipsDirectory(), filename);
	}

File getSlideXMLRel ( int slideNumber ) { String filename = String . format ( "slide%d.xml.rels" , slideNumber ) ; return new File ( getRelationshipsDirectory ( ) , filename ) ; }

Get the file of the slide rel for a slide number


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);
	}

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 ) ; }

Check the mouse action is within the screen region range.
@param e native mouse event
@return true if the mouse event was within the screen region range.
Otherwise, it returns false.

Check the mouse action is within the screen region range .


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;
	}

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 ; }

namely, if they have the same x range, they would intersect

namely if they have the same x range they would intersect


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();
	}

public
Object
executeOutboundOperation
(
final
Message
<
>
message
)
{
try
{
String
serializedMessage
=
messageMarshaller
.
serialize
(
message
)
;
if
(
queue
==
)
{
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
(
)
;
}


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();
	}

public
Object
executeOutboundOperation
(
final
Message
<
>
message
)
{
try
{
String
serializedMessage
=
messageMarshaller
.
serialize
(
message
)
;
if
(
snsTestProxy
==
)
{
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
(
)
;
}


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;
    }

synchronized
static
public
File
requireFile
(
String
name
,
Options
options
)
throws
IOException
{
File
file
=
findFile
(
name
,
options
)
;
if
(
file
==
)
{
throw
new
ResourceNotFoundException
(
"Resource file "
+
name
+
" not found"
)
;
}
return
file
;
}

Same as findFile but throws an exception if the file was not found.

Same as findFile but throws an exception if the file was not found .


static private File getOrCreateTempDirectory(boolean deleteOnExit) throws ExtractException {
        // return the single instance if already created
        if ((TEMP_DIRECTORY != null) && TEMP_DIRECTORY.exists()) {
            return TEMP_DIRECTORY;
        }

        // use jvm supplied temp directory in case multiple jvms compete
//        try {
//            Path tempDirectory = Files.createTempDirectory("jne.");
//            File tempDirectoryAsFile = tempDirectory.toFile();
//            if (deleteOnExit) {
//                tempDirectoryAsFile.deleteOnExit();
//            }
//            return tempDirectoryAsFile;
//        } catch (IOException e) {
//            throw new ExtractException("Unable to create temporary dir", e);
//        }

        // use totally unique name to avoid race conditions
        try {
            Path baseDir = Paths.get(System.getProperty("java.io.tmpdir"));
            Path tempDirectory = baseDir.resolve("jne." + UUID.randomUUID().toString());
            Files.createDirectories(tempDirectory);
            File tempDirectoryAsFile = tempDirectory.toFile();
            if (deleteOnExit) {
                tempDirectoryAsFile.deleteOnExit();
            }
            // save temp directory so its only exactracted once
            TEMP_DIRECTORY = tempDirectoryAsFile;
            return TEMP_DIRECTORY;
        } catch (IOException e) {
            throw new ExtractException("Unable to create temporary dir", e);
        }

//        File baseDir = new File(System.getProperty("java.io.tmpdir"));
//        String baseName = System.currentTimeMillis() + "-";
//
//        for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
//            File d = new File(baseDir, baseName + counter);
//            if (d.mkdirs()) {
//                // schedule this directory to be deleted on exit
//                if (deleteOnExit) {
//                    d.deleteOnExit();
//                }
//                tempDirectory = d;
//                return d;
//            }
//        }
//
//        throw new ExtractException("Failed to create temporary directory within " + TEMP_DIR_ATTEMPTS + " attempts (tried " + baseName + "0 to " + baseName + (TEMP_DIR_ATTEMPTS - 1) + ')');
    }

//                tempDirectoryAsFile.deleteOnExit();

//            return tempDirectoryAsFile;

Attempts to create a temporary directory that did not exist previously.

Attempts to create a temporary directory that did not exist previously .