@Override
    public Object fromBody(final TypedInput body, final Type type) throws ConversionException {
        try {
            return converter.fromBody(body, type);
        } catch(final ConversionException e) {
            if(e.getCause() instanceof JsonParseException) {
                throw new HodUnavailableException(e.getCause());
            } else {
                throw e;
            }

        }
    }

@ Override public Object fromBody ( final TypedInput body , final Type type ) throws ConversionException { try { return converter . fromBody ( body , type ) ; } catch ( final ConversionException e ) { if ( e . getCause ( ) instanceof JsonParseException ) { throw new HodUnavailableException ( e . getCause ( ) ) ; } else { throw e ; } } }

Returns the object returned by calling fromBody on the underlying converter


@Override
    public void renderHead(final Component _component,
                           final IHeaderResponse _response)
    {
        super.renderHead(_component, _response);
        _response.render(AbstractEFapsHeaderItem.forJavaScript(AjaxFieldUpdateBehavior.JS));
    }

@ Override public void renderHead ( final Component _component , final IHeaderResponse _response ) { super . renderHead ( _component , _response ) ; _response . render ( AbstractEFapsHeaderItem . forJavaScript ( AjaxFieldUpdateBehavior . JS ) ) ; }

Render to the web response the eFapsContentReference.

@param _response Response object

Render to the web response the eFapsContentReference .


