private Artifact getServerArtifact(final String serverType)
            throws ComponentConfigurationException {
        if (serverType.startsWith("gav-")) {
            int index = serverType.indexOf("-", 4);
            if (index > 0) {
                String[] gav = serverType.substring(index + 1).split(":");
                if (gav.length == 3) {
                    return repositorySystem.createArtifact(
                            gav[0],
                            gav[1],
                            gav[2],
                            "runtime",
                            "jar"
                    );
                }
            }
            throw new ComponentConfigurationException("Invalid server type: " + serverType);
        } else {
            return repositorySystem.createArtifact(
                    DEFAULT_GROUP_ID,
                    MessageFormat.format(DEFAULT_ARTIFACT_ID_FORMAT, serverType),
                    getClass().getPackage().getImplementationVersion(),
                    "runtime",
                    "jar");
        }
    }

private
Artifact
getServerArtifact
(
final
String
serverType
)
throws
ComponentConfigurationException
{
if
(
serverType
.
startsWith
(
"gav-"
)
)
{
int
index
=
serverType
.
indexOf
(
"-"
,
4
)
;
if
(
index
>
0
)
{
String
[
]
gav
=
serverType
.
substring
(
index
+
1
)
.
split
(
":"
)
;
if
(
gav
.
length
==
3
)
{
return
repositorySystem
.
createArtifact
(
gav
[
0
]
,
gav
[
1
]
,
gav
[
2
]
,
"runtime"
,
"jar"
)
;
}
}
throw
new
ComponentConfigurationException
(
"Invalid server type: "
+
serverType
)
;
}
else
{
return
repositorySystem
.
createArtifact
(
DEFAULT_GROUP_ID
,
MessageFormat
.
format
(
DEFAULT_ARTIFACT_ID_FORMAT
,
serverType
)
,
getClass
(
)
.
getPackage
(
)
.
getImplementationVersion
(
)
,
"runtime"
,
"jar"
)
;
}
}

Get the artifact descriptor for the JAR file that implements support for the LDAP server type.

@param serverType The LDAP server type.
@return The JAR file artifact descriptor.

Get the artifact descriptor for the JAR file that implements support for the LDAP server type .


private String getServerType(final PlexusConfiguration configuration) {
        final Pattern pattern = Pattern.compile("\\$\\{[A-Za-z0-9\\._]+\\}");
        for (final PlexusConfiguration cfg : configuration.getChildren()) {
            if (cfg.getName().equals(SERVER_TYPE_ATTRIBUTE)) {
                if (pattern.matcher(cfg.getValue()).matches()) {
                    return DEFAULT_SERVER_TYPE_VALUE;
                } else {
                    return cfg.getValue();
                }
            }
        }
        return DEFAULT_SERVER_TYPE_VALUE;
    }

private String getServerType ( final PlexusConfiguration configuration ) { final Pattern pattern = Pattern . compile ( "\\$\\{[A-Za-z0-9\\._]+\\}" ) ; for ( final PlexusConfiguration cfg : configuration . getChildren ( ) ) { if ( cfg . getName ( ) . equals ( SERVER_TYPE_ATTRIBUTE ) ) { if ( pattern . matcher ( cfg . getValue ( ) ) . matches ( ) ) { return DEFAULT_SERVER_TYPE_VALUE ; } else { return cfg . getValue ( ) ; } } } return DEFAULT_SERVER_TYPE_VALUE ; }

Determine the configured LDAP server type. If one has not been configured then
return the default.

@param configuration The plugin configuration.
@return The LDAP server type.

Determine the configured LDAP server type . If one has not been configured then return the default .


@Override
    protected FormatWriter createWriter(final OutputStream outputStream,
                                        final FormatLogger logger) {
        try {
            return new DSMLFormatWriter(outputStream);
        } catch (final IOException e) {
            logger.logError("Could not create and intialise the DSML writer", e);
        }
        return null;
    }

Create the LDAP writer that will dump LDAP entries to a DSML file.

@param outputStream The target output stream.
@param logger       Used to log information or error messages.
@return A {@link DSMLFormatWriter} object.

Create the LDAP writer that will dump LDAP entries to a DSML file .


@Override
    protected FormatReader openReader(final InputStream inputStream,
                                      final FormatLogger logger) {
        try {
            return new DSMLFormatReader(inputStream);
        } catch (final DocumentException e) {
            logger.logError("Error parsing DSML file", e);
        } catch (final JaxenException e) {
            logger.logError("Error processing DSML file", e);
        } catch (final IOException e) {
            logger.logError("Error reading DSML file", e);
        }
        return null;
    }

@
Override
protected
FormatReader
openReader
(
final
InputStream
inputStream
,
final
FormatLogger
logger
)
{
try
{
return
new
DSMLFormatReader
(
inputStream
)
;
}
catch
(
final
DocumentException
e
)
{
logger
.
logError
(
"Error parsing DSML file"
,
e
)
;
}
catch
(
final
JaxenException
e
)
{
logger
.
logError
(
"Error processing DSML file"
,
e
)
;
}
catch
(
final
IOException
e
)
{
logger
.
logError
(
"Error reading DSML file"
,
e
)
;
}
return
;
}

Create the LDAP reader that will load LDAP entries from a DSML file.

@param inputStream The file input stream.
@param logger      Used to log information or error messages.
@return A {@link DSMLFormatReader} object.

Create the LDAP reader that will load LDAP entries from a DSML file .


@Override
    public void configure(final String name, final Object value, final Logger logger) {
        if (ROOT.equals(name)) {
            if (value instanceof String) {
                root = (String) value;
                logger.logInfo("Configured root DN for directory server: " + root);
            }
        } else if (OBJECT_CLASSES.equals(name)) {
            if (value instanceof String[]) {
                objectClasses = (String[]) value;
                logger.logInfo("Configured object classes for root DN: " + objectClasses);
            }
        } else if (AUTH_DN.equals(name)) {
            if (value instanceof String) {
                authDn = (String) value;
                logger.logInfo("Configured admin identity for directory server: " + authDn);
            }
        } else if (PASSWD.equals(name)) {
            if (value instanceof String) {
                passwd = (String) value;
                logger.logInfo("Configured admin credentials for directory server: " + passwd);
            }
        } else if (WORK_DIR.equals(name)) {
            if (value instanceof File) {
                workingDirectory = (File) value;
                logger.logInfo("Configured working directory for directory server: " + workingDirectory);
            }
        } else if (LDIF_FILE.equals(name)) {
            if (value instanceof File) {
                ldifFile = (File) value;
                logger.logInfo("Configured LDIF seed data source for directory server: " + ldifFile);
            }
        } else if (LDAP_PORT.equals(name)) {
            if (value instanceof Integer) {
                serverPort = (Integer) value;
                logger.logInfo("Configured TCP port for directory server: " + serverPort);
            }
        }
    }

Used to configure the root DN of the LDAP directory, the working directory used by the directory service to
store the directory data, the LDIF file used to seed the directory or the TCP port number on which the server
will listening for LDAP traffic.

@param name   The name of the property to configure.
@param value  The value of the property being configured.
@param logger Used to log error and information messages.

Used to configure the root DN of the LDAP directory the working directory used by the directory service to store the directory data the LDIF file used to seed the directory or the TCP port number on which the server will listening for LDAP traffic .


@Override
    public void start(final Logger logger) {
        try {
            logger.logInfo("Starting UnboundID server");
            final InMemoryListenerConfig listenerConfig = InMemoryListenerConfig.createLDAPConfig("default", getServerPort());
            final InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(new DN(getRoot()));
            config.setListenerConfigs(listenerConfig);
            if (getAuthDn() != null) {
                config.addAdditionalBindCredentials(getAuthDn(), getPasswd());
            }
            server = new InMemoryDirectoryServer(config);
            String[] objectClasses = getObjectClasses();
            if (objectClasses == null) {
                objectClasses = DEFAULT_ROOT_OBJECT_CLASSES;
            }
            server.add(new Entry(getRoot(), new Attribute("objectclass", objectClasses)));
            if (getLdifFile() != null) {
                final InputStream in = new FileInputStream(getLdifFile());
                try {
                    final LDIFReader reader = new LDIFReader(in);
                    server.importFromLDIF(false, reader);
                } finally {
                    in.close();
                }
            }
            server.startListening();
            logger.logInfo("Started UnboundID server");
        } catch (final LDAPException e) {
            e.printStackTrace();
            logger.logError("Could not launch embedded UnboundID directory server", e);
        } catch (final IOException e) {
            e.printStackTrace();
            logger.logError("Could not launch embedded UnboundID directory server", e);
        }
    }

Configure and start the embedded UnboundID server creating the root DN and loading the LDIF seed data.

@param logger Used to log informational and error messages.

Configure and start the embedded UnboundID server creating the root DN and loading the LDIF seed data .


@Override
    public void stop(final Logger logger) {
        logger.logInfo("Stopping UnboundID server");
        server.shutDown(true);
        logger.logInfo("Stopped UnboundID server");
    }

@
Override
public
void
stop
(
final
Logger
logger
)
{
logger
.
logInfo
(
"Stopping UnboundID server"
)
;
server
.
shutDown
(
true
)
;
logger
.
logInfo
(
"Stopped UnboundID server"
)
;
}

Shutdown the the embedded UnboundID server.

@param logger Used to log informational and error messages.

Shutdown the the embedded UnboundID server .


public LDIFChangeRecord nextRecord() {
        if (entryIterator.hasNext()) {
            try {
                final Node entryNode = entryIterator.next();
                final String dn = entryNode.valueOf("@dn");
                final List<Attribute> attributes = new ArrayList<Attribute>();

                final List<Node> objectClassList = (List<Node>) objectClassXPath.selectNodes(entryNode);
                final String[] objectClasses = new String[objectClassList.size()];
                for (int j = 0; j < objectClasses.length; ++j) {
                    objectClasses[j] = objectClassList.get(j).getStringValue();
                }
                attributes.add(new Attribute("objectclass", objectClasses));
                for (final Node attributeNode : (List<Node>) attrXPath.selectNodes(entryNode)) {
                    final String attributeName = attributeNode.valueOf("@name");
                    final List<Node> attributeValueNodes = (List<Node>) attrValueXPath.selectNodes(attributeNode);
                    switch (attributeValueNodes.size()) {
                        case 0:
                            break;
                        case 1: {
                            final String attributeValue = attributeValueNodes.get(0).getStringValue();
                            attributes.add(new Attribute(attributeName, attributeValue));
                            break;
                        }
                        default: {
                            final String[] attributeValues = new String[attributeValueNodes.size()];
                            for (int j = 0; j < attributeValueNodes.size(); ++j) {
                                attributeValues[j] = attributeValueNodes.get(j).getStringValue();
                            }
                            attributes.add(new Attribute(attributeName, attributeValues));
                            break;
                        }
                    }
                }
                return new LDIFAddChangeRecord(dn, attributes);
            } catch (final JaxenException e) {
                return null;
            }
        } else {
            return null;
        }
    }

public LDIFChangeRecord nextRecord ( ) { if ( entryIterator . hasNext ( ) ) { try { final Node entryNode = entryIterator . next ( ) ; final String dn = entryNode . valueOf ( "@dn" ) ; final List < Attribute > attributes = new ArrayList < Attribute > ( ) ; final List < Node > objectClassList = ( List < Node > ) objectClassXPath . selectNodes ( entryNode ) ; final String [ ] objectClasses = new String [ objectClassList . size ( ) ] ; for ( int j = 0 ; j < objectClasses . length ; ++ j ) { objectClasses [ j ] = objectClassList . get ( j ) . getStringValue ( ) ; } attributes . add ( new Attribute ( "objectclass" , objectClasses ) ) ; for ( final Node attributeNode : ( List < Node > ) attrXPath . selectNodes ( entryNode ) ) { final String attributeName = attributeNode . valueOf ( "@name" ) ; final List < Node > attributeValueNodes = ( List < Node > ) attrValueXPath . selectNodes ( attributeNode ) ; switch ( attributeValueNodes . size ( ) ) { case 0 : break ; case 1 : { final String attributeValue = attributeValueNodes . get ( 0 ) . getStringValue ( ) ; attributes . add ( new Attribute ( attributeName , attributeValue ) ) ; break ; } default : { final String [ ] attributeValues = new String [ attributeValueNodes . size ( ) ] ; for ( int j = 0 ; j < attributeValueNodes . size ( ) ; ++ j ) { attributeValues [ j ] = attributeValueNodes . get ( j ) . getStringValue ( ) ; } attributes . add ( new Attribute ( attributeName , attributeValues ) ) ; break ; } } } return new LDIFAddChangeRecord ( dn , attributes ) ; } catch ( final JaxenException e ) { return null ; } } else { return null ; } }

