Populate embedded object.

@param sc
the sc
@param m
the m
@return the object
@throws Exception
the exception
177836
private Object populateEmbeddedObject(SuperColumn sc, EntityMetadata m) throws Exception
    {
        Field embeddedCollectionField = null;
        Object embeddedObject = null;
        String scName = PropertyAccessorFactory.STRING.fromBytes(String.class, sc.getName());
        String scNamePrefix = null;

        // Get a name->field map for super-columns
        Map<String, Field> columnNameToFieldMap = new HashMap<String, Field>();
        Map<String, Field> superColumnNameToFieldMap = new HashMap<String, Field>();
        MetadataUtils.populateColumnAndSuperColumnMaps(m, columnNameToFieldMap, superColumnNameToFieldMap,
                kunderaMetadata);

        // If this super column is variable in number (name#sequence format)
        if (scName.indexOf(Constants.EMBEDDED_COLUMN_NAME_DELIMITER) != -1)
        {
            StringTokenizer st = new StringTokenizer(scName, Constants.EMBEDDED_COLUMN_NAME_DELIMITER);
            if (st.hasMoreTokens())
            {
                scNamePrefix = st.nextToken();
            }

            embeddedCollectionField = superColumnNameToFieldMap.get(scNamePrefix);
            Class<?> embeddedClass = PropertyAccessorHelper.getGenericClass(embeddedCollectionField);

            // must have a default no-argument constructor
            try
            {
                embeddedClass.getConstructor();
            }
            catch (NoSuchMethodException nsme)
            {
                throw new PersistenceException(embeddedClass.getName()
                        + " is @Embeddable and must have a default no-argument constructor.");
            }
            embeddedObject = embeddedClass.newInstance();

            for (Column column : sc.getColumns())
            {
                String name = PropertyAccessorFactory.STRING.fromBytes(String.class, column.getName());
                byte[] value = column.getValue();
                if (value == null)
                {
                    continue;
                }
                Field columnField = columnNameToFieldMap.get(name);
                PropertyAccessorHelper.set(embeddedObject, columnField, value);
            }
        }
        else
        {
            Field superColumnField = superColumnNameToFieldMap.get(scName);
            Class superColumnClass = superColumnField.getType();
            embeddedObject = superColumnClass.newInstance();

            for (Column column : sc.getColumns())
            {
                String name = PropertyAccessorFactory.STRING.fromBytes(String.class, column.getName());
                byte[] value = column.getValue();

                if (value == null)
                {
                    continue;
                }
                // set value of the field in the bean
                Field columnField = columnNameToFieldMap.get(name);
                PropertyAccessorHelper.set(embeddedObject, columnField, value);
            }
        }
        return embeddedObject;
    }
572864
public Object call(Map<String,Object> m) throws ScriptException {
        List<Object> args = Objects.newArrayList();
        for(Object o:m.values()){
            args.add(o);
        }
        return call(m,args);
    }
1212773
public static ManagedEntity[] createManagedEntities(ServerConnection sc, ManagedObjectReference[] mors) {
        if (mors == null) {
            return new ManagedEntity[0];
        }
        ManagedEntity[] mes = new ManagedEntity[mors.length];

        for (int i = 0; i < mors.length; i++) {
            mes[i] = createExactManagedEntity(sc, mors[i]);
        }

        return mes;
    }
1155723
@Override
    protected List recursivelyPopulateEntities(EntityMetadata m, Client client)
    {
        List<EnhanceEntity> ls = populateEntities(m, client);
        return setRelationEntities(ls, client, m);
    }
826037
public T create() throws Exception {
        if (type == TYPE_DEFAULT) {
            if (args == null || args.length == 0) {
                return aClass.newInstance();
            }
        } else if (type == TYPE_CREATOR) {
            return creator.create();
        }

        throw new RuntimeException("Unsupported create method");
    }
406509
public static ManagedObject createExactManagedObject(ServerConnection sc, ManagedObjectReference mor) {
        if (mor == null) {
            return null;
        }

        String moType = mor.getType();
        Class moClass = null;
        try {
            moClass = Class.forName(moPackageName + "." + moType);
            Constructor constructor = moClass.getConstructor(
                    new Class[]{ServerConnection.class, ManagedObjectReference.class});
            return (ManagedObject) constructor.newInstance(new Object[]{sc, mor});
        }
        catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("vijava does not have an associated class for this mor: " + mor.getVal(), e);
        } catch (NoSuchMethodException e) {
            throw new IllegalArgumentException("No constructor found in vijava for class: " + moClass.getName(),e);
        } catch (InstantiationException e){
            throw new IllegalArgumentException("vijava is unable to create a managed object from this mor: " + mor.getVal(),e);
        } catch (IllegalAccessException e){
            throw new IllegalArgumentException("vijava is unable to create a managed object from this mor: " + mor.getVal(),e);
        } catch (InvocationTargetException e) {
            throw new IllegalArgumentException("vijava is unable to create a managed object from this mor: " + mor.getVal(),e);
        }
    }
