public FluidItemListing getFluidItemsForView(
            JobView jobViewParam,
            int queryLimitParam,
            int offsetParam,
            String sortFieldParam,
            String sortOrderParam)
    {
        if(this.serviceTicket != null && jobViewParam != null)
        {
            jobViewParam.setServiceTicket(this.serviceTicket);
        }

        try {
            return new FluidItemListing(this.postJson(
                    jobViewParam,
                    WS.Path.FlowItem.Version1.getByJobView(
                            queryLimitParam,
                            offsetParam,
                            sortFieldParam,
                            sortOrderParam
                    )));
        }
        //rethrow as a Fluid Client exception.
        catch (JSONException jsonExcept) {
            throw new FluidClientException(jsonExcept.getMessage(),
                    FluidClientException.ErrorCode.JSON_PARSING);
        }
    }

public
FluidItemListing
getFluidItemsForView
(
JobView
jobViewParam
,
int
queryLimitParam
,
int
offsetParam
,
String
sortFieldParam
,
String
sortOrderParam
)
{
if
(
this
.
serviceTicket
!=
&&
jobViewParam
!=
)
{
jobViewParam
.
setServiceTicket
(
this
.
serviceTicket
)
;
}
try
{
return
new
FluidItemListing
(
this
.
postJson
(
jobViewParam
,
WS
.
Path
.
FlowItem
.
Version1
.
getByJobView
(
queryLimitParam
,
offsetParam
,
sortFieldParam
,
sortOrderParam
)
)
)
;
}
//rethrow as a Fluid Client exception.
catch
(
JSONException
jsonExcept
)
{
throw
new
FluidClientException
(
jsonExcept
.
getMessage
(
)
,
FluidClientException
.
ErrorCode
.
JSON_PARSING
)
;
}
}

Retrieves items for the provided JobView.

@param jobViewParam The {@link JobView} to retrieve items from.
@param queryLimitParam The query limit.
@param offsetParam The offset.
@param sortFieldParam The sort field.
@param sortOrderParam The sort order.
@return The Fluid items for the {@code jobViewParam}.

Retrieves items for the provided JobView .


public FluidItem sendFormToFlow(
            Form formToSendToFlowParam,
            String flowParam) {

        FluidItem itemToSend = new FluidItem();
        itemToSend.setForm(formToSendToFlowParam);
        itemToSend.setFlow(flowParam);

        if (this.serviceTicket != null) {
            itemToSend.setServiceTicket(this.serviceTicket);
        }

        try {

            return new FluidItem(this.postJson(
                    itemToSend, WS.Path.FlowItem.Version1.sendFlowItemToFlow()));
        } catch (JSONException e) {
            throw new FluidClientException(e.getMessage(), e,
                    FluidClientException.ErrorCode.JSON_PARSING);
        }
    }

public FluidItem sendFormToFlow ( Form formToSendToFlowParam , String flowParam ) { FluidItem itemToSend = new FluidItem ( ) ; itemToSend . setForm ( formToSendToFlowParam ) ; itemToSend . setFlow ( flowParam ) ; if ( this . serviceTicket != null ) { itemToSend . setServiceTicket ( this . serviceTicket ) ; } try { return new FluidItem ( this . postJson ( itemToSend , WS . Path . FlowItem . Version1 . sendFlowItemToFlow ( ) ) ) ; } catch ( JSONException e ) { throw new FluidClientException ( e . getMessage ( ) , e , FluidClientException . ErrorCode . JSON_PARSING ) ; } }

Send a form item to be part of a workflow.

@param formToSendToFlowParam The Form to {@code "Send To Flow (introduction)"} in the workflow process.
@param flowParam The Flow the {@code formToSendToFlowParam} must be sent to.

@return The Fluid item that was initiated in a workflow process.

Send a form item to be part of a workflow .


@OnClose
	public void onClose(Session userSessionParam, CloseReason reasonParam) {
		this.userSession = null;

		if (this.messageHandlers != null) {

			this.messageHandlers.values().forEach(handle ->{
				handle.connectionClosed();
			});
		}
	}

@ OnClose public void onClose ( Session userSessionParam , CloseReason reasonParam ) { this . userSession = null ; if ( this . messageHandlers != null ) { this . messageHandlers . values ( ) . forEach ( handle -> { handle . connectionClosed ( ) ; } ) ; } }

Callback hook for Connection close events.

@param userSessionParam The userSession which is getting closed.
@param reasonParam The reason for connection close.

Callback hook for Connection close events .


@OnMessage
	public void onMessage(String messageParam) {

		boolean handlerFoundForMsg = false;
		for(IMessageResponseHandler handler : new ArrayList<>(this.messageHandlers.values())) {
			Object qualifyObj = handler.doesHandlerQualifyForProcessing(messageParam);
			if(qualifyObj instanceof Error) {
				handler.handleMessage(qualifyObj);
			} else if(qualifyObj instanceof JSONObject) {
				handler.handleMessage(qualifyObj);
				handlerFoundForMsg = true;
				break;
			}
		}

		if(!handlerFoundForMsg) {
			throw new FluidClientException(
					"No handler found for message;\n"+messageParam,
					FluidClientException.ErrorCode.IO_ERROR);
		}
	}

@
OnMessage
public
void
onMessage
(
String
messageParam
)
{
boolean
handlerFoundForMsg
=
false
;
for
(
IMessageResponseHandler
handler
:
new
ArrayList
<>
(
this
.
messageHandlers
.
values
(
)
)
)
{
Object
qualifyObj
=
handler
.
doesHandlerQualifyForProcessing
(
messageParam
)
;
if
(
qualifyObj
instanceof
Error
)
{
handler
.
handleMessage
(
qualifyObj
)
;
}
else
if
(
qualifyObj
instanceof
JSONObject
)
{
handler
.
handleMessage
(
qualifyObj
)
;
handlerFoundForMsg
=
true
;
break
;
}
}
if
(
!
handlerFoundForMsg
)
{
throw
new
FluidClientException
(
"No handler found for message;\n"
+
messageParam
,
FluidClientException
.
ErrorCode
.
IO_ERROR
)
;
}
}

Callback hook for Message Events. This method will be invoked when
a client sends a message.
@param messageParam The text message

Callback hook for Message Events . This method will be invoked when a client sends a message .


public void sendMessage(ABaseFluidJSONObject aBaseFluidJSONObjectParam) {

		if(aBaseFluidJSONObjectParam == null) {
			throw new FluidClientException(
					"No JSON Object to send.",
					FluidClientException.ErrorCode.IO_ERROR);
		} else {
			this.sendMessage(aBaseFluidJSONObjectParam.toJsonObject().toString());
		}
	}

public
void
sendMessage
(
ABaseFluidJSONObject
aBaseFluidJSONObjectParam
)
{
if
(
aBaseFluidJSONObjectParam
==
)
{
throw
new
FluidClientException
(
"No JSON Object to send."
,
FluidClientException
.
ErrorCode
.
IO_ERROR
)
;
}
else
{
this
.
sendMessage
(
aBaseFluidJSONObjectParam
.
toJsonObject
(
)
.
toString
(
)
)
;
}
}

Send a message.

@param aBaseFluidJSONObjectParam The JSON Object to send.


public void sendMessage(String messageToSendParam) {

		if(this.userSession == null) {
			throw new FluidClientException(
					"User Session is not set. Check if connection is open.",
					FluidClientException.ErrorCode.IO_ERROR);
		}

		RemoteEndpoint.Async asyncRemote = null;
		if((asyncRemote = this.userSession.getAsyncRemote()) == null) {
			throw new FluidClientException(
					"Remote Session is not set. Check if connection is open.",
					FluidClientException.ErrorCode.IO_ERROR);
		}

		asyncRemote.sendText(messageToSendParam);
	}

Send a message as text.

@param messageToSendParam The text message to send.


public void closeSession() {
		if(this.userSession == null) {
			return;
		}

		try {
			this.userSession.close();
		} catch (IOException e) {
			throw new FluidClientException(
					"Unable to close session. "+e.getMessage(),
					e,FluidClientException.ErrorCode.IO_ERROR);
		}
	}

public
void
closeSession
(
)
{
if
(
this
.
userSession
==
)
{
return
;
}
try
{
this
.
userSession
.
close
(
)
;
}
catch
(
IOException
e
)
{
throw
new
FluidClientException
(
"Unable to close session. "
+
e
.
getMessage
(
)
,
e
,
FluidClientException
.
ErrorCode
.
IO_ERROR
)
;
}
}


public List<SQLResultSet> executeNativeSQLSynchronized(
            NativeSQLQuery nativeSQLQueryParam) {

        if(nativeSQLQueryParam == null)
        {
            return null;
        }

        if(nativeSQLQueryParam.getDatasourceName() == null ||
                nativeSQLQueryParam.getDatasourceName().isEmpty())
        {
            throw new FluidClientException(
                    "No data-source name provided. Not allowed.",
                    FluidClientException.ErrorCode.FIELD_VALIDATE);
        }

        //No query to execute...
        if((nativeSQLQueryParam.getQuery() == null ||
                nativeSQLQueryParam.getQuery().isEmpty()) &&
                (nativeSQLQueryParam.getStoredProcedure() == null ||
                        nativeSQLQueryParam.getStoredProcedure().isEmpty()))
        {
            return null;
        }

        //Validate the echo...
        this.setEchoIfNotSet(nativeSQLQueryParam);

        //Start a new request...
        String uniqueReqId = this.initNewRequest();

        //Send the actual message...
        this.sendMessage(nativeSQLQueryParam, uniqueReqId);

        try {
            List<SQLResultSet> returnValue =
                    this.getHandler(uniqueReqId).getCF().get(
                            this.getTimeoutInMillis(),TimeUnit.MILLISECONDS);

            //Connection was closed.. this is a problem....
            if(this.getHandler(uniqueReqId).isConnectionClosed())
            {
                throw new FluidClientException(
                        "SQLUtil-WebSocket-ExecuteNativeSQL: " +
                                "The connection was closed by the server prior to the response received.",
                        FluidClientException.ErrorCode.IO_ERROR);
            }

            return returnValue;
        }
        //Interrupted...
        catch (InterruptedException exceptParam) {

            throw new FluidClientException(
                    "SQLUtil-WebSocket-ExecuteNativeSQL: " +
                            exceptParam.getMessage(),
                    exceptParam,
                    FluidClientException.ErrorCode.STATEMENT_EXECUTION_ERROR);
        }
        //Error on the web-socket...
        catch (ExecutionException executeProblem) {

            Throwable cause = executeProblem.getCause();

            //Fluid client exception...
            if(cause instanceof FluidClientException)
            {
                throw (FluidClientException)cause;
            }
            else
            {
                throw new FluidClientException(
                        "SQLUtil-WebSocket-ExecuteNativeSQL: " +
                                cause.getMessage(), cause,
                        FluidClientException.ErrorCode.STATEMENT_EXECUTION_ERROR);
            }
        }
        //Timeout...
        catch (TimeoutException eParam) {

            throw new FluidClientException(
                    "SQLUtil-WebSocket-ExecuteNativeSQL: Timeout while waiting for all return data. There were '"
                            +this.getHandler(uniqueReqId).getReturnValue().size()
                            +"' items after a Timeout of "+(
                            TimeUnit.MILLISECONDS.toSeconds(this.getTimeoutInMillis()))+" seconds."
                    ,FluidClientException.ErrorCode.IO_ERROR);
        }
        finally {
            this.removeHandler(uniqueReqId);
        }
    }

Executes a native SQL query on the remote Fluid instance.

The relevant access must exist.

@param nativeSQLQueryParam The SQL Query to execute.

@return The SQL Execution result as {@code SQLResultSet}'s.

@throws FluidClientException if data-source name is not set.

Executes a native SQL query on the remote Fluid instance .


