Index or reindex a given list of instances. The given instances m,ust be
all of the same type!

@param _context the _context
@param _instances the instances
@throws EFapsException the e faps exception
979823
public static void index(final IndexContext _context,
                             final List<Instance> _instances)
        throws EFapsException
    {
        if (CollectionUtils.isNotEmpty(_instances)) {
            final Company currentCompany = Context.getThreadContext().getCompany();
            final String currentLanguage = Context.getThreadContext().getLanguage();

            Context.getThreadContext().setCompany(Company.get(_context.getCompanyId()));
            Context.getThreadContext().setLanguage(_context.getLanguage());
            final IndexWriterConfig config = new IndexWriterConfig(_context.getAnalyzer());
            try (
                    IndexWriter writer = new IndexWriter(_context.getDirectory(), config);
                    TaxonomyWriter taxonomyWriter = new DirectoryTaxonomyWriter(_context.getTaxonomyDirectory());
                ) {

                final IndexDefinition def = IndexDefinition.get(_instances.get(0).getType().getUUID());
                final MultiPrintQuery multi = new MultiPrintQuery(_instances);
                for (final IndexField field : def.getFields()) {
                    multi.addSelect(field.getSelect());
                }
                Attribute createdAttr = null;
                if (!_instances.get(0).getType().getAttributes(CreatedType.class).isEmpty()) {
                    createdAttr = _instances.get(0).getType().getAttributes(CreatedType.class).iterator().next();
                    multi.addAttribute(createdAttr);
                }
                multi.addMsgPhrase(def.getMsgPhrase());
                multi.executeWithoutAccessCheck();
                while (multi.next()) {
                    final String oid = multi.getCurrentInstance().getOid();
                    final String type = multi.getCurrentInstance().getType().getLabel();
                    final DateTime created;
                    if (createdAttr == null) {
                        created = new DateTime();
                    } else {
                        created = multi.getAttribute(createdAttr);
                    }

                    final Document doc = new Document();
                    doc.add(new FacetField(Dimension.DIMTYPE.name(), type));
                    doc.add(new FacetField(Dimension.DIMCREATED.name(), String.valueOf(created.getYear()),
                                    String.format("%02d", created.getMonthOfYear())));
                    doc.add(new StringField(Key.OID.name(), oid, Store.YES));
                    doc.add(new TextField(DBProperties.getProperty("index.Type"), type, Store.YES));
                    doc.add(new NumericDocValuesField(Key.CREATED.name(), created.getMillis()));
                    doc.add(new StringField(Key.CREATEDSTR.name(),
                                    DateTools.dateToString(created.toDate(), DateTools.Resolution.DAY), Store.NO));

                    final StringBuilder allBldr = new StringBuilder()
                                    .append(type).append(" ");

                    for (final IndexField field : def.getFields()) {
                        final String name = DBProperties.getProperty(field.getKey());
                        Object value = multi.getSelect(field.getSelect());
                        if (value != null) {
                            if (StringUtils.isNoneEmpty(field.getTransform())) {
                                final Class<?> clazz = Class.forName(field.getTransform(),
                                                false, EFapsClassLoader.getInstance());
                                final ITransformer transformer = (ITransformer) clazz.newInstance();
                                value = transformer.transform(value);
                            }
                            switch (field.getFieldType()) {
                                case LONG:
                                    long val = 0;
                                    if (value instanceof String) {
                                        val = NumberUtils.toLong((String) value);
                                    } else if (value instanceof Number) {
                                        val = ((Number) value).longValue();
                                    }
                                    doc.add(new LongField(name, val, Store.YES));
                                    allBldr.append(value).append(" ");
                                    break;
                                case SEARCHLONG:
                                    long val2 = 0;
                                    if (value instanceof String) {
                                        val2 = NumberUtils.toLong((String) value);
                                    } else if (value instanceof Number) {
                                        val2 = ((Number) value).longValue();
                                    }
                                    doc.add(new LongField(name, val2, Store.NO));
                                    allBldr.append(value).append(" ");
                                    break;
                                case STRING:
                                    doc.add(new StringField(name, String.valueOf(value), Store.YES));
                                    allBldr.append(value).append(" ");
                                    break;
                                case SEARCHSTRING:
                                    doc.add(new StringField(name, String.valueOf(value), Store.NO));
                                    allBldr.append(value).append(" ");
                                    break;
                                case TEXT:
                                    doc.add(new TextField(name, String.valueOf(value), Store.YES));
                                    allBldr.append(value).append(" ");
                                    break;
                                case SEARCHTEXT:
                                    doc.add(new TextField(name, String.valueOf(value), Store.NO));
                                    allBldr.append(value).append(" ");
                                    break;
                                case STORED:
                                    doc.add(new StoredField(name, String.valueOf(value)));
                                    allBldr.append(value).append(" ");
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    doc.add(new StoredField(Key.MSGPHRASE.name(), multi.getMsgPhrase(def.getMsgPhrase())));
                    doc.add(new TextField(Key.ALL.name(), allBldr.toString(), Store.NO));
                    writer.updateDocument(new Term(Key.OID.name(), oid),
                                    Index.getFacetsConfig().build(taxonomyWriter, doc));
                    LOG.debug("Add Document: {}", doc);
                }
                writer.close();
                taxonomyWriter.close();
            } catch (final IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                throw new EFapsException(Indexer.class, "IOException", e);
            } finally {
                Context.getThreadContext().setCompany(currentCompany);
                Context.getThreadContext().setLanguage(currentLanguage);
            }
        }
    }
10119
public static void registerUpdate(final Instance _instance)
        throws EFapsException
    {
        // check if SystemConfiguration exists, necessary during install
        if (EFapsSystemConfiguration.get() != null
                        && EFapsSystemConfiguration.get().getAttributeValueAsBoolean(KernelSettings.INDEXACTIVATE)) {
            if (_instance != null && _instance.getType() != null
                            && IndexDefinition.get(_instance.getType().getUUID()) != null) {
                final AdvancedCache<String, String> cache = InfinispanCache.get()
                                .<String, String>getIgnReCache(CACHENAME);
                cache.put(RandomUtil.random(12), _instance.getOid());
            }
        }
    }
922561
public AbstractPrintQuery addMsgPhrase(final String... _msgPhrase)
        throws EFapsException
    {
        final List<MsgPhrase> msgphrases = new ArrayList<>();
        for (final String phraseStr : _msgPhrase) {
            msgphrases.add(MsgPhrase.get(phraseStr));
        }
        return addMsgPhrase(msgphrases.toArray(new MsgPhrase[msgphrases.size()]));
    }
842136
public static PermissionSet getPermissionSet(final Instance _instance)
        throws EFapsException
    {
        Evaluation.LOG.debug("Evaluation PermissionSet for {}", _instance);
        final Key accessKey = Key.get4Instance(_instance);
        final PermissionSet ret = AccessCache.getPermissionCache().get(accessKey);
        Evaluation.LOG.debug("Evaluated PermissionSet {}", ret);
        return ret;
    }
745464
protected Map<String, String> readCompiledSources()
        throws EFapsException
    {
        final Map<String, String> ret = new HashMap<>();
        final QueryBuilder queryBldr = new QueryBuilder(getClassName4TypeCompiled());
        final MultiPrintQuery multi = queryBldr.getPrint();
        multi.addAttribute(CIAdminProgram.StaticCompiled.Name);
        multi.executeWithoutAccessCheck();
        while (multi.next()) {
            final String name = multi.<String>getAttribute(CIAdminProgram.StaticCompiled.Name);
            ret.put(name, multi.getCurrentInstance().getOid());
        }
        return ret;
    }
443290
public synchronized void start(StartContext context) throws StartException {
        Logger.getLogger("org.mobicents.as10").debug(
                "SipConnectorService.start(), protocol = " + protocol + " - scheme = " + scheme);
        final SocketBinding binding = this.binding.getValue();
        final InetSocketAddress address = binding.getSocketAddress();
        final Executor executor = this.executor.getOptionalValue();
        try {

            SipConnector sipConnector = new SipConnector();
            sipConnector.setIpAddress(address.getAddress().getHostAddress());
            sipConnector.setPort(address.getPort());
            // https://github.com/Mobicents/sip-servlets/issues/44 support multiple connectors
            sipConnector.setTransport(binding.getName().substring(binding.getName().lastIndexOf("sip-") + ("sip-".length())));
            sipConnector.setUseLoadBalancer(useLoadBalancer);
            sipConnector.setLoadBalancerAddress(loadBalancerAddress);
            sipConnector.setLoadBalancerRmiPort(loadBalancerRmiPort);
            sipConnector.setLoadBalancerSipPort(loadBalancerSipPort);
            sipConnector.setUseStaticAddress(useStaticAddress);
            sipConnector.setStaticServerAddress(staticServerAddress);
            sipConnector.setStaticServerPort(staticServerPort);
            sipConnector.setUseStun(useStun);
            sipConnector.setStunServerAddress(stunServerAddress);
            sipConnector.setStunServerPort(stunServerPort);
            sipConnector.setHostNames(hostNames);

            Logger.getLogger("org.mobicents.as10").debug(
                    "SipConnectorService.start(), address = " + address.getAddress().getHostAddress() + " - port = "
                            + address.getPort() + " - transport = " + sipConnector.getTransport());
            Logger.getLogger("org.mobicents.as10").debug("SipConnectorService.start(), hostnames = " + hostNames);

            /*
             * FIXME: kakonyii: need an implementation in SipConnector class for the following fields: enableLookups proxyName
             * proxyPort redirectPort secure maxPostSize maxSavePostSize
             */

            SipProtocolHandler sipProtocolHandler = new SipProtocolHandler(sipConnector);

            // TODO set Executor on ProtocolHandler
            // TODO use server socket factory - or integrate with {@code ManagedBinding}

            final SipConnectorListener connector = new SipConnectorListener(sipProtocolHandler);

            connector.init();
            getSipServer().addConnector(connector);
            connector.start();

            this.connector = connector;
        } catch (Exception e) {
            throw new StartException(MESSAGES.connectorStartError(), e);
        }
        // Register the binding after the connector is started
        binding.getSocketBindings().getNamedRegistry().registerBinding(new ConnectorBinding(binding));
        //notify SipServer only when connector has already been added/started
        getSipServer().connectorAdded(connector);        
    }
1244184
public void setContext(Context context) {
    super.setContext(context);
    if (null != context) {
      Object count = context.getDatas().get("countPerSheet");
      if (null != count && Numbers.isDigits(count.toString())) {
        int countParam = Numbers.toInt(count.toString());
        if (countParam > 0) this.countPerSheet = countParam;
      }
    }
  }
200384
public Resource getStoreResource(final Instance _instance,
                                     final Resource.StoreEvent _event)
        throws EFapsException
    {
        Resource storeRsrc = null;
        final Store store = Store.get(_instance.getType().getStoreId());
        storeRsrc = store.getResource(_instance);
        storeRsrc.open(_event);
        this.storeStore.add(storeRsrc);
        return storeRsrc;
    }
150911
private void getValues4Instances(final String _oid)
        throws EFapsException
    {
        // group the instance by type
        // check if the current instance is the list (happens if this
        // value select is e.g. part of a linkto
        final Map<Type, List<Instance>> type2instance = new HashMap<>();
        final Instance currentInst = Instance.get(_oid);
        final List<Instance> instances = new ArrayList<>();
        if (getOneSelect().getQuery().getInstanceList().contains(currentInst)) {
            instances.addAll(getOneSelect().getQuery().getInstanceList());
        } else {
            for (final Object object : getOneSelect().getObjectList()) {
                final String oid =  (String) super.getValue(object);
                instances.add(Instance.get(oid));
            }
        }

        for (final Instance instance : instances) {
            final List<Instance> tmpList;
            if (type2instance.containsKey(instance.getType())) {
                tmpList = type2instance.get(instance.getType());
            } else {
                tmpList = new ArrayList<>();
                type2instance.put(instance.getType(), tmpList);
            }
            tmpList.add(instance);
        }

        // make one union part for every type
        for (final Entry<Type, List<Instance>> entry : type2instance.entrySet()) {

            boolean union = false;
            final Set<Classification> classTypes = new HashSet<>();
            Type curr = entry.getKey();
            while (curr.getParentType() != null) {
                classTypes.addAll(curr.getClassifiedByTypes());
                curr = curr.getParentType();
            }
            classTypes.addAll(curr.getClassifiedByTypes());
            final SQLSelect unionSelect = new SQLSelect();
            for (final Classification clazz : classTypes) {

                final Attribute typeAttr = clazz.getClassifyRelationType()
                                .getAttribute(clazz.getRelTypeAttributeName());
                final Attribute linkAttr = clazz.getClassifyRelationType()
                                .getAttribute(clazz.getRelLinkAttributeName());
                final SQLSelect select;
                if (union) {
                    unionSelect.addPart(SQLPart.UNION).addPart(SQLPart.ALL);
                    select = new SQLSelect();
                } else {
                    select = unionSelect;
                    union = true;
                }
                select.column(0, "ID")
                    .column(0, linkAttr.getSqlColNames().get(0))
                    .column(0, typeAttr.getSqlColNames().get(0))
                    .from(clazz.getClassifyRelationType().getMainTable().getSqlTable(), 0)
                    .addPart(SQLPart.WHERE)
                    .addColumnPart(0, linkAttr.getSqlColNames().get(0))
                    .addPart(SQLPart.IN).addPart(SQLPart.PARENTHESIS_OPEN);

                boolean first = true;
                for (final Instance instance : entry.getValue()) {
                    if (first) {
                        first = false;
                    } else {
                        select.addPart(SQLPart.COMMA);
                    }
                    select.addValuePart(instance.getId());
                }
                select.addPart(SQLPart.PARENTHESIS_CLOSE);
                if (clazz.getClassifyRelationType().getMainTable().getSqlColType() != null) {
                    select.addPart(SQLPart.AND)
                        .addColumnPart(0, clazz.getClassifyRelationType().getMainTable().getSqlColType())
                        .addPart(SQLPart.EQUAL).addValuePart(clazz.getClassifyRelationType().getId());
                }
                if (union && !select.equals(unionSelect)) {
                    unionSelect.addNestedSelectPart(select.getSQL());
                }
            }
            if (classTypes.size() > 0) {
                executeOneCompleteStmt(unionSelect.getSQL(), entry.getValue());
            }
        }
    }
195737
private void checkAccess()
        throws EFapsException
    {
        // check the access for the given instances
        final Map<Instance, Boolean> accessmap = new HashMap<Instance, Boolean>();
        for (final Entry<Type, List<Instance>> entry : this.typeMapping.entrySet()) {
            accessmap.putAll(entry.getKey().checkAccess(entry.getValue(), AccessTypeEnums.SHOW.getAccessType()));
        }
        this.elements.entrySet().removeIf(entry -> accessmap.size() > 0 && (!accessmap.containsKey(entry.getKey())
                        || !accessmap.get(entry.getKey())));
    }
714132
static void releaseContext(SeaGlassContext context) {
        synchronized (contextMap) {
            List instances = (List) contextMap.get(context.getClass());

            if (instances == null) {
                instances = new ArrayList(5);
                contextMap.put(context.getClass(), instances);
            }

            instances.add(context);
        }
    }
274176
@SuppressWarnings("rawtypes")
    public void evaluateInstanceList(TransducerTrainer tt, InstanceList data,
            String description) {
        Transducer model = tt.getTransducer();
        int numCorrectTokens, totalTokens;
        int[] numTrueSegments, numPredictedSegments, numCorrectSegments;
        int allIndex = segmentStartTags.length;
        numTrueSegments = new int[allIndex + 1];
        numPredictedSegments = new int[allIndex + 1];
        numCorrectSegments = new int[allIndex + 1];

        totalTokens = numCorrectTokens = 0;
        for (int n = 0; n < numTrueSegments.length; n++)
            numTrueSegments[n] = numPredictedSegments[n] = numCorrectSegments[n] = 0;
        for (int i = 0; i < data.size(); i++) {
            Instance instance = data.get(i);
            Sequence input = (Sequence) instance.getData();
            // String tokens = null;
            // if (instance.getSource() != null)
            // tokens = (String) instance.getSource().toString();
            Sequence trueOutput = (Sequence) instance.getTarget();
            assert (input.size() == trueOutput.size());
            Sequence predOutput = model.transduce(input);
            assert (predOutput.size() == trueOutput.size());
            int trueStart, predStart; // -1 for non-start, otherwise index into
                                      // segmentStartTag

            boolean hasIncorrect = false;
            StringBuilder sentencePrint = new StringBuilder();

            for (int j = 0; j < trueOutput.size(); j++) {
                totalTokens++;
                if (trueOutput.get(j).equals(predOutput.get(j))) {
                    numCorrectTokens++;
                    if (printMissclassified)
                        sentencePrint.append(getText(input, j) + " ");

                } else if (printMissclassified) {// not predicted correctly
                    hasIncorrect = true;
                    sentencePrint.append("{{" + getText(input, j) + "}} ");
                }

                trueStart = predStart = -1;
                // Count true segment starts
                for (int n = 0; n < segmentStartTags.length; n++) {
                    if (segmentStartTags[n].equals(trueOutput.get(j))) {
                        numTrueSegments[n]++;
                        numTrueSegments[allIndex]++;
                        trueStart = n;
                        break;
                    }
                }
                // Count predicted segment starts
                for (int n = 0; n < segmentStartTags.length; n++) {
                    if (segmentStartTags[n].equals(predOutput.get(j))) {
                        numPredictedSegments[n]++;
                        numPredictedSegments[allIndex]++;
                        predStart = n;
                    }
                }
                if (trueStart != -1 && trueStart == predStart) {
                    // Truth and Prediction both agree that the same segment
                    // tag-type is starting now
                    int m;
                    boolean trueContinue = false;
                    boolean predContinue = false;
                    for (m = j + 1; m < trueOutput.size(); m++) {
                        trueContinue = segmentContinueTags[predStart]
                                .equals(trueOutput.get(m));
                        predContinue = segmentContinueTags[predStart]
                                .equals(predOutput.get(m));
                        if (!trueContinue || !predContinue) {
                            if (trueContinue == predContinue) {
                                // They agree about a segment is ending somehow
                                numCorrectSegments[predStart]++;
                                numCorrectSegments[allIndex]++;
                            }
                            break;
                        }
                    }
                    // for the case of the end of the sequence
                    if (m == trueOutput.size()) {
                        if (trueContinue == predContinue) {
                            numCorrectSegments[predStart]++;
                            numCorrectSegments[allIndex]++;
                        }
                    }
                }
            }
            if (hasIncorrect && printMissclassified)
                System.out.println(sentencePrint.toString());
        }

        tokenAccuracy = ((double) numCorrectTokens) / totalTokens;
        for (int n = 0; n < numCorrectSegments.length; n++) {
            if (!(n < allIndex)) {// only "OVERALL"
                precision = numPredictedSegments[n] == 0 ? 1
                        : ((double) numCorrectSegments[n])
                                / numPredictedSegments[n];
                recall = numTrueSegments[n] == 0 ? 1
                        : ((double) numCorrectSegments[n]) / numTrueSegments[n];
                f1 = recall + precision == 0.0 ? 0.0
                        : (2.0 * recall * precision) / (recall + precision);
            }
        }
    }
321082
public void restoreAllMockEc2Instances(final Collection<AbstractMockEc2Instance> instances) {
        allMockEc2Instances.clear();
        if (null != instances) {
            for (AbstractMockEc2Instance instance : instances) {
                allMockEc2Instances.put(instance.getInstanceID(), instance);
                // re-initialize the internal timer
                instance.initializeInternalTimer();
            }
        }
    }
1224233
@Override
    public void setContext(Context context) {
        super.setContext(context);

        fsInfo = FSInfo.instance(context);

        contextUseOptimizedZip = options.getBoolean("useOptimizedZip", true);
        if (contextUseOptimizedZip)
            zipFileIndexCache = ZipFileIndexCache.getSharedInstance();

        mmappedIO = options.isSet("mmappedIO");
        symbolFileEnabled = !options.isSet("ignore.symbol.file");

        String sf = options.get("sortFiles");
        if (sf != null) {
            sortFiles = (sf.equals("reverse") ? SortFiles.REVERSE : SortFiles.FORWARD);
        }
    }
7119
protected List<T> readSources()
        throws EFapsException
    {
        final List<T> ret = new ArrayList<>();
        final QueryBuilder queryBldr = new QueryBuilder(getClassName4Type());
        final MultiPrintQuery multi = queryBldr.getPrint();
        multi.addAttribute(CIAdminProgram.Abstract.Name);
        multi.executeWithoutAccessCheck();
        while (multi.next()) {
            final String name = multi.<String>getAttribute(CIAdminProgram.StaticCompiled.Name);
            ret.add(getNewSource(name, multi.getCurrentInstance()));
        }
        return ret;
    }
1258082
@Override
    public List<Instance> executeWithoutAccessCheck()
        throws EFapsException
    {
        prepareQuery();
        final String sql = createSQLStatement();
        final QueryKey querykey = QueryKey.get(getKey(), sql);
        final Cache<QueryKey, Object> cache = QueryCache.getSqlCache();
        if (cache.containsKey(querykey)) {
            final Object object = cache.get(querykey);
            if (object instanceof List) {
                final List<?> values = (List<?>) object;
                for (final Object value : values) {
                    if (value instanceof Instance) {
                        getValues().add((Instance) value);
                    }
                }
            }
        } else {
            executeOneCompleteStmt(sql);
            QueryCache.put(this, querykey, getValues());
        }
        return getValues();
    }
366294
private void updateInstances(List<InstanceContext> instances, final CountingCompletionHandler<Void> counter) {
    for (final InstanceContext instance : instances) {
      data.put(instance.address(), Contexts.serialize(instance).encode(), new Handler<AsyncResult<String>>() {
        @Override
        public void handle(AsyncResult<String> result) {
          if (result.failed()) {
            counter.fail(result.cause());
          } else {
            counter.succeed();
          }
        }
      });
    }
  }