337717
public void sendError(int sc) throws IOException
    {
        String message;
        RequestProcessor ref = getCurrentServletReference();
        if (ref != null)
        {
            sendError(sc, MessageFormat.format(nls.getString("[{0}].reported.an.error", "[{0}] reported an error"), new Object[] { ref.getName()}));
        }
        else
        {
            sendError(
                      sc,
                      MessageFormat.format(nls.getString("[{0}].reported.an.error", "[{0}] reported an error"), new Object[] { getWebApp().getConfiguration().getDisplayName()}));
        }
    }
869799
protected List populateEntitiesFromKeySlices(EntityMetadata m, boolean isWrapReq, List<String> relations,
        List<KeySlice> keys, CassandraDataHandler dataHandler) throws Exception {
        List results;
        MetamodelImpl metaModel =
            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());

        Set<String> superColumnAttribs = metaModel.getEmbeddables(m.getEntityClazz()).keySet();
        results = new ArrayList(keys.size());

        ThriftDataResultHelper dataGenerator = new ThriftDataResultHelper();
        for (KeySlice key : keys) {
            List<ColumnOrSuperColumn> columns = key.getColumns();

            byte[] rowKey = key.getKey();

            Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), rowKey);

            Object e = null;
            Map<ByteBuffer, List<ColumnOrSuperColumn>> data = new HashMap<ByteBuffer, List<ColumnOrSuperColumn>>(1);
            data.put(ByteBuffer.wrap(rowKey), columns);
            ThriftRow tr = new ThriftRow();
            tr.setId(id);
            tr.setColumnFamilyName(m.getTableName());
            tr = dataGenerator.translateToThriftRow(data, m.isCounterColumnType(), m.getType(), tr);

            e = dataHandler.populateEntity(tr, m, KunderaCoreUtils.getEntity(e), relations, isWrapReq);

            if (e != null) {
                results.add(e);
            }
        }
        return results;
    }
12121
public void execute() throws Exception {
        final var jsonFile = new File(buildDir, "classes/java/main/META-INF/spring-configuration-metadata.json");
        if (!jsonFile.exists()) {
            throw new RuntimeException("Could not locate file " + jsonFile.getCanonicalPath());
        }
        final var mapper = new ObjectMapper().findAndRegisterModules();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);

        final TypeReference<Map<String, Set<ConfigurationMetadataProperty>>> values = new TypeReference<>() {
        };
        final Map<String, Set> jsonMap = mapper.readValue(jsonFile, values);
        final Set<ConfigurationMetadataProperty> properties = jsonMap.get("properties");
        final Set<ConfigurationMetadataProperty> groups = jsonMap.get("groups");

        final Set<ConfigurationMetadataProperty> collectedProps = new HashSet<>();
        final Set<ConfigurationMetadataProperty> collectedGroups = new HashSet<>();

        properties.stream()
            .filter(p -> NESTED_TYPE_PATTERN.matcher(p.getType()).matches())
            .forEach(Unchecked.consumer(p -> {
                final var matcher = NESTED_TYPE_PATTERN.matcher(p.getType());
                final var indexBrackets = matcher.matches();
                final var typeName = matcher.group(1);
                final var typePath = ConfigurationMetadataClassSourceLocator.buildTypeSourcePath(this.sourcePath, typeName);

                final var parser = new ConfigurationMetadataUnitParser(this.sourcePath);
                parser.parseCompilationUnit(collectedProps, collectedGroups, p, typePath, typeName, indexBrackets);
            }));

        properties.addAll(collectedProps);
        groups.addAll(collectedGroups);

        final var hints = processHints(properties, groups);

        processNestedEnumProperties(properties, groups);

        jsonMap.put("properties", properties);
        jsonMap.put("groups", groups);
        jsonMap.put("hints", hints);

        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        final var pp = new MinimalPrettyPrinter();
        final var writer = mapper.writer(pp);
        writer.writeValue(jsonFile, jsonMap);
    }
