Пример #1
0
void xml_parser_doc_dump(FILE * f, WsXmlDocH doc)
{

	xmlDocPtr d = (xmlDocPtr) doc->parserDoc;
	xmlDocFormatDump(f, d, 1);
	return;
}
Пример #2
0
bool BayesianClassifier::Save(const char* filename)
{
  FILE* file;
  xmlDocPtr document;
  xmlNodePtr rootNode;
  bool retCode = true;

  if ( !filename || !*filename )
  {
    fprintf(stderr, "BayesianClassifier::Save - Invalid parameter\n");
    return false;
  }

  file = fopen(filename, "w");
  if ( !file )
  {
    fprintf(stderr, "BayesianClassifier::Save - Failed opening %s\n", filename);
    return false;
  }

  document = xmlNewDoc(NULL);
  rootNode = xmlNewDocNode(document, NULL, (const xmlChar *)BAYESIAN_CLASSIFIER_STR, NULL);
  xmlDocSetRootElement(document, rootNode);

  retCode = Save(rootNode);

  xmlDocFormatDump(file, document, 1);
  fclose(file);
  xmlFreeDoc(document);

  return retCode;
}
Пример #3
0
void TwsXml::dumpAndFree( xmlNodePtr root )
{
	xmlDocFormatDump(stdout, root->doc, 1);
	//HACK print form feed as xml file separator
	printf("\f");

	xmlFreeDoc(root->doc);
}
/**
 * infd_chat_filesystem_format_write:
 * @storage: A #InfdFilesystemStorage.
 * @path: Storage path where to write the session to.
 * @buffer: The #InfChatBuffer to write.
 * @error: Location to store error information, if any, or %NULL.
 *
 * Writes the given buffer into the filesystem storage at @path. If
 * successful, the session can then be read back with
 * infd_chat_filesystem_format_read(). If the function fails, %FALSE is
 * returned and @error is set.
 *
 * Returns: %TRUE on success or %FALSE on error.
 */