@Override
    protected void onError(final AjaxRequestTarget _target)
    {
        if (this.errorHandling) {
            final FeedbackCollector collector = new FeedbackCollector(getForm().getPage());
            final List<FeedbackMessage> msgs = collector.collect();
            final StringBuilder html = new StringBuilder()
                            .append("
");
            for (final FeedbackMessage msg : msgs) {
                msg.getReporter().add(AttributeModifier.append("class", "invalid"));
                _target.add(msg.getReporter());
                Serializable warn = null;
                if (msg.getMessage() instanceof ValidationErrorFeedback) {
                    // look if a message was set
                    warn = ((ValidationErrorFeedback) msg.getMessage()).getMessage();
                    // still no message, create one
                    if (warn == null) {
                        warn = ((ValidationErrorFeedback) msg.getMessage()).getError().getErrorMessage(
                                        new ErrorMessageResource());
                    }
                }
                String label = "";
                if (msg.getReporter() instanceof IFieldConfig) {
                    label = ((IFieldConfig) msg.getReporter()).getFieldConfig().getLabel();
                }
                html.append("
").append(label).append(":	")
                                .append(warn).append("
");
            }
            html.append("
");

            final ModalWindowContainer modal = ((AbstractContentPage) getComponent().getPage()).getModal();

            modal.setInitialWidth(350);
            modal.setInitialHeight(200);

            modal.setPageCreator(new ModalWindow.PageCreator()
            {

                private static final long serialVersionUID = 1L;

                @Override
                public Page createPage()
                {
                    return new DialogPage(((AbstractContentPage) getComponent().getPage()).getPageReference(),
                                    html.toString(), true, false);
                }
            });
            modal.show(_target);
        }
    }

Default means nothing is done on error.

@see org.apache.wicket.ajax.form.AjaxFormSubmitBehavior#onError(org.apache.wicket.ajax.AjaxRequestTarget)
@param _target AjaxRequestTarget

Default means nothing is done on error .


public ExecutionBridge launch(final IJob _job,
                                  final String _jobName)
        throws EFapsException
    {
        // we are on WEB thread so services should be normally injected.
        final ExecutionBridge bridge = new ExecutionBridge();
        // register bridge on session
        if (_jobName == null) {
            bridge.setJobName("EFapsJob-" + EFapsSession.get().countJobs() + 1 + "-"
                            + RandomUtil.randomAlphanumeric(4));
        } else {
            bridge.setJobName(_jobName);
        }
        bridge.setJobContext(new JobContext().setUserName(Context.getThreadContext().getPerson().getName()).setLocale(
                        Context.getThreadContext().getLocale()).setCompanyUUID(Context.getThreadContext().getCompany()
                                        .getUUID()));

        EFapsSession.get().addExecutionBridge(bridge);
        // run the task
        this.executorService.execute(new JobRunnable(_job, bridge));
        return bridge;
    }

Launch a job.

@param _job the _job
@param _jobName the _job name
@return the execution bridge
@throws EFapsException on error


public AddToTextIndexRequestBuilder addReferencePrefixes(final String referencePrefix, final String... referencePrefixes) {
        this.referencePrefixes.add(referencePrefix);
        this.referencePrefixes.addAll(Arrays.asList(referencePrefixes));

        return this;
    }

public AddToTextIndexRequestBuilder addReferencePrefixes ( final String referencePrefix , final String ... referencePrefixes ) { this . referencePrefixes . add ( referencePrefix ) ; this . referencePrefixes . addAll ( Arrays . asList ( referencePrefixes ) ) ; return this ; }

Adds values to the referencePrefixes parameter

@param referencePrefix   The first index
@param referencePrefixes The remaining referencePrefixes
@return this


public AddToTextIndexRequestBuilder addAdditionalMetadata(final Object metadatum, final Object... metadata) {
        this.additionalMetadata.add(metadatum);
        this.additionalMetadata.addAll(Arrays.asList(metadata));

        return this;
    }

public AddToTextIndexRequestBuilder addAdditionalMetadata ( final Object metadatum , final Object ... metadata ) { this . additionalMetadata . add ( metadatum ) ; this . additionalMetadata . addAll ( Arrays . asList ( metadata ) ) ; return this ; }

Sets the value of the metadata parameter

@param metadatum The first index
@param metadata  The remaining metadata
@return this


public QueryProfileRequestBuilder addPromotionCategories(final String category0, final String... categories) {
        promotionCategories.add(category0);
        promotionCategories.addAll(Arrays.asList(categories));
        return this;
    }

public QueryProfileRequestBuilder addPromotionCategories ( final String category0 , final String ... categories ) { promotionCategories . add ( category0 ) ; promotionCategories . addAll ( Arrays . asList ( categories ) ) ; return this ; }

Adds categories to the promotion_categories parameter

@param category0  The first category to add
@param categories Additional categories to add
@return this


public QueryProfileRequestBuilder addSynonymCategories(final String category0, final String... categories) {
        synonymCategories.add(category0);
        synonymCategories.addAll(Arrays.asList(categories));
        return this;
    }

public QueryProfileRequestBuilder addSynonymCategories ( final String category0 , final String ... categories ) { synonymCategories . add ( category0 ) ; synonymCategories . addAll ( Arrays . asList ( categories ) ) ; return this ; }

Adds categories to the synonym_categories parameter

@param category0  The first category to add
@param categories Additional categories to add
@return this


public QueryProfileRequestBuilder addBlacklistCategories(final String category0, final String... categories) {
        blacklistCategories.add(category0);
        blacklistCategories.addAll(Arrays.asList(categories));
        return this;
    }

public QueryProfileRequestBuilder addBlacklistCategories ( final String category0 , final String ... categories ) { blacklistCategories . add ( category0 ) ; blacklistCategories . addAll ( Arrays . asList ( categories ) ) ; return this ; }

Adds categories to the blacklist_categories parameter

@param category0  The first category to add
@param categories Additional categories to add
@return this


public void initiate(final IPartialPageRequestHandler _target)
    {
        final String url = getCallBackURL();
        if (url != null) {
            _target.prependJavaScript(getCallBackScript(url));
        }
    }

public void initiate ( final IPartialPageRequestHandler _target ) { final String url = getCallBackURL ( ) ; if ( url != null ) { _target . prependJavaScript ( getCallBackScript ( url ) ) ; } }

Call this method to initiate the download.
@param _target Ajaxtarget

Call this method to initiate the download .


@Override
    public void onRequest()
    {
        final String fileName = getFileName();
        final IResourceStream stream = getResourceStream();
        final ResourceStreamRequestHandler handler = new ResourceStreamRequestHandler(stream, fileName);
        handler.setContentDisposition(ContentDisposition.ATTACHMENT);
        getComponent().getRequestCycle().scheduleRequestHandlerAfterCurrent(handler);
    }

@ Override public void onRequest ( ) { final String fileName = getFileName ( ) ; final IResourceStream stream = getResourceStream ( ) ; final ResourceStreamRequestHandler handler = new ResourceStreamRequestHandler ( stream , fileName ) ; handler . setContentDisposition ( ContentDisposition . ATTACHMENT ) ; getComponent ( ) . getRequestCycle ( ) . scheduleRequestHandlerAfterCurrent ( handler ) ; }

On request, respond with a ResourcStream.

On request respond with a ResourcStream .


protected IResourceStream getResourceStream()
    {
        final File file = EFapsSession.get().getFile();
        final FileResourceStream ret = new FileResourceStream(file);
        EFapsSession.get().setFile(null);
        return ret;
    }

protected IResourceStream getResourceStream ( ) { final File file = EFapsSession . get ( ) . getFile ( ) ; final FileResourceStream ret = new FileResourceStream ( file ) ; EFapsSession . get ( ) . setFile ( null ) ; return ret ; }

Hook method providing the actual resource stream.
@return stream

Hook method providing the actual resource stream .


protected CharSequence getCallBackScript(final String _url)
    {
        final StringBuilder js = new StringBuilder()
            .append("baseWindow.withDoc(top.dojo.doc, function () {\n")
            .append("var node = dom.byId('downloadFrame');\n")
            .append("if (node == null) {\n")
            .append("node = domConstruct.place('<iframe id=\"downloadFrame\" src=\"about:blank\" ")
                .append("style=\"position: absolute; left: 1px; top: 1px; height: 1px; width: 1px; ")
                .append("visibility: hidden\">', win.body());\n")
            .append("}\n")
            .append("node.src='").append(_url).append("';")
            .append("});\n");
        return DojoWrapper.require(js, DojoClasses.baseWindow, DojoClasses.dom, DojoClasses.domConstruct);
    }

Script that searches for an existing iframe to use it for the download of the frame.
If it does not exist it will be created.

@param _url the url
@return the callback script

Script that searches for an existing iframe to use it for the download of the frame . If it does not exist it will be created .


public void sendKeepAlive(final Application _application)
    {
        final long reference = new Date().getTime();
        final ConcurrentMap<String, IKey> sessionId2key = _application.getMetaData(ConnectionRegistry.SESSION2KEY);
        final ConcurrentMap<String, Long> keepalive = _application.getMetaData(ConnectionRegistry.KEEPALIVE);
        if (keepalive != null) {
            for (final Entry<String, Long> entry : keepalive.entrySet()) {
                if (reference - entry.getValue()
                                > Configuration.getAttributeAsInteger(ConfigAttribute.WEBSOCKET_KATH) * 1000) {
                    final IKey key = sessionId2key.get(entry.getKey());
                    if (key != null) {
                        final IWebSocketConnectionRegistry registry = WebSocketSettings.Holder.get(
                                        _application).getConnectionRegistry();
                        final IWebSocketConnection conn = registry.getConnection(_application, entry.getKey(), key);
                        if (conn != null) {
                            try {
                                conn.sendMessage(KeepAliveBehavior.MSG);
                                ConnectionRegistry.LOG.debug("Send KeepAlive for Session: {}", entry.getKey());
                            } catch (final IOException e) {
                                ConnectionRegistry.LOG.error("Catched error", e);
                            }
                        }
                    }
                }
            }
        }
    }

public
void
sendKeepAlive
(
final
Application
_application
)
{
final
long
reference
=
new
Date
(
)
.
getTime
(
)
;
final
ConcurrentMap
<
String
,
IKey
>
sessionId2key
=
_application
.
getMetaData
(
ConnectionRegistry
.
SESSION2KEY
)
;
final
ConcurrentMap
<
String
,
Long
>
keepalive
=
_application
.
getMetaData
(
ConnectionRegistry
.
KEEPALIVE
)
;
if
(
keepalive
!=
)
{
for
(
final
Entry
<
String
,
Long
>
entry
:
keepalive
.
entrySet
(
)
)
{
if
(
reference
entry
.
getValue
(
)
>
Configuration
.
getAttributeAsInteger
(
ConfigAttribute
.
WEBSOCKET_KATH
)
*
1000
)
{
final
IKey
key
=
sessionId2key
.
get
(
entry
.
getKey
(
)
)
;
if
(
key
!=
)
{
final
IWebSocketConnectionRegistry
registry
=
WebSocketSettings
.
Holder
.
get
(
_application
)
.
getConnectionRegistry
(
)
;
final
IWebSocketConnection
conn
=
registry
.
getConnection
(
_application
,
entry
.
getKey
(
)
,
key
)
;
if
(
conn
!=
)
{
try
{
conn
.
sendMessage
(
KeepAliveBehavior
.
MSG
)
;
ConnectionRegistry
.
LOG
.
debug
(
"Send KeepAlive for Session: {}"
,
entry
.
getKey
(
)
)
;
}
catch
(
final
IOException
e
)
{
ConnectionRegistry
.
LOG
.
error
(
"Catched error"
,
e
)
;
}
}
}
}
}
}
}

Send the KeepAlive.
@param _application Application the KeepAlive will be send for


private void initKeepAlive()
    {
        if (!this.keepAlive) {
            this.keepAlive = true;
            final KeepAliveTask keepAliveTask = new KeepAliveTask(EFapsApplication.get().getApplicationKey());
            final Timer timer = new Timer(true);
            // every two minutes
            timer.scheduleAtFixedRate(keepAliveTask, 0 * 1000,
                            Configuration.getAttributeAsInteger(ConfigAttribute.WEBSOCKET_KASP) * 1000);
        }
    }

private
void
initKeepAlive
(
)
{
if
(
!
this
.
keepAlive
)
{
this
.
keepAlive
=
true
;
final
KeepAliveTask
keepAliveTask
=
new
KeepAliveTask
(
EFapsApplication
.
get
(
)
.
getApplicationKey
(
)
)
;
final
Timer
timer
=
new
Timer
(
true
)
;
// every two minutes
timer
.
scheduleAtFixedRate
(
keepAliveTask
,
0
*
1000
,
Configuration
.
getAttributeAsInteger
(
ConfigAttribute
.
WEBSOCKET_KASP
)
*
1000
)
;
}
}


public static List<UIUserSession> getUIUserSessions()
    {
        final List<UIUserSession> ret = new ArrayList<>();
        final Collection<UserSession> userSessions = RegistryManager.getUserSessions();
        for (final UserSession userSession : userSessions) {
            ret.add(new UIUserSession(userSession.getUserName(), userSession.getSessionId(), userSession
                            .getLastActivity()));
        }
        return ret;
    }

public static List < UIUserSession > getUIUserSessions ( ) { final List < UIUserSession > ret = new ArrayList <> ( ) ; final Collection < UserSession > userSessions = RegistryManager . getUserSessions ( ) ; for ( final UserSession userSession : userSessions ) { ret . add ( new UIUserSession ( userSession . getUserName ( ) , userSession . getSessionId ( ) , userSession . getLastActivity ( ) ) ) ; } return ret ; }

Gets the UI user sessions.

@return list of currently registered Users


@Override
    public void onComponentTagBody(final MarkupStream _markupStream,
                                      final ComponentTag _openTag)
    {
        setEscapeModelStrings(false);
        String value = getDefaultModelObjectAsString(getDefaultModelObject());
        // if the value contains the EFAPSTMPTAG all tags from this component
        // will be moved to the subcomponent
        if (value != null && value.contains(IUserInterface.EFAPSTMPTAG)) {
            final StringBuilder tagBldr = new StringBuilder();
            final List<? extends Behavior> behaviors = getBehaviors();
            final ComponentTag tmpTag = new ComponentTag(_openTag);
            for (final Behavior behavior : behaviors) {
                behavior.onComponentTag(this, tmpTag);
            }
            final IValueMap map = tmpTag.getAttributes();
            for (final Entry<String, Object> entry : map.entrySet()) {
                final String key = entry.getKey();
                if (!"wicket:id".equals(key)) {
                    tagBldr.append(" ").append(key).append("=\"").append(entry.getValue()).append("\" ");
                }
            }
            // if no id is given add the id here
            if (!map.containsKey("id")) {
                tagBldr.append(" id=\"").append(getMarkupId()).append("\" ");
            }
            value = value.replace(IUserInterface.EFAPSTMPTAG, tagBldr);
        }
        super.replaceComponentTagBody(_markupStream, _openTag, value);
    }

Must be overwritten so that no replacing of html tags is done.

@see org.apache.wicket.Component#onComponentTagBody(org.apache.wicket.markup.MarkupStream,
org.apache.wicket.markup.ComponentTag)

@param _markupStream MarkupStream
@param _openTag Tag

Must be overwritten so that no replacing of html tags is done .


@Override
    protected void onRender()
    {
        final IMarkupFragment markup = getMarkup();
        if (markup == null) {
            throw new MarkupException("Markup not found. Component: " + toString());
        }

        final MarkupStream markupStream = new MarkupStream(markup);

        // Get mutable copy of next tag
        final ComponentTag openTag = markupStream.getTag();
        final ComponentTag tag = openTag.mutable();

        // Call any tag handler
        onComponentTag(tag);

        // If we're an openclose tag
        if (!tag.isOpenClose() && !tag.isOpen()) {
            // We were something other than <tag> or <tag/>
            markupStream.throwMarkupException("Method renderComponent called on bad markup element: " + tag);
        }

        if (tag.isOpenClose() && openTag.isOpen()) {
            markupStream.throwMarkupException("You can not modify a open tag to open-close: " + tag);
        }

        markupStream.next();

        getMarkupSourcingStrategy().onComponentTagBody(this, markupStream, tag);
    }

Method is overwritten to prevent the annoing warnings from Component to come up.
The warning come up due to the reason that this component moves the tags from parent
element to its child.

Method is overwritten to prevent the annoing warnings from Component to come up . The warning come up due to the reason that this component moves the tags from parent element to its child .


public static EmbeddedLink getDashboardLink(final String _instanceKey,
                                                final String _identifier)
    {
        final EmbeddedLink ret = new EmbeddedLink(_instanceKey);
        ret.setTagHtml(TAG.DASHBOARD.getHtml());
        ret.setIdentifier(_identifier);
        return ret;
    }

public static EmbeddedLink getDashboardLink ( final String _instanceKey , final String _identifier ) { final EmbeddedLink ret = new EmbeddedLink ( _instanceKey ) ; ret . setTagHtml ( TAG . DASHBOARD . getHtml ( ) ) ; ret . setIdentifier ( _identifier ) ; return ret ; }

Gets the dashboard link.

@param _instanceKey instance key the link is wanted for
@param _identifier the identifier
@return new Embeded Link


<T> T parseResponse(final TokenProxy<?, ?> tokenProxy, final Class<T> clazz, final Response response) {
        return unsafeParseResponse(tokenProxy, objectMapper.constructType(clazz), response);
    }

< T > T parseResponse ( final TokenProxy < ? , ? > tokenProxy , final Class < T > clazz , final Response response ) { return unsafeParseResponse ( tokenProxy , objectMapper . constructType ( clazz ) , response ) ; }

Parse the response into a type represented by the Class object. Checks for a refreshed token and updates the token
repository accordingly.
@param <T> The desired type of the response body
@param tokenProxy The token proxy to update in the token repository if required
@param clazz A class object representing the desired type of the response body
@param response The response to parse
@return An object representing the result from HP Haven OnDemand

Parse the response into a type represented by the Class object . Checks for a refreshed token and updates the token repository accordingly .


<T> T parseResponse(final TokenProxy<?, ?> tokenProxy, final TypeReference<T> typeReference, final Response response) {
        return unsafeParseResponse(tokenProxy, objectMapper.getTypeFactory().constructType(typeReference), response);
    }

< T > T parseResponse ( final TokenProxy < ? , ? > tokenProxy , final TypeReference < T > typeReference , final Response response ) { return unsafeParseResponse ( tokenProxy , objectMapper . getTypeFactory ( ) . constructType ( typeReference ) , response ) ; }

Parse the response into a type represented by the TypeReference object. Checks for a refreshed token and updates
the token repository accordingly.
@param <T> The desired type of the response body
@param tokenProxy The token proxy to update in the token repository if required
@param typeReference A type reference object representing the desired type of the response body
@param response The response to parse
@return An object representing the result from HP Haven OnDemand

Parse the response into a type represented by the TypeReference object . Checks for a refreshed token and updates the token repository accordingly .


<T> T unsafeParseResponse(final TokenProxy<?, ?> tokenProxy, final JavaType type, final Response response) {
        checkRefresh(tokenProxy, response);

        try {
            return objectMapper.readValue(response.getBody().in(), type);
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }
    }

< T > T unsafeParseResponse ( final TokenProxy < ? , ? > tokenProxy , final JavaType type , final Response response ) { checkRefresh ( tokenProxy , response ) ; try { return objectMapper . readValue ( response . getBody ( ) . in ( ) , type ) ; } catch ( final IOException e ) { throw new RuntimeException ( e ) ; } }

Parse the response into a type represented by the JavaType object. Checks for a refreshed token and updates
the token repository accordingly. This method does not guarantee that the type parameter T represents the given
JavaType. If possible, use one of the safe parseResponse methods instead.
@param <T> The desired type of the response body
@param tokenProxy The token proxy to update in the token repository if required
@param type A JavaType representing the desired type of the response body
@param response The response to parse
@return An object representing the result from HP Haven OnDemand

Parse the response into a type represented by the JavaType object . Checks for a refreshed token and updates the token repository accordingly . This method does not guarantee that the type parameter T represents the given JavaType . If possible use one of the safe parseResponse methods instead .


InputStream parseResponse(final TokenProxy<?, ?> tokenProxy, final Response response) {
        checkRefresh(tokenProxy, response);

        try {
            return response.getBody().in();
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }
    }

InputStream parseResponse ( final TokenProxy < ? , ? > tokenProxy , final Response response ) { checkRefresh ( tokenProxy , response ) ; try { return response . getBody ( ) . in ( ) ; } catch ( final IOException e ) { throw new RuntimeException ( e ) ; } }

Checks the response headers for a refreshed authentication token then returns the response body as an input stream.
@param tokenProxy The token proxy to update in the token repository if required
@param response The response to read
@return The response body as an input stream

Checks the response headers for a refreshed authentication token then returns the response body as an input stream .


@Override
    protected List<EventDefinition> getEvents(final EventType _eventType)
    {
        return Field.get(this.fieldId).getEvents(_eventType);
    }

@ Override protected List < EventDefinition > getEvents ( final EventType _eventType ) { return Field . get ( this . fieldId ) . getEvents ( _eventType ) ; }

Method to get the events that are related to this UITable.

@param _eventType eventype to get
@return List of events

Method to get the events that are related to this UITable .


protected void onComponentTagInternal(final ComponentTag _tag)
    {
        _tag.put("name", getConfig().getName());
        _tag.append("style", "text-align:" + getConfig().getAlign(), ";");
    }

protected void onComponentTagInternal ( final ComponentTag _tag ) { _tag . put ( "name" , getConfig ( ) . getName ( ) ) ; _tag . append ( "style" , "text-align:" + getConfig ( ) . getAlign ( ) , ";" ) ; }

Add to the tag.
@param _tag tag to write


@Override
    public void run() {
        try {
            log.debug("About to check status for jobId {}", jobId);

            final JobStatus<T> jobStatus;

            if (tokenProxy != null) {
                jobStatus = jobService.getJobStatus(tokenProxy, jobId);
            }
            else {
                jobStatus = jobService.getJobStatus(jobId);
            }

            final Status jobStatusStatus = jobStatus.getStatus();

            if (jobStatusStatus == Status.FINISHED || jobStatusStatus == Status.FAILED) {
                for (final Action<T> action : jobStatus.getActions()) {
                    final Status status = action.getStatus();

                    if (status == Status.FINISHED) {
                        log.debug("Found a finished action, calling callback");

                        callback.success(action.getResult());
                    }
                    else if (status == Status.FAILED) {
                        log.debug("Found a failed action, calling callback");

                        for (final HodError error : action.getErrors()) {
                            log.debug("Error callback called with: {}", error);

                            callback.error(error.getErrorCode());
                        }
                    }
                }
            }
            else if (timeout != null && timeout.isBefore(LocalDateTime.now())) {
                callback.timeout();
                log.debug("Timeout callback called");
            }
            else {
                log.debug("Not finished or failed, retrying");

                // we got a status successfully, so reset the counter
                tries.set(0);

                executorService.schedule(this, WAIT_SECONDS, TimeUnit.SECONDS);
            }
        } catch (final HodErrorException e) {
            log.error("Error retrieving job status for jobId: {}", jobId);
            log.error("Cause:", e);

            if (DO_NOT_RETRY_CODES.contains(e.getErrorCode())) {
                log.error("Unrecoverable error, will not retry");

                callback.error(e.getErrorCode());
            }
            else if (tries.get() >= MAX_TRIES) {
                log.error("Max retries reached, will not retry");

                callback.error(e.getErrorCode());
            }
            else {
                log.error("Retrying");

                tries.incrementAndGet();

                executorService.schedule(this, WAIT_SECONDS, TimeUnit.SECONDS);
            }
        } catch (final RuntimeException e) {
            log.error("Error retrieving job status for jobId: {}", jobId);
            log.error("Cause:", e);

            callback.handleException(e);
        }
    }

Checks the status of the job. If the job has not finished, the runnable will schedule itself to run again after a
short wait

Checks the status of the job . If the job has not finished the runnable will schedule itself to run again after a short wait


@Override
    public void onComponentTag(final Component _component,
                               final ComponentTag _tag)
    {
        super.onComponentTag(_component, _tag);

        if (this.type == DnDBehavior.BehaviorType.ITEM) {
            String value = "dojoDndItem ";
            if (_tag.getAttribute("class") != null) {
                value += _tag.getAttribute("class");
            }
            _tag.put("dndType", this.dndType);
            _tag.put("class", value);
        }
    }

@
Override
public
void
onComponentTag
(
final
Component
_component
,
final
ComponentTag
_tag
)
{
super
.
onComponentTag
(
_component
,
_tag
)
;
if
(
this
.
type
==
DnDBehavior
.
BehaviorType
.
ITEM
)
{
String
value
=
"dojoDndItem "
;
if
(
_tag
.
getAttribute
(
"class"
)
!=
)
{
value
+=
_tag
.
getAttribute
(
"class"
)
;
}
_tag
.
put
(
"dndType"
,
this
.
dndType
)
;
_tag
.
put
(
"class"
,
value
)
;
}
}

The tag of the component must be altered, so that the dojo dnd will be rendered.

@see org.apache.wicket.behavior.AbstractBehavior#onComponentTag(org.apache.wicket.Component,
org.apache.wicket.markup.ComponentTag)
@param _component Component
@param _tag tag to edit

The tag of the component must be altered so that the dojo dnd will be rendered .


@Override
    public void renderHead(final Component _component,
                           final IHeaderResponse _response)
    {
        super.renderHead(_component, _response);
        _response.render(RequireHeaderItem.forClasses(DojoClasses.DnDSource, DojoClasses.parser));

        if (this.type == DnDBehavior.BehaviorType.SOURCE) {
            final StringBuilder js = new StringBuilder()
                .append("var nSrc = new dojo.dnd.Source(dom.byId('").append(_component.getMarkupId(true)).append("'),")
                .append("{ accept: ['" + this.dndType + "']});")
                .append(" aspect.after(nSrc,\"onDrop\", function(){\n")
                .append(this.appendJavaScript)
                .append("\n});");
            _response.render(OnDojoReadyHeaderItem.forScript(DojoWrapper.require(js, DojoClasses.aspect,
                            DojoClasses.dom, DojoClasses.DnDSource)));
        }
    }

Add the javascriupt to the head of the webpage.

@see org.efaps.ui.wicket.behaviors.dojo.AbstractDojoBehavior#renderHead(
org.apache.wicket.markup.html.IHeaderResponse)

@param _component component the header will be rendered for
@param _response rseponse

Add the javascriupt to the head of the webpage .


public void setDefault(final UUID _selectCmdUUID)
    {
        final UIMenuItem menuItem = getProvider().getRoots().next();
        menuItem.setHeader(true);
        boolean hasDefault = false;
        for (final UIMenuItem childItem : menuItem.getChildren()) {
            if (_selectCmdUUID == null && childItem.isDefaultSelected()
                            || _selectCmdUUID != null && _selectCmdUUID.equals(childItem.getCommandUUID())) {
                hasDefault = true;
                childItem.setSelected(true);
            }
        }
        if (!hasDefault) {
            menuItem.setSelected(true);
        }
        expand(menuItem);
        expandChildren(menuItem);
    }

public void setDefault ( final UUID _selectCmdUUID ) { final UIMenuItem menuItem = getProvider ( ) . getRoots ( ) . next ( ) ; menuItem . setHeader ( true ) ; boolean hasDefault = false ; for ( final UIMenuItem childItem : menuItem . getChildren ( ) ) { if ( _selectCmdUUID == null && childItem . isDefaultSelected ( ) || _selectCmdUUID != null && _selectCmdUUID . equals ( childItem . getCommandUUID ( ) ) ) { hasDefault = true ; childItem . setSelected ( true ) ; } } if ( ! hasDefault ) { menuItem . setSelected ( true ) ; } expand ( menuItem ) ; expandChildren ( menuItem ) ; }

Set the default selected item.

@param _selectCmdUUID UUID of the selected Command


public static String getLabel(final String _cmdName,
                                   final String _keytype)
    {
        final String ret;
        if (DBProperties.hasProperty(_cmdName + ".Button." + _keytype)) {
            ret = DBProperties.getProperty(_cmdName + ".Button." + _keytype);
        } else {
            ret = DBProperties.getProperty("default.Button." + _keytype);
        }
        return ret;
    }

public static String getLabel ( final String _cmdName , final String _keytype ) { final String ret ; if ( DBProperties . hasProperty ( _cmdName + ".Button." + _keytype ) ) { ret = DBProperties . getProperty ( _cmdName + ".Button." + _keytype ) ; } else { ret = DBProperties . getProperty ( "default.Button." + _keytype ) ; } return ret ; }

Method that gets the Value for the Buttons from the DBProperties.

@param _cmdName Name of the Command, that Label for the Button should be
retrieved
@param _keytype type of the key e.g. "Cancel", "Submit", "Close"
@return Label

Method that gets the Value for the Buttons from the DBProperties .


protected Component getEditableComp(final String _wicketId,
                                        final AbstractUIField _uiField)
        throws EFapsException
    {
        Component ret = null;
        switch (_uiField.getFieldConfiguration().getUIType()) {
            case SNIPPLET:
                if (!_uiField.getFieldConfiguration().isHideLabel()) {
                    _uiField.getFieldConfiguration().evalLabel(_uiField.getValue(), _uiField.getInstance());
                }
                final String html = String.valueOf(_uiField.getValue().getEditValue(
                                _uiField.getParent().getMode()));
                ret = new SnippletField(_wicketId, Model.of(html),  _uiField);
                break;
            case DROPDOWN:
                final List<DropDownOption> choices = DropDownOption.getChoices(_uiField.getValue()
                                .getEditValue(_uiField.getParent().getMode()));
                ret = new DropDownField(_wicketId, Model.of(_uiField), choices);
                break;
            case RADIO:
                final List<RadioOption> radios = RadioOption.getChoices(_uiField.getValue()
                                .getEditValue(_uiField.getParent().getMode()));
                ret = new RadioField(_wicketId, Model.of(_uiField), radios);
                break;
            case CHECKBOX:
                final List<CheckBoxOption> checkBoxes = CheckBoxOption.getChoices(_uiField,
                                _uiField.getValue().getEditValue(_uiField.getParent().getMode()));
                ret = new CheckBoxField(_wicketId, Model.of(_uiField), checkBoxes);
                break;
            case BUTTON:
                ret = new AjaxPickerButton(_wicketId, Model.<IPickable>of(_uiField));
                break;
            case NUMBER:
                ret = new NumberField(_wicketId, Model.of(_uiField), _uiField.getFieldConfiguration());
                break;
            case UPLOAD:
                ret = new UploadField(_wicketId, Model.of(_uiField), false);
                break;
            case UPLOADMULTIPLE:
                ret = new UploadField(_wicketId, Model.of(_uiField), true);
                break;
            default:
                break;
        }
        return ret;
    }

protected Component getEditableComp ( final String _wicketId , final AbstractUIField _uiField ) throws EFapsException { Component ret = null ; switch ( _uiField . getFieldConfiguration ( ) . getUIType ( ) ) { case SNIPPLET : if ( ! _uiField . getFieldConfiguration ( ) . isHideLabel ( ) ) { _uiField . getFieldConfiguration ( ) . evalLabel ( _uiField . getValue ( ) , _uiField . getInstance ( ) ) ; } final String html = String . valueOf ( _uiField . getValue ( ) . getEditValue ( _uiField . getParent ( ) . getMode ( ) ) ) ; ret = new SnippletField ( _wicketId , Model . of ( html ) , _uiField ) ; break ; case DROPDOWN : final List < DropDownOption > choices = DropDownOption . getChoices ( _uiField . getValue ( ) . getEditValue ( _uiField . getParent ( ) . getMode ( ) ) ) ; ret = new DropDownField ( _wicketId , Model . of ( _uiField ) , choices ) ; break ; case RADIO : final List < RadioOption > radios = RadioOption . getChoices ( _uiField . getValue ( ) . getEditValue ( _uiField . getParent ( ) . getMode ( ) ) ) ; ret = new RadioField ( _wicketId , Model . of ( _uiField ) , radios ) ; break ; case CHECKBOX : final List < CheckBoxOption > checkBoxes = CheckBoxOption . getChoices ( _uiField , _uiField . getValue ( ) . getEditValue ( _uiField . getParent ( ) . getMode ( ) ) ) ; ret = new CheckBoxField ( _wicketId , Model . of ( _uiField ) , checkBoxes ) ; break ; case BUTTON : ret = new AjaxPickerButton ( _wicketId , Model . < IPickable > of ( _uiField ) ) ; break ; case NUMBER : ret = new NumberField ( _wicketId , Model . of ( _uiField ) , _uiField . getFieldConfiguration ( ) ) ; break ; case UPLOAD : ret = new UploadField ( _wicketId , Model . of ( _uiField ) , false ) ; break ; case UPLOADMULTIPLE : ret = new UploadField ( _wicketId , Model . of ( _uiField ) , true ) ; break ; default : break ; } return ret ; }

Gets the editable comp.

@param _wicketId the wicket id
@param _uiField the ui field
@return the editable comp
@throws EFapsException on error


@Override
    protected void onAfterRender()
    {
        super.onAfterRender();
        if (getDefaultModel() != null) {
            final UITableHeader headermodel = (UITableHeader) getDefaultModelObject();
            headermodel.setMarkupId(this.getMarkupId());
        }
    }

@ Override protected void onAfterRender ( ) { super . onAfterRender ( ) ; if ( getDefaultModel ( ) != null ) { final UITableHeader headermodel = ( UITableHeader ) getDefaultModelObject ( ) ; headermodel . setMarkupId ( this . getMarkupId ( ) ) ; } }

Set the markupid into the model.

@see org.apache.wicket.Component#onAfterRender()


public List<StringValue> getDateAsString(final List<StringValue> _date,
                                             final List<StringValue> _hour,
                                             final List<StringValue> _minute,
                                             final List<StringValue> _ampm)
        throws EFapsException
    {
        final List<StringValue> ret = new ArrayList<>();
        final List<DateTime> dates = getDateList(_date, _hour, _minute, _ampm);
        for (final DateTime date : dates) {
            final DateTimeFormatter isofmt = ISODateTimeFormat.dateTime();
            ret.add(StringValue.valueOf(date.toString(isofmt)));
        }
        return ret;
    }

public List < StringValue > getDateAsString ( final List < StringValue > _date , final List < StringValue > _hour , final List < StringValue > _minute , final List < StringValue > _ampm ) throws EFapsException { final List < StringValue > ret = new ArrayList <> ( ) ; final List < DateTime > dates = getDateList ( _date , _hour , _minute , _ampm ) ; for ( final DateTime date : dates ) { final DateTimeFormatter isofmt = ISODateTimeFormat . dateTime ( ) ; ret . add ( StringValue . valueOf ( date . toString ( isofmt ) ) ) ; } return ret ; }

Method to get for the parameters returned from the form as a valid string. for a datetime

@param _date date
@param _hour hour
@param _minute minutes
@param _ampm am/pm
@return valid string
@throws EFapsException on error

Method to get for the parameters returned from the form as a valid string . for a datetime


public List<DateTime> getDateList(final List<StringValue> _date,
                                      final List<StringValue> _hour,
                                      final List<StringValue> _minute,
                                      final List<StringValue> _ampm)
        throws EFapsException
    {
        final List<DateTime> ret = new ArrayList<>();
        if (_date != null) {
            Iterator<StringValue> hourIter = null;
            Iterator<StringValue> minuteIter = null;
            Iterator<StringValue> ampmIter = null;
            if (_hour != null) {
                hourIter = _hour.iterator();
            }
            if (_minute != null) {
                minuteIter = _minute.iterator();
            }
            if (_ampm != null) {
                ampmIter = _ampm.iterator();
            }

            for (final StringValue date : _date) {
                if (!date.isNull() && !date.isEmpty()) {
                    final DateTimeFormatter fmt = DateTimeFormat.forPattern(
                                    this.converter.getDatePattern(Context.getThreadContext().getLocale()))
                                    .withChronology(Context.getThreadContext().getChronology());
                    fmt.withLocale(getLocale());
                    final MutableDateTime mdt = fmt.parseMutableDateTime(date.toString());
                    if (hourIter != null) {
                        final StringValue hourStr = hourIter.next();
                        final int hour = Integer.parseInt(hourStr.toString("0"));
                        mdt.setHourOfDay(hour);
                        if (ampmIter != null) {
                            final StringValue ampmStr = ampmIter.next();
                            if ("am".equals(ampmStr.toString("am"))) {
                                if (hour == 12) {
                                    mdt.setHourOfDay(0);
                                }
                            } else {
                                if (hour != 12) {
                                    mdt.setHourOfDay(hour + 12);
                                }
                            }
                        }
                        if (minuteIter != null) {
                            final StringValue minuteStr = minuteIter.next();
                            final int minute = Integer.parseInt(minuteStr.toString("0"));
                            mdt.setMinuteOfHour(minute);
                        }
                    }
                    ret.add(mdt.toDateTime());
                }
            }
        }
        return ret;
    }

public List < DateTime > getDateList ( final List < StringValue > _date , final List < StringValue > _hour , final List < StringValue > _minute , final List < StringValue > _ampm ) throws EFapsException { final List < DateTime > ret = new ArrayList <> ( ) ; if ( _date != null ) { Iterator < StringValue > hourIter = null ; Iterator < StringValue > minuteIter = null ; Iterator < StringValue > ampmIter = null ; if ( _hour != null ) { hourIter = _hour . iterator ( ) ; } if ( _minute != null ) { minuteIter = _minute . iterator ( ) ; } if ( _ampm != null ) { ampmIter = _ampm . iterator ( ) ; } for ( final StringValue date : _date ) { if ( ! date . isNull ( ) && ! date . isEmpty ( ) ) { final DateTimeFormatter fmt = DateTimeFormat . forPattern ( this . converter . getDatePattern ( Context . getThreadContext ( ) . getLocale ( ) ) ) . withChronology ( Context . getThreadContext ( ) . getChronology ( ) ) ; fmt . withLocale ( getLocale ( ) ) ; final MutableDateTime mdt = fmt . parseMutableDateTime ( date . toString ( ) ) ; if ( hourIter != null ) { final StringValue hourStr = hourIter . next ( ) ; final int hour = Integer . parseInt ( hourStr . toString ( "0" ) ) ; mdt . setHourOfDay ( hour ) ; if ( ampmIter != null ) { final StringValue ampmStr = ampmIter . next ( ) ; if ( "am" . equals ( ampmStr . toString ( "am" ) ) ) { if ( hour == 12 ) { mdt . setHourOfDay ( 0 ) ; } } else { if ( hour != 12 ) { mdt . setHourOfDay ( hour + 12 ) ; } } } if ( minuteIter != null ) { final StringValue minuteStr = minuteIter . next ( ) ; final int minute = Integer . parseInt ( minuteStr . toString ( "0" ) ) ; mdt . setMinuteOfHour ( minute ) ; } } ret . add ( mdt . toDateTime ( ) ) ; } } } return ret ; }

Method to get for the parameters returned from the form as a datetimes.

@param _date date
@param _hour hour
@param _minute minutes
@param _ampm am/pm
@return valid string
@throws EFapsException on error

Method to get for the parameters returned from the form as a datetimes .


@Override
    protected void onAfterRender()
    {
        super.onAfterRender();
        final IDateListener container = this.findParent(IDateListener.class);
        if (container != null) {
            container.addDateComponent(this);
        }
    }

@ Override protected void onAfterRender ( ) { super . onAfterRender ( ) ; final IDateListener container = this . findParent ( IDateListener . class ) ; if ( container != null ) { container . addDateComponent ( this ) ; } }

After rendering the datefields are added to the parent.

After rendering the datefields are added to the parent .


public void destroy() {
        log.debug("Shutting down executor service");

        executorService.shutdown();

        try {
            if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) {
                log.debug("Timed out waiting for executor service to die, calling shutdownNow");
                executorService.shutdownNow();
            }
        } catch (final InterruptedException e) {
            log.debug("Interrupted waiting for executor service to die, calling shutdownNow");
            executorService.shutdownNow();
        }
    }

