public List<String> getFilterPickList(final UITableHeader _uitableHeader)
        throws EFapsException
    {
        final List<String> ret = new ArrayList<>();
        for (final UIRow rowmodel : this.values) {
            for (final IFilterable cell : rowmodel.getCells()) {
                if (cell.belongsTo(_uitableHeader.getFieldId())) {
                    final String value = cell.getPickListValue();
                    if (!ret.contains(value)) {
                        ret.add(value);
                    }
                    break;
                }
            }
        }
        Collections.sort(ret);
        return ret;
    }

public List < String > getFilterPickList ( final UITableHeader _uitableHeader ) throws EFapsException { final List < String > ret = new ArrayList <> ( ) ; for ( final UIRow rowmodel : this . values ) { for ( final IFilterable cell : rowmodel . getCells ( ) ) { if ( cell . belongsTo ( _uitableHeader . getFieldId ( ) ) ) { final String value = cell . getPickListValue ( ) ; if ( ! ret . contains ( value ) ) { ret . add ( value ) ; } break ; } } } Collections . sort ( ret ) ; return ret ; }

Get the List of values for a PICKERLIST.

@param _uitableHeader UitableHeader this filter belongs to
@return List of Values
@throws EFapsException on error

Get the List of values for a PICKERLIST .


private List<Status> getStatus4Type(final Type _type)
        throws CacheReloadException
    {
        final List<Status> ret = new ArrayList<>();
        final StatusGroup grp = Status.get(_type.getUUID());
        if (grp != null) {
            ret.addAll(grp.values());
        } else {
            for (final Type type : _type.getChildTypes()) {
                ret.addAll(getStatus4Type(type));
            }
        }
        return ret;
    }

private List < Status > getStatus4Type ( final Type _type ) throws CacheReloadException { final List < Status > ret = new ArrayList <> ( ) ; final StatusGroup grp = Status . get ( _type . getUUID ( ) ) ; if ( grp != null ) { ret . addAll ( grp . values ( ) ) ; } else { for ( final Type type : _type . getChildTypes ( ) ) { ret . addAll ( getStatus4Type ( type ) ) ; } } return ret ; }

Recursive method to get all status for a Type representing a StatusGrp.
@param _type Type the status list is wanted for
@return list of status
@throws CacheReloadException on error

Recursive method to get all status for a Type representing a StatusGrp .


private void storeFilters()
    {
        final Map<String, TableFilter> sessFilter = new HashMap<>();
        for (final Entry<String, TableFilter> entry : this.filters.entrySet()) {
            sessFilter.put(entry.getKey(), entry.getValue());
        }
        try {
            Context.getThreadContext().setSessionAttribute(getCacheKey(UITable.UserCacheKey.FILTER), sessFilter);
        } catch (final EFapsException e) {
            UITable.LOG.error("Error storing Filtermap for Table called by Command with UUID: {}", getCommandUUID(), e);
        }
    }


public void removeFilter(final UITableHeader _uiTableHeader)
    {
        this.filters.remove(_uiTableHeader.getFieldName());
        final UITableHeader orig = getHeader4Id(_uiTableHeader.getFieldId());
        if (orig != null) {
            orig.setFilterApplied(false);
        }
        storeFilters();
    }

public void removeFilter ( final UITableHeader _uiTableHeader ) { this . filters . remove ( _uiTableHeader . getFieldName ( ) ) ; final UITableHeader orig = getHeader4Id ( _uiTableHeader . getFieldId ( ) ) ; if ( orig != null ) { orig . setFilterApplied ( false ) ; } storeFilters ( ) ; }

Method to remove a filter from the filters.

@param _uiTableHeader UITableHeader the filter is removed for

Method to remove a filter from the filters .


protected GridCell getCell(final GridColumn _column,
                           final UIValue _uiValue,
                           final Object _sortValue,
                           final Map<Long, JSField> _fields)
        throws EFapsException
    {
        JSField jsField;
        if (_fields.containsKey(_uiValue.getField().getId())) {
            jsField = _fields.get(_uiValue.getField().getId());
        } else {
            jsField = new JSField(_uiValue);
            final IComponentFactory fact = jsField.getFactory();
            if (fact == null) {
                _fields.put(_uiValue.getField().getId(), null);
                jsField = null;
            } else {
                _fields.put(_uiValue.getField().getId(), jsField);
                if (fact instanceof DateUIFactory) {
                    _column.setDataType("date");
                } else if (fact instanceof DateTimeUIFactory) {
                    _column.setDataType("datetime");
                } else if (fact instanceof DecimalUIFactory || fact instanceof NumberUIFactory) {
                    _column.setDataType("number");
                } else if (fact instanceof BooleanUIFactory) {
                    _column.setDataType("enum");
                    @SuppressWarnings("unchecked")
                    final Map<String, ?> enumValues = (Map<String, ?>) _uiValue.getReadOnlyValue(TargetMode.VIEW);
                    _column.setEnumValues(enumValues.keySet());
                }
            }
        }
        final String value;
        if (jsField == null) {
            value = "";
        } else {
            jsField.setValue(_uiValue);
            value = jsField.getFactory().getStringValue(jsField);
        }
        return  new GridCell().setValue(value)
                        .setSortValue(_sortValue)
                        .setFieldConfig(_column.getFieldConfig());
    }

protected GridCell getCell ( final GridColumn _column , final UIValue _uiValue , final Object _sortValue , final Map < Long , JSField > _fields ) throws EFapsException { JSField jsField ; if ( _fields . containsKey ( _uiValue . getField ( ) . getId ( ) ) ) { jsField = _fields . get ( _uiValue . getField ( ) . getId ( ) ) ; } else { jsField = new JSField ( _uiValue ) ; final IComponentFactory fact = jsField . getFactory ( ) ; if ( fact == null ) { _fields . put ( _uiValue . getField ( ) . getId ( ) , null ) ; jsField = null ; } else { _fields . put ( _uiValue . getField ( ) . getId ( ) , jsField ) ; if ( fact instanceof DateUIFactory ) { _column . setDataType ( "date" ) ; } else if ( fact instanceof DateTimeUIFactory ) { _column . setDataType ( "datetime" ) ; } else if ( fact instanceof DecimalUIFactory || fact instanceof NumberUIFactory ) { _column . setDataType ( "number" ) ; } else if ( fact instanceof BooleanUIFactory ) { _column . setDataType ( "enum" ) ; @ SuppressWarnings ( "unchecked" ) final Map < String , ? > enumValues = ( Map < String , ? > ) _uiValue . getReadOnlyValue ( TargetMode . VIEW ) ; _column . setEnumValues ( enumValues . keySet ( ) ) ; } } } final String value ; if ( jsField == null ) { value = "" ; } else { jsField . setValue ( _uiValue ) ; value = jsField . getFactory ( ) . getStringValue ( jsField ) ; } return new GridCell ( ) . setValue ( value ) . setSortValue ( _sortValue ) . setFieldConfig ( _column . getFieldConfig ( ) ) ; }

Gets the cell.

@param _column the column
@param _uiValue the ui value
@param _sortValue the sort value
@param _fields the fields
@return the cell
@throws EFapsException the e faps exception


@SuppressWarnings("unchecked")
    protected List<Instance> getInstances()
        throws EFapsException
    {
        final List<Return> returns = getEventObject().executeEvents(EventType.UI_TABLE_EVALUATE,
                        ParameterValues.INSTANCE, getCallInstance(),
                        ParameterValues.CALL_INSTANCE, getCallInstance(),
                        ParameterValues.PARAMETERS, Context.getThreadContext().getParameters(),
                        ParameterValues.CLASS, this,
                        ParameterValues.OTHERS, this.filterList);
        List<Instance> ret = null;
        if (returns.size() < 1) {
            throw new EFapsException(UIGrid.class, "getInstanceList");
        } else {
            final Object result = returns.get(0).get(ReturnValues.VALUES);
            if (result instanceof List) {
                ret = (List<Instance>) result;
            }
        }
        return ret;
    }

@ SuppressWarnings ( "unchecked" ) protected List < Instance > getInstances ( ) throws EFapsException { final List < Return > returns = getEventObject ( ) . executeEvents ( EventType . UI_TABLE_EVALUATE , ParameterValues . INSTANCE , getCallInstance ( ) , ParameterValues . CALL_INSTANCE , getCallInstance ( ) , ParameterValues . PARAMETERS , Context . getThreadContext ( ) . getParameters ( ) , ParameterValues . CLASS , this , ParameterValues . OTHERS , this . filterList ) ; List < Instance > ret = null ; if ( returns . size ( ) < 1 ) { throw new EFapsException ( UIGrid . class , "getInstanceList" ) ; } else { final Object result = returns . get ( 0 ) . get ( ReturnValues . VALUES ) ; if ( result instanceof List ) { ret = ( List < Instance > ) result ; } } return ret ; }

Gets the instances.

@return the instances
@throws EFapsException the e faps exception


protected IFilter getFilter4Field(final Field _field)
    {
        final IFilter ret;
        switch (_field.getFilter().getType()) {
            case STATUS:
            case PICKLIST:
                ret = new ListFilter(_field.getId());
                break;
            case FREETEXT:
            case FORM:
                ret = new MapFilter(_field.getId());
                break;
            case CLASSIFICATION:
                ret = new ClassificationFilter(_field.getId());
                break;
            case NONE:
            default:
                ret = new IFilter()
                {
                    /** The Constant serialVersionUID. */
                    private static final long serialVersionUID = 1L;

                    @Override
                    public long getFieldId()
                    {
                        return _field.getId();
                    }
                };
                break;
        }
        return ret;
    }

protected
IFilter
getFilter4Field
(
final
Field
_field
)
{
final
IFilter
ret
;
switch
(
_field
.
getFilter
(
)
.
getType
(
)
)
{
case
STATUS
:
case
PICKLIST
:
ret
=
new
ListFilter
(
_field
.
getId
(
)
)
;
break
;
case
FREETEXT
:
case
FORM
:
ret
=
new
MapFilter
(
_field
.
getId
(
)
)
;
break
;
case
CLASSIFICATION
:
ret
=
new
ClassificationFilter
(
_field
.
getId
(
)
)
;
break
;
case
:
default
:
ret
=
new
IFilter
(
)
{
/** The Constant serialVersionUID. */
private
static
final
long
serialVersionUID
=
1L
;
@
Override
public
long
getFieldId
(
)
{
return
_field
.
getId
(
)
;
}
}
;
break
;
}
return
ret
;
}

Gets the filter for field.

@param _field the field
@return the filter for field


@Override
    public AbstractCommand getCommand()
        throws CacheReloadException
    {
        AbstractCommand cmd = Command.get(getCmdUUID());
        if (cmd == null) {
            cmd = Menu.get(getCmdUUID());
        }
        return cmd;
    }

@ Override public AbstractCommand getCommand ( ) throws CacheReloadException { AbstractCommand cmd = Command . get ( getCmdUUID ( ) ) ; if ( cmd == null ) { cmd = Menu . get ( getCmdUUID ( ) ) ; } return cmd ; }

Gets the command.

@return the command
@throws CacheReloadException the cache reload exception


public String getTitle()
    {
        String title = "";
        try {
            final String key = getCommand().getTargetTitle() == null
                            ? getCommand().getName() + ".Title"
                            : getCommand().getTargetTitle();
            title = DBProperties.getProperty(key);
            if (title != null && getCallInstance() != null) {
                final PrintQuery print = new PrintQuery(getCallInstance());
                final ValueParser parser = new ValueParser(new StringReader(title));
                final ValueList list = parser.ExpressionString();
                list.makeSelect(print);
                if (print.execute()) {
                    title = list.makeString(getCallInstance(), print, TargetMode.VIEW);
                }
                // Administration
                if (Configuration.getAttributeAsBoolean(Configuration.ConfigAttribute.SHOW_OID)
                                && Context.getThreadContext()
                                                .getPerson()
                                                .isAssigned(Role.get(UUID
                                                                .fromString("1d89358d-165a-4689-8c78-fc625d37aacd")))) {
                    title = title + " " + getCallInstance().getOid();
                }
            }
        } catch (final EFapsException | ParseException e) {
            throw new RestartResponseException(new ErrorPage(new EFapsException(this.getClass(), "",
                            "Error reading the Title")));
        }
        return title;
    }