gboolean
infd_chat_filesystem_format_write(InfdFilesystemStorage* storage,
                                  const gchar* path,
                                  InfChatBuffer* buffer,
                                  GError** error)
{
  FILE* stream;
  xmlDocPtr doc;
  xmlNodePtr root;
  xmlErrorPtr xmlerror;

  g_return_val_if_fail(INFD_IS_FILESYSTEM_STORAGE(storage), FALSE);
  g_return_val_if_fail(path != NULL, FALSE);
  g_return_val_if_fail(INF_IS_CHAT_BUFFER(buffer), FALSE);
  g_return_val_if_fail(error == NULL || *error == NULL, FALSE);

  /* Open stream before exporting buffer to XML so possible errors are
   * catched earlier. */
  stream = infd_filesystem_storage_open(
    INFD_FILESYSTEM_STORAGE(storage),
    "InfChat",
    path,
    "w",
    NULL,
    error
  );

  if(stream == NULL)
    return FALSE;

  root = xmlNewNode(NULL, (const xmlChar*)"inf-chat-session");

  doc = xmlNewDoc((const xmlChar*)"1.0");
  xmlDocSetRootElement(doc, root);

  /* TODO: At this point, we should tell libxml2 to use
   * infd_filesystem_storage_stream_write() instead of fwrite(),
   * to prevent C runtime mixups. */
  if(xmlDocFormatDump(stream, doc, 1) == -1)
  {
    xmlerror = xmlGetLastError();
    infd_filesystem_storage_stream_close(stream);
    xmlFreeDoc(doc);

    g_set_error_literal(
      error,
      g_quark_from_static_string("LIBXML2_OUTPUT_ERROR"),
      xmlerror->code,
      xmlerror->message
    );

    return FALSE;
  }

  infd_filesystem_storage_stream_close(stream);
  xmlFreeDoc(doc);
  return TRUE;
}
Пример #5
0
void
test_main (gint argc,
           gchar **argv)
{
    const gchar *url;
    E2kContext *ctx;
    E2kHTTPStatus status;
    E2kResult *results;
    gint nresults;
    GByteArray *ba;
    E2kRules *rules;
    xmlDoc *doc;

    if (argc != 2) {
        fprintf (stderr, "Usage: %s URL\n", argv[0]);
        exit (1);
    }
    url = argv[1];

    ctx = test_get_context (url);
    status = e2k_context_propfind (ctx, NULL, url,
                                   rules_props,
                                   G_N_ELEMENTS (rules_props),
                                   &results, &nresults);
    test_abort_if_http_error (status);

    ba = e2k_properties_get_prop (results[0].props, PR_RULES_DATA);
    if (!ba) {
        printf ("No rules\n");
        goto done;
    }

    rules = e2k_rules_from_binary (ba);
    if (!rules) {
        printf ("Could not parse rules\n");
        goto done;
    }

    doc = e2k_rules_to_xml (rules);
    if (doc) {
        xmlDocFormatDump (stdout, doc, TRUE);
        xmlFreeDoc (doc);
    } else
        printf ("Could not convert normal rules to XML\n");

    e2k_rules_free (rules);
    e2k_results_free (results, nresults);

done:
    test_quit ();
}
Пример #6
0
int main() {
    xmlDocPtr doc;
    xmlNodePtr racine, premier_prod, nouv_prod;

    // Ouverture du fichier XML
    xmlKeepBlanksDefault(0);
    doc = xmlParseFile("catalogue.xml");
    if (doc == NULL) {
        fprintf(stderr, "Document XML invalide\n");
        return EXIT_FAILURE;
    }
    // Récupération de la racine
    racine = xmlDocGetRootElement(doc);
    if (racine == NULL) {
        fprintf(stderr, "Document XML vierge\n");
        xmlFreeDoc(doc);
        return EXIT_FAILURE;
    }
    // Récupération du premier produit
    premier_prod = obtenir_premier_produit(doc);
    if (premier_prod == NULL) {
        fprintf(stderr, "Impossible de trouver le premier produit\n");
        xmlFreeDoc(doc);
        return EXIT_FAILURE;
    }
    // Ajout d'un nouveau produit avant le premier produit (en tête)
    nouv_prod = creer_produit("CD0YAH", "Autocollant Developpez.com", "0.80");
    if (nouv_prod) {
        xmlAddPrevSibling(premier_prod, nouv_prod);
    }
    // Ajout d'un nouveau produit après le premier produit
    nouv_prod = creer_produit("U0TZ6K", "Lot de 10 autocollants Developpez.com", "5.00");
    if (nouv_prod) {
        xmlAddNextSibling(premier_prod, nouv_prod);
    }
    // Ajout d'un nouveau produit en fin/queue
    nouv_prod = creer_produit("ZQEYAN", "Mug Developpez.com", "4.00");
    if (nouv_prod) {
        xmlAddSibling(premier_prod, nouv_prod);
    }
    // Affichage de l'arbre DOM tel qu'il est en mémoire
    xmlDocFormatDump(stdout, doc, 1);
    // Libération de la mémoire
    xmlFreeDoc(doc);

    return EXIT_SUCCESS;
}
Пример #7
0
int export_dives_xslt(const char *filename, const bool selected, const char *export_xslt)
{
	FILE *f;
	struct membuffer buf = { 0 };
	xmlDoc *doc;
	xsltStylesheetPtr xslt = NULL;
	xmlDoc *transformed;


	if (!filename)
		return report_error("No filename for export");

	/* Save XML to file and convert it into a memory buffer */
	save_dives_buffer(&buf, selected);

	/*
	 * Parse the memory buffer into XML document and
	 * transform it to selected export format, finally dumping
	 * the XML into a character buffer.
	 */
	doc = xmlReadMemory(buf.buffer, buf.len, "divelog", NULL, 0);
	free_buffer(&buf);
	if (!doc)
		return report_error("Failed to read XML memory");

	/* Convert to export format */
	xslt = get_stylesheet(export_xslt);
	if (!xslt)
		return report_error("Failed to open export conversion stylesheet");

	transformed = xsltApplyStylesheet(xslt, doc, NULL);
	xsltFreeStylesheet(xslt);
	xmlFreeDoc(doc);

	/* Write the transformed export to file */
	f = subsurface_fopen(filename, "w");
	if (!f)
		return report_error("Failed to open %s for writing (%s)", filename, strerror(errno));

	xmlDocFormatDump(f, transformed, 1);
	xmlFreeDoc(transformed);

	fclose(f);
	/* Check write errors? */
	return 0;
}
Пример #8
0
int main (int argc, char **argv) {
  struct arguments arguments;
  struct list_elem elem;
  struct list_elem *elemptr = &elem;
  elem.has_next = 0;
  
  arguments.include_files = elemptr;
  arguments.output_file = "-";
  arguments.parsley = "-";
  argp_parse (&argp, argc, argv, 0, 0, &arguments);
  
  struct printbuf* parsley = printbuf_new();
  struct printbuf* incl = printbuf_new();
  sprintbuf(parsley, "");
  sprintbuf(incl, "");

  FILE* in = parsley_fopen(arguments.parsley, "r");
  
  printbuf_file_read(in, parsley);
  while(elemptr->has_next) {
    elemptr = elemptr->next;
    FILE* f = parsley_fopen(elemptr->string, "r");
    printbuf_file_read(f, incl);
    fclose(f);
  }
  
  parsleyPtr compiled = parsley_compile(parsley->buf, incl->buf);
  if(compiled->error != NULL) {
    fprintf(stderr, "%s\n", compiled->error);
     exit(1);
  }
  
  FILE* fo = parsley_fopen(arguments.output_file, "w");
  xmlDocFormatDump(fo, compiled->stylesheet->doc, 1);
  fclose(fo);
  
  return 0;
}
Пример #9
0
int main(int argc, char* argv[])
{
	char* event, *stream, **list, *desc, *start;
	int i, c;
	int verbosity = NC_VERB_ERROR;
	int listing = 0;
	int corrupted = 0;
	int time_start = 0, time_end = -1;
	xmlDocPtr eventDoc;

	while ((c = getopt(argc, argv, ARGUMENTS)) != -1) {
		switch (c) {
		case 'h': /* Show help */
			usage(argv[0]);
			return EXIT_SUCCESS;

		case 'l': /* list the streams */
			listing = 1;
			break;

		case 's': /* time range - start */
			time_start = nc_datetime2time(optarg);
			break;

		case 'e': /* time range - end */
			time_end = nc_datetime2time(optarg);
			break;

		case 'v': /* Verbose operation */
			verbosity = atoi(optarg);
			if (verbosity < NC_VERB_ERROR) {
				verbosity = NC_VERB_ERROR;
			} else if (verbosity > NC_VERB_DEBUG) {
				verbosity = NC_VERB_DEBUG;
			}
			break;

		default:
			fprintf(stderr, "unknown argument -%c", optopt);
			break;
		}
	}

	if (!listing && (argc - optind) != 1) {
		if ((argc - optind) < 1) {
			fprintf(stderr, "Missing stream name\n\n");
		} else { /* (argc - optind) > 1 */
			fprintf(stderr, "Only a single stream name is allowed\n\n");
		}
		usage(argv[0]);
		return (EXIT_FAILURE);
	}
	stream = argv[optind];

	nc_verbosity(verbosity);
	nc_callback_print(clb_print);

	c = nc_init(NC_INIT_NOTIF);
	if (c == -1) {
		fprintf(stderr, "libnetconf initiation failed.");
		return (EXIT_FAILURE);
	}

	if (listing) {
		list = ncntf_stream_list();
		if (list == NULL || list[0] == NULL) {
			fprintf(stderr, "There is no NETCONF Event Stream.\n");
			return (EXIT_FAILURE);
		}
		fprintf(stdout, "NETCONF Event Stream list:\n");
		for (i = 0; list[i] != NULL; i++) {
			if (ncntf_stream_info(list[i], &desc, &start) == 0) {
				fprintf(stdout, "\t%s\n\t\t%s\n\t\t%s\n", list[i], desc, start);
				free(desc);
				free(start);
			}
			free(list[i]);
		}
		fprintf(stdout, "\n");
		free(list);

		return(EXIT_SUCCESS);
	}

	i = 0;
	ncntf_stream_iter_start(stream);
	while((event = ncntf_stream_iter_next(stream, time_start, time_end, NULL)) != NULL) {
		if ((eventDoc = xmlReadMemory(event, strlen(event), NULL, NULL, 0)) != NULL) {
			fprintf(stdout, "Event:\n");
			xmlDocFormatDump(stdout, eventDoc, 1);
			xmlFreeDoc(eventDoc);
			i++;
		} else {
			fprintf(stdout, "Invalid event format.\n");
			corrupted = 1;
		}
		free(event);
	}
	ncntf_stream_iter_finish(stream);

	/* print summary */
	fprintf(stdout, "\nSummary:\n\tNumber of records: %d\n", i);
	if (corrupted) {
		fprintf(stdout, "\tSTREAM FILE IS CORRUPTED!\n");
	}

	ncntf_close();

	return (EXIT_SUCCESS);
}
Пример #10
0
/*!
  @param filename - the name of the configuration file
  @return CFG_FILE_NOT_SPECIFIED if filename is ""
  @return CFG_FILE_NOT_WRITABLE if the file cannot be opened for writing
  @return CFG_OK if successful

  Saves the configuration of the ConfigMgr to file.
*/
ConfigMgrStatusType ConfigMgr::Save(string filename)
{
  int i;
  FILE *fp;
  xmlDocPtr document;
  xmlNodePtr rootNode;
  xmlNodePtr repositoryNode;
  xmlNodePtr featureNode;
  int numRepositories;
  string appRoverDir = APP_ROVER_DIR;
  map<string,bool>::iterator feature;

  if ( filename == "" )
    return CFG_FILE_NOT_SPECIFIED;

  fp = fopen(filename.c_str(), "w");
  if ( !fp )
    return CFG_FILE_NOT_WRITABLE;

  mCfgFilename = filename;

  document = xmlNewDoc(NULL);
  rootNode = xmlNewDocNode(document,NULL,(const xmlChar *)CONFIG_HDR_STR,NULL);
  SetDoubleValue(rootNode, VERSION_STR, 1);
  xmlDocSetRootElement(document,rootNode);

  if ( mInstallLogFilename == "" )
    SetStringValue(rootNode, LOG_STR, appRoverDir+"AppRover.log");
  else
    SetStringValue(rootNode, LOG_STR, mInstallLogFilename);
  if ( mStorageDirectory == "" )
    SetStringValue(rootNode, STORAGE_STR, appRoverDir+"storage/");
  else
    SetStringValue(rootNode, STORAGE_STR, mStorageDirectory);
  if ( mWorkDirectory == "" )
    SetStringValue(rootNode, WORK_STR, appRoverDir + "work/");
  else
    SetStringValue(rootNode, WORK_STR, mWorkDirectory);
  if ( mInstallFileDirectory == "" )
    SetStringValue(rootNode, INSTALL_FILE_STR, appRoverDir + "files/");
  else
    SetStringValue(rootNode, INSTALL_FILE_STR, mInstallFileDirectory);

  if ( mNumProcessors < 1 )
    DetectNumProcessors();
  SetIntValue(rootNode, PROCESSOR_STR, mNumProcessors);

  numRepositories = mRepositoryDirectories.size();
  if ( !numRepositories )
  {
    repositoryNode = xmlNewNode(NULL,(const xmlChar*)REPOSITORY_STR);
    SetStringValue(repositoryNode, DIR_STR, appRoverDir+"repo/");
    xmlAddChild(rootNode,repositoryNode);
  }
  else
  {
    for (i = 0; i < numRepositories; i++)
    {
      repositoryNode = xmlNewNode(NULL,(const xmlChar*)REPOSITORY_STR);
      SetStringValue(repositoryNode, DIR_STR, mRepositoryDirectories[i]);
      xmlAddChild(rootNode,repositoryNode);
    }
  }

  for (feature=mFeatureSettings.begin(); feature!=mFeatureSettings.end(); feature++)
  {
    featureNode = xmlNewNode(NULL,(const xmlChar*)FEATURE_STR);
    SetStringValue(featureNode, FEATURE_NAME_STR, (*feature).first);
    SetBoolValue(featureNode, ENABLED_STR, (*feature).second);
    xmlAddChild(rootNode,featureNode);
  }

  xmlDocFormatDump(fp,document,1);
  fclose(fp);
  xmlFreeDoc(document);
  return CFG_OK;
}
Пример #11
0
int ploop_store_diskdescriptor(const char *fname, struct ploop_disk_images_data *di)
{
	int i, rc = -1;
	xmlTextWriterPtr writer = NULL;
	xmlDocPtr doc = NULL;
	char tmp[PATH_MAX];
	char basedir[PATH_MAX];
	FILE *fp = NULL;

	ploop_log(0, "Storing %s", fname);

	if (convert_disk_descriptor(di))
		return -1;

	if (di->runtime->xml_fname == NULL)
		di->runtime->xml_fname = strdup(fname);

	get_basedir(fname, tmp, sizeof(tmp));
	if (tmp[0] == '\0')
		strcpy(tmp, "./");

	if (realpath(tmp, basedir) == NULL) {
		ploop_err(errno, "Can't resolve %s", tmp);
		return -1;
	}

	doc = xmlNewDoc(BAD_CAST XML_DEFAULT_VERSION);
	if (doc == NULL) {
		ploop_err(0, "Error creating xml document tree");
		return -1;
	}

	/* Create a new XmlWriter for DOM tree, with no compression. */
	writer = xmlNewTextWriterTree(doc, NULL, 0);
	if (writer == NULL) {
		ploop_err(0, "Error creating xml writer");
		goto err;
	}

	/* Start the document with the xml default for the version,
	 * encoding ISO 8859-1 and the default for the standalone
	 * declaration. */
	rc = xmlTextWriterStartDocument(writer, NULL, NULL, NULL);
	if (rc < 0) {
		ploop_err(0, "Error at xmlTextWriterStartDocument");
		goto err;
	}
	rc = xmlTextWriterStartElement(writer, BAD_CAST "Parallels_disk_image");
	if (rc < 0) {
		ploop_err(0, "Error at xmlTextWriterStartDocument");
		goto err;
	}
	/*********************************************
	 *	Disk_Parameters
	 ********************************************/
	rc = xmlTextWriterStartElement(writer, BAD_CAST "Disk_Parameters");
	if (rc < 0) {
		ploop_err(0, "Error at xmlTextWriter Disk_Parameters");
		goto err;
	}
	rc = xmlTextWriterWriteFormatElement(writer, BAD_CAST "Disk_size", "%llu", di->size);
	if (rc < 0) {
		ploop_err(0, "Error at xmlTextWriter Disk_size");
		goto err;
	}

	if (di->max_delta_size != 0) {
		rc = xmlTextWriterWriteFormatElement(writer,
				BAD_CAST "Max_delta_size", "%llu", di->max_delta_size);
		if (rc < 0) {
			ploop_err(0, "Error at xmlTextWriter Max_delta_size");
			goto err;
		}
	}

	rc = xmlTextWriterWriteFormatElement(writer, BAD_CAST "Cylinders", "%u", di->cylinders);
	if (rc < 0) {
		ploop_err(0, "Error at xmlTextWriter Cylinders");
		goto err;
	}
	rc = xmlTextWriterWriteFormatElement(writer, BAD_CAST "Heads", "%u", di->heads);
	if (rc < 0) {
		ploop_err(0, "Error at xmlTextWriter Heads");
		goto err;
	}
	rc = xmlTextWriterWriteFormatElement(writer, BAD_CAST "Sectors", "%llu",
			di->size /(di->cylinders * di->heads));
	if (rc < 0) {
		ploop_err(0, "Error at xmlTextWriter Sectors");
		goto err;
	}
	rc = xmlTextWriterWriteFormatElement(writer, BAD_CAST "Padding", "%u", 0);
	if (rc < 0) {
		ploop_err(0, "Error at xmlTextWriter Padding");
		goto err;
	}

	/* Close   Disk_Parameters */
	rc = xmlTextWriterEndElement(writer);
	if (rc < 0) {
		ploop_err(0, "Error at xmlTextWriterEndElement");
		goto err;
	}
	/****************************************
	 * StorageData
	 ****************************************/
	rc = xmlTextWriterStartElement(writer, BAD_CAST "StorageData");
	if (rc < 0) {
		ploop_err(0, "Error at xmlTextWriter StorageData");
		goto err;
	}
	/* Start an element named "Storage" as child of StorageData. */
	rc = xmlTextWriterStartElement(writer, BAD_CAST "Storage");
	if (rc < 0) {
		ploop_err(0, "Error at xmlTextWriter Storage");
		goto err;
	}
	rc = xmlTextWriterWriteElement(writer, BAD_CAST "Start",  BAD_CAST "0");
	if (rc < 0) {
		ploop_err(0, "Error at xmlTextWriter Start");
		goto err;
	}
	rc = xmlTextWriterWriteFormatElement(writer, BAD_CAST "End", "%llu", di->size);
	if (rc < 0) {
		ploop_err(0, "Error at xmlTextWriter End");
		goto err;
	}
	rc = xmlTextWriterWriteFormatElement(writer, BAD_CAST "Blocksize", "%d",
			di->blocksize);
	if (rc < 0) {
		ploop_err(0, "Error at xmlTextWriter Blocksize");
		goto err;
	}
	if (di->mode == PLOOP_EXPANDED_PREALLOCATED_MODE) {
		rc = xmlTextWriterWriteElement(writer, BAD_CAST "Preallocated",
				BAD_CAST "1");
		if (rc < 0) {
			ploop_err(0, "Error at xmlTextWriter Preallocated");
			goto err;
		}
	}
	/****************************************
	 *	Images
	 ****************************************/
	for (i = 0; i < di->nimages; i++) {
		rc = xmlTextWriterStartElement(writer, BAD_CAST "Image");
		if (rc < 0) {
			ploop_err(0, "Error at xmlTextWriter Image");
			goto err;
		}

		rc = xmlTextWriterWriteElement(writer, BAD_CAST "GUID",
				BAD_CAST di->images[i]->guid);
		if (rc < 0) {
			ploop_err(0, "Error at xmlTextWriter GUID");
			goto err;
		}
		rc = xmlTextWriterWriteElement(writer, BAD_CAST "Type",
			BAD_CAST (di->mode == PLOOP_RAW_MODE ? "Plain" : "Compressed"));
		if (rc < 0) {
			ploop_err(0, "Error at xmlTextWriter Type");
			goto err;
		}

		normalize_image_name(basedir, di->images[i]->file, tmp, sizeof(tmp));
		rc = xmlTextWriterWriteElement(writer, BAD_CAST "File",
				BAD_CAST tmp);
		if (rc < 0) {
			ploop_err(0, "Error at xmlTextWriter File");
			goto err;
		}

		/*  Close  Image */
		rc = xmlTextWriterEndElement(writer);
		if (rc < 0) {
			ploop_err(0, "Error at xmlTextWriterEndElement");
			goto err;
		}
	}

	/* Close Storage */
	rc = xmlTextWriterEndElement(writer);
	if (rc < 0) {
		ploop_err(0, "Error at xmlTextWriterEndElement");
		goto err;
	}
	/* Close StorageData. */
	rc = xmlTextWriterEndElement(writer);
	if (rc < 0) {
		ploop_err(0, "Error at xmlTextWriterEndElement");
		goto err;
	}
	/****************************************
	 *	Snapshots
	 ****************************************/
	rc = xmlTextWriterStartElement(writer, BAD_CAST "Snapshots");
	if (rc < 0) {
		ploop_err(0, "Error at xmlTextWriter Snapshots");
		goto err;
	}

	if (di->top_guid != NULL) {
		rc = xmlTextWriterWriteElement(writer, BAD_CAST "TopGUID",
				BAD_CAST di->top_guid);
		if (rc < 0) {
			ploop_err(0, "Error at xmlTextWriter TopGUID");
			goto err;
		}
	}

	/****************************************
	 *      Shot
	 ****************************************/
	for (i = 0; i < di->nsnapshots; i++) {
		rc = xmlTextWriterStartElement(writer, BAD_CAST "Shot");
		if (rc < 0) {
			ploop_err(0, "Error at xmlTextWriter Shot");
			goto err;
		}

		rc = xmlTextWriterWriteElement(writer, BAD_CAST "GUID",
				BAD_CAST di->snapshots[i]->guid);
		if (rc < 0) {
			ploop_err(0, "Error at xmlTextWriterWrite GUID");
			goto err;
		}
		rc = xmlTextWriterWriteElement(writer, BAD_CAST "ParentGUID",
				BAD_CAST di->snapshots[i]->parent_guid);
		if (rc < 0) {
			ploop_err(0, "Error at xmlTextWriter ParentGUID");
			goto err;
		}

		if (di->snapshots[i]->temporary) {
			rc = xmlTextWriterWriteElement(writer, BAD_CAST "Temporary",  BAD_CAST "");
			if (rc < 0) {
				ploop_err(0, "Error at xmlTextWriter Temporary");
				goto err;
			}
		}

		/*  Close Shot */
		rc = xmlTextWriterEndElement(writer);
		if (rc < 0) {
			ploop_err(0, "Error at xmlTextWriterEndElement");
			goto err;
		}
	}
	/* Close Snapshots */
	rc = xmlTextWriterEndElement(writer);
	if (rc < 0) {
		ploop_err(0, "Error at xmlTextWriterEndElement");
		goto err;
	}

	/* Close Parallels_disk_image */
	rc = xmlTextWriterEndElement(writer);
	if (rc < 0) {
		ploop_err(0, "Error at xmlTextWriterEndElement");
		goto err;
	}
	xmlFreeTextWriter(writer);
	writer = NULL;

	snprintf(tmp, sizeof(tmp), "%s.tmp", fname);
	fp = fopen(tmp, "w+");
	if (fp == NULL) {
		ploop_err(errno, "Can't open %s", tmp);
		goto err;
	}

	rc = xmlDocFormatDump(fp, doc, 1);
	if (rc < 0) {
		ploop_err(0, "Error at xmlDocFormatDump %s", tmp);
		goto err;
	}

	rc = fsync(fileno(fp));
	if (rc) {
		ploop_err(errno, "Failed to sync %s", tmp);
		goto err;
	}
	fclose(fp);
	fp = NULL;

	rc = rename(tmp, fname);
	if (rc < 0) {
		ploop_err(errno, "Can't rename %s to %s", tmp, fname);
		goto err;
	}

	rc = 0;
err:
	if (fp)
		fclose(fp);

	if (writer)
		xmlFreeTextWriter(writer);
	if (doc)
		xmlFreeDoc(doc);
	if (rc)
		return SYSEXIT_DISKDESCR;

	return 0;
}
Пример #12
0
/*
 * dump metrics received from xenstore to the dest file 
 */