Shuts down the executor service. This method should be called when the job service is no longer needed, if the
default executor service was used

Shuts down the executor service . This method should be called when the job service is no longer needed if the default executor service was used


@Override
    @SuppressWarnings("checkstyle:illegalcatch")
    public void onClick(final AjaxRequestTarget _target)
    {
        Instance instance = null;
        try {
            if (this.target.equals(ScriptTarget.TOP)) {
                final PageReference reference = ((AbstractContentPage) getPage()).getCalledByPageReference();
                if (reference != null) {
                    final UIMenuItem menuItem = (UIMenuItem) ((ContentContainerPage) reference.getPage()).getMenuTree()
                                    .getSelected().getDefaultModelObject();
                    final RecentObjectLink link = new RecentObjectLink(menuItem);
                    if (link != null) {
                        ((EFapsSession) getSession()).addRecent(link);
                    }
                }
            }
            final AbstractUIField uiField = super.getModelObject();
            if (uiField.getInstanceKey() != null) {
                Menu menu = null;
                try {
                    instance = uiField.getInstance();
                    menu = Menu.getTypeTreeMenu(instance.getType());
                } catch (final Exception e) {
                    if (menu == null) {
                        throw new EFapsException(LoadInTargetAjaxLink.class, "NoTreeMenu", instance);
                    }
                }

                final ContentContainerPage page = new ContentContainerPage(menu.getUUID(), uiField.getInstanceKey(),
                                uiField.getParent() instanceof UIStructurBrowser);
                final CharSequence url = urlFor(new RenderPageRequestHandler(new PageProvider(page)));
                // touch the page to ensure that the pagemanager stores it to be accessible
                getSession().getPageManager().touchPage(page);
                final StringBuilder js = new StringBuilder()
                    .append(this.target.key).append(".dijit.registry.byId(\"").append("mainPanel")
                    .append("\").set(\"content\", dojo.create(\"iframe\",{")
                    .append("\"id\": \"").append(MainPage.IFRAME_ID)
                    .append("\",\"src\": \"./wicket/").append(url)
                    .append("\",\"style\": \"border: 0; width: 100%; height: 99%\"")
                    .append("}));");
                _target.appendJavaScript(js);
            }
        } catch (final EFapsException e) {
            throw new RestartResponseException(new ErrorPage(e));
        }
    }

