Example #1
0
char *xml_parser_node_query(WsXmlNodeH node, int what)
{
	char *ptr = NULL;
	xmlNodePtr xmlNode = (xmlNodePtr) node;
	iWsNode *wsNode = (iWsNode *) xmlNode->_private;

	switch (what) {
	case XML_TEXT_VALUE:
		if (wsNode == NULL)
			xmlNode->_private = wsNode =
				u_zalloc(sizeof(iWsNode));

		if (wsNode != NULL) {
			if (wsNode->valText == NULL) {
				wsNode->valText =
					(char *) xmlNodeGetContent(xmlNode);
			}
			ptr = wsNode->valText;
		}
		break;
	case XML_LOCAL_NAME:
		ptr = (char *) xmlNode->name;
		break;
	case XML_NS_URI:
		if (xmlNode->ns != NULL)
			ptr = (char *) xmlNode->ns->href;
		break;
	case XML_NS_PREFIX:
		if (xmlNode->ns != NULL)
			ptr = (char *) xmlNode->ns->prefix;
		break;
	default:
		break;
	}

	return ptr;
}
Example #2
0
static gchar* __lastfm_art_xml_get_artist_bio(const gchar* data , gint size)
{
	xmlDocPtr doc = xmlParseMemory(data,size);
	gchar* info=NULL;
	if(doc)
	{
		xmlNodePtr root = xmlDocGetRootElement(doc);
		/* Todo this is ugly */
		xmlNodePtr bio = get_first_node_by_name(
				get_first_node_by_name(get_first_node_by_name(root,
						BAD_CAST"artist"),
					BAD_CAST"bio"),
				BAD_CAST"content");
		if(bio)
		{
			xmlChar *temp = xmlNodeGetContent(bio);
			info = g_strdup((gchar*) temp);
			xmlFree(temp);
		}
	}
	xmlFreeDoc(doc);

	return info;
}
void test_log_severity_to_elem_works_with_int_min()
{
	severity->level_val = INT_MIN;
	xmlNodePtr new_elem = NULL;
	enum jal_status ret = jalp_log_severity_to_elem(severity, new_doc, &new_elem);
	assert_not_equals(NULL, new_elem);
	assert_equals(JAL_OK, ret);
	xmlDocSetRootElement(new_doc, new_elem);

	xmlChar *ret_val = NULL;
	assert_equals(1, new_doc != NULL);
	assert_equals(0, xmlStrcmp(new_doc->xmlChildrenNode->name, BAD_CAST "Severity"));
	ret_val = xmlGetProp(new_doc->xmlChildrenNode, BAD_CAST NAME_ATTR_NAME);
	assert_equals(0, xmlStrcmp(ret_val, BAD_CAST LEVEL_NAME));
	xmlFree(ret_val);
	ret_val = xmlNodeGetContent(new_doc->xmlChildrenNode);

	char *min = NULL;
	int check = jal_asprintf(&min, "%d", INT_MIN);
	assert_equals(1, check > 0);
	assert_equals(0, xmlStrcmp(ret_val, BAD_CAST min));
	xmlFree(ret_val);
	assert_equals(0, validate(new_doc, __FUNCTION__, TEST_XML_APP_META_TYPES_SCHEMA, 0));
}
Example #4
0
/**
 * as_validator_check_children_quick:
 **/
