Exemplo n.º 1
0
/************************************************************

Operator function.  Prints the name and type of the object
being examined.

************************************************************/
static herr_t op_func_v1(hid_t loc_id, const char *name, const H5L_info_t *info, void *operator_data)
{
    H5O_info_t oinfo;
    herr_t status = 0;
    int *pDataSetId = (int*)operator_data;
    hid_t obj = H5Oopen(loc_id, name, H5P_DEFAULT);
    if (obj < 0)
    {
        return -1;
    }

    /*
     * Get type of the object and return only datasetId
     * through operator_data.
     */
    status = H5Oget_info(obj, &oinfo);
    if (status < 0)
    {
        H5Oclose(obj);
        return -1;
    }

    if (oinfo.type == H5O_TYPE_DATASET)
    {
        *pDataSetId = obj;
    }
    else
    {
        H5Oclose(obj);
    }

    return 0;
}
Exemplo n.º 2
0
char* test_utf_8() {
  hid_t file, node, unode, dset;
  size_t len;
  char res, *path, *attr, **dset_val;

  file = H5Fopen(FILE, H5F_ACC_RDONLY, H5P_DEFAULT);
  mu_assert("H5Fopen() open file...", file >= 0);

  mu_assert("Valid node path...", AH5_path_valid(file, NODE_PATH));
  node = H5Oopen(file, NODE_PATH, H5P_DEFAULT);
  mu_assert("H5Oopen() open node...", node >= 0);

  mu_assert("Valid unode path...", AH5_path_valid(node, UNODE_PATH));
  unode = H5Oopen(node, UNODE_PATH, H5P_DEFAULT);
  mu_assert("H5Oopen() open unode...", unode >= 0);

  H5Oclose(unode);

  path = (char*) malloc(sizeof(char) * (1 + strlen(NODE_PATH) + 1 + strlen(UNODE_PATH) + 1));
  path[0] = '/';
  path[1] = '\0';
  strcat(path, NODE_PATH);
  strcat(path, "/");
  strcat(path, UNODE_PATH);
  mu_assert("Valid unode absolute path...", AH5_path_valid(file, path));
  unode = H5Oopen(file, path, H5P_DEFAULT);
  mu_assert("H5Oopen() open unode...", unode >= 0);
  free(path);

  len = AH5_read_str_attr_len(unode, ".", "attribut du sous-nœud accentué");
  mu_assert("AH5_read_str_attr_len() read utf-8 attr len...", len > 0);

  attr = (char*) malloc(sizeof(char) * (len + 1));
  res = AH5_read_str_attr(unode, ".", "attribut du sous-nœud accentué", &attr);
  mu_assert("AH5_read_str_attr() status...", res == AH5_TRUE);
  mu_assert("AH5_read_str_attr() str length...", strlen(attr) == strlen("é è à œ"));
  mu_assert("AH5_read_str_attr() str value...", strcmp(attr, "é è à œ") == 0);
  free(attr);

  mu_assert("Valid dset path...", AH5_path_valid(unode, DSET_PATH));
  dset = H5Oopen(unode, DSET_PATH, H5P_DEFAULT);
  mu_assert("H5Oopen() open dset...", dset >= 0);
  len = 11;
  dset_val = (char**) malloc(sizeof(char*));
  dset_val[0] = (char*) malloc(sizeof(char) * (len + 1));
  res = AH5_read_str_dataset(dset, ".", 1, len, &dset_val);
  mu_assert("AH5_read_str_dataset() status...", res == AH5_TRUE);
  mu_assert("AH5_read_str_dataset() str length...", strlen(dset_val[0]) == strlen("é è à œ"));
  mu_assert("AH5_read_str_dataset() str value...", strcmp(dset_val[0], "é è à œ") == 0);
  free(dset_val[0]);
  free(dset_val);

  H5Oclose(dset);
  H5Oclose(unode);
  H5Oclose(node);
  H5Fclose(file);

  return MU_FINISHED_WITHOUT_ERRORS;
}
Exemplo n.º 3
0
/*-------------------------------------------------------------*/
static hid_t findDependentField(pNXVcontext self,
		hid_t inFieldID,char *dpData)
{
	char *pPtr;
	hid_t fieldID, groupID;
	char fname[512], newPath[1024], groupName[1024];

	/*
		get at enclosing group
  */
	memset(groupName,0,sizeof(groupName));
	H5Iget_name(inFieldID,groupName,sizeof(groupName));
	pPtr = strrchr(groupName,'/');
	*pPtr = '\0';
	pPtr = NULL;

	pPtr = strchr(dpData,'/');

	if(pPtr != NULL){
		if(pPtr == dpData){
			/* absolute path */
			if(H5LTpath_valid(self->fileID,dpData,1)){
				fieldID = H5Oopen(self->fileID,dpData,H5P_DEFAULT);
				return fieldID;
			} else {
				return -1;
			}
		} else {
			/* relative path further along the path */
			snprintf(newPath,sizeof(newPath), "%s/%s", groupName, dpData);
			if(H5LTpath_valid(self->fileID,newPath,1)){
				fieldID = H5Oopen(self->fileID,newPath,H5P_DEFAULT);
				return fieldID;
			} else {
				return -1;
			}
		}
	} else {
		/* path within the group */
		groupID = H5Oopen(self->fileID, groupName,H5P_DEFAULT);
		if(H5LTfind_dataset(groupID,dpData)){
			fieldID = H5Dopen(groupID,dpData,H5P_DEFAULT);
			H5Oclose(groupID);
			return fieldID;
		} else {
			H5Oclose(groupID);
			return -1;
		}
	}

	return -1;
}
Exemplo n.º 4
0
H5Object & H5ReferenceData::getData(const unsigned int size, const unsigned int * index) const
{
    char * cdata = static_cast<char *>(data) + offset;
    void ** ref = 0;
    unsigned int pos = 0;
    unsigned int cumprod = 1;
    H5O_info_t info;
    H5Object * hobj;
    hid_t obj;
    hid_t file;
    ssize_t ssize;
    char * name = 0;
    std::string _name;

    for (unsigned int i = 0; i < size; i++)
    {
        pos += cumprod * index[i];
    }

    if (pos >= totalSize)
    {
        throw H5Exception(__LINE__, __FILE__, _("Invalid index."));
    }

    cdata += pos * (stride ? stride : dataSize);

    file = getFile().getH5Id();
    ref = &(((void **)cdata)[0]);
    obj = H5Rdereference(file, datasetReference ? H5R_DATASET_REGION : H5R_OBJECT, ref);
    if (obj < 0)
    {
        throw H5Exception(__LINE__, __FILE__, _("Cannot open object at the given position."));
    }

    ssize = H5Rget_name(file, datasetReference ? H5R_DATASET_REGION : H5R_OBJECT, ref, 0, 0);
    name = new char[ssize + 1];
    H5Rget_name(file, datasetReference ? H5R_DATASET_REGION : H5R_OBJECT, ref, name, ssize + 1);
    _name = std::string(name);
    delete[] name;

    H5Oget_info(obj, &info);
    switch (info.type)
    {
        case H5O_TYPE_GROUP:
            hobj = new H5Group(getParent(), obj, _name);
            break;
        case H5O_TYPE_DATASET:
            hobj = new H5Dataset(getParent(), obj, _name);
            break;
        case H5O_TYPE_NAMED_DATATYPE:
            hobj = new H5Type(getParent(), obj, _name);
            break;
        case H5O_TYPE_UNKNOWN:
        default:
            H5Oclose(obj);
            throw H5Exception(__LINE__, __FILE__, _("Unknown HDF5 object"));
    }

    return *hobj;
}
Exemplo n.º 5
0
/* This is a callback function for H5Literate(). 

The parameters of this callback function have the following values or
meanings:

g_id Group that serves as root of the iteration; same value as the
H5Lvisit group_id parameter

name Name of link, relative to g_id, being examined at current step of
the iteration

info H5L_info_t struct containing information regarding that link

op_data User-defined pointer to data required by the application in
processing the link; a pass-through of the op_data pointer provided
with the H5Lvisit function call

*/
herr_t
op_func (hid_t g_id, const char *name, const H5L_info_t *info, 
	 void *op_data)  
{
   hid_t id;
   H5I_type_t obj_type;

   strcpy((char *)op_data, name);
   if ((id = H5Oopen_by_addr(g_id, info->u.address)) < 0) ERR;

/* Using H5Ovisit is really slow. Use H5Iget_type for a fast
 * answer. */
/*    if (H5Ovisit(id, H5_INDEX_CRT_ORDER, H5_ITER_INC, obj_iter,  */
/* 		(void *)&obj_class) != 1) ERR; */

   if ((obj_type = H5Iget_type(id)) < 0) ERR;
   if (H5Oclose(id) < 0) ERR;

/* Turn this on to learn what type of object you've opened. */
/*    switch (obj_type) */
/*    { */
/*       case H5I_GROUP: */
/* 	 printf("group %s\n", name); */
/* 	 break; */
/*       case H5I_DATATYPE: */
/* 	 printf("type %s\n", name); */
/* 	 break; */
/*       case H5I_DATASET: */
/* 	 printf("data %s\n", name); */
/* 	 break; */
/*       default: */
/* 	 printf("unknown class\n"); */
/*    } */
   return 1;
}
Exemplo n.º 6
0
// Write complex attribute <attr_name> given by address <path>
char AH5_write_cpx_attr(hid_t loc_id, const char* path, char* attr_name, const AH5_complex_t wdata)
{
    char success = AH5_FALSE;
    hid_t attr_id = 0, cpx_filetype, cpx_memtype, object_id, space;
    hsize_t dims[1] = {1};

    cpx_filetype = AH5_H5Tcreate_cpx_filetype();
    cpx_memtype = AH5_H5Tcreate_cpx_memtype();
    space = H5Screate_simple (1, dims, NULL);

    if (AH5_path_valid(loc_id, path))
    {
        if ((object_id = H5Oopen(loc_id, path, H5P_DEFAULT)) >= 0)
        {
            if ((attr_id = H5Acreate(object_id, attr_name, cpx_filetype, space, H5P_DEFAULT, H5P_DEFAULT)) >= 0)
            {
                if (H5Awrite(attr_id, cpx_memtype, &wdata) >= 0)
                {
                    success = AH5_TRUE;
                }
                H5Aclose(attr_id);
            }
            H5Oclose(object_id);
        }
    }

    H5Sclose(space);
    H5Tclose(cpx_memtype);
    H5Tclose(cpx_filetype);

    return success;
}
Exemplo n.º 7
0
static herr_t
visit_link(hid_t g_id, const char *name, const H5L_info_t *info, 
	   void *op_data)  
{
   /* A positive return value causes the visit iterator to immediately
    * return that positive value, indicating short-circuit
    * success. The iterator can be restarted at the next group
    * member. */
   int ret = 1;
   hid_t id;
   
   strncpy(((struct nc_hdf5_link_info *)op_data)->name, name, NC_MAX_NAME);
   
   /* Open this critter. */
   if ((id = H5Oopen_by_addr(g_id, info->u.address)) < 0) 
      return NC_EHDFERR;
   
   /* Is this critter a group, type, data, attribute, or what? */
   if ((((struct nc_hdf5_link_info *)op_data)->obj_type = H5Iget_type(id)) < 0)
      ret = NC_EHDFERR;

   /* Close the critter to release resouces. */
   if (H5Oclose(id) < 0)
      return NC_EHDFERR;
   
   return ret;
}
Exemplo n.º 8
0
//-*****************************************************************************
void CloseObject( H5Node& iNode )
{
    if ( iNode.isValidObject() )
    {
        H5Oclose( iNode.getObject() );
        iNode.setObject( -1 );
    }
}
Exemplo n.º 9
0
herr_t H5Group::getLsInfo(hid_t g_id, const char * name, const H5L_info_t * info, void * op_data)
{
    H5O_info_t oinfo;
    herr_t err;
    hid_t obj;
    OpDataGetLs & opdata = *(OpDataGetLs *)op_data;

    switch (info->type)
    {
        case H5L_TYPE_SOFT:
            opdata.name->push_back(name);
            opdata.type->push_back("soft");
            break;
        case H5L_TYPE_EXTERNAL:
            opdata.name->push_back(name);
            opdata.type->push_back("external");
            break;
        case H5L_TYPE_HARD:
            obj = H5Oopen_by_addr(g_id, info->u.address);
            if (obj < 0)
            {
                return (herr_t) - 1;
            }

            err = H5Oget_info(obj, &oinfo);
            H5Oclose(obj);
            if (err < 0)
            {
                return (herr_t) - 1;
            }

            switch (oinfo.type)
            {
                case H5O_TYPE_GROUP:
                    opdata.name->push_back(name);
                    opdata.type->push_back("group");
                    break;
                case H5O_TYPE_DATASET:
                    opdata.name->push_back(name);
                    opdata.type->push_back("dataset");
                    break;
                case H5O_TYPE_NAMED_DATATYPE:
                    opdata.name->push_back(name);
                    opdata.type->push_back("type");
                    break;
                default:
                    return (herr_t) - 1;
            }
            break;
        default:
            return (herr_t) - 1;
    }

    return (herr_t)0;
}
Exemplo n.º 10
0
/*
 * Class:     hdf_hdf5lib_H5
 * Method:    _H5Oclose
 * Signature: (J)I
 */