public String requestLicense(LicenseRequest licenseRequestParam) {

        if(licenseRequestParam != null &&
                this.serviceTicket != null)
        {
            licenseRequestParam.setServiceTicket(this.serviceTicket);
        }

        return this.executeTxtReceiveTxt(
                HttpMethod.POST,
                null,
                false,
                (licenseRequestParam == null) ? null :
                        licenseRequestParam.toJsonObject().toString(),
                ContentType.APPLICATION_JSON,
                Version1.licenseRequest());
    }

public String requestLicense ( LicenseRequest licenseRequestParam ) { if ( licenseRequestParam != null && this . serviceTicket != null ) { licenseRequestParam . setServiceTicket ( this . serviceTicket ) ; } return this . executeTxtReceiveTxt ( HttpMethod . POST , null , false , ( licenseRequestParam == null ) ? null : licenseRequestParam . toJsonObject ( ) . toString ( ) , ContentType . APPLICATION_JSON , Version1 . licenseRequest ( ) ) ; }

Request a new license based on the license request input.

It is important to set the following fields.
{@code Valid From}
{@code Valid To}
{@code User Count}

@param licenseRequestParam The license request used to issue a license request from.
@return The License Request file.

Request a new license based on the license request input .


public LicenseRequest applyLicense(String licenseToApplyParam)
    {
        LicenseRequest liceReq = new LicenseRequest();
        liceReq.setLicenseCipherText(licenseToApplyParam);

        if(this.serviceTicket != null)
        {
            liceReq.setServiceTicket(this.serviceTicket);
        }

        return new LicenseRequest(this.postJson(
                liceReq, Version1.licenseApply()));
    }

public LicenseRequest applyLicense ( String licenseToApplyParam ) { LicenseRequest liceReq = new LicenseRequest ( ) ; liceReq . setLicenseCipherText ( licenseToApplyParam ) ; if ( this . serviceTicket != null ) { liceReq . setServiceTicket ( this . serviceTicket ) ; } return new LicenseRequest ( this . postJson ( liceReq , Version1 . licenseApply ( ) ) ) ; }

Applies a generated license for the server.

@param licenseToApplyParam The clear license to apply.
@return The applied license.

Applies a generated license for the server .


public Field createFieldTextPlain(Field routeFieldParam) {
		if(routeFieldParam != null && this.serviceTicket != null) {
			routeFieldParam.setServiceTicket(this.serviceTicket);
		}

		if(routeFieldParam != null) {
			routeFieldParam.setTypeAsEnum(Field.Type.Text);
			routeFieldParam.setTypeMetaData(FieldMetaData.Text.PLAIN);
		}

		return new Field(this.putJson(
				routeFieldParam, Version1.routeFieldCreate()));
	}

public Field createFieldTextPlain ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . Text ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . Text . PLAIN ) ; } return new Field ( this . putJson ( routeFieldParam , Version1 . routeFieldCreate ( ) ) ) ; }

Create a new Plain Text field.

@param routeFieldParam Field to Create.
@return Created Field.


public Field createFieldParagraphTextPlain(Field routeFieldParam) {
		if(routeFieldParam != null && this.serviceTicket != null) {
			routeFieldParam.setServiceTicket(this.serviceTicket);
		}

		if(routeFieldParam != null) {
			routeFieldParam.setTypeAsEnum(Field.Type.ParagraphText);
			routeFieldParam.setTypeMetaData(FieldMetaData.ParagraphText.PLAIN);
		}

		return new Field(this.putJson(
				routeFieldParam, Version1.routeFieldCreate()));
	}

public Field createFieldParagraphTextPlain ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . ParagraphText ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . ParagraphText . PLAIN ) ; } return new Field ( this . putJson ( routeFieldParam , Version1 . routeFieldCreate ( ) ) ) ; }

Create a new Paragraph Text field.

@param routeFieldParam Field to Create.
@return Created Field.


public Field createFieldParagraphTextHTML(Field routeFieldParam) {
		if(routeFieldParam != null && this.serviceTicket != null) {
			routeFieldParam.setServiceTicket(this.serviceTicket);
		}

		if(routeFieldParam != null) {
			routeFieldParam.setTypeAsEnum(Field.Type.ParagraphText);
			routeFieldParam.setTypeMetaData(FieldMetaData.ParagraphText.HTML);
		}

		return new Field(this.putJson(
				routeFieldParam, Version1.routeFieldCreate()));
	}

public Field createFieldParagraphTextHTML ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . ParagraphText ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . ParagraphText . HTML ) ; } return new Field ( this . putJson ( routeFieldParam , Version1 . routeFieldCreate ( ) ) ) ; }

Create a new Paragraph HTML field.

@param routeFieldParam Field to Create.
@return Created Field.


public Field createFieldMultiChoiceSelectMany(
			Field routeFieldParam,
			List<String> multiChoiceValuesParam
	) {
		if(routeFieldParam != null && this.serviceTicket != null) {
			routeFieldParam.setServiceTicket(this.serviceTicket);
		}

		if(multiChoiceValuesParam == null ||
				multiChoiceValuesParam.isEmpty()) {
			throw new FluidClientException(
					"No Multi-choice values provided.",
					FluidClientException.ErrorCode.FIELD_VALIDATE);
		}

		if(routeFieldParam != null) {
			routeFieldParam.setTypeAsEnum(Field.Type.MultipleChoice);
			routeFieldParam.setTypeMetaData(FieldMetaData.MultiChoice.SELECT_MANY);
			routeFieldParam.setFieldValue(new MultiChoice(multiChoiceValuesParam));
		}

		return new Field(this.putJson(
				routeFieldParam, Version1.routeFieldCreate()));
	}

public
Field
createFieldMultiChoiceSelectMany
(
Field
routeFieldParam
,
List
<
String
>
multiChoiceValuesParam
)
{
if
(
routeFieldParam
!=
&&
this
.
serviceTicket
!=
)
{
routeFieldParam
.
setServiceTicket
(
this
.
serviceTicket
)
;
}
if
(
multiChoiceValuesParam
==
||
multiChoiceValuesParam
.
isEmpty
(
)
)
{
throw
new
FluidClientException
(
"No Multi-choice values provided."
,
FluidClientException
.
ErrorCode
.
FIELD_VALIDATE
)
;
}
if
(
routeFieldParam
!=
)
{
routeFieldParam
.
setTypeAsEnum
(
Field
.
Type
.
MultipleChoice
)
;
routeFieldParam
.
setTypeMetaData
(
FieldMetaData
.
MultiChoice
.
SELECT_MANY
)
;
routeFieldParam
.
setFieldValue
(
new
MultiChoice
(
multiChoiceValuesParam
)
)
;
}
return
new
Field
(
this
.
putJson
(
routeFieldParam
,
Version1
.
routeFieldCreate
(
)
)
)
;
}

Create a new Multi Choice select Many field.

@param routeFieldParam Field to Create.
@param multiChoiceValuesParam The available multi choice values.
@return Created Field.

Create a new Multi Choice select Many field .


public Field createFieldDateTimeDate(Field routeFieldParam) {
		if(routeFieldParam != null && this.serviceTicket != null) {
			routeFieldParam.setServiceTicket(this.serviceTicket);
		}

		if(routeFieldParam != null) {
			routeFieldParam.setTypeAsEnum(Field.Type.DateTime);
			routeFieldParam.setTypeMetaData(FieldMetaData.DateTime.DATE);
		}

		return new Field(this.putJson(
				routeFieldParam, Version1.routeFieldCreate()));
	}

public Field createFieldDateTimeDate ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . DateTime ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . DateTime . DATE ) ; } return new Field ( this . putJson ( routeFieldParam , Version1 . routeFieldCreate ( ) ) ) ; }

Create a new Date only field.

@param routeFieldParam Field to Create.
@return Created Field.


public Field updateFieldTextPlain(Field routeFieldParam) {
		if(routeFieldParam != null && this.serviceTicket != null) {
			routeFieldParam.setServiceTicket(this.serviceTicket);
		}

		if(routeFieldParam != null) {
			routeFieldParam.setTypeAsEnum(Field.Type.Text);
			routeFieldParam.setTypeMetaData(FieldMetaData.Text.PLAIN);
		}

		return new Field(this.postJson(
				routeFieldParam, Version1.routeFieldUpdate()));
	}

public Field updateFieldTextPlain ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . Text ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . Text . PLAIN ) ; } return new Field ( this . postJson ( routeFieldParam , Version1 . routeFieldUpdate ( ) ) ) ; }

Update an existing Text field.

@param routeFieldParam Field to Update.
@return Updated Field.


public Field updateFieldParagraphTextHTML(Field routeFieldParam) {
		if(routeFieldParam != null && this.serviceTicket != null) {
			routeFieldParam.setServiceTicket(this.serviceTicket);
		}

		if(routeFieldParam != null) {
			routeFieldParam.setTypeAsEnum(Field.Type.ParagraphText);
			routeFieldParam.setTypeMetaData(FieldMetaData.ParagraphText.HTML);
		}

		return new Field(this.postJson(
				routeFieldParam, Version1.routeFieldUpdate()));
	}

public Field updateFieldParagraphTextHTML ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . ParagraphText ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . ParagraphText . HTML ) ; } return new Field ( this . postJson ( routeFieldParam , Version1 . routeFieldUpdate ( ) ) ) ; }

Update an existing Paragraph HTML field.

@param routeFieldParam Field to Update.
@return Updated Field.

Update an existing Paragraph HTML field .


public Field updateFieldDateTimeDateAndTime(Field routeFieldParam) {
		if(routeFieldParam != null && this.serviceTicket != null) {
			routeFieldParam.setServiceTicket(this.serviceTicket);
		}

		if(routeFieldParam != null) {
			routeFieldParam.setTypeAsEnum(Field.Type.DateTime);
			routeFieldParam.setTypeMetaData(FieldMetaData.DateTime.DATE_AND_TIME);
		}

		return new Field(this.postJson(
				routeFieldParam, Version1.routeFieldUpdate()));
	}

public Field updateFieldDateTimeDateAndTime ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . DateTime ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . DateTime . DATE_AND_TIME ) ; } return new Field ( this . postJson ( routeFieldParam , Version1 . routeFieldUpdate ( ) ) ) ; }

Update an existing Date and Time field.

@param routeFieldParam Field to Update.
@return Updated Field.

Update an existing Date and Time field .


public Field updateFieldDecimalPlain(Field routeFieldParam) {
		if(routeFieldParam != null && this.serviceTicket != null) {
			routeFieldParam.setServiceTicket(this.serviceTicket);
		}

		if(routeFieldParam != null) {
			routeFieldParam.setTypeAsEnum(Field.Type.Decimal);
			routeFieldParam.setTypeMetaData(FieldMetaData.Decimal.PLAIN);
		}

		return new Field(this.postJson(
				routeFieldParam, Version1.routeFieldUpdate()));
	}

public Field updateFieldDecimalPlain ( Field routeFieldParam ) { if ( routeFieldParam != null && this . serviceTicket != null ) { routeFieldParam . setServiceTicket ( this . serviceTicket ) ; } if ( routeFieldParam != null ) { routeFieldParam . setTypeAsEnum ( Field . Type . Decimal ) ; routeFieldParam . setTypeMetaData ( FieldMetaData . Decimal . PLAIN ) ; } return new Field ( this . postJson ( routeFieldParam , Version1 . routeFieldUpdate ( ) ) ) ; }

Update an existing Decimal field.

@param routeFieldParam Field to Update.
@return Updated Field.


public Field updateFieldValue(Field routeFieldValueParam) {
		if(routeFieldValueParam != null && this.serviceTicket != null) {
			routeFieldValueParam.setServiceTicket(this.serviceTicket);
		}

		return new Field(this.postJson(
				routeFieldValueParam, Version1.routeFieldUpdateValue()));
	}

public Field updateFieldValue ( Field routeFieldValueParam ) { if ( routeFieldValueParam != null && this . serviceTicket != null ) { routeFieldValueParam . setServiceTicket ( this . serviceTicket ) ; } return new Field ( this . postJson ( routeFieldValueParam , Version1 . routeFieldUpdateValue ( ) ) ) ; }