static void
as_validator_check_children_quick (AsValidator *validator, xmlNode *node, const gchar *allowed_tagname, AsComponent *cpt)
{
	xmlNode *iter;

	for (iter = node->children; iter != NULL; iter = iter->next) {
		const gchar *node_name;
		gchar *node_content;
		/* discard spaces */
		if (iter->type != XML_ELEMENT_NODE)
			continue;
		node_name = (const gchar*) iter->name;
		node_content = (gchar*) xmlNodeGetContent (iter);

		if (g_strcmp0 (node_name, allowed_tagname) == 0) {
			gchar *tag_path;
			tag_path = g_strdup_printf ("%s/%s", (const gchar*) node->name, node_name);
			as_validator_check_content_empty (validator,
								node_content,
								tag_path,
								AS_ISSUE_IMPORTANCE_WARNING,
								cpt);
			g_free (tag_path);
		} else {
			as_validator_add_issue (validator,
						AS_ISSUE_IMPORTANCE_WARNING,
						AS_ISSUE_KIND_TAG_UNKNOWN,
						"Found tag '%s' in section '%s'. Only '%s' tags are allowed.",
						node_name,
						(const gchar*) node->name,
						allowed_tagname);
		}

		g_free (node_content);
	}
}
Example #5
0
//get node under root has not attributes 
int get_eag_node(char * fpath,char * node_name,char *content)
{
	xmlDocPtr pdoc = NULL;

	xmlNodePtr pcurnode = NULL;
	char *psfilename;
	psfilename = fpath;

	pdoc = xmlReadFile(psfilename,"utf-8",256); 

	if(NULL == pdoc)
	{
		return 1;
	}

	pcurnode = xmlDocGetRootElement(pdoc);  

	pcurnode = pcurnode->xmlChildrenNode; 

	xmlChar *value;

	while (NULL != pcurnode)
	{			
		if (!xmlStrcmp(pcurnode->name, BAD_CAST node_name))           
		{
		    
			value = xmlNodeGetContent(pcurnode);        	
			strcpy(content,(char *)value);			 
			xmlFree(value);
		}        
		pcurnode = pcurnode->next; 
	}	  
	//xmlSaveFile(fpath,pdoc);  
	xmlFreeDoc(pdoc);
	return 0;
}
Example #6
0
static void simpleXpathMakeTag (xmlNode *node,
				const tagXpathMakeTagSpec *spec,
				const kindOption* const kinds,
				void *userData)
{
	tagEntryInfo tag;
	xmlChar* str;
	const kindOption *kind;

	str = xmlNodeGetContent(node);
	if (str == NULL)
		return;

	kind = kinds + spec->kind;

	if (spec->role == ROLE_INDEX_DEFINITION)
		initTagEntry (&tag, (char *)str, kind);
	else if (isXtagEnabled(XTAG_REFERENCE_TAGS))
		initRefTagEntry (&tag, (char *)str,
				 kind,
				 spec->role);
	else
		goto out;


	tag.lineNumber = xmlGetLineNo (node);
	tag.filePosition = getInputFilePositionForLine (tag.lineNumber);

	if (spec->make)
		spec->make (node, spec, &tag, userData);
	else
		makeTagEntry (&tag);

out:
	xmlFree (str);
}
Example #7
0
static void
default_parse_item (ProponoConnection *conn, xmlNode *root)
{
  xmlNode *curr;
  xmlChar *s_value;

  for (curr = root->children; curr; curr = curr->next)
    {
      s_value = xmlNodeGetContent (curr);

      if (!xmlStrcmp(curr->name, (const xmlChar *)"host"))
	propono_connection_set_host (conn, s_value);
      else if (!xmlStrcmp(curr->name, (const xmlChar *)"name"))
	propono_connection_set_name (conn, s_value);
      else if (!xmlStrcmp(curr->name, (const xmlChar *)"username"))
	propono_connection_set_username (conn, s_value);
      else if (!xmlStrcmp(curr->name, (const xmlChar *)"port"))
	propono_connection_set_port (conn, atoi (s_value));
      else if (!xmlStrcmp(curr->name, (const xmlChar *)"fullscreen"))
	propono_connection_set_fullscreen (conn, propono_utils_parse_boolean (s_value));

      xmlFree (s_value);
    }
}
Example #8
0
//---------------------------------------------------------------------------
void JsTree::interpret_trace_data_in_data(xmlNodePtr data, std::string& json)
{
    //Format: "text": "name", "data": {"offset": "offset_hexa", "dataValue": "value (value_in_hexa)"}
    std::string offset; //Decimal to hexa
    std::string name;
    std::string value; //decimal + hexa if numerical

    xmlChar *offset_c = xmlGetNoNsProp(data, (const unsigned char*)"offset");
    if (offset_c != NULL)
        offset = (const char *)offset_c;
    xmlChar *name_c = xmlGetNoNsProp(data, (const unsigned char*)"name");
    if (name_c != NULL)
        name = std::string((const char *)name_c);

    xmlChar *value_c = xmlNodeGetContent(data);
    if (value_c != NULL)
        value = std::string((const char *)value_c);

    json += ", \"text\":\"";
    json += name;

    //Block data
    json += "\", \"data\":{";
    bool coma = false;
    if (offset_c)
    {
        interpret_offset(offset, coma, json);
        coma = true;
    }
    if (value.length())
    {
        interpret_value(value, coma, json);
        coma = true;
    }
    json += "}";
}
Example #9
0
static int
xmlSecXPathDataNodeRead(xmlSecXPathDataPtr data, xmlNodePtr node) {
    int ret;

    xmlSecAssert2(data != NULL, -1);
    xmlSecAssert2(data->expr == NULL, -1);
    xmlSecAssert2(data->ctx != NULL, -1);
    xmlSecAssert2(node != NULL, -1);

    ret = xmlSecXPathDataRegisterNamespaces (data, node);
    if(ret < 0) {
        xmlSecInternalError("xmlSecXPathDataRegisterNamespaces", NULL);
        return(-1);
    }

    /* read node content and set expr */
    data->expr = xmlNodeGetContent(node);
    if(data->expr == NULL) {
        xmlSecInvalidNodeContentError(node, NULL, "empty");
        return(-1);
    }

    return(0);
}
Example #10
0
static int
xmlSecOpenSSLHmacNodeRead(xmlSecTransformPtr transform, xmlNodePtr node, xmlSecTransformCtxPtr transformCtx) {
    xmlSecOpenSSLHmacCtxPtr ctx;
    xmlNodePtr cur;

    xmlSecAssert2(xmlSecOpenSSLHmacCheckId(transform), -1);
    xmlSecAssert2(xmlSecTransformCheckSize(transform, xmlSecOpenSSLHmacSize), -1);
    xmlSecAssert2(node!= NULL, -1);
    xmlSecAssert2(transformCtx != NULL, -1);

    ctx = xmlSecOpenSSLHmacGetCtx(transform);
    xmlSecAssert2(ctx != NULL, -1);

    cur = xmlSecGetNextElementNode(node->children); 
    if((cur != NULL) && xmlSecCheckNodeName(cur, xmlSecNodeHMACOutputLength, xmlSecDSigNs)) {  
	xmlChar *content;
	
	content = xmlNodeGetContent(cur);
	if(content != NULL) {
	    ctx->dgstSize = atoi((char*)content);	    
	    xmlFree(content);
	}
	/* todo: error if dgstSize == 0 ?*/
	cur = xmlSecGetNextElementNode(cur->next);
    }
    
    if(cur != NULL) {
	xmlSecErr_a_ignorar5(XMLSEC_ERRORS_HERE,
		    xmlSecErrorsSafeString(xmlSecTransformGetName(transform)),
		    xmlSecErrorsSafeString(xmlSecNodeGetName(cur)),
		    XMLSEC_ERRORS_R_UNEXPECTED_NODE,
		    XMLSEC_ERRORS_NO_MESSAGE);
	return(-1);
    }
    return(0); 
}
static void parse_compatibility(struct uae_prefs *p, xmlNode *node)
{
  for(xmlNode *curr_node = node; curr_node; curr_node = curr_node->next) {
    if (curr_node->type == XML_ELEMENT_NODE && strcmp((const char *)curr_node->name, _T("compatibility")) == 0) {
      xmlChar *content = xmlNodeGetContent(curr_node);
      if(content != NULL) {
        if(strcmp((const char *) content, "flexible-blitter-immediate") == 0)
          p->immediate_blits = 1;
        else if(strcmp((const char *) content, "turbo-floppy") == 0)
          p->floppy_speed = 400;
        else if(strcmp((const char *) content, "flexible-sprite-collisions-spritesplayfield") == 0)
          p->collision_level = 2;
        else if(strcmp((const char *) content, "flexible-sprite-collisions-spritesonly") == 0)
          p->collision_level = 1;
        else if(strcmp((const char *) content, "flexible-sound") == 0)
          p->produce_sound = 2;
        else if(strcmp((const char *) content, "flexible-maxhorizontal-nohires") == 0)
          clip_no_hires = true;
        else if(strcmp((const char *) content, "jit") == 0)
        {
          p->cachesize = 8192;
          p->address_space_24 = 0;
        }
        else if(strcmp((const char *) content, "flexible-cpu-cycles") == 0)
          p->cpu_compatible = 0;
        else if(strcmp((const char *) content, "flexible-maxhorizontal-nosuperhires") == 0)
          ; /* nothing to change */
        else if(strcmp((const char *) content, "flexible-maxvertical-nointerlace") == 0)
          ; /* nothing to change */
        else
          printf("rp9: unknown compatibility: %s\n", content);
        xmlFree(content);
      }      
    }
  }
}
static void parse_ram(struct uae_prefs *p, xmlNode *node)
{
  for(xmlNode *curr_node = node; curr_node; curr_node = curr_node->next) {
    if (curr_node->type == XML_ELEMENT_NODE && strcmp((const char *)curr_node->name, _T("ram")) == 0) {
      xmlChar *content = xmlNodeGetContent(curr_node);
      if(content != NULL) {
        xmlChar *attr = xmlGetProp(curr_node, (const xmlChar *) _T("type"));
        if(attr != NULL) 
        {
          int size = atoi((const char *)content);
          if(strcmp((const char *) attr, "fast") == 0)
            p->fastmem_size = size;
          else if(strcmp((const char *) attr, "z3") == 0)
            p->z3fastmem_size = size;
          else if(strcmp((const char *) attr, "chip") == 0)
            p->chipmem_size = size;
          xmlFree(attr);
        }

        xmlFree(content);
      }      
    }
  }
}
Example #13
0
/// @todo: проверить, обновляется ли parent!
static void pa_addAttributeNode(xmlNode& selfNode, xmlAttr& attrNode) 
{
	if(attrNode.type!=XML_ATTRIBUTE_NODE)
		throw Exception(PARSER_RUNTIME,
			0,
			"must be ATTRIBUTE_NODE");

    /*
     * Add it at the end to preserve parsing order ...
     */
    if (selfNode.properties == NULL) {
        selfNode.properties = &attrNode;
    } else {
        xmlAttrPtr prev = selfNode.properties;

        while (prev->next != NULL)
            prev = prev->next;
        prev->next = &attrNode;
        attrNode.prev = prev;
    }

    if (xmlIsID(selfNode.doc, &selfNode, &attrNode) == 1)
        xmlAddID(NULL, selfNode.doc, xmlNodeGetContent((xmlNode*)&attrNode), &attrNode);
}
Example #14
0
/* parse the cmml head tag */
static void
gst_cmml_parser_parse_head (GstCmmlParser * parser, xmlNodePtr head)
{
  GstCmmlTagHead *head_tag;
  xmlNodePtr walk;
  GValue str_val = { 0 };

  head_tag = g_object_new (GST_TYPE_CMML_TAG_HEAD, NULL);

  g_value_init (&str_val, G_TYPE_STRING);

  /* Parse the content of the node and setup the GST_TAG_CMML_HEAD tag.
   * Create a GST_TAG_TITLE when we find the title element.
   */
  for (walk = head->children; walk; walk = walk->next) {
    if (!xmlStrcmp (walk->name, (xmlChar *) "title")) {
      head_tag->title = xmlNodeGetContent (walk);
    } else if (!xmlStrcmp (walk->name, (xmlChar *) "base")) {
      head_tag->base = xmlGetProp (walk, (xmlChar *) "uri");
    } else if (!xmlStrcmp (walk->name, (xmlChar *) "meta")) {
      if (head_tag->meta == NULL)
        head_tag->meta = g_value_array_new (0);
      /* add a pair name, content to the meta value array */
      g_value_take_string (&str_val,
          (gchar *) xmlGetProp (walk, (xmlChar *) "name"));
      g_value_array_append (head_tag->meta, &str_val);
      g_value_take_string (&str_val,
          (gchar *) xmlGetProp (walk, (xmlChar *) "content"));
      g_value_array_append (head_tag->meta, &str_val);
    }
  }
  g_value_unset (&str_val);

  parser->head_callback (parser->user_data, head_tag);
  g_object_unref (head_tag);
}
void UiThemeSetting::loadUiSelfAdaptArea(const std::string &name,xmlNodePtr node,UiThemeDef *themeDef)
{
    if(name.size() == 0){
        return;
    }
    SelfAdaptBgData *bgData = new SelfAdaptBgData;
    bgData->setName(name);
    std::string key,value;
    while(node){
        if(strcmp((char*)node->name, "text") == 0){
            //filter return char here
            node = node->next;
            continue;
        }else{
            key = (char*)node->name;
            xmlChar *data = xmlNodeGetContent(node);
            value = (char*)data;
            xmlFree(data);
            bgData->setAreaData(key,value);
        }
        node = node->next;
    }
    themeDef->addSelfAdaptBgData(bgData);
}
Example #16
0
/* parse a cmml clip tag */
static void
gst_cmml_parser_parse_clip (GstCmmlParser * parser, xmlNodePtr clip)
{
  GstCmmlTagClip *clip_tag;
  GValue str_val = { 0 };
  guchar *id, *track, *start, *end;
  xmlNodePtr walk;
  GstClockTime start_time = GST_CLOCK_TIME_NONE;
  GstClockTime end_time = GST_CLOCK_TIME_NONE;

  start = xmlGetProp (clip, (xmlChar *) "start");
  if (parser->mode == GST_CMML_PARSER_ENCODE && start == NULL)
    /* XXX: validate the document */
    return;

  id = xmlGetProp (clip, (xmlChar *) "id");
  track = xmlGetProp (clip, (xmlChar *) "track");
  end = xmlGetProp (clip, (xmlChar *) "end");

  if (track == NULL)
    track = (guchar *) g_strdup ("default");

  if (start) {
    if (!strncmp ((gchar *) start, "smpte", 5))
      start_time = gst_cmml_clock_time_from_smpte ((gchar *) start);
    else
      start_time = gst_cmml_clock_time_from_npt ((gchar *) start);
  }

  if (end) {
    if (!strncmp ((gchar *) end, "smpte", 5))
      start_time = gst_cmml_clock_time_from_smpte ((gchar *) end);
    else
      end_time = gst_cmml_clock_time_from_npt ((gchar *) end);
  }

  clip_tag = g_object_new (GST_TYPE_CMML_TAG_CLIP, "id", id,
      "track", track, "start-time", start_time, "end-time", end_time, NULL);

  g_free (id);
  g_free (track);
  g_free (start);
  g_free (end);

  g_value_init (&str_val, G_TYPE_STRING);

  /* parse the children */
  for (walk = clip->children; walk; walk = walk->next) {
    /* the clip is not empty */
    clip_tag->empty = FALSE;

    if (!xmlStrcmp (walk->name, (xmlChar *) "a")) {
      clip_tag->anchor_href = xmlGetProp (walk, (xmlChar *) "href");
      clip_tag->anchor_text = xmlNodeGetContent (walk);
    } else if (!xmlStrcmp (walk->name, (xmlChar *) "img")) {
      clip_tag->img_src = xmlGetProp (walk, (xmlChar *) "src");
      clip_tag->img_alt = xmlGetProp (walk, (xmlChar *) "alt");
    } else if (!xmlStrcmp (walk->name, (xmlChar *) "desc")) {
      clip_tag->desc_text = xmlNodeGetContent (walk);
    } else if (!xmlStrcmp (walk->name, (xmlChar *) "meta")) {
      if (clip_tag->meta == NULL)
        clip_tag->meta = g_value_array_new (0);
      /* add a pair name, content to the meta value array */
      g_value_take_string (&str_val,
          (char *) xmlGetProp (walk, (xmlChar *) "name"));
      g_value_array_append (clip_tag->meta, &str_val);
      g_value_take_string (&str_val,
          (char *) xmlGetProp (walk, (xmlChar *) "content"));
      g_value_array_append (clip_tag->meta, &str_val);
    }
  }
  g_value_unset (&str_val);

  parser->clip_callback (parser->user_data, clip_tag);
  g_object_unref (clip_tag);
}
Example #17
0
/*
 * If there is a mismatch or an error, then gda_connection_add_event_string() is used
 *
 *  - Modifies @sbuffer (to separate HASH from XML part)
 *  - if all OK, extracs the <challenge> value and replace cdata->next_challenge with it (or simply
 *    reset cdata->next_challenge to NULL)
 *
 * Returns: a new #xmlDocPtr, or %NULL on error
 */
static xmlDocPtr
decode_buffer_response (GdaConnection *cnc, WebConnectionData *cdata, SoupBuffer *sbuffer,
			gchar *out_status_chr, guint *out_counter_id)
{
	xmlDocPtr doc;
	gchar *ptr, *response;

	if (out_status_chr)
		*out_status_chr = 0;
	if (out_counter_id)
		*out_counter_id = 0;

	g_assert (sbuffer);
	response = (gchar*) sbuffer->data;

	for (ptr = response; *ptr && (*ptr != '\n'); ptr++);
	if (*ptr != '\n') {
		gda_connection_add_event_string (cnc, _("Could not parse server's reponse"));
		return NULL;
	}
	*ptr = 0;
	ptr++;

	if ((cdata->key && !check_hash (cdata->key, ptr, response)) &&
	    (cdata->server_secret && !check_hash (cdata->server_secret, ptr, response))) {
		gda_connection_add_event_string (cnc, _("Invalid response hash"));
		return NULL;
	}
	doc = xmlParseMemory (ptr, strlen (ptr));

	if (!doc) {
		gda_connection_add_event_string (cnc, _("Could not parse server's reponse"));
		return NULL;
	}
	else {
		xmlNodePtr node, root;

		root = xmlDocGetRootElement (doc);
		for (node = root->children; node; node = node->next) {
			if (!strcmp ((gchar*) node->name, "session")) {
				xmlChar *contents;
				contents = xmlNodeGetContent (node);
				g_free (cdata->session_id);
				cdata->session_id = g_strdup ((gchar*) contents);
				xmlFree (contents);
			}
			else if (!strcmp ((gchar*) node->name, "challenge")) {
				xmlChar *contents;
				if (cdata->next_challenge) {
					g_free (cdata->next_challenge);
					cdata->next_challenge = NULL;
				}
				contents = xmlNodeGetContent (node);
				cdata->next_challenge = g_strdup ((gchar*) contents);
				xmlFree (contents);
			}
			else if (out_status_chr && !strcmp ((gchar*) node->name, "status")) {
				xmlChar *contents;
				contents = xmlNodeGetContent (node);
				*out_status_chr = *contents;
				xmlFree (contents);
			}
			else if (out_counter_id && !strcmp ((gchar*) node->name, "counter")) {
				xmlChar *contents;
				contents = xmlNodeGetContent (node);
				*out_counter_id = atoi ((gchar*) contents);
				xmlFree (contents);
			}
			else if (!cdata->server_id && !strcmp ((gchar*) node->name, "servertype")) {
				xmlChar *contents;
				contents = xmlNodeGetContent (node);
				cdata->server_id = g_strdup ((gchar*) contents);
				xmlFree (contents);

				cdata->reuseable = _gda_provider_reuseable_new (cdata->server_id);
#ifdef DEBUG_WEB_PROV
				g_print ("REUSEABLE [%s]: %p\n", cdata->server_id, cdata->reuseable);
#endif
			}
			else if (!cdata->server_version && !strcmp ((gchar*) node->name, "serverversion")) {
				xmlChar *contents;
				contents = xmlNodeGetContent (node);
				cdata->server_version = g_strdup ((gchar*) contents);
				xmlFree (contents);
#ifdef DEBUG_WEB_PROV
				g_print ("SERVER version [%s]\n", cdata->server_version);
#endif
			}
		}
	}

	return doc;
}
Example #18
0
/*
 * COMMAND: <gda_report_section>
 *
 * creates a new RunContext, then executes its children, and destroys the RunContext
 *
 * uses node's contents: yes
 * requested attributes: "query_name"
 *
 * REM: either "query_name" or a <gda_report_query> sub node must be provided to create a data model.
 */