427165
private void populate(final Element subroot,
                        final Object o,
                        final Collection<Object> col,
                        final Class cl) throws Throwable {
    String name = subroot.getNodeName();

    Method meth = null;

    Class elClass = null;

    if (col == null) {
      /* We must have a setter */
      meth = findSetter(o, name);

      if (meth == null) {
        error("No setter for " + name);

        return;
      }

      /* We require a single parameter */

      Class[] parClasses = meth.getParameterTypes();
      if (parClasses.length != 1) {
        error("Invalid setter method " + name);
        throw new ConfigException("Invalid setter method " + name);
      }

      elClass = parClasses[0];
    } else {
      elClass = cl;
    }

    if (!XmlUtil.hasChildren(subroot)) {
      /* A primitive value for which we should have a setter */

      Object val = simpleValue(elClass, subroot, name);
      if (val != null) {
        assign(val, col, o, meth);
      }

      return;
    }

    /* There are children to this element. It either represents a complex type
     * or a collection.
     */

    if (Collection.class.isAssignableFrom(elClass)) {
      Collection<Object> colVal = null;

      if (elClass.getName().equals("java.util.Set")) {
        colVal = new TreeSet<Object>();
      } else if (elClass.getName().equals("java.util.List")) {
        colVal = new ArrayList<Object>();
      } else {
        error("Unsupported element class " + elClass +
              " for field " + name);
        return;
      }

      assign(colVal, col, o, meth);

      // Figure out the class of the elements
      /* I thought I might be able toextract it from the generic info -
       * Doesn't appear to be the case.
       *
      Type gft = elClass;

      if (!(gft instanceof ParameterizedType)) {
        error("Unsupported type " + elClass +
              " with name " + name);
        return;
      }

      Type[] fieldArgTypes = ((ParameterizedType)gft).getActualTypeArguments();

      if (fieldArgTypes.length != 1) {
        error("Unsupported type " + elClass +
              " with name " + name);
        return;
      }

      Class colElType = (Class)fieldArgTypes[0];
      */
      ConfInfo ci = meth.getAnnotation(ConfInfo.class);

      String colElTypeName;

      if (ci == null) {
        colElTypeName = "java.lang.String";
      } else {
        colElTypeName = ci.elementType();
      }

      for (Element el: XmlUtil.getElementsArray(subroot)) {
        populate(el, o, colVal, Class.forName(colElTypeName));
      }

      return;
    }

    /* Asssume a complex type */

    Object val = getObject(subroot, elClass);

    assign(val, col, o, meth);

    for (Element el: XmlUtil.getElementsArray(subroot)) {
      populate(el, val, null, null);
    }
  }
755739
@Override
    protected List<Object> populateEntities(EntityMetadata m, Client client)
    {
        return onQuery(m, client);
    }
1037801
@SuppressWarnings("unchecked")
  public static <T> T populate(Class<T> clazz, String name) {
    EntityType type = null;
    if (clazz.isInterface()) {
      type = Model.getType(clazz.getName());
    } else {
      type = Model.getType(clazz);
    }
    return (T) populate(type.newInstance(), type.getEntityName(), name);
  }
193128
private Object populateEntityFromDataFrame(EntityMetadata m, Map<String, Integer> columnIndexMap, Row row)
    {
        try
        {
            // create entity instance
            Object entity = KunderaCoreUtils.createNewInstance(m.getEntityClazz());
            // handle relations
            Map<String, Object> relations = new HashMap<String, Object>();
            if (entity.getClass().isAssignableFrom(EnhanceEntity.class))
            {
                relations = ((EnhanceEntity) entity).getRelations();
                entity = ((EnhanceEntity) entity).getEntity();
            }
            // get a Set of attributes
            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                    m.getPersistenceUnit());
            EntityType entityType = metaModel.entity(m.getEntityClazz());
            Set<Attribute> attributes = ((AbstractManagedType) entityType).getAttributes();
            // iterate over attributes and find its value
            for (Attribute attribute : attributes)
            {
                String columnName = getColumnName(attribute);
                Object columnValue = row.get(columnIndexMap.get(columnName));
                if (columnValue != null)
                {
                    Object value = PropertyAccessorHelper.fromSourceToTargetClass(attribute.getJavaType(),
                            columnValue.getClass(), columnValue);

                    PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), value);
                }
            }
            // find the value of @Id field for EnhanceEntity
            SingularAttribute attrib = m.getIdAttribute();
            Object rowKey = PropertyAccessorHelper.getObject(entity, (Field) attrib.getJavaMember());
            if (!relations.isEmpty())
            {
                return new EnhanceEntity(entity, rowKey, relations);
            }
            return entity;
        }
        catch (PropertyAccessException e1)
        {
            throw new RuntimeException(e1);
        }
    }