public
String
getTitle
(
)
{
String
title
=
""
;
try
{
final
String
key
=
getCommand
(
)
.
getTargetTitle
(
)
==
getCommand
(
)
.
getName
(
)
+
".Title"
:
getCommand
(
)
.
getTargetTitle
(
)
;
title
=
DBProperties
.
getProperty
(
key
)
;
if
(
title
!=
&&
getCallInstance
(
)
!=
)
{
final
PrintQuery
print
=
new
PrintQuery
(
getCallInstance
(
)
)
;
final
ValueParser
parser
=
new
ValueParser
(
new
StringReader
(
title
)
)
;
final
ValueList
list
=
parser
.
ExpressionString
(
)
;
list
.
makeSelect
(
print
)
;
if
(
print
.
execute
(
)
)
{
title
=
list
.
makeString
(
getCallInstance
(
)
,
print
,
TargetMode
.
VIEW
)
;
}
// Administration
if
(
Configuration
.
getAttributeAsBoolean
(
Configuration
.
ConfigAttribute
.
SHOW_OID
)
&&
Context
.
getThreadContext
(
)
.
getPerson
(
)
.
isAssigned
(
Role
.
get
(
UUID
.
fromString
(
"1d89358d-165a-4689-8c78-fc625d37aacd"
)
)
)
)
{
title
=
title
+
" "
+
getCallInstance
(
)
.
getOid
(
)
;
}
}
}
catch
(
final
EFapsException
|
ParseException
e
)
{
throw
new
RestartResponseException
(
new
ErrorPage
(
new
EFapsException
(
this
.
getClass
(
)
,
""
,
"Error reading the Title"
)
)
)
;
}
return
title
;
}

This method retrieves the Value for the Title from the eFaps Database.

@return Value of the Title

This method retrieves the Value for the Title from the eFaps Database .


public boolean isDateFilter(final IFilter _filter) throws EFapsException
    {
        final boolean ret;
        final Field field = Field.get(_filter.getFieldId());
        // Explicitly set UIProvider
        if (field.getUIProvider() != null && (field.getUIProvider() instanceof DateTimeUI || field
                        .getUIProvider() instanceof DateUI)) {
            ret = true;
        } else {
            final Attribute attr = getType().getAttribute(field.getAttribute());
            if (attr == null) {
                ret = false;
            } else {
                final IUIProvider uiProvider = attr.getAttributeType().getUIProvider();
                ret = uiProvider instanceof DateTimeUI || uiProvider instanceof DateUI;
            }
        }
        return ret;
    }

public
boolean
isDateFilter
(
final
IFilter
_filter
)
throws
EFapsException
{
final
boolean
ret
;
final
Field
field
=
Field
.
get
(
_filter
.
getFieldId
(
)
)
;
// Explicitly set UIProvider
if
(
field
.
getUIProvider
(
)
!=
&&
(
field
.
getUIProvider
(
)
instanceof
DateTimeUI
||
field
.
getUIProvider
(
)
instanceof
DateUI
)
)
{
ret
=
true
;
}
else
{
final
Attribute
attr
=
getType
(
)
.
getAttribute
(
field
.
getAttribute
(
)
)
;
if
(
attr
==
)
{
ret
=
false
;
}
else
{
final
IUIProvider
uiProvider
=
attr
.
getAttributeType
(
)
.
getUIProvider
(
)
;
ret
=
uiProvider
instanceof
DateTimeUI
||
uiProvider
instanceof
DateUI
;
}
}
return
ret
;
}

Checks if is date filter.

@param _filter the filter
@return true, if is date filter
@throws EFapsException the e faps exception


public GridRow getRow4Id(final String _rowId)
        throws EFapsException
    {
        final String[] rowIds = _rowId.split("-");
        GridRow row = null;
        for (final String id : rowIds) {
            if (row == null) {
                row = getValues().get(Integer.parseInt(id));
            } else {
                row = row.getChildren().get(Integer.parseInt(id));
            }
        }
        return row;
    }

public GridRow getRow4Id ( final String _rowId ) throws EFapsException { final String [ ] rowIds = _rowId . split ( "-" ) ; GridRow row = null ; for ( final String id : rowIds ) { if ( row == null ) { row = getValues ( ) . get ( Integer . parseInt ( id ) ) ; } else { row = row . getChildren ( ) . get ( Integer . parseInt ( id ) ) ; } } return row ; }

Gets the row for id.

@param _rowId the row id
@return the row for id
@throws EFapsException the e faps exception


public static File print(final UIGrid _uiGrid)
    {
        File ret = null;
        final String clazzName = Configuration.getAttribute(ConfigAttribute.GRIDPRINTESJP);
        try {
            UIGrid.LOG.debug("Print method executed for {}", _uiGrid);

            final Class<?> clazz = Class.forName(clazzName, false, EFapsClassLoader.getInstance());
            final EventExecution event = (EventExecution) clazz.newInstance();
            final Parameter param = new Parameter();
            param.put(ParameterValues.PARAMETERS, Context.getThreadContext().getParameters());
            param.put(ParameterValues.CLASS, _uiGrid);
            final Return retu = event.execute(param);
            if (retu != null) {
                ret = (File) retu.get(ReturnValues.VALUES);
            }
        } catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            UIGrid.LOG.error("Catched", e);
        } catch (final EFapsException e) {
            UIGrid.LOG.error("Catched", e);
        }
        return ret;
    }

public
static
File
print
(
final
UIGrid
_uiGrid
)
{
File
ret
=
;
final
String
clazzName
=
Configuration
.
getAttribute
(
ConfigAttribute
.
GRIDPRINTESJP
)
;
try
{
UIGrid
.
LOG
.
debug
(
"Print method executed for {}"
,
_uiGrid
)
;
final
Class
<
>
clazz
=
Class
.
forName
(
clazzName
,
false
,
EFapsClassLoader
.
getInstance
(
)
)
;
final
EventExecution
event
=
(
EventExecution
)
clazz
.
newInstance
(
)
;
final
Parameter
param
=
new
Parameter
(
)
;
param
.
put
(
ParameterValues
.
PARAMETERS
,
Context
.
getThreadContext
(
)
.
getParameters
(
)
)
;
param
.
put
(
ParameterValues
.
CLASS
,
_uiGrid
)
;
final
Return
retu
=
event
.
execute
(
param
)
;
if
(
retu
!=
)
{
ret
=
(
File
)
retu
.
get
(
ReturnValues
.
VALUES
)
;
}
}
catch
(
final
ClassNotFoundException
|
InstantiationException
|
IllegalAccessException
e
)
{
UIGrid
.
LOG
.
error
(
"Catched"
,
e
)
;
}
catch
(
final
EFapsException
e
)
{
UIGrid
.
LOG
.
error
(
"Catched"
,
e
)
;
}
return
ret
;
}

Prints the.

@param _uiGrid the ui grid
@return the file


protected String getQuery()
    {
        final StringBuilder ret = new StringBuilder();
        try {
            final String clazzname;
            if (EFapsSystemConfiguration.get().containsAttributeValue("org.efaps.kernel.index.QueryBuilder")) {
                clazzname = EFapsSystemConfiguration.get().getAttributeValue("org.efaps.kernel.index.QueryBuilder");
            } else {
                clazzname = "org.efaps.esjp.admin.index.LucenceQueryBuilder";
            }
            final Class<?> clazz = Class.forName(clazzname, false, EFapsClassLoader.getInstance());
            final Object obj = clazz.newInstance();
            final Method method = clazz.getMethod("getQuery4DimValues", String.class, List.class, List.class);
            final Object newQuery = method.invoke(obj, getCurrentQuery(), getIncluded(), getExcluded());
            ret.append(newQuery);
        } catch (final EFapsException | ClassNotFoundException | InstantiationException | IllegalAccessException
                        | NoSuchMethodException | SecurityException | IllegalArgumentException
                        | InvocationTargetException e) {
            IndexSearch.LOG.error("Catched", e);
            ret.append(getCurrentQuery());
        }
        return ret.toString();
    }


private List<DimValue> getExcluded()
    {
        final List<DimValue> ret = new ArrayList<>();
        for (final DimTreeNode node : getDimensionProvider().getRootList()) {
            ret.addAll(node.getExcluded());
        }
        return ret;
    }

private List < DimValue > getExcluded ( ) { final List < DimValue > ret = new ArrayList <> ( ) ; for ( final DimTreeNode node : getDimensionProvider ( ) . getRootList ( ) ) { ret . addAll ( node . getExcluded ( ) ) ; } return ret ; }

Gets the excluded.

@return the excluded


private boolean dimFilterApplied(final List<DimTreeNode> _nodes)
    {
        final List<DimTreeNode> nodes = _nodes == null ? getDimensionProvider().getRootList() : _nodes;

        boolean ret = false;
        for (final DimTreeNode node : nodes) {
            if (node.getStatus() != null) {
                ret = true;
                break;
            }
            ret = dimFilterApplied(node.getChildren());
            if (ret) {
                break;
            }
        }
        return ret;
    }

private boolean dimFilterApplied ( final List < DimTreeNode > _nodes ) { final List < DimTreeNode > nodes = _nodes == null ? getDimensionProvider ( ) . getRootList ( ) : _nodes ; boolean ret = false ; for ( final DimTreeNode node : nodes ) { if ( node . getStatus ( ) != null ) { ret = true ; break ; } ret = dimFilterApplied ( node . getChildren ( ) ) ; if ( ret ) { break ; } } return ret ; }

Check if a dimension filter applied.

@param _nodes the nodes
@return true, if successful


private void fillDimensionProvider(final boolean _updateDim)
    {
        final DimensionProvider provider = getDimensionProvider();
        final Iterator<? extends DimTreeNode> currentIter = provider.getRoots();

        final List<Dimension> dims = getDimensions();
        if (_updateDim && dims.isEmpty()) {
            provider.getRootList().clear();
        } else {
            Collections.sort(dims, new Comparator<Dimension>()
            {

                @Override
                public int compare(final Dimension _arg0,
                                   final Dimension _arg1)
                {
                    final String dim0 = DBProperties.getProperty(DimensionPanel.class.getName() + "." + _arg0.getKey());
                    final String dim1 = DBProperties.getProperty(DimensionPanel.class.getName() + "." + _arg1.getKey());
                    return dim0.compareTo(dim1);
                }
            });

            final Iterator<Dimension> newDimsIter = dims.iterator();
            while (currentIter.hasNext()) {
                final DimTreeNode current = currentIter.next();
                if (newDimsIter.hasNext()) {
                    final Dimension newDim = newDimsIter.next();
                    if (!newDim.getKey().equals(((Dimension) current.getValue()).getKey())) {
                        currentIter.remove();
                    } else if (_updateDim) {
                        current.update(newDim.getValues());
                    }
                }
            }
            // add new ones
            while (newDimsIter.hasNext()) {
                final DimTreeNode node = new DimTreeNode().setValue(newDimsIter.next());
                provider.getRootList().add(node);
            }
        }
    }

private
void
fillDimensionProvider
(
final
boolean
_updateDim
)
{
final
DimensionProvider
provider
=
getDimensionProvider
(
)
;
final
Iterator
<
extends
DimTreeNode
>
currentIter
=
provider
.
getRoots
(
)
;
final
List
<
Dimension
>
dims
=
getDimensions
(
)
;
if
(
_updateDim
&&
dims
.
isEmpty
(
)
)
{
provider
.
getRootList
(
)
.
clear
(
)
;
}
else
{
Collections
.
sort
(
dims
,
new
Comparator
<
Dimension
>
(
)
{
@
Override
public
int
compare
(
final
Dimension
_arg0
,
final
Dimension
_arg1
)
{
final
String
dim0
=
DBProperties
.
getProperty
(
DimensionPanel
.
class
.
getName
(
)
+
"."
+
_arg0
.
getKey
(
)
)
;
final
String
dim1
=
DBProperties
.
getProperty
(
DimensionPanel
.
class
.
getName
(
)
+
"."
+
_arg1
.
getKey
(
)
)
;
return
dim0
.
compareTo
(
dim1
)
;
}
}
)
;
final
Iterator
<
Dimension
>
newDimsIter
=
dims
.
iterator
(
)
;
while
(
currentIter
.
hasNext
(
)
)
{
final
DimTreeNode
current
=
currentIter
.
next
(
)
;
if
(
newDimsIter
.
hasNext
(
)
)
{
final
Dimension
newDim
=
newDimsIter
.
next
(
)
;
if
(
!
newDim
.
getKey
(
)
.
equals
(
(
(
Dimension
)
current
.
getValue
(
)
)
.
getKey
(
)
)
)
{
currentIter
.
remove
(
)
;
}
else
if
(
_updateDim
)
{
current
.
update
(
newDim
.
getValues
(
)
)
;
}
}
}
// add new ones
while
(
newDimsIter
.
hasNext
(
)
)
{
final
DimTreeNode
node
=
new
DimTreeNode
(
)
.
setValue
(
newDimsIter
.
next
(
)
)
;
provider
.
getRootList
(
)
.
add
(
node
)
;
}
}
}

Fill dimension provider.

@param _updateDim the update dim


private Map<String, Object> buildHierarchyParameters(final List<String> parents, final List<String> children) {
        final MultiMap<String, Object> parameters = new MultiMap<>();

        if (parents != null) {
            for (final String parent : parents) {
                parameters.put("parents", parent);
            }
        }

        if (children != null) {
            for (final String child : children) {
                parameters.put("children", child);
            }
        }

        return parameters;
    }