int dump_xenstore_metrics(const char *dest_file)
{
    char *buf = NULL, *path = NULL, *metrics = NULL;
    struct xs_handle *xsh = NULL;
    unsigned int len;
    int ret = 0;
	xmlParserCtxtPtr pctxt = NULL;
	xmlDocPtr doc = NULL;
    int domid;
    FILE *fp;

    if (dest_file) {
        fp = fopen(dest_file, "w");
        if (fp == NULL) {
            libmsg("Error, unable to dump metrics from xenstore: %s\n", strerror(errno));
            return -1;
        }
    }
    else {
        fp = stdout;
    }

    if ((domid = get_dom_id()) == -1) {
        libmsg("Unable to derive domID.\n" );
        ret = -1;
        goto out;
    }

    xsh = xs_domain_open();
    if (xsh == NULL) {
        libmsg("xs_domain_open() error. errno: %d.\n", errno);
        ret = -1;
        goto out;
    }

    path = xs_get_domain_path(xsh, domid);
    if (path == NULL) {
        libmsg("xs_get_domain_path() error. domid %d.\n", 0);
        ret = -1;
        goto out;
    }
    asprintf(&buf, "%s/metrics", path);
    metrics = xs_read(xsh, XBT_NULL, buf, &len);
    if (metrics == NULL) {
        libmsg("xs_read(): uuid get error. %s.\n", buf);
        ret = -1;
        goto out;
    }

    pctxt = xmlNewParserCtxt();
    if (!pctxt || !pctxt->sax) {
      libmsg("%s(): failed to create parser \n", __func__);
      ret = -1;
      goto out;
    }

    doc = xmlCtxtReadMemory(pctxt, metrics,
                            strlen(metrics), "mdisk.xml", NULL,
                            XML_PARSE_NOENT | XML_PARSE_NONET |
                            XML_PARSE_NOWARNING);
    if (!doc) {
      libmsg("%s(): libxml failed to xenstore metrics attribute\n", __func__);
      ret = -1;
      goto out;
    }
    xmlDocFormatDump(fp, doc, 1);

out:
    if (fp && fp != stdout)
        fclose(fp);
    if (doc)
      xmlFreeDoc(doc);
    if (pctxt)
      xmlFreeParserCtxt(pctxt);
    free(path);
    free(buf);
    free(metrics);
    return ret;
}
Пример #13
0
static gboolean
infd_note_plugin_text_session_write(InfdStorage* storage,
                                    InfSession* session,
                                    const gchar* path,
                                    gpointer user_data,
                                    GError** error)
{
  InfUserTable* table;
  InfTextBuffer* buffer;
  InfTextBufferIter* iter;
  xmlNodePtr root;
  xmlNodePtr buffer_node;
  xmlNodePtr segment_node;

  guint author;
  gchar* content;
  gsize bytes;

  FILE* stream;
  xmlDocPtr doc;
  xmlErrorPtr xmlerror;

  g_assert(INFD_IS_FILESYSTEM_STORAGE(storage));
  g_assert(INF_TEXT_IS_SESSION(session));

  /* Open stream before exporting buffer to XML so possible errors are
   * catched earlier. */
  stream = infd_filesystem_storage_open(
    INFD_FILESYSTEM_STORAGE(storage),
    "InfText",
    path,
    "w",
    error
  );

  if(stream == NULL)
    return FALSE;

  root = xmlNewNode(NULL, (const xmlChar*)"inf-text-session");
  buffer = INF_TEXT_BUFFER(inf_session_get_buffer(session));
  table = inf_session_get_user_table(session);

  inf_user_table_foreach_user(
    table,
    infd_note_plugin_text_session_write_foreach_user_func,
    root
  );

  buffer_node = xmlNewChild(root, NULL, (const xmlChar*)"buffer", NULL);
  iter = inf_text_buffer_create_iter(buffer);
  if(iter != NULL)
  {
    do
    {
      author = inf_text_buffer_iter_get_author(buffer, iter);
      content = inf_text_buffer_iter_get_text(buffer, iter);
      bytes = inf_text_buffer_iter_get_bytes(buffer, iter);

      segment_node = xmlNewChild(
        buffer_node,
        NULL,
        (const xmlChar*)"segment",
        NULL
      );

      inf_xml_util_set_attribute_uint(segment_node, "author", author);
      inf_xml_util_add_child_text(segment_node, content, bytes);
      g_free(content);
    } while(inf_text_buffer_iter_next(buffer, iter));

    inf_text_buffer_destroy_iter(buffer, iter);
  }

  doc = xmlNewDoc((const xmlChar*)"1.0");
  xmlDocSetRootElement(doc, root);

  if(xmlDocFormatDump(stream, doc, 1) == -1)
  {
    xmlerror = xmlGetLastError();
    fclose(stream);
    xmlFreeDoc(doc);

    g_set_error(
      error,
      g_quark_from_static_string("LIBXML2_OUTPUT_ERROR"),
      xmlerror->code,
      "%s",
      xmlerror->message
    );

    return FALSE;
  }

  fclose(stream);
  xmlFreeDoc(doc);
  return TRUE;
}
Пример #14
0
/*
 * Main entry to availdisks.
 *
 * @return      0 on successful exit, non-zero otherwise
 */