JNIEXPORT jint JNICALL
Java_hdf_hdf5lib_H5__1H5Oclose
    (JNIEnv *env, jclass clss, jlong object_id)
{
    herr_t retVal = H5Oclose((hid_t)object_id);

    if (retVal < 0)
        h5libraryError(env);

    return (jint)retVal;
} /* end Java_hdf_hdf5lib_H5__1H5Oclose */
Exemplo n.º 11
0
/****if* H5Of/h5oclose_c
 * NAME
 *   h5oclose_c
 * PURPOSE
 *   Call H5Oclose
 * INPUTS
 *   object_id   - Object identifier  
 * RETURNS
 *   0 on success, -1 on failure
 * AUTHOR
 *   M. Scot Breitenfeld
 *   December 17, 2008
 * SOURCE
*/
int_f
nh5oclose_c ( hid_t_f *object_id )
/******/
{
  int_f ret_value=0;          /* Return value */
  
  if (H5Oclose((hid_t)*object_id) < 0)
    HGOTO_DONE(FAIL);
  
 done:
  return ret_value;
}
Exemplo n.º 12
0
herr_t H5Group::printLsInfo(hid_t g_id, const char * name, const H5L_info_t * info, void * op_data)
{
    H5O_info_t oinfo;
    herr_t err;
    H5Object * hobj = 0;
    hid_t obj = 0;
    OpDataPrintLs & opdata = *(OpDataPrintLs *)op_data;

    switch (info->type)
    {
        case H5L_TYPE_SOFT:
            hobj = new H5SoftLink(*opdata.parent, name);
            break;
        case H5L_TYPE_EXTERNAL:
            hobj = new H5ExternalLink(*opdata.parent, name);
            break;
        case H5L_TYPE_HARD:
            obj = H5Oopen(g_id, name, H5P_DEFAULT);
            err = H5Oget_info(obj, &oinfo);
            H5Oclose(obj);

            if (err < 0)
            {
                return (herr_t) - 1;
            }

            switch (oinfo.type)
            {
                case H5O_TYPE_GROUP:
                    hobj = new H5Group(*opdata.parent, name);
                    break;
                case H5O_TYPE_DATASET:
                    hobj = new H5Dataset(*opdata.parent, name);
                    break;
                case H5O_TYPE_NAMED_DATATYPE:
                    hobj = new H5Type(*opdata.parent, name);
                    break;
                default:
                    return (herr_t) - 1;
            }
            break;
        default:
            return (herr_t) - 1;
    }

    hobj->printLsInfo(*opdata.os);
    delete hobj;

    return (herr_t)0;
}
Exemplo n.º 13
0
/*
 * Class:     hdf_hdf5lib_H5
 * Method:    _H5Oclose
 * Signature: (J)I
 */