private Map < String , Object > buildHierarchyParameters ( final List < String > parents , final List < String > children ) { final MultiMap < String , Object > parameters = new MultiMap <> ( ) ; if ( parents != null ) { for ( final String parent : parents ) { parameters . put ( "parents" , parent ) ; } } if ( children != null ) { for ( final String child : children ) { parameters . put ( "children" , child ) ; } } return parameters ; }

Build the hierarchy parameters map for a create group request


public static boolean rootElementMatches(FileResource fileResource, String path, String expectedRootElement) throws IOException {
        try (InputStream stream = fileResource.createStream()) {
            XMLStreamReader reader = factory.createXMLStreamReader(stream);
            while (reader.hasNext()) {
                int event = reader.next();
                switch (event) {
                    case XMLStreamConstants.START_ELEMENT:
                        String rootElement = reader.getLocalName();
                        return expectedRootElement.equals(rootElement);
                }
            }
        } catch (XMLStreamException e) {
            LOGGER.warn("Cannot parse XML file '{}'.", path);
        }
        return false;

    }

public
static
boolean
rootElementMatches
(
FileResource
fileResource
,
String
path
,
String
expectedRootElement
)
throws
IOException
{
try
(
InputStream
stream
=
fileResource
.
createStream
(
)
)
{
XMLStreamReader
reader
=
factory
.
createXMLStreamReader
(
stream
)
;
while
(
reader
.
hasNext
(
)
)
{
int
event
=
reader
.
next
(
)
;
switch
(
event
)
{
case
XMLStreamConstants
.
START_ELEMENT
:
String
rootElement
=
reader
.
getLocalName
(
)
;
return
expectedRootElement
.
equals
(
rootElement
)
;
}
}
}
catch
(
XMLStreamException
e
)
{
LOGGER
.
warn
(
"Cannot parse XML file '{}'."
,
path
)
;
}
return
false
;
}

Matches a file resource for being an XML file with a specific root
element.

@param fileResource
The file resource.
@param path
The path of the file resource.
@param expectedRootElement
The expected local name of the root element.
@return `true` If the file is an XML file and contains the
expected root element.
@throws IOException
If the file resource cannot be read.

Matches a file resource for being an XML file with a specific root element .


public boolean touch() {
        if (expireAfterAccess > 0) {
            long now = System.currentTimeMillis();
            if (lastAccessTimestampMs + LAST_ACCESS_THRESHOLD_MS < now) {
                lastAccessTimestampMs = now;
                return true;
            }
        }
        return false;
    }

public boolean touch ( ) { if ( expireAfterAccess > 0 ) { long now = System . currentTimeMillis ( ) ; if ( lastAccessTimestampMs + LAST_ACCESS_THRESHOLD_MS < now ) { lastAccessTimestampMs = now ; return true ; } } return false ; }

"Touch" the cache entry.

@return
@since 0.2.1 entry can be touched only if {@code expireAfterAccess > 0}.


protected void refreshTTL(String key, CacheEntry ce) {
        final String KEY = calcCacheKey(key);
        final long TTL = ce.getExpireAfterAccess();
        try (ShardedJedis jedis = getJedis()) {
            if (TTL > 0) {
                if (keyMode == KeyMode.HASH) {
                    jedis.expire(getName(), (int) TTL);
                } else {
                    jedis.expire(SafeEncoder.encode(KEY), (int) TTL);
                }
            }
        } catch (Exception e) {
            throw e instanceof CacheException ? (CacheException) e : new CacheException(e);
        }
    }

protected void refreshTTL ( String key , CacheEntry ce ) { final String KEY = calcCacheKey ( key ) ; final long TTL = ce . getExpireAfterAccess ( ) ; try ( ShardedJedis jedis = getJedis ( ) ) { if ( TTL > 0 ) { if ( keyMode == KeyMode . HASH ) { jedis . expire ( getName ( ) , ( int ) TTL ) ; } else { jedis . expire ( SafeEncoder . encode ( KEY ) , ( int ) TTL ) ; } } } catch ( Exception e ) { throw e instanceof CacheException ? ( CacheException ) e : new CacheException ( e ) ; } }

Refresh TTL of a cache entry.

@param key
@param ce
@since 0.6.2


public static Object tryClone(Object toBeCloned) {
        if (toBeCloned == null) {
            return null;
        }
        Object clonedObj = null;
        if (toBeCloned instanceof Cloneable) {
            try {
                Method method = Object.class.getDeclaredMethod("clone");
                method.setAccessible(true);
                clonedObj = method.invoke(toBeCloned);
            } catch (Exception e) {
                if (e instanceof CloneNotSupportedException) {
                    clonedObj = toBeCloned;
                } else {
                    throw e instanceof RuntimeException ? (RuntimeException) e
                            : new RuntimeException(e);
                }
            }
        } else {
            clonedObj = toBeCloned;
        }
        return clonedObj;
    }

public static Object tryClone ( Object toBeCloned ) { if ( toBeCloned == null ) { return null ; } Object clonedObj = null ; if ( toBeCloned instanceof Cloneable ) { try { Method method = Object . class . getDeclaredMethod ( "clone" ) ; method . setAccessible ( true ) ; clonedObj = method . invoke ( toBeCloned ) ; } catch ( Exception e ) { if ( e instanceof CloneNotSupportedException ) { clonedObj = toBeCloned ; } else { throw e instanceof RuntimeException ? ( RuntimeException ) e : new RuntimeException ( e ) ; } } } else { clonedObj = toBeCloned ; } return clonedObj ; }

Try cloning an object.

@param toBeCloned
@return result from object's {@code clone()} method if object implements
interface {@link Cloneable}, otherwise the same object is
returned


public AbstractCache init() {
        /*
         * Parse custom property: capacity
         */
        long oldCapacity = this.capacity;
        try {
            String entry = getCacheProperty(CACHE_PROP_CAPACITY);
            if (entry != null) {
                this.capacity = Long.parseLong(entry);
            }
        } catch (Exception e) {
            this.capacity = oldCapacity;
            LOGGER.warn(e.getMessage(), e);
        }
        if (capacity < -1) {
            setCapacity(-1);
        }

        /*
         * Parse custom property: expire-after-access
         */
        long oldExpireAfterAccess = this.expireAfterAccess;
        try {
            String entry = getCacheProperty(CACHE_PROP_EXPIRE_AFTER_ACCESS);
            if (entry != null) {
                this.expireAfterAccess = Long.parseLong(entry);
            }
        } catch (Exception e) {
            this.expireAfterAccess = oldExpireAfterAccess;
            LOGGER.warn(e.getMessage(), e);
        }
        if (expireAfterAccess < -1) {
            setExpireAfterAccess(-1);
        }

        /*
         * Parse custom property: expire-after-write
         */
        long oldExpireAfterWrite = this.expireAfterWrite;
        try {
            String entry = getCacheProperty(CACHE_PROP_EXPIRE_AFTER_WRITE);
            if (entry != null) {
                this.expireAfterWrite = Long.parseLong(entry);
            }
        } catch (Exception e) {
            this.expireAfterWrite = oldExpireAfterWrite;
            LOGGER.warn(e.getMessage(), e);
        }
        if (expireAfterWrite < -1) {
            setExpireAfterWrite(-1);
        }

        return this;
    }

/*
         * Parse custom property: capacity
         */


public AbstractCache setCacheProperties(Properties cacheProps) {
        this.cacheProps = cacheProps != null ? new Properties(cacheProps) : new Properties();
        return this;
    }

public AbstractCache setCacheProperties ( Properties cacheProps ) { this . cacheProps = cacheProps != null ? new Properties ( cacheProps ) : new Properties ( ) ; return this ; }

Cache's custom properties.

@param cacheProps
@return
@since 0.6.1


protected String getCacheProperty(String key) {
        return cacheProps != null ? cacheProps.getProperty(key) : null;
    }

protected String getCacheProperty ( String key ) { return cacheProps != null ? cacheProps . getProperty ( key ) : null ; }

Get cache's custom property.

@param key
@return
@since 0.6.1


protected String calcCacheKey(String key) {
        switch (keyMode) {
        case HASH:
        case MONOPOLISTIC:
            return key;
        case NAMESPACE:
            return getName() + ":" + key;
        default:
            throw new IllegalStateException("Invalid key mode: " + keyMode);
        }
    }

protected
String
calcCacheKey
(
String
key
)
{
switch
(
keyMode
)
{
case
HASH
:
case
MONOPOLISTIC
:
return
key
;
case
NAMESPACE
:
return
getName
(
)
+
":"
+
key
;
default
:
throw
new
IllegalStateException
(
"Invalid key mode: "
+
keyMode
)
;
}
}

Calculates cache key based on the key mode.

HASH & MONOPOLISTIC mode: return the key as-is

NAMESPACE mode: return {@code cache_name:key}

@param key
@return

Calculates cache key based on the key mode .


protected Properties getCacheProperties(String name) {
        return cacheProperties != null ? cacheProperties.get(name) : null;
    }

protected Properties getCacheProperties ( String name ) { return cacheProperties != null ? cacheProperties . get ( name ) : null ; }

Gets a cache's properties

@param name
@return


@Override
    public void set(String key, Object entry, long expireAfterWrite, long expireAfterAccess) {
        try {
            if (localCache != null) {
                localCache.set(key, entry, expireAfterWrite, expireAfterAccess);
            }
            if (remoteCache != null) {
                remoteCache.set(key, entry, expireAfterWrite, expireAfterAccess);
            }
        } catch (Exception e) {
            throw e instanceof CacheException ? (CacheException) e : new CacheException(e);
        }
    }

@ Override public void set ( String key , Object entry , long expireAfterWrite , long expireAfterAccess ) { try { if ( localCache != null ) { localCache . set ( key , entry , expireAfterWrite , expireAfterAccess ) ; } if ( remoteCache != null ) { remoteCache . set ( key , entry , expireAfterWrite , expireAfterAccess ) ; } } catch ( Exception e ) { throw e instanceof CacheException ? ( CacheException ) e : new CacheException ( e ) ; } }

Puts an entry to both local and remote caches, with specified expiries.

Puts an entry to both local and remote caches with specified expiries .


@Override
    public void delete(String key) {
        try {
            if (localCache != null) {
                localCache.delete(key);
            }
            if (remoteCache != null) {
                remoteCache.delete(key);
            }
        } catch (Exception e) {
            throw e instanceof CacheException ? (CacheException) e : new CacheException(e);
        }
    }

@ Override public void delete ( String key ) { try { if ( localCache != null ) { localCache . delete ( key ) ; } if ( remoteCache != null ) { remoteCache . delete ( key ) ; } } catch ( Exception e ) { throw e instanceof CacheException ? ( CacheException ) e : new CacheException ( e ) ; } }

Delete an entry from both local and remote caches.

Delete an entry from both local and remote caches .


public void deleteLocal(String key) {
        if (localCache != null) {
            try {
                localCache.delete(key);
            } catch (Exception e) {
                throw e instanceof CacheException ? (CacheException) e : new CacheException(e);
            }
        }
    }

public void deleteLocal ( String key ) { if ( localCache != null ) { try { localCache . delete ( key ) ; } catch ( Exception e ) { throw e instanceof CacheException ? ( CacheException ) e : new CacheException ( e ) ; } } }

Delete an entry from the local cache.

@param key


@Override
    public void deleteAll() {
        try {
            if (localCache != null) {
                localCache.deleteAll();
            }
            if (remoteCache != null) {
                remoteCache.deleteAll();
            }
        } catch (Exception e) {
            throw e instanceof CacheException ? (CacheException) e : new CacheException(e);
        }
    }

@ Override public void deleteAll ( ) { try { if ( localCache != null ) { localCache . deleteAll ( ) ; } if ( remoteCache != null ) { remoteCache . deleteAll ( ) ; } } catch ( Exception e ) { throw e instanceof CacheException ? ( CacheException ) e : new CacheException ( e ) ; } }

Deletes all entries in both local and remote caches.

Deletes all entries in both local and remote caches .


public void deleteAllLocal() {
        if (localCache != null) {
            try {
                localCache.deleteAll();
            } catch (Exception e) {
                throw e instanceof CacheException ? (CacheException) e : new CacheException(e);
            }
        }
    }

public void deleteAllLocal ( ) { if ( localCache != null ) { try { localCache . deleteAll ( ) ; } catch ( Exception e ) { throw e instanceof CacheException ? ( CacheException ) e : new CacheException ( e ) ; } } }

Deletes all entries in the local cache .


public String getLabelForElement(FormCheckerElement e, Map<String, String> attribs) {
		return config.getFormBuilder().getLabelForElement(e, new TagAttributes(attribs), firstRun);
	}