int
main(int argc, char **argv)
{
	int error = 0;
	int get_pools = 0;
	int get_devices = 0;

	/* Examine first arg */
	int c = getopt(argc, argv, CLI_OPTSTRING);
	switch (c) {
		case CLI_ARG_ALL:
			get_devices = 1;
			get_pools = 1;
			break;

		case CLI_ARG_DEVICES:
			get_devices = 1;
			break;

		case CLI_ARG_POOLS:
			get_pools = 1;
			break;

		default:
			return (1);
			break;
	}

	argc -= optind;
	argv += optind;

	if (get_pools || get_devices) {
		xmlDocPtr doc = create_doc();
		xmlNodePtr root = xmlDocGetRootElement(doc);

		if (get_devices) {
			/* Create the available node */
			xmlNodePtr available = xmlNewChild(root, NULL,
			    (xmlChar *)ELEMENT_AVAILABLE, NULL);

			/* libzfs_jni_diskmgt.o error handler */
			dmgt_set_error_handler(handle_error);

			error = dmgt_avail_disk_iter(
			    add_disk_to_xml, &available);
		}

		if (get_pools && !error) {
			/* Create the importable node */
			xmlNodePtr importable = xmlNewChild(root, NULL,
			    (xmlChar *)ELEMENT_IMPORTABLE, NULL);

			error = zjni_ipool_iter(
			    argc, argv, add_pool_to_xml, &importable);
		}

		if (!error) {
			/* Print out XML */
			(void) xmlDocFormatDump(stdout, doc, 1);
		}

		xmlFreeDoc(doc);
	}

	return (error != 0);
}
Пример #15
0
/*>void testWriteAsPDBML(FILE *fp, PDB *pdb)
   -----------------------------------------
*//**

   \param[in]     *fp   PDB file pointer to be written
   \param[in]     *pdb  PDB linked list to write

   Write a PDB linked list in PDBML format.
   
   This test function is based on the bioplib function blWriteAsPDBML(). 
   The function calls blAddTagVariablesNodes() which writes additional 
   user-defined tags for each atom.

   Tags are written if gPDBTagWrite is TRUE.

-  25.08.14 Original. By: CTP
-  28.08.14 Use gNPDBTagFunctions to control output of user-defined tags.
            By: CTP

*/
void testWriteAsPDBML(FILE *fp, PDB  *pdb)
{
   /* PDBML format supported */
   PDB         *p;
   xmlDocPtr   doc         = NULL;
   xmlNodePtr  root_node   = NULL, 
               sites_node  = NULL, 
               atom_node   = NULL, 
               node        = NULL;
   xmlNsPtr    pdbx        = NULL,
               xsi         = NULL;
   char        buffer[16], 
               *buffer_ptr;
   
   /* Create doc */
   doc = xmlNewDoc((xmlChar *) "1.0");
   doc->encoding = xmlStrdup((xmlChar *) "UTF-8");
   
   /* Root node */
   root_node = xmlNewNode(NULL, (xmlChar *) "datablock");
   xmlDocSetRootElement(doc, root_node);
   pdbx = xmlNewNs(root_node, (xmlChar *) "null", (xmlChar *) "PDBx");
   xsi  = xmlNewNs(root_node, (xmlChar *) "null", (xmlChar *) "xsi");
   xmlSetNs(root_node,pdbx);
   
   
   /* Atom_sites node */
   sites_node = xmlNewChild(root_node, NULL,
                            (xmlChar *) "atom_siteCategory", NULL);
   
   /* Atom nodes */
   for(p = pdb ; p ; NEXT(p))
   {
      /* skip TER */
      if(!strncmp("TER",p->resnam,3))
      {
         continue;
      }

      /* Add atom node */
      atom_node = xmlNewChild(sites_node, NULL,
                              (xmlChar *) "atom_site", NULL);
      sprintf(buffer, "%d", p->atnum);
      xmlNewProp(atom_node, (xmlChar *) "id", (xmlChar *) buffer);
      
      /* Add atom data nodes */
      /* B value */
      sprintf(buffer,"%.2f", p->bval);
      node = xmlNewChild(atom_node, NULL, 
                         (xmlChar *) "B_iso_or_equiv",
                         (xmlChar *) buffer);

      /* coordinates */
      sprintf(buffer,"%.3f", p->x);
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "Cartn_x",
                         (xmlChar *) buffer);

      sprintf(buffer,"%.3f", p->y);
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "Cartn_y",
                         (xmlChar *) buffer);

      sprintf(buffer,"%.3f", p->z);
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "Cartn_z",
                         (xmlChar *) buffer);

      /* author atom site labels */
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "auth_asym_id",
                         (xmlChar *) p->chain);

      strcpy(buffer,p->atnam);
      KILLTRAILSPACES(buffer);
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "auth_atom_id",
                         (xmlChar *) buffer);

      strcpy(buffer,p->resnam);
      KILLTRAILSPACES(buffer);
      KILLLEADSPACES(buffer_ptr,buffer);
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "auth_comp_id",
                         (xmlChar *) buffer_ptr);
      
      sprintf(buffer,"%d", p->resnum);
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "auth_seq_id",
                         (xmlChar *) buffer);

      /* record type atom/hetatm */
      strcpy(buffer,p->record_type);
      KILLTRAILSPACES(buffer);
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "group_PDB",
                         (xmlChar *) buffer);

      /* atom site labels */
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "label_alt_id",
                         NULL);
      if(p->altpos == ' ')
      {
         xmlNewNsProp(node, xsi, (xmlChar *) "nil", (xmlChar *) "true");
      }
      else
      {
         buffer[0] = p->altpos;
         buffer[1] = '\0';
         xmlNodeSetContent(node, (xmlChar *) buffer);
      }
      
      node = xmlNewChild(atom_node, NULL, 
                         (xmlChar *) "label_asym_id",
                         (xmlChar *) p->chain);

      strcpy(buffer,p->atnam);
      KILLTRAILSPACES(buffer);
      node = xmlNewChild(atom_node, NULL, 
                         (xmlChar *) "label_atom_id",
                         (xmlChar *) buffer);

      strcpy(buffer,p->resnam);
      KILLTRAILSPACES(buffer);
      KILLLEADSPACES(buffer_ptr,buffer);
      node = xmlNewChild(atom_node, NULL, 
                         (xmlChar *) "label_comp_id",
                         (xmlChar *) buffer_ptr);

      /* Note: Entity ID is not stored in PDB data structure. 
               Value set to 1 */
      node = xmlNewChild(atom_node, NULL,
                         (xmlChar *) "label_entity_id",
                         (xmlChar *) "1");
      
      sprintf(buffer,"%d", p->resnum);
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "label_seq_id",
                         (xmlChar *) buffer);

      /* occupancy */
      sprintf(buffer,"%.2f", p->occ);
      node = xmlNewChild(atom_node, NULL, (xmlChar *) "occupancy",
                         (xmlChar *) buffer);
                         
      /* insertion code */
      /* Note: Insertion code node only included for residues with 
               insertion codes */
      if(strcmp(p->insert," "))
      {
         sprintf(buffer,"%s", p->insert);
         node = xmlNewChild(atom_node, NULL, 
                            (xmlChar *) "pdbx_PDB_ins_code",
                            (xmlChar *) buffer);
      }

      /* model number */
      /* Note: Model number is not stored in PDB data structure.
               Value set to 1 */
      node = xmlNewChild(atom_node, NULL,
                         (xmlChar *) "pdbx_PDB_model_num",
                         (xmlChar *) "1");

      /* formal charge */
      /* Note: Formal charge node not included for neutral atoms */
      if(p->formal_charge != 0)
      {
         sprintf(buffer,"%d", p->formal_charge);
         node = xmlNewChild(atom_node, NULL, 
                            (xmlChar *) "pdbx_formal_charge",
                            (xmlChar *) buffer);
      }

      /* atom symbol */
      /* Note: If the atomic symbol is not set in PDB data structure then
               the value set is based on columns 13-14 of pdb-formated
               text file.  */
      sprintf(buffer,"%s", p->element);
      KILLLEADSPACES(buffer_ptr,buffer);
      if(strlen(buffer_ptr))
      {
         node = xmlNewChild(atom_node, NULL, (xmlChar *) "type_symbol",
                            (xmlChar *) buffer_ptr);
      }
      else
      {
         blSetElementSymbolFromAtomName(buffer,p->atnam_raw);
         node = xmlNewChild(atom_node, NULL, (xmlChar *) "type_symbol",
                            (xmlChar *) buffer);
      }

      /* NEW CODE */
      /* user-defined tags */
      if(gNPDBTagFunctions)
      {
         blAddTagVariablesNodes(p,atom_node);
      }
   }

   /* Write to doc file pointer */
   xmlDocFormatDump(fp,doc,1);

   /* Free Memory */
    xmlFreeDoc(doc);
    xmlCleanupParser();

   return;
}