static gboolean
command_gda_report_section_run (GdaReportEngine *engine, xmlNodePtr node, GSList **created_nodes,
				RunContext *context, GError **error)
{	
	xmlChar *qname;
	RunContext *ctx = NULL;
	
	/* compute stmt to push a RunContext */
	qname = xmlGetProp (node, BAD_CAST "query_name");
	if (qname) {
		GdaStatement *stmt;
		GdaConnection *cnc = NULL;
		xmlChar *prop;

		/* find statement */
		stmt = run_context_find_stmt (engine, context, qname);
		if (!stmt) {
			g_set_error (error, 0, 0,
				     _("Unknown query '%s'"), qname);
			xmlFree (qname);
			return FALSE;
		}

		/* find which connection to use */
		prop = xmlGetProp (node, BAD_CAST "cnc_name");
		cnc = run_context_find_connection (engine, context, prop);
		if (!cnc) {
			if (prop) {
				g_set_error (error, 0, 0,
					     _("No connection named '%s' found"), prop);
				xmlFree (prop);
			}
			else
				g_set_error (error, 0, 0, "%s", 
					     _("No connection specified"));
			return FALSE;
		}

		ctx = run_context_push_with_stmt (engine, context, cnc, stmt, (gchar *) qname, error);
		xmlFree (qname);
	}
	else {
		xmlNodePtr child;
		for (child = node->children; child; child = child->next) {
			if (!strcmp ((gchar *) child->name, "gda_report_query")) {
				GdaStatement *stmt;
				xmlChar *prop;
				GdaConnection *cnc = NULL;
				GdaSqlParser *parser = NULL;

				/* find which connection to use */
				prop = xmlGetProp (child, BAD_CAST "cnc_name");
				cnc = run_context_find_connection (engine, context, prop);
				if (!cnc) {
					if (prop) {
						g_set_error (error, 0, 0,
							     _("No connection named '%s' found"), prop);
						xmlFree (prop);
					}
					else
						g_set_error (error, 0, 0, "%s", 
							     _("No connection specified"));
					return FALSE;
				}
				
				/* parser object */
				parser = g_object_get_data (G_OBJECT (cnc), "__gda_parser");
				if (!parser) {
					parser = gda_connection_create_parser (cnc);
					g_object_set_data_full (G_OBJECT (cnc), "__gda_parser", 
								parser, g_object_unref);
				}
				
				/* statement */
				stmt = gda_sql_parser_parse_string (parser, (gchar *) xmlNodeGetContent (child), 
								    NULL, error);
				if (!stmt)
					return FALSE;

				qname = xmlGetProp (child, BAD_CAST "query_name");
				if (qname) {
					ctx = run_context_push_with_stmt (engine, context, cnc,
									  stmt, (gchar *) qname, error);
					xmlFree (qname);
				}
				else
					ctx = run_context_push_with_stmt (engine, context, cnc,
									  stmt, "context", error);
				if (ctx)
					ctx->stmt = stmt;
				else {
					g_object_unref (stmt);
					return FALSE;
				}
				break;
			}
		}
	}

	if (!ctx) {
		g_set_error (error, 0, 0, "%s", 
			     _("Query is not specified (not named and not defined)"));
		return FALSE;
	}
	
	/* go for the children while iterating */
	if (!real_run_at_node (engine, node->children, ctx, error)) {
		run_context_pop (engine, ctx);
		return FALSE;
	}
	else {
		xmlNodePtr child;
		for (child = node->children; child; child = node->children) {
			xmlUnlinkNode (child);
			*created_nodes = g_slist_prepend (*created_nodes, child);
		}
	}

	*created_nodes = g_slist_reverse (*created_nodes);
	run_context_pop (engine, ctx);

	return TRUE;
}
Example #19
0
File: xdr.c Project: GYGit/reactos
static inline xmlChar* get_attr_val(xmlAttrPtr attr)
{
    return xmlNodeGetContent((xmlNodePtr)attr);
}
Example #20
0
/**
 * Parses a notification and creates the r_notification object
 * @param xml - the XML data
 * @returns the new r_notification* or NULL on error
 */