public String getLabelForElement ( FormCheckerElement e , Map < String , String > attribs ) { return config . getFormBuilder ( ) . getLabelForElement ( e , new TagAttributes ( attribs ) , firstRun ) ; }


private void sortTabIndexes() {
		int tabIndex = 100;
		for (FormCheckerElement elem : form.getElements()) {
			elem.setTabIndex(tabIndex);
			tabIndex = elem.getLastTabIndex();
			tabIndex++;
		}
	}

private void sortTabIndexes ( ) { int tabIndex = 100 ; for ( FormCheckerElement elem : form . getElements ( ) ) { elem . setTabIndex ( tabIndex ) ; tabIndex = elem . getLastTabIndex ( ) ; tabIndex ++ ; } }


@Deprecated
	final public String generateGenericForm(String formAction,
			boolean firstRun, FormCheckerForm form, Request req, FormCheckerConfig config) {
		return this.generateGenericForm(formAction, firstRun, form, req, config.properties);
	}

@ Deprecated final public String generateGenericForm ( String formAction , boolean firstRun , FormCheckerForm form , Request req , FormCheckerConfig config ) { return this . generateGenericForm ( formAction , firstRun , form , req , config . properties ) ; }

Renders the html for the complete form with all elements within.

Renders the html for the complete form with all elements within .


String generateHtmlForElement(boolean firstRun, MessageSource messageSource, FormCheckerElement elem, boolean html5Validation) {
		InputElementStructure inputStruct = new InputElementStructure();
		// errors
		ValidationResult vr = getErrors(elem, firstRun);
		if (!vr.isValid()) {
			inputStruct.setErrors(formatError(messageSource.getMessage(vr)));
		}

		// label
		boolean displayLabel = !StringUtils.isEmpty(elem.getDescription());
		if (displayLabel) {
			inputStruct.setLabel(getLabelForElement(elem, getLabelAttributes(elem), firstRun));
		}
		// input tag
		Map<String, String> attribs = new LinkedHashMap<>();
		addAttributesToInputFields(attribs, elem);
		inputStruct.setInput(elem.getInputTag(attribs, messageSource, html5Validation));
		// help tag
		if (!StringUtils.isEmpty(elem.getHelpText())) {
			inputStruct.setHelp(getHelpTag(elem.getHelpText(), elem));
		}
		return getCompleteRenderedInput(inputStruct, elem, firstRun);
	}

String
generateHtmlForElement
(
boolean
firstRun
,
MessageSource
messageSource
,
FormCheckerElement
elem
,
boolean
html5Validation
)
{
InputElementStructure
inputStruct
=
new
InputElementStructure
(
)
;
// errors
ValidationResult
vr
=
getErrors
(
elem
,
firstRun
)
;
if
(
!
vr
.
isValid
(
)
)
{
inputStruct
.
setErrors
(
formatError
(
messageSource
.
getMessage
(
vr
)
)
)
;
}
// label
boolean
displayLabel
=
!
StringUtils
.
isEmpty
(
elem
.
getDescription
(
)
)
;
if
(
displayLabel
)
{
inputStruct
.
setLabel
(
getLabelForElement
(
elem
,
getLabelAttributes
(
elem
)
,
firstRun
)
)
;
}
// input tag
Map
<
String
,
String
>
attribs
=
new
LinkedHashMap
<>
(
)
;
addAttributesToInputFields
(
attribs
,
elem
)
;
inputStruct
.
setInput
(
elem
.
getInputTag
(
attribs
,
messageSource
,
html5Validation
)
)
;
// help tag
if
(
!
StringUtils
.
isEmpty
(
elem
.
getHelpText
(
)
)
)
{
inputStruct
.
setHelp
(
getHelpTag
(
elem
.
getHelpText
(
)
,
elem
)
)
;
}
return
getCompleteRenderedInput
(
inputStruct
,
elem
,
firstRun
)
;
}


public String getCompleteRenderedInput(InputElementStructure inputStruct, FormCheckerElement elem,
			boolean firstRun) {
		StringBuilder elemHtml = new StringBuilder();
		Wrapper elementWrapper = getWrapperForElem(elem, firstRun);
		elemHtml.append(elementWrapper.start);
		elemHtml.append(inputStruct.getErrors());

		Wrapper labelWrapper = getWrapperForLabel(elem);
		elemHtml.append(labelWrapper.start).append(inputStruct.getLabel()).append(labelWrapper.end);

		Wrapper inputWrapper = getWrapperForInput(elem);
		elemHtml.append(inputWrapper.start);

		elemHtml.append(inputStruct.getInput());
		elemHtml.append(inputStruct.getHelp());

		elemHtml.append(inputWrapper.end);
		elemHtml.append(elementWrapper.end);

		return elemHtml.toString();

	}

public String getCompleteRenderedInput ( InputElementStructure inputStruct , FormCheckerElement elem , boolean firstRun ) { StringBuilder elemHtml = new StringBuilder ( ) ; Wrapper elementWrapper = getWrapperForElem ( elem , firstRun ) ; elemHtml . append ( elementWrapper . start ) ; elemHtml . append ( inputStruct . getErrors ( ) ) ; Wrapper labelWrapper = getWrapperForLabel ( elem ) ; elemHtml . append ( labelWrapper . start ) . append ( inputStruct . getLabel ( ) ) . append ( labelWrapper . end ) ; Wrapper inputWrapper = getWrapperForInput ( elem ) ; elemHtml . append ( inputWrapper . start ) ; elemHtml . append ( inputStruct . getInput ( ) ) ; elemHtml . append ( inputStruct . getHelp ( ) ) ; elemHtml . append ( inputWrapper . end ) ; elemHtml . append ( elementWrapper . end ) ; return elemHtml . toString ( ) ; }

override this, if you want to have a different order of the elements.

override this if you want to have a different order of the elements .


public String getElement(String name) {
		return formBuilder.generateHtmlForElement(fc.firstRun, fc.config.getProperties(), form.getElement(name), this.form.isHtml5Validation());
	}

public String getElement ( String name ) { return formBuilder . generateHtmlForElement ( fc . firstRun , fc . config . getProperties ( ) , form . getElement ( name ) , this . form . isHtml5Validation ( ) ) ; }


public static ApplicationContext registerAppContext(String embeddedWebContext, ApplicationContext appContext) {
        return appContextMap.put(embeddedWebContext, appContext);
    }

public static ApplicationContext registerAppContext ( String embeddedWebContext , ApplicationContext appContext ) { return appContextMap . put ( embeddedWebContext , appContext ) ; }

Registers the specified embedded web context.

@return the previously-registered {@link ApplicationContext} or null if nothing previously-registered

Registers the specified embedded web context .


@Deprecated
	public static SelectInput build(String name, LinkedHashMap<String, String> possibleNames) {
		SelectInput si = SelectInput.build(name);
		si.setPossibleValues(possibleNames);
		return si;
	}

@ Deprecated public static SelectInput build ( String name , LinkedHashMap < String , String > possibleNames ) { SelectInput si = SelectInput . build ( name ) ; si . setPossibleValues ( possibleNames ) ; return si ; }

a map is not a good structure for that, because keys may be used more than once

a map is not a good structure for that because keys may be used more than once


protected String buildAllAttributes(TagAttributes tagAttributes, MessageSource messageSource, boolean html5Validation) {
		StringBuilder allAttribs = new StringBuilder();
		allAttribs.append(AttributeUtils.buildAttributes(tagAttributes));
		allAttribs.append(getElementId());
		allAttribs.append(getTabIndexTag());
		if (html5Validation) {
			allAttribs.append(buildRequiredAttribute());
			allAttribs.append(buildFcRequiredMessage(messageSource));
		}
		allAttribs.append(buildSizeAttribute());
		// help-text
		if (!StringUtils.isEmpty(helpText)) {
			allAttribs.append(
					AttributeUtils.buildAttributes(new TagAttributes("aria-describedby",
							parent.getConfig().getFormBuilder().getHelpBlockId(this))));
		}
		return allAttribs.toString();
	}

protected
String
buildAllAttributes
(
TagAttributes
tagAttributes
,
MessageSource
messageSource
,
boolean
html5Validation
)
{
StringBuilder
allAttribs
=
new
StringBuilder
(
)
;
allAttribs
.
append
(
AttributeUtils
.
buildAttributes
(
tagAttributes
)
)
;
allAttribs
.
append
(
getElementId
(
)
)
;
allAttribs
.
append
(
getTabIndexTag
(
)
)
;
if
(
html5Validation
)
{
allAttribs
.
append
(
buildRequiredAttribute
(
)
)
;
allAttribs
.
append
(
buildFcRequiredMessage
(
messageSource
)
)
;
}
allAttribs
.
append
(
buildSizeAttribute
(
)
)
;
// help-text
if
(
!
StringUtils
.
isEmpty
(
helpText
)
)
{
allAttribs
.
append
(
AttributeUtils
.
buildAttributes
(
new
TagAttributes
(
"aria-describedby"
,
parent
.
getConfig
(
)
.
getFormBuilder
(
)
.
getHelpBlockId
(
this
)
)
)
)
;
}
return
allAttribs
.
toString
(
)
;
}


public String buildMaxLen() {
		List<Criterion> criteria = this.getCriteria();
		if (criteria != null) {
			for (Criterion criterion : criteria) {
				if (criterion instanceof MaxLength) {
					return AttributeUtils.buildSingleAttribute("maxlength", Integer.toString(((MaxLength) criterion).getMaxLength()));
				}
			}
		}
		return "";
	}

public String buildMaxLen ( ) { List < Criterion > criteria = this . getCriteria ( ) ; if ( criteria != null ) { for ( Criterion criterion : criteria ) { if ( criterion instanceof MaxLength ) { return AttributeUtils . buildSingleAttribute ( "maxlength" , Integer . toString ( ( ( MaxLength ) criterion ) . getMaxLength ( ) ) ) ; } } } return "" ; }


private List<ContentType> getAcceptedContentTypes()
    {
        Annotation consumesAnnotation = referencedMethod.getAnnotation(Consumes.class);
        if (null == consumesAnnotation) consumesAnnotation = referencedClass.getAnnotation(Consumes.class);
        final List<ContentType> acceptedContentTypes = Lists.newArrayList();
        if (null != consumesAnnotation)
        {
            for (final String cts : ((Consumes)consumesAnnotation).value())
            {
                try
                {
                    acceptedContentTypes.add(ContentType.valueOf(cts));
                }
                catch (IllegalArgumentException e) { }
            }
        }
        return acceptedContentTypes;
    }

private List < ContentType > getAcceptedContentTypes ( ) { Annotation consumesAnnotation = referencedMethod . getAnnotation ( Consumes . class ) ; if ( null == consumesAnnotation ) consumesAnnotation = referencedClass . getAnnotation ( Consumes . class ) ; final List < ContentType > acceptedContentTypes = Lists . newArrayList ( ) ; if ( null != consumesAnnotation ) { for ( final String cts : ( ( Consumes ) consumesAnnotation ) . value ( ) ) { try { acceptedContentTypes . add ( ContentType . valueOf ( cts ) ) ; } catch ( IllegalArgumentException e ) { } } } return acceptedContentTypes ; }


public boolean isSameSession() {
        String sessionId = sessionIdProvider.get();
        if (callbackStartSessionId == null) {
            return sessionId == null;
        }
        return callbackStartSessionId.equals(sessionId);
    }

public boolean isSameSession ( ) { String sessionId = sessionIdProvider . get ( ) ; if ( callbackStartSessionId == null ) { return sessionId == null ; } return callbackStartSessionId . equals ( sessionId ) ; }

Checks if currently we are during same session that we were during
callback creation.

@return True if we are still during same session, false otherwise.

Checks if currently we are during same session that we were during callback creation .


public static <D> CursorConverter<List<D>> listConverter(final CursorConverter<D> converter) {
    return new ListConverter<>(converter);
  }

public static < D > CursorConverter < List < D > > listConverter ( final CursorConverter < D > converter ) { return new ListConverter <> ( converter ) ; }

Wrap a provided converter.
Returns a converter that creates of list of elements obtained with a provider converter.

Wrap a provided converter . Returns a converter that creates of list of elements obtained with a provider converter .


void initStartedLoaders() {
    LoaderManager lm = operatorContext.loaderManager;
    SparseArray<LoaderCookies> listenersMap = this.listenersMap;

    int count = listenersMap.size();
    for (int i = 0; i < count; i++) {
      int loaderId = listenersMap.keyAt(i);
      Loader<?> loader = lm.getLoader(loaderId);
      if (loader != null && loader.isStarted()) {
        LoaderCookies cookies = listenersMap.valueAt(i);
        boolean notInit = (cookies.options & LoaderCookies.ALREADY_INIT) == 0;
        if (notInit) {
          Utils.initLoader(
              operatorContext,
              loaderId,
              STUB_PROVIDER,
              (cookies.options & LoaderCookies.DESTROY_ON_FINISH) == LoaderCookies.DESTROY_ON_FINISH,
              this
          );
        }
      }
    }
  }