Read the next change record from the underlying input stream.

@return The next change record or {@code null} if the end of the input stream has been reached.

Read the next change record from the underlying input stream .


public void execute() throws MojoExecutionException {
        if (!isSkip()){
            final LDAPConnection connection = connect();
            try {
                for (final Source source : sources) {
                    try {
                        getLog().info("Processing input source: " + source);
                        final FormatHandler handler = getFormatHandler(source);
                        if (handler == null) {
                            getLog().warn("No handler for input source: " + source);
                        } else {
                            final InputStream inputStream = source.open();
                            if (inputStream == null) {
                                if (!this.continueOnError) {
                                    throw new MojoExecutionException("Cannot open source for reading: " + source);
                                } else {
                                    getLog().warn("Skipping source that could not be opened for reading: " + source);
                                }
                            } else {
                                try {
                                    handler.load(connection, source.open(), continueOnError, this);
                                } finally {
                                    inputStream.close();
                                }
                            }
                        }
                    } catch (final IOException e) {
                        if (!this.continueOnError) {
                            throw new MojoExecutionException("Error closing input source: " + source, e);
                        } else {
                            this.getLog().warn("Ignoring error closing input source: " + source, e);
                        }
                    }
                }
            } finally {
                connection.close();
            }
        }
    }

Execute the plugin goal iterating over the list of source files and loading the LDAP directory entries from
each file using the appropriate handler.

@throws MojoExecutionException If there was an error executing the plugin goal.

Execute the plugin goal iterating over the list of source files and loading the LDAP directory entries from each file using the appropriate handler .


@Override
    public void start(final Logger logger) {
        try {
            logger.logInfo("Starting ApacheDS server");
            service = new DefaultDirectoryService();

            final List<Interceptor> list = new ArrayList<Interceptor>();

            list.add(new NormalizationInterceptor());
            list.add(new AuthenticationInterceptor());
            list.add(new ReferralInterceptor());
            // list.add( new AciAuthorizationInterceptor() );
            // list.add( new DefaultAuthorizationInterceptor() );
            list.add(new ExceptionInterceptor());
            // list.add( new ChangeLogInterceptor() );
            list.add(new OperationalAttributeInterceptor());
            // list.add( new SchemaInterceptor() );
            list.add(new SubentryInterceptor());
            // list.add( new CollectiveAttributeInterceptor() );
            // list.add( new EventInterceptor() );
            // list.add( new TriggerInterceptor() );
            // list.add( new JournalInterceptor() );
            service.setInterceptors(list);
            service.setWorkingDirectory(getWorkingDirectory());

            final JdbmPartition partition = new JdbmPartition();
            partition.setId("rootPartition");
            partition.setSuffix(getRoot());
            service.addPartition(partition);
            service.setExitVmOnShutdown(false);
            service.setShutdownHookEnabled(false);
            service.getChangeLog().setEnabled(false);
            service.setDenormalizeOpAttrsEnabled(true);

            server = new LdapServer();
            server.setDirectoryService(service);
            server.setTransports(new TcpTransport(getServerPort()));

            service.startup();
            server.start();

            createRoot(partition);

            loadLdifFile();

            logger.logInfo("Started ApacheDS server");

        } catch (final Exception e) {
            logger.logError("Error starting ApacheDS server e");
        }
    }

Configure and start the embedded ApacheDS server creating the root DN and loading the LDIF seed data.

@param logger Used to log informational and error messages.

Configure and start the embedded ApacheDS server creating the root DN and loading the LDIF seed data .


@Override
    public void stop(final Logger logger) {
        try {
            logger.logInfo("Stopping ApacheDS server");
            server.stop();
            service.shutdown();
            logger.logInfo("Stopped ApacheDS server");
        } catch (final Exception e) {
            logger.logError("Error stopping ApacheDS server", e);
        }
    }

@
Override
public
void
stop
(
final
Logger
logger
)
{
try
{
logger
.
logInfo
(
"Stopping ApacheDS server"
)
;
server
.
stop
(
)
;
service
.
shutdown
(
)
;
logger
.
logInfo
(
"Stopped ApacheDS server"
)
;
}
catch
(
final
Exception
e
)
{
logger
.
logError
(
"Error stopping ApacheDS server"
,
e
)
;
}
}

Shutdown the the embedded ApacheDS server.

@param logger Used to log informational and error messages.

Shutdown the the embedded ApacheDS server .


private void createRoot(final Partition partition) throws Exception {
        try {
            service.getAdminSession().lookup(partition.getSuffixDn());
        } catch (final LdapNameNotFoundException e) {
            final LdapDN dn = new LdapDN(getRoot());
            final String dc = getRoot().substring(3, getRoot().indexOf(','));
            final ServerEntry entry = service.newEntry(dn);
            entry.add("objectClass", "top", "domain", "extensibleObject");
            entry.add("dc", dc);
            service.getAdminSession().add(entry);
        }
    }

private void createRoot ( final Partition partition ) throws Exception { try { service . getAdminSession ( ) . lookup ( partition . getSuffixDn ( ) ) ; } catch ( final LdapNameNotFoundException e ) { final LdapDN dn = new LdapDN ( getRoot ( ) ) ; final String dc = getRoot ( ) . substring ( 3 , getRoot ( ) . indexOf ( ' ' ) ) ; final ServerEntry entry = service . newEntry ( dn ) ; entry . add ( "objectClass" , "top" , "domain" , "extensibleObject" ) ; entry . add ( "dc" , dc ) ; service . getAdminSession ( ) . add ( entry ) ; } }

Create the root DN.

@param partition The partition in which to create the root DN.
@throws Exception If there was an error creating the root DN.


@Override
    public void start(final Logger logger) {
        try {
            logger.logInfo("Starting OpenDJ server");
            final MemoryBackend backend;
            if (getLdifFile() == null) {
                backend = new MemoryBackend();
            } else {
                final InputStream inputStream = new FileInputStream(getLdifFile());
                final LDIFEntryReader reader = new LDIFEntryReader(inputStream);
                backend = new MemoryBackend(reader);
            }
            final ServerConnectionFactory<LDAPClientContext, Integer> connectionHandler = Connections.newServerConnectionFactory(backend);
            final LDAPListenerOptions options = new LDAPListenerOptions().setBacklog(4096);
            listener = new LDAPListener("localhost", getServerPort(), connectionHandler, options);
            logger.logInfo("Started OpenDJ server");
        } catch (final IOException e) {
            logger.logError("Error starting OpenDJ server", e);
        }
    }

@
Override
public
void
start
(
final
Logger
logger
)
{
try
{
logger
.
logInfo
(
"Starting OpenDJ server"
)
;
final
MemoryBackend
backend
;
if
(
getLdifFile
(
)
==
)
{
backend
=
new
MemoryBackend
(
)
;
}
else
{
final
InputStream
inputStream
=
new
FileInputStream
(
getLdifFile
(
)
)
;
final
LDIFEntryReader
reader
=
new
LDIFEntryReader
(
inputStream
)
;
backend
=
new
MemoryBackend
(
reader
)
;
}
final
ServerConnectionFactory
<
LDAPClientContext
,
Integer
>
connectionHandler
=
Connections
.
newServerConnectionFactory
(
backend
)
;
final
LDAPListenerOptions
options
=
new
LDAPListenerOptions
(
)
.
setBacklog
(
4096
)
;
listener
=
new
LDAPListener
(
"localhost"
,
getServerPort
(
)
,
connectionHandler
,
options
)
;
logger
.
logInfo
(
"Started OpenDJ server"
)
;
}
catch
(
final
IOException
e
)
{
logger
.
logError
(
"Error starting OpenDJ server"
,
e
)
;
}
}

Start the OpenDJ in-memory directory server.

@param logger Used for logging.

Start the OpenDJ in - memory directory server .


@Override
    public void stop(final Logger logger) {
        logger.logInfo("Stopping OpenDJ server");
        if (listener != null) {
            listener.close();
        }
        logger.logInfo("Stopped OpenDJ server");
    }

@
Override
public
void
stop
(
final
Logger
logger
)
{
logger
.
logInfo
(
"Stopping OpenDJ server"
)
;
if
(
listener
!=
)
{
listener
.
close
(
)
;
}
logger
.
logInfo
(
"Stopped OpenDJ server"
)
;
}

Stop the OpenDJ in-memory directory server.

@param logger User for logging.

Stop the OpenDJ in - memory directory server .


public void printEntry(final Entry entry) throws IOException {
        final ByteStringBuffer buffer = new ByteStringBuffer();
        buffer.append("\t\t<dsml:entry dn=\"");
        buffer.append(entry.getDN());
        buffer.append("\">");
        buffer.append(eol);
        final String[] values = entry.getAttributeValues("objectclass");
        if (values != null) {
            buffer.append("\t\t\t<dsml:objectclass>");
            buffer.append(eol);
            for (final String value : values) {
                buffer.append("\t\t\t\t<dsml:oc-value>");
                buffer.append(value);
                buffer.append("</dsml:oc-value>");
                buffer.append(eol);
            }
            buffer.append("\t\t\t</dsml:objectclass>");
            buffer.append(eol);
        }
        for (final Attribute attribute : entry.getAttributes()) {
            final String name = attribute.getName();
            if (!name.equals("objectclass")) {
                buffer.append("\t\t\t<dsml:attr name=\"");
                buffer.append(name);
                buffer.append("\">");
                buffer.append(eol);
                for (final String value : attribute.getValues()) {
                    buffer.append("\t\t\t\t<dsml:value>");
                    buffer.append(value);
                    buffer.append("</dsml:value>");
                    buffer.append(eol);
                }
                buffer.append("\t\t\t</dsml:attr>");
                buffer.append(eol);
            }
        }
        buffer.append("\t\t</dsml:entry>");
        buffer.append(eol);
        ldifOutputStream.write(buffer.toByteArray());
    }

public
void
printEntry
(
final
Entry
entry
)
throws
IOException
{
final
ByteStringBuffer
buffer
=
new
ByteStringBuffer
(
)
;
buffer
.
append
(
"\t\t<dsml:entry dn=\""
)
;
buffer
.
append
(
entry
.
getDN
(
)
)
;
buffer
.
append
(
"\">"
)
;
buffer
.
append
(
eol
)
;
final
String
[
]
values
=
entry
.
getAttributeValues
(
"objectclass"
)
;
if
(
values
!=
)
{
buffer
.
append
(
"\t\t\t<dsml:objectclass>"
)
;
buffer
.
append
(
eol
)
;
for
(
final
String
value
:
values
)
{
buffer
.
append
(
"\t\t\t\t<dsml:oc-value>"
)
;
buffer
.
append
(
value
)
;
buffer
.
append
(
"</dsml:oc-value>"
)
;
buffer
.
append
(
eol
)
;
}
buffer
.
append
(
"\t\t\t</dsml:objectclass>"
)
;
buffer
.
append
(
eol
)
;
}
for
(
final
Attribute
attribute
:
entry
.
getAttributes
(
)
)
{
final
String
name
=
attribute
.
getName
(
)
;
if
(
!
name
.
equals
(
"objectclass"
)
)
{
buffer
.
append
(
"\t\t\t<dsml:attr name=\""
)
;
buffer
.
append
(
name
)
;
buffer
.
append
(
"\">"
)
;
buffer
.
append
(
eol
)
;
for
(
final
String
value
:
attribute
.
getValues
(
)
)
{
buffer
.
append
(
"\t\t\t\t<dsml:value>"
)
;
buffer
.
append
(
value
)
;
buffer
.
append
(
"</dsml:value>"
)
;
buffer
.
append
(
eol
)
;
}
buffer
.
append
(
"\t\t\t</dsml:attr>"
)
;
buffer
.
append
(
eol
)
;
}
}
buffer
.
append
(
"\t\t</dsml:entry>"
)
;
buffer
.
append
(
eol
)
;
ldifOutputStream
.
write
(
buffer
.
toByteArray
(
)
)
;
}