889612
public synchronized void start() throws Exception {
    Preconditions.checkState(mState != State.STARTED, "Cannot start while already started");
    Preconditions.checkState(mState != State.DESTROYED, "Cannot start a destroyed cluster");
    mWorkDir = AlluxioTestDirectory.createTemporaryDirectory(mClusterName);
    mState = State.STARTED;

    mMasterAddresses = generateMasterAddresses(mNumMasters);
    LOG.info("Master addresses: {}", mMasterAddresses);
    switch (mDeployMode) {
      case UFS_NON_HA:
        MasterNetAddress masterAddress = mMasterAddresses.get(0);
        mProperties.put(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.UFS.toString());
        mProperties.put(PropertyKey.MASTER_HOSTNAME, masterAddress.getHostname());
        mProperties.put(PropertyKey.MASTER_RPC_PORT, Integer.toString(masterAddress.getRpcPort()));
        mProperties.put(PropertyKey.MASTER_WEB_PORT, Integer.toString(masterAddress.getWebPort()));
        break;
      case EMBEDDED:
        List<String> journalAddresses = new ArrayList<>();
        List<String> rpcAddresses = new ArrayList<>();
        for (MasterNetAddress address : mMasterAddresses) {
          journalAddresses
              .add(String.format("%s:%d", address.getHostname(), address.getEmbeddedJournalPort()));
          rpcAddresses.add(String.format("%s:%d", address.getHostname(), address.getRpcPort()));
        }
        mProperties.put(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.EMBEDDED.toString());
        mProperties.put(PropertyKey.MASTER_EMBEDDED_JOURNAL_ADDRESSES,
            com.google.common.base.Joiner.on(",").join(journalAddresses));
        mProperties.put(PropertyKey.MASTER_RPC_ADDRESSES,
            com.google.common.base.Joiner.on(",").join(rpcAddresses));
        break;
      case ZOOKEEPER_HA:
        mCuratorServer = mCloser.register(
            new RestartableTestingServer(-1, AlluxioTestDirectory.createTemporaryDirectory("zk")));
        mProperties.put(PropertyKey.MASTER_JOURNAL_TYPE, JournalType.UFS.toString());
        mProperties.put(PropertyKey.ZOOKEEPER_ENABLED, "true");
        mProperties.put(PropertyKey.ZOOKEEPER_ADDRESS, mCuratorServer.getConnectString());
        break;
      default:
        throw new IllegalStateException("Unknown deploy mode: " + mDeployMode.toString());
    }

    for (Entry<PropertyKey, String> entry :
        ConfigurationTestUtils.testConfigurationDefaults(ServerConfiguration.global(),
        NetworkAddressUtils.getLocalHostName(
            (int) ServerConfiguration.getMs(PropertyKey.NETWORK_HOST_RESOLUTION_TIMEOUT_MS)),
            mWorkDir.getAbsolutePath()).entrySet()) {
      // Don't overwrite explicitly set properties.
      if (mProperties.containsKey(entry.getKey())) {
        continue;
      }
      // Keep the default RPC timeout.
      if (entry.getKey().equals(PropertyKey.USER_RPC_RETRY_MAX_DURATION)) {
        continue;
      }
      mProperties.put(entry.getKey(), entry.getValue());
    }
    mProperties.put(PropertyKey.MASTER_MOUNT_TABLE_ROOT_UFS,
        PathUtils.concatPath(mWorkDir, "underFSStorage"));
    new File(mProperties.get(PropertyKey.MASTER_MOUNT_TABLE_ROOT_UFS)).mkdirs();
    if (!mNoFormat) {
      formatJournal();
    }
    writeConf();
    ServerConfiguration.merge(mProperties, Source.RUNTIME);

    // Start servers
    LOG.info("Starting alluxio cluster {} with base directory {}", mClusterName,
        mWorkDir.getAbsolutePath());
    for (int i = 0; i < mNumMasters; i++) {
      createMaster(i).start();
    }
    for (int i = 0; i < mNumWorkers; i++) {
      createWorker(i).start();
    }
    System.out.printf("Starting alluxio cluster in directory %s%n", mWorkDir.getAbsolutePath());
  }