Method to load something inside the opener window.

@param _target AjaxRequestTarget

Method to load something inside the opener window .


@Override
    protected void onComponentTag(final ComponentTag _tag)
    {
        if (this.actionUrl == null) {
            this.actionUrl = urlFor(getRequestCycle().getActiveRequestHandler()).toString();
        }
        super.onComponentTag(_tag);
        if (getPage().getDefaultModelObject() != null) {
            // only on SearchMode we want normal submit, in any other case we
            // use AjaxSubmit
            if (getPage().getDefaultModelObject() instanceof AbstractUIObject
                            && !((AbstractUIObject) getPage().getDefaultModelObject()).isSearchMode()) {
                //_tag.put("onSubmit", "return false;");
                _tag.put("action", "");
            }
        }
    }

On component tag.

@param _tag the tag

@see org.apache.wicket.markup.html.form.Form
#onComponentTag(org.apache.wicket.markup.ComponentTag)


@Override
    protected boolean handleMultiPart()
    {
        final boolean ret = super.handleMultiPart();
        try {
            if (isMultiPart() && getRequest() instanceof MultipartServletWebRequest) {
                for (final Entry<String, List<FileItem>> entry : ((MultipartServletWebRequest) getRequest()).getFiles()
                                .entrySet()) {
                    int i = -1;
                    if (entry.getValue().size() > 1) {
                        i = 0;
                    }
                    for (final FileItem fileItem : entry.getValue()) {
                        final String key = i > -1 ? entry.getKey() + "_" + i : entry.getKey();
                        final FileParameter parameter = new FileParameter(key, fileItem);
                        Context.getThreadContext().getFileParameters().put(key, parameter);
                        if (i > -1) {
                            i++;
                        }
                    }
                }

                final Map<String, String[]> parameters = new HashMap<>();
                final IRequestParameters reqPara = getRequest().getRequestParameters();
                for (final String name : reqPara.getParameterNames()) {
                    final List<StringValue> values = reqPara.getParameterValues(name);
                    final String[] valArray = new String[values.size()];
                    int i = 0;
                    for (final StringValue value : values) {
                        valArray[i] = value.toString();
                        i++;
                    }
                    parameters.put(name, valArray);
                }
                Context.getThreadContext().getParameters().putAll(parameters);
            }
        } catch (final EFapsException e) {
            throw new RestartResponseAtInterceptPageException(new ErrorPage(e));
        }
        return ret;
    }