Writes an individual LDAP directory entry to the DSML file.

@param entry The directory entry.
@throws IOException If there was a problem writing to the underlying output stream.

Writes an individual LDAP directory entry to the DSML file .


@Override
    public String getServerType() {
        if (serverType.startsWith("dependency-")) {
            return serverType.substring(11);
        }
        if (serverType.startsWith("gav-")) {
            int index = serverType.indexOf("-", 4);
            if (index > 0) {
                return serverType.substring(4, index);
            }
        }
        return serverType;
    }

@ Override public String getServerType ( ) { if ( serverType . startsWith ( "dependency-" ) ) { return serverType . substring ( 11 ) ; } if ( serverType . startsWith ( "gav-" ) ) { int index = serverType . indexOf ( "-" , 4 ) ; if ( index > 0 ) { return serverType . substring ( 4 , index ) ; } } return serverType ; }

Get the server type.

@return The server type.


@Override
    public Map<String, Object> getServerConfig() {
        final Map<String, Object> config = new HashMap<String, Object>();
        config.put(LDAPServer.ROOT, rootDn);
        if (objectClasses != null) {
            config.put(LDAPServer.OBJECT_CLASSES, objectClasses.split(","));
        }
        config.put(LDAPServer.WORK_DIR, new File(outputDirectory, serverType));
        if (ldifFile != null) {
            config.put(LDAPServer.LDIF_FILE, ldifFile);
        }
        config.put(LDAPServer.LDAP_PORT, ldapPort);
        config.put(LDAPServer.AUTH_DN, authDn);
        config.put(LDAPServer.PASSWD, passwd);
        return config;
    }

@ Override public Map < String , Object > getServerConfig ( ) { final Map < String , Object > config = new HashMap < String , Object > ( ) ; config . put ( LDAPServer . ROOT , rootDn ) ; if ( objectClasses != null ) { config . put ( LDAPServer . OBJECT_CLASSES , objectClasses . split ( "," ) ) ; } config . put ( LDAPServer . WORK_DIR , new File ( outputDirectory , serverType ) ) ; if ( ldifFile != null ) { config . put ( LDAPServer . LDIF_FILE , ldifFile ) ; } config . put ( LDAPServer . LDAP_PORT , ldapPort ) ; config . put ( LDAPServer . AUTH_DN , authDn ) ; config . put ( LDAPServer . PASSWD , passwd ) ; return config ; }

Get the embedded LDAP directory server configuration.

@return A {@link Map} containing the server configuration.

Get the embedded LDAP directory server configuration .


protected void sendMetric(MetricBuilder metricBuilder) throws ReportingException {
    try {
      HttpClient client = new HttpClient("http://" + this.server + ":" + this.port);
      Response response = client.pushMetrics(metricBuilder);

      //check if response is ok
      if (response.getStatusCode() / 100 != 2) {
        LOGGER.error("Kairos DB reported error. Status code: " + response.getStatusCode());
        LOGGER.error("Error message: " + response.getErrors());
        throw new ReportingException();
      } else {
        LOGGER.debug("Kairos DB returned OK. Status code: " + response.getStatusCode());
      }
      client.shutdown();
    } catch (MalformedURLException | URISyntaxException e) {
      throw new ConfigurationException(e);
    } catch (IOException e) {
      LOGGER.error("Could not request KairosDB.", e);
      throw new ReportingException(e);
    }
  }

Sends a metric to the kairos server.

@param metricBuilder the metricbuilder containing the metrics.
@throws de.uniulm.omi.cloudiator.visor.reporting.ReportingException If the kairos server could
not be reached.


@Override
  public void report(Metric metric) throws ReportingException {

    KairosMetricConverter kairosMetricConverter = new KairosMetricConverter();
    try {
      kairosMetricConverter.add(metric);
    } catch (KairosMetricConversionException e) {
      throw new ReportingException(e);
    }
    this.sendMetric(kairosMetricConverter.convert());
  }

@ Override public void report ( Metric metric ) throws ReportingException { KairosMetricConverter kairosMetricConverter = new KairosMetricConverter ( ) ; try { kairosMetricConverter . add ( metric ) ; } catch ( KairosMetricConversionException e ) { throw new ReportingException ( e ) ; } this . sendMetric ( kairosMetricConverter . convert ( ) ) ; }

Report method. Converts the given metric to a metric kairos understands and sends them.

@param metric the metric to report.
@throws ReportingException of the metric could not be converted. or sent to kairos.

Report method . Converts the given metric to a metric kairos understands and sends them .


public static GeometryTypeInfo readGeometryType(ByteReader reader) {

		// Read the single byte order byte
		byte byteOrderValue = reader.readByte();
		ByteOrder byteOrder = byteOrderValue == 0 ? ByteOrder.BIG_ENDIAN
				: ByteOrder.LITTLE_ENDIAN;
		reader.setByteOrder(byteOrder);

		// Read the geometry type unsigned integer
		long unsignedGeometryTypeCode = reader.readUnsignedInt();

		// Check for 2.5D geometry types
		boolean hasZ = false;
		if (unsignedGeometryTypeCode > WKB25D) {
			hasZ = true;
			unsignedGeometryTypeCode -= WKB25D;
		}

		int geometryTypeCode = (int) unsignedGeometryTypeCode;

		// Determine the geometry type
		GeometryType geometryType = GeometryCodes
				.getGeometryType(geometryTypeCode);

		// Determine if the geometry has a z (3d) or m (linear referencing
		// system) value
		if (!hasZ) {
			hasZ = GeometryCodes.hasZ(geometryTypeCode);
		}
		boolean hasM = GeometryCodes.hasM(geometryTypeCode);

		GeometryTypeInfo geometryInfo = new GeometryTypeInfo(geometryTypeCode,
				geometryType, hasZ, hasM);

		return geometryInfo;
	}

Read the geometry type info

@param reader
byte reader
@return geometry type info


public static Point readPoint(ByteReader reader, boolean hasZ, boolean hasM) {

		double x = reader.readDouble();
		double y = reader.readDouble();

		Point point = new Point(hasZ, hasM, x, y);

		if (hasZ) {
			double z = reader.readDouble();
			point.setZ(z);
		}

		if (hasM) {
			double m = reader.readDouble();
			point.setM(m);
		}

		return point;
	}

public static Point readPoint ( ByteReader reader , boolean hasZ , boolean hasM ) { double x = reader . readDouble ( ) ; double y = reader . readDouble ( ) ; Point point = new Point ( hasZ , hasM , x , y ) ; if ( hasZ ) { double z = reader . readDouble ( ) ; point . setZ ( z ) ; } if ( hasM ) { double m = reader . readDouble ( ) ; point . setM ( m ) ; } return point ; }

Read a Point

@param reader
@param hasZ
@param hasM
@return point


public static LineString readLineString(ByteReader reader, boolean hasZ,
			boolean hasM) {

		LineString lineString = new LineString(hasZ, hasM);

		int numPoints = reader.readInt();

		for (int i = 0; i < numPoints; i++) {
			Point point = readPoint(reader, hasZ, hasM);
			lineString.addPoint(point);

		}

		return lineString;
	}

public static LineString readLineString ( ByteReader reader , boolean hasZ , boolean hasM ) { LineString lineString = new LineString ( hasZ , hasM ) ; int numPoints = reader . readInt ( ) ; for ( int i = 0 ; i < numPoints ; i ++ ) { Point point = readPoint ( reader , hasZ , hasM ) ; lineString . addPoint ( point ) ; } return lineString ; }

Read a Line String

@param reader
@param hasZ
@param hasM
@return line string


public static Polygon readPolygon(ByteReader reader, boolean hasZ,
			boolean hasM) {

		Polygon polygon = new Polygon(hasZ, hasM);

		int numRings = reader.readInt();

		for (int i = 0; i < numRings; i++) {
			LineString ring = readLineString(reader, hasZ, hasM);
			polygon.addRing(ring);

		}

		return polygon;
	}

public static Polygon readPolygon ( ByteReader reader , boolean hasZ , boolean hasM ) { Polygon polygon = new Polygon ( hasZ , hasM ) ; int numRings = reader . readInt ( ) ; for ( int i = 0 ; i < numRings ; i ++ ) { LineString ring = readLineString ( reader , hasZ , hasM ) ; polygon . addRing ( ring ) ; } return polygon ; }

Read a Polygon

@param reader
@param hasZ
@param hasM
@return polygon


public static MultiPoint readMultiPoint(ByteReader reader, boolean hasZ,
			boolean hasM) {

		MultiPoint multiPoint = new MultiPoint(hasZ, hasM);

		int numPoints = reader.readInt();

		for (int i = 0; i < numPoints; i++) {
			Point point = readGeometry(reader, Point.class);
			multiPoint.addPoint(point);

		}

		return multiPoint;
	}

public static MultiPoint readMultiPoint ( ByteReader reader , boolean hasZ , boolean hasM ) { MultiPoint multiPoint = new MultiPoint ( hasZ , hasM ) ; int numPoints = reader . readInt ( ) ; for ( int i = 0 ; i < numPoints ; i ++ ) { Point point = readGeometry ( reader , Point . class ) ; multiPoint . addPoint ( point ) ; } return multiPoint ; }

Read a Multi Point

@param reader
@param hasZ
@param hasM
@return multi point


public static MultiLineString readMultiLineString(ByteReader reader,
			boolean hasZ, boolean hasM) {

		MultiLineString multiLineString = new MultiLineString(hasZ, hasM);

		int numLineStrings = reader.readInt();

		for (int i = 0; i < numLineStrings; i++) {
			LineString lineString = readGeometry(reader, LineString.class);
			multiLineString.addLineString(lineString);
		}

		return multiLineString;
	}

public static MultiLineString readMultiLineString ( ByteReader reader , boolean hasZ , boolean hasM ) { MultiLineString multiLineString = new MultiLineString ( hasZ , hasM ) ; int numLineStrings = reader . readInt ( ) ; for ( int i = 0 ; i < numLineStrings ; i ++ ) { LineString lineString = readGeometry ( reader , LineString . class ) ; multiLineString . addLineString ( lineString ) ; } return multiLineString ; }

Read a Multi Line String

@param reader
@param hasZ
@param hasM
@return multi line string


public static MultiPolygon readMultiPolygon(ByteReader reader,
			boolean hasZ, boolean hasM) {

		MultiPolygon multiPolygon = new MultiPolygon(hasZ, hasM);

		int numPolygons = reader.readInt();

		for (int i = 0; i < numPolygons; i++) {
			Polygon polygon = readGeometry(reader, Polygon.class);
			multiPolygon.addPolygon(polygon);

		}

		return multiPolygon;
	}

public static MultiPolygon readMultiPolygon ( ByteReader reader , boolean hasZ , boolean hasM ) { MultiPolygon multiPolygon = new MultiPolygon ( hasZ , hasM ) ; int numPolygons = reader . readInt ( ) ; for ( int i = 0 ; i < numPolygons ; i ++ ) { Polygon polygon = readGeometry ( reader , Polygon . class ) ; multiPolygon . addPolygon ( polygon ) ; } return multiPolygon ; }

Read a Multi Polygon

@param reader
@param hasZ
@param hasM
@return multi polygon


public static GeometryCollection<Geometry> readGeometryCollection(
			ByteReader reader, boolean hasZ, boolean hasM) {

		GeometryCollection<Geometry> geometryCollection = new GeometryCollection<Geometry>(
				hasZ, hasM);

		int numGeometries = reader.readInt();

		for (int i = 0; i < numGeometries; i++) {
			Geometry geometry = readGeometry(reader, Geometry.class);
			geometryCollection.addGeometry(geometry);

		}

		return geometryCollection;
	}