void initStartedLoaders ( ) { LoaderManager lm = operatorContext . loaderManager ; SparseArray < LoaderCookies > listenersMap = this . listenersMap ; int count = listenersMap . size ( ) ; for ( int i = 0 ; i < count ; i ++ ) { int loaderId = listenersMap . keyAt ( i ) ; Loader < ? > loader = lm . getLoader ( loaderId ) ; if ( loader != null && loader . isStarted ( ) ) { LoaderCookies cookies = listenersMap . valueAt ( i ) ; boolean notInit = ( cookies . options & LoaderCookies . ALREADY_INIT ) == 0 ; if ( notInit ) { Utils . initLoader ( operatorContext , loaderId , STUB_PROVIDER , ( cookies . options & LoaderCookies . DESTROY_ON_FINISH ) == LoaderCookies . DESTROY_ON_FINISH , this ) ; } } } }


public RemoteProfile getProfileOf(SPFPerson p) {
		if (p == null) {
			throw new NullPointerException();
		}

		return new RemoteProfile(p, mInterface);
	}

public RemoteProfile getProfileOf ( SPFPerson p ) { if ( p == null ) { throw new NullPointerException ( ) ; } return new RemoteProfile ( p , mInterface ) ; }

Provides a reference to a remote profile. With this reference it is
possible to perform read operations and retrieve information from remote
people.

@param p
- the {@link SPFPerson} whose profile to load.
@return an instance of {@link RemoteProfile} to interact with the remote
profile.

Provides a reference to a remote profile . With this reference it is possible to perform read operations and retrieve information from remote people .


public void setChangeListener(OnChangeListener listener) {
        changeListener = listener;
        if (changeListener != null) {
            // add a listener to TagViewer for removed tags events
            tv.setOnRemovedTagListener(new TagsViewer.OnRemovedListener() {
                @Override
                public void onRemovedTag(String tag) {
                    notifyChangeListener();
                }
            });
        }
    }

Set the change listener.

@param listener


public static DocumentBuilderFactory getDocumentBuilderFactory(final String schema)
	{
		System.setProperty(DOCUMENT_BUILDER_FACTORY_KEY, DOCUMENT_BUILDER_FACTORY_VALUE);
		final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(true);
		factory.setValidating(true);
		factory.setAttribute(SCHEMA_LANGUAGE_KEY, HTTP_WWW_W3_ORG_2001_XML_SCHEMA);
		factory.setAttribute(SCHEMA_SOURCE_KEY, schema);
		return factory;
	}

public static DocumentBuilderFactory getDocumentBuilderFactory ( final String schema ) { System . setProperty ( DOCUMENT_BUILDER_FACTORY_KEY , DOCUMENT_BUILDER_FACTORY_VALUE ) ; final DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; factory . setValidating ( true ) ; factory . setAttribute ( SCHEMA_LANGUAGE_KEY , HTTP_WWW_W3_ORG_2001_XML_SCHEMA ) ; factory . setAttribute ( SCHEMA_SOURCE_KEY , schema ) ; return factory ; }

Gets the document builder factory.

@param schema
the schema
@return the document builder factory


public static DOMSource getDOMSource(final File xml, final ErrorHandler errorHandler)
		throws SAXException, ParserConfigurationException, IOException
	{
		return new DOMSource(parse(xml, errorHandler));
	}

public static DOMSource getDOMSource ( final File xml , final ErrorHandler errorHandler ) throws SAXException , ParserConfigurationException , IOException { return new DOMSource ( parse ( xml , errorHandler ) ) ; }

Gets the dOM source.

@param xml
the xml
@param errorHandler
the error handler
@return the dOM source
@throws SAXException
If a SAX error occurs during parsing.
@throws ParserConfigurationException
if a DocumentBuilder cannot be created which satisfies the configuration
requested.
@throws IOException
Signals that an I/O exception has occurred.


public static Schema getSchema(final File xsd, final ErrorHandler errorHandler)
		throws SAXException
	{
		// Create a new instance for an XSD-aware SchemaFactory
		final SchemaFactory schemaFactory = SchemaFactory
			.newInstance(HTTP_WWW_W3_ORG_2001_XML_SCHEMA);

		// Set the ErrorHandler implementation.
		schemaFactory.setErrorHandler(errorHandler);

		// get the custom xsd schema that describes
		// the required format for my XML files.
		return schemaFactory.newSchema(xsd);
	}

Gets the schema.

@param xsd
the xsd
@param errorHandler
the error handler
@return the schema
@throws SAXException
If a SAX error occurs during parsing.


public static Document parse(final File xml, final ErrorHandler errorHandler)
		throws SAXException, ParserConfigurationException, IOException
	{
		final DocumentBuilderFactory factory = getDocumentBuilderFactory(xml.getName());
		final DocumentBuilder builder = factory.newDocumentBuilder();
		builder.setErrorHandler(errorHandler);
		return builder.parse(xml);
	}

public static Document parse ( final File xml , final ErrorHandler errorHandler ) throws SAXException , ParserConfigurationException , IOException { final DocumentBuilderFactory factory = getDocumentBuilderFactory ( xml . getName ( ) ) ; final DocumentBuilder builder = factory . newDocumentBuilder ( ) ; builder . setErrorHandler ( errorHandler ) ; return builder . parse ( xml ) ; }

Parses the.

@param xml
the xml
@param errorHandler
the error handler
@return the document
@throws SAXException
If a SAX error occurs during parsing.
@throws ParserConfigurationException
if a DocumentBuilder cannot be created which satisfies the configuration
requested.
@throws IOException
Signals that an I/O exception has occurred.


public static void validateSchema(final File xsd, final File xml,
		final ErrorHandler errorHandler)
		throws SAXException, ParserConfigurationException, IOException
	{

		final Schema schemaXSD = getSchema(xsd, errorHandler);

		// Create a Validator capable of validating XML files according to my custom schema.
		final Validator validator = schemaXSD.newValidator();

		// parse the XML DOM tree againts the stricter XSD schema
		validator.validate(getDOMSource(xml, errorHandler));
	}

Validate xml through xsd.

@param xsd
the xsd
@param xml
the xml
@param errorHandler
the error handler
@throws SAXException
If a SAX error occurs during parsing.
@throws ParserConfigurationException
if a DocumentBuilder cannot be created which satisfies the configuration
requested.
@throws IOException
Signals that an I/O exception has occurred.


public static boolean validateSchema(final String SchemaUrl, final String XmlDocumentUrl)
		throws SAXException, ParserConfigurationException, IOException
	{
		System.setProperty(DOCUMENT_BUILDER_FACTORY_KEY, DOCUMENT_BUILDER_FACTORY_VALUE);
		final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(true);
		factory.setValidating(true);
		factory.setAttribute(SCHEMA_LANGUAGE_KEY, HTTP_WWW_W3_ORG_2001_XML_SCHEMA);
		factory.setAttribute(SCHEMA_SOURCE_KEY, SchemaUrl);
		final DocumentBuilder builder = factory.newDocumentBuilder();
		final ValidatorHandler handler = new ValidatorHandler();
		builder.setErrorHandler(handler);
		builder.parse(XmlDocumentUrl);
		if (handler.isValid())
		{
			return false;
		}
		return true;
	}

public static boolean validateSchema ( final String SchemaUrl , final String XmlDocumentUrl ) throws SAXException , ParserConfigurationException , IOException { System . setProperty ( DOCUMENT_BUILDER_FACTORY_KEY , DOCUMENT_BUILDER_FACTORY_VALUE ) ; final DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; factory . setValidating ( true ) ; factory . setAttribute ( SCHEMA_LANGUAGE_KEY , HTTP_WWW_W3_ORG_2001_XML_SCHEMA ) ; factory . setAttribute ( SCHEMA_SOURCE_KEY , SchemaUrl ) ; final DocumentBuilder builder = factory . newDocumentBuilder ( ) ; final ValidatorHandler handler = new ValidatorHandler ( ) ; builder . setErrorHandler ( handler ) ; builder . parse ( XmlDocumentUrl ) ; if ( handler . isValid ( ) ) { return false ; } return true ; }

Validate given xml schema.

@param SchemaUrl
the schema url
@param XmlDocumentUrl
the xml document url
@return true if the given xml is valid otherwise false
@throws SAXException
If a SAX error occurs during parsing.
@throws ParserConfigurationException
if a DocumentBuilder cannot be created which satisfies the configuration
requested.
@throws IOException
Signals that an I/O exception has occurred.


public boolean addChild(final SimpleTag child)
	{
		if (getChildren() == null)
		{
			setChildren(ListFactory.newArrayList());
		}
		return getChildren().add(child);
	}

public boolean addChild ( final SimpleTag child ) { if ( getChildren ( ) == null ) { setChildren ( ListFactory . newArrayList ( ) ) ; } return getChildren ( ) . add ( child ) ; }

Adds the given child.

@param child
the child
@return true, if successful


public String removeAttribute(final String name)
	{
		if (getAttributes() != null)
		{
			getAttributes().remove(name);
		}
		return null;
	}

public String removeAttribute ( final String name ) { if ( getAttributes ( ) != null ) { getAttributes ( ) . remove ( name ) ; } return null ; }

Removes the attribute with the given name.

@param name
the name
@return the string

Removes the attribute with the given name .


public StringBuilder toVelocityTemplate()
	{
		final StringBuilder buffer = new StringBuilder();
		buffer.append("<");
		buffer.append("${").append(getName()).append(".name}\n");
		if (getAttributes() != null && !getAttributes().isEmpty())
		{
			buffer.append(" #foreach(" + "$attribute in $").append(getName())
				.append(".attributes.keySet()" + ")\n");
			buffer.append("$attribute=\"$").append(getName())
				.append(".getAttributes().get($attribute)\"\n");
			buffer.append(" #end\n");
		}
		buffer.append("#if(${").append(getName()).append(".endTag})>${").append(getName())
			.append(".content}\n");
		if (getChildren() != null && !getChildren().isEmpty())
		{
			buffer.append("#foreach($").append(getChildren().get(0).getName()).append(" in $")
				.append(getName()).append(".children)\n");
			for (final SimpleTag child : getChildren())
			{
				buffer.append(child.toVelocityTemplate().toString());
			}
			buffer.append("#end\n");
		}
		buffer.append("</${").append(getName()).append(".name}>\n");
		buffer.append("#else />\n" + "#end\n");
		return buffer;
	}

public
StringBuilder
toVelocityTemplate
(
)
{
final
StringBuilder
buffer
=
new
StringBuilder
(
)
;
buffer
.
append
(
"<"
)
;
buffer
.
append
(
"${"
)
.
append
(
getName
(
)
)
.
append
(
".name}\n"
)
;
if
(
getAttributes
(
)
!=
&&
!
getAttributes
(
)
.
isEmpty
(
)
)
{
buffer
.
append
(
" #foreach("
+
"$attribute in $"
)
.
append
(
getName
(
)
)
.
append
(
".attributes.keySet()"
+
")\n"
)
;
buffer
.
append
(
"$attribute=\"$"
)
.
append
(
getName
(
)
)
.
append
(
".getAttributes().get($attribute)\"\n"
)
;
buffer
.
append
(
" #end\n"
)
;
}
buffer
.
append
(
"#if(${"
)
.
append
(
getName
(
)
)
.
append
(
".endTag})>${"
)
.
append
(
getName
(
)
)
.
append
(
".content}\n"
)
;
if
(
getChildren
(
)
!=
&&
!
getChildren
(
)
.
isEmpty
(
)
)
{
buffer
.
append
(
"#foreach($"
)
.
append
(
getChildren
(
)
.
get
(
0
)
.
getName
(
)
)
.
append
(
" in $"
)
.
append
(
getName
(
)
)
.
append
(
".children)\n"
)
;
for
(
final
SimpleTag
child
:
getChildren
(
)
)
{
buffer
.
append
(
child
.
toVelocityTemplate
(
)
.
toString
(
)
)
;
}
buffer
.
append
(
"#end\n"
)
;
}
buffer
.
append
(
"</${"
)
.
append
(
getName
(
)
)
.
append
(
".name}>\n"
)
;
buffer
.
append
(
"#else />\n"
+
"#end\n"
)
;
return
buffer
;
}

Creates from this Tag object an velocity template as String object. It puts children Tag
object in the template recursively.

@return the string buffer

Creates from this Tag object an velocity template as String object . It puts children Tag object in the template recursively .