@ Override protected boolean handleMultiPart ( ) { final boolean ret = super . handleMultiPart ( ) ; try { if ( isMultiPart ( ) && getRequest ( ) instanceof MultipartServletWebRequest ) { for ( final Entry < String , List < FileItem > > entry : ( ( MultipartServletWebRequest ) getRequest ( ) ) . getFiles ( ) . entrySet ( ) ) { int i = - 1 ; if ( entry . getValue ( ) . size ( ) > 1 ) { i = 0 ; } for ( final FileItem fileItem : entry . getValue ( ) ) { final String key = i > - 1 ? entry . getKey ( ) + "_" + i : entry . getKey ( ) ; final FileParameter parameter = new FileParameter ( key , fileItem ) ; Context . getThreadContext ( ) . getFileParameters ( ) . put ( key , parameter ) ; if ( i > - 1 ) { i ++ ; } } } final Map < String , String [ ] > parameters = new HashMap <> ( ) ; final IRequestParameters reqPara = getRequest ( ) . getRequestParameters ( ) ; for ( final String name : reqPara . getParameterNames ( ) ) { final List < StringValue > values = reqPara . getParameterValues ( name ) ; final String [ ] valArray = new String [ values . size ( ) ] ; int i = 0 ; for ( final StringValue value : values ) { valArray [ i ] = value . toString ( ) ; i ++ ; } parameters . put ( name , valArray ) ; } Context . getThreadContext ( ) . getParameters ( ) . putAll ( parameters ) ; } } catch ( final EFapsException e ) { throw new RestartResponseAtInterceptPageException ( new ErrorPage ( e ) ) ; } return ret ; }

Handle the multipart to store the files and parameters in the context also.
@return true if multipart

Handle the multipart to store the files and parameters in the context also .