Update an existing 'Route field' value.

@param routeFieldValueParam Field to Update.
@return Updated Field.


public Field createFieldValue(
			Field routeFieldValueToCreateParam,
			FluidItem fluidItemParam) {
		if(routeFieldValueToCreateParam != null && this.serviceTicket != null) {
			routeFieldValueToCreateParam.setServiceTicket(this.serviceTicket);
		}

		Long fluidItmId = (fluidItemParam == null) ? null : fluidItemParam.getId();

		return new Field(this.putJson(
				routeFieldValueToCreateParam,
				Version1.routeFieldCreateValue(fluidItmId)));
	}

public Field createFieldValue ( Field routeFieldValueToCreateParam , FluidItem fluidItemParam ) { if ( routeFieldValueToCreateParam != null && this . serviceTicket != null ) { routeFieldValueToCreateParam . setServiceTicket ( this . serviceTicket ) ; } Long fluidItmId = ( fluidItemParam == null ) ? null : fluidItemParam . getId ( ) ; return new Field ( this . putJson ( routeFieldValueToCreateParam , Version1 . routeFieldCreateValue ( fluidItmId ) ) ) ; }

Create an new 'Route field' value.

@param routeFieldValueToCreateParam Field to Create.
@param fluidItemParam Fluid item to create field for.
@return Created Field.


public Configuration getConfigurationByKey(String configurationKeyParam)
    {
        Configuration configuration = new Configuration();

        configuration.setKey(configurationKeyParam);

        if(this.serviceTicket != null)
        {
            configuration.setServiceTicket(this.serviceTicket);
        }

        return new Configuration(this.postJson(
                configuration, WS.Path.Configuration.Version1.getByKey()));
    }

public Configuration getConfigurationByKey ( String configurationKeyParam ) { Configuration configuration = new Configuration ( ) ; configuration . setKey ( configurationKeyParam ) ; if ( this . serviceTicket != null ) { configuration . setServiceTicket ( this . serviceTicket ) ; } return new Configuration ( this . postJson ( configuration , WS . Path . Configuration . Version1 . getByKey ( ) ) ) ; }

Retrieves a Configuration by Key.

@param configurationKeyParam The Flow key.
@return The Configuration.


public ConfigurationListing getAllConfigurations()
    {
        Configuration configuration = new Configuration();

        if(this.serviceTicket != null)
        {
            configuration.setServiceTicket(this.serviceTicket);
        }

        return new ConfigurationListing(this.postJson(
                configuration, WS.Path.Configuration.Version1.getAllConfigurations()));
    }

public ConfigurationListing getAllConfigurations ( ) { Configuration configuration = new Configuration ( ) ; if ( this . serviceTicket != null ) { configuration . setServiceTicket ( this . serviceTicket ) ; } return new ConfigurationListing ( this . postJson ( configuration , WS . Path . Configuration . Version1 . getAllConfigurations ( ) ) ) ; }

Retrieves all Configurations.

@return All the Configurations.


public Attachment createAttachment(Attachment attachmentParam)
    {
        if(attachmentParam != null && this.serviceTicket != null)
        {
            attachmentParam.setServiceTicket(this.serviceTicket);
        }

        return new Attachment(this.putJson(
                attachmentParam, WS.Path.Attachment.Version1.attachmentCreate()));
    }

public Attachment createAttachment ( Attachment attachmentParam ) { if ( attachmentParam != null && this . serviceTicket != null ) { attachmentParam . setServiceTicket ( this . serviceTicket ) ; } return new Attachment ( this . putJson ( attachmentParam , WS . Path . Attachment . Version1 . attachmentCreate ( ) ) ) ; }

Uploads a new Attachment.
If there is an existing attachment with the same name, a new version will be
uploaded.

@param attachmentParam The attachment to upload.
@return The created attachment.

@see Attachment

Uploads a new Attachment . If there is an existing attachment with the same name a new version will be uploaded .


public Attachment getAttachmentById(
            Long attachmentIdParam,
            boolean includeAttachmentDataParam)
    {
        Attachment attachment = new Attachment(attachmentIdParam);

        if(this.serviceTicket != null)
        {
            attachment.setServiceTicket(this.serviceTicket);
        }

        return new Attachment(this.postJson(
                attachment, WS.Path.Attachment.Version1.getById(
                        includeAttachmentDataParam)));
    }

public Attachment getAttachmentById ( Long attachmentIdParam , boolean includeAttachmentDataParam ) { Attachment attachment = new Attachment ( attachmentIdParam ) ; if ( this . serviceTicket != null ) { attachment . setServiceTicket ( this . serviceTicket ) ; } return new Attachment ( this . postJson ( attachment , WS . Path . Attachment . Version1 . getById ( includeAttachmentDataParam ) ) ) ; }

Retrieves a Attachment by Primary Key.

@param attachmentIdParam The Attachment primary key.
@param includeAttachmentDataParam Include the attachment data (Base-64).

@return The Attachment associated with {@code attachmentIdParam}.


public Attachment deleteAttachment(Attachment attachmentParam)
    {
        if(attachmentParam != null && this.serviceTicket != null)
        {
            attachmentParam.setServiceTicket(this.serviceTicket);
        }

        return new Attachment(this.postJson(
                attachmentParam, WS.Path.Attachment.Version1.attachmentDelete()));
    }

public Attachment deleteAttachment ( Attachment attachmentParam ) { if ( attachmentParam != null && this . serviceTicket != null ) { attachmentParam . setServiceTicket ( this . serviceTicket ) ; } return new Attachment ( this . postJson ( attachmentParam , WS . Path . Attachment . Version1 . attachmentDelete ( ) ) ) ; }

Delete an existing Attachment.

@param attachmentParam The Attachment to delete.
@return The deleted Attachment.


public Attachment forceDeleteAttachment(Attachment attachmentParam)
    {
        if(attachmentParam != null && this.serviceTicket != null)
        {
            attachmentParam.setServiceTicket(this.serviceTicket);
        }

        return new Attachment(this.postJson(
                attachmentParam,
                WS.Path.Attachment.Version1.attachmentDelete(true)));
    }

public Attachment forceDeleteAttachment ( Attachment attachmentParam ) { if ( attachmentParam != null && this . serviceTicket != null ) { attachmentParam . setServiceTicket ( this . serviceTicket ) ; } return new Attachment ( this . postJson ( attachmentParam , WS . Path . Attachment . Version1 . attachmentDelete ( true ) ) ) ; }

Forcefully Delete an existing Attachment.

Only 'admin' can forcefully delete a Attachment.

@param attachmentParam The Attachment to delete.
@return The deleted Attachment.

Forcefully Delete an existing Attachment .


private void parseJarFile(InputStream inputStream) {
        //https://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/
        try {
            Node schemaNode = getSchemaNode(inputStream);

            if (isXsdSchema(schemaNode)){
                XsdSchema.parse(this, schemaNode);
            } else {
                throw new ParsingException("The top level element of a XSD file should be the xsd:schema node.");
            }
        } catch (SAXException | IOException | ParserConfigurationException e) {
            Logger.getAnonymousLogger().log(Level.SEVERE, "Exception while parsing.", e);
        }
    }

Parses the XSD file represented by the received InputStream.
@param inputStream The inputStream of the XSD file.

Parses the XSD file represented by the received InputStream .


private void setClassLoader(String jarPath) {
        if (!jarPath.endsWith(".jar")){
            throw new ParsingException("The jarPath received doesn't represent a jar file.");
        }

        ClassLoader originalCl = Thread.currentThread().getContextClassLoader();

        URL url = originalCl.getResource(jarPath);

        if (url == null){
            try {
                url = new URL("file:/" + jarPath);
            } catch (MalformedURLException e) {
                throw new ParsingException("Invalid jar name.");
            }
        }

        // Create class loader using given codebase
        // Use prevCl as parent to maintain current visibility
        ClassLoader urlCl = URLClassLoader.newInstance(new URL[]{url}, originalCl);

        Thread.currentThread().setContextClassLoader(urlCl);

        classLoader = urlCl;
    }

Creates a new class loader, replacing the current one, having another path added to the classpath. The new
path is the path to the jar received in this class constructor.
@param jarPath The path of the jar file.

Creates a new class loader replacing the current one having another path added to the classpath . The new path is the path to the jar received in this class constructor .


private void rule2() {
        if (!(parent instanceof XsdSchema) && name != null){
            throw new ParsingException(XSD_TAG + " element: The " + NAME_TAG + " should only be used when the parent of the " + XSD_TAG + " is the " + XsdSchema.XSD_TAG + " element." );
        }
    }

Asserts if the current object has the name attribute when not being a direct child of the XsdSchema element, which is
not allowed, throwing an exception in that case.

Asserts if the current object has the name attribute when not being a direct child of the XsdSchema element which is not allowed throwing an exception in that case .


private void rule3() {
        if (parent instanceof XsdSchema && name == null){
            throw new ParsingException(XSD_TAG + " element: The " + NAME_TAG + " should is required the parent of the " + XSD_TAG + " is the " + XsdSchema.XSD_TAG + " element." );
        }
    }

Asserts if the current has no value for its name attribute while being a direct child of the top level XsdSchema element,
which is required. Throws an exception if no name is present.

Asserts if the current has no value for its name attribute while being a direct child of the top level XsdSchema element which is required . Throws an exception if no name is present .


private void rule3() {
        if (attributesMap.containsKey(REF_TAG) && (simpleType != null || form != null || type != null)){
            throw new ParsingException(XSD_TAG + " element: If " + REF_TAG + " attribute is present, simpleType element, form attribute and type attribute cannot be present at the same time.");
        }
    }

Asserts if the current object has a ref attribute at the same time as either a simpleType as children, a form attribute or a type attribute.
Throws an exception in that case.

Asserts if the current object has a ref attribute at the same time as either a simpleType as children a form attribute or a type attribute . Throws an exception in that case .


private Node getSchemaNode(String filePath) throws IOException, SAXException, ParserConfigurationException {
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(filePath);

        doc.getDocumentElement().normalize();

        return doc.getFirstChild();
    }

private Node getSchemaNode ( String filePath ) throws IOException , SAXException , ParserConfigurationException { Document doc = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) . parse ( filePath ) ; doc . getDocumentElement ( ) . normalize ( ) ; return doc . getFirstChild ( ) ; }