JNIEXPORT jint JNICALL
Java_hdf_hdf5lib_H5__1H5Oclose
    (JNIEnv *env, jclass clss, jlong object_id)
{
    herr_t retVal = FAIL;

    UNUSED(clss);

    if ((retVal = H5Oclose((hid_t)object_id)) < 0)
        H5_LIBRARY_ERROR(ENVONLY);

done:
    return (jint)retVal;
} /* end Java_hdf_hdf5lib_H5__1H5Oclose */
Exemplo n.º 14
0
H5Object & H5File::getRoot()
{
    hid_t obj = H5Oopen(getH5Id(), path.c_str(), H5P_DEFAULT);
    if (obj < 0)
    {
        throw H5Exception(__LINE__, __FILE__, _("Invalid path: %s"), path.c_str());
    }

    try
    {
        return H5Object::getObject(*this, obj);
    }
    catch (const H5Exception & /*e*/)
    {
        H5Oclose(obj);
        throw;
    }
}
Exemplo n.º 15
0
    void DCGroup::getEntriesInternal(H5Handle base, const std::string baseGroup,
            std::string baseName, VisitObjCBType *param)
    throw (DCException)
    {
        H5G_info_t group_info;
        H5Gget_info(base, &group_info);

        for (size_t i = 0; i < group_info.nlinks; ++i)
        {
            std::string currentBaseName = baseName;
            std::string currentEntryName = "";

            H5O_info_t obj_info;
            H5Oget_info_by_idx(base, ".", H5_INDEX_NAME, H5_ITER_INC, i, &obj_info, H5P_DEFAULT);

            if (param->entries)
            {
                ssize_t len_name = H5Lget_name_by_idx(base, ".", H5_INDEX_NAME,
                        H5_ITER_INC, i, NULL, 0, H5P_LINK_ACCESS_DEFAULT);
                char *link_name_c = new char[len_name + 1];
                H5Lget_name_by_idx(base, ".", H5_INDEX_NAME,
                        H5_ITER_INC, i, link_name_c, len_name + 1, H5P_LINK_ACCESS_DEFAULT);

                currentEntryName = std::string(link_name_c) + std::string("/");
                currentBaseName += currentEntryName;
                delete[] link_name_c;
            }

            if (obj_info.type == H5O_TYPE_GROUP)
            {
                hid_t group_id = H5Oopen_by_idx(base, ".", H5_INDEX_NAME, H5_ITER_INC, i, H5P_DEFAULT);
                getEntriesInternal(group_id, baseGroup, currentBaseName, param);
                H5Oclose(group_id);
            }

            if (obj_info.type == H5O_TYPE_DATASET)
            {
                if (param->entries)
                    param->entries[param->count].name = currentEntryName;

                param->count++;
            }
        }
    }
Exemplo n.º 16
0
/*-------------------------------------------------------------------------
 * Function:    flush_verification
 *
 * Purpose:     This function tries to open target object in the test file.
 *              It compares the success of the open function to the expected 
 *              value, and succeeds if they are equal and fails if they differ.
 *
 *              Note that full path to the object must be provided as the 
 *              obj_pathname argument.
 *
 * Return:      0 on Success, 1 on Failure
 *
 * Programmer:  Mike McGreevy
 *              July 16, 2010
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
herr_t flush_verification(const char * obj_pathname, const char * expected) 
{
    /* Variables */
    hid_t oid,fid,status = 0;
    H5O_info_t oinfo;

    /* Try to open the testfile and then obj_pathname within the file */
    H5E_BEGIN_TRY {
        fid = H5Fopen(FILENAME, H5F_ACC_SWMR_READ, H5P_DEFAULT);
        oid = H5Oopen(fid, obj_pathname, H5P_DEFAULT);
        status = H5Oget_info(oid, &oinfo);
    } H5E_END_TRY;

    /* Compare to expected result */
    if (strcmp(expected, FLUSHED) == 0) {
        if ((oid < 0) || (status < 0)) {
            HDfprintf(stderr, "Error! %s should be on disk, but was NOT!\n", obj_pathname);
            PROCESS_ERROR;
        } /* end if */
    } else if (strcmp(expected, NOT_FLUSHED) == 0) {
        if ((oid > 0) || (status > 0)) {
            HDfprintf(stderr, "Error! %s not expected to be flushed, but it was found on disk!\n", obj_pathname);
            PROCESS_ERROR;
        } /* end if */
    } else {
        HDfprintf(stderr, "Error! Bad verification parameters. %s is an invalid expected outcome.\n", expected);
        PROCESS_ERROR;
    } /* end if */

    /* Cleanup */
    H5E_BEGIN_TRY {
        H5Oclose(oid);
        H5Fclose(fid);
    } H5E_END_TRY;

    return SUCCEED;

error:
    return FAIL;

} /* flush_verification */
Exemplo n.º 17
0
/* UD_hard_delete
 * Since the creation function increments the object's reference count, it's
 * important to decrement it again when the link is deleted.
 */
static herr_t UD_hard_delete(const char *link_name, hid_t loc_group,
    const void *udata, size_t udata_size)
{
    haddr_t addr;
    hid_t target_obj = -1;
    herr_t ret_value = 0;

    /* Sanity check; we have already verified the udata's size in the creation
     * callback.
     */
    if(udata_size != sizeof(haddr_t))
    {
      ret_value = -1;
      goto done;
    }

    addr = *((const haddr_t *) udata);

    /* Open the object this link points to */
    target_obj= H5Oopen_by_addr(loc_group, addr);
    if(target_obj < 0)
    {
      ret_value = -1;
      goto done;
    }

    /* Decrement the reference count of the target object */
    if(H5Odecr_refcount(target_obj) < 0)
    {
      ret_value = -1;
      goto done;
    }

done:
    /* Close the target object if we opened it */
    if(target_obj >= 0)
        H5Oclose(target_obj);
    return ret_value;
}
Exemplo n.º 18
0
/* UD_hard_create
 * The most important thing this callback does is to increment the reference
 * count on the target object. Without this step, the object could be
 * deleted while this link still pointed to it, resulting in possible data
 * corruption!
 * The create callback also checks the arguments used to create this link.
 * If this function returns a negative value, the call to H5Lcreate_ud()
 * will also return failure and the link will not be created.
 */