private void resetSetCounter()
    {
        if (getPage().getDefaultModelObject() instanceof UIForm) {
            for (final Element element : ((UIForm) getPage().getDefaultModelObject()).getElements()) {
                if (element.getType().equals(ElementType.FORM)) {
                    final Iterator<FormRow> iter = ((UIForm.FormElement) element.getElement()).getRowModels();
                    while (iter.hasNext()) {
                        final FormRow row = iter.next();
                        for (final IUIElement uiElement : row.getValues()) {
                            if (uiElement instanceof UIFieldSet) {
                                ((UIFieldSet) uiElement).resetIndex();
                            }
                        }
                    }
                } else if (element.getType().equals(ElementType.SUBFORM)) {
                    for (final Element nElement : ((UIFieldForm) element.getElement()).getElements()) {
                        if (nElement.getType().equals(ElementType.FORM)) {
                            final Iterator<FormRow> iter = ((UIForm.FormElement) nElement.getElement()).getRowModels();
                            while (iter.hasNext()) {
                                final FormRow row = iter.next();
                                for (final IUIElement uiElement : row.getValues()) {
                                    if (uiElement instanceof UIFieldSet) {
                                        ((UIFieldSet) uiElement).resetIndex();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

private void resetSetCounter ( ) { if ( getPage ( ) . getDefaultModelObject ( ) instanceof UIForm ) { for ( final Element element : ( ( UIForm ) getPage ( ) . getDefaultModelObject ( ) ) . getElements ( ) ) { if ( element . getType ( ) . equals ( ElementType . FORM ) ) { final Iterator < FormRow > iter = ( ( UIForm . FormElement ) element . getElement ( ) ) . getRowModels ( ) ; while ( iter . hasNext ( ) ) { final FormRow row = iter . next ( ) ; for ( final IUIElement uiElement : row . getValues ( ) ) { if ( uiElement instanceof UIFieldSet ) { ( ( UIFieldSet ) uiElement ) . resetIndex ( ) ; } } } } else if ( element . getType ( ) . equals ( ElementType . SUBFORM ) ) { for ( final Element nElement : ( ( UIFieldForm ) element . getElement ( ) ) . getElements ( ) ) { if ( nElement . getType ( ) . equals ( ElementType . FORM ) ) { final Iterator < FormRow > iter = ( ( UIForm . FormElement ) nElement . getElement ( ) ) . getRowModels ( ) ; while ( iter . hasNext ( ) ) { final FormRow row = iter . next ( ) ; for ( final IUIElement uiElement : row . getValues ( ) ) { if ( uiElement instanceof UIFieldSet ) { ( ( UIFieldSet ) uiElement ) . resetIndex ( ) ; } } } } } } } } }


@Override
    public void init(final FilterConfig _filterConfig)
        throws ServletException
    {
        super.init(_filterConfig);
        try {
            this.loginHandler = new LoginHandler(AppAccessHandler.getApplicationKey());
        } catch (final EFapsException e) {
            AbstractAuthenticationFilter.LOG.error("AppAccessHandler", e);
        }
    }

@ Override public void init ( final FilterConfig _filterConfig ) throws ServletException { super . init ( _filterConfig ) ; try { this . loginHandler = new LoginHandler ( AppAccessHandler . getApplicationKey ( ) ) ; } catch ( final EFapsException e ) { AbstractAuthenticationFilter . LOG . error ( "AppAccessHandler" , e ) ; } }

Called by the web container to indicate to a filter that it is being
placed into service. The servlet container calls the init method exactly
once after instantiating the filter. The init method must complete
successfully before the filter is asked to do any filtering work.

The web container cannot place the filter into service if the init method
either 1.Throws a ServletException 2.Does not return within a time period
defined by the web container // sets the login handler

@param _filterConfig filter configuration instance
@see #INIT_PARAM_TITLE
@see #title
@see #INIT_PARAM_APPLICATION
@see #loginhandler
@throws ServletException on error

Called by the web container to indicate to a filter that it is being placed into service . The servlet container calls the init method exactly once after instantiating the filter . The init method must complete successfully before the filter is asked to do any filtering work .


@Override
    protected void doFilter(final HttpServletRequest _request,
                            final HttpServletResponse _response,
                            final FilterChain _chain)
        throws IOException, ServletException
    {
        if (isLoggedIn(_request)) {
            _chain.doFilter(_request, _response);
        } else {
            doAuthenticate(_request, _response, _chain);
        }
    }

@ Override protected void doFilter ( final HttpServletRequest _request , final HttpServletResponse _response , final FilterChain _chain ) throws IOException , ServletException { if ( isLoggedIn ( _request ) ) { _chain . doFilter ( _request , _response ) ; } else { doAuthenticate ( _request , _response , _chain ) ; } }

If the current user is already logged in, nothing is filtered.
@param _request      HttpServletRequest
@param _response     HttpServletResponse
@param _chain        FilterChain
@see #doAuthenticate
@throws IOException on error
@throws ServletException on error

If the current user is already logged in nothing is filtered .


protected boolean checkLogin(final String _name,
                                 final String _passwd)
    {

        boolean loginOk = false;

        Context context = null;
        try {
            context = Context.begin();

            boolean ok = false;

            try {
                if (this.loginHandler.checkLogin(_name, _passwd) != null) {
                    loginOk = true;
                }
                ok = true;
            } finally {

                if (ok && Context.isTMActive()) {
                    Context.commit();
                } else {
                    if (Context.isTMMarkedRollback()) {
                        AbstractAuthenticationFilter.LOG.error("transaction is marked to roll back");
                    } else {
                        AbstractAuthenticationFilter.LOG.error("transaction manager in undefined status");
                    }
                    Context.rollback();
                }
            }
        } catch (final EFapsException e) {
            AbstractAuthenticationFilter.LOG.error("could not check name and password", e);
        } finally {
            context.close();
        }
        return loginOk;
    }

Checks if the user with given name and password is allowed to login.

@param _name user name to check
@param _passwd password to check
@return true if the user is allowed to login (name and password is
correct), otherweise false
@see #loginhandler
@see #doFilter

Checks if the user with given name and password is allowed to login .


@Override
    public void onRequest(final AjaxRequestTarget _target)
    {
        final UICmdField uiObject = (UICmdField) getDefaultModelObject();
        final StringBuilder snip = new StringBuilder();
        try {
            final AbstractUIPageObject pageObject = (AbstractUIPageObject) getPage().getDefaultModelObject();
            final Map<String, String> uiID2Oid = pageObject == null ? null : pageObject.getUiID2Oid();
            final List<Return> returns = uiObject.executeEvents(null, uiID2Oid);
            for (final Return oneReturn : returns) {
                if (oneReturn.contains(ReturnValues.SNIPLETT)) {
                    snip.append(oneReturn.get(ReturnValues.SNIPLETT));
                }
            }
        } catch (final EFapsException e) {
            throw new RestartResponseException(new ErrorPage(e));
        }
        _target.appendJavaScript(snip.toString());
    }

@ Override public void onRequest ( final AjaxRequestTarget _target ) { final UICmdField uiObject = ( UICmdField ) getDefaultModelObject ( ) ; final StringBuilder snip = new StringBuilder ( ) ; try { final AbstractUIPageObject pageObject = ( AbstractUIPageObject ) getPage ( ) . getDefaultModelObject ( ) ; final Map < String , String > uiID2Oid = pageObject == null ? null : pageObject . getUiID2Oid ( ) ; final List < Return > returns = uiObject . executeEvents ( null , uiID2Oid ) ; for ( final Return oneReturn : returns ) { if ( oneReturn . contains ( ReturnValues . SNIPLETT ) ) { snip . append ( oneReturn . get ( ReturnValues . SNIPLETT ) ) ; } } } catch ( final EFapsException e ) { throw new RestartResponseException ( new ErrorPage ( e ) ) ; } _target . appendJavaScript ( snip . toString ( ) ) ; }

On submit.

@param _target   AjaxRequestTarget


protected CharSequence getPersistenceScript(final UIGrid _uiGrid)
        throws EFapsException
    {
        final StringBuilder ret = new StringBuilder();
        ret.append("persistGet: function(_key) {");
        if (Context.getThreadContext().containsUserAttribute(_uiGrid.getCacheKey(CacheKey.GRIDX))) {
            final Set<Long> colIds = _uiGrid.getColumns()
                            .stream()
                            .map(col -> col.getField().getId())
                            .collect(Collectors.toSet());
            boolean add = true;
            final JSONObject json = new JSONObject(new JSONTokener(Context.getThreadContext().getUserAttribute(
                            _uiGrid.getCacheKey(CacheKey.GRIDX))));
            final JSONArray columnsArray = json.getJSONArray("column");
            for (int i = 0; i < columnsArray.length(); i++) {
                final JSONObject colObj = (JSONObject) columnsArray.get(i);
                final Long colid = colObj.getLong("id");
                if (!colIds.contains(colid)) {
                    add = false;
                    break;
                }
            }
            if (add && !json.isNull("filterBar")) {
                final JSONObject filterBar =  json.getJSONObject("filterBar");
                if (!filterBar.isNull("conditions")) {
                    final JSONArray conditionsArray = filterBar.getJSONArray("conditions");
                    for (int i = 0; i < conditionsArray.length(); i++) {
                        final JSONObject colObj = (JSONObject) conditionsArray.get(i);
                        if (colObj.has("colId")) {
                            final Long colid = colObj.optLong("colId");
                            if (colid > 0 && !colIds.contains(colid)) {
                                add = false;
                                break;
                            }
                        }
                    }
                }
            }
            if (add) {
                ret.append("return ").append(json.toString());
            }
        }
        ret.append("},\n")
            .append("persistPut: function(_key, _value, _options) {\n")
            .append("  var value;")
            .append("  if(_value && lang.isObject(_value)){\n")
            .append("    value = json.toJson(_value);\n")
            .append("  }else{\n")
            .append("    value = {expires: -1};\n")
            .append("  }\n")
            .append("top.eFaps.persistUserAttr('")
                .append(_uiGrid.getCacheKey(CacheKey.GRIDX)).append("', value);")
            .append("},\n");
        return ret;
    }

Gets the persistence script.

@param _uiGrid the ui grid
@return the persistence script
@throws EFapsException the e faps exception


protected CharSequence getPrintMenuItems(final Set<DojoClass> _dojoClasses)
    {
        final StringBuilder ret = new StringBuilder();
        Collections.addAll(_dojoClasses, DojoClasses.MenuItem);
        final PrintBehavior printBehavior = (PrintBehavior) getBehavior(PrintBehavior.class);
        final String[] mimes = new String[] {"PDF", "XLS"};
        for (final String mime : mimes) {
            if (ret.length() > 0) {
                ret.append(",");
            }
            ret.append("new MenuItem({\n")
                .append("label: \"").append(mime).append("\",\n")
                .append("iconClass:\"eFapsMenuIcon eFapsMenuIcon").append(mime.toUpperCase()).append("\",\n")
                .append("onClick: function(event) {\n")
                    .append("var g = registry.byId('grid');\n")
                    .append("var sr = g.select.row.getSelected();\n")
                    .append("if (sr.length == 0) {\n")
                    .append("array.forEach(g.rows(), function (_item, _id) {\n")
                    .append("sr[_id] = _item.id;\n")
                    .append("});\n")
                    .append("}\n")
                    .append("var cm = [];\n")
                    .append("array.forEach(g.columns(), function (_item, _id) {\n")
                    .append("cm[_id] = _item.id;\n")
                    .append("});\n")
                    .append(printBehavior.getCallbackFunctionBody(
                            CallbackParameter.resolved("MIME", "\"" + mime + "\""), CallbackParameter.explicit("sr"),
                            CallbackParameter.explicit("cm")))
                    .append("}\n")
                .append("})\n");
        }
        return ret;
    }

Gets the prints the menu items.

@param _dojoClasses the dojo classes
@return the prints the menu items


protected CharSequence getMenu(final Set<DojoClass> _dojoClasses)
        throws EFapsException
    {
        final StringBuilder ret = new StringBuilder();
        final UIGrid uiGrid = (UIGrid) getDefaultModelObject();
        if (!(uiGrid instanceof UIFieldGrid) && uiGrid.getCommand().getTargetMenu() != null) {
            Collections.addAll(_dojoClasses, DojoClasses.MenuBar, DojoClasses.DropDownMenu, DojoClasses.MenuItem,
                            DojoClasses.PopupMenuBarItem, DojoClasses.MenuBarItem);

            ret.append("var pMenuBar = new MenuBar({});\n");
            for (final AbstractCommand child : uiGrid.getCommand().getTargetMenu().getCommands()) {
                if (child.hasAccess(uiGrid.getCommand().getTargetMode(), uiGrid.getInstance())) {
                    if (child instanceof AbstractMenu) {
                        ret.append(getSubMenu((AbstractMenu) child, "pMenuBar"));
                    } else {
                        ret.append("pMenuBar.addChild(").append(getMenuItem(child, true)).append(");\n");
                    }
                }
            }
        }
        return ret;
    }

protected
CharSequence
getMenu
(
final
Set
<
DojoClass
>
_dojoClasses
)
throws
EFapsException
{
final
StringBuilder
ret
=
new
StringBuilder
(
)
;
final
UIGrid
uiGrid
=
(
UIGrid
)
getDefaultModelObject
(
)
;
if
(
!
(
uiGrid
instanceof
UIFieldGrid
)
&&
uiGrid
.
getCommand
(
)
.
getTargetMenu
(
)
!=
)
{
Collections
.
addAll
(
_dojoClasses
,
DojoClasses
.
MenuBar
,
DojoClasses
.
DropDownMenu
,
DojoClasses
.
MenuItem
,
DojoClasses
.
PopupMenuBarItem
,
DojoClasses
.
MenuBarItem
)
;
ret
.
append
(
"var pMenuBar = new MenuBar({});\n"
)
;
for
(
final
AbstractCommand
child
:
uiGrid
.
getCommand
(
)
.
getTargetMenu
(
)
.
getCommands
(
)
)
{
if
(
child
.
hasAccess
(
uiGrid
.
getCommand
(
)
.
getTargetMode
(
)
,
uiGrid
.
getInstance
(
)
)
)
{
if
(
child
instanceof
AbstractMenu
)
{
ret
.
append
(
getSubMenu
(
(
AbstractMenu
)
child
,
"pMenuBar"
)
)
;
}
else
{
ret
.
append
(
"pMenuBar.addChild("
)
.
append
(
getMenuItem
(
child
,
true
)
)
.
append
(
");\n"
)
;
}
}
}
}
return
ret
;
}

Gets the menu.

@param _dojoClasses the dojo classes
@return the menu
@throws EFapsException on error


protected CharSequence getSubMenu(final AbstractMenu _menu,
                                      final String _parent)
        throws EFapsException
    {
        final String var = RandomUtil.randomAlphabetic(4);
        final StringBuilder js = new StringBuilder();
        js.append("var ").append(var).append(" = new DropDownMenu({});\n");
        final UIGrid uiGrid = (UIGrid) getDefaultModelObject();
        for (final AbstractCommand child : _menu.getCommands()) {
            if (child.hasAccess(uiGrid.getCommand().getTargetMode(), uiGrid.getInstance())) {
                if (child instanceof AbstractMenu) {
                    js.append(getSubMenu((AbstractMenu) child, var));
                } else {
                    js.append(var).append(".addChild(")
                        .append(getMenuItem(child, false))
                        .append(");\n");
                }
            }
        }
        js.append(_parent).append(".addChild(new PopupMenuBarItem({\n")
            .append("label: \"").append(StringEscapeUtils.escapeEcmaScript(_menu.getLabelProperty())).append("\",\n")
            .append(" popup: ").append(var).append("\n")
            .append(" }));\n");
        return js;
    }

protected
CharSequence
getSubMenu
(
final
AbstractMenu
_menu
,
final
String
_parent
)
throws
EFapsException
{
final
String
var
=
RandomUtil
.
randomAlphabetic
(
4
)
;
final
StringBuilder
js
=
new
StringBuilder
(
)
;
js
.
append
(
"var "
)
.
append
(
var
)
.
append
(
" = new DropDownMenu({});\n"
)
;
final
UIGrid
uiGrid
=
(
UIGrid
)
getDefaultModelObject
(
)
;
for
(
final
AbstractCommand
child
:
_menu
.
getCommands
(
)
)
{
if
(
child
.
hasAccess
(
uiGrid
.
getCommand
(
)
.
getTargetMode
(
)
,
uiGrid
.
getInstance
(
)
)
)
{
if
(
child
instanceof
AbstractMenu
)
{
js
.
append
(
getSubMenu
(
(
AbstractMenu
)
child
,
var
)
)
;
}
else
{
js
.
append
(
var
)
.
append
(
".addChild("
)
.
append
(
getMenuItem
(
child
,
false
)
)
.
append
(
");\n"
)
;
}
}
}
js
.
append
(
_parent
)
.
append
(
".addChild(new PopupMenuBarItem({\n"
)
.
append
(
"label: \""
)
.
append
(
StringEscapeUtils
.
escapeEcmaScript
(
_menu
.
getLabelProperty
(
)
)
)
.
append
(
"\",\n"
)
.
append
(
" popup: "
)
.
append
(
var
)
.
append
(
"\n"
)
.
append
(
" }));\n"
)
;
return
js
;
}

Gets the sub menu.

@param _menu the menu
@param _parent the parent
@return the sub menu
@throws EFapsException on error


public static CharSequence getDataJS(final UIGrid _uiGrid)
        throws EFapsException
    {
        final StringBuilder ret = new StringBuilder().append(" [\n");
        int i = 0;
        for (final GridRow row : _uiGrid.getValues()) {
            if (i > 0) {
                ret.append(",\n");
            }
            ret.append(getRowJS(row, String.valueOf(i)));
            i++;
        }
        ret.append("]\n");
        return ret;
    }

public
static
CharSequence
getDataJS
(
final
UIGrid
_uiGrid
)
throws
EFapsException
{
final
StringBuilder
ret
=
new
StringBuilder
(
)
.
append
(
" [\n"
)
;
int
i
=
0
;
for
(
final
GridRow
row
:
_uiGrid
.
getValues
(
)
)
{
if
(
i
>
0
)
{
ret
.
append
(
",\n"
)
;
}
ret
.
append
(
getRowJS
(
row
,
String
.
valueOf
(
i
)
)
)
;
i
++
;
}
ret
.
append
(
"]\n"
)
;
return
ret
;
}

Gets the data JS.

@param _uiGrid the ui grid
@return the data JS
@throws EFapsException on error


public static CharSequence getDataReloadJS(final UIGrid _uiGrid)
        throws EFapsException
    {
        final StringBuilder js = new StringBuilder()
            .append("var grid = registry.byId('grid');\n")
            .append("var items = ").append(GridXComponent.getDataJS(_uiGrid));

        final StringBuilder dialogJs = new StringBuilder();
        if (!_uiGrid.isColumnsUpToDate()) {
            // lazy setting of data type when first time data
            _uiGrid.setColumnsUpToDate(true);
            js.append("array.forEach(grid.structure, function(entry){\n");
            for (final GridColumn column : _uiGrid.getColumns()) {
                if (column.getDataType() != null) {
                    js.append("if ('").append(column.getField().getId()).append("'== entry.id) {\n")
                        .append("entry.dataType='").append(column.getDataType()).append("';\n")
                        .append("entry.comparator = grid.comparators.").append(column.getDataType()).append(";\n")
                        .append("}\n");
                }
                if (_uiGrid.getFilterList().stream()
                                .filter(filter -> filter.getFieldId() == column.getField().getId())
                                .findFirst().isPresent()) {
                    // to prevent jumping of the modal filter dialog, close and open it
                    final String varName = RandomUtil.randomAlphabetic(4);
                    dialogJs.append("var ").append(varName)
                        .append(" = registry.byId('").append("fttd_" + column.getField().getId()).append("');\n")
                        .append("if (").append(varName).append(" && !(").append(varName)
                            .append(".domNode.offsetHeight == 0 && ")
                            .append(varName).append(".domNode.offsetWidth == 0)) {\n")
                        .append(varName).append(".onBlur();\n")
                        .append("var nl = query(\".gridxHeaderMenuBtn\", dom.byId('grid-")
                            .append(column.getField().getId()).append("'));\n")
                        .append("nl[0].click();\n")
                        .append("}\n");
                }
            }
            js.append("});\n")
                .append("grid.setColumns(grid.structure);\n")
                .append(dialogJs);
        }
        js.append("grid.model.clearCache();\n")
            .append("grid.model.store.setData(items);\n")
            .append("grid.body.refresh();\n");
        return DojoWrapper.require(js, DojoClasses.registry, DojoClasses.array, DojoClasses.dom, DojoClasses.query);
    }

Gets the javascript.

@param _uiGrid the ui grid
@return the javascript
@throws EFapsException on error


@Override
    public Page createPage()
    {
        Page ret = null;
        try {
            final String instKey = this.uiObject.getInstance() == null ? null : this.uiObject.getInstance().getKey();

            if (this.uiObject.getCommand().getTargetTable() == null) {
                final UIForm uiform = new UIForm(this.uiObject.getCommand().getUUID(), instKey)
                                .setPagePosition(this.pagePosition);
                uiform.setPicker(this.uiObject);
                if (!uiform.isInitialized()) {
                    uiform.execute();
                }
                if (uiform.getElements().isEmpty()) {
                    ret = new DialogPage(this.modalWindow.getPage().getPageReference(),
                                    uiform.getCommand().getName() + ".InvalidInstance", false, false);
                } else {
                    if (this.uiObject.getCommand().isSubmit()) {
                        final IRequestParameters parameters = RequestCycle.get().getRequest().getRequestParameters();
                        uiform.setSelected(parameters.getParameterValues("selectedRow"));
                    }
                    ret = new FormPage(Model.of(uiform), this.modalWindow, this.modalWindow.getPage()
                                    .getPageReference());
                }
            } else {
                if (this.uiObject.getCommand().getTargetStructurBrowserField() == null) {
                    final UITable uitable = new UITable(this.uiObject.getCommand().getUUID(), instKey)
                                    .setPagePosition(this.pagePosition);
                    uitable.setPicker(this.uiObject);
                    ret = new TablePage(Model.of(uitable), this.modalWindow, this.modalWindow.getPage()
                                    .getPageReference());
                } else {
                    final UIStructurBrowser uiPageObject = new UIStructurBrowser(this.uiObject.getCommand().getUUID(),
                                    instKey);
                    uiPageObject.setPicker(this.uiObject);
                    ret = new StructurBrowserPage(Model.of(uiPageObject), this.modalWindow,
                                    this.modalWindow.getPage().getPageReference());
                }
            }
        } catch (final EFapsException e) {
            ret = new ErrorPage(e);
        }
        return ret;
    }

@ Override public Page createPage ( ) { Page ret = null ; try { final String instKey = this . uiObject . getInstance ( ) == null ? null : this . uiObject . getInstance ( ) . getKey ( ) ; if ( this . uiObject . getCommand ( ) . getTargetTable ( ) == null ) { final UIForm uiform = new UIForm ( this . uiObject . getCommand ( ) . getUUID ( ) , instKey ) . setPagePosition ( this . pagePosition ) ; uiform . setPicker ( this . uiObject ) ; if ( ! uiform . isInitialized ( ) ) { uiform . execute ( ) ; } if ( uiform . getElements ( ) . isEmpty ( ) ) { ret = new DialogPage ( this . modalWindow . getPage ( ) . getPageReference ( ) , uiform . getCommand ( ) . getName ( ) + ".InvalidInstance" , false , false ) ; } else { if ( this . uiObject . getCommand ( ) . isSubmit ( ) ) { final IRequestParameters parameters = RequestCycle . get ( ) . getRequest ( ) . getRequestParameters ( ) ; uiform . setSelected ( parameters . getParameterValues ( "selectedRow" ) ) ; } ret = new FormPage ( Model . of ( uiform ) , this . modalWindow , this . modalWindow . getPage ( ) . getPageReference ( ) ) ; } } else { if ( this . uiObject . getCommand ( ) . getTargetStructurBrowserField ( ) == null ) { final UITable uitable = new UITable ( this . uiObject . getCommand ( ) . getUUID ( ) , instKey ) . setPagePosition ( this . pagePosition ) ; uitable . setPicker ( this . uiObject ) ; ret = new TablePage ( Model . of ( uitable ) , this . modalWindow , this . modalWindow . getPage ( ) . getPageReference ( ) ) ; } else { final UIStructurBrowser uiPageObject = new UIStructurBrowser ( this . uiObject . getCommand ( ) . getUUID ( ) , instKey ) ; uiPageObject . setPicker ( this . uiObject ) ; ret = new StructurBrowserPage ( Model . of ( uiPageObject ) , this . modalWindow , this . modalWindow . getPage ( ) . getPageReference ( ) ) ; } } } catch ( final EFapsException e ) { ret = new ErrorPage ( e ) ; } return ret ; }

Method that creates the page.

@return new Page


@Override
    protected void onEvent(final AjaxRequestTarget _target)
    {
        final ModalWindowContainer modal = getComponent().getPage().visitChildren(ModalWindowContainer.class,
                        new ModalVisitor());
        modal.show(_target);
    }

@ Override protected void onEvent ( final AjaxRequestTarget _target ) { final ModalWindowContainer modal = getComponent ( ) . getPage ( ) . visitChildren ( ModalWindowContainer . class , new ModalVisitor ( ) ) ; modal . show ( _target ) ; }

Show the modal window.

@param _target AjaxRequestTarget


public void addValue(final Instance _rowInstance,
                         final UIFieldSetValue _uiFieldSetValue)
    {
        this.instKey2row.get(_rowInstance.getKey()).add(_uiFieldSetValue);
    }

public void addValue ( final Instance _rowInstance , final UIFieldSetValue _uiFieldSetValue ) { this . instKey2row . get ( _rowInstance . getKey ( ) ) . add ( _uiFieldSetValue ) ; }

Adds the value.

@param _rowInstance instance for the row to be added
@param _uiFieldSetValue the _ui field set value


public int getIndex(final String _inputName)
    {
        Integer ret = 0;
        if (this.indexes.containsKey(_inputName)) {
            ret = this.indexes.get(_inputName) + 1;
        }
        this.indexes.put(_inputName, ret);
        return ret;
    }

public int getIndex ( final String _inputName ) { Integer ret = 0 ; if ( this . indexes . containsKey ( _inputName ) ) { ret = this . indexes . get ( _inputName ) + 1 ; } this . indexes . put ( _inputName , ret ) ; return ret ; }

Gets the index.

@param _inputName the _input name
@return the index


public void addNewRow()
        throws EFapsException
    {
        final UIFieldSetRow row = new UIFieldSetRow(this);
        this.rows.add(row);
        for (final UIFieldSetColHeader header : getHeaders()) {
            final UIValue uiValue = UIValue
                            .get(Field.get(header.getFieldId()), Attribute.get(header.getAttrId()), null);
            final UIFieldSetValue cellSetValue = new UIFieldSetValue(getParent(), null, this, uiValue);
            row.add(cellSetValue);
        }
    }

public void addNewRow ( ) throws EFapsException { final UIFieldSetRow row = new UIFieldSetRow ( this ) ; this . rows . add ( row ) ; for ( final UIFieldSetColHeader header : getHeaders ( ) ) { final UIValue uiValue = UIValue . get ( Field . get ( header . getFieldId ( ) ) , Attribute . get ( header . getAttrId ( ) ) , null ) ; final UIFieldSetValue cellSetValue = new UIFieldSetValue ( getParent ( ) , null , this , uiValue ) ; row . add ( cellSetValue ) ; } }

Add a new Row.

@throws EFapsException on error


private void addChildren(final UIClassification _uiClass,
                             final boolean _force)
    {
        if (_force || _uiClass.isExpanded()) {
            getModelObject().add(_uiClass);
            for (final UIClassification child : _uiClass.getChildren()) {
                addChildren(child, _force);
            }
        }
    }

private void addChildren ( final UIClassification _uiClass , final boolean _force ) { if ( _force || _uiClass . isExpanded ( ) ) { getModelObject ( ) . add ( _uiClass ) ; for ( final UIClassification child : _uiClass . getChildren ( ) ) { addChildren ( child , _force ) ; } } }

Recursive method to add child classifications.

@param _uiClass  classification to add
@param _force    force expanded

Recursive method to add child classifications .


public static CharSequence getHelp(final long _cmdId)
    {
        CharSequence ret;
        try {
            final Class<?> clazz = Class.forName(Configuration.getAttribute(Configuration.ConfigAttribute.HELPSNIPPROV),
                            false, EFapsClassLoader.getInstance());
            final IHelpProvider provider = (IHelpProvider) clazz.newInstance();
            ret = provider.getHelp(_cmdId);
        } catch (final ClassNotFoundException | InstantiationException | IllegalAccessException
                        | EFapsBaseException e) {
            HelpUtil.LOG.error("ClassNotFoundException", e);
            ret = "";
        }
        return ret;
    }

public static CharSequence getHelp ( final long _cmdId ) { CharSequence ret ; try { final Class < ? > clazz = Class . forName ( Configuration . getAttribute ( Configuration . ConfigAttribute . HELPSNIPPROV ) , false , EFapsClassLoader . getInstance ( ) ) ; final IHelpProvider provider = ( IHelpProvider ) clazz . newInstance ( ) ; ret = provider . getHelp ( _cmdId ) ; } catch ( final ClassNotFoundException | InstantiationException | IllegalAccessException | EFapsBaseException e ) { HelpUtil . LOG . error ( "ClassNotFoundException" , e ) ; ret = "" ; } return ret ; }

Gets the help.

@param _cmdId the cmd id
@return the help


protected UIStructurBrowser getNewStructurBrowser(final Instance _instance,
                                                      final UIStructurBrowser _strucBrwsr)
        throws EFapsException
    {
        final UUID uuid;
        if (_strucBrwsr.getTable() == null) {
            uuid = Menu.getTypeTreeMenu(_instance.getType()).getUUID();
        } else {
            uuid = _strucBrwsr.getCommandUUID();
        }
        final UIStructurBrowser ret = new UIStructurBrowser(uuid, _instance == null ? null : _instance.getKey(), false,
                        _strucBrwsr.getSortDirection());
        ret.setParentBrws(this);
        ret.setLevel(getLevel() + 1);
        return ret;
    }

protected UIStructurBrowser getNewStructurBrowser ( final Instance _instance , final UIStructurBrowser _strucBrwsr ) throws EFapsException { final UUID uuid ; if ( _strucBrwsr . getTable ( ) == null ) { uuid = Menu . getTypeTreeMenu ( _instance . getType ( ) ) . getUUID ( ) ; } else { uuid = _strucBrwsr . getCommandUUID ( ) ; } final UIStructurBrowser ret = new UIStructurBrowser ( uuid , _instance == null ? null : _instance . getKey ( ) , false , _strucBrwsr . getSortDirection ( ) ) ; ret . setParentBrws ( this ) ; ret . setLevel ( getLevel ( ) + 1 ) ; return ret ; }

Internal method to call a constructor, it is used to set that this
StructurBrowserModel is not a root.

@param _instance     Instance
@param _strucBrwsr   StructurBrowser the values will be copied from
@return UIStructurBrowser
@throws EFapsException on error

Internal method to call a constructor it is used to set that this StructurBrowserModel is not a root .


protected void initialise()
        throws EFapsException
    {
        final AbstractCommand command = getCommand();
        if (command != null && command.getTargetTable() != null) {
            setTableUUID(command.getTargetTable().getUUID());
            this.browserFieldName = command.getTargetStructurBrowserField();
            setShowCheckBoxes(command.isTargetShowCheckBoxes());
        } else if (getInstance() != null) {
            final String tmplabel = Menu.getTypeTreeMenu(getInstance().getType()).getLabel();
            this.valueLabel = DBProperties.getProperty(tmplabel);
        }

        // set default sort
        if (command.getTargetTableSortKey() != null) {
            setSortKeyInternal(command.getTargetTableSortKey());
            setSortDirection(command.getTargetTableSortDirection());
        }

        // get the User specific Attributes if exist overwrite the defaults
        try {
            if (Context.getThreadContext().containsUserAttribute(
                            getCacheKey(UITable.UserCacheKey.SORTKEY))) {
                setSortKeyInternal(Context.getThreadContext().getUserAttribute(
                                getCacheKey(UITable.UserCacheKey.SORTKEY)));
            }
            if (Context.getThreadContext().containsUserAttribute(
                            getCacheKey(UITable.UserCacheKey.SORTDIRECTION))) {
                setSortDirection(SortDirection.getEnum(Context.getThreadContext()
                                .getUserAttribute(getCacheKey(UITable.UserCacheKey.SORTDIRECTION))));
            }
        } catch (final EFapsException e) {
            // we don't throw an error because this are only Usersettings
            UIStructurBrowser.LOG.error("error during the retrieve of UserAttributes", e);
        }
    }

Method used to initialize this StructurBrowserModel.

@throws EFapsException on error

Method used to initialize this StructurBrowserModel .


@SuppressWarnings("unchecked")
    protected void expand(final boolean _expand)
    {
        try {
            // only if the element was opened the first time e.g. reload etc.
            if ((isRoot() || _expand)
                       && (Context.getThreadContext().containsSessionAttribute(getCacheKey()) || this.forceExpanded)) {
                final Map<String, Boolean> sessMap = (Map<String, Boolean>) Context
                                .getThreadContext().getSessionAttribute(getCacheKey());
                for (final UIStructurBrowser uiChild : this.children) {
                    if (isForceExpanded() || sessMap == null || sessMap.containsKey(uiChild.getInstanceKey())) {
                        final Boolean expandedTmp = sessMap == null || isForceExpanded()
                                                ? true : sessMap.get(uiChild.getInstanceKey());
                        if (expandedTmp != null && expandedTmp && uiChild.isParent()) {
                            uiChild.setExecutionStatus(UIStructurBrowser.ExecutionStatus.ADDCHILDREN);
                            final List<Return> ret = getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE,
                                                ParameterValues.INSTANCE, uiChild.getInstance(),
                                                ParameterValues.CLASS, uiChild);
                            final Map<Instance, Boolean> map = (Map<Instance, Boolean>) ret.get(0).get(
                                            ReturnValues.VALUES);
                            uiChild.setExpanded(true);
                            uiChild.add2ExpandedBrowsers(uiChild);
                            if (uiChild.getTableUUID() == null) {
                                uiChild.executeTree(map, true);
                            } else {
                                uiChild.executeTreeTable(map, true);
                            }
                        }
                    }
                }
            }
        } catch (final EFapsException e) {
            UIStructurBrowser.LOG.error("Error retreiving Session info for StruturBrowser from Command with UUID: {}",
                            getCommandUUID(), e);
        }
    }

Expand the tree with the information from the Session.
@param _expand is this inside an expand

Expand the tree with the information from the Session .


protected void sortModel()
    {
        setExecutionStatus(UIStructurBrowser.ExecutionStatus.SORT);
        try {
            getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE, ParameterValues.CLASS, this);

            if (getSortDirection() == SortDirection.DESCENDING) {
                Collections.reverse(this.children);
            }
        } catch (final EFapsException e) {
            throw new RestartResponseException(new ErrorPage(e));
        }
    }

protected void sortModel ( ) { setExecutionStatus ( UIStructurBrowser . ExecutionStatus . SORT ) ; try { getObject4Event ( ) . executeEvents ( EventType . UI_TABLE_EVALUATE , ParameterValues . CLASS , this ) ; if ( getSortDirection ( ) == SortDirection . DESCENDING ) { Collections . reverse ( this . children ) ; } } catch ( final EFapsException e ) { throw new RestartResponseException ( new ErrorPage ( e ) ) ; } }

Method to sort the data of this model. It calls an esjp for sorting.

Method to sort the data of this model . It calls an esjp for sorting .


public void checkHideColumn4Row()
    {
        setExecutionStatus(UIStructurBrowser.ExecutionStatus.CHECKHIDECOLUMN4ROW);
        try {
            getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE,
                            ParameterValues.INSTANCE, getInstance(),
                            ParameterValues.CLASS, this);
        } catch (final EFapsException e) {
            throw new RestartResponseException(new ErrorPage(e));
        }
    }

public void checkHideColumn4Row ( ) { setExecutionStatus ( UIStructurBrowser . ExecutionStatus . CHECKHIDECOLUMN4ROW ) ; try { getObject4Event ( ) . executeEvents ( EventType . UI_TABLE_EVALUATE , ParameterValues . INSTANCE , getInstance ( ) , ParameterValues . CLASS , this ) ; } catch ( final EFapsException e ) { throw new RestartResponseException ( new ErrorPage ( e ) ) ; } }

Method is called from the StructurBrowser in edit mode before rendering
the columns for row to be able to hide the columns for different rows by
setting the cell model to hide.

Method is called from the StructurBrowser in edit mode before rendering the columns for row to be able to hide the columns for different rows by setting the cell model to hide .


protected boolean checkForAllowChildren(final Instance _instance)
    {
        setExecutionStatus(UIStructurBrowser.ExecutionStatus.ALLOWSCHILDREN);
        try {
            final List<Return> ret = getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE,
                            ParameterValues.INSTANCE, _instance,
                            ParameterValues.CLASS, this);
            return ret.isEmpty() ? false : ret.get(0).get(ReturnValues.TRUE) != null;
        } catch (final EFapsException e) {
            throw new RestartResponseException(new ErrorPage(e));
        }
    }

protected boolean checkForAllowChildren ( final Instance _instance ) { setExecutionStatus ( UIStructurBrowser . ExecutionStatus . ALLOWSCHILDREN ) ; try { final List < Return > ret = getObject4Event ( ) . executeEvents ( EventType . UI_TABLE_EVALUATE , ParameterValues . INSTANCE , _instance , ParameterValues . CLASS , this ) ; return ret . isEmpty ( ) ? false : ret . get ( 0 ) . get ( ReturnValues . TRUE ) != null ; } catch ( final EFapsException e ) { throw new RestartResponseException ( new ErrorPage ( e ) ) ; } }

This method is used to check if a node has potential children.

@param _instance Instance of a Node to be checked
@return true if this Node has children, else false

This method is used to check if a node has potential children .


public void executeListener(final ExecutionStatus _status,
                                final Map<String, String> _uiID2Oid)
    {
        setExecutionStatus(_status);
        try {
            getObject4Event().executeEvents(EventType.UI_TABLE_EVALUATE,
                            ParameterValues.INSTANCE, getInstance(),
                            ParameterValues.CLASS, this,
                            ParameterValues.OIDMAP4UI,  _uiID2Oid);
        } catch (final EFapsException e) {
            throw new RestartResponseException(new ErrorPage(e));
        }
    }

public void executeListener ( final ExecutionStatus _status , final Map < String , String > _uiID2Oid ) { setExecutionStatus ( _status ) ; try { getObject4Event ( ) . executeEvents ( EventType . UI_TABLE_EVALUATE , ParameterValues . INSTANCE , getInstance ( ) , ParameterValues . CLASS , this , ParameterValues . OIDMAP4UI , _uiID2Oid ) ; } catch ( final EFapsException e ) { throw new RestartResponseException ( new ErrorPage ( e ) ) ; } }

This method is used to execute a listener with a specific event.
@param _status status to be executed
@param _uiID2Oid UI Id 2 Oid mapping

This method is used to execute a listener with a specific event .


public void requeryLabel()
    {
        try {
            final ValueParser parser = new ValueParser(new StringReader(this.valueLabel));
            final ValueList valList = parser.ExpressionString();
            final PrintQuery print = new PrintQuery(getInstance());
            valList.makeSelect(print);
            if (print.execute()) {
                setLabel(valList.makeString(getInstance(), print, getMode()).toString());
            }
        } catch (final EFapsException e) {
            throw new RestartResponseException(new ErrorPage(e));
        } catch (final ParseException e) {
            throw new RestartResponseException(new ErrorPage(e));
        }
    }

public void requeryLabel ( ) { try { final ValueParser parser = new ValueParser ( new StringReader ( this . valueLabel ) ) ; final ValueList valList = parser . ExpressionString ( ) ; final PrintQuery print = new PrintQuery ( getInstance ( ) ) ; valList . makeSelect ( print ) ; if ( print . execute ( ) ) { setLabel ( valList . makeString ( getInstance ( ) , print , getMode ( ) ) . toString ( ) ) ; } } catch ( final EFapsException e ) { throw new RestartResponseException ( new ErrorPage ( e ) ) ; } catch ( final ParseException e ) { throw new RestartResponseException ( new ErrorPage ( e ) ) ; } }

This method is updating the Label, by querying the eFaps-DataBase.

This method is updating the Label by querying the eFaps - DataBase .


@Override
    public final void bind(final Component _hostComponent)
    {
        Args.notNull(_hostComponent, "hostComponent");

        if (this.component != null) {
            throw new IllegalStateException("this kind of handler cannot be attached to "
                            + "multiple components; it is already attached to component " + this.component
                            + ", but component " + _hostComponent + " wants to be attached too");
        }
        this.component = _hostComponent;
        this.component.setOutputMarkupId(true);
    }

Bind this handler to the given component.

@param _hostComponent the component to bind to

Bind this handler to the given component .


private DataTable<Element, Void> getDataTable(final IndexSearch _indexSearch)
    {
        final List<IColumn<Element, Void>> columns = new ArrayList<>();

        columns.add(new AbstractColumn<Element, Void>(new Model<>(""))
        {

            private static final long serialVersionUID = 1L;

            @Override
            public void populateItem(final Item<ICellPopulator<Element>> _cellItem,
                                     final String _componentId,
                                     final IModel<Element> _rowModel)
            {
                _cellItem.add(new Link(_componentId, _rowModel));
            }
        });

        if (_indexSearch.getSearch() == null || _indexSearch.getSearch().getResultFields().isEmpty()) {
            columns.add(new PropertyColumn<Element, Void>(new Model<>(""), "text"));
        } else {
            for (final Entry<String, Collection<String>> entry : _indexSearch.getSearch().getResultFields()
                            .entrySet()) {
                columns.add(new ResultColumn(_indexSearch.getSearch().getResultLabel().get(entry.getKey()), entry
                                .getValue()));
            }
        }
        final DataTable<Element, Void> ret = new DataTable<>("table", columns, _indexSearch
                        .getDataProvider(), _indexSearch.getSearch() == null ? 100
                                        : _indexSearch.getSearch().getNumHits());

        ret.addTopToolbar(new HeadersToolbar<>(ret, null));
        return ret;
    }

private DataTable < Element , Void > getDataTable ( final IndexSearch _indexSearch ) { final List < IColumn < Element , Void > > columns = new ArrayList <> ( ) ; columns . add ( new AbstractColumn < Element , Void > ( new Model <> ( "" ) ) { private static final long serialVersionUID = 1L ; @ Override public void populateItem ( final Item < ICellPopulator < Element > > _cellItem , final String _componentId , final IModel < Element > _rowModel ) { _cellItem . add ( new Link ( _componentId , _rowModel ) ) ; } } ) ; if ( _indexSearch . getSearch ( ) == null || _indexSearch . getSearch ( ) . getResultFields ( ) . isEmpty ( ) ) { columns . add ( new PropertyColumn < Element , Void > ( new Model <> ( "" ) , "text" ) ) ; } else { for ( final Entry < String , Collection < String > > entry : _indexSearch . getSearch ( ) . getResultFields ( ) . entrySet ( ) ) { columns . add ( new ResultColumn ( _indexSearch . getSearch ( ) . getResultLabel ( ) . get ( entry . getKey ( ) ) , entry . getValue ( ) ) ) ; } } final DataTable < Element , Void > ret = new DataTable <> ( "table" , columns , _indexSearch . getDataProvider ( ) , _indexSearch . getSearch ( ) == null ? 100 : _indexSearch . getSearch ( ) . getNumHits ( ) ) ; ret . addTopToolbar ( new HeadersToolbar <> ( ret , null ) ) ; return ret ; }

Gets the data table.

@param _indexSearch the index search
@return the data table