public String toXmlString()
	{
		final StringBuilder buffer = new StringBuilder();
		buffer.append("<");
		buffer.append(getName());
		Optional<String> attr = TagExtensions.attributesToString(getAttributes());
		if (attr.isPresent())
		{
			buffer.append(attr.get());
		}
		if (isEndTag())
		{
			buffer.append(">");
			buffer.append(getContent());
			if (getChildren() != null && !getChildren().isEmpty())
			{
				for (final SimpleTag child : getChildren())
				{
					buffer.append(child.toXmlString());
				}
			}
			buffer.append("</");
			buffer.append(getName());
			buffer.append(">");
		}
		else
		{
			buffer.append("/>");
		}
		return buffer.toString();
	}

public String toXmlString ( ) { final StringBuilder buffer = new StringBuilder ( ) ; buffer . append ( "<" ) ; buffer . append ( getName ( ) ) ; Optional < String > attr = TagExtensions . attributesToString ( getAttributes ( ) ) ; if ( attr . isPresent ( ) ) { buffer . append ( attr . get ( ) ) ; } if ( isEndTag ( ) ) { buffer . append ( ">" ) ; buffer . append ( getContent ( ) ) ; if ( getChildren ( ) != null && ! getChildren ( ) . isEmpty ( ) ) { for ( final SimpleTag child : getChildren ( ) ) { buffer . append ( child . toXmlString ( ) ) ; } } buffer . append ( "</" ) ; buffer . append ( getName ( ) ) ; buffer . append ( ">" ) ; } else { buffer . append ( "/>" ) ; } return buffer . toString ( ) ; }

Creates from this Tag object an xml string.

@return the string

Creates from this Tag object an xml string .


public void addServiceIfNotPresent(WiFiP2pService service) {
        WfdLog.d(TAG, "addServiceIfNotPresent BEGIN, with size = " + serviceList.size());

        if (service == null) {
            WfdLog.e(TAG, "Service is null, returning...");
            return;
        }

        boolean add = true;
        for (WiFiP2pService element : serviceList) {
            if (element != null
                    && element.getDevice().equals(service.getDevice())
                    && element.getInstanceName().equals(service.getInstanceName())) {
                add = false; //already in the list
            }
        }

        if (add) {
            serviceList.add(service);
        }

        WfdLog.d(TAG, "addServiceIfNotPresent END, with size = " + serviceList.size());
    }

Method to add a service inside the list in a secure way.
The service is added only if isn't already inside the list.

@param service {@link WiFiP2pService} to add.

Method to add a service inside the list in a secure way . The service is added only if isn t already inside the list .


public WiFiP2pService getServiceByDevice(WifiP2pDevice device) {
        if (device == null) {
            return null;
        }

        WfdLog.d(TAG, "groupownerdevice passed to getServiceByDevice: " + device.deviceName + ", " + device.deviceAddress);

        WfdLog.d(TAG, "servicelist size: " + serviceList.size());

        for (WiFiP2pService element : serviceList) {
            WfdLog.d(TAG, "element in list: " + element.getDevice().deviceName + ", " + element.getDevice().deviceAddress);
            WfdLog.d(TAG, "element passed : " + device.deviceName + ", " + device.deviceAddress);

            if (element.getDevice().deviceAddress.equals(device.deviceAddress)) {
                WfdLog.d(TAG, "getServiceByDevice if satisfied : " + device.deviceAddress + ", " + element.getDevice().deviceAddress);
                return element;
            }
        }

        WfdLog.d(TAG, "servicelist size: " + serviceList.size());

        return null;
    }

Method to get a service from the list, using only the device.
This method use only the deviceAddress, not the device name, because sometimes Android doesn't
get the name, but only the mac address.

@param device WifiP2pDevice that you want to use to search the service.
@return The WiFiP2pService associated to the device or null, if the device isn't in the list.

Method to get a service from the list using only the device . This method use only the deviceAddress not the device name because sometimes Android doesn t get the name but only the mac address .


@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) {
            return START_STICKY;
        }

        String action = intent.getAction();

        if (ACTION_START_FOREGROUND.equals(action)) {
            if (!SPF.get().isConnected()) {
                SPF.get().connect();
            }
            SPF.get().notifyProximityStatus(false); //false because it's starting

            startInForeground();
            Log.d(TAG, "Started in foreground");
        } else if (ACTION_STOP_FOREGROUND.equals(action)) {

            //notify to the middleware that i killed the proximity service
            SPF.get().notifyProximityStatus(true); //true because it's killing

            stopForeground(true);
            mIsStartedForeground = false;
            Log.d(TAG, "Foreground stopped");
        }

        return START_STICKY;
    }

Triggered by the front end to keep spf service active in foreground


List<SPFTrigger> getAllTriggers(String appIdentifier) {
		String where = Contract.COLUMN_APP_IDENTIFIER + " = ?";
		String[] whereArgs = { appIdentifier };
		Cursor c = getReadableDatabase().query(Contract.TABLE_NAME, null, where, whereArgs, null, null, null);
		List<SPFTrigger> triggers = new ArrayList<SPFTrigger>();

		while (c.moveToNext()) {
			triggers.add(triggerFromCursor(c));
		}

		c.close();
		return triggers;
	}

List
<
SPFTrigger
>
getAllTriggers
(
String
appIdentifier
)
{
String
where
=
Contract
.
COLUMN_APP_IDENTIFIER
+
" = ?"
;
String
[
]
whereArgs
=
{
appIdentifier
}
;
Cursor
c
=
getReadableDatabase
(
)
.
query
(
Contract
.
TABLE_NAME
,
,
where
,
whereArgs
,
,
,
)
;
List
<
SPFTrigger
>
triggers
=
new
ArrayList
<
SPFTrigger
>
(
)
;
while
(
c
.
moveToNext
(
)
)
{
triggers
.
add
(
triggerFromCursor
(
c
)
)
;
}
c
.
close
(
)
;
return
triggers
;
}

Return all the triggers of the specified application

@param appIdentifier
- the identifier of the application
@return a list of {@link SPFTrigger}


boolean deleteAllTriggerOf(String appPackageName) {
		String where = Contract.COLUMN_APP_IDENTIFIER + " = ?";
		String[] whereArgs = { appPackageName };
		int c = getReadableDatabase().delete(Contract.TABLE_NAME, where, whereArgs);
		return c > 0;
	}

boolean
deleteAllTriggerOf
(
String
appPackageName
)
{
String
where
=
Contract
.
COLUMN_APP_IDENTIFIER
+
" = ?"
;
String
[
]
whereArgs
=
{
appPackageName
}
;
int
c
=
getReadableDatabase
(
)
.
delete
(
Contract
.
TABLE_NAME
,
where
,
whereArgs
)
;
return
c
>
0
;
}

Delete all the triggers registered with the given application identifier.

@param appPackageName
@return true if there is at least one row deleted

Delete all the triggers registered with the given application identifier .


boolean deleteTrigger(long id, String appPackageName) {
		String where = Contract.COLUMN_APP_IDENTIFIER + " = ? AND " + Contract._ID + " = ?";
		String[] whereArgs = { appPackageName, Long.toString(id) };
		int count = getReadableDatabase().delete(Contract.TABLE_NAME, where, whereArgs);
		return count > 0;

	}

boolean
deleteTrigger
(
long
id
,
String
appPackageName
)
{
String
where
=
Contract
.
COLUMN_APP_IDENTIFIER
+
" = ? AND "
+
Contract
.
_ID
+
" = ?"
;
String
[
]
whereArgs
=
{
appPackageName
,
Long
.
toString
(
id
)
}
;
int
count
=
getReadableDatabase
(
)
.
delete
(
Contract
.
TABLE_NAME
,
where
,
whereArgs
)
;
return
count
>
0
;
}

Delete the trigger with the given id.

@param id
@param appPackageName
@return true if there is a deletion


SPFTrigger getTrigger(long triggerId, String appPackageName) {
		String where = Contract._ID + " = ? AND " + Contract.COLUMN_APP_IDENTIFIER + " = ?";
		String[] whereArgs = { Long.toString(triggerId), appPackageName };
		Cursor c = getReadableDatabase().query(Contract.TABLE_NAME, null, where, whereArgs, null, null, null);
		if (!c.moveToFirst()) {
			return null;
		}
		SPFTrigger t = triggerFromCursor(c);
		c.close();
		return t;
	}

SPFTrigger
getTrigger
(
long
triggerId
,
String
appPackageName
)
{
String
where
=
Contract
.
_ID
+
" = ? AND "
+
Contract
.
COLUMN_APP_IDENTIFIER
+
" = ?"
;
String
[
]
whereArgs
=
{
Long
.
toString
(
triggerId
)
,
appPackageName
}
;
Cursor
c
=
getReadableDatabase
(
)
.
query
(
Contract
.
TABLE_NAME
,
,
where
,
whereArgs
,
,
,
)
;
if
(
!
c
.
moveToFirst
(
)
)
{
return
;
}
SPFTrigger
t
=
triggerFromCursor
(
c
)
;
c
.
close
(
)
;
return
t
;
}

Return the trigger with the specified id.

@param triggerId
@param appPackageName
@return

Return the trigger with the specified id .


public AppAuth validateAccess(String accessToken, Permission permission) throws TokenNotValidException, PermissionDeniedException {
		AppAuth appAuth;
		if (accessToken == null) {
			throw new TokenNotValidException();
		}

		appAuth = mAppRegistry.getAppAuthorization(accessToken);

		if ((appAuth.getPermissionCode() & permission.getCode()) == 0) {
			throw new PermissionDeniedException();
		}

		return appAuth;
	}

public AppAuth validateAccess ( String accessToken , Permission permission ) throws TokenNotValidException , PermissionDeniedException { AppAuth appAuth ; if ( accessToken == null ) { throw new TokenNotValidException ( ) ; } appAuth = mAppRegistry . getAppAuthorization ( accessToken ) ; if ( ( appAuth . getPermissionCode ( ) & permission . getCode ( ) ) == 0 ) { throw new PermissionDeniedException ( ) ; } return appAuth ; }


public static <T> T toObjectWithXStream(final String xmlString,
		final Map<String, Class<?>> aliases)
	{
		return toObjectWithXStream(null, xmlString, aliases);
	}

public static < T > T toObjectWithXStream ( final String xmlString , final Map < String , Class < ? > > aliases ) { return toObjectWithXStream ( null , xmlString , aliases ) ; }

Creates from the given xml string an Object. The given map hold the aliases. For more
information with aliasing see documation of xstream.

@param <T>
the generic type of the return type
@param xmlString
the xml as string object
@param aliases
the aliases
@return the created object from the given xml string.

Creates from the given xml string an Object . The given map hold the aliases . For more information with aliasing see documation of xstream .


@SuppressWarnings("unchecked")
	public static <T> T toObjectWithXStream(XStream xstream, final String xmlString,
		final Map<String, Class<?>> aliases)
	{
		if (xstream == null)
		{
			xstream = new XStream();
		}
		if (aliases != null)
		{
			for (final Map.Entry<String, Class<?>> alias : aliases.entrySet())
			{
				xstream.alias(alias.getKey(), alias.getValue());
			}
		}
		return (T)xstream.fromXML(xmlString);
	}

@ SuppressWarnings ( "unchecked" ) public static < T > T toObjectWithXStream ( XStream xstream , final String xmlString , final Map < String , Class < ? > > aliases ) { if ( xstream == null ) { xstream = new XStream ( ) ; } if ( aliases != null ) { for ( final Map . Entry < String , Class < ? > > alias : aliases . entrySet ( ) ) { xstream . alias ( alias . getKey ( ) , alias . getValue ( ) ) ; } } return ( T ) xstream . fromXML ( xmlString ) ; }

Creates from the given xml string an java object. The given map hold the aliases. For more
information with aliasing see documation of xstream.

@param <T>
the generic type of the return type
@param xstream
the xstream object.
@param xmlString
the xml
@param aliases
the aliases
@return the object

Creates from the given xml string an java object . The given map hold the aliases . For more information with aliasing see documation of xstream .


public static String toJson(final String xmlString, final Map<String, Class<?>> aliases)
	{
		final Object object = XmlToObjectExtensions.toObjectWithXStream(xmlString);
		final XStream xstream = new XStream(new JettisonMappedXmlDriver());
		if (aliases != null)
		{
			for (final Map.Entry<String, Class<?>> alias : aliases.entrySet())
			{
				xstream.alias(alias.getKey(), alias.getValue());
			}
		}
		final String json = xstream.toXML(object);
		return json;
	}

public static String toJson ( final String xmlString , final Map < String , Class < ? > > aliases ) { final Object object = XmlToObjectExtensions . toObjectWithXStream ( xmlString ) ; final XStream xstream = new XStream ( new JettisonMappedXmlDriver ( ) ) ; if ( aliases != null ) { for ( final Map . Entry < String , Class < ? > > alias : aliases . entrySet ( ) ) { xstream . alias ( alias . getKey ( ) , alias . getValue ( ) ) ; } } final String json = xstream . toXML ( object ) ; return json ; }