static herr_t UD_hard_create(const char *link_name, hid_t loc_group,
    const void *udata, size_t udata_size, hid_t lcpl_id)
{
    haddr_t addr;
    hid_t target_obj = -1;
    herr_t ret_value = 0;

    /* Make sure that the address passed in looks valid */
    if(udata_size != sizeof(haddr_t))
    {
      ret_value = -1;
      goto done;
    }

    addr = *((const haddr_t *) udata);

    /* Open the object this link points to so that we can increment
     * its reference count. This also ensures that the address passed
     * in points to a real object (although this check is not perfect!) */
    target_obj= H5Oopen_by_addr(loc_group, addr);
    if(target_obj < 0)
    {
      ret_value = -1;
      goto done;
    }

    /* Increment the reference count of the target object */
    if(H5Oincr_refcount(target_obj) < 0)
    {
      ret_value = -1;
      goto done;
    }

done:
    /* Close the target object if we opened it */
    if(target_obj >= 0)
        H5Oclose(target_obj);
    return ret_value;
}
Exemplo n.º 19
0
void FileHDF5::close() {

    if (!isOpen())
        return;

    data.close();
    metadata.close();
    root.close();

    unsigned types = H5F_OBJ_GROUP|H5F_OBJ_DATASET|H5F_OBJ_DATATYPE;

    ssize_t obj_count = H5Fget_obj_count(hid, types);

    if (obj_count < 0) {
        throw H5Exception("FileHDF5::close(): Could not get object count");
    }

    std::vector<hid_t> objs(static_cast<size_t>(obj_count));

    if (obj_count > 0) {
        obj_count = H5Fget_obj_ids(hid, types, objs.size(), objs.data());

        if (obj_count < 0) {
            throw H5Exception("FileHDF5::close(): Could not get objs");
        }
    }

    for (auto obj : objs) {
        int ref_count = H5Iget_ref(obj);

        for (int j = 0; j < ref_count; j++) {
            H5Oclose(obj);
        }
    }

    H5Object::close();
}
Exemplo n.º 20
0
int
main (void)
{
    hid_t       file, space, dset, obj;     /* Handles */
    herr_t      status;
    hsize_t     dims[1] = {DIM0};
    hobj_ref_t  wdata[DIM0],                /* Write buffer */
                *rdata;                     /* Read buffer */
    H5O_type_t  objtype;
    ssize_t     size;
    char        *name;
    int         ndims,
                i;

    /*
     * Create a new file using the default properties.
     */
    file = H5Fcreate (FILE, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);

    /*
     * Create a dataset with a null dataspace.
     */
    space = H5Screate (H5S_NULL);
    obj = H5Dcreate (file, "DS2", H5T_STD_I32LE, space, H5P_DEFAULT,
                H5P_DEFAULT, H5P_DEFAULT);
    status = H5Dclose (obj);
    status = H5Sclose (space);

    /*
     * Create a group.
     */
    obj = H5Gcreate (file, "G1", H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
    status = H5Gclose (obj);

    /*
     * Create references to the previously created objects.  Passing -1
     * as space_id causes this parameter to be ignored.  Other values
     * besides valid dataspaces result in an error.
     */
    status = H5Rcreate (&wdata[0], file, "G1", H5R_OBJECT, -1);
    status = H5Rcreate (&wdata[1], file, "DS2", H5R_OBJECT, -1);

    /*
     * Create dataspace.  Setting maximum size to NULL sets the maximum
     * size to be the current size.
     */
    space = H5Screate_simple (1, dims, NULL);

    /*
     * Create the dataset and write the object references to it.
     */
    dset = H5Dcreate (file, DATASET, H5T_STD_REF_OBJ, space, H5P_DEFAULT,
                H5P_DEFAULT, H5P_DEFAULT);
    status = H5Dwrite (dset, H5T_STD_REF_OBJ, H5S_ALL, H5S_ALL, H5P_DEFAULT,
                wdata);

    /*
     * Close and release resources.
     */
    status = H5Dclose (dset);
    status = H5Sclose (space);
    status = H5Fclose (file);


    /*
     * Now we begin the read section of this example.  Here we assume
     * the dataset has the same name and rank, but can have any size.
     * Therefore we must allocate a new array to read in data using
     * malloc().
     */

    /*
     * Open file and dataset.
     */
    file = H5Fopen (FILE, H5F_ACC_RDONLY, H5P_DEFAULT);
    dset = H5Dopen (file, DATASET, H5P_DEFAULT);

    /*
     * Get dataspace and allocate memory for read buffer.
     */
    space = H5Dget_space (dset);
    ndims = H5Sget_simple_extent_dims (space, dims, NULL);
    rdata = (hobj_ref_t *) malloc (dims[0] * sizeof (hobj_ref_t));

    /*
     * Read the data.
     */
    status = H5Dread (dset, H5T_STD_REF_OBJ, H5S_ALL, H5S_ALL, H5P_DEFAULT,
                rdata);

    /*
     * Output the data to the screen.
     */
    for (i=0; i<dims[0]; i++) {
        printf ("%s[%d]:\n  ->", DATASET, i);

        /*
         * Open the referenced object, get its name and type.
         */
        obj = H5Rdereference (dset, H5R_OBJECT, &rdata[i]);
        status = H5Rget_obj_type (dset, H5R_OBJECT, &rdata[i], &objtype);

        /*
         * Get the length of the name, allocate space, then retrieve
         * the name.
         */
        size = 1 + H5Iget_name (obj, NULL, 0);
        name = (char *) malloc (size);
        size = H5Iget_name (obj, name, size);

        /*
         * Print the object type and close the object.
         */
        switch (objtype) {
            case H5O_TYPE_GROUP:
                printf ("Group");
                break;
            case H5O_TYPE_DATASET:
                printf ("Dataset");
                break;
            case H5O_TYPE_NAMED_DATATYPE:
                printf ("Named Datatype");
        }
        status = H5Oclose (obj);

        /*
         * Print the name and deallocate space for the name.
         */
        printf (": %s\n", name);
        free (name);
    }

    /*
     * Close and release resources.
     */
    free (rdata);
    status = H5Dclose (dset);
    status = H5Sclose (space);
    status = H5Fclose (file);

    return 0;
}
Exemplo n.º 21
0
SWIGEXPORT hid_t JNICALL Java_permafrost_hdf_libhdf_ObjectLibExtensionJNI_JHOopen_1by_1idx(
	JNIEnv *jenv, 
	jclass jcls, 
	jint loc_id, 
	jstring group_name,
	jint idx_type, 
	jint order, 
	jlong n, 
	jint lapl_id, 
	jintArray type, 
	jobjectArray name
	) {
		jint sz = 0;
		char* pGroupName = NULL;
		hid_t obj_id = -1;
		jint jiType;
		char* pName = NULL;
		char* tmpName = NULL;
		const int szName = 64;
		int lenName = 0;
		jstring jname;

		if (!group_name) {
			SWIG_JavaThrowException(jenv, SWIG_JavaIllegalArgumentException, "Null group name.");
			return (-1);
		} else if (!type) {
			SWIG_JavaThrowException(jenv, SWIG_JavaIllegalArgumentException, "Null type array.");
			return (-1);
		} else if (!name) {
			SWIG_JavaThrowException(jenv, SWIG_JavaIllegalArgumentException, "Null object name array.");
			return (-1);
		}
		sz = (*jenv)->GetArrayLength(jenv, type);
		if (sz < 1) {
			SWIG_JavaThrowException(jenv, SWIG_JavaIllegalArgumentException, "Zero-length type array.");
			return (-1);
		}
		sz = (*jenv)->GetArrayLength(jenv, name);
		if (sz < 1) {
			SWIG_JavaThrowException(jenv, SWIG_JavaIllegalArgumentException, "Zero-length object name array.");
			return (-1);
		}

		pGroupName = (char *)(*jenv)->GetStringUTFChars(jenv, group_name, 0);
		if (!pGroupName) return -1;
		
		obj_id = H5Oopen_by_idx(
			(hid_t)loc_id, 
			pGroupName, 
			(H5_index_t) idx_type, 
			(H5_iter_order_t) order,
			(hsize_t) n, 
			(hid_t) lapl_id
			);

		if (pGroupName) (*jenv)->ReleaseStringUTFChars(jenv, group_name, (const char *) pGroupName);
		if (obj_id <= 0) return (obj_id);

		jiType = (jint) H5Iget_type(obj_id);
		(*jenv)->SetIntArrayRegion(jenv, type, 0, 1, &jiType);

		pName = (char*) calloc(szName, sizeof(char));
		lenName = H5Iget_name(obj_id, pName, szName-1);
		if (lenName >= szName) {
			char* tmpName = (char*) realloc(pName, sizeof(char)*lenName+1);
			if (!tmpName) {
				free(pName);
				pName = NULL;
				H5Oclose(loc_id);
				return (-1);
			}
			pName = tmpName;
			lenName = H5Iget_name(obj_id, pName, lenName);
		}
		jname = (*jenv)->NewStringUTF(jenv, pName);
		(*jenv)->SetObjectArrayElement(jenv, name, 0, jname);
		
		free(pName);
		
		return (obj_id);
}
Exemplo n.º 22
0
/*--------------------------------------------------------------*/
static void validateLink(pNXVcontext self, hid_t groupID,
		xmlChar *name, xmlChar *target)
{
	hid_t objID;
	herr_t att;
	char linkTarget[512], dataPath[512];
  char nxdlPath[512], curPath[512];

	/*
		set our path for correct error printing
	*/
	snprintf(nxdlPath,sizeof(nxdlPath),"%s/%s", self->nxdlPath,
		(char *)name);
	NXVsetLog(self,"nxdlPath",nxdlPath);
	H5Iget_name(groupID,curPath,sizeof(curPath));
	snprintf(dataPath,sizeof(dataPath),"%s/%s", curPath,
		(char *)name);
	NXVsetLog(self,"dataPath",dataPath);

	/*
		log what we are doing
	*/
	NXVsetLog(self,"sev","debug");
	NXVprintLog(self,"message","Validating link %s at %s",
		(char *)name, (char *)target);
	NXVlog(self);

	/*
		now we really validate
	*/
	if(H5LTpath_valid(groupID,(char *)name, 1)){
		/*
		  The positive test means that the link exists and is pointing to
			a valid HDF5 object. This is alread good.
		*/
		objID = H5Oopen(groupID,(char *)name,H5P_DEFAULT);
		assert(objID >= 0); /* we just tested for existence, didn't we? */
		memset(linkTarget,0,sizeof(linkTarget));
		att = H5NXget_attribute_string(groupID,(char *)name,"target",linkTarget);
		if(att < 0){
				NXVsetLog(self,"sev","error");
				H5Iget_name(objID,dataPath,sizeof(dataPath));
				NXVsetLog(self,"dataPath",dataPath);
				NXVsetLog(self,"message","Link is missing required attribute target");
				NXVlog(self);
				self->errCount++;
		} else {
			/*
				test that the target attribute really points to something
				real. It could be that the link was done right but the
				target attribute set sloppily.
			*/
			if(!H5LTpath_valid(self->fileID,linkTarget,1)){
				NXVsetLog(self,"sev","error");
				H5Iget_name(objID,dataPath,sizeof(dataPath));
				NXVsetLog(self,"dataPath",dataPath);
				NXVprintLog(self,"message","Link target %s is invalid",
					linkTarget);
				NXVlog(self);
				self->errCount++;
			} else {
				validateLinkTarget(self,target,linkTarget);
			}
		}
		H5Oclose(objID);
	} else {
		NXVsetLog(self,"sev","error");
		NXVprintLog(self,"message",
			"Required link %s missing or not pointing to an HDF5 object",
			(char *)name);
		NXVlog(self);
		self->errCount++;
	}
}
Exemplo n.º 23
0
/**
 * Reads an array of double attributes from the HDF5 metadata.
 * It reads the attributes directly on its binary form directly,
 * thus avoiding string conversions.
 *
 * Important: It allocates the memory for the attributes internally,
 * so the caller must free the returned array after using it.
 * @param pszAttrName Name of the attribute to be read.
 *        the attribute name must be the form:
 *            root attribute name
 *            SUBDATASET/subdataset attribute name
 * @param pdfValues pointer which will store the array of doubles read.
 * @param nLen it stores the length of the array read. If NULL it doesn't
 *        inform the length of the array.
 * @return CPLErr CE_None in case of success, CE_Failure in case of failure
 */
CPLErr HDF5Dataset::HDF5ReadDoubleAttr(const char *pszAttrFullPath,
                                       double **pdfValues, int *nLen)
{
    CPLString osAttrFullPath(pszAttrFullPath);

    // Search for the last "/" in order to get the path to the attribute.
    const size_t nSlashPos = osAttrFullPath.find_last_of("/");

    CPLString osObjName;
    CPLString osAttrName;

    // If objects name have been found.
    if( nSlashPos != CPLString::npos )
    {
        // Split Object name (dataset, group).
        osObjName = osAttrFullPath.substr(0, nSlashPos);
        // Split attribute name.
        osAttrName = osAttrFullPath.substr(nSlashPos + 1);
    }
    else
    {
        // By default the group is root, and
        // the attribute is the full path.
        osObjName = "/";
        osAttrName = pszAttrFullPath;
    }

    const hid_t hObjAttrID = H5Oopen(hHDF5, osObjName.c_str(), H5P_DEFAULT);

    CPLErr retVal = CE_Failure;

    if(hObjAttrID < 0)
    {
        CPLError(CE_Failure, CPLE_OpenFailed,
                 "Object %s could not be opened", pszAttrFullPath);
        retVal = CE_Failure;
    }
    else
    {
        // Open attribute handler by name, from the object handler opened
        // earlier.
        const hid_t hAttrID = H5Aopen_name(hObjAttrID, osAttrName.c_str());

        // Check for errors opening the attribute.
        if( hAttrID < 0 )
        {
            CPLError(CE_Failure, CPLE_OpenFailed,
                     "Attribute %s could not be opened", pszAttrFullPath);
            retVal = CE_Failure;
        }
        else
        {
            const hid_t hAttrTypeID = H5Aget_type(hAttrID);
            const hid_t hAttrNativeType =
                H5Tget_native_type(hAttrTypeID, H5T_DIR_DEFAULT);
            const hid_t hAttrSpace = H5Aget_space(hAttrID);
            hsize_t nSize[64] = {};
            const unsigned int nAttrDims =
                H5Sget_simple_extent_dims(hAttrSpace, nSize, nullptr);

            if( !H5Tequal(H5T_NATIVE_DOUBLE, hAttrNativeType) )
            {
                CPLError(CE_Failure, CPLE_OpenFailed,
                         "Attribute %s is not of type double",
                         pszAttrFullPath);
                retVal = CE_Failure;
            }
            else
            {
                // Get the amount of elements.
                unsigned int nAttrElmts = 1;
                for( hsize_t i = 0; i < nAttrDims; i++ )
                {
                    // For multidimensional attributes
                    nAttrElmts *= static_cast<unsigned int>(nSize[i]);
                }

                if(nLen != nullptr)
                    *nLen = nAttrElmts;

                *pdfValues = static_cast<double *>(
                    CPLMalloc(nAttrElmts * sizeof(double)));

                // Read the attribute contents
                if( H5Aread(hAttrID, hAttrNativeType, *pdfValues) < 0 )
                {
                    CPLError(CE_Failure, CPLE_OpenFailed,
                             "Attribute %s could not be opened",
                             pszAttrFullPath);
                    retVal = CE_Failure;
                }
                else
                {
                    retVal = CE_None;
                }
            }

            H5Tclose(hAttrNativeType);
            H5Tclose(hAttrTypeID);
            H5Sclose(hAttrSpace);
            H5Aclose(hAttrID);
        }
        H5Oclose(hObjAttrID);
    }

    return retVal;
}
Exemplo n.º 24
0
int VsFilter::visitLinks(hid_t locId, const char* name,
    const H5L_info_t *linfo, void* opdata) {
  VsLog::debugLog() <<"VsFilter::visitLinks() - looking at object " <<name <<std::endl;
  
  switch (linfo->type) {
    case H5L_TYPE_HARD: {

      H5O_info_t objinfo;

      /* Stat the object */
      if(H5Oget_info_by_name(locId, name, &objinfo, H5P_DEFAULT) < 0) {
        VsLog::errorLog() <<"VsFilter::visitLinks() - unable to open object with name " <<name <<std::endl;
        VsLog::errorLog() <<"VsFilter::visitLinks() - this object and all children will be dropped." <<std::endl;
        return 0;
      }

      switch(objinfo.type)
      {
        case H5O_TYPE_GROUP:
        return visitGroup( locId, name, opdata );
        break;
        case H5O_TYPE_DATASET:
        return visitDataset( locId, name, opdata );
        break;

        default:
        VsLog::debugLog() << "VsFilter::visitLinks: node '" << name <<
        "' has an unknown type " << objinfo.type << std::endl;
        break;
      }
    }
    break;
    //end of case H5L_TYPE_HARD
    case H5L_TYPE_EXTERNAL: {

      char *targbuf = (char*) malloc( linfo->u.val_size );

      if (H5Lget_val(locId, name, targbuf, linfo->u.val_size, H5P_DEFAULT) < 0) {
        VsLog::errorLog() <<"VsFilter::visitLinks() - unable to open external link with name " <<targbuf <<std::endl;
        VsLog::errorLog() <<"VsFilter::visitLinks() - this object and all children will be dropped." <<std::endl;
        return 0;
      }
      
      const char *filename;
      const char *targname;

      if (H5Lunpack_elink_val(targbuf, linfo->u.val_size, 0, &filename, &targname) < 0) {
        VsLog::errorLog() <<"VsFilter::visitLinks() - unable to open external file with name " <<filename <<std::endl;
        VsLog::errorLog() <<"VsFilter::visitLinks() - this object and all children will be dropped." <<std::endl;
        return 0;
      }
      
      VsLog::debugLog() << "VsFilter::visitLinks(): node '" << name << "' is an external link." << std::endl;
      VsLog::debugLog() << "VsFilter::visitLinks(): node '" << targname << "' is an external target group." << std::endl;

      free(targbuf);
      targbuf = NULL;
      
      // Get info of the linked object.
      H5O_info_t objinfo;
#ifndef H5_USE_16_API
      hid_t obj_id = H5Oopen(locId, name, H5P_DEFAULT);
#else
      hid_t obj_id = H5Oopen(locId, name);        
#endif
      
      if (obj_id < 0) {
        VsLog::errorLog() <<"VsFilter::visitLinks() - unable to get id for external object " <<name <<std::endl;
        VsLog::errorLog() <<"VsFilter::visitLinks() - this object and all children will be dropped." <<std::endl;
        return 0;
      }

      //Test-open the linked object
      if (H5Oget_info (obj_id, &objinfo) < 0) {
        VsLog::errorLog() <<"VsFilter::visitLinks() - unable to open external object " <<name <<std::endl;
        VsLog::errorLog() <<"VsFilter::visitLinks() - this object and all children will be dropped." <<std::endl;
        return 0;
      }
      
      //Close the linked object to release hdf5 id
      H5Oclose( obj_id );

      //Finally, decide what to do depending on what type of object this is
      switch(objinfo.type)
      {
        case H5O_TYPE_GROUP:
        return visitGroup( locId, name, opdata );
        break;
        case H5O_TYPE_DATASET:
        return visitDataset( locId, name, opdata );
        break;

        default:
          VsLog::debugLog() << "VsFilter::visitLinks: node '" << name <<
        "' has an unknown type " << objinfo.type << std::endl;
        break;
      }
    }
    break;
      //END OF CASE H5L_TYPE_EXTERNAL
    
    default:
    VsLog::debugLog() << "VsFilter::visitLinks: node '" << name <<
    "' has an unknown object type " << linfo->type << std::endl;
    break;
  }

  return 0;
}
Exemplo n.º 25
0
/*-------------------------------------------------------------------------
 * Function:    refresh_verification
 *
 * Purpose:     This function opens the specified object, and checks to see
 *              that is does not have any attributes on it. It then sends
 *              a signal to the main process, which will flush the object
 *              (putting an attribute on the object on disk). This function
 *              will then refresh the object, and verify that it has picked
 *              up the new metadata reflective of the added attribute.
 *
 * Return:      0 on Success, 1 on Failure
 *
 * Programmer:  Mike McGreevy
 *              July 16, 2010
 *
 * Modifications:
 *
 *-------------------------------------------------------------------------
 */
herr_t refresh_verification(const char * obj_pathname) 
{
    /* Variables */
    hid_t oid,fid,status = 0;
    H5O_info_t flushed_oinfo;
    H5O_info_t refreshed_oinfo;
    
    /* Open Object */
    if ((fid = H5Fopen(FILENAME, H5F_ACC_SWMR_READ, H5P_DEFAULT)) < 0) PROCESS_ERROR;
    if ((oid = H5Oopen(fid, obj_pathname, H5P_DEFAULT)) < 0) PROCESS_ERROR;

    /* Get Object info */
    if ((status = H5Oget_info(oid, &flushed_oinfo)) < 0) PROCESS_ERROR;
    
    /* Make sure there are no attributes on the object. This is just a sanity
        check to ensure we didn't erroneously flush the attribute before
        starting the verification. */
    if (flushed_oinfo.num_attrs != 0) PROCESS_ERROR;

    /* Send Signal to MAIN PROCESS indicating that it can go ahead and modify the 
        object. */
    send_signal(SIGNAL_BETWEEN_PROCESSES_1, NULL, NULL);

    /* Wait for Signal from MAIN PROCESS indicating that it's modified the 
        object and we can run verification now. */
    if (wait_for_signal(SIGNAL_BETWEEN_PROCESSES_2) < 0) PROCESS_ERROR;

    /* Get object info again. This will NOT reflect what's on disk, only what's 
       in the cache. Thus, all values will be unchanged from above, despite 
       newer information being on disk. */
    if ((status = H5Oget_info(oid, &refreshed_oinfo)) < 0) PROCESS_ERROR;

    /* Verify that before doing a refresh, getting the object info returns stale
       information. (i.e., unchanged from above, despite new info on disk). */
    if (flushed_oinfo.addr != refreshed_oinfo.addr) PROCESS_ERROR;
    if (flushed_oinfo.type != refreshed_oinfo.type) PROCESS_ERROR;
    if (flushed_oinfo.hdr.version != refreshed_oinfo.hdr.version) PROCESS_ERROR;
    if (flushed_oinfo.hdr.flags != refreshed_oinfo.hdr.flags) PROCESS_ERROR;
    if (flushed_oinfo.num_attrs != refreshed_oinfo.num_attrs) PROCESS_ERROR;
    if (flushed_oinfo.hdr.nmesgs != refreshed_oinfo.hdr.nmesgs) PROCESS_ERROR;
    if (flushed_oinfo.hdr.nchunks != refreshed_oinfo.hdr.nchunks) PROCESS_ERROR;
    if (flushed_oinfo.hdr.space.total != refreshed_oinfo.hdr.space.total) PROCESS_ERROR;

    /* Refresh object */
    /* The H5*refresh function called depends on which object we are trying
     * to refresh. (MIKE: add desired refresh call as parameter so adding new
     * test cases is easy). */
    if ((strcmp(obj_pathname, D1) == 0) || 
        (strcmp(obj_pathname, D2) == 0)) {
        if (H5Drefresh(oid) < 0) PROCESS_ERROR;
    } /* end if */
    else if ((strcmp(obj_pathname, G1) == 0) || 
        (strcmp(obj_pathname, G2) == 0)) {
        if (H5Grefresh(oid) < 0) PROCESS_ERROR;
    } /* end if */
    else if ((strcmp(obj_pathname, T1) == 0) || 
        (strcmp(obj_pathname, T2) == 0)) {
        if (H5Trefresh(oid) < 0) PROCESS_ERROR;
    } /* end if */
    else if ((strcmp(obj_pathname, D3) == 0) || 
        (strcmp(obj_pathname, G3) == 0) ||
        (strcmp(obj_pathname, T3) == 0)) {
        if (H5Orefresh(oid) < 0) PROCESS_ERROR;
    } /* end if */
    else {
        HDfprintf(stdout, "Error. %s is an unrecognized object.\n", obj_pathname);
        PROCESS_ERROR;
    } /* end else */

    /* Get object info. This should now accurately reflect the refreshed object on disk. */
    if ((status = H5Oget_info(oid, &refreshed_oinfo)) < 0) PROCESS_ERROR;
    
    /* Confirm following attributes are the same: */
    if (flushed_oinfo.addr != refreshed_oinfo.addr) PROCESS_ERROR;
    if (flushed_oinfo.type != refreshed_oinfo.type) PROCESS_ERROR;
    if (flushed_oinfo.hdr.version != refreshed_oinfo.hdr.version) PROCESS_ERROR;
    if (flushed_oinfo.hdr.flags != refreshed_oinfo.hdr.flags) PROCESS_ERROR;

    /* Confirm following attributes are different */
    if (flushed_oinfo.num_attrs == refreshed_oinfo.num_attrs) PROCESS_ERROR;
    if (flushed_oinfo.hdr.nmesgs == refreshed_oinfo.hdr.nmesgs) PROCESS_ERROR;
    if (flushed_oinfo.hdr.nchunks == refreshed_oinfo.hdr.nchunks) PROCESS_ERROR;
    if (flushed_oinfo.hdr.space.total == refreshed_oinfo.hdr.space.total) PROCESS_ERROR;

    /* Close objects */
    if (H5Oclose(oid) < 0) PROCESS_ERROR;
    if (H5Fclose(fid) < 0) PROCESS_ERROR;

    /* Return */
    return SUCCEED;

error:

    return FAIL;

} /* refresh_verification */
Exemplo n.º 26
0
void H5ReferenceData::printData(std::ostream & os, const unsigned int pos, const unsigned int indentLevel) const
{
    char * cdata = static_cast<char *>(data) + offset + pos * (stride ? stride : dataSize);
    void ** ref = &(((void **)cdata)[0]);
    hid_t file = getFile().getH5Id();
    hid_t obj = H5Rdereference(file, datasetReference ? H5R_DATASET_REGION : H5R_OBJECT, ref);
    if (obj < 0)
    {
        os << "NULL";
        return;
    }

    ssize_t size = H5Rget_name(file, datasetReference ? H5R_DATASET_REGION : H5R_OBJECT, ref, 0, 0);
    char * name = 0;
    H5O_info_t info;

    if (size != -1)
    {
        name = new char[size + 1];
        H5Rget_name(file, datasetReference ? H5R_DATASET_REGION : H5R_OBJECT, ref, name, size + 1);

        if (datasetReference == H5R_OBJECT)
        {
            H5Oget_info(obj, &info);
            H5Oclose(obj);

            switch (info.type)
            {
                case H5O_TYPE_GROUP:
                    os << "GROUP ";
                    break;
                case H5O_TYPE_DATASET:
                    os << "DATASET ";
                    break;
                case H5O_TYPE_NAMED_DATATYPE:
                    os << "DATATYPE ";
                    break;
                case H5O_TYPE_UNKNOWN:
                default:
                    if (size != -1)
                    {
                        delete[] name;
                    }
                    throw H5Exception(__LINE__, __FILE__, _("Unknown HDF5 object"));
            }

            os << (haddr_t)(*ref) << " " << name;
        }
        else
        {
            hid_t space = H5Rget_region(file, H5R_DATASET_REGION, ref);
            hssize_t npoints = H5Sget_select_elem_npoints(space);
            hsize_t ndims = H5Sget_simple_extent_dims(space, 0, 0);
            H5Oclose(obj);

            os << "DATASET " << name << " {";

            if (npoints >= 0)
            {
                const hsize_t N = ndims * npoints;
                hsize_t * buf = new hsize_t[N];
                herr_t err =  H5Sget_select_elem_pointlist(space, 0, npoints, buf);
                for (hssize_t i = 0; i < (hssize_t)N; i += ndims)
                {
                    os << "(";
                    for (unsigned int j = 0; j < ndims - 1; j++)
                    {
                        os << buf[i + j] << ",";
                    }
                    os << buf[i + ndims - 1] << ")";

                    if (i != N - ndims)
                    {
                        os << ", ";
                    }
                    else
                    {
                        os << "}";
                    }
                }
                delete[] buf;
            }
            else
            {
                hssize_t nblocks = H5Sget_select_hyper_nblocks(space);
                if (nblocks >= 0)
                {
                    const hsize_t N = 2 * ndims * nblocks;
                    hsize_t * buf = new hsize_t[N];
                    herr_t err = H5Sget_select_hyper_blocklist(space, 0, nblocks, buf);
                    for (hssize_t i = 0; i < (hssize_t)N; i += 2 * ndims)
                    {
                        os << "(";
                        for (unsigned int j = 0; j < ndims - 1; j++)
                        {
                            os << buf[i + j] << ",";
                        }
                        os << buf[i + ndims - 1] << ")-(";
                        for (unsigned int j = 0; j < ndims - 1; j++)
                        {
                            os << buf[i + ndims + j] << ",";
                        }
                        os << buf[i + 2 * ndims - 1] << ")";

                        if (i != N - 2 * ndims)
                        {
                            os << ", ";
                        }
                        else
                        {
                            os << "}";
                        }
                    }

                    delete[] buf;
                }
            }

            H5Sclose(space);
        }

        delete[] name;
    }
}
Exemplo n.º 27
0
int do_copy_refobjs(hid_t fidin,
                    hid_t fidout,
                    trav_table_t *travt,
                    pack_opt_t *options) /* repack options */
{
    hid_t     grp_in = (-1);          /* read group ID */
    hid_t     grp_out = (-1);         /* write group ID */
    hid_t     dset_in = (-1);         /* read dataset ID */
    hid_t     dset_out = (-1);        /* write dataset ID */
    hid_t     type_in = (-1);         /* named type ID */
    hid_t     dcpl_id = (-1);         /* dataset creation property list ID */
    hid_t     space_id = (-1);        /* space ID */
    hid_t     ftype_id = (-1);        /* file data type ID */
    hid_t     mtype_id = (-1);        /* memory data type ID */
    size_t    msize;                  /* memory size of memory type */
    hsize_t   nelmts;                 /* number of elements in dataset */
    int       rank;                   /* rank of dataset */
    hsize_t   dims[H5S_MAX_RANK];     /* dimensions of dataset */
    unsigned int i, j;
    int       k;
    named_dt_t *named_dt_head=NULL;   /* Pointer to the stack of named datatypes
                                         copied */

    /*-------------------------------------------------------------------------
    * browse
    *-------------------------------------------------------------------------
    */
    for(i = 0; i < travt->nobjs; i++) {
        switch(travt->objs[i].type)
        {
            /*-------------------------------------------------------------------------
            * H5TRAV_TYPE_GROUP
            *-------------------------------------------------------------------------
            */
            case H5TRAV_TYPE_GROUP:
                /*-------------------------------------------------------------------------
                * copy referenced objects in attributes
                *-------------------------------------------------------------------------
                */
                if((grp_out = H5Gopen2(fidout, travt->objs[i].name, H5P_DEFAULT)) < 0)
                    goto error;

                if((grp_in = H5Gopen2(fidin, travt->objs[i].name, H5P_DEFAULT)) < 0)
                    goto error;

                if(copy_refs_attr(grp_in, grp_out, options, travt, fidout) < 0)
                    goto error;

                if(H5Gclose(grp_out) < 0)
                    goto error;
                if(H5Gclose(grp_in) < 0)
                    goto error;

                /*-------------------------------------------------------------------------
                * check for hard links
                *-------------------------------------------------------------------------
                */
                if(travt->objs[i].nlinks)
                    for(j = 0; j < travt->objs[i].nlinks; j++)
                        H5Lcreate_hard(fidout, travt->objs[i].name, H5L_SAME_LOC, travt->objs[i].links[j].new_name, H5P_DEFAULT, H5P_DEFAULT);
                break;

            /*-------------------------------------------------------------------------
            * H5TRAV_TYPE_DATASET
            *-------------------------------------------------------------------------
            */
            case H5TRAV_TYPE_DATASET:
                if((dset_in = H5Dopen2(fidin, travt->objs[i].name, H5P_DEFAULT)) < 0)
                    goto error;
                if((space_id = H5Dget_space(dset_in)) < 0)
                    goto error;
                if((ftype_id = H5Dget_type(dset_in)) < 0)
                    goto error;
                if((dcpl_id = H5Dget_create_plist(dset_in)) < 0)
                    goto error;
                if((rank = H5Sget_simple_extent_ndims(space_id)) < 0)
                    goto error;
                if(H5Sget_simple_extent_dims(space_id, dims, NULL) < 0)
                    goto error;
                nelmts = 1;
                for(k = 0; k < rank; k++)
                    nelmts *= dims[k];

                if((mtype_id = h5tools_get_native_type(ftype_id)) < 0)
                    goto error;

                if((msize = H5Tget_size(mtype_id)) == 0)
                    goto error;

                /*-------------------------------------------------------------------------
                 * check if the dataset creation property list has filters that
                 * are not registered in the current configuration
                 * 1) the external filters GZIP and SZIP might not be available
                 * 2) the internal filters might be turned off
                 *-------------------------------------------------------------------------
                 */
                if(h5tools_canreadf(NULL, dcpl_id) == 1) {
                    /*-------------------------------------------------------------------------
                    * test for a valid output dataset
                    *-------------------------------------------------------------------------
                    */
                    dset_out = FAIL;

                    /*-------------------------------------------------------------------------
                    * object references are a special case
                    * we cannot just copy the buffers, but instead we recreate the reference
                    *-------------------------------------------------------------------------
                    */
                    if(H5Tequal(mtype_id, H5T_STD_REF_OBJ)) {
                        hid_t            refobj_id;
                        hobj_ref_t       *refbuf = NULL; /* buffer for object references */
                        hobj_ref_t       *buf = NULL;
                        const char*      refname;
                        unsigned         u;

                        /*-------------------------------------------------------------------------
                        * read to memory
                        *-------------------------------------------------------------------------
                        */
                        if(nelmts) {
                            buf = (hobj_ref_t *)HDmalloc((unsigned)(nelmts * msize));
                            if(buf==NULL) {
                                printf("cannot read into memory\n" );
                                goto error;
                            } /* end if */
                            if(H5Dread(dset_in, mtype_id, H5S_ALL, H5S_ALL, H5P_DEFAULT, buf) < 0)
                                goto error;

                            refbuf = (hobj_ref_t*) HDcalloc((unsigned)nelmts, msize);
                            if(refbuf == NULL){
                                printf("cannot allocate memory\n" );
                                goto error;
                            } /* end if */
                            for(u = 0; u < nelmts; u++) {
                                H5E_BEGIN_TRY {
                                    if((refobj_id = H5Rdereference(dset_in, H5R_OBJECT, &buf[u])) < 0)
                                        continue;
                                } H5E_END_TRY;

                                /* get the name. a valid name could only occur
                                 * in the second traversal of the file
                                 */
                                if((refname = MapIdToName(refobj_id, travt)) != NULL) {
                                    /* create the reference, -1 parameter for objects */
                                    if(H5Rcreate(&refbuf[u], fidout, refname, H5R_OBJECT, -1) < 0)
                                        goto error;
                                    if(options->verbose)
                                    {


                                        printf(FORMAT_OBJ,"dset",travt->objs[i].name );
                                        printf("object <%s> object reference created to <%s>\n",
                                            travt->objs[i].name,
                                            refname);
                                    }
                                } /*refname*/
                                H5Oclose(refobj_id);
                            } /* u */
                        } /*nelmts*/

                        /*-------------------------------------------------------------------------
                        * create/write dataset/close
                        *-------------------------------------------------------------------------
                        */
                        if((dset_out = H5Dcreate2(fidout, travt->objs[i].name, mtype_id, space_id, H5P_DEFAULT, dcpl_id, H5P_DEFAULT)) < 0)
                            goto error;
                        if(nelmts)
                            if(H5Dwrite(dset_out, mtype_id, H5S_ALL, H5S_ALL, H5P_DEFAULT, refbuf) < 0)
                                goto error;

                        if(buf)
                            HDfree(buf);
                        if(refbuf)
                            HDfree(refbuf);

                       /*------------------------------------------------------
                        * copy attrs
                        *----------------------------------------------------*/
                        if(copy_attr(dset_in, dset_out, &named_dt_head, travt, options) < 0)
                            goto error;
                    } /*H5T_STD_REF_OBJ*/

                    /*-------------------------------------------------------------------------
                    * dataset region references
                    *-------------------------------------------------------------------------
                    */
                    else if(H5Tequal(mtype_id, H5T_STD_REF_DSETREG)) 
                    {
                        hid_t            refobj_id;
                        hdset_reg_ref_t  *refbuf = NULL; /* input buffer for region references */
                        hdset_reg_ref_t  *buf = NULL;    /* output buffer */
                        const char*      refname;
                        unsigned         u;

                        /*-------------------------------------------------------------------------
                        * read input to memory
                        *-------------------------------------------------------------------------
                        */
                        if(nelmts) {
                            buf = (hdset_reg_ref_t *)HDmalloc((unsigned)(nelmts * msize));
                            if(buf == NULL) {
                                printf("cannot read into memory\n");
                                goto error;
                            } /* end if */
                            if(H5Dread(dset_in, mtype_id, H5S_ALL, H5S_ALL, H5P_DEFAULT, buf) < 0)
                                goto error;

                            /*-------------------------------------------------------------------------
                            * create output
                            *-------------------------------------------------------------------------
                            */
                            refbuf = (hdset_reg_ref_t *)HDcalloc(sizeof(hdset_reg_ref_t), (size_t)nelmts); /*init to zero */
                            if(refbuf == NULL) {
                                printf("cannot allocate memory\n");
                                goto error;
                            } /* end if */

                            for(u = 0; u < nelmts; u++) {
                                H5E_BEGIN_TRY {
                                    if((refobj_id = H5Rdereference(dset_in, H5R_DATASET_REGION, &buf[u])) < 0)
                                        continue;
                                } H5E_END_TRY;

                                /* get the name. a valid name could only occur
                                 * in the second traversal of the file
                                 */
                                if((refname = MapIdToName(refobj_id, travt)) != NULL) {
                                    hid_t region_id;    /* region id of the referenced dataset */

                                    if((region_id = H5Rget_region(dset_in, H5R_DATASET_REGION, &buf[u])) < 0)
                                        goto error;

                                    /* create the reference, we need the space_id */
                                    if(H5Rcreate(&refbuf[u], fidout, refname, H5R_DATASET_REGION, region_id) < 0)
                                        goto error;
                                    if(H5Sclose(region_id) < 0)
                                        goto error;
                                    if(options->verbose)
                                    {



                                        printf(FORMAT_OBJ,"dset",travt->objs[i].name );
                                        printf("object <%s> region reference created to <%s>\n",
                                            travt->objs[i].name,
                                            refname);
                                    }
                                } /*refname*/
                                H5Oclose(refobj_id);
                            } /* u */
                        } /*nelmts*/

                        /*-------------------------------------------------------------------------
                        * create/write dataset/close
                        *-------------------------------------------------------------------------
                        */
                        if((dset_out = H5Dcreate2(fidout, travt->objs[i].name, mtype_id, space_id, H5P_DEFAULT, dcpl_id, H5P_DEFAULT)) < 0)
                            goto error;
                        if(nelmts)
                            if(H5Dwrite(dset_out, mtype_id, H5S_ALL, H5S_ALL, H5P_DEFAULT, refbuf) < 0)
                                goto error;

                        if(buf)
                            HDfree(buf);
                        if(refbuf)
                            HDfree(refbuf);

                       /*-----------------------------------------------------
                        * copy attrs
                        *----------------------------------------------------*/
                        if(copy_attr(dset_in, dset_out, &named_dt_head, travt, options) < 0)
                            goto error;
                    } /* H5T_STD_REF_DSETREG */
                    /*-------------------------------------------------------------------------
                    * not references, open previously created object in 1st traversal
                    *-------------------------------------------------------------------------
                    */
                    else {
                        if((dset_out = H5Dopen2(fidout, travt->objs[i].name, H5P_DEFAULT)) < 0)
                            goto error;
                    } /* end else */

                    assert(dset_out != FAIL);

                    /*-------------------------------------------------------------------------
                    * copy referenced objects in attributes
                    *-------------------------------------------------------------------------
                    */
                    if(copy_refs_attr(dset_in, dset_out, options, travt, fidout) < 0)
                        goto error;

                    /*-------------------------------------------------------------------------
                    * check for hard links
                    *-------------------------------------------------------------------------
                    */
                    if(travt->objs[i].nlinks)
                        for(j = 0; j < travt->objs[i].nlinks; j++)
                            H5Lcreate_hard(fidout, travt->objs[i].name, H5L_SAME_LOC, travt->objs[i].links[j].new_name, H5P_DEFAULT, H5P_DEFAULT);

                    if(H5Dclose(dset_out) < 0)
                        goto error;
                } /*can_read*/
Exemplo n.º 28
0
hid_t dat1Reopen( hid_t file_id, unsigned int flags, hid_t fapl,
                  int *status ){

/* Local Variables; */
   HDSLoc **loc;
   HDSLoc **loclist;
   char **paths;
   char file[EMS__SZMSG+1];
   char path[EMS__SZMSG+1];
   hid_t *file_ids;
   hid_t id;
   int *isgroup;
   int iloc;
   int nlev;
   int nloc;
   ssize_t size;

/* Return immediately if an error has already occurred. */
   if( *status != SAI__OK ) return file_id;

/* Get a list of any active locators associated with the file. Also get a
   list of file_ids for the same file that have associated locators. */
   hds1GetLocators( file_id, &nloc, &loclist, &file_ids, status );

/* Check that none of the locators are mapped. */
   if( *status == SAI__OK ) {
      loc = loclist;
      for( iloc = 0; iloc < nloc; iloc++,loc++ ) {
         if( (*loc)->regpntr ) {
            hdsTrace( (*loc), &nlev, path, file, status, sizeof(path), sizeof(file) );
            *status = DAT__PRMAP;
            emsRepf( " ", "hdsOpen: Cannot re-open '%s' in read-write mode "
                     "since '%s' is currently mapped.", status, file, path );
            break;
         }
      }
   }

/* Store the path to the HDF5 object associated with each active locator,
   and also a flag indicating if the HDF5 object is a group or dataset.
   Then close the HDF5 objects. */
   paths = MEM_CALLOC( nloc, sizeof( *paths ) );
   isgroup = MEM_CALLOC( nloc, sizeof( *isgroup ) );
   if( paths && isgroup && *status == SAI__OK ) {
      loc = loclist;
      for( iloc = 0; iloc < nloc; iloc++,loc++ ) {
         if( (*loc)->group_id ) {
            isgroup[ iloc ] = 1;
            id = (*loc)->group_id;
         } else {
            isgroup[ iloc ] = 0;
            id = (*loc)->dataset_id;
         }
         if( id ) {
            size = H5Iget_name( id, NULL, 0 );
            paths[ iloc ] = MEM_CALLOC( size + 1, 1 );
            H5Iget_name( id, paths[ iloc ], size + 1 );
         } else {
            hdsTrace( (*loc), &nlev, path, file, status, sizeof(path), sizeof(file) );
            *status = DAT__FATAL;
            emsRepf( " ", "hdsOpen: Locator for '%s.%s' has no group or "
                     "dataset so cannot be reopened.", status, file, path );
            break;
         }
         if( H5Oclose( id ) < 0 ) {
            hdsTrace( (*loc), &nlev, path, file, status, sizeof(path), sizeof(file) );
            *status = DAT__FATAL;
            dat1H5EtoEMS( status );
            emsRepf( " ", "hdsOpen: Failed to close HDF5 object for '%s.%s'.",
                     status, file, path );
            break;
         }
      }
   }

/* Get the path for the file. */
   H5Fget_name( file_id, path, sizeof(path) );

/* Close all HDF5 file_ids associated with file. */
   if( *status == SAI__OK ) {
      int this_closed = 0;

      int i = -1;
      while( file_ids[ ++i ] ) {

         if( file_ids[ i ] == file_id ) this_closed = 1;

         if( H5Fclose( file_ids[ i ] ) < 0 ) {
            *status = DAT__FATAL;
            dat1H5EtoEMS( status );
            emsRepf( " ", "hdsOpen: Failed to close file '%s' prior to "
                     "re-opening it.", status, path );
            break;
         }
      }

/* Close the supplied file_id if it has not already been closed. */
      if( !this_closed ) {
         if( H5Fclose( file_id ) < 0 ) {
            *status = DAT__FATAL;
            dat1H5EtoEMS( status );
            emsRepf( " ", "hdsOpen: Failed to close file '%s' prior to "
                     "re-opening it.", status, path );
         }
      }
   }

/* Re-open it. */
   if( *status == SAI__OK ) {
      file_id = H5Fopen( path, flags, fapl );
      if( file_id < 0 ) {
         *status = DAT__FATAL;
         dat1H5EtoEMS( status );
         emsRepf( " ", "hdsOpen: Failed to reopen file '%s'.",
                  status, path );
      }
   }

/* Update the file, group and dataset id in each locator. */
   if( *status == SAI__OK ) {
      loc = loclist;
      for( iloc = 0; iloc < nloc; iloc++,loc++ ) {
         hds1SetFileId( (*loc), file_id, status );
         if( isgroup[ iloc ] ) {
            (*loc)->group_id = H5Gopen2( file_id, paths[ iloc ], H5P_DEFAULT );
         } else {
            (*loc)->dataset_id = H5Dopen2( file_id, paths[ iloc ], H5P_DEFAULT );
         }
      }
   }

/* Free resources. */
   if( paths ) {
      for( iloc = 0; iloc < nloc; iloc++ ) {
         MEM_FREE( paths[ iloc ] );
      }
      MEM_FREE( paths );
   }
   if( isgroup ) MEM_FREE( isgroup );
   if( loclist ) MEM_FREE( loclist );
   if( file_ids ) MEM_FREE( file_ids );

/* Return the new file id. */
   return file_id;
}