963847
public function insert(Model $m, $data)
    {
        if (!$this->mode) {
            $this->mode = 'w';
        } elseif ($this->mode == 'r') {
            throw new Exception(['Currently reading records, so writing is not possible.']);
        }

        if (!$this->handle) {
            $this->saveHeader($m);
        }

        $line = [];

        foreach ($this->header as $name) {
            $line[] = $data[$name];
        }

        $this->putLine($line);
    }
2853
@Override
    public void start() throws Exception {
        if (this.started) {
            logger.warn(String.format("management=%s is already started", this.name));
            return;
        }

        synchronized (this) {
            this.persistFile.clear();

            if (persistDir != null) {
                this.persistFile.append(persistDir).append(File.separator).append(this.name).append("_")
                        .append(PERSIST_FILE_NAME);
            } else {
                persistFile.append(System.getProperty(SCTP_PERSIST_DIR_KEY, System.getProperty(USER_DIR_KEY)))
                        .append(File.separator).append(this.name).append("_").append(PERSIST_FILE_NAME);
            }

            logger.info(String.format("SCTP configuration file path %s", persistFile.toString()));

            this.bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("Sctp-BossGroup-" + this.name));
            // TODO: make a thread count for WorkerGroup configurable
            this.workerGroup = new NioEventLoopGroup(0, new DefaultThreadFactory("Sctp-WorkerGroup-" + this.name));
            this.clientExecutor = new ScheduledThreadPoolExecutor(1, new DefaultThreadFactory("Sctp-ClientExecutorGroup-"
                    + this.name));

            // this.nettyClientOpsThread = new NettyClientOpsThread(this);
            // (new Thread(this.nettyClientOpsThread )).start();

            try {
                this.load();
            } catch (FileNotFoundException e) {
                logger.warn(String.format("Failed to load the SCTP configuration file. \n%s", e.getMessage()));
            }

            this.started = true;

            if (logger.isInfoEnabled()) {
                logger.info(String.format("Started SCTP Management=%s", this.name));
            }

            for (ManagementEventListener lstr : managementEventListeners) {
                try {
                    lstr.onServiceStarted();
                } catch (Throwable ee) {
                    logger.error("Exception while invoking onServiceStarted", ee);
                }
            }
        }
    }
567374
@Override
    protected List populateEntities(EntityMetadata m, Client client)
    {
        List results = new ArrayList();

        if (!MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))
        {
            results.addAll(populateUsingLucene(m, client, null, getKunderaQuery().getResult()));
        }

        else
        {
            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                    m.getPersistenceUnit());
            EntityType entityType = metaModel.entity(m.getEntityClazz());

            KuduClient kuduClient = ((KuduDBClient) client).getKuduClient();
            KuduTable table;
            try
            {
                table = kuduClient.openTable(m.getTableName());
            }
            catch (Exception e)
            {
                logger.error("Cannot open table : " + m.getTableName(), e);
                throw new KunderaException("Cannot open table : " + m.getTableName(), e);
            }

            KuduScannerBuilder scannerBuilder = kuduClient.newScannerBuilder(table);
            JPQLExpression jpqlExp = kunderaQuery.getJpqlExpression();
            List<String> selectColumns = KunderaQueryUtils.getSelectColumns(jpqlExp);
            if (!selectColumns.isEmpty())
            {
                // select by specific columns, set projection
                scannerBuilder.setProjectedColumnNames(selectColumns);
            }
            if (KunderaQueryUtils.hasWhereClause(jpqlExp))
            {
                // add predicate filters
                WhereClause whereClause = KunderaQueryUtils.getWhereClause(jpqlExp);
                Expression whereExp = whereClause.getConditionalExpression();
                parseAndBuildFilters(entityType, scannerBuilder, whereExp);
            }

            KuduScanner scanner = scannerBuilder.build();

            Object entity;
            while (scanner.hasMoreRows())
            {
                RowResultIterator rowResultIter;
                try
                {
                    rowResultIter = scanner.nextRows();
                }
                catch (Exception e)
                {
                    logger.error("Cannot get results from table : " + m.getTableName(), e);
                    throw new KunderaException("Cannot get results from table : " + m.getTableName(), e);
                }

                while (rowResultIter.hasNext())
                {
                    RowResult result = rowResultIter.next();
                    entity = KunderaCoreUtils.createNewInstance(m.getEntityClazz());
                    // populate RowResult to entity object and return
                    ((KuduDBClient) client).populateEntity(entity, result, entityType, metaModel);
                    results.add(entity);
                    logger.debug(result.rowToString());
                }
            }
        }
        return results;
    }