Creates from the given xml string a json string.

@param xmlString
the xml as string object
@param aliases
the aliases
@return the json string.

Creates from the given xml string a json string .


public Object invokeMethod(String methodName, Object[] args, Type retType) throws ServiceInvocationException {
		checkCurrentThread(methodName);
		Utils.notNull(methodName);
		Utils.notNull(args);

		// Let the target prepare the arguments if needed
		mInvocationTarget.prepareArguments(args);

		// Serialize arguments
		String payload = GsonHelper.gson.toJson(args);
		InvocationRequest request = new InvocationRequest(mServiceDescriptor.getAppIdentifier(), mServiceDescriptor.getServiceName(), methodName, payload);

		// Let the target perform the execution
		InvocationResponse response = mInvocationTarget.executeService(request);

		// Analyze the response
		if (!response.isResult()) {
			throw new ServiceInvocationException(response.getErrorMessage());
		} else if (retType.equals(void.class)) {
			return null;
		} else {
			return GsonHelper.gson.fromJson(response.getPayload(), retType);
		}
	}

Invokes a remote service providing the name of the method to invoke name
and the list of parameters. The invocation is a blocking network request
and thus should not be performed on the main thread.

@param methodName
- the name of the method to invoke.
@param args
- the array of the parameters to pass to the method.
@return the return value of the method, if any, or null if the method
returns void.
@throws ServiceInvocationException
if an invocation is thrown during the execution of the
service.

Invokes a remote service providing the name of the method to invoke name and the list of parameters . The invocation is a blocking network request and thus should not be performed on the main thread .


private void checkCurrentThread(String methodName) {
		if (Looper.myLooper() == Looper.getMainLooper()) {
			Log.w(TAG, String.format(WRONG_THREAD_MSG, mServiceDescriptor.getServiceName(), methodName));
		}
	}

private void checkCurrentThread ( String methodName ) { if ( Looper . myLooper ( ) == Looper . getMainLooper ( ) ) { Log . w ( TAG , String . format ( WRONG_THREAD_MSG , mServiceDescriptor . getServiceName ( ) , methodName ) ) ; } }

Checks if the current thread is the main thread, if so it logs a wrning.

Checks if the current thread is the main thread if so it logs a wrning .


public static void logCall(String tag, String methodName, Object... args) {
		if (SPFConfig.DEBUG) {
			Log.d(tag, "method call: " + methodName + "(" + (args != null ? TextUtils.join(",", args) : "") + ")");
		}
	}

public
static
void
logCall
(
String
tag
,
String
methodName
,
Object
...
args
)
{
if
(
SPFConfig
.
DEBUG
)
{
Log
.
d
(
tag
,
"method call: "
+
methodName
+
"("
+
(
args
!=
TextUtils
.
join
(
","
,
args
)
:
""
)
+
")"
)
;
}
}

Helper to log a call to a method

@param tag
- the tag
@param methodName
- the name of the method
@param args
- the method args


private static <T> T loadObject(final InputStream is) throws IOException
	{
		final String xmlString = ReadFileExtensions.inputStream2String(is);
		final T object = XmlToObjectExtensions.toObjectWithXStream(xmlString);
		return object;
	}

private static < T > T loadObject ( final InputStream is ) throws IOException { final String xmlString = ReadFileExtensions . inputStream2String ( is ) ; final T object = XmlToObjectExtensions . toObjectWithXStream ( xmlString ) ; return object ; }

Load from the given input stream that should represent an xml file and transform it to the
generic type object.

@param <T>
the generic type
@param is
the input stream
@return the object from the given input stream.
@throws IOException
Signals that an I/O exception has occurred.

Load from the given input stream that should represent an xml file and transform it to the generic type object .


public static String newTag(final String tagname, final String value,
		final Map<String, String> attributes)
	{
		final StringBuilder xmlTag = new StringBuilder();
		xmlTag.append("<").append(tagname);
		if (attributes != null && !attributes.isEmpty())
		{
			xmlTag.append(" ");
			int count = 1;
			for (final Map.Entry<String, String> attributte : attributes.entrySet())
			{
				xmlTag.append(attributte.getKey());
				xmlTag.append("=");
				xmlTag.append("\"").append(attributte.getValue()).append("\"");
				if (count != attributes.size())
				{
					xmlTag.append(" ");
				}
				count++;
			}
		}
		xmlTag.append(">");
		xmlTag.append(value);
		xmlTag.append("</").append(tagname).append(">");
		return xmlTag.toString();
	}

public
static
String
newTag
(
final
String
tagname
,
final
String
value
,
final
Map
<
String
,
String
>
attributes
)
{
final
StringBuilder
xmlTag
=
new
StringBuilder
(
)
;
xmlTag
.
append
(
"<"
)
.
append
(
tagname
)
;
if
(
attributes
!=
&&
!
attributes
.
isEmpty
(
)
)
{
xmlTag
.
append
(
" "
)
;
int
count
=
1
;
for
(
final
Map
.
Entry
<
String
,
String
>
attributte
:
attributes
.
entrySet
(
)
)
{
xmlTag
.
append
(
attributte
.
getKey
(
)
)
;
xmlTag
.
append
(
"="
)
;
xmlTag
.
append
(
"\""
)
.
append
(
attributte
.
getValue
(
)
)
.
append
(
"\""
)
;
if
(
count
!=
attributes
.
size
(
)
)
{
xmlTag
.
append
(
" "
)
;
}
count
++
;
}
}
xmlTag
.
append
(
">"
)
;
xmlTag
.
append
(
value
)
;
xmlTag
.
append
(
"</"
)
.
append
(
tagname
)
.
append
(
">"
)
;
return
xmlTag
.
toString
(
)
;
}

Creates a tag from the given string values. Can be used for creating html or xml tags.

@param tagname
the tag name
@param value
the value from the tag
@param attributes
a map with the attributes
@return the string

Creates a tag from the given string values . Can be used for creating html or xml tags .


public boolean matches(String queryJSON) {
		QueryContainer queryContainer;
		try {
			queryContainer = QueryContainer.fromJSON(queryJSON);
		} catch (JSONException e) {
			return false;
		}

		SPFQuery query = queryContainer.getQuery();
		String callerApp = queryContainer.getCallerAppId();
		String userUID = queryContainer.getUserUID();
		return analyzeWith(query, callerApp, userUID);
	}

public boolean matches ( String queryJSON ) { QueryContainer queryContainer ; try { queryContainer = QueryContainer . fromJSON ( queryJSON ) ; } catch ( JSONException e ) { return false ; } SPFQuery query = queryContainer . getQuery ( ) ; String callerApp = queryContainer . getCallerAppId ( ) ; String userUID = queryContainer . getUserUID ( ) ; return analyzeWith ( query , callerApp , userUID ) ; }

Verifies if the local profile matches the given query.

@see Query
@param q
@return

Verifies if the local profile matches the given query .


public InvocationResponse dispatchInvocation(InvocationRequest request) {
		String appName = request.getAppName();
		String serviceName = request.getServiceName();
		String componentName = mServiceTable.getComponentForService(appName, serviceName);

		if (componentName == null) {
			return InvocationResponse.error("Application " + appName + " doesn't have a service named " + serviceName);
		}

		AppServiceProxy proxy = mCommunicationAgent.getProxy(componentName);
		if (proxy == null) {
			return InvocationResponse.error("Cannot bind to service");
		}

		try {
			return proxy.executeService(request);
		} catch (Throwable t) {
			Log.e("ServiceRegistry", "Error dispatching invocation: ", t);
			return InvocationResponse.error("Internal error: " + t.getMessage());
		}
	}

public
InvocationResponse
dispatchInvocation
(
InvocationRequest
request
)
{
String
appName
=
request
.
getAppName
(
)
;
String
serviceName
=
request
.
getServiceName
(
)
;
String
componentName
=
mServiceTable
.
getComponentForService
(
appName
,
serviceName
)
;
if
(
componentName
==
)
{
return
InvocationResponse
.
error
(
"Application "
+
appName
+
" doesn't have a service named "
+
serviceName
)
;
}
AppServiceProxy
proxy
=
mCommunicationAgent
.
getProxy
(
componentName
)
;
if
(
proxy
==
)
{
return
InvocationResponse
.
error
(
"Cannot bind to service"
)
;
}
try
{
return
proxy
.
executeService
(
request
)
;
}
catch
(
Throwable
t
)
{
Log
.
e
(
"ServiceRegistry"
,
"Error dispatching invocation: "
,
t
)
;
return
InvocationResponse
.
error
(
"Internal error: "
+
t
.
getMessage
(
)
)
;
}
}

Dispatches an invocation request to the right application. If the
application is not found, an error response is returned.

@param request
@return

Dispatches an invocation request to the right application . If the application is not found an error response is returned .


public <T> void unregisterService(Class<? super T> serviceInterface) {
		Utils.notNull(serviceInterface, "serviceInterface must not be null");
		ServiceValidator.validateInterface(serviceInterface, ServiceValidator.TYPE_PUBLISHED);
		ServiceInterface svcInterface = serviceInterface.getAnnotation(ServiceInterface.class);
		SPFServiceDescriptor svcDesc = ServiceInterface.Convert.toServiceDescriptor(svcInterface);
		String token = getAccessToken();

		try {
			SPFError error = new SPFError();
			getService().unregisterService(token, svcDesc, error);
			if (!error.isOk()) {
				handleError(error);
			}
		} catch (RemoteException e) {
			catchRemoteException(e);
		}
	}

public
<
T
>
void
unregisterService
(
Class
<
super
T
>
serviceInterface
)
{
Utils
.
notNull
(
serviceInterface
,
"serviceInterface must not be null"
)
;
ServiceValidator
.
validateInterface
(
serviceInterface
,
ServiceValidator
.
TYPE_PUBLISHED
)
;
ServiceInterface
svcInterface
=
serviceInterface
.
getAnnotation
(
ServiceInterface
.
class
)
;
SPFServiceDescriptor
svcDesc
=
ServiceInterface
.
Convert
.
toServiceDescriptor
(
svcInterface
)
;
String
token
=
getAccessToken
(
)
;
try
{
SPFError
error
=
new
SPFError
(
)
;
getService
(
)
.
unregisterService
(
token
,
svcDesc
,
error
)
;
if
(
!
error
.
isOk
(
)
)
{
handleError
(
error
)
;
}
}
catch
(
RemoteException
e
)
{
catchRemoteException
(
e
)
;
}
}

Allows to unregister a previously registered service.

@param serviceInterface

Allows to unregister a previously registered service .


private String generateQueryId(QueryInfo queryInfo) {
		String queryId = SPF.get().getUniqueIdentifier() + (++id);
		queryInfo.setQueryId(queryId);
		return queryId;
	}

private String generateQueryId ( QueryInfo queryInfo ) { String queryId = SPF . get ( ) . getUniqueIdentifier ( ) + ( ++ id ) ; queryInfo . setQueryId ( queryId ) ; return queryId ; }

Generate a query id for the specified query. The query id is assigned to
the query descriptor.

@param queryInfo
@return the query id

Generate a query id for the specified query . The query id is assigned to the query descriptor .


void onInstanceLost(String uniqueIdentifier) {
		log(TAG, "instance lost " + uniqueIdentifier);
		List<String> queriesIds = results.get(uniqueIdentifier);
		if (queriesIds == null) {
			return;
		}
		for (String queryId : queriesIds) {
			String[] args = new String[2];
			args[0] = queryId;
			args[1] = uniqueIdentifier;
			Message msg = handler.obtainMessage(SearchMessages.RESULT_LOST,
					args);
			log(TAG, "sending message RESULT_LOST to handler for queryId: "
					+ queryId);
			handler.sendMessage(msg);
		}
	}

Call this method when the middleware notify that a spf instance is lost.
It will notify the event to all the active searches that have the lost
instance in their results.

@param uniqueIdentifier
the identifier of the lost instance

Call this method when the middleware notify that a spf instance is lost . It will notify the event to all the active searches that have the lost instance in their results .


void stopSearch(String queryId) {
		QueryInfo info = queries.get(queryId);
		if(info !=  null){
			stopSearch(info);
		}
	}

void stopSearch ( String queryId ) { QueryInfo info = queries . get ( queryId ) ; if ( info != null ) { stopSearch ( info ) ; } }

Call this method to stop the search and release the associated resources.
The application will not be notified about the event;

@param qd
@return

Call this method to stop the search and release the associated resources . The application will not be notified about the event ;


void stopAllSearches(String appIdentifier) {
		List<QueryInfo> qinfos;
		synchronized (queries) {
			qinfos = new ArrayList<QueryInfo>(queries.values());
		}
		for (QueryInfo queryInfo : qinfos) {
			if (queryInfo.getAppName().equals(appIdentifier)) {
				stopSearch(queryInfo);
			}
		}

	}