public static GeometryCollection < Geometry > readGeometryCollection ( ByteReader reader , boolean hasZ , boolean hasM ) { GeometryCollection < Geometry > geometryCollection = new GeometryCollection < Geometry > ( hasZ , hasM ) ; int numGeometries = reader . readInt ( ) ; for ( int i = 0 ; i < numGeometries ; i ++ ) { Geometry geometry = readGeometry ( reader , Geometry . class ) ; geometryCollection . addGeometry ( geometry ) ; } return geometryCollection ; }

Read a Geometry Collection

@param reader
@param hasZ
@param hasM
@return geometry collection


public static CircularString readCircularString(ByteReader reader,
			boolean hasZ, boolean hasM) {

		CircularString circularString = new CircularString(hasZ, hasM);

		int numPoints = reader.readInt();

		for (int i = 0; i < numPoints; i++) {
			Point point = readPoint(reader, hasZ, hasM);
			circularString.addPoint(point);

		}

		return circularString;
	}

public static CircularString readCircularString ( ByteReader reader , boolean hasZ , boolean hasM ) { CircularString circularString = new CircularString ( hasZ , hasM ) ; int numPoints = reader . readInt ( ) ; for ( int i = 0 ; i < numPoints ; i ++ ) { Point point = readPoint ( reader , hasZ , hasM ) ; circularString . addPoint ( point ) ; } return circularString ; }

Read a Circular String

@param reader
@param hasZ
@param hasM
@return circular string


public static CompoundCurve readCompoundCurve(ByteReader reader,
			boolean hasZ, boolean hasM) {

		CompoundCurve compoundCurve = new CompoundCurve(hasZ, hasM);

		int numLineStrings = reader.readInt();

		for (int i = 0; i < numLineStrings; i++) {
			LineString lineString = readGeometry(reader, LineString.class);
			compoundCurve.addLineString(lineString);

		}

		return compoundCurve;
	}

public static CompoundCurve readCompoundCurve ( ByteReader reader , boolean hasZ , boolean hasM ) { CompoundCurve compoundCurve = new CompoundCurve ( hasZ , hasM ) ; int numLineStrings = reader . readInt ( ) ; for ( int i = 0 ; i < numLineStrings ; i ++ ) { LineString lineString = readGeometry ( reader , LineString . class ) ; compoundCurve . addLineString ( lineString ) ; } return compoundCurve ; }

Read a Compound Curve

@param reader
@param hasZ
@param hasM
@return compound curve


public static CurvePolygon<Curve> readCurvePolygon(ByteReader reader,
			boolean hasZ, boolean hasM) {

		CurvePolygon<Curve> curvePolygon = new CurvePolygon<Curve>(hasZ, hasM);

		int numRings = reader.readInt();

		for (int i = 0; i < numRings; i++) {
			Curve ring = readGeometry(reader, Curve.class);
			curvePolygon.addRing(ring);

		}

		return curvePolygon;
	}

public static CurvePolygon < Curve > readCurvePolygon ( ByteReader reader , boolean hasZ , boolean hasM ) { CurvePolygon < Curve > curvePolygon = new CurvePolygon < Curve > ( hasZ , hasM ) ; int numRings = reader . readInt ( ) ; for ( int i = 0 ; i < numRings ; i ++ ) { Curve ring = readGeometry ( reader , Curve . class ) ; curvePolygon . addRing ( ring ) ; } return curvePolygon ; }

Read a Curve Polygon

@param reader
@param hasZ
@param hasM
@return curve polygon


public static PolyhedralSurface readPolyhedralSurface(ByteReader reader,
			boolean hasZ, boolean hasM) {

		PolyhedralSurface polyhedralSurface = new PolyhedralSurface(hasZ, hasM);

		int numPolygons = reader.readInt();

		for (int i = 0; i < numPolygons; i++) {
			Polygon polygon = readGeometry(reader, Polygon.class);
			polyhedralSurface.addPolygon(polygon);

		}

		return polyhedralSurface;
	}

public static PolyhedralSurface readPolyhedralSurface ( ByteReader reader , boolean hasZ , boolean hasM ) { PolyhedralSurface polyhedralSurface = new PolyhedralSurface ( hasZ , hasM ) ; int numPolygons = reader . readInt ( ) ; for ( int i = 0 ; i < numPolygons ; i ++ ) { Polygon polygon = readGeometry ( reader , Polygon . class ) ; polyhedralSurface . addPolygon ( polygon ) ; } return polyhedralSurface ; }

Read a Polyhedral Surface

@param reader
@param hasZ
@param hasM
@return polyhedral surface


public static TIN readTIN(ByteReader reader, boolean hasZ, boolean hasM) {

		TIN tin = new TIN(hasZ, hasM);

		int numPolygons = reader.readInt();

		for (int i = 0; i < numPolygons; i++) {
			Polygon polygon = readGeometry(reader, Polygon.class);
			tin.addPolygon(polygon);

		}

		return tin;
	}

public static TIN readTIN ( ByteReader reader , boolean hasZ , boolean hasM ) { TIN tin = new TIN ( hasZ , hasM ) ; int numPolygons = reader . readInt ( ) ; for ( int i = 0 ; i < numPolygons ; i ++ ) { Polygon polygon = readGeometry ( reader , Polygon . class ) ; tin . addPolygon ( polygon ) ; } return tin ; }

Read a TIN

@param reader
@param hasZ
@param hasM
@return TIN


public static Triangle readTriangle(ByteReader reader, boolean hasZ,
			boolean hasM) {

		Triangle triangle = new Triangle(hasZ, hasM);

		int numRings = reader.readInt();

		for (int i = 0; i < numRings; i++) {
			LineString ring = readLineString(reader, hasZ, hasM);
			triangle.addRing(ring);

		}

		return triangle;
	}

public static Triangle readTriangle ( ByteReader reader , boolean hasZ , boolean hasM ) { Triangle triangle = new Triangle ( hasZ , hasM ) ; int numRings = reader . readInt ( ) ; for ( int i = 0 ; i < numRings ; i ++ ) { LineString ring = readLineString ( reader , hasZ , hasM ) ; triangle . addRing ( ring ) ; } return triangle ; }

Read a Triangle

@param reader
@param hasZ
@param hasM
@return triangle


public static void writeGeometry(ByteWriter writer, Geometry geometry)
			throws IOException {

		// Write the single byte order byte
		byte byteOrder = writer.getByteOrder() == ByteOrder.BIG_ENDIAN ? (byte) 0
				: (byte) 1;
		writer.writeByte(byteOrder);

		// Write the geometry type integer
		writer.writeInt(GeometryCodes.getCode(geometry));

		GeometryType geometryType = geometry.getGeometryType();

		switch (geometryType) {

		case GEOMETRY:
			throw new SFException("Unexpected Geometry Type of "
					+ geometryType.name() + " which is abstract");
		case POINT:
			writePoint(writer, (Point) geometry);
			break;
		case LINESTRING:
			writeLineString(writer, (LineString) geometry);
			break;
		case POLYGON:
			writePolygon(writer, (Polygon) geometry);
			break;
		case MULTIPOINT:
			writeMultiPoint(writer, (MultiPoint) geometry);
			break;
		case MULTILINESTRING:
			writeMultiLineString(writer, (MultiLineString) geometry);
			break;
		case MULTIPOLYGON:
			writeMultiPolygon(writer, (MultiPolygon) geometry);
			break;
		case GEOMETRYCOLLECTION:
		case MULTICURVE:
		case MULTISURFACE:
			writeGeometryCollection(writer, (GeometryCollection<?>) geometry);
			break;
		case CIRCULARSTRING:
			writeCircularString(writer, (CircularString) geometry);
			break;
		case COMPOUNDCURVE:
			writeCompoundCurve(writer, (CompoundCurve) geometry);
			break;
		case CURVEPOLYGON:
			writeCurvePolygon(writer, (CurvePolygon<?>) geometry);
			break;
		case CURVE:
			throw new SFException("Unexpected Geometry Type of "
					+ geometryType.name() + " which is abstract");
		case SURFACE:
			throw new SFException("Unexpected Geometry Type of "
					+ geometryType.name() + " which is abstract");
		case POLYHEDRALSURFACE:
			writePolyhedralSurface(writer, (PolyhedralSurface) geometry);
			break;
		case TIN:
			writeTIN(writer, (TIN) geometry);
			break;
		case TRIANGLE:
			writeTriangle(writer, (Triangle) geometry);
			break;
		default:
			throw new SFException("Geometry Type not supported: "
					+ geometryType);
		}

	}

public
static
void
writeGeometry
(
ByteWriter
writer
,
Geometry
geometry
)
throws
IOException
{
// Write the single byte order byte
byte
byteOrder
=
writer
.
getByteOrder
(
)
==
ByteOrder
.
BIG_ENDIAN
(
byte
)
0
:
(
byte
)
1
;
writer
.
writeByte
(
byteOrder
)
;
// Write the geometry type integer
writer
.
writeInt
(
GeometryCodes
.
getCode
(
geometry
)
)
;
GeometryType
geometryType
=
geometry
.
getGeometryType
(
)
;
switch
(
geometryType
)
{
case
GEOMETRY
:
throw
new
SFException
(
"Unexpected Geometry Type of "
+
geometryType
.
name
(
)
+
" which is abstract"
)
;
case
POINT
:
writePoint
(
writer
,
(
Point
)
geometry
)
;
break
;
case
LINESTRING
:
writeLineString
(
writer
,
(
LineString
)
geometry
)
;
break
;
case
POLYGON
:
writePolygon
(
writer
,
(
Polygon
)
geometry
)
;
break
;
case
MULTIPOINT
:
writeMultiPoint
(
writer
,
(
MultiPoint
)
geometry
)
;
break
;
case
MULTILINESTRING
:
writeMultiLineString
(
writer
,
(
MultiLineString
)
geometry
)
;
break
;
case
MULTIPOLYGON
:
writeMultiPolygon
(
writer
,
(
MultiPolygon
)
geometry
)
;
break
;
case
GEOMETRYCOLLECTION
:
case
MULTICURVE
:
case
MULTISURFACE
:
writeGeometryCollection
(
writer
,
(
GeometryCollection
<
>
)
geometry
)
;
break
;
case
CIRCULARSTRING
:
writeCircularString
(
writer
,
(
CircularString
)
geometry
)
;
break
;
case
COMPOUNDCURVE
:
writeCompoundCurve
(
writer
,
(
CompoundCurve
)
geometry
)
;
break
;
case
CURVEPOLYGON
:
writeCurvePolygon
(
writer
,
(
CurvePolygon
<
>
)
geometry
)
;
break
;
case
CURVE
:
throw
new
SFException
(
"Unexpected Geometry Type of "
+
geometryType
.
name
(
)
+
" which is abstract"
)
;
case
SURFACE
:
throw
new
SFException
(
"Unexpected Geometry Type of "
+
geometryType
.
name
(
)
+
" which is abstract"
)
;
case
POLYHEDRALSURFACE
:
writePolyhedralSurface
(
writer
,
(
PolyhedralSurface
)
geometry
)
;
break
;
case
TIN
:
writeTIN
(
writer
,
(
TIN
)
geometry
)
;
break
;
case
TRIANGLE
:
writeTriangle
(
writer
,
(
Triangle
)
geometry
)
;
break
;
default
:
throw
new
SFException
(
"Geometry Type not supported: "
+
geometryType
)
;
}
}

Write a geometry to the byte writer

@param writer
@param geometry
@throws IOException


public static void writePoint(ByteWriter writer, Point point)
			throws IOException {

		writer.writeDouble(point.getX());
		writer.writeDouble(point.getY());

		if (point.hasZ()) {
			writer.writeDouble(point.getZ());
		}

		if (point.hasM()) {
			writer.writeDouble(point.getM());
		}
	}

public static void writePoint ( ByteWriter writer , Point point ) throws IOException { writer . writeDouble ( point . getX ( ) ) ; writer . writeDouble ( point . getY ( ) ) ; if ( point . hasZ ( ) ) { writer . writeDouble ( point . getZ ( ) ) ; } if ( point . hasM ( ) ) { writer . writeDouble ( point . getM ( ) ) ; } }