r_notification* r_notification_parse(str xml)
{
	r_notification *n;
	r_registration *r;
	r_regcontact *rc;
	xmlDocPtr doc=0;
	xmlNodePtr root=0,child=0,nephew=0,node=0;
	xmlChar *reginfo_state=0,*x;
	char c=0;
	
	n = pkg_malloc(sizeof(r_notification));
	if (!n) {
		LOG(L_ERR,"ERR:"M_NAME":r_notification_parse: Error allocating %d bytes\n",
			sizeof(r_notification));
		goto error;
	}
	memset(n,0,sizeof(r_notification));

	if (!dtd) parser_init(pcscf_reginfo_dtd);
	doc=0;
	c = xml.s[xml.len];
	xml.s[xml.len]=0;
	doc = xmlParseDoc((unsigned char *)xml.s);
	if (!doc){
		LOG(L_ERR,"ERR:"M_NAME":r_notification_parse:  This is not a valid XML <%.*s>\n",
			xml.len,xml.s);
		goto error;
	}
	if (xmlValidateDtd(&cvp,doc,dtd)!=1){
		LOG(L_ERR,"ERR:"M_NAME":r_notification_parse:  Verification of XML against DTD failed <%.*s>\n",
			xml.len,xml.s);
		goto error;
	}
	root = xmlDocGetRootElement(doc);
	if (!root){
		LOG(L_ERR,"ERR:"M_NAME":r_notification_parse:  Empty XML <%.*s>\n",
			xml.len,xml.s);
		goto error;
	}

	reginfo_state = xmlGetProp(root,(xmlChar*)"state");
	LOG(L_DBG,"DBG:"M_NAME":r_notification_parse: reginfo_state <%s>\n",
			reginfo_state);
	if (reginfo_state[0]=='f'||reginfo_state[0]=='F')
		n->state = IMS_REGINFO_FULL;
	else 
		n->state = IMS_REGINFO_PARTIAL;
	
	for(child = root->children; child; child = child->next)
		if (child->type == XML_ELEMENT_NODE)
	{
		r = pkg_malloc(sizeof(r_registration));
		if (!r){
			LOG(L_ERR,"ERR:"M_NAME":r_notification_parse: Error allocating %d bytes\n",
				sizeof(r_registration));
			goto error;
		}
		memset(r,0,sizeof(r_registration));
		
		x = xmlGetProp(child,(xmlChar*)"id");
		space_trim_dup(&(r->id),(char*)x);
		xmlFree(x);

		x = xmlGetProp(child,(xmlChar*)"aor");
		space_trim_dup(&(r->aor),(char*)x);
		xmlFree(x);
		
		x = xmlGetProp(child,(xmlChar*)"state");
		
		if (x[0]=='a'||x[0]=='A') 
			r->state = IMS_REGINFO_ACTIVE;
		else 
			r->state = IMS_REGINFO_TERMINATED;
		xmlFree(x);

		for(nephew = child->children; nephew; nephew = nephew->next)
				if (nephew->type == XML_ELEMENT_NODE)
		{
			rc = pkg_malloc(sizeof(r_regcontact));
			if (!rc){
				LOG(L_ERR,"ERR:"M_NAME":r_notification_parse: Error allocating %d bytes\n",
					sizeof(r_regcontact));
				goto error;
			}
			memset(rc,0,sizeof(r_regcontact));
			
			x = xmlGetProp(nephew,(xmlChar*)"id");
			space_trim_dup(&(rc->id),(char*)x);
			xmlFree(x);
				
			x = xmlGetProp(nephew,(xmlChar*)"state");
			if (x[0]=='a'||x[0]=='A') 
				rc->state = IMS_REGINFO_ACTIVE;
			else 
				rc->state = IMS_REGINFO_TERMINATED;
			xmlFree(x);
			
			x = xmlGetProp(nephew,(xmlChar*)"event");
			switch(x[0]){
				case 'r':case 'R':
					switch (x[2]){
						case 'g': case 'G':
							rc->event = IMS_REGINFO_CONTACT_REGISTERED;
							break;
						case 'f': case 'F':
							rc->event = IMS_REGINFO_CONTACT_REFRESHED;
							break;						
						case 'j': case 'J':
							rc->event = IMS_REGINFO_CONTACT_REJECTED;
							break;						
						default:
							rc->event = IMS_REGINFO_NONE;
					}
					break;
				case 'c':case 'C':
					rc->event = IMS_REGINFO_CONTACT_CREATED;	
					break;
				case 's':case 'S':
					rc->event = IMS_REGINFO_CONTACT_SHORTENED;	
					break;
				case 'e':case 'E':
					rc->event = IMS_REGINFO_CONTACT_EXPIRED;	
					break;
				case 'd':case 'D':
					rc->event = IMS_REGINFO_CONTACT_DEACTIVATED;	
					break;
				case 'p':case 'P':
					rc->event = IMS_REGINFO_CONTACT_PROBATION;	
					break;
				case 'u':case 'U':
					rc->event = IMS_REGINFO_CONTACT_UNREGISTERED;	
					break;
				default:
					rc->event = IMS_REGINFO_NONE;	
			}
			xmlFree(x);

			x = xmlGetProp(nephew,(xmlChar*)"expires");			
			if (x) {
				rc->expires = atoi((char*)x);
				xmlFree(x);
			}
			
			node = nephew->children;
			while(node && node->type!=XML_ELEMENT_NODE)
				node =node->next;
			if (node) {
				x = xmlNodeGetContent(node);
				space_trim_dup(&(rc->uri),(char*)x);
				xmlFree(x);
			}
			
			rc->next = r->contact;
			r->contact = rc;
		}
		
		r->next = n->registration;
		n->registration = r;
					
	}
			
	if (reginfo_state) xmlFree(reginfo_state);		
	
	if (doc) xmlFreeDoc(doc);
	xml.s[xml.len]=c;
	return n;
error:	
	if (reginfo_state) xmlFree(reginfo_state);		

	if (doc) xmlFreeDoc(doc);
	xml.s[xml.len]=c;
	if (n) r_notification_free(n);
	return 0;
}
Example #21
0
File: dict.c Project: No-name/dict
GPtrArray * dict_get_translate(const gchar * keyword)
{
	gchar * key_url = NULL;
	htmlDocPtr html_doc = NULL;
	xmlDocPtr doc = NULL;
	xmlNodePtr clone = NULL;
	xmlXPathContextPtr ctx = NULL;
	xmlXPathObjectPtr obj = NULL;
	xmlNodeSetPtr nodeset = NULL;
	gchar * tmp_str = NULL;
	GPtrArray * result = NULL;
	gint i;


	key_url = g_strjoin(NULL, KEY_URL_PREFIX, keyword, KEY_URL_SUFIX, NULL);
	g_debug("KEY-URL: %s", key_url);

	html_doc = htmlReadFile(key_url, NULL, HTML_PARSE_NOWARNING | HTML_PARSE_NOERROR);
	if (!html_doc)
	{
		g_message("KEY-URL %s get failed", key_url);
		goto out;
	}

	ctx = xmlXPathNewContext((xmlDocPtr)html_doc);
	if (!ctx)
	{
		g_message("XPath context creat failed");
		goto out;
	}

	obj = xmlXPathEvalExpression(KEY_WORD_XPATH, ctx);
	if (!obj)
	{
		g_message("XPath eval key word xpath failed");
		goto out;
	}

	if (xmlXPathNodeSetIsEmpty(obj->nodesetval))
	{
		g_message("XPath search keyword failed");
		goto out;
	}

	nodeset = obj->nodesetval;
	g_debug("Key word node set have %d object", nodeset->nodeNr);

	clone = xmlCopyNode(nodeset->nodeTab[0], 1);
	if (!clone)
		goto out;

	doc = xmlNewDoc("1.0");
	if (!doc)
		goto out;

	xmlDocSetRootElement(doc, clone);

	xmlXPathFreeContext(ctx);
	ctx = NULL;

	xmlXPathFreeObject(obj);
	obj = NULL;

	ctx = xmlXPathNewContext(doc);
	if (!ctx)
		goto out;

	obj = xmlXPathEvalExpression("//span[@class='keyword']", ctx);
	if (!obj)
		goto out;

	nodeset = obj->nodesetval;
	tmp_str = xmlNodeGetContent(nodeset->nodeTab[0]->xmlChildrenNode);
	g_debug("The word to search %s", tmp_str);

	xmlFree(tmp_str);
	tmp_str = NULL;

	xmlXPathFreeObject(obj);
	obj = NULL;

	obj = xmlXPathEvalExpression("//ul/li", ctx);
	if (!obj)
		goto out;

	if (xmlXPathNodeSetIsEmpty(obj->nodesetval))
	{
		g_message("Result value is empty");
		goto out;
	}

	nodeset = obj->nodesetval;
	result = g_ptr_array_sized_new(nodeset->nodeNr + 1);
	for (i = 0; i < nodeset->nodeNr; ++i)
	{
		tmp_str = xmlNodeGetContent(nodeset->nodeTab[i]->xmlChildrenNode);
		g_ptr_array_add(result, tmp_str);
	}

	g_ptr_array_add(result, NULL);

out:
	if (doc)
		xmlFreeDoc(doc);

	if (key_url)
		g_free(key_url);

	if (html_doc)
		xmlFreeDoc((xmlDocPtr)html_doc);

	if (ctx)
		xmlXPathFreeContext(ctx);

	if (obj)
		xmlXPathFreeObject(obj);

	return result;
}
Example #22
0
static void check_themes (void)
{
	const char *session_name, *ret;
	char *user_config_file, *cptr, *nptr, *fname;
	GKeyFile *kf;
	GError *err;
	int count;

	orig_lxsession_theme = "";
	orig_openbox_theme = "";

	// construct the file path for lxsession settings
	session_name = g_getenv ("DESKTOP_SESSION");
	if (!session_name) session_name = DEFAULT_SES;
	user_config_file = g_build_filename (g_get_user_config_dir (), "lxsession/", session_name, "/desktop.conf", NULL);

	// read in data from file to a key file structure
	kf = g_key_file_new ();
	if (g_key_file_load_from_file (kf, user_config_file, G_KEY_FILE_KEEP_COMMENTS | G_KEY_FILE_KEEP_TRANSLATIONS, NULL))
	{
		// get data from the key file
		err = NULL;
		ret = g_key_file_get_string (kf, "GTK", "sNet/ThemeName", &err);
		if (err == NULL) orig_lxsession_theme = ret;
	}

	// construct the file path for openbox settings
	fname = g_strconcat (g_ascii_strdown (session_name, -1), "-rc.xml", NULL);
	user_config_file = g_build_filename (g_get_user_config_dir (), "openbox/", fname, NULL);
	g_free (fname);

	// read in data from XML file
	xmlInitParser ();
	LIBXML_TEST_VERSION
	xmlDocPtr xDoc = xmlParseFile (user_config_file);
	if (xDoc)
	{
		xmlXPathContextPtr xpathCtx = xmlXPathNewContext (xDoc);
		xmlXPathObjectPtr xpathObj = xmlXPathEvalExpression ((xmlChar *) "/*[local-name()='openbox_config']/*[local-name()='theme']", xpathCtx);

		// find relevant node and read value
		for (count = 0; count < xpathObj->nodesetval->nodeNr; count++)
		{
			xmlNode *node = xpathObj->nodesetval->nodeTab[count];
			xmlAttr *attr = node->properties;
			xmlNode *cur_node = NULL;
			for (cur_node = node->children; cur_node; cur_node = cur_node->next)
			{
				if (cur_node->type == XML_ELEMENT_NODE)
				{
					if (!strcmp (cur_node->name, "name"))
						orig_openbox_theme = xmlNodeGetContent (cur_node);
				}
			}
		}

		// cleanup XML
		xmlXPathFreeObject (xpathObj);
		xmlXPathFreeContext (xpathCtx);
		xmlSaveFile (user_config_file, xDoc);
		xmlFreeDoc (xDoc);
		xmlCleanupParser ();
	}

	g_free (user_config_file);

	// set the new themes if needed
	if (strcmp ("PiX", orig_lxsession_theme))
	{
		set_lxsession_theme ("PiX");
		if (needs_refresh) system (RELOAD_LXSESSION);
	}
	if (strcmp ("PiX", orig_openbox_theme))
	{
		set_openbox_theme ("PiX");
		system (RELOAD_OPENBOX);
	}
}
Example #23
0
/*===========================================================================*/
static int parseState(xmlDocPtr doc, xmlNodePtr cur, ghmm_xmlfile* f, int * inDegree, int * outDegree, int modelNo) {
#define CUR_PROC "parseState"

  int i, error, order=0, state=-1442, fixed=-985, tied=-9354, M, aprox, label;
  int curX=0, curY=0;
  double pi, prior;
  double *emissions = NULL;
  char *desc = NULL;
  char *s = NULL, *estr;
  int rev, stateFixed=1;
  ghmm_cstate *newcstate;
  ghmm_c_emission *emission;

  xmlNodePtr elem, child, multichild;

  state = getIntAttribute(cur, "id", &error);
  pi = getDoubleAttribute(cur, "initial", &error);
  if (error) {
    estr = ighmm_mprintf(NULL, 0, "can't read required intial probability for"
                         "state %d", state);
    GHMM_LOG(LERROR, estr);
    goto STOP;
  } else

  desc = xmlGetProp(cur, BAD_CAST "desc");

  elem = cur->children;
  while (elem!=NULL) {
    /* ======== silent state ============================================== */
    if ((!xmlStrcmp(elem->name, BAD_CAST "silent"))) {
      switch (f->modelType & PTR_TYPE_MASK) {
      case (GHMM_kDiscreteHMM):
        f->model.d[modelNo]->silent[state] = 1;
        break;
      case (GHMM_kDiscreteHMM+GHMM_kTransitionClasses):
        f->model.ds[modelNo]->silent[state] = 1;
        break;
      case (GHMM_kDiscreteHMM+GHMM_kPairHMM):
      case (GHMM_kDiscreteHMM+GHMM_kPairHMM+GHMM_kTransitionClasses):
        f->model.dp[modelNo]->silent[state] = 1;
        break;
      default:
        GHMM_LOG(LERROR, "invalid modelType");
        goto STOP;
      }
    }

    /* ======== discrete state (possible higher order) ==================== */
    if ((!xmlStrcmp(elem->name, BAD_CAST "discrete"))) {
      assert((f->modelType & GHMM_kDiscreteHMM) && ((f->modelType & GHMM_kPairHMM) == 0));

      /* fixed is a propety of the distribution and optional */
      fixed = getIntAttribute(elem, "fixed", &error);
      if (error)
        fixed = 0;

      /* order is optional for discrete */
      if (f->modelType & GHMM_kHigherOrderEmissions) {
        order = getIntAttribute(elem, "order", &error);
        if (error)
          order = 0;
      }

      rev = getIntAttribute(cur, "rev", &error);
      if (error)
        rev = 0;

      /* parsing emission probabilities */
      s = (char *)xmlNodeGetContent(elem);

      switch (f->modelType & PTR_TYPE_MASK) {

      case (GHMM_kDiscreteHMM):
        f->model.d[modelNo]->s[state].desc = desc;
        f->model.d[modelNo]->s[state].pi = pi;
        f->model.d[modelNo]->s[state].fix = fixed;
        if (f->modelType & GHMM_kHigherOrderEmissions) {
          f->model.d[modelNo]->order[state] = order;
          if (f->model.d[modelNo]->maxorder < order) {
            f->model.d[modelNo]->maxorder = order;
            estr = ighmm_mprintf(NULL, 0, "Updated maxorder to %d\n",
                                 f->model.d[modelNo]->maxorder);
            GHMM_LOG(LDEBUG, estr);
            m_free(estr);
          }
        }
        ARRAY_MALLOC(emissions, pow(f->model.d[modelNo]->M, order+1));
        parseCSVList(s, pow(f->model.d[modelNo]->M, order+1), emissions, rev);
        free(f->model.d[modelNo]->s[state].b);
        f->model.d[modelNo]->s[state].b = emissions;
        break;

      case (GHMM_kDiscreteHMM+GHMM_kTransitionClasses):
        f->model.ds[modelNo]->s[state].desc = desc;
        f->model.ds[modelNo]->s[state].pi = pi;
        f->model.ds[modelNo]->s[state].fix = fixed;
        if (f->modelType & GHMM_kHigherOrderEmissions)
          f->model.ds[modelNo]->order[state] = order;
        ARRAY_MALLOC(emissions, pow(f->model.ds[modelNo]->M, order+1));
        parseCSVList(s, pow(f->model.ds[modelNo]->M, order+1), emissions, rev);
        f->model.ds[modelNo]->s[state].b = emissions;
        break;

      default:
        GHMM_LOG(LERROR, "invalid modelType");
        goto STOP;
      }
      m_free(s);
    }

    /* ======== continuous state ========================================== */
    if ((!xmlStrcmp(elem->name, BAD_CAST "mixture"))) {
      assert(f->modelType & GHMM_kContinuousHMM);
      M = 0;
      child = elem->children;
      while (child != NULL) {
        if ((!xmlStrcmp(child->name, BAD_CAST "normal")) ||
            (!xmlStrcmp(child->name, BAD_CAST "normalLeftTail")) ||
            (!xmlStrcmp(child->name, BAD_CAST "normalRightTail")) ||
            (!xmlStrcmp(child->name, BAD_CAST "multinormal")) ||
            (!xmlStrcmp(child->name, BAD_CAST "uniform"))){
          M ++;

        }
        child = child->next;
      }
      ghmm_cstate_alloc(f->model.c[modelNo]->s + state, M, inDegree[state], outDegree[state], f->model.c[modelNo]->cos);
      newcstate = f->model.c[modelNo]->s + state;

      newcstate->desc = desc;
      newcstate->M = M;
      newcstate->pi = pi;

      if( f->model.c[modelNo]->M < M)
        f->model.c[modelNo]->M = M;

      child = elem->children;

      i = 0;
      while (child != NULL) {

        emission = newcstate->e+i;

        /* common attributes */
        if ((!xmlStrcmp(child->name, BAD_CAST "normal")) ||
            (!xmlStrcmp(child->name, BAD_CAST "normalLeftTail")) ||
            (!xmlStrcmp(child->name, BAD_CAST "normalRightTail")) ||
            (!xmlStrcmp(child->name, BAD_CAST "multinormal")) ||
            (!xmlStrcmp(child->name, BAD_CAST "uniform"))){
          fixed = getIntAttribute(child, "fixed", &error);
          if (error)
            fixed = 0;
          stateFixed = fixed && stateFixed;
          /* allocate emission */
          emission->fixed = fixed;

          prior = getDoubleAttribute(child, "prior", &error);
          if (error)
            prior = 1.0;
          newcstate->c[i] = prior;
        }
        /* child is not a density, continue with the next child */
        else {
          child = child->next;
          continue;
        }

        /* density type dependent attributes */
        if ((!xmlStrcmp(child->name, BAD_CAST "normal"))) {
          emission->mean.val  = getDoubleAttribute(child, "mean", &error);
          emission->variance.val = getDoubleAttribute(child, "variance", &error);
          /* should the normal distribution be approximated? */
          aprox = getIntAttribute(child, "approx", &error);
          if (error)
            aprox = 0;
          emission->type      = aprox ? normal_approx : normal;
          emission->dimension = 1;
          if (f->model.c[modelNo]->dim > 1) {
            GHMM_LOG(LERROR, "All emissions must have same dimension.");
            goto STOP;
          }
        }
        if ((!xmlStrcmp(child->name, BAD_CAST "normalLeftTail"))) {
          emission->mean.val  = getDoubleAttribute(child, "mean", &error);
          emission->variance.val = getDoubleAttribute(child, "variance", &error);
          emission->min       = getDoubleAttribute(child, "max", &error);
          emission->type      = normal_left;
          emission->dimension = 1;
          if (f->model.c[modelNo]->dim > 1) {
            GHMM_LOG(LERROR, "All emissions must have same dimension.");
            goto STOP;
          }
        }
        if ((!xmlStrcmp(child->name, BAD_CAST "normalRightTail"))) {

          emission->mean.val  = getDoubleAttribute(child, "mean", &error);
          emission->variance.val = getDoubleAttribute(child, "variance", &error);
          emission->max       = getDoubleAttribute(child, "min", &error);
          emission->type      = normal_right;
          emission->dimension = 1;
          if (f->model.c[modelNo]->dim > 1) {
            GHMM_LOG(LERROR, "All emissions must have same dimension.");
            goto STOP;
          }
        }
        if ((!xmlStrcmp(child->name, BAD_CAST "uniform"))) {
          emission->max  = getDoubleAttribute(child, "max", &error);
          emission->min  = getDoubleAttribute(child, "min", &error);
          emission->type = uniform;
          emission->dimension = 1;
          if (f->model.c[modelNo]->dim > 1) {
            GHMM_LOG(LERROR, "All emissions must have same dimension.");
            goto STOP;
          }
        }
        if ((!xmlStrcmp(child->name, BAD_CAST "multinormal"))) {
          emission->type = multinormal;
          emission->dimension = getIntAttribute(child, "dimension", &error);

          /* check that all emissions in all states have same dimension or
             set when first emission is read*/
          if (f->model.c[modelNo]->dim <= 1)
            f->model.c[modelNo]->dim = emission->dimension;
          else if (f->model.c[modelNo]->dim != emission->dimension) {
            GHMM_LOG(LERROR, "All emissions must have same dimension.");
            goto STOP;
          }

          if (0 != ghmm_c_emission_alloc(emission, emission->dimension)) {
            GHMM_LOG(LERROR, "Can not allocate multinormal emission.");
            goto STOP;
          }
          multichild = child->children;
          while (multichild != NULL) {
            if ((!xmlStrcmp(multichild->name, BAD_CAST "mean"))) {
              s = (char *)xmlNodeGetContent(multichild);
              if (-1 == parseCSVList(s, emission->dimension, emission->mean.vec, 0)) {
                GHMM_LOG(LERROR, "Can not parse mean CSV list.");
                goto STOP;
              }
            }
            if ((!xmlStrcmp(multichild->name, BAD_CAST "variance"))) {
              s = (char *)xmlNodeGetContent(multichild);
              if (-1 == parseCSVList(s, emission->dimension * emission->dimension,
                                     emission->variance.mat, 0)) {
                GHMM_LOG(LERROR, "Can not parse variance CSV list.");
                goto STOP;
              }
              if (0 != ighmm_invert_det(emission->sigmainv, &emission->det,
                                        emission->dimension, emission->variance.mat))
              {
                GHMM_LOG(LERROR, "Can not calculate inverse of covariance matrix.");
                goto STOP;
              }
              if (0 != ighmm_cholesky_decomposition(emission->sigmacd,
                                                    emission->dimension,
                                                    emission->variance.mat))
              {
                GHMM_LOG(LERROR, "Can not calculate cholesky decomposition of covariance matrix.");
                goto STOP;
              }
            }
            multichild = multichild->next;
          }
        }
        i++;
        child = child->next;
      }
      newcstate->fix = stateFixed;
    }

    /* ======== pair hmm state ============================================ */
    if ((!xmlStrcmp(elem->name, BAD_CAST "pair"))) {
    }

    /* -------- background name  ------------------------------------------ */
    if ((!xmlStrcmp(elem->name, BAD_CAST "backgroundKey"))) {

      assert(f->modelType & GHMM_kBackgroundDistributions);

      s = (char *)xmlNodeGetContent(elem);

      for (i=0; i<f->model.d[modelNo]->bp->n; i++) {
        if (0 == strcmp(s, f->model.d[modelNo]->bp->name[i])) {
          if (order != f->model.d[modelNo]->bp->order[i]) {
            estr = ighmm_mprintf(NULL, 0, "order of background %s and state %d"
                                 " does not match",
                                 f->model.d[modelNo]->bp->name[i], state);
            GHMM_LOG(LERROR, estr);
            m_free(estr);
            goto STOP;
          } else {
            f->model.d[modelNo]->background_id[state] = i;
            break;
          }
        }
      }
      if (i == f->model.d[modelNo]->bp->n) {
        estr = ighmm_mprintf(NULL, 0, "can't find background with name %s in"
                             " state %d", s, state);
        GHMM_LOG(LERROR, estr);
        m_free(estr);
        goto STOP;
      }
      m_free(s);
    }

    /* -------- tied to --------------------------------------------------- */
    if ((!xmlStrcmp(elem->name, BAD_CAST "class"))) {

      assert(f->modelType & GHMM_kLabeledStates);

      s = (char *)xmlNodeGetContent(elem);
      label = atoi(s);
      m_free(s);
      if ((f->modelType & PTR_TYPE_MASK) == GHMM_kDiscreteHMM) {
        if (f->model.d[modelNo]->label_alphabet->size > label)
          f->model.d[modelNo]->label[state] = label;
        else
          GHMM_LOG(LWARN, "Invalid label");
      }
    }

    /* -------- tied to --------------------------------------------------- */
    if ((!xmlStrcmp(elem->name, BAD_CAST "tiedTo"))) {

      assert(f->modelType & GHMM_kTiedEmissions);

      s = (char *)xmlNodeGetContent(elem);
      tied = atoi(s);
      if (state>=tied) {
        f->model.d[modelNo]->tied_to[state] = tied;
        if (f->model.d[modelNo]->tied_to[tied] != tied) {
          estr = ighmm_mprintf(NULL, 0, "state %d not tied to tie group leader", state);
          GHMM_LOG(LERROR, estr);
          m_free(estr);
          goto STOP;
        }
      } else {
        estr = ighmm_mprintf(NULL, 0, "state %d tiedTo (%d) is invalid", state, tied);
        GHMM_LOG(LERROR, estr);
        m_free(estr);
        goto STOP;
      }
      m_free(s);
    }

    /* -------- position for graphical editing ---------------------------- */
    if ((!xmlStrcmp(elem->name, BAD_CAST "position"))) {
      curX = getIntAttribute(elem, "x", &error);
      if (error)
        GHMM_LOG(LWARN, "failed to read x position");
      curY = getIntAttribute(elem, "y", &error);
      if (error)
        GHMM_LOG(LWARN, "failed to read y position");

      switch (f->modelType & PTR_TYPE_MASK) {
      case GHMM_kDiscreteHMM:
        f->model.d[modelNo]->s[state].xPosition = curX;
        f->model.d[modelNo]->s[state].yPosition = curY;
        break;
      case GHMM_kDiscreteHMM+GHMM_kTransitionClasses:
        f->model.ds[modelNo]->s[state].xPosition = curX;
        f->model.ds[modelNo]->s[state].yPosition = curY;
        break;
      case GHMM_kDiscreteHMM+GHMM_kPairHMM:
      case GHMM_kDiscreteHMM+GHMM_kPairHMM+GHMM_kTransitionClasses:
        f->model.dp[modelNo]->s[state].xPosition = curX;
        f->model.dp[modelNo]->s[state].yPosition = curY;
        break;
      case GHMM_kContinuousHMM:
      case GHMM_kContinuousHMM+GHMM_kTransitionClasses:
      case (GHMM_kContinuousHMM+GHMM_kMultivariate):
      case (GHMM_kContinuousHMM+GHMM_kMultivariate+GHMM_kTransitionClasses):
        f->model.c[modelNo]->s[state].xPosition = curX;
        f->model.c[modelNo]->s[state].yPosition = curY;
        break;
      default:
        GHMM_LOG(LERROR, "invalid modelType");
        goto STOP;
      }
    }

    elem = elem->next;
  }

  return 0;
STOP:
  m_free(s);
  m_free(desc);
  m_free(emissions)
  return -1;
#undef CUR_PROC
}
Example #24
0
osrfHash* oilsIDLInit( const char* idl_filename ) {

	if (idlHash) return idlHash;

	char* prop_str = NULL;

	idlHash = osrfNewHash();
	osrfHash* class_def_hash = NULL;

	osrfLogInfo(OSRF_LOG_MARK, "Parsing the IDL XML...");
	idlDoc = xmlReadFile( idl_filename, NULL, XML_PARSE_XINCLUDE );
	
	if (!idlDoc) {
		osrfLogError(OSRF_LOG_MARK, "Could not load or parse the IDL XML file!");
		return NULL;
	}

	osrfLogDebug(OSRF_LOG_MARK, "Initializing the Fieldmapper IDL...");

	xmlNodePtr docRoot = xmlDocGetRootElement(idlDoc);
	xmlNodePtr kid = docRoot->children;
	while (kid) {
		if (!strcmp( (char*)kid->name, "class" )) {

			class_def_hash = osrfNewHash();
			char* current_class_name = (char*) xmlGetProp(kid, BAD_CAST "id");
			
			osrfHashSet( class_def_hash, current_class_name, "classname" );
			osrfHashSet( class_def_hash, xmlGetNsProp(kid, BAD_CAST "fieldmapper", BAD_CAST OBJECT_NS), "fieldmapper" );
			osrfHashSet( class_def_hash, xmlGetNsProp(kid, BAD_CAST "readonly", BAD_CAST PERSIST_NS), "readonly" );

			osrfHashSet( idlHash, class_def_hash, current_class_name );

			if ((prop_str = (char*)xmlGetNsProp(kid, BAD_CAST "tablename", BAD_CAST PERSIST_NS))) {
				osrfLogDebug(OSRF_LOG_MARK, "Using table '%s' for class %s", prop_str, current_class_name );
				osrfHashSet(
					class_def_hash,
					prop_str,
					"tablename"
				);
			}

			if ((prop_str = (char*)xmlGetNsProp(kid, BAD_CAST "restrict_primary", BAD_CAST PERSIST_NS))) {
				osrfLogDebug(OSRF_LOG_MARK, "Delete restriction policy set at '%s' for pkey of class %s", prop_str, current_class_name );
				osrfHashSet(
					class_def_hash,
					prop_str,
					"restrict_primary"
				);
			}

			if ((prop_str = (char*)xmlGetNsProp(kid, BAD_CAST "virtual", BAD_CAST PERSIST_NS))) {
				osrfHashSet(
					class_def_hash,
					prop_str,
					"virtual"
				);
			}

			// Tokenize controller attribute into an osrfStringArray
			prop_str = (char*) xmlGetProp(kid, BAD_CAST "controller");
			if( prop_str )
				osrfLogDebug(OSRF_LOG_MARK, "Controller list is %s", prop_str );
			osrfStringArray* controller = osrfStringArrayTokenize( prop_str, ' ' );
			xmlFree( prop_str );
			osrfHashSet( class_def_hash, controller, "controller");

			osrfHash* current_links_hash = osrfNewHash();
			osrfHash* current_fields_hash = osrfNewHash();

			osrfHashSet( class_def_hash, current_fields_hash, "fields" );
			osrfHashSet( class_def_hash, current_links_hash, "links" );

			xmlNodePtr _cur = kid->children;

			while (_cur) {

				if (!strcmp( (char*)_cur->name, "fields" )) {

					if( (prop_str = (char*)xmlGetNsProp(_cur, BAD_CAST "primary", BAD_CAST PERSIST_NS)) ) {
						osrfHashSet(
							class_def_hash,
							prop_str,
							"primarykey"
						);
					}

					if( (prop_str = (char*)xmlGetNsProp(_cur, BAD_CAST "sequence", BAD_CAST PERSIST_NS)) ) {
						osrfHashSet(
							class_def_hash,
							prop_str,
							"sequence"
						);
					}

					unsigned int array_pos = 0;
					char array_pos_buf[ 7 ];  // For up to 1,000,000 fields per class

					xmlNodePtr _f = _cur->children;
					while(_f) {
						if (strcmp( (char*)_f->name, "field" )) {
							_f = _f->next;
							continue;
						}

						// Get the field name.  If it's one of the three standard
						// fields that we always generate, ignore it.
						char* field_name = (char*)xmlGetProp(_f, BAD_CAST "name");
						if( field_name ) {
							osrfLogDebug(OSRF_LOG_MARK, 
									"Found field %s for class %s", field_name, current_class_name );
							if(    !strcmp( field_name, "isnew" )
								|| !strcmp( field_name, "ischanged" )
								|| !strcmp( field_name, "isdeleted" ) ) {
								free( field_name );
								_f = _f->next;
								continue;
							}
						} else {
							osrfLogDebug(OSRF_LOG_MARK,
									"Found field with no name for class %s", current_class_name );
							_f = _f->next;
							continue;
						}
 
						osrfHash* field_def_hash = osrfNewHash();

						// Insert array_position
						snprintf( array_pos_buf, sizeof( array_pos_buf ), "%u", array_pos++ );
						osrfHashSet( field_def_hash, strdup( array_pos_buf ), "array_position" );

						if( (prop_str = (char*)xmlGetNsProp(_f, BAD_CAST "i18n", BAD_CAST PERSIST_NS)) ) {
							osrfHashSet(
								field_def_hash,
								prop_str,
								"i18n"
							);
						}

						if( (prop_str = (char*)xmlGetNsProp(_f, BAD_CAST "virtual", BAD_CAST PERSIST_NS)) ) {
							osrfHashSet(
								field_def_hash,
								prop_str,
								"virtual"
							);
						} else {   // default to virtual
							osrfHashSet(
								field_def_hash,
								"false",
								"virtual"
							);
						}

						if( (prop_str = (char*)xmlGetNsProp(_f, BAD_CAST "primitive", BAD_CAST PERSIST_NS)) ) {
							osrfHashSet(
								field_def_hash,
								prop_str,
								"primitive"
							);
						}

						osrfHashSet( field_def_hash, field_name, "name" );
						osrfHashSet(
							current_fields_hash,
							field_def_hash,
							field_name
						);
						_f = _f->next;
					}

					// Create three standard, stereotyped virtual fields for every class
					add_std_fld( current_fields_hash, "isnew",     array_pos++ );
					add_std_fld( current_fields_hash, "ischanged", array_pos++ );
					add_std_fld( current_fields_hash, "isdeleted", array_pos   );

				}

				if (!strcmp( (char*)_cur->name, "links" )) {
					xmlNodePtr _l = _cur->children;

					while(_l) {
						if (strcmp( (char*)_l->name, "link" )) {
							_l = _l->next;
							continue;
						}

						osrfHash* link_def_hash = osrfNewHash();

						if( (prop_str = (char*)xmlGetProp(_l, BAD_CAST "reltype")) ) {
							osrfHashSet(
								link_def_hash,
								prop_str,
								"reltype"
							);
							osrfLogDebug(OSRF_LOG_MARK, "Adding link with reltype %s", prop_str );
						} else
							osrfLogDebug(OSRF_LOG_MARK, "Adding link with no reltype" );

						if( (prop_str = (char*)xmlGetProp(_l, BAD_CAST "key")) ) {
							osrfHashSet(
								link_def_hash,
								prop_str,
								"key"
							);
							osrfLogDebug(OSRF_LOG_MARK, "Link fkey is %s", prop_str );
						} else
							osrfLogDebug(OSRF_LOG_MARK, "Link with no fkey" );

						if( (prop_str = (char*)xmlGetProp(_l, BAD_CAST "class")) ) {
							osrfHashSet(
								link_def_hash,
								prop_str,
								"class"
							);
							osrfLogDebug(OSRF_LOG_MARK, "Link fclass is %s", prop_str );
						} else
							osrfLogDebug(OSRF_LOG_MARK, "Link with no fclass" );

						// Tokenize map attribute into an osrfStringArray
						prop_str = (char*) xmlGetProp(_l, BAD_CAST "map");
						if( prop_str )
							osrfLogDebug(OSRF_LOG_MARK, "Link mapping list is %s", prop_str );
						osrfStringArray* map = osrfStringArrayTokenize( prop_str, ' ' );
						osrfHashSet( link_def_hash, map, "map");
						xmlFree( prop_str );

						if( (prop_str = (char*)xmlGetProp(_l, BAD_CAST "field")) ) {
							osrfHashSet(
								link_def_hash,
								prop_str,
								"field"
							);
							osrfLogDebug(OSRF_LOG_MARK, "Link fclass is %s", prop_str );
						} else
							osrfLogDebug(OSRF_LOG_MARK, "Link with no fclass" );

						osrfHashSet(
							current_links_hash,
							link_def_hash,
							prop_str
						);

						_l = _l->next;
					}
				}
/**** Structure of permacrud in memory ****

{ create :
    { permission : [ x, y, z ],
      global_required : "true", -- anything else, or missing, is false
      local_context : [ f1, f2 ],
      foreign_context : { class1 : { fkey : local_class_key, field : class1_field, context : [ a, b, c ] }, ...}
    },
  retrieve : null, -- no perm check, or structure similar to the others
  update : -- like create
    ...
  delete : -- like create
    ...
}   

**** Structure of permacrud in memory ****/

				if (!strcmp( (char*)_cur->name, "permacrud" )) {
					osrfHash* pcrud = osrfNewHash();
					osrfHashSet( class_def_hash, pcrud, "permacrud" );
					xmlNodePtr _l = _cur->children;

					while(_l) {
						if (strcmp( (char*)_l->name, "actions" )) {
							_l = _l->next;
							continue;
						}

						xmlNodePtr _a = _l->children;

						while(_a) {
							const char* action_name = (const char*) _a->name;
							if (
								strcmp( action_name, "create" ) &&
								strcmp( action_name, "retrieve" ) &&
								strcmp( action_name, "update" ) &&
								strcmp( action_name, "delete" )
							) {
								_a = _a->next;
								continue;
							}

							osrfLogDebug(OSRF_LOG_MARK, "Found Permacrud action %s for class %s",
								action_name, current_class_name );

							osrfHash* action_def_hash = osrfNewHash();
							osrfHashSet( pcrud, action_def_hash, action_name );

							// Tokenize permission attribute into an osrfStringArray
							prop_str = (char*) xmlGetProp(_a, BAD_CAST "permission");
							if( prop_str )
								osrfLogDebug(OSRF_LOG_MARK,
									"Permacrud permission list is %s", prop_str );
							osrfStringArray* map = osrfStringArrayTokenize( prop_str, ' ' );
							osrfHashSet( action_def_hash, map, "permission");
							xmlFree( prop_str );

					    	osrfHashSet( action_def_hash,
								(char*)xmlGetNoNsProp(_a, BAD_CAST "global_required"), "global_required");

							// Tokenize context_field attribute into an osrfStringArray
							prop_str = (char*) xmlGetProp(_a, BAD_CAST "context_field");
							if( prop_str )
								osrfLogDebug(OSRF_LOG_MARK,
									"Permacrud context_field list is %s", prop_str );
							map = osrfStringArrayTokenize( prop_str, ' ' );
							osrfHashSet( action_def_hash, map, "local_context");
							xmlFree( prop_str );

							osrfHash* foreign_context = osrfNewHash();
							osrfHashSet( action_def_hash, foreign_context, "foreign_context");

							xmlNodePtr _f = _a->children;

							while(_f) {
								if ( strcmp( (char*)_f->name, "context" ) ) {
									_f = _f->next;
									continue;
								}

								if( (prop_str = (char*)xmlGetNoNsProp(_f, BAD_CAST "link")) ) {
									osrfLogDebug(OSRF_LOG_MARK,
										"Permacrud context link definition is %s", prop_str );

									osrfHash* _tmp_fcontext = osrfNewHash();

									// Store pointers to elements already stored
									// from the <link> aggregate
									osrfHash* _flink = osrfHashGet( current_links_hash, prop_str );
									osrfHashSet( _tmp_fcontext, osrfHashGet(_flink, "field"), "fkey" );
									osrfHashSet( _tmp_fcontext, osrfHashGet(_flink, "key"), "field" );
									xmlFree( prop_str );

								    if( (prop_str = (char*)xmlGetNoNsProp(_f, BAD_CAST "jump")) )
									    osrfHashSet( _tmp_fcontext, osrfStringArrayTokenize( prop_str, '.' ), "jump" );
									xmlFree( prop_str );

									// Tokenize field attribute into an osrfStringArray
									char * field_list = (char*) xmlGetProp(_f, BAD_CAST "field");
									if( field_list )
										osrfLogDebug(OSRF_LOG_MARK,
											"Permacrud foreign context field list is %s", field_list );
									map = osrfStringArrayTokenize( field_list, ' ' );
									osrfHashSet( _tmp_fcontext, map, "context");
									xmlFree( field_list );

									// Insert the new hash into a hash attached to the parent node
									osrfHashSet( foreign_context, _tmp_fcontext, osrfHashGet( _flink, "class" ) );

								} else {

									if( (prop_str = (char*)xmlGetNoNsProp(_f, BAD_CAST "field") )) {
										char* map_list = prop_str;
										osrfLogDebug(OSRF_LOG_MARK,
											"Permacrud local context field list is %s", prop_str );
			
										if (strlen( map_list ) > 0) {
											char* st_tmp = NULL;
											char* _map_class = strtok_r(map_list, " ", &st_tmp);
											osrfStringArrayAdd(
												osrfHashGet( action_def_hash, "local_context"), _map_class);
									
											while ((_map_class = strtok_r(NULL, " ", &st_tmp))) {
												osrfStringArrayAdd(
													osrfHashGet( action_def_hash, "local_context"), _map_class);
											}
										}
										xmlFree(map_list);
									}

								}
								_f = _f->next;
							}
							_a = _a->next;
						}
						_l = _l->next;
					}
				}

				if (!strcmp( (char*)_cur->name, "source_definition" )) {
					char* content_str;
					if( (content_str = (char*)xmlNodeGetContent(_cur)) ) {
						osrfLogDebug(OSRF_LOG_MARK, "Using source definition '%s' for class %s",
							content_str, current_class_name );
						osrfHashSet(
							class_def_hash,
							content_str,
							"source_definition"
						);
					}

				}

				_cur = _cur->next;
			} // end while
		}

		kid = kid->next;
	} // end while

	osrfLogInfo(OSRF_LOG_MARK, "...IDL XML parsed");

	return idlHash;
}
Example #25
0
static void xml_to_node(xmlNodePtr xml_node, plist_t * plist_node)
{
    xmlNodePtr node = NULL;
    plist_data_t data = NULL;
    plist_t subnode = NULL;

    //for string
    long len = 0;
    int type = 0;

    if (!xml_node)
        return;

    for (node = xml_node->children; node; node = node->next)
    {

        while (node && !xmlStrcmp(node->name, XPLIST_TEXT))
            node = node->next;
        if (!node)
            break;

        if (!xmlStrcmp(node->name, BAD_CAST("comment"))) {
            continue;
        }

        data = plist_new_plist_data();
        subnode = plist_new_node(data);
        if (*plist_node)
            node_attach(*plist_node, subnode);
        else
            *plist_node = subnode;

        if (!xmlStrcmp(node->name, XPLIST_TRUE))
        {
            data->boolval = TRUE;
            data->type = PLIST_BOOLEAN;
            data->length = 1;
            continue;
        }

        if (!xmlStrcmp(node->name, XPLIST_FALSE))
        {
            data->boolval = FALSE;
            data->type = PLIST_BOOLEAN;
            data->length = 1;
            continue;
        }

        if (!xmlStrcmp(node->name, XPLIST_INT))
        {
            xmlChar *strval = xmlNodeGetContent(node);
            int is_negative = 0;
            char *str = (char*)strval;
            if ((str[0] == '-') || (str[0] == '+')) {
                if (str[0] == '-') {
                    is_negative = 1;
                }
                str++;
            }
            char* endp = NULL;
            data->intval = strtoull((char*)str, &endp, 0);
            if ((endp != NULL) && (strlen(endp) > 0)) {
                fprintf(stderr, "%s: integer parse error: string contains invalid characters: '%s'\n", __func__, endp);
            }
            if (is_negative || (data->intval <= INT64_MAX)) {
                int64_t v = data->intval;
                if (is_negative) {
                    v = -v;
                }
                data->intval = (uint64_t)v;
                data->length = 8;
            } else {
                data->length = 16;
            }
            data->type = PLIST_UINT;
            xmlFree(strval);
            continue;
        }

        if (!xmlStrcmp(node->name, XPLIST_REAL))
        {
            xmlChar *strval = xmlNodeGetContent(node);
            data->realval = atof((char *) strval);
            data->type = PLIST_REAL;
            data->length = 8;
            xmlFree(strval);
            continue;
        }

        if (!xmlStrcmp(node->name, XPLIST_DATE))
        {
            xmlChar *strval = xmlNodeGetContent(node);
            time_t timev = 0;
            if (strlen((const char*)strval) >= 11) {
                struct tm btime;
                struct tm* tm_utc;
                parse_date((const char*)strval, &btime);
                timev = mktime(&btime);
                tm_utc = gmtime(&timev);
                timev -= (mktime(tm_utc) - timev);
            }
            data->timeval.tv_sec = (long)(timev - MAC_EPOCH);
            data->timeval.tv_usec = 0;
            data->type = PLIST_DATE;
            data->length = sizeof(struct timeval);
            xmlFree(strval);
            continue;
        }

        if (!xmlStrcmp(node->name, XPLIST_STRING))
        {
            xmlChar *strval = xmlNodeGetContent(node);
            len = strlen((char *) strval);
            type = xmlDetectCharEncoding(strval, len);

            if (XML_CHAR_ENCODING_UTF8 == type || XML_CHAR_ENCODING_ASCII == type || XML_CHAR_ENCODING_NONE == type)
            {
                data->strval = strdup((char *) strval);
                data->type = PLIST_STRING;
                data->length = strlen(data->strval);
            }
            xmlFree(strval);
            continue;
        }

        if (!xmlStrcmp(node->name, XPLIST_KEY))
        {
            xmlChar *strval = xmlNodeGetContent(node);
            len = strlen((char *) strval);
            type = xmlDetectCharEncoding(strval, len);

            if (XML_CHAR_ENCODING_UTF8 == type || XML_CHAR_ENCODING_ASCII == type || XML_CHAR_ENCODING_NONE == type)
            {
                data->strval = strdup((char *) strval);
                data->type = PLIST_KEY;
                data->length = strlen(data->strval);
            }
            xmlFree(strval);
            continue;
        }

        if (!xmlStrcmp(node->name, XPLIST_DATA))
        {
            xmlChar *strval = xmlNodeGetContent(node);
            size_t size = 0;
            unsigned char *dec = base64decode((char*)strval, &size);
            data->buff = (uint8_t *) malloc(size * sizeof(uint8_t));
            memcpy(data->buff, dec, size * sizeof(uint8_t));
            free(dec);
            data->length = size;
            data->type = PLIST_DATA;
            xmlFree(strval);
            continue;
        }

        if (!xmlStrcmp(node->name, XPLIST_ARRAY))
        {
            data->type = PLIST_ARRAY;
            xml_to_node(node, &subnode);
            continue;
        }

        if (!xmlStrcmp(node->name, XPLIST_DICT))
        {
            data->type = PLIST_DICT;
            xml_to_node(node, &subnode);
            if (plist_get_node_type(subnode) == PLIST_DICT) {
                if (plist_dict_get_size(subnode) == 1) {
                    plist_t uid = plist_dict_get_item(subnode, "CF$UID");
                    if (uid) {
                        uint64_t val = 0;
                        plist_get_uint_val(uid, &val);
                        plist_dict_remove_item(subnode, "CF$UID");
                        plist_data_t nodedata = plist_get_data((node_t*)subnode);
                        free(nodedata->buff);
                        nodedata->type = PLIST_UID;
                        nodedata->length = sizeof(uint64_t);
                        nodedata->intval = val;
                    } 
                }
            }
            continue;
        }
    }
}
Example #26
0
int pres_watcher_allowed(subs_t* subs)
{
    xmlDocPtr xcap_tree= NULL;
    xmlNodePtr node= NULL,  actions_node = NULL;
    xmlNodePtr sub_handling_node = NULL;
    char* sub_handling = NULL;
	
    subs->status= PENDING_STATUS;
    subs->reason.s= NULL;
    subs->reason.len= 0;

    if (subs->auth_rules_doc== NULL)
	return 0;

    xcap_tree= xmlParseMemory(subs->auth_rules_doc->s,
			      subs->auth_rules_doc->len);
    if (xcap_tree== NULL) {
	LM_ERR("parsing xml memory\n");
	return -1;
    }

    node= get_rule_node(subs, xcap_tree);
    if (node== NULL) {
	xmlFreeDoc(xcap_tree);
	return 0;
	}

    /* process actions */	
    actions_node = xmlNodeGetChildByName(node, "actions");
    if (actions_node == NULL) {
	LM_DBG("actions_node NULL\n");
	xmlFreeDoc(xcap_tree);
	return 0;
    }
    LM_DBG("actions_node->name= %s\n", actions_node->name);
			
    sub_handling_node = xmlNodeGetChildByName(actions_node, "sub-handling");
    if (sub_handling_node== NULL) {
	LM_DBG("sub_handling_node NULL\n");
	xmlFreeDoc(xcap_tree);
	return 0;
    }
    sub_handling = (char*)xmlNodeGetContent(sub_handling_node);
    LM_DBG("sub_handling_node->name= %s\n", sub_handling_node->name);
    LM_DBG("sub_handling_node->content= %s\n", sub_handling);
	
    if (sub_handling == NULL) {
	LM_ERR("Couldn't get sub-handling content\n");
	xmlFreeDoc(xcap_tree);
	return -1;
    }
    if (strncmp((char*)sub_handling, "block", 5) == 0) {
	subs->status = TERMINATED_STATUS;;
	subs->reason.s= "rejected";
	subs->reason.len = 8;
    } else	
	if (strncmp((char*)sub_handling, "confirm", 7) == 0) {
	    subs->status = PENDING_STATUS;
	} else
	    if (strncmp((char*)sub_handling , "polite-block", 12) == 0) {
		subs->status = ACTIVE_STATUS;
		subs->reason.s= "polite-block";
		subs->reason.len = 12;
	    }
	else
	    if (strncmp((char*)sub_handling, "allow", 5) == 0) {
		subs->status = ACTIVE_STATUS;
		subs->reason.s = NULL;
	    }
	    else {
		LM_ERR("unknown subscription handling action\n");
		xmlFreeDoc(xcap_tree);
		xmlFree(sub_handling);
		return -1;
	    }

	xmlFreeDoc(xcap_tree);
    xmlFree(sub_handling);

    return 0;

}
Example #27
0
xmlNodePtr get_rule_node(subs_t* subs, xmlDocPtr xcap_tree)
{
    str w_uri = {0, 0};
    char* id = NULL, *domain = NULL, *time_cont= NULL;
    int apply_rule = -1;
    xmlNodePtr ruleset_node = NULL, node1= NULL, node2= NULL;
    xmlNodePtr cond_node = NULL, except_node = NULL;
    xmlNodePtr identity_node = NULL;
    xmlNodePtr iden_child;
    xmlNodePtr validity_node, time_node;
    time_t t_init, t_fin, t;
    int valid= 0;

    uandd_to_uri(subs->from_user, subs->from_domain, &w_uri);
    if (w_uri.s == NULL) {
	LM_ERR("while creating uri\n");
	return NULL;
    }
    ruleset_node = xmlDocGetNodeByName(xcap_tree, "ruleset", NULL);
    if (ruleset_node == NULL) {
	LM_DBG("ruleset_node NULL\n");
	goto error;
    }	
    for (node1 = ruleset_node->children; node1; node1 = node1->next) {
	if (xmlStrcasecmp(node1->name, (unsigned char*)"text") == 0)
	    continue;

	/* process conditions */
	LM_DBG("node1->name= %s\n", node1->name);
	
	cond_node = xmlNodeGetChildByName(node1, "conditions");
	if(cond_node == NULL) {
	    LM_DBG("cond node NULL\n");
	    goto error;
	}
	LM_DBG("cond_node->name= %s\n", cond_node->name);

	validity_node = xmlNodeGetChildByName(cond_node, "validity");
	if (validity_node != NULL) {
	    LM_DBG("found validity tag\n");
	    
	    t= time(NULL);
		
	    /* search all from-until pair */
	    for (time_node = validity_node->children; time_node;
		time_node = time_node->next) {
		if (xmlStrcasecmp(time_node->name, (unsigned char*)"from")!= 0)
		    continue;

		time_cont= (char*)xmlNodeGetContent(time_node);
		t_init= xml_parse_dateTime(time_cont);
		xmlFree(time_cont);
		if (t_init< 0) {
		    LM_ERR("failed to parse xml dateTime\n");
		    goto error;
		}

		if (t< t_init) {
		    LM_DBG("the lower time limit is not respected\n");
		    continue;
		}
				
		time_node= time_node->next;
		while (1) {
		    if (time_node == NULL) {
			LM_ERR("bad formatted xml doc:until child not found in"
			       " validity pair\n");
			goto error;
		    }
		    if( xmlStrcasecmp(time_node->name, 
				      (unsigned char*)"until")== 0)
			break;
		    time_node= time_node->next;
		}
				
		time_cont = (char*)xmlNodeGetContent(time_node);
		t_fin= xml_parse_dateTime(time_cont);
		xmlFree(time_cont);
		
		if (t_fin< 0) {
		    LM_ERR("failed to parse xml dateTime\n");
		    goto error;
		}
			
		if (t <= t_fin) {
		    LM_DBG("the rule is active at this time\n");
		    valid= 1;
		}
			
	    }
		
	    if (!valid) {
		LM_DBG("the rule is not active at this time\n");
		continue;
	    }
	    
	}	

	identity_node = xmlNodeGetChildByName(cond_node, "identity");
	if (identity_node == NULL) {
	    LM_ERR("didn't find identity tag\n");
	    goto error;
	}	
		
	iden_child = xmlNodeGetChildByName(identity_node, "one");
	if(iden_child) {
	    for (node2 = identity_node->children; node2; node2 = node2->next) {
		if(xmlStrcasecmp(node2->name, (unsigned char*)"one")!= 0)
		    continue;
				
		id = xmlNodeGetAttrContentByName(node2, "id");	
		if(id== NULL) {
		    LM_ERR("while extracting attribute\n");
		    goto error;
		}
		if ((strlen(id)== w_uri.len && 
		     (strncmp(id, w_uri.s, w_uri.len)==0))) {
		    apply_rule = 1;
		    xmlFree(id);
		    break;
		}
		xmlFree(id);
	    }
	}	

	/* search for many node*/
	iden_child = xmlNodeGetChildByName(identity_node, "many");
	if (iden_child)	{
	    domain = NULL;
	    for (node2 = identity_node->children; node2; node2 = node2->next) {
		if (xmlStrcasecmp(node2->name, (unsigned char*)"many") != 0)
		    continue;
	
		domain = xmlNodeGetAttrContentByName(node2, "domain");
		if(domain == NULL) {
		    LM_DBG("No domain attribute to many\n");
		} else	{
		    LM_DBG("<many domain= %s>\n", domain);
		    if((strlen(domain)!= subs->from_domain.len && 
			strncmp(domain, subs->from_domain.s,
				subs->from_domain.len) )) {
			xmlFree(domain);
			continue;
		    }	
		}
		xmlFree(domain);
		apply_rule = 1;
		if (node2->children == NULL)       /* there is no exception */
		    break;

		for (except_node = node2->children; except_node;
		     except_node= except_node->next) {
		    if(xmlStrcasecmp(except_node->name,
				     (unsigned char*)"except"))
			continue;

		    id = xmlNodeGetAttrContentByName(except_node, "id");	
		    if (id != NULL) {
			if((strlen(id)- 1== w_uri.len && 
			    (strncmp(id, w_uri.s, w_uri.len)==0))) {
			    xmlFree(id);
			    apply_rule = 0;
			    break;
			}
			xmlFree(id);
		    } else {
			domain = NULL;
			domain = xmlNodeGetAttrContentByName(except_node,
							     "domain");
			if(domain!=NULL) {
			    LM_DBG("Found except domain= %s\n- strlen(domain)= %d\n",
				   domain, (int)strlen(domain));
			    if (strlen(domain)==subs->from_domain.len &&
				(strncmp(domain,subs->from_domain.s ,
					 subs->from_domain.len)==0)) {
				LM_DBG("except domain match\n");
				xmlFree(domain);
				apply_rule = 0;
				break;
			    }
			    xmlFree(domain);
			}	
		    }	
		}
		if (apply_rule == 1)  /* if a match was found no need to keep searching*/
		    break;
	    }
	}
	if (apply_rule ==1)
	    break;
    }

    LM_DBG("apply_rule= %d\n", apply_rule);
    if(w_uri.s!=NULL)
	pkg_free(w_uri.s);

    if( !apply_rule || !node1)
	return NULL;
    
    return node1;

 error:
    if(w_uri.s)
	pkg_free(w_uri.s);
    return NULL;
}
Example #28
0
void
RL::Heap::edit ()
{
  Ekiga::FormRequestSimple request(sigc::mem_fun (this, &RL::Heap::on_edit_form_submitted));

  std::string name_str;
  std::string root_str;
  std::string username_str;
  std::string password_str;
  std::string user_str;
  bool writable = false;

  {
    xmlChar* str = xmlNodeGetContent (root);
    if (str != NULL) {

      root_str = (const char*)str;
      xmlFree (str);
    }
  }
  {
    xmlChar* str = xmlNodeGetContent (user);
    if (str != NULL) {

      user_str = (const char*)str;
      xmlFree (str);
    }
  }
  {
    xmlChar* str = xmlNodeGetContent (username);
    if (str != NULL) {

      username_str = (const char*)str;
      xmlFree (str);
    }
  }
  {
    xmlChar* str = xmlNodeGetContent (password);
    if (str != NULL) {

      password_str = (const char*)str;
      xmlFree (str);
    }
  }
  {
    xmlChar* str = xmlGetProp (node, BAD_CAST "writable");
    if (str != NULL) {

      if (xmlStrEqual (str, BAD_CAST "1"))
	writable = true;
      xmlFree (str);
    }
  }

  request.title (_("Edit contact list properties"));

  request.instructions (_("Please edit the following fields (no identifier"
			  " means global)"));

  request.text ("name", _("Contact list's name"), get_name ());
  /* "Document" used as a name -- uri point to the root of a document tree */
  request.text ("root", _("Document root"), root_str);
  request.text ("user", _("Identifier"), user_str);
  request.boolean ("writable", _("Writable"), writable);
  request.text ("username", _("Server username"), username_str);
  request.private_text ("password", _("Server password"), password_str);

  if (!questions.handle_request (&request)) {

    // FIXME: better error reporting
#ifdef __GNUC__
    std::cout << "Unhandled form request in "
	      << __PRETTY_FUNCTION__ << std::endl;
#endif
  }
}
Example #29
0
void FissionReactor::setConfig(const Vocabulary& v, const xmlNodePtr config_ptr)
{
	// first set config options for the Reactor base class
	ConfigWriteLock cfg_lock(*this);
	Reactor::setConfig(v, config_ptr);

	// get the input event type
	std::string config_str;
	if (! ConfigManager::getConfigOption(INPUT_EVENT_TYPE_ELEMENT_NAME, config_str, config_ptr))
		throw EmptyInputEventTypeException(getId());

	// find vocabulary term for input event type
	Vocabulary::TermRef term_ref = v.findTerm(config_str);
	if (term_ref == Vocabulary::UNDEFINED_TERM_REF)
		throw UnknownTermException(config_str);
	m_input_event_type = v[term_ref];

	// make sure that term is object/event type
	if (m_input_event_type.term_type != Vocabulary::TYPE_OBJECT)
		throw NotAnObjectException(config_str);

	// get the input event term
	if (! ConfigManager::getConfigOption(INPUT_EVENT_TERM_ELEMENT_NAME, config_str, config_ptr))
		throw EmptyInputEventTermException(getId());

	// find vocabulary term for input event term
	term_ref = v.findTerm(config_str);
	if (term_ref == Vocabulary::UNDEFINED_TERM_REF)
		throw UnknownTermException(config_str);
	m_input_event_term = v[term_ref];

	// only string types are currently supported for input event term
	switch (m_input_event_term.term_type) {
	case Vocabulary::TYPE_NULL:
	case Vocabulary::TYPE_OBJECT:
	case Vocabulary::TYPE_INT8:
	case Vocabulary::TYPE_INT16:
	case Vocabulary::TYPE_INT32:
	case Vocabulary::TYPE_UINT8:
	case Vocabulary::TYPE_UINT16:
	case Vocabulary::TYPE_UINT32:
	case Vocabulary::TYPE_INT64:
	case Vocabulary::TYPE_UINT64:
	case Vocabulary::TYPE_FLOAT:
	case Vocabulary::TYPE_DOUBLE:
	case Vocabulary::TYPE_LONG_DOUBLE:
	case Vocabulary::TYPE_DATE_TIME:
	case Vocabulary::TYPE_DATE:
	case Vocabulary::TYPE_TIME:
		throw TermNotStringException(config_str);
		break;
	case Vocabulary::TYPE_SHORT_STRING:
	case Vocabulary::TYPE_STRING:
	case Vocabulary::TYPE_LONG_STRING:
	case Vocabulary::TYPE_CHAR:
	case Vocabulary::TYPE_BLOB:
	case Vocabulary::TYPE_ZBLOB:
		break;	// these are all OK
	}

	// get the codec to use
	boost::mutex::scoped_lock codec_lock(m_codec_mutex);
	if (! ConfigManager::getConfigOption(CODEC_ELEMENT_NAME, m_codec_id, config_ptr))
		throw EmptyCodecException(getId());
	m_codec_ptr = getCodecFactory().getCodec(m_codec_id);	
	PION_ASSERT(m_codec_ptr);
	codec_lock.unlock();

	// check if we should copy all terms from original event
	m_copy_all_terms = false;
	std::string copy_all_terms_str;
	if (ConfigManager::getConfigOption(COPY_ALL_TERMS_ELEMENT_NAME,
									   copy_all_terms_str, config_ptr))
	{
		if (copy_all_terms_str == "true")
			m_copy_all_terms = true;
	}

	// get list of terms to copy from original event
	m_copy_terms.clear();
	xmlNodePtr copy_term_node = config_ptr;
	while ((copy_term_node = ConfigManager::findConfigNodeByName(COPY_TERM_ELEMENT_NAME, copy_term_node)) != NULL) {
		xmlChar *xml_char_ptr = xmlNodeGetContent(copy_term_node);
		if (xml_char_ptr != NULL) {
			const std::string copy_term_str(reinterpret_cast<char*>(xml_char_ptr));
			xmlFree(xml_char_ptr);
			if (! copy_term_str.empty()) {
				// find the term in the Vocabulary
				term_ref = v.findTerm(copy_term_str);
				if (term_ref == Vocabulary::UNDEFINED_TERM_REF)
					throw UnknownTermException(copy_term_str);

				// add it to the copy terms collection
				m_copy_terms.push_back(v[term_ref]);
			}
		}

		// step to the next copy term
		copy_term_node = copy_term_node->next;
	}
}
Example #30
0
void
RL::Heap::on_new_entry_form_submitted (bool submitted,
				       Ekiga::Form& result)
{
  if (!submitted)
    return;

  std::string entry_name = result.text ("name");
  std::string entry_uri = result.text ("uri");
  std::set<std::string> entry_groups = result.editable_set ("groups");

  xmlNodePtr entry_node = xmlNewChild (list_node, NULL,
				       BAD_CAST "entry", NULL);
  xmlSetProp (entry_node, BAD_CAST "uri",
	      BAD_CAST robust_xmlEscape (doc.get (), entry_uri).c_str ());
  xmlNewChild (entry_node, NULL, BAD_CAST "display-name",
	       BAD_CAST robust_xmlEscape (doc.get (), entry_name).c_str ());
  xmlNsPtr ns = xmlSearchNsByHref (doc.get (), entry_node,
				   BAD_CAST "http://www.ekiga.org");
  if (ns == NULL) {

    // FIXME: we should handle the case, even if it shouldn't happen
  }

  for (std::set<std::string>::const_iterator iter = entry_groups.begin ();
       iter != entry_groups.end ();
       ++iter) {

    xmlNewChild (entry_node, ns, BAD_CAST "group",
		 BAD_CAST robust_xmlEscape (doc.get (), *iter).c_str ());
  }

  xmlBufferPtr buffer = xmlBufferCreate ();
  int res = xmlNodeDump (buffer, doc.get (), entry_node, 0, 0);

  if (res >= 0) {

    std::string root_str;
    std::string username_str;
    std::string password_str;
    std::string user_str;

    {
      xmlChar* str = xmlNodeGetContent (root);
      if (str != NULL)
	root_str = (const char*)str;
    }
    {
      xmlChar* str = xmlNodeGetContent (user);
      if (str != NULL)
	user_str = (const char*)str;
    }
    {
      xmlChar* str = xmlNodeGetContent (username);
      if (str != NULL)
	username_str = (const char*)str;
    }
    {
      xmlChar* str = xmlNodeGetContent (password);
      if (str != NULL)
	password_str = (const char*)str;
    }
    gmref_ptr<XCAP::Path> path(new XCAP::Path (root_str, "resource-lists",
					       user_str));
    path->set_credentials (username_str, password_str);
    path = path->build_child ("resource-lists");
    path = path->build_child ("list");
    path = path->build_child_with_attribute ("entry", "uri", entry_uri);
    gmref_ptr<XCAP::Core> xcap(services.get ("xcap-core"));
    xcap->write (path, "application/xcap-el+xml",
		 (const char*)xmlBufferContent (buffer),
		 sigc::mem_fun (this, &RL::Heap::new_entry_result));
  }
  xmlBufferFree (buffer);
}