This function uses DOM to obtain a list of nodes from a XSD file.
@param filePath The path to the XSD file.
@throws IOException If the file parsing throws {@link IOException}.
@throws SAXException if the file parsing throws {@link SAXException}.
@throws ParserConfigurationException If the {@link DocumentBuilderFactory#newDocumentBuilder()} throws
{@link ParserConfigurationException}.
@return A list of nodes that represent the node tree of the XSD file with the path received.

This function uses DOM to obtain a list of nodes from a XSD file .


private void rule7() {
        if (parent instanceof XsdSchema && attributesMap.containsKey(FORM_TAG)){
            throw new ParsingException(XSD_TAG + " element: The " + FORM_TAG + " attribute can only be present when the parent of the " + xsdElementIsXsdSchema);
        }
    }

Asserts if the current object has a form attribute while being a direct child of the top level XsdSchema element,
which isn't allowed, throwing an exception in that case.

Asserts if the current object has a form attribute while being a direct child of the top level XsdSchema element which isn t allowed throwing an exception in that case .


private void rule3() {
        if (parent instanceof XsdSchema && attributesMap.containsKey(REF_TAG)){
            throw new ParsingException(XSD_TAG + " element: The " + REF_TAG + " attribute cannot be present when the parent of the " + xsdElementIsXsdSchema);
        }
    }

Asserts if the current object has a ref attribute while being a direct child of the top level XsdSchema element, which isn't allowed,
throwing an exception in that case.

Asserts if the current object has a ref attribute while being a direct child of the top level XsdSchema element which isn t allowed throwing an exception in that case .


@Override public T convert(final Object value) {
        if (value == null) {
            return null;
        } else if (isIterable() && Iterable.class.isAssignableFrom(value.getClass())) {
            return convertIterable(value);
        } else if (reflectedKlass.assignableFromObject(value)) {
            return (T) value;
        } else if (reflectedKlass.canBeUnboxed(value.getClass())) {
            return (T) value;
        } else if (reflectedKlass.canBeBoxed(value.getClass())) {
            return (T) value;
        }

        FluentClass<?> klassToCreate;
        if (reflectedKlass.isPrimitive()) {
            klassToCreate = reflectedKlass.boxedType();
        } else {
            klassToCreate = reflectedKlass;
        }

        return (T) convertValueTo(value, klassToCreate);
    }

@ Override public T convert ( final Object value ) { if ( value == null ) { return null ; } else if ( isIterable ( ) && Iterable . class . isAssignableFrom ( value . getClass ( ) ) ) { return convertIterable ( value ) ; } else if ( reflectedKlass . assignableFromObject ( value ) ) { return ( T ) value ; } else if ( reflectedKlass . canBeUnboxed ( value . getClass ( ) ) ) { return ( T ) value ; } else if ( reflectedKlass . canBeBoxed ( value . getClass ( ) ) ) { return ( T ) value ; } FluentClass < ? > klassToCreate ; if ( reflectedKlass . isPrimitive ( ) ) { klassToCreate = reflectedKlass . boxedType ( ) ; } else { klassToCreate = reflectedKlass ; } return ( T ) convertValueTo ( value , klassToCreate ) ; }

If T is assignable from value, then return the value. Otherwise tries to
create an instance of this type using the provided argument.

Will first attempt to find a static method called "valueOf" which returns
this type and takes a single argument compatible with the type of the
value given. If that is not found, tries to find a constructor which
takes an argument of the type of the given value. Otherwise throws a
ClassCastException

@param value
the value to be converted

@throws ClassCastException
if the types cannot be converted

@return the converted value

If T is assignable from value then return the value . Otherwise tries to create an instance of this type using the provided argument .


public static <O> Cli<O> createCli(final Class<O> klass) throws InvalidOptionSpecificationException
    {
        return new CliInterfaceImpl<O>(klass);
    }

public static < O > Cli < O > createCli ( final Class < O > klass ) throws InvalidOptionSpecificationException { return new CliInterfaceImpl < O > ( klass ) ; }

Construct a Cli from an annotated interface definition

@param <O>
The type of the interface that will be used to present the
arguments
@param klass
The annotated interface definition

@return A Cli configured to create instance of klass

@throws ArgumentValidationException the arguments do not meet the CLI specification
@throws InvalidOptionSpecificationException the CLI specification is not valid


public static <O> Cli<O> createCliUsingInstance(final O options) throws InvalidOptionSpecificationException
    {
        return new CliInstanceImpl<O>(options);
    }

public static < O > Cli < O > createCliUsingInstance ( final O options ) throws InvalidOptionSpecificationException { return new CliInstanceImpl < O > ( options ) ; }

Construct a Cli from an annotated class

@param <O>
The type of the class used to present the arguments
@param options
The annotated class

@return A Cli configured to configure the options

@throws ArgumentValidationException the arguments do not meet the CLI specification
@throws InvalidOptionSpecificationException the CLI specification is not valid


public static <O> O parseArguments(final Class<O> klass, final String... arguments)
            throws ArgumentValidationException, InvalidOptionSpecificationException
    {
        return createCli(klass).parseArguments(arguments);
    }

public static < O > O parseArguments ( final Class < O > klass , final String ... arguments ) throws ArgumentValidationException , InvalidOptionSpecificationException { return createCli ( klass ) . parseArguments ( arguments ) ; }

Parse arguments from an annotated interface definition

@param <O>
The type of the interface that will be used to present the
arguments
@param klass
The annotated interface definition
@param arguments

@return The parsed arguments

@throws ArgumentValidationException the arguments do not meet the CLI specification
@throws InvalidOptionSpecificationException the CLI specification is not valid


public static <O> O parseArgumentsUsingInstance(final O options, final String... arguments)
            throws ArgumentValidationException, InvalidOptionSpecificationException
    {
        return createCliUsingInstance(options).parseArguments(arguments);
    }

public static < O > O parseArgumentsUsingInstance ( final O options , final String ... arguments ) throws ArgumentValidationException , InvalidOptionSpecificationException { return createCliUsingInstance ( options ) . parseArguments ( arguments ) ; }

Parse arguments from an annotated class instance

@param <O>
The type of the class used to present the arguments
@param klass
The annotated interface definition
@param arguments

@return The parsed arguments

@throws ArgumentValidationException the arguments do not meet the CLI specification
@throws InvalidOptionSpecificationException the CLI specification is not valid


Builder urlBuilder(String path) {
    Builder builder =
        baseUrlBuilder().addPathSegment(configuration.getApiPackage())
            .addPathSegment(configuration.getApiVersion()).addPathSegment(path);

    if (configuration.getPathModifier() != DiscoveryApiConfiguration.PathModifier.NONE) {
      builder.addPathSegment(configuration.getPathModifier().getModifier());
    }

    return builder;
  }

Builder urlBuilder ( String path ) { Builder builder = baseUrlBuilder ( ) . addPathSegment ( configuration . getApiPackage ( ) ) . addPathSegment ( configuration . getApiVersion ( ) ) . addPathSegment ( path ) ; if ( configuration . getPathModifier ( ) != DiscoveryApiConfiguration . PathModifier . NONE ) { builder . addPathSegment ( configuration . getPathModifier ( ) . getModifier ( ) ) ; } return builder ; }


public boolean removeFooterView(View v) {
		if (mFooterViewInfos.size() > 0) {
			boolean result = false;
			if (mAdapter != null && ((FooterViewGridAdapter) mAdapter).removeFooter(v)) {
				notifiyChanged();
				result = true;
			}
			removeFixedViewInfo(v, mFooterViewInfos);
			return result;
		}
		return false;
	}

public boolean removeFooterView ( View v ) { if ( mFooterViewInfos . size ( ) > 0 ) { boolean result = false ; if ( mAdapter != null && ( ( FooterViewGridAdapter ) mAdapter ) . removeFooter ( v ) ) { notifiyChanged ( ) ; result = true ; } removeFixedViewInfo ( v , mFooterViewInfos ) ; return result ; } return false ; }

Removes a previously-added footer view.

@param v The view to remove
@return
true if the view was removed, false if the view was not a footer view

Removes a previously - added footer view .


public double getValue(double p) {
        if (module == null) {
            throw new NoModuleException();
        }

        double x = (x1 - x0) * p + x0;
        double y = (y1 - y0) * p + y0;
        double z = (z1 - z0) * p + z0;
        double value = module.getValue(x, y, z);

        if (attenuate) {
            return p * (1.0 - p) * 4 * value;
        } else {
            return value;
        }
    }

public double getValue ( double p ) { if ( module == null ) { throw new NoModuleException ( ) ; } double x = ( x1 - x0 ) * p + x0 ; double y = ( y1 - y0 ) * p + y0 ; double z = ( z1 - z0 ) * p + z0 ; double value = module . getValue ( x , y , z ) ; if ( attenuate ) { return p * ( 1.0 - p ) * 4 * value ; } else { return value ; } }

Returns the output value from the noise module given the one-dimensional coordinate of the specified input value located on the line segment.

@param p The distance along the line segment (ranges from 0.0 to 1.0)
@return The output value from the noise module.

Returns the output value from the noise module given the one - dimensional coordinate of the specified input value located on the line segment .


public static double gradientNoise3D(double fx, double fy, double fz, int ix, int iy, int iz, int seed) {
        // Randomly generate a gradient vector given the integer coordinates of the
        // input value.  This implementation generates a random number and uses it
        // as an index into a normalized-vector lookup table.
        int vectorIndex = (X_NOISE_GEN * ix + Y_NOISE_GEN * iy + Z_NOISE_GEN * iz + SEED_NOISE_GEN * seed);
        vectorIndex ^= (vectorIndex >> SHIFT_NOISE_GEN);
        vectorIndex &= 0xff;

        double xvGradient = Utils.RANDOM_VECTORS[(vectorIndex << 2)];
        double yvGradient = Utils.RANDOM_VECTORS[(vectorIndex << 2) + 1];
        double zvGradient = Utils.RANDOM_VECTORS[(vectorIndex << 2) + 2];

        // Set up us another vector equal to the distance between the two vectors
        // passed to this function.
        double xvPoint = (fx - ix);
        double yvPoint = (fy - iy);
        double zvPoint = (fz - iz);

        // Now compute the dot product of the gradient vector with the distance
        // vector.  The resulting value is gradient noise.  Apply a scaling and
        // offset value so that this noise value ranges from 0 to 1.
        return ((xvGradient * xvPoint) + (yvGradient * yvPoint) + (zvGradient * zvPoint)) + 0.5;
    }

Generates a gradient-noise value from the coordinates of a three-dimensional input value and the integer coordinates of a nearby three-dimensional value.

@param fx The floating-point @a x coordinate of the input value.
@param fy The floating-point @a y coordinate of the input value.
@param fz The floating-point @a z coordinate of the input value.
@param ix The integer @a x coordinate of a nearby value.
@param iy The integer @a y coordinate of a nearby value.
@param iz The integer @a z coordinate of a nearby value.
@param seed The random number seed.
@return The generated gradient-noise value.

The difference between fx and ix must be less than or equal to one. The difference between @a fy and @a iy must be less than or equal to one. The difference between @a fz and @a iz must be less
than or equal to one.

A gradient-noise function generates better-quality noise than a value-noise function. Most noise modules use gradient noise for this reason, although it takes much longer to
calculate.

The return value ranges from 0 to 1.

This function generates a gradient-noise value by performing the following steps: - It first calculates a random normalized vector based on the nearby integer value passed to this function. -
It then calculates a new value by adding this vector to the nearby integer value passed to this function. - It then calculates the dot product of the above-generated value and the
floating-point input value passed to this function.

A noise function differs from a random-number generator because it always returns the same output value if the same input value is passed to it.

Generates a gradient - noise value from the coordinates of a three - dimensional input value and the integer coordinates of a nearby three - dimensional value .


public static int intValueNoise3D(int x, int y, int z, int seed) {
        // All constants are primes and must remain prime in order for this noise
        // function to work correctly.
        int n = (X_NOISE_GEN * x + Y_NOISE_GEN * y + Z_NOISE_GEN * z + SEED_NOISE_GEN * seed) & 0x7fffffff;
        n = (n >> 13) ^ n;
        return (n * (n * n * 60493 + 19990303) + 1376312589) & 0x7fffffff;
    }

Generates an integer-noise value from the coordinates of a three-dimensional input value.

@param x The integer @a x coordinate of the input value.
@param y The integer @a y coordinate of the input value.
@param z The integer @a z coordinate of the input value.
@param seed A random number seed.
@return The generated integer-noise value.

The return value ranges from 0 to 2147483647.

A noise function differs from a random-number generator because it always returns the same output value if the same input value is passed to it.

Generates an integer - noise value from the coordinates of a three - dimensional input value .


public static double valueNoise3D(int x, int y, int z, int seed) {
        return intValueNoise3D(x, y, z, seed) / 2147483647.0;
    }

public static double valueNoise3D ( int x , int y , int z , int seed ) { return intValueNoise3D ( x , y , z , seed ) / 2147483647.0 ; }

Generates a value-noise value from the coordinates of a three-dimensional input value.

@param x The @a x coordinate of the input value.
@param y The @a y coordinate of the input value.
@param z The @a z coordinate of the input value.
@param seed A random number seed.
@return The generated value-noise value.

The return value ranges from 0 to 1.

A noise function differs from a random-number generator because it always returns the same output value if the same input value is passed to it.

Generates a value - noise value from the coordinates of a three - dimensional input value .


public static double cubicInterp(double n0, double n1, double n2, double n3, double a) {
        double p = (n3 - n2) - (n0 - n1);
        double q = (n0 - n1) - p;
        double r = n2 - n0;

        return p * a * a * a + q * a * a + r * a + n1;
    }

public static double cubicInterp ( double n0 , double n1 , double n2 , double n3 , double a ) { double p = ( n3 - n2 ) - ( n0 - n1 ) ; double q = ( n0 - n1 ) - p ; double r = n2 - n0 ; return p * a * a * a + q * a * a + r * a + n1 ; }

Performs cubic interpolation between two values bound between two other values

@param n0 the value before the first value
@param n1 the first value
@param n2 the second value
@param n3 the value after the second value
@param a the alpha value
@return the interpolated value


public static double sCurve5(double a) {
        double a3 = a * a * a;
        double a4 = a3 * a;
        double a5 = a4 * a;
        return (6.0 * a5) - (15.0 * a4) + (10.0 * a3);
    }

public static double sCurve5 ( double a ) { double a3 = a * a * a ; double a4 = a3 * a ; double a5 = a4 * a ; return ( 6.0 * a5 ) - ( 15.0 * a4 ) + ( 10.0 * a3 ) ; }

maps a value onto a quitnic S-Curve

@param a the value to map onto a quitic S-curve
@return the mapped value


public void setBounds(double currentLower, double currentUpper, double newLower,
    		double newUpper) {
    	if (currentLower == currentUpper) {
    		throw new IllegalArgumentException("currentLower must not equal currentUpper. Both are " + currentUpper);
    	}
    	if (newLower == newUpper) {
    		throw new IllegalArgumentException("newLowerBound must not equal newUpperBound. Both are " + newUpper);
    	}
    	currentLowerBound = currentLower;
    	currentUpperBound = currentUpper;
    	newLowerBound = newLower;
    	newUpperBound = newUpper;
    	recalculateScaleBias();
    }

Configure bounds for range module
@param currentLower current lower bound
@param currentUpper current upper bound
@param newLower new lower bound
@param newUpper new upper bound


protected void doProcess(final CloudTrailEvent event) {
        for (final FullstopPlugin plugin : getPluginsForEvent(event)) {
            doProcess(event, plugin);
        }
    }

protected void doProcess ( final CloudTrailEvent event ) { for ( final FullstopPlugin plugin : getPluginsForEvent ( event ) ) { doProcess ( event , plugin ) ; } }

Processes an single event by looping available plugins.

@see #doProcess(CloudTrailEvent, FullstopPlugin)

Processes an single event by looping available plugins .


protected void doProcess(final CloudTrailEvent event, final FullstopPlugin plugin) {
        try {
            plugin.processEvent(event);
        } catch (HystrixRuntimeException | HttpServerErrorException e) {
            log.warn(e.getMessage(), e);
        } catch (final Exception e) {
            log.error(e.getMessage(), e);
        }
    }

protected void doProcess ( final CloudTrailEvent event , final FullstopPlugin plugin ) { try { plugin . processEvent ( event ) ; } catch ( HystrixRuntimeException | HttpServerErrorException e ) { log . warn ( e . getMessage ( ) , e ) ; } catch ( final Exception e ) { log . error ( e . getMessage ( ) , e ) ; } }

Processes a specific event on specified plugin.

Processes a specific event on specified plugin .


public static String getAccountId(final CloudTrailEvent event) {
        final CloudTrailEventData eventData = getEventData(event);
        final UserIdentity userIdentity = checkNotNull(eventData.getUserIdentity(), USER_IDENTITY_SHOULD_NEVER_BE_NULL);
        final String value = ofNullable(userIdentity.getAccountId()).orElse(eventData.getRecipientAccountId());
        return checkNotNull(value, ACCOUNT_ID_OR_RECIPIENT_SHOULD_NEVER_BE_NULL);
    }


@Override
    public Boolean apply(final RuleEntity ruleEntity, final ViolationEntity violationEntity) {
        final List<Predicate<ViolationEntity>> predicates = newArrayList();

        trimOptional(ruleEntity.getAccountId())
                .map(WhitelistRulesEvaluator::accountIsEqual)
                .ifPresent(predicates::add);

        trimOptional(ruleEntity.getRegion())
                .map(WhitelistRulesEvaluator::regionIsEqual)
                .ifPresent(predicates::add);

        trimOptional(ruleEntity.getViolationTypeEntityId())
                .map(WhitelistRulesEvaluator::violationTypeIdIsEqual)
                .ifPresent(predicates::add);

        trimOptional(ruleEntity.getImageName())
                .map(WhitelistRulesEvaluator::imageNameMatches)
                .ifPresent(predicates::add);

        trimOptional(ruleEntity.getImageOwner())
                .map(WhitelistRulesEvaluator::imageOwnerIsEqual)
                .ifPresent(predicates::add);

        trimOptional(ruleEntity.getApplicationId())
                .map(WhitelistRulesEvaluator::applicationIdIsEqual)
                .ifPresent(predicates::add);

        trimOptional(ruleEntity.getApplicationVersion())
                .map(WhitelistRulesEvaluator::applicationVersionIsEqual)
                .ifPresent(predicates::add);

        trimOptional(ruleEntity.getMetaInfoJsonPath())
                .map(this::metaInfoJsonPathExists)
                .ifPresent(predicates::add);

        final Optional<Predicate<ViolationEntity>> whiteListTest = predicates.stream().reduce(Predicate::and);

        return whiteListTest.isPresent() && whiteListTest.get().test(violationEntity);
    }

@ Override public Boolean apply ( final RuleEntity ruleEntity , final ViolationEntity violationEntity ) { final List < Predicate < ViolationEntity > > predicates = newArrayList ( ) ; trimOptional ( ruleEntity . getAccountId ( ) ) . map ( WhitelistRulesEvaluator :: accountIsEqual ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getRegion ( ) ) . map ( WhitelistRulesEvaluator :: regionIsEqual ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getViolationTypeEntityId ( ) ) . map ( WhitelistRulesEvaluator :: violationTypeIdIsEqual ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getImageName ( ) ) . map ( WhitelistRulesEvaluator :: imageNameMatches ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getImageOwner ( ) ) . map ( WhitelistRulesEvaluator :: imageOwnerIsEqual ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getApplicationId ( ) ) . map ( WhitelistRulesEvaluator :: applicationIdIsEqual ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getApplicationVersion ( ) ) . map ( WhitelistRulesEvaluator :: applicationVersionIsEqual ) . ifPresent ( predicates :: add ) ; trimOptional ( ruleEntity . getMetaInfoJsonPath ( ) ) . map ( this :: metaInfoJsonPathExists ) . ifPresent ( predicates :: add ) ; final Optional < Predicate < ViolationEntity > > whiteListTest = predicates . stream ( ) . reduce ( Predicate :: and ) ; return whiteListTest . isPresent ( ) && whiteListTest . get ( ) . test ( violationEntity ) ; }

true if rule matches a violation and should be whitelisted.

@return true if rule matches a violation

true if rule matches a violation and should be whitelisted .


private EventSerializer getEventSerializer(final GZIPInputStream inputStream, final CloudTrailLog ctLog)
            throws IOException {
        final EventSerializer serializer;

        if (isEnableRawEventInfo) {
            final String logFileContent = new String(LibraryUtils.toByteArray(inputStream), StandardCharsets.UTF_8);
            final JsonParser jsonParser = this.mapper.getFactory().createParser(logFileContent);
            serializer = new RawLogDeliveryEventSerializer(logFileContent, ctLog, jsonParser);
        }
        else {
            final JsonParser jsonParser = this.mapper.getFactory().createParser(inputStream);
            serializer = new DefaultEventSerializer(ctLog, jsonParser);
        }

        return serializer;
    }

private EventSerializer getEventSerializer ( final GZIPInputStream inputStream , final CloudTrailLog ctLog ) throws IOException { final EventSerializer serializer ; if ( isEnableRawEventInfo ) { final String logFileContent = new String ( LibraryUtils . toByteArray ( inputStream ) , StandardCharsets . UTF_8 ) ; final JsonParser jsonParser = this . mapper . getFactory ( ) . createParser ( logFileContent ) ; serializer = new RawLogDeliveryEventSerializer ( logFileContent , ctLog , jsonParser ) ; } else { final JsonParser jsonParser = this . mapper . getFactory ( ) . createParser ( inputStream ) ; serializer = new DefaultEventSerializer ( ctLog , jsonParser ) ; } return serializer ; }

Get the EventSerializer based on user's configuration.

@param inputStream the Gzipped content from CloudTrail log file
@param ctLog       CloudTrail log file
@return parser that parses CloudTrail log file
@throws java.io.IOException

Get the EventSerializer based on user s configuration .


public File createFile(String fileName) throws IOException {
    Path path = Paths.get(rootFolder.getPath(), fileName);
    return Files.createFile(path).toFile();
  }

public File createFile ( String fileName ) throws IOException { Path path = Paths . get ( rootFolder . getPath ( ) , fileName ) ; return Files . createFile ( path ) . toFile ( ) ; }

Create a file within the temporary folder root.

@param fileName the name of the file to be created
@return the newly created file instance
@throws IOException in case the file creation call fails

Create a file within the temporary folder root .


public File createDirectory(String directoryName) {
    Path path = Paths.get(rootFolder.getPath(), directoryName);
    try {
      return Files.createDirectory(path).toFile();
    } catch (IOException ex) {
      throw new TemporaryFolderException(
          String.format("Failed to create directory: '%s'", path.toString()), ex);
    }
  }

public
File
createDirectory
(
String
directoryName
)
{
Path
path
=
Paths
.
get
(
rootFolder
.
getPath
(
)
,
directoryName
)
;
try
{
return
Files
.
createDirectory
(
path
)
.
toFile
(
)
;
}
catch
(
IOException
ex
)
{
throw
new
TemporaryFolderException
(
String
.
format
(
"Failed to create directory: '%s'"
,
path
.
toString
(
)
)
,
ex
)
;
}
}

Create a directory within the temporary folder root.

@param directoryName the name of the directory to be created
@return the directory instance

Create a directory within the temporary folder root .


public void restore() {
    for (String propertyName : propertyNames) {
      if (restoreProperties.containsKey(propertyName)) {
        // reinstate the original value
        System.setProperty(propertyName, restoreProperties.get(propertyName));
      } else {
        // remove the (previously unset) property
        System.clearProperty(propertyName);
      }
    }
  }

Reverse the system property 'sets' performed on behalf of this restore context.

<p>For each entry in {@link #propertyNames}, if {@link #restoreProperties} contains an entry
then reset the system property with the value from {@link #restoreProperties} otherwise just
remove the system property for that property name.

Reverse the system property sets performed on behalf of this restore context .


private Map<K, V> createImplementation()
   {
      if (delegate instanceof HashMap == false)
         return new HashMap<K, V>(delegate);
      return delegate;
   }

private Map < K , V > createImplementation ( ) { if ( delegate instanceof HashMap == false ) return new HashMap < K , V > ( delegate ) ; return delegate ; }

Create the map implementation

@return the map


public boolean add(final Object obj) {
      maintain();

      SoftObject soft = SoftObject.create(obj, queue);

      return collection.add(soft);
   }

public boolean add ( final Object obj ) { maintain ( ) ; SoftObject soft = SoftObject . create ( obj , queue ) ; return collection . add ( soft ) ; }

Add an object to the collection.

@param obj  Object (or <i>null</i> to add to the collection.
@return     True if object was added.


public static String set(String name, String value)
   {
      return PropertyManager.setProperty(name, value);
   }

public static String set ( String name , String value ) { return PropertyManager . setProperty ( name , value ) ; }

Set a property

@param name    Property name
@param value   Property value
@return        Previous property value or null


public static String[] getArray(String base, String[] defaultValues)
   {
      return PropertyManager.getArrayProperty(base, defaultValues);
   }

public static String [ ] getArray ( String base , String [ ] defaultValues ) { return PropertyManager . getArrayProperty ( base , defaultValues ) ; }

Get an array style property

@param base          Base property name
@param defaultValues Default property values
@return              Array of property values or default


public State nextState(String actionName)
      throws IllegalTransitionException
   {
      Transition t = currentState.getTransition(actionName);
      if( t == null )
      {
         String msg = "No transition for action: '" + actionName
            + "' from state: '" + currentState.getName() + "'";
         throw new IllegalTransitionException(msg);
      }
      State nextState = t.getTarget();
      log.trace("nextState("+actionName+") = "+nextState);
      currentState = nextState;
      return currentState;
   }

public
State
nextState
(
String
actionName
)
throws
IllegalTransitionException
{
Transition
t
=
currentState
.
getTransition
(
actionName
)
;
if
(
t
==
)
{
String
msg
=
"No transition for action: '"
+
actionName
+
"' from state: '"
+
currentState
.
getName
(
)
+
"'"
;
throw
new
IllegalTransitionException
(
msg
)
;
}
State
nextState
=
t
.
getTarget
(
)
;
log
.
trace
(
"nextState("
+
actionName
+
") = "
+
nextState
)
;
currentState
=
nextState
;
return
currentState
;
}

Transition to the next state given the name of a valid transition.
@param actionName - the name of transition that is valid for the
current state.
@return the next state
@throws IllegalTransitionException

Transition to the next state given the name of a valid transition .


private void processQueue()
   {
      ComparableSoftReference cr;
      while( (cr = (ComparableSoftReference) gcqueue.poll()) != null )
      {
         map.remove(cr.getKey());
      }
   }

private void processQueue ( ) { ComparableSoftReference cr ; while ( ( cr = ( ComparableSoftReference ) gcqueue . poll ( ) ) != null ) { map . remove ( cr . getKey ( ) ) ; } }

Iterate through the gcqueue for for any cleared reference, remove
the associated value from the underlying set.

Iterate through the gcqueue for for any cleared reference remove the associated value from the underlying set .


@SuppressWarnings({"unchecked", "cast"})
   public T get(Type type)
   {
      if (type == null)
         throw new IllegalArgumentException("Null type");

      if (type instanceof ParameterizedType)
         return getParameterizedType((ParameterizedType) type);
      else if (type instanceof Class)
         return getClass((Class<?>) type);
      else if (type instanceof TypeVariable)
         // TODO Figure out why we need this cast with the Sun compiler?
         return (T) getTypeVariable((TypeVariable) type);
      else if (type instanceof GenericArrayType)
         return getGenericArrayType((GenericArrayType) type);
      else if (type instanceof WildcardType)
         return getWildcardType((WildcardType) type);
      else
         throw new UnsupportedOperationException("Unknown type: " + type + " class=" + type.getClass());
   }

Get the information for a type

@param type the type
@return the info


protected T getParameterizedType(ParameterizedType type)
   {
      // First check if we already have it
      T result = peek(type);
      if (result != null)
         return result;

      // Instantiate
      result = instantiate(type);

      // Put the perlimanary result into the cache
      put(type, result);

      // Generate the details
      generate(type, result);

      return result;
   }

Get the information for a parameterized type

@param type the parameterized type
@return the info


protected <D extends GenericDeclaration> T getTypeVariable(TypeVariable<D> type)
   {
      // TODO JBMICROCONT-131 improve this
      return get(type.getBounds()[0]);
   }

protected
<
D
extends
GenericDeclaration
>
T
getTypeVariable
(
TypeVariable
<
D
>
type
)
{
// TODO JBMICROCONT-131 improve this
return
get
(
type
.
getBounds
(
)
[
0
]
)
;
}

Get the information for a type variable

@param <D> the declaration
@param type the type variable
@return the info


public void printStackTrace(final PrintStream stream) {
      if (nested == null || NestedThrowable.PARENT_TRACE_ENABLED) {
         super.printStackTrace(stream);
      }
      NestedThrowable.Util.print(nested, stream);
   }

public void printStackTrace ( final PrintStream stream ) { if ( nested == null || NestedThrowable . PARENT_TRACE_ENABLED ) { super . printStackTrace ( stream ) ; } NestedThrowable . Util . print ( nested , stream ) ; }

Prints the composite message and the embedded stack trace to the
specified print stream.

@param stream  Stream to print to.

Prints the composite message and the embedded stack trace to the specified print stream .


public void printStackTrace(final PrintWriter writer) {
      if (nested == null || NestedThrowable.PARENT_TRACE_ENABLED) {
         super.printStackTrace(writer);
      }
      NestedThrowable.Util.print(nested, writer);
   }

public void printStackTrace ( final PrintWriter writer ) { if ( nested == null || NestedThrowable . PARENT_TRACE_ENABLED ) { super . printStackTrace ( writer ) ; } NestedThrowable . Util . print ( nested , writer ) ; }

Prints the composite message and the embedded stack trace to the
specified print writer.

@param writer  Writer to print to.

Prints the composite message and the embedded stack trace to the specified print writer .


protected Object replaceObject(Object obj) throws IOException
   {
      if( (obj instanceof Remote) && !(obj instanceof RemoteStub) )
      {
         Remote remote = (Remote) obj;
         try
         {
            obj = RemoteObject.toStub(remote);
         }
         catch(IOException ignore)
         {
            // Let the Serialization layer try with the orignal obj
         }
      }
      return obj;
   }

Override replaceObject to check for Remote objects that are
not RemoteStubs.

Override replaceObject to check for Remote objects that are not RemoteStubs .


public void run()
   {
      // Get the execution thread
      this.runThread = Thread.currentThread();

      // Check for a start timeout
      long runTime = getElapsedTime();
      if (startTimeout > 0l && runTime >= startTimeout)
      {
         taskRejected(new StartTimeoutException("Start Timeout exceeded for task " + taskString));
         return;
      }

      // We are about to start, check for a stop
      boolean stopped = false;
      synchronized (stateLock)
      {
         if (state == TASK_STOPPED)
         {
            stopped = true;
         }
         else
         {
            state = TASK_STARTED;
            taskStarted();
            if (waitType == Task.WAIT_FOR_START)
               stateLock.notifyAll();
         }
      }
      if (stopped)
      {
         taskRejected(new TaskStoppedException("Task stopped for task " + taskString));
         return;
      }

      // Run the task
      Throwable throwable = null;
      try
      {
         task.execute();
      }
      catch (Throwable t)
      {
         throwable = t;
      }

      // It is complete
      taskCompleted(throwable);

      // We are completed
      synchronized (stateLock)
      {
         state = TASK_COMPLETED;
         if (waitType == Task.WAIT_FOR_COMPLETE)
            stateLock.notifyAll();
      }
   }


protected void setTask(Task task)
   {
      if (task == null)
         throw new IllegalArgumentException("Null task");
      this.task = task;
      this.taskString = task.toString();
      this.startTime = System.currentTimeMillis();
      this.waitType = task.getWaitType();
      this.priority = task.getPriority();
      this.startTimeout = task.getStartTimeout();
      this.completionTimeout = task.getCompletionTimeout();
   }

protected
void
setTask
(
Task
task
)
{
if
(
task
==
)
throw
new
IllegalArgumentException
(
"Null task"
)
;
this
.
task
=
task
;
this
.
taskString
=
task
.
toString
(
)
;
this
.
startTime
=
System
.
currentTimeMillis
(
)
;
this
.
waitType
=
task
.
getWaitType
(
)
;
this
.
priority
=
task
.
getPriority
(
)
;
this
.
startTimeout
=
task
.
getStartTimeout
(
)
;
this
.
completionTimeout
=
task
.
getCompletionTimeout
(
)
;
}

Set thetask for this wrapper

@param task the task


protected boolean taskAccepted()
   {
      try
      {
         task.accepted(getElapsedTime());
         return true;
      }
      catch (Throwable t)
      {
         log.warn("Unexpected error during 'accepted' for task: " + taskString, t);
         return false;
      }
   }

Notify the task it has been accepted

@return true when the notification succeeds, false otherwise


protected boolean taskRejected(RuntimeException e)
   {
      try
      {
         task.rejected(getElapsedTime(), e);
         return true;
      }
      catch (Throwable t)
      {
         log.warn("Unexpected error during 'rejected' for task: " + taskString, t);
         if (e != null)
            log.warn("Original reason for rejection of task: " + taskString, e);
         return false;
      }
   }

Notify the task it has been rejected

@param e any error associated with the rejection
@return true when the notification succeeds, false otherwise


protected boolean taskStarted()
   {
      try
      {
         task.started(getElapsedTime());
         return true;
      }
      catch (Throwable t)
      {
         log.warn("Unexpected error during 'started' for task: " + taskString, t);
         return false;
      }
   }

Notify the task it has started

@return true when the notification succeeds, false otherwise


protected boolean taskCompleted(Throwable throwable)
   {
      try
      {
         task.completed(getElapsedTime(), throwable);
         return true;
      }
      catch (Throwable t)
      {
         log.warn("Unexpected error during 'completed' for task: " + taskString, t);
         if (throwable != null)
            log.warn("Original error during 'run' for task: " + taskString, throwable);
         return false;
      }
   }

Notify the task it has completed

@param throwable any throwable associated with the completion
@return true when the notification succeeds, false otherwise


protected boolean taskStop()
   {
      try
      {
         task.stop();
         return true;
      }
      catch (Throwable t)
      {
         log.warn("Unexpected error during 'stop' for task: " + taskString, t);
         return false;
      }
   }

Stop the task

@return true when the notification succeeds, false otherwise


protected Executable getJobImpl() throws InterruptedException
   {
      // While the queue is empty, wait();
      // when notified take an event from the queue and return it.
      while (m_currentJob == null) {wait();}
      // This one is the job to return
      JobItem item = m_currentJob;
      // Go on to the next object for the next call.
      m_currentJob = m_currentJob.m_next;
      return item.m_job;
   }

Never call this method, only override in subclasses to perform
job getting in a specific way, normally tied to the data structure
holding the jobs.
@return the exectuable
@throws InterruptedException

Never call this method only override in subclasses to perform job getting in a specific way normally tied to the data structure holding the jobs .


protected void putJobImpl(Executable job)
   {
      JobItem posted = new JobItem(job);
      if (m_currentJob == null)
      {
         // The queue is empty, set the current job to process and
         // wake up the thread waiting in method getJob
         m_currentJob = posted;
         notifyAll();
      }
      else
      {
         JobItem item = m_currentJob;
         // The queue is not empty, find the end of the queue ad add the
         // posted job at the end
         while (item.m_next != null) {item = item.m_next;}
         item.m_next = posted;
      }
   }

Never call this method, only override in subclasses to perform
job adding in a specific way, normally tied to the data structure
holding the jobs.
@param job

Never call this method only override in subclasses to perform job adding in a specific way normally tied to the data structure holding the jobs .


public static final BlockingMode toBlockingMode(String name)
   {
      BlockingMode mode = null;
      if( name == null )
      {
         mode = null;
      }
      else if( name.equalsIgnoreCase("run") )
      {
         mode = RUN;
      }
      else if( name.equalsIgnoreCase("wait") )
      {
         mode = WAIT;
      }
      else if( name.equalsIgnoreCase("discard") )
      {
         mode = DISCARD;
      }
      else if( name.equalsIgnoreCase("discardOldest") )
      {
         mode = DISCARD_OLDEST;
      }
      else if( name.equalsIgnoreCase("abort") )
      {
         mode = ABORT;
      }
      return mode;
   }

public static final BlockingMode toBlockingMode ( String name ) { BlockingMode mode = null ; if ( name == null ) { mode = null ; } else if ( name . equalsIgnoreCase ( "run" ) ) { mode = RUN ; } else if ( name . equalsIgnoreCase ( "wait" ) ) { mode = WAIT ; } else if ( name . equalsIgnoreCase ( "discard" ) ) { mode = DISCARD ; } else if ( name . equalsIgnoreCase ( "discardOldest" ) ) { mode = DISCARD_OLDEST ; } else if ( name . equalsIgnoreCase ( "abort" ) ) { mode = ABORT ; } return mode ; }

A utility method to convert a string name to a BlockingMode
@param name
@return The associated BlockingMode constant if name is valid, null otherwise


Object readResolve() throws ObjectStreamException
   {
      // Replace the marshalled instance type with the local instance
      BlockingMode mode = ABORT;
      switch( type )
      {
         case RUN_TYPE:
            mode = RUN;
            break;
         case WAIT_TYPE:
            mode = RUN;
            break;
         case DISCARD_TYPE:
            mode = RUN;
            break;
         case DISCARD_OLDEST_TYPE:
            mode = RUN;
            break;
         case ABORT_TYPE:
            mode = RUN;
            break;
      }
      return mode;
   }

Overriden to return the indentity instance of BlockingMode based on the
stream type int value. This ensures that BlockingMode enums can be
compared using ==.

@return The BlockingMode instance for the XXX_TYPE int.
@throws ObjectStreamException

Overriden to return the indentity instance of BlockingMode based on the stream type int value . This ensures that BlockingMode enums can be compared using == .


public void setupReaders() {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    spf.setValidating(false);

    SAXCatalogReader saxReader = new SAXCatalogReader(spf);

    saxReader.setCatalogParser(null, "XMLCatalog",
			       "org.apache.xml.resolver.readers.XCatalogReader");

    saxReader.setCatalogParser(OASISXMLCatalogReader.namespaceName,
			       "catalog",
			       "org.apache.xml.resolver.readers.OASISXMLCatalogReader");

    addReader("application/xml", saxReader);

    TR9401CatalogReader textReader = new TR9401CatalogReader();
    addReader("text/plain", textReader);
  }


public void addReader(String mimeType, CatalogReader reader) {
    if (readerMap.containsKey(mimeType)) {
      Integer pos = (Integer) readerMap.get(mimeType);
      readerArr.set(pos.intValue(), reader);
    } else {
      readerArr.add(reader);
      Integer pos = new Integer(readerArr.size()-1);
      readerMap.put(mimeType, pos);
    }
  }

public void addReader ( String mimeType , CatalogReader reader ) { if ( readerMap . containsKey ( mimeType ) ) { Integer pos = ( Integer ) readerMap . get ( mimeType ) ; readerArr . set ( pos . intValue ( ) , reader ) ; } else { readerArr . add ( reader ) ; Integer pos = new Integer ( readerArr . size ( ) - 1 ) ; readerMap . put ( mimeType , pos ) ; } }

Add a new CatalogReader to the Catalog.

This method allows you to add a new CatalogReader to the
catalog. The reader will be associated with the specified mimeType.
You can only have one reader per mimeType.

In the absence of a mimeType (e.g., when reading a catalog
directly from a file on the local system), the readers are attempted
in the order that you add them to the Catalog.

Note that subordinate catalogs (created by CATALOG or
DELEGATE* entries) get a copy of the set of readers present in
the primary catalog when they are created. Readers added subsequently
will not be available. For this reason, it is best to add all
of the readers before the first call to parse a catalog.

@param mimeType The MIME type associated with this reader.
@param reader The CatalogReader to use.

Add a new CatalogReader to the Catalog .


protected void copyReaders(Catalog newCatalog) {
    // Have to copy the readers in the right order...convert hash to arr
    Vector mapArr = new Vector(readerMap.size());

    // Pad the mapArr out to the right length
    for (int count = 0; count < readerMap.size(); count++) {
      mapArr.add(null);
    }

    Enumeration enumt = readerMap.keys();
    while (enumt.hasMoreElements()) {
      String mimeType = (String) enumt.nextElement();
      Integer pos = (Integer) readerMap.get(mimeType);
      mapArr.set(pos.intValue(), mimeType);
    }

    for (int count = 0; count < mapArr.size(); count++) {
      String mimeType = (String) mapArr.get(count);
      Integer pos = (Integer) readerMap.get(mimeType);
      newCatalog.addReader(mimeType,
			   (CatalogReader)
			   readerArr.get(pos.intValue()));
    }
  }

Copies the reader list from the current Catalog to a new Catalog.

<p>This method is used internally when constructing a new catalog.
It copies the current reader associations over to the new catalog.
</p>

@param newCatalog The new Catalog.

Copies the reader list from the current Catalog to a new Catalog .


protected Catalog newCatalog() {
    String catalogClass = this.getClass().getName();

    try {
      Catalog c = (Catalog) (Class.forName(catalogClass).newInstance());
      c.setCatalogManager(catalogManager);
      copyReaders(c);
      return c;
    } catch (ClassNotFoundException cnfe) {
      catalogManager.debug.message(1, "Class Not Found Exception: " + catalogClass);
    } catch (IllegalAccessException iae) {
      catalogManager.debug.message(1, "Illegal Access Exception: " + catalogClass);
    } catch (InstantiationException ie) {
      catalogManager.debug.message(1, "Instantiation Exception: " + catalogClass);
    } catch (ClassCastException cce) {
      catalogManager.debug.message(1, "Class Cast Exception: " + catalogClass);
    } catch (Exception e) {
      catalogManager.debug.message(1, "Other Exception: " + catalogClass);
    }

    Catalog c = new Catalog();
    c.setCatalogManager(catalogManager);
    copyReaders(c);
    return c;
  }

protected
Catalog
newCatalog
(
)
{
String
catalogClass
=
this
.
getClass
(
)
.
getName
(
)
;
try
{
Catalog
c
=
(
Catalog
)
(
Class
.
forName
(
catalogClass
)
.
newInstance
(
)
)
;
c
.
setCatalogManager
(
catalogManager
)
;
copyReaders
(
c
)
;
return
c
;
}
catch
(
ClassNotFoundException
cnfe
)
{
catalogManager
.
debug
.
message
(
1
,
"Class Not Found Exception: "
+
catalogClass
)
;
}
catch
(
IllegalAccessException
iae
)
{
catalogManager
.
debug
.
message
(
1
,
"Illegal Access Exception: "
+
catalogClass
)
;
}
catch
(
InstantiationException
ie
)
{
catalogManager
.
debug
.
message
(
1
,
"Instantiation Exception: "
+
catalogClass
)
;
}
catch
(
ClassCastException
cce
)
{
catalogManager
.
debug
.
message
(
1
,
"Class Cast Exception: "
+
catalogClass
)
;
}
catch
(
Exception
e
)
{
catalogManager
.
debug
.
message
(
1
,
"Other Exception: "
+
catalogClass
)
;
}
Catalog
c
=
new
Catalog
(
)
;
c
.
setCatalogManager
(
catalogManager
)
;
copyReaders
(
c
)
;
return
c
;
}

Create a new Catalog object.

This method constructs a new instance of the running Catalog
class (which might be a subtype of org.apache.xml.resolver.Catalog).
All new catalogs are managed by the same CatalogManager.

N.B. All Catalog subtypes should call newCatalog() to construct
a new Catalog. Do not simply use "new Subclass()" since that will
confuse future subclasses.

@return the catalog


public void loadSystemCatalogs()
    throws MalformedURLException, IOException {

    Vector catalogs = catalogManager.getCatalogFiles();
    if (catalogs != null) {
      for (int count = 0; count < catalogs.size(); count++) {
	catalogFiles.addElement(catalogs.elementAt(count));
      }
    }

    if (catalogFiles.size() > 0) {
      // This is a little odd. The parseCatalog() method expects
      // a filename, but it adds that name to the end of the
      // catalogFiles vector, and then processes that vector.
      // This allows the system to handle CATALOG entries
      // correctly.
      //
      // In this init case, we take the last element off the
      // catalogFiles vector and pass it to parseCatalog. This
      // will "do the right thing" in the init case, and allow
      // parseCatalog() to do the right thing in the non-init
      // case. Honest.
      //
      String catfile = (String) catalogFiles.lastElement();
      catalogFiles.removeElement(catfile);
      parseCatalog(catfile);
    }
  }

Load the system catalog files.

The method adds all of the
catalogs specified in the <tt>xml.catalog.files</tt> property
to the Catalog list.

@throws MalformedURLException  One of the system catalogs is
identified with a filename that is not a valid URL.
@throws IOException One of the system catalogs cannot be read.


public synchronized void parseCatalog(URL aUrl) throws IOException {
    catalogCwd = aUrl;
    base = aUrl;

    default_override = catalogManager.getPreferPublic();
    catalogManager.debug.message(4, "Parse catalog: " + aUrl.toString());

    DataInputStream inStream = null;
    boolean parsed = false;

    for (int count = 0; !parsed && count < readerArr.size(); count++) {
      CatalogReader reader = (CatalogReader) readerArr.get(count);

      try {
      	inStream = new DataInputStream(aUrl.openStream());
      } catch (FileNotFoundException fnfe) {
        // No catalog; give up!
        break;
      }

      try {
        reader.readCatalog(this, inStream);
        parsed=true;
      } catch (CatalogException ce) {
        if (ce.getExceptionType() == CatalogException.PARSE_FAILED) {
          // give up!
          break;
        } else {
          // try again!
        }
      }

      try {
      	inStream.close();
      } catch (IOException e) {
      	//nop
      }
    }

    if (parsed) parsePendingCatalogs();
  }

public
synchronized
void
parseCatalog
(
URL
aUrl
)
throws
IOException
{
catalogCwd
=
aUrl
;
base
=
aUrl
;
default_override
=
catalogManager
.
getPreferPublic
(
)
;
catalogManager
.
debug
.
message
(
4
,
"Parse catalog: "
+
aUrl
.
toString
(
)
)
;
DataInputStream
inStream
=
;
boolean
parsed
=
false
;
for
(
int
count
=
0
;
!
parsed
&&
count
<
readerArr
.
size
(
)
;
count
++
)
{
CatalogReader
reader
=
(
CatalogReader
)
readerArr
.
get
(
count
)
;
try
{
inStream
=
new
DataInputStream
(
aUrl
.
openStream
(
)
)
;
}
catch
(
FileNotFoundException
fnfe
)
{
// No catalog; give up!
break
;
}
try
{
reader
.
readCatalog
(
this
,
inStream
)
;
parsed
=
true
;
}
catch
(
CatalogException
ce
)
{
if
(
ce
.
getExceptionType
(
)
==
CatalogException
.
PARSE_FAILED
)
{
// give up!
break
;
}
else
{
// try again!
}
}
try
{
inStream
.
close
(
)
;
}
catch
(
IOException
e
)
{
//nop
}
}
if
(
parsed
)
parsePendingCatalogs
(
)
;
}

Parse a catalog document, augmenting internal data structures.

This method supports catalog files stored in jar files: e.g.,
jar:file:///path/to/filename.jar!/path/to/catalog.xml". That URI
doesn't survive transmogrification through the URI processing that
the parseCatalog(String) performs and passing it as an input stream
doesn't set the base URI appropriately.

Written by Stefan Wachter (2002-09-26)

@param aUrl The URL of the catalog document to process

@throws IOException Error reading catalog file.

Parse a catalog document augmenting internal data structures .


protected synchronized void parsePendingCatalogs()
    throws MalformedURLException, IOException {

    if (!localCatalogFiles.isEmpty()) {
      // Move all the localCatalogFiles into the front of
      // the catalogFiles queue
      Vector newQueue = new Vector();
      Enumeration q = localCatalogFiles.elements();
      while (q.hasMoreElements()) {
	newQueue.addElement(q.nextElement());
      }

      // Put the rest of the catalogs on the end of the new list
      for (int curCat = 0; curCat < catalogFiles.size(); curCat++) {
	String catfile = (String) catalogFiles.elementAt(curCat);
	newQueue.addElement(catfile);
      }

      catalogFiles = newQueue;
      localCatalogFiles.clear();
    }

    // Suppose there are no catalog files to process, but the
    // single catalog already parsed included some delegate
    // entries? Make sure they don't get lost.
    if (catalogFiles.isEmpty() && !localDelegate.isEmpty()) {
      Enumeration e = localDelegate.elements();
      while (e.hasMoreElements()) {
	catalogEntries.addElement(e.nextElement());
      }
      localDelegate.clear();
    }

    // Now process all the files on the catalogFiles vector. This
    // vector can grow during processing if CATALOG entries are
    // encountered in the catalog
    while (!catalogFiles.isEmpty()) {
      String catfile = (String) catalogFiles.elementAt(0);
      try {
	catalogFiles.remove(0);
      } catch (ArrayIndexOutOfBoundsException e) {
	// can't happen
      }

      if (catalogEntries.size() == 0 && catalogs.size() == 0) {
	// We haven't parsed any catalogs yet, let this
	// catalog be the first...
	try {
	  parseCatalogFile(catfile);
	} catch (CatalogException ce) {
	  System.out.println("FIXME: " + ce.toString());
	}
      } else {
	// This is a subordinate catalog. We save its name,
	// but don't bother to load it unless it's necessary.
	catalogs.addElement(catfile);
      }

      if (!localCatalogFiles.isEmpty()) {
	// Move all the localCatalogFiles into the front of
	// the catalogFiles queue
	Vector newQueue = new Vector();
	Enumeration q = localCatalogFiles.elements();
	while (q.hasMoreElements()) {
	  newQueue.addElement(q.nextElement());
	}

	// Put the rest of the catalogs on the end of the new list
	for (int curCat = 0; curCat < catalogFiles.size(); curCat++) {
	  catfile = (String) catalogFiles.elementAt(curCat);
	  newQueue.addElement(catfile);
	}

	catalogFiles = newQueue;
	localCatalogFiles.clear();
      }

      if (!localDelegate.isEmpty()) {
	Enumeration e = localDelegate.elements();
	while (e.hasMoreElements()) {
	  catalogEntries.addElement(e.nextElement());
	}
	localDelegate.clear();
      }
    }

    // We've parsed them all, reinit the vector...
    catalogFiles.clear();
  }

Parse all of the pending catalogs.

Catalogs may refer to other catalogs, this method parses
all of the currently pending catalog files.

@throws MalformedURLException
@throws IOException


protected synchronized void parseCatalogFile(String fileName)
    throws MalformedURLException, IOException, CatalogException {

    // The base-base is the cwd. If the catalog file is specified
    // with a relative path, this assures that it gets resolved
    // properly...
    try {
      // tack on a basename because URLs point to files not dirs
      String userdir = fixSlashes(System.getProperty("user.dir"));
      catalogCwd = new URL("file:" + userdir + "/basename");
    } catch (MalformedURLException e) {
      String userdir = fixSlashes(System.getProperty("user.dir"));
      catalogManager.debug.message(1, "Malformed URL on cwd", userdir);
      catalogCwd = null;
    }

    // The initial base URI is the location of the catalog file
    try {
      base = new URL(catalogCwd, fixSlashes(fileName));
    } catch (MalformedURLException e) {
      try {
	base = new URL("file:" + fixSlashes(fileName));
      } catch (MalformedURLException e2) {
	catalogManager.debug.message(1, "Malformed URL on catalog filename",
		      fixSlashes(fileName));
	base = null;
      }
    }

    catalogManager.debug.message(2, "Loading catalog", fileName);
    catalogManager.debug.message(4, "Default BASE", base.toString());

    fileName = base.toString();

    DataInputStream inStream = null;
    boolean parsed = false;
    boolean notFound = false;

    for (int count = 0; !parsed && count < readerArr.size(); count++) {
      CatalogReader reader = (CatalogReader) readerArr.get(count);

      try {
	notFound = false;
	inStream = new DataInputStream(base.openStream());
      } catch (FileNotFoundException fnfe) {
	// No catalog; give up!
	notFound = true;
	break;
      }

      try {
	reader.readCatalog(this, inStream);
	parsed = true;
      } catch (CatalogException ce) {
	if (ce.getExceptionType() == CatalogException.PARSE_FAILED) {
	  // give up!
	  break;
	} else {
	  // try again!
	}
      }

      try {
	inStream.close();
      } catch (IOException e) {
	//nop
      }
    }

    if (!parsed) {
      if (notFound) {
	catalogManager.debug.message(3, "Catalog does not exist", fileName);
      } else {
	catalogManager.debug.message(1, "Failed to parse catalog", fileName);
      }
    }
  }

Parse a single catalog file, augmenting internal data structures.

@param fileName The filename of the catalog file to process

@throws MalformedURLException The fileName cannot be turned into
a valid URL.
@throws IOException Error reading catalog file.
@throws CatalogException for any error

Parse a single catalog file augmenting internal data structures .


public void unknownEntry(Vector strings) {
    if (strings != null && strings.size() > 0) {
      String keyword = (String) strings.elementAt(0);
      catalogManager.debug.message(2, "Unrecognized token parsing catalog", keyword);
    }
  }

public
void
unknownEntry
(
Vector
strings
)
{
if
(
strings
!=
&&
strings
.
size
(
)
>
0
)
{
String
keyword
=
(
String
)
strings
.
elementAt
(
0
)
;
catalogManager
.
debug
.
message
(
2
,
"Unrecognized token parsing catalog"
,
keyword
)
;
}
}

Handle unknown CatalogEntry types.

This method exists to allow subclasses to deal with unknown
entry types.

@param strings


public void parseAllCatalogs()
    throws MalformedURLException, IOException {

    // Parse all the subordinate catalogs
    for (int catPos = 0; catPos < catalogs.size(); catPos++) {
      Catalog c = null;

      try {
	c = (Catalog) catalogs.elementAt(catPos);
      } catch (ClassCastException e) {
	String catfile = (String) catalogs.elementAt(catPos);
	c = newCatalog();

	c.parseCatalog(catfile);
	catalogs.setElementAt(c, catPos);
	c.parseAllCatalogs();
      }
    }

    // Parse all the DELEGATE catalogs
    Enumeration enumt = catalogEntries.elements();
    while (enumt.hasMoreElements()) {
      CatalogEntry e = (CatalogEntry) enumt.nextElement();
      if (e.getEntryType() == DELEGATE_PUBLIC
	  || e.getEntryType() == DELEGATE_SYSTEM
	  || e.getEntryType() == DELEGATE_URI) {
	Catalog dcat = newCatalog();
	dcat.parseCatalog(e.getEntryArg(1));
      }
    }
  }

public
void
parseAllCatalogs
(
)
throws
MalformedURLException
,
IOException
{
// Parse all the subordinate catalogs
for
(
int
catPos
=
0
;
catPos
<
catalogs
.
size
(
)
;
catPos
++
)
{
Catalog
c
=
;
try
{
c
=
(
Catalog
)
catalogs
.
elementAt
(
catPos
)
;
}
catch
(
ClassCastException
e
)
{
String
catfile
=
(
String
)
catalogs
.
elementAt
(
catPos
)
;
c
=
newCatalog
(
)
;
c
.
parseCatalog
(
catfile
)
;
catalogs
.
setElementAt
(
c
,
catPos
)
;
c
.
parseAllCatalogs
(
)
;
}
}
// Parse all the DELEGATE catalogs
Enumeration
enumt
=
catalogEntries
.
elements
(
)
;
while
(
enumt
.
hasMoreElements
(
)
)
{
CatalogEntry
e
=
(
CatalogEntry
)
enumt
.
nextElement
(
)
;
if
(
e
.
getEntryType
(
)
==
DELEGATE_PUBLIC
||
e
.
getEntryType
(
)
==
DELEGATE_SYSTEM
||
e
.
getEntryType
(
)
==
DELEGATE_URI
)
{
Catalog
dcat
=
newCatalog
(
)
;
dcat
.
parseCatalog
(
e
.
getEntryArg
(
1
)
)
;
}
}
}

Parse all subordinate catalogs.

This method recursively parses all of the subordinate catalogs.
If this method does not throw an exception, you can be confident that
no subsequent call to any resolve*() method will either, with two
possible exceptions:

Delegated catalogs are re-parsed each time they are needed
(because a variable list of them may be needed in each case,
depending on the length of the matching partial public identifier).

But they are parsed by this method, so as long as they don't
change or disappear while the program is running, they shouldn't
generate errors later if they don't generate errors now.

If you add new catalogs with parseCatalog, they
won't be loaded until they are needed or until you call
parseAllCatalogs again.

On the other hand, if you don't call this method, you may
successfully parse documents without having to load all possible
catalogs.

@throws MalformedURLException The filename (URL) for a
subordinate or delegated catalog is not a valid URL.
@throws IOException Error reading some subordinate or delegated
catalog file.


public String resolveDoctype(String entityName,
			       String publicId,
			       String systemId)
    throws MalformedURLException, IOException {
    String resolved = null;

    catalogManager.debug.message(3, "resolveDoctype("
		  +entityName+","+publicId+","+systemId+")");

    systemId = normalizeURI(systemId);

    if (publicId != null && publicId.startsWith("urn:publicid:")) {
      publicId = PublicId.decodeURN(publicId);
    }

    if (systemId != null && systemId.startsWith("urn:publicid:")) {
      systemId = PublicId.decodeURN(systemId);
      if (publicId != null && !publicId.equals(systemId)) {
	catalogManager.debug.message(1, "urn:publicid: system identifier differs from public identifier; using public identifier");
	systemId = null;
      } else {
	publicId = systemId;
	systemId = null;
      }
    }

    if (systemId != null) {
      // If there's a SYSTEM entry in this catalog, use it
      resolved = resolveLocalSystem(systemId);
      if (resolved != null) {
	return resolved;
      }
    }

    if (publicId != null) {
      // If there's a PUBLIC entry in this catalog, use it
      resolved = resolveLocalPublic(DOCTYPE,
				    entityName,
				    publicId,
				    systemId);
      if (resolved != null) {
	return resolved;
      }
    }

    // If there's a DOCTYPE entry in this catalog, use it
    boolean over = default_override;
    Enumeration enumt = catalogEntries.elements();
    while (enumt.hasMoreElements()) {
      CatalogEntry e = (CatalogEntry) enumt.nextElement();
      if (e.getEntryType() == OVERRIDE) {
	over = e.getEntryArg(0).equalsIgnoreCase("YES");
	continue;
      }

      if (e.getEntryType() == DOCTYPE
	  && e.getEntryArg(0).equals(entityName)) {
	if (over || systemId == null) {
	  return e.getEntryArg(1);
	}
      }
    }

    // Otherwise, look in the subordinate catalogs
    return resolveSubordinateCatalogs(DOCTYPE,
				      entityName,
				      publicId,
				      systemId);
  }

Return the applicable DOCTYPE system identifier.

@param entityName The name of the entity (element) for which
a doctype is required.
@param publicId The nominal public identifier for the doctype
(as provided in the source document).
@param systemId The nominal system identifier for the doctype
(as provided in the source document).

@return The system identifier to use for the doctype.

@throws MalformedURLException The formal system identifier of a
subordinate catalog cannot be turned into a valid URL.
@throws IOException Error reading subordinate catalog file.

Return the applicable DOCTYPE system identifier .


public String resolveDocument()
    throws MalformedURLException, IOException {
    // If there's a DOCUMENT entry, return it

    catalogManager.debug.message(3, "resolveDocument");

    Enumeration enumt = catalogEntries.elements();
    while (enumt.hasMoreElements()) {
      CatalogEntry e = (CatalogEntry) enumt.nextElement();
      if (e.getEntryType() == DOCUMENT) {
	return e.getEntryArg(1); //FIXME check this
      }
    }

    return resolveSubordinateCatalogs(DOCUMENT,
				      null, null, null);
  }

Return the applicable DOCUMENT entry.

@return The system identifier to use for the doctype.

@throws MalformedURLException The formal system identifier of a
subordinate catalog cannot be turned into a valid URL.
@throws IOException Error reading subordinate catalog file.