void stopAllSearches ( String appIdentifier ) { List < QueryInfo > qinfos ; synchronized ( queries ) { qinfos = new ArrayList < QueryInfo > ( queries . values ( ) ) ; } for ( QueryInfo queryInfo : qinfos ) { if ( queryInfo . getAppName ( ) . equals ( appIdentifier ) ) { stopSearch ( queryInfo ) ; } } }

Unregister all the active queries associated with the given
appIdentifier. Application will not be notified about the event.

Unregister all the active queries associated with the given appIdentifier . Application will not be notified about the event .


public static void connect(final Context context, final ConnectionListener listener) {
		Component.load(context, DESCRIPTOR, asBase(listener));
	}

public static void connect ( final Context context , final ConnectionListener listener ) { Component . load ( context , DESCRIPTOR , asBase ( listener ) ) ; }

Creates a connection to SPF asynchronously.

@param context
- the context used to bind to SPF service.
@param listener
- the listener that is notified when the connection to SPF is
ready, when the connection is closed or when an error occurs.

Creates a connection to SPF asynchronously .


private <E> View createStandardDisplayView(ProfileField<E> field, E currentValue, ViewGroup viewContainer) {
		View result = mInflater.inflate(R.layout.profileview_field_listelement, viewContainer, false);

		String friendlyFieldName = mHelper.getFriendlyNameOfField(field);
		((TextView) result.findViewById(R.id.profile_field_key)).setText(friendlyFieldName);

		String fieldValue = mHelper.convertToFriendlyString(field, currentValue);
		((TextView) result.findViewById(R.id.profile_field_value)).setText(fieldValue);

		setUpCircleView(result, field, null);
		return result;
	}

private < E > View createStandardDisplayView ( ProfileField < E > field , E currentValue , ViewGroup viewContainer ) { View result = mInflater . inflate ( R . layout . profileview_field_listelement , viewContainer , false ) ; String friendlyFieldName = mHelper . getFriendlyNameOfField ( field ) ; ( ( TextView ) result . findViewById ( R . id . profile_field_key ) ) . setText ( friendlyFieldName ) ; String fieldValue = mHelper . convertToFriendlyString ( field , currentValue ) ; ( ( TextView ) result . findViewById ( R . id . profile_field_value ) ) . setText ( fieldValue ) ; setUpCircleView ( result , field , null ) ; return result ; }

Standard display view for all profile fields except tags


private <E> View createSpinner(MultipleChoicheProfileField<E> field, E currentValue, FieldValueListener<E> listener, ViewGroup container) {
		View result = mInflater.inflate(R.layout.profileedit_field_multiplechoiche, container, false);

		String friendlyName = mHelper.getFriendlyNameOfField(field);
		((TextView) result.findViewById(R.id.profileedit_field_identifier)).setText(friendlyName);

		Spinner spinner = (Spinner) result.findViewById(R.id.profileedit_field_multiple_value);
		ArrayAdapter<E> adapter = new ArrayAdapter<E>(mContext, android.R.layout.simple_list_item_1, field.getChoiches());
		spinner.setAdapter(adapter);

		int index = indexOf(field.getChoiches(), currentValue);
		if (index >= 0) {
			spinner.setSelection(index, false);
		}

		spinner.setOnItemSelectedListener(new OnItemSelectedAdapter<E>(field, listener, adapter));
		setUpCircleView(result, field, listener);
		return result;
	}

private < E > View createSpinner ( MultipleChoicheProfileField < E > field , E currentValue , FieldValueListener < E > listener , ViewGroup container ) { View result = mInflater . inflate ( R . layout . profileedit_field_multiplechoiche , container , false ) ; String friendlyName = mHelper . getFriendlyNameOfField ( field ) ; ( ( TextView ) result . findViewById ( R . id . profileedit_field_identifier ) ) . setText ( friendlyName ) ; Spinner spinner = ( Spinner ) result . findViewById ( R . id . profileedit_field_multiple_value ) ; ArrayAdapter < E > adapter = new ArrayAdapter < E > ( mContext , android . R . layout . simple_list_item_1 , field . getChoiches ( ) ) ; spinner . setAdapter ( adapter ) ; int index = indexOf ( field . getChoiches ( ) , currentValue ) ; if ( index >= 0 ) { spinner . setSelection ( index , false ) ; } spinner . setOnItemSelectedListener ( new OnItemSelectedAdapter < E > ( field , listener , adapter ) ) ; setUpCircleView ( result , field , listener ) ; return result ; }


@SuppressWarnings("unchecked")
	private <E> View createDateView(final DateProfileField field, Date currentValue, final FieldValueListener<Date> listener, ViewGroup container) {
		View result = mInflater.inflate(R.layout.profileedit_field_date, container, false);
		String friendlyName = mHelper.getFriendlyNameOfField(field);
		((TextView) result.findViewById(R.id.profileedit_field_identifier)).setText(friendlyName);

		String dateToShow;
		if (currentValue == null) {
			dateToShow = "Click to edit";
		} else {
			dateToShow = mHelper.convertToFriendlyString(field, currentValue);
		}
		final TextView dateTextView = (TextView) result.findViewById(R.id.profileedit_field_date_text);
		dateTextView.setText(dateToShow);
		dateTextView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Calendar today = GregorianCalendar.getInstance();
				int year = today.get(Calendar.YEAR);
				int monthOfYear = today.get(Calendar.MONTH);
				int dayOfMonth = today.get(Calendar.DAY_OF_MONTH);
				OnDateSetListener callBack = new OnDateSetListener() {
					@Override
					public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
						GregorianCalendar cal = new GregorianCalendar(year, monthOfYear, dayOfMonth);
						Date newDate = new Date(cal.getTimeInMillis());
						String newDateString = mHelper.convertToFriendlyString(field, newDate);
						dateTextView.setText(newDateString);
						listener.onFieldValueChanged(field, newDate);
					}
				};
				DatePickerDialog dialog = new DatePickerDialog(mContext, callBack, year, monthOfYear, dayOfMonth);
				dialog.show();
			}
		});

		setUpCircleView(result, (ProfileField<E>) field, (FieldValueListener<E>) listener);

		return result;
	}

@
SuppressWarnings
(
"unchecked"
)
private
<
E
>
View
createDateView
(
final
DateProfileField
field
,
Date
currentValue
,
final
FieldValueListener
<
Date
>
listener
,
ViewGroup
container
)
{
View
result
=
mInflater
.
inflate
(
R
.
layout
.
profileedit_field_date
,
container
,
false
)
;
String
friendlyName
=
mHelper
.
getFriendlyNameOfField
(
field
)
;
(
(
TextView
)
result
.
findViewById
(
R
.
id
.
profileedit_field_identifier
)
)
.
setText
(
friendlyName
)
;
String
dateToShow
;
if
(
currentValue
==
)
{
dateToShow
=
"Click to edit"
;
}
else
{
dateToShow
=
mHelper
.
convertToFriendlyString
(
field
,
currentValue
)
;
}
final
TextView
dateTextView
=
(
TextView
)
result
.
findViewById
(
R
.
id
.
profileedit_field_date_text
)
;
dateTextView
.
setText
(
dateToShow
)
;
dateTextView
.
setOnClickListener
(
new
View
.
OnClickListener
(
)
{
@
Override
public
void
onClick
(
View
v
)
{
Calendar
today
=
GregorianCalendar
.
getInstance
(
)
;
int
year
=
today
.
get
(
Calendar
.
YEAR
)
;
int
monthOfYear
=
today
.
get
(
Calendar
.
MONTH
)
;
int
dayOfMonth
=
today
.
get
(
Calendar
.
DAY_OF_MONTH
)
;
OnDateSetListener
callBack
=
new
OnDateSetListener
(
)
{
@
Override
public
void
onDateSet
(
DatePicker
view
,
int
year
,
int
monthOfYear
,
int
dayOfMonth
)
{
GregorianCalendar
cal
=
new
GregorianCalendar
(
year
,
monthOfYear
,
dayOfMonth
)
;
Date
newDate
=
new
Date
(
cal
.
getTimeInMillis
(
)
)
;
String
newDateString
=
mHelper
.
convertToFriendlyString
(
field
,
newDate
)
;
dateTextView
.
setText
(
newDateString
)
;
listener
.
onFieldValueChanged
(
field
,
newDate
)
;
}
}
;
DatePickerDialog
dialog
=
new
DatePickerDialog
(
mContext
,
callBack
,
year
,
monthOfYear
,
dayOfMonth
)
;
dialog
.
show
(
)
;
}
}
)
;
setUpCircleView
(
result
,
(
ProfileField
<
E
>
)
field
,
(
FieldValueListener
<
E
>
)
listener
)
;
return
result
;
}


@SuppressWarnings("unchecked")
	private <E> View createTagView(TagProfileField field, String[] currentValue, FieldValueListener<E> listener, ViewGroup container, boolean editable) {
		View result = mInflater.inflate(editable ? R.layout.profileedit_field_tag : R.layout.profileview_tag_field, container, false);

		String friendlyName = mHelper.getFriendlyNameOfField(field);
		((TextView) result.findViewById(R.id.profileedit_field_identifier)).setText(friendlyName);

		TagsPicker picker = (TagsPicker) result.findViewById(R.id.profileedit_tags_picker);
		picker.setEditable(editable);

		if (currentValue != null) {
			picker.setInitialTags(Arrays.asList(currentValue));
		}
		if (editable) {
			picker.setChangeListener(new OnChangeListenerAdapter(field, (FieldValueListener<String[]>) listener));
		}

		setUpCircleView(result, (ProfileField<E>) field, listener);

		return result;
	}

@ SuppressWarnings ( "unchecked" ) private < E > View createTagView ( TagProfileField field , String [ ] currentValue , FieldValueListener < E > listener , ViewGroup container , boolean editable ) { View result = mInflater . inflate ( editable ? R . layout . profileedit_field_tag : R . layout . profileview_tag_field , container , false ) ; String friendlyName = mHelper . getFriendlyNameOfField ( field ) ; ( ( TextView ) result . findViewById ( R . id . profileedit_field_identifier ) ) . setText ( friendlyName ) ; TagsPicker picker = ( TagsPicker ) result . findViewById ( R . id . profileedit_tags_picker ) ; picker . setEditable ( editable ) ; if ( currentValue != null ) { picker . setInitialTags ( Arrays . asList ( currentValue ) ) ; } if ( editable ) { picker . setChangeListener ( new OnChangeListenerAdapter ( field , ( FieldValueListener < String [ ] > ) listener ) ) ; } setUpCircleView ( result , ( ProfileField < E > ) field , listener ) ; return result ; }


private <E> View createStandardEditView(ProfileField<E> field, E currentValue, FieldValueListener<E> listener, ViewGroup container) {
		View result = mInflater.inflate(R.layout.profileedit_field_standard, container, false);

		String friendlyName = mHelper.getFriendlyNameOfField(field);
		((TextView) result.findViewById(R.id.profileedit_field_identifier)).setText(friendlyName);

		EditText editText = (EditText) result.findViewById(R.id.profileedit_field_value);
		editText.addTextChangedListener(new OnEditorActionAdapter<>(listener, field));

		if (currentValue != null) {
			editText.setText(mHelper.convertToFriendlyString(field, currentValue));
		}

		setUpCircleView(result, field, listener);

		return result;
	}

private < E > View createStandardEditView ( ProfileField < E > field , E currentValue , FieldValueListener < E > listener , ViewGroup container ) { View result = mInflater . inflate ( R . layout . profileedit_field_standard , container , false ) ; String friendlyName = mHelper . getFriendlyNameOfField ( field ) ; ( ( TextView ) result . findViewById ( R . id . profileedit_field_identifier ) ) . setText ( friendlyName ) ; EditText editText = ( EditText ) result . findViewById ( R . id . profileedit_field_value ) ; editText . addTextChangedListener ( new OnEditorActionAdapter <> ( listener , field ) ) ; if ( currentValue != null ) { editText . setText ( mHelper . convertToFriendlyString ( field , currentValue ) ) ; } setUpCircleView ( result , field , listener ) ; return result ; }


public final void sendNotification(String uniqueIdentifier, SPFActionSendNotification action) {
        if (uniqueIdentifier == null || action == null) {
            throw new NullPointerException();
        }

        String actionJSON = action.toJSON();
        sendNotification(uniqueIdentifier, actionJSON);
    }

public final void sendNotification ( String uniqueIdentifier , SPFActionSendNotification action ) { if ( uniqueIdentifier == null || action == null ) { throw new NullPointerException ( ) ; } String actionJSON = action . toJSON ( ) ; sendNotification ( uniqueIdentifier , actionJSON ) ; }

Sends a notification to the remote SPF instance.

@param uniqueIdentifier - the identifier of the sender.
@param action           - the notification action.

Sends a notification to the remote SPF instance .