Write a Point

@param writer
@param point
@throws IOException


public static void writeLineString(ByteWriter writer, LineString lineString)
			throws IOException {

		writer.writeInt(lineString.numPoints());

		for (Point point : lineString.getPoints()) {
			writePoint(writer, point);
		}
	}

public static void writeLineString ( ByteWriter writer , LineString lineString ) throws IOException { writer . writeInt ( lineString . numPoints ( ) ) ; for ( Point point : lineString . getPoints ( ) ) { writePoint ( writer , point ) ; } }

Write a Line String

@param writer
@param lineString
@throws IOException


public static void writePolygon(ByteWriter writer, Polygon polygon)
			throws IOException {

		writer.writeInt(polygon.numRings());

		for (LineString ring : polygon.getRings()) {
			writeLineString(writer, ring);
		}
	}

public static void writePolygon ( ByteWriter writer , Polygon polygon ) throws IOException { writer . writeInt ( polygon . numRings ( ) ) ; for ( LineString ring : polygon . getRings ( ) ) { writeLineString ( writer , ring ) ; } }

Write a Polygon

@param writer
@param polygon
@throws IOException


public static void writeMultiPoint(ByteWriter writer, MultiPoint multiPoint)
			throws IOException {

		writer.writeInt(multiPoint.numPoints());

		for (Point point : multiPoint.getPoints()) {
			writeGeometry(writer, point);
		}
	}

public static void writeMultiPoint ( ByteWriter writer , MultiPoint multiPoint ) throws IOException { writer . writeInt ( multiPoint . numPoints ( ) ) ; for ( Point point : multiPoint . getPoints ( ) ) { writeGeometry ( writer , point ) ; } }

Write a Multi Point

@param writer
@param multiPoint
@throws IOException


public static void writeMultiLineString(ByteWriter writer,
			MultiLineString multiLineString) throws IOException {

		writer.writeInt(multiLineString.numLineStrings());

		for (LineString lineString : multiLineString.getLineStrings()) {
			writeGeometry(writer, lineString);
		}
	}

public static void writeMultiLineString ( ByteWriter writer , MultiLineString multiLineString ) throws IOException { writer . writeInt ( multiLineString . numLineStrings ( ) ) ; for ( LineString lineString : multiLineString . getLineStrings ( ) ) { writeGeometry ( writer , lineString ) ; } }

Write a Multi Line String

@param writer
@param multiLineString
@throws IOException


public static void writeMultiPolygon(ByteWriter writer,
			MultiPolygon multiPolygon) throws IOException {

		writer.writeInt(multiPolygon.numPolygons());

		for (Polygon polygon : multiPolygon.getPolygons()) {
			writeGeometry(writer, polygon);
		}
	}

public static void writeMultiPolygon ( ByteWriter writer , MultiPolygon multiPolygon ) throws IOException { writer . writeInt ( multiPolygon . numPolygons ( ) ) ; for ( Polygon polygon : multiPolygon . getPolygons ( ) ) { writeGeometry ( writer , polygon ) ; } }

Write a Multi Polygon

@param writer
@param multiPolygon
@throws IOException


public static void writeGeometryCollection(ByteWriter writer,
			GeometryCollection<?> geometryCollection) throws IOException {

		writer.writeInt(geometryCollection.numGeometries());

		for (Geometry geometry : geometryCollection.getGeometries()) {
			writeGeometry(writer, geometry);
		}
	}

public static void writeGeometryCollection ( ByteWriter writer , GeometryCollection < ? > geometryCollection ) throws IOException { writer . writeInt ( geometryCollection . numGeometries ( ) ) ; for ( Geometry geometry : geometryCollection . getGeometries ( ) ) { writeGeometry ( writer , geometry ) ; } }

Write a Geometry Collection

@param writer
@param geometryCollection
@throws IOException


public static void writeCircularString(ByteWriter writer,
			CircularString circularString) throws IOException {

		writer.writeInt(circularString.numPoints());

		for (Point point : circularString.getPoints()) {
			writePoint(writer, point);
		}
	}

public static void writeCircularString ( ByteWriter writer , CircularString circularString ) throws IOException { writer . writeInt ( circularString . numPoints ( ) ) ; for ( Point point : circularString . getPoints ( ) ) { writePoint ( writer , point ) ; } }

Write a Circular String

@param writer
@param circularString
@throws IOException


public static void writeCompoundCurve(ByteWriter writer,
			CompoundCurve compoundCurve) throws IOException {

		writer.writeInt(compoundCurve.numLineStrings());

		for (LineString lineString : compoundCurve.getLineStrings()) {
			writeGeometry(writer, lineString);
		}
	}

public static void writeCompoundCurve ( ByteWriter writer , CompoundCurve compoundCurve ) throws IOException { writer . writeInt ( compoundCurve . numLineStrings ( ) ) ; for ( LineString lineString : compoundCurve . getLineStrings ( ) ) { writeGeometry ( writer , lineString ) ; } }

Write a Compound Curve

@param writer
@param compoundCurve
@throws IOException


public static void writeCurvePolygon(ByteWriter writer,
			CurvePolygon<?> curvePolygon) throws IOException {

		writer.writeInt(curvePolygon.numRings());

		for (Curve ring : curvePolygon.getRings()) {
			writeGeometry(writer, ring);
		}
	}

public static void writeCurvePolygon ( ByteWriter writer , CurvePolygon < ? > curvePolygon ) throws IOException { writer . writeInt ( curvePolygon . numRings ( ) ) ; for ( Curve ring : curvePolygon . getRings ( ) ) { writeGeometry ( writer , ring ) ; } }

Write a Curve Polygon

@param writer
@param curvePolygon
@throws IOException


public static void writePolyhedralSurface(ByteWriter writer,
			PolyhedralSurface polyhedralSurface) throws IOException {

		writer.writeInt(polyhedralSurface.numPolygons());

		for (Polygon polygon : polyhedralSurface.getPolygons()) {
			writeGeometry(writer, polygon);
		}
	}

public static void writePolyhedralSurface ( ByteWriter writer , PolyhedralSurface polyhedralSurface ) throws IOException { writer . writeInt ( polyhedralSurface . numPolygons ( ) ) ; for ( Polygon polygon : polyhedralSurface . getPolygons ( ) ) { writeGeometry ( writer , polygon ) ; } }

Write a Polyhedral Surface

@param writer
@param polyhedralSurface
@throws IOException


public static void writeTIN(ByteWriter writer, TIN tin) throws IOException {

		writer.writeInt(tin.numPolygons());

		for (Polygon polygon : tin.getPolygons()) {
			writeGeometry(writer, polygon);
		}
	}

public static void writeTIN ( ByteWriter writer , TIN tin ) throws IOException { writer . writeInt ( tin . numPolygons ( ) ) ; for ( Polygon polygon : tin . getPolygons ( ) ) { writeGeometry ( writer , polygon ) ; } }

Write a TIN

@param writer
@param tin
@throws IOException


public static void writeTriangle(ByteWriter writer, Triangle triangle)
			throws IOException {

		writer.writeInt(triangle.numRings());

		for (LineString ring : triangle.getRings()) {
			writeLineString(writer, ring);
		}
	}

public static void writeTriangle ( ByteWriter writer , Triangle triangle ) throws IOException { writer . writeInt ( triangle . numRings ( ) ) ; for ( LineString ring : triangle . getRings ( ) ) { writeLineString ( writer , ring ) ; } }

Write a Triangle

@param writer
@param triangle
@throws IOException


public static int getCode(Geometry geometry) {
		int code = getCode(geometry.getGeometryType());
		if (geometry.hasZ()) {
			code += 1000;
		}
		if (geometry.hasM()) {
			code += 2000;
		}
		return code;
	}

public static int getCode ( Geometry geometry ) { int code = getCode ( geometry . getGeometryType ( ) ) ; if ( geometry . hasZ ( ) ) { code += 1000 ; } if ( geometry . hasM ( ) ) { code += 2000 ; } return code ; }

Get the geometry code from the geometry

@param geometry
geometry
@return geometry code


public static int getCode(GeometryType geometryType) {

		int code;

		switch (geometryType) {
		case GEOMETRY:
			code = 0;
			break;
		case POINT:
			code = 1;
			break;
		case LINESTRING:
			code = 2;
			break;
		case POLYGON:
			code = 3;
			break;
		case MULTIPOINT:
			code = 4;
			break;
		case MULTILINESTRING:
			code = 5;
			break;
		case MULTIPOLYGON:
			code = 6;
			break;
		case GEOMETRYCOLLECTION:
			code = 7;
			break;
		case CIRCULARSTRING:
			code = 8;
			break;
		case COMPOUNDCURVE:
			code = 9;
			break;
		case CURVEPOLYGON:
			code = 10;
			break;
		case MULTICURVE:
			code = 11;
			break;
		case MULTISURFACE:
			code = 12;
			break;
		case CURVE:
			code = 13;
			break;
		case SURFACE:
			code = 14;
			break;
		case POLYHEDRALSURFACE:
			code = 15;
			break;
		case TIN:
			code = 16;
			break;
		case TRIANGLE:
			code = 17;
			break;
		default:
			throw new SFException(
					"Unsupported Geometry Type for code retrieval: "
							+ geometryType);
		}

		return code;
	}

Get the geometry code from the geometry type

@param geometryType
geometry type
@return geometry code


public static GeometryType getGeometryType(int code) {

		// Look at the last 2 digits to find the geometry type code
		int geometryTypeCode = code % 1000;

		GeometryType geometryType = null;

		switch (geometryTypeCode) {
		case 0:
			geometryType = GeometryType.GEOMETRY;
			break;
		case 1:
			geometryType = GeometryType.POINT;
			break;
		case 2:
			geometryType = GeometryType.LINESTRING;
			break;
		case 3:
			geometryType = GeometryType.POLYGON;
			break;
		case 4:
			geometryType = GeometryType.MULTIPOINT;
			break;
		case 5:
			geometryType = GeometryType.MULTILINESTRING;
			break;
		case 6:
			geometryType = GeometryType.MULTIPOLYGON;
			break;
		case 7:
			geometryType = GeometryType.GEOMETRYCOLLECTION;
			break;
		case 8:
			geometryType = GeometryType.CIRCULARSTRING;
			break;
		case 9:
			geometryType = GeometryType.COMPOUNDCURVE;
			break;
		case 10:
			geometryType = GeometryType.CURVEPOLYGON;
			break;
		case 11:
			geometryType = GeometryType.MULTICURVE;
			break;
		case 12:
			geometryType = GeometryType.MULTISURFACE;
			break;
		case 13:
			geometryType = GeometryType.CURVE;
			break;
		case 14:
			geometryType = GeometryType.SURFACE;
			break;
		case 15:
			geometryType = GeometryType.POLYHEDRALSURFACE;
			break;
		case 16:
			geometryType = GeometryType.TIN;
			break;
		case 17:
			geometryType = GeometryType.TRIANGLE;
			break;
		default:
			throw new SFException(
					"Unsupported Geometry code for type retrieval: " + code);
		}

		return geometryType;
	}

Get the Geometry Type from the code

@param code
geometry type code
@return geometry type


@Override
    public boolean exists() {
        // Try file existence: can we find the file in the file system?
        try {
            return getFile().exists();
        }
        catch (IoRuntimeException ex) {
            // Fall back to stream existence: can we open the stream?
            try {
                try (InputStream is = getInputStream()) {
                	return true;
                }
            }
            catch (Throwable isEx) {
                return false;
            }
        }
    }

This implementation checks whether a File can be opened,
falling back to whether an InputStream can be opened.
This will cover both directories and content resources.

This implementation checks whether a File can be opened falling back to whether an InputStream can be opened . This will cover both directories and content resources .


public static long gcd(List<Long> l) {
        if (l.isEmpty()) {
            throw new IllegalArgumentException("List must contain at least one element");
        }
        BigInteger gcd = BigInteger.valueOf(l.get(0));
        for (Long num : l.subList(1, l.size())) {
            gcd = gcd.gcd(BigInteger.valueOf(num));
        }
        return gcd.longValue();

    }

Finds the greatest common divisor of all numbers in the list.

@return the GCD or Long.MAX_VALUE if the list is empty.

Finds the greatest common divisor of all numbers in the list .


@Nonnull
    public static String abbreviate(String str, int max) {
        if (str == null) {
            return "";
        } else if (str.length() <= max) {
            return str;
        } else {
            return str.substring(0, max - 3) + "...";
        }
    }

@ Nonnull public static String abbreviate ( String str , int max ) { if ( str == null ) { return "" ; } else if ( str . length ( ) <= max ) { return str ; } else { return str . substring ( 0 , max - 3 ) + "..." ; } }

Abbreviates a String using ellipses. This will turn "Now is the time for all good men" into "Now is the time for..."

@param str the String to abbreviate
@param max the max number of chars of the abbreviated String
@return the abbreviated string

Abbreviates a String using ellipses . This will turn Now is the time for all good men into Now is the time for ...


public static org.jmxtrans.agent.util.json.JsonValue value(String string) {
    return string == null ? NULL : new JsonString(string);
  }

public static org . jmxtrans . agent . util . json . JsonValue value ( String string ) { return string == null ? NULL : new JsonString ( string ) ; }

Returns a JsonValue instance that represents the given string.

@param string
the string to get a JSON representation for
@return a JSON value that represents the given string

Returns a JsonValue instance that represents the given string .


public static org.jmxtrans.agent.util.json.JsonObject object() {
    return new org.jmxtrans.agent.util.json.JsonObject();
  }

public static org . jmxtrans . agent . util . json . JsonObject object ( ) { return new org . jmxtrans . agent . util . json . JsonObject ( ) ; }

Creates a new empty JsonObject. This is equivalent to creating a new JsonObject using the
constructor.

@return a new empty JSON object

Creates a new empty JsonObject . This is equivalent to creating a new JsonObject using the constructor .


public static org.jmxtrans.agent.util.json.JsonValue parse(String string) {
    if (string == null) {
      throw new NullPointerException("string is null");
    }
    DefaultHandler handler = new DefaultHandler();
    new JsonParser(handler).parse(string);
    return handler.getValue();
  }

public
static
org
.
jmxtrans
.
agent
.
util
.
json
.
JsonValue
parse
(
String
string
)
{
if
(
string
==
)
{
throw
new
NullPointerException
(
"string is null"
)
;
}
DefaultHandler
handler
=
new
DefaultHandler
(
)
;
new
JsonParser
(
handler
)
.
parse
(
string
)
;
return
handler
.
getValue
(
)
;
}

Parses the given input string as JSON. The input must contain a valid JSON value, optionally
padded with whitespace.

@param string
the input string, must be valid JSON
@return a value that represents the parsed JSON
@throws ParseException
if the input is not valid JSON

Parses the given input string as JSON . The input must contain a valid JSON value optionally padded with whitespace .


public static String getString(Map<String, String> settings, String name, String defaultValue) {
        if (settings.containsKey(name)) {
            return settings.get(name);
        } else {
            return defaultValue;
        }
    }

public static String getString ( Map < String , String > settings , String name , String defaultValue ) { if ( settings . containsKey ( name ) ) { return settings . get ( name ) ; } else { return defaultValue ; } }

Return the value of the given property.

If the property is not found, the defaultValue is returned.

@param name         name of the property
@param defaultValue default value if the property is not defined.
@return value of the property or defaultValue if the property is not defined.

Return the value of the given property .


@Deprecated
  public static JsonObject readFrom(String string) {
    return org.jmxtrans.agent.util.json.JsonValue.readFrom(string).asObject();
  }

@ Deprecated public static JsonObject readFrom ( String string ) { return org . jmxtrans . agent . util . json . JsonValue . readFrom ( string ) . asObject ( ) ; }

Reads a JSON object from the given string.

@param string
the string that contains the JSON object
@return the JSON object that has been read
@throws ParseException
if the input is not valid JSON
@throws UnsupportedOperationException
if the input does not contain a JSON object
@deprecated Use {@link Json#parse(String)}{@link org.jmxtrans.agent.util.json.JsonValue#asObject() .asObject()} instead

Reads a JSON object from the given string .


public org.jmxtrans.agent.util.json.JsonValue get(String name) {
    if (name == null) {
      throw new NullPointerException("name is null");
    }
    int index = indexOf(name);
    return index != -1 ? values.get(index) : null;
  }

public
org
.
jmxtrans
.
agent
.
util
.
json
.
JsonValue
get
(
String
name
)
{
if
(
name
==
)
{
throw
new
NullPointerException
(
"name is null"
)
;
}
int
index
=
indexOf
(
name
)
;
return
index
!=
1
values
.
get
(
index
)
:
;
}

Returns the value of the member with the specified name in this object. If this object contains
multiple members with the given name, this method will return the last one.

@param name
the name of the member whose value is to be returned
@return the value of the last member with the specified name, or null if this
object does not contain a member with that name

Returns the value of the member with the specified name in this object . If this object contains multiple members with the given name this method will return the last one .


public Iterator<Member> iterator() {
    final Iterator<String> namesIterator = names.iterator();
    final Iterator<org.jmxtrans.agent.util.json.JsonValue> valuesIterator = values.iterator();
    return new Iterator<JsonObject.Member>() {

      public boolean hasNext() {
        return namesIterator.hasNext();
      }

      public Member next() {
        String name = namesIterator.next();
        org.jmxtrans.agent.util.json.JsonValue value = valuesIterator.next();
        return new Member(name, value);
      }

      public void remove() {
        throw new UnsupportedOperationException();
      }

    };
  }

public Iterator < Member > iterator ( ) { final Iterator < String > namesIterator = names . iterator ( ) ; final Iterator < org . jmxtrans . agent . util . json . JsonValue > valuesIterator = values . iterator ( ) ; return new Iterator < JsonObject . Member > ( ) { public boolean hasNext ( ) { return namesIterator . hasNext ( ) ; } public Member next ( ) { String name = namesIterator . next ( ) ; org . jmxtrans . agent . util . json . JsonValue value = valuesIterator . next ( ) ; return new Member ( name , value ) ; } public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; }

Returns an iterator over the members of this object in document order. The returned iterator
cannot be used to modify this object.

@return an iterator over the members of this object

Returns an iterator over the members of this object in document order . The returned iterator cannot be used to modify this object .


protected String resolvePlaceholder(String property, String defaultValue) throws IllegalStateException {

        // "graphite.host" -> "GRAPHITE_HOST"
        String environmentVariableStyleProperty = property.toUpperCase();
        environmentVariableStyleProperty = environmentVariableStyleProperty.replaceAll("\\.", "_");

        String result;
        if (externalProperties.containsKey(property)) {
            result = externalProperties.get(property);
        } else if (System.getProperties().containsKey(property)) {
            result = System.getProperty(property);
        } else if (System.getenv().containsKey(property)) {
            result = System.getenv(property);
        } else if (System.getenv().containsKey(environmentVariableStyleProperty)) {
            result = System.getenv(environmentVariableStyleProperty);
        } else if (defaultValue != null) {
            result = defaultValue;
        } else {
            throw new IllegalStateException("Property '" + property + "' not found in System properties nor in Environment variables");
        }
        return result;
    }

Search for the given placeholder in system properties then in environment variables.

@param property     property to resolve
@param defaultValue Default value if the placeholder is not found. null means not default value is
defined and the placeholder must exist
@return the resolved property or the default value if the placeholder is not found and the default value is defined. Non null.
@throws IllegalStateException if the placeholder is not found and the given defaultValue is not
defined (null)

Search for the given placeholder in system properties then in environment variables .


@Nonnull
    public static String getVersionInfo() {
        Package pkg = JmxTransAgent.class.getPackage();
        if (pkg == null) {
            return "jmxtrans-agent";
        } else {
            return pkg.getImplementationTitle() + ": " + pkg.getImplementationVersion();
        }
    }

@
Nonnull
public
static
String
getVersionInfo
(
)
{
Package
pkg
=
JmxTransAgent
.
class
.
getPackage
(
)
;
if
(
pkg
==
)
{
return
"jmxtrans-agent"
;
}
else
{
return
pkg
.
getImplementationTitle
(
)
+
": "
+
pkg
.
getImplementationVersion
(
)
;
}
}

Human readable name and version.

@return project name and version or "{@code jmxtrans-agent}" if package information not found


@Deprecated
  public static JsonArray readFrom(String string) {
    return org.jmxtrans.agent.util.json.JsonValue.readFrom(string).asArray();
  }

@ Deprecated public static JsonArray readFrom ( String string ) { return org . jmxtrans . agent . util . json . JsonValue . readFrom ( string ) . asArray ( ) ; }

Reads a JSON array from the given string.

@param string
the string that contains the JSON array
@return the JSON array that has been read
@throws ParseException
if the input is not valid JSON
@throws UnsupportedOperationException
if the input does not contain a JSON array
@deprecated Use {@link Json#parse(String)}{@link org.jmxtrans.agent.util.json.JsonValue#asArray() .asArray()} instead

Reads a JSON array from the given string .


public JsonArray add(org.jmxtrans.agent.util.json.JsonValue value) {
    if (value == null) {
      throw new NullPointerException("value is null");
    }
    values.add(value);
    return this;
  }

public
JsonArray
add
(
org
.
jmxtrans
.
agent
.
util
.
json
.
JsonValue
value
)
{
if
(
value
==
)
{
throw
new
NullPointerException
(
"value is null"
)
;
}
values
.
add
(
value
)
;
return
this
;
}

Appends the specified JSON value to the end of this array.

@param value
the JsonValue to add to the array, must not be null
@return the array itself, to enable method chaining

Appends the specified JSON value to the end of this array .


public JsonArray set(int index, org.jmxtrans.agent.util.json.JsonValue value) {
    if (value == null) {
      throw new NullPointerException("value is null");
    }
    values.set(index, value);
    return this;
  }

public
JsonArray
set
(
int
index
,
org
.
jmxtrans
.
agent
.
util
.
json
.
JsonValue
value
)
{
if
(
value
==
)
{
throw
new
NullPointerException
(
"value is null"
)
;
}
values
.
set
(
index
,
value
)
;
return
this
;
}

Replaces the element at the specified position in this array with the specified JSON value.

@param index
the index of the array element to replace
@param value
the value to be stored at the specified array position, must not be null
@return the array itself, to enable method chaining
@throws IndexOutOfBoundsException
if the index is out of range, i.e. index < 0 or
index >= size

Replaces the element at the specified position in this array with the specified JSON value .


public org.jmxtrans.agent.util.json.JsonValue get(int index) {
    return values.get(index);
  }

public org . jmxtrans . agent . util . json . JsonValue get ( int index ) { return values . get ( index ) ; }

Returns the value of the element at the specified position in this array.

@param index
the index of the array element to return
@return the value of the element at the specified position
@throws IndexOutOfBoundsException
if the index is out of range, i.e. index < 0 or
index >= size

Returns the value of the element at the specified position in this array .


public List<org.jmxtrans.agent.util.json.JsonValue> values() {
    return Collections.unmodifiableList(values);
  }

public List < org . jmxtrans . agent . util . json . JsonValue > values ( ) { return Collections . unmodifiableList ( values ) ; }

Returns a list of the values in this array in document order. The returned list is backed by
this array and will reflect subsequent changes. It cannot be used to modify this array.
Attempts to modify the returned list will result in an exception.

@return a list of the values in this array

Returns a list of the values in this array in document order . The returned list is backed by this array and will reflect subsequent changes . It cannot be used to modify this array . Attempts to modify the returned list will result in an exception .


public Iterator<org.jmxtrans.agent.util.json.JsonValue> iterator() {
    final Iterator<org.jmxtrans.agent.util.json.JsonValue> iterator = values.iterator();
    return new Iterator<org.jmxtrans.agent.util.json.JsonValue>() {

      public boolean hasNext() {
        return iterator.hasNext();
      }

      public org.jmxtrans.agent.util.json.JsonValue next() {
        return iterator.next();
      }

      public void remove() {
        throw new UnsupportedOperationException();
      }
    };
  }

public Iterator < org . jmxtrans . agent . util . json . JsonValue > iterator ( ) { final Iterator < org . jmxtrans . agent . util . json . JsonValue > iterator = values . iterator ( ) ; return new Iterator < org . jmxtrans . agent . util . json . JsonValue > ( ) { public boolean hasNext ( ) { return iterator . hasNext ( ) ; } public org . jmxtrans . agent . util . json . JsonValue next ( ) { return iterator . next ( ) ; } public void remove ( ) { throw new UnsupportedOperationException ( ) ; } } ; }

Returns an iterator over the values of this array in document order. The returned iterator
cannot be used to modify this array.

@return an iterator over the values of this array

Returns an iterator over the values of this array in document order . The returned iterator cannot be used to modify this array .


private void processEvent(final Object event)
    {
	    System.out.println("Processing event: " + event.toString());
	    for (final EventHandler handler : getConsumersFor(event.getClass()))
	    {
    		EVENT_EXECUTOR.execute(new Runnable(){
				@Override
                public void run()
                {
			    	try
			    	{
			    		handler.handle(event);
			    	}
			    	catch(Exception e)
			    	{
			    		e.printStackTrace();

			    		if (shouldReRaiseOnError)
			    		{
			    			System.out.println("Event handler failed. Re-publishing event: " + event.toString());
			    			eventQueue.publish(event);
			    		}
			    	}
                }
    		});
	    }
    }

Runs each appropriate EventHandler in an Executor.

@param event

Runs each appropriate EventHandler in an Executor .


private void publishEvent(Object event)
	{
		assert(hasEventBusses());

		for (EventBus eventBus : eventBusses.values())
		{
			eventBus.publish(event);
		}
	}

private void publishEvent ( Object event ) { assert ( hasEventBusses ( ) ) ; for ( EventBus eventBus : eventBusses . values ( ) ) { eventBus . publish ( event ) ; } }

Raise an event on all event busses, passing it to applicable consumers asynchronously.

@param event

Raise an event on all event busses passing it to applicable consumers asynchronously .


private void publishEvent(String name, Object event)
	{
		assert(hasEventBusses());
		EventBus eventBus = getEventBus(name);

		if (eventBus == null)
		{
			throw new RuntimeException("Unknown event bus name: " + name);
		}

		eventBus.publish(event);
	}

private
void
publishEvent
(
String
name
,
Object
event
)
{
assert
(
hasEventBusses
(
)
)
;
EventBus
eventBus
=
getEventBus
(
name
)
;
if
(
eventBus
==
)
{
throw
new
RuntimeException
(
"Unknown event bus name: "
+
name
)
;
}
eventBus
.
publish
(
event
)
;
}

Raise an event on a named event bus, passing it to applicable consumers asynchronously.

@param name the name of an event bus, assigned during calls to addEventBus(String, EventBus).
@param event the event to publish.

Raise an event on a named event bus passing it to applicable consumers asynchronously .


public void removeChild(final String child) {
        final StringBuilder htmlMiddleSB = getHtmlMiddleSB();
        final String sb = htmlMiddleSB.toString();
        final String replaced = sb.replace(child, "");
        final int lastIndex = htmlMiddleSB.length() - 1;
        htmlMiddleSB.delete(0, lastIndex);
        htmlMiddleSB.append(replaced);
    }

public void removeChild ( final String child ) { final StringBuilder htmlMiddleSB = getHtmlMiddleSB ( ) ; final String sb = htmlMiddleSB . toString ( ) ; final String replaced = sb . replace ( child , "" ) ; final int lastIndex = htmlMiddleSB . length ( ) - 1 ; htmlMiddleSB . delete ( 0 , lastIndex ) ; htmlMiddleSB . append ( replaced ) ; }

removes the the child content.

@param child
@since 1.0.0
@author WFF


private void addInWffIdMap(final AbstractHtml tag) {

        final Deque<Set<AbstractHtml>> childrenStack = new ArrayDeque<>();
        // passed 2 instead of 1 because the load factor is 0.75f
        final Set<AbstractHtml> initialSet = new HashSet<>(2);
        initialSet.add(tag);
        childrenStack.push(initialSet);

        Set<AbstractHtml> children;
        while ((children = childrenStack.poll()) != null) {
            for (final AbstractHtml child : children) {

                final DataWffId wffIdAttr = child.getDataWffId();

                if (wffIdAttr != null) {
                    tagByWffId.put(wffIdAttr.getValue(), child);
                }

                final Set<AbstractHtml> subChildren = child
                        .getChildren(accessObject);
                if (subChildren != null && subChildren.size() > 0) {
                    childrenStack.push(subChildren);
                }

            }
        }

    }

adds to wffid map

@param tag
@since 2.0.0
@author WFF


protected boolean addToAttributeValueMap(final String key,
            final String value) {

        final Collection<AbstractHtml5SharedObject> sharedObjects = getSharedObjects();
        boolean listenerInvoked = false;
        final Collection<WriteLock> writeLocks = lockAndGetWriteLocks();
        try {
            final Map<String, String> attributeValueMap = getAttributeValueMap();

            final String previousValue = attributeValueMap.put(key, value);

            if (!Objects.equals(previousValue, value)) {
                setModified(true);
                invokeValueChangeListeners(sharedObjects);
                listenerInvoked = true;
            }

        } finally {
            for (final Lock lock : writeLocks) {
                lock.unlock();
            }
        }

        pushQueues(sharedObjects, listenerInvoked);

        return listenerInvoked;
    }

protected boolean addToAttributeValueMap ( final String key , final String value ) { final Collection < AbstractHtml5SharedObject > sharedObjects = getSharedObjects ( ) ; boolean listenerInvoked = false ; final Collection < WriteLock > writeLocks = lockAndGetWriteLocks ( ) ; try { final Map < String , String > attributeValueMap = getAttributeValueMap ( ) ; final String previousValue = attributeValueMap . put ( key , value ) ; if ( ! Objects . equals ( previousValue , value ) ) { setModified ( true ) ; invokeValueChangeListeners ( sharedObjects ) ; listenerInvoked = true ; } } finally { for ( final Lock lock : writeLocks ) { lock . unlock ( ) ; } } pushQueues ( sharedObjects , listenerInvoked ) ; return listenerInvoked ; }

adds the given key value.

@param key
@param value
@return true if it is modified
@since 1.0.0
@author WFF


private void invokeValueChangeListeners(
            final Collection<AbstractHtml5SharedObject> sharedObjects) {

        for (final AbstractHtml5SharedObject sharedObject : sharedObjects) {
            final AttributeValueChangeListener valueChangeListener = sharedObject
                    .getValueChangeListener(ACCESS_OBJECT);
            if (valueChangeListener != null) {

                // ownerTags should not be modified in the consuming
                // part, here
                // skipped it making unmodifiable to gain
                // performance
                final AttributeValueChangeListener.Event event = new AttributeValueChangeListener.Event(
                        this, ownerTags);
                valueChangeListener.valueChanged(event);
            }
        }

        if (valueChangeListeners != null) {
            for (final AttributeValueChangeListener listener : valueChangeListeners) {
                final AttributeValueChangeListener.Event event = new AttributeValueChangeListener.Event(
                        this, Collections.unmodifiableSet(ownerTags));
                listener.valueChanged(event);
            }
        }

    }

this method should be called after changing of attribute value not before
changing value


protected boolean addAllToAttributeValueMap(final Map<String, String> map) {

        if (map != null && map.size() > 0) {

            final Collection<AbstractHtml5SharedObject> sharedObjects = getSharedObjects();
            boolean listenerInvoked = false;

            final Collection<WriteLock> writeLocks = lockAndGetWriteLocks();
            try {

                getAttributeValueMap().putAll(map);

                setModified(true);

                invokeValueChangeListeners(sharedObjects);
                listenerInvoked = true;

            } finally {
                for (final Lock lock : writeLocks) {
                    lock.unlock();
                }
            }
            pushQueues(sharedObjects, listenerInvoked);
            return listenerInvoked;

        }
        return false;
    }

protected boolean addAllToAttributeValueMap ( final Map < String , String > map ) { if ( map != null && map . size ( ) > 0 ) { final Collection < AbstractHtml5SharedObject > sharedObjects = getSharedObjects ( ) ; boolean listenerInvoked = false ; final Collection < WriteLock > writeLocks = lockAndGetWriteLocks ( ) ; try { getAttributeValueMap ( ) . putAll ( map ) ; setModified ( true ) ; invokeValueChangeListeners ( sharedObjects ) ; listenerInvoked = true ; } finally { for ( final Lock lock : writeLocks ) { lock . unlock ( ) ; } } pushQueues ( sharedObjects , listenerInvoked ) ; return listenerInvoked ; } return false ; }

adds all to the attribute value map.

@param map
@since 1.0.0
@author WFF
@return true if it is modified


protected boolean removeFromAttributeValueMapByKeys(final String... keys) {

        final Collection<AbstractHtml5SharedObject> sharedObjects = getSharedObjects();
        boolean listenerInvoked = false;
        final Collection<WriteLock> writeLocks = lockAndGetWriteLocks();
        boolean result = false;
        try {

            final Map<String, String> valueMap = getAttributeValueMap();

            if (nullableAttrValueMapValue) {
                for (final String key : keys) {
                    result = valueMap.containsKey(key);
                    if (result) {
                        break;
                    }
                }
            }

            for (final String key : keys) {
                final String previous = valueMap.remove(key);
                if (previous != null) {
                    result = true;
                }
            }

            if (result) {
                setModified(true);
                invokeValueChangeListeners(sharedObjects);
                listenerInvoked = true;
            }

        } finally {
            for (final Lock lock : writeLocks) {
                lock.unlock();
            }
        }
        pushQueues(sharedObjects, listenerInvoked);
        return result;
    }

protected boolean removeFromAttributeValueMapByKeys ( final String ... keys ) { final Collection < AbstractHtml5SharedObject > sharedObjects = getSharedObjects ( ) ; boolean listenerInvoked = false ; final Collection < WriteLock > writeLocks = lockAndGetWriteLocks ( ) ; boolean result = false ; try { final Map < String , String > valueMap = getAttributeValueMap ( ) ; if ( nullableAttrValueMapValue ) { for ( final String key : keys ) { result = valueMap . containsKey ( key ) ; if ( result ) { break ; } } } for ( final String key : keys ) { final String previous = valueMap . remove ( key ) ; if ( previous != null ) { result = true ; } } if ( result ) { setModified ( true ) ; invokeValueChangeListeners ( sharedObjects ) ; listenerInvoked = true ; } } finally { for ( final Lock lock : writeLocks ) { lock . unlock ( ) ; } } pushQueues ( sharedObjects , listenerInvoked ) ; return result ; }

removes the key value for the input key.

@param keys
@since 3.0.1
@author WFF
@return true if any of the given keys (as well as value contained
corresponding to it) has been removed.

removes the key value for the input key .


private void pushQueues(
            final Collection<AbstractHtml5SharedObject> sharedObjects,
            final boolean listenerInvoked) {
        if (listenerInvoked) {
            for (final AbstractHtml5SharedObject sharedObject : sharedObjects) {
                final PushQueue pushQueue = sharedObject
                        .getPushQueue(ACCESS_OBJECT);
                if (pushQueue != null) {
                    pushQueue.push();
                }
            }
        }
    }

private void pushQueues ( final Collection < AbstractHtml5SharedObject > sharedObjects , final boolean listenerInvoked ) { if ( listenerInvoked ) { for ( final AbstractHtml5SharedObject sharedObject : sharedObjects ) { final PushQueue pushQueue = sharedObject . getPushQueue ( ACCESS_OBJECT ) ; if ( pushQueue != null ) { pushQueue . push ( ) ; } } } }

pushes PushQueue from all shared object of parent tags.

@param sharedObjects
@param listenerInvoked

pushes PushQueue from all shared object of parent tags .


protected boolean removeFromAttributeValueMap(final String key,
            final String value) {

        final Collection<AbstractHtml5SharedObject> sharedObjects = getSharedObjects();

        final Collection<WriteLock> writeLocks = lockAndGetWriteLocks();
        boolean listenerInvoked = false;
        try {

            final boolean removed = getAttributeValueMap().remove(key, value);

            if (removed) {
                setModified(true);
                invokeValueChangeListeners(sharedObjects);
                listenerInvoked = true;
            }

        } finally {
            for (final Lock lock : writeLocks) {
                lock.unlock();
            }
        }
        pushQueues(sharedObjects, listenerInvoked);
        return listenerInvoked;
    }

protected boolean removeFromAttributeValueMap ( final String key , final String value ) { final Collection < AbstractHtml5SharedObject > sharedObjects = getSharedObjects ( ) ; final Collection < WriteLock > writeLocks = lockAndGetWriteLocks ( ) ; boolean listenerInvoked = false ; try { final boolean removed = getAttributeValueMap ( ) . remove ( key , value ) ; if ( removed ) { setModified ( true ) ; invokeValueChangeListeners ( sharedObjects ) ; listenerInvoked = true ; } } finally { for ( final Lock lock : writeLocks ) { lock . unlock ( ) ; } } pushQueues ( sharedObjects , listenerInvoked ) ; return listenerInvoked ; }

removes only if the key and value matches in the map for any particular
entry.

@param key
@param value
@since 1.0.0
@author WFF
@return true if it is modified

removes only if the key and value matches in the map for any particular entry .


protected boolean addToAttributeValueSet(final String value) {
        final Collection<AbstractHtml5SharedObject> sharedObjects = getSharedObjects();
        boolean listenerInvoked = false;
        final Collection<WriteLock> writeLocks = lockAndGetWriteLocks();
        try {

            final boolean added = getAttributeValueSet().add(value);

            if (added) {
                setModified(true);

                invokeValueChangeListeners(sharedObjects);
                listenerInvoked = true;

            }

        } finally {
            for (final Lock lock : writeLocks) {
                lock.unlock();
            }
        }
        pushQueues(sharedObjects, listenerInvoked);
        return listenerInvoked;
    }

protected boolean addToAttributeValueSet ( final String value ) { final Collection < AbstractHtml5SharedObject > sharedObjects = getSharedObjects ( ) ; boolean listenerInvoked = false ; final Collection < WriteLock > writeLocks = lockAndGetWriteLocks ( ) ; try { final boolean added = getAttributeValueSet ( ) . add ( value ) ; if ( added ) { setModified ( true ) ; invokeValueChangeListeners ( sharedObjects ) ; listenerInvoked = true ; } } finally { for ( final Lock lock : writeLocks ) { lock . unlock ( ) ; } } pushQueues ( sharedObjects , listenerInvoked ) ; return listenerInvoked ; }

adds to the attribute value set.

@param value
@since 1.0.0
@author WFF
@return


protected void addAllToAttributeValueSet(final Collection<String> values) {
        if (values != null) {
            final Collection<AbstractHtml5SharedObject> sharedObjects = getSharedObjects();
            boolean listenerInvoked = false;
            final Collection<WriteLock> writeLocks = lockAndGetWriteLocks();
            try {

                final boolean added = getAttributeValueSet().addAll(values);

                if (added) {
                    setModified(true);

                    invokeValueChangeListeners(sharedObjects);
                    listenerInvoked = true;
                }

            } finally {
                for (final Lock lock : writeLocks) {
                    lock.unlock();
                }
            }
            pushQueues(sharedObjects, listenerInvoked);
        }
    }

protected void addAllToAttributeValueSet ( final Collection < String > values ) { if ( values != null ) { final Collection < AbstractHtml5SharedObject > sharedObjects = getSharedObjects ( ) ; boolean listenerInvoked = false ; final Collection < WriteLock > writeLocks = lockAndGetWriteLocks ( ) ; try { final boolean added = getAttributeValueSet ( ) . addAll ( values ) ; if ( added ) { setModified ( true ) ; invokeValueChangeListeners ( sharedObjects ) ; listenerInvoked = true ; } } finally { for ( final Lock lock : writeLocks ) { lock . unlock ( ) ; } } pushQueues ( sharedObjects , listenerInvoked ) ; } }

adds all to the attribute value set.

@param values
@since 1.0.0
@author WFF


protected void removeAllFromAttributeValueSet(
            final Collection<String> values) {
        final Collection<AbstractHtml5SharedObject> sharedObjects = getSharedObjects();
        boolean listenerInvoked = false;
        final Collection<WriteLock> writeLocks = lockAndGetWriteLocks();
        try {

            final boolean removedAll = getAttributeValueSet().removeAll(values);

            if (removedAll) {
                setModified(true);

                invokeValueChangeListeners(sharedObjects);
                listenerInvoked = true;
            }

        } finally {
            for (final Lock lock : writeLocks) {
                lock.unlock();
            }
        }
        pushQueues(sharedObjects, listenerInvoked);
    }

protected void removeAllFromAttributeValueSet ( final Collection < String > values ) { final Collection < AbstractHtml5SharedObject > sharedObjects = getSharedObjects ( ) ; boolean listenerInvoked = false ; final Collection < WriteLock > writeLocks = lockAndGetWriteLocks ( ) ; try { final boolean removedAll = getAttributeValueSet ( ) . removeAll ( values ) ; if ( removedAll ) { setModified ( true ) ; invokeValueChangeListeners ( sharedObjects ) ; listenerInvoked = true ; } } finally { for ( final Lock lock : writeLocks ) { lock . unlock ( ) ; } } pushQueues ( sharedObjects , listenerInvoked ) ; }

removes the value from the the attribute set.

@param values
@since 1.0.0
@author WFF

removes the value from the the attribute set .


protected void removeAllFromAttributeValueSet() {

        final Collection<AbstractHtml5SharedObject> sharedObjects = getSharedObjects();
        boolean listenerInvoked = false;

        final Collection<WriteLock> writeLocks = lockAndGetWriteLocks();
        try {
            getAttributeValueSet().clear();
            setModified(true);

            invokeValueChangeListeners(sharedObjects);
            listenerInvoked = true;
        } finally {
            for (final Lock lock : writeLocks) {
                lock.unlock();
            }
        }
        pushQueues(sharedObjects, listenerInvoked);
    }

protected void removeAllFromAttributeValueSet ( ) { final Collection < AbstractHtml5SharedObject > sharedObjects = getSharedObjects ( ) ; boolean listenerInvoked = false ; final Collection < WriteLock > writeLocks = lockAndGetWriteLocks ( ) ; try { getAttributeValueSet ( ) . clear ( ) ; setModified ( true ) ; invokeValueChangeListeners ( sharedObjects ) ; listenerInvoked = true ; } finally { for ( final Lock lock : writeLocks ) { lock . unlock ( ) ; } } pushQueues ( sharedObjects , listenerInvoked ) ; }

clears all values from the value set.

@since 1.0.0
@author WFF


public void addValueChangeListener(
            final AttributeValueChangeListener valueChangeListener) {
        if (valueChangeListeners == null) {
            synchronized (this) {
                if (valueChangeListeners == null) {
                    valueChangeListeners = new LinkedHashSet<>();
                }
            }
        }

        valueChangeListeners.add(valueChangeListener);
    }

public void addValueChangeListener ( final AttributeValueChangeListener valueChangeListener ) { if ( valueChangeListeners == null ) { synchronized ( this ) { if ( valueChangeListeners == null ) { valueChangeListeners = new LinkedHashSet <> ( ) ; } } } valueChangeListeners . add ( valueChangeListener ) ; }

adds value change lister which will be invoked when the value changed

@param valueChangeListener
@since 2.0.0
@author WFF


public boolean containsValidRegEx() {

        try {
            java.util.regex.Pattern.compile(super.getAttributeValue());
            return true;
        } catch (final PatternSyntaxException e) {
            // NOP
        }

        return false;
    }

public
boolean
containsValidRegEx
(
)
{
try
{
java
.
util
.
regex
.
Pattern
.
compile
(
super
.
getAttributeValue
(
)
)
;
return
true
;
}
catch
(
final
PatternSyntaxException
e
)
{
// NOP
}
return
false
;
}

checks the value in this attribute contains a valid regex.

@return true if this attribute contains a valid regex
@since 3.0.1
@author WFF

checks the value in this attribute contains a valid regex .


public void setR(final int r) {
        if (r < 0 || r > 255) {
            throw new InvalidValueException(
                    "r paramater accept values only from 0 to 255.");
        }
        this.r = r;
        rgba = "rgba(" + r + ", " + g + ", " + b + ", " + a + ")";
        if (getStateChangeInformer() != null) {
            getStateChangeInformer().stateChanged(this);
        }
    }

to set the red value which is in between 0 to 255.

@param r
represents red
@author WFF
@since 1.0.0

to set the red value which is in between 0 to 255 .


public void setG(final int g) {
        if (g < 0 || g > 255) {
            throw new InvalidValueException(
                    "g paramater accept values only from 0 to 255.");
        }
        this.g = g;
        rgba = "rgba(" + r + ", " + g + ", " + b + ", " + a + ")";
        if (getStateChangeInformer() != null) {
            getStateChangeInformer().stateChanged(this);
        }
    }

to set the green value which is in between 0 to 255.

@param g
represents green
@author WFF
@since 1.0.0

to set the green value which is in between 0 to 255 .


public void setB(final int b) {
        if (b < 0 || b > 255) {
            throw new InvalidValueException(
                    "b paramater accept values only from 0 to 255.");
        }
        this.b = b;
        rgba = "rgba(" + r + ", " + g + ", " + b + ", " + a + ")";
        if (getStateChangeInformer() != null) {
            getStateChangeInformer().stateChanged(this);
        }
    }

to set the blue value which is in between 0 to 255.

@param b
@author WFF
@since 1.0.0

to set the blue value which is in between 0 to 255 .


public void setA(final float a) {
        if (a < 0 || a > 1) {
            throw new InvalidValueException(
                    "a paramater accept values only from 0 to 255.");
        }
        this.a = a;
        rgba = "rgba(" + r + ", " + g + ", " + b + ", " + a + ")";
        if (getStateChangeInformer() != null) {
            getStateChangeInformer().stateChanged(this);
        }
    }

to set alpha. The default value is 0.

@param a
@author WFF
@since 1.0.0


public static void loadAllTagClasses() {

        final Map<String, Class<?>> unloadedClasses = new HashMap<>();

        for (final Entry<String, Class<?>> entry : tagClassByTagNameTmp
                .entrySet()) {
            try {

                Class.forName(entry.getValue().getName());

            } catch (final ClassNotFoundException e) {
                unloadedClasses.put(entry.getKey(), entry.getValue());
                if (LOGGER.isLoggable(Level.WARNING)) {
                    LOGGER.warning("Could not load tag class "
                            + entry.getValue().getName());
                }

            }
        }
        tagClassByTagNameTmp.clear();
        if (unloadedClasses.size() > 0) {
            tagClassByTagNameTmp.putAll(unloadedClasses);
        } else {
            tagClassByTagNameTmp = null;
        }
    }

public
static
void
loadAllTagClasses
(
)
{
final
Map
<
String
,
Class
<
>
>
unloadedClasses
=
new
HashMap
<>
(
)
;
for
(
final
Entry
<
String
,
Class
<
>
>
entry
:
tagClassByTagNameTmp
.
entrySet
(
)
)
{
try
{
Class
.
forName
(
entry
.
getValue
(
)
.
getName
(
)
)
;
}
catch
(
final
ClassNotFoundException
e
)
{
unloadedClasses
.
put
(
entry
.
getKey
(
)
,
entry
.
getValue
(
)
)
;
if
(
LOGGER
.
isLoggable
(
Level
.
WARNING
)
)
{
LOGGER
.
warning
(
"Could not load tag class "
+
entry
.
getValue
(
)
.
getName
(
)
)
;
}
}
}
tagClassByTagNameTmp
.
clear
(
)
;
if
(
unloadedClasses
.
size
(
)
>
0
)
{
tagClassByTagNameTmp
.
putAll
(
unloadedClasses
)
;
}
else
{
tagClassByTagNameTmp
=
;
}
}

Loads all tag classes.

@since 2.1.13
@author WFF