Example #1
0
// TODO: Refactor: This function differs from EPUB3ParseOPFFromData by 1 line.
EPUB3Error EPUB3ParseNCXFromData(EPUB3Ref epub, void * buffer, uint32_t bufferSize)
{
  assert(epub != NULL);
  assert(buffer != NULL);
  assert(bufferSize > 0);

  EPUB3Error error = kEPUB3Success;
  xmlInitParser();
  xmlTextReaderPtr reader = NULL;
  reader = xmlReaderForMemory(buffer, bufferSize, NULL, NULL, XML_PARSE_RECOVER | XML_PARSE_NONET);
  if(reader != NULL) {
    EPUB3XMLParseContext contextStack[PARSE_CONTEXT_NCX_STACK_DEPTH];
    EPUB3XMLParseContextPtr currentContext = &contextStack[0];

    int retVal = xmlTextReaderRead(reader);
    currentContext->state = kEPUB3NCXStateRoot;
    currentContext->tagName = xmlTextReaderConstName(reader);
    while(retVal == 1)
    {
//      _EPUB3DumpXMLParseContextStack(&currentContext);
        error = EPUB3ParseXMLReaderNodeForNCX(epub, reader, &currentContext);
        if (error != kEPUB3NCXNavMapEnd && reader != NULL) {
            retVal = xmlTextReaderRead(reader);
        }
        else {
            retVal = 0;
            error = kEPUB3Success;
        }
    }
    if(retVal < 0) {
      error = kEPUB3XMLParseError;
    }
  } else {
    error = kEPUB3XMLReadFromBufferError;
  }
  xmlFreeTextReader(reader);
  xmlCleanupParser();
  return error;
}
Example #2
0
/**
 * processNode:
 * @reader: the xmlReader
 *
 * Dump information about the current node
 */
static void processNode (xmlTextReaderPtr reader) {
	const xmlChar *name, *value;

	name = xmlTextReaderConstName (reader);
	if (name == NULL)
		name = BAD_CAST "--";

	value = xmlTextReaderConstValue (reader);

	printf ("%d %d %s %d %d", xmlTextReaderDepth (reader),
	                xmlTextReaderNodeType (reader), name,
	                xmlTextReaderIsEmptyElement (reader),
	                xmlTextReaderHasValue (reader));
	if (value == NULL)
		printf ("\n");
	else {
		if (xmlStrlen (value) > 40)
			printf (" %.40s...\n", value);
		else
			printf (" %s\n", value);
	}
}
Example #3
0
void XmlParser::_readRelation() {
    std::string idStr;
    std::string versionStr;
    std::string timestampStr;
    std::string changesetStr;
    std::string uidStr;
    std::string userStr;
    std::string actionStr;
    std::string visibleStr;
    // Read attributes
    if (xmlTextReaderHasAttributes(_reader) == XmlStatus::TRUE) {
        while (xmlTextReaderMoveToNextAttribute(_reader)) {
            std::string k = (char*) xmlTextReaderConstName(_reader);
            std::string v = (char*) xmlTextReaderConstValue(_reader);
            if (k == "id") {
                idStr = v;
            } else if (k == "version") {
                versionStr = v;
            } else if (k == "timestamp") {
                timestampStr = v;
            } else if (k == "changeset") {
                changesetStr = v;
            } else if (k == "uid") {
                uidStr = v;
            } else if (k == "user") {
                userStr = v;
            } else if (k == "action") {
                actionStr = v;
            } else if (k == "visible") {
                visibleStr = v;
            }
        }
    }
    _parentElementType = ElementType::RELATION;
    _parentElementId = idStr;
    _dbBuilder.addRelation(idStr, versionStr, timestampStr, changesetStr,
                  uidStr, userStr, actionStr, visibleStr);
}
Example #4
0
int xmlconfig_load( const char *filename )
{
	int rc = -1;
	int ret;
	xmlTextReaderPtr reader;
	const xmlChar *name;
        
	reader = xmlReaderForFile( filename, NULL, 0 );
	if ( reader != NULL ) {
		ret = xmlTextReaderRead( reader );
		while (ret == 1) {
			name = xmlTextReaderConstName( reader );
			if ( name &&
                            (XML_READER_TYPE_ELEMENT == xmlTextReaderNodeType( reader )) &&
                            ( 0 == xmlStrncmp( name, (const xmlChar *)"NodeConfig", 10 ) ) )
			{
				xmlconfig_load_node( reader );
			}
			else if ( name &&
                            (XML_READER_TYPE_ELEMENT == xmlTextReaderNodeType( reader )) &&
                            ( 0 == xmlStrncmp( name, (const xmlChar *)"TimerConfig", 10 ) ) )
			{
				xmlconfig_load_timer( reader );
			}
			ret = xmlTextReaderRead( reader );
		}
		xmlFreeTextReader( reader );
		if (ret != 0) {
			fprintf( stderr, "%s : failed to parse\n", filename );
			goto out;
		}
		rc = 0;
	} else {
		fprintf( stderr, "Unable to open %s\n", filename );
	}
out:
	return rc;
}
static void
process_bijiben_start_elem (BijiLazyDeserializer *self)
{
  BijiLazyDeserializerPrivate *priv = self->priv;
  const gchar *element_name;

  element_name = (const gchar *) xmlTextReaderConstName(priv->inner);

  /* Block level elements introduce a new line, except that blocks
     at the very beginning of their parent don't, and <br/> at the
     end of a block causes the next block to skip the new line.
     list-item elements add also a bullet at the beginning.

     These are the only block elements we produce and therefore
     support. If you manage to introduce more (eg. by copy-pasting),
     you accept that the result may not be faithful.

     TODO: use webkit_web_view_get_snapshot() instead of showing
     the raw text content in the main view.
  */
  if (g_strcmp0 (element_name, "br") == 0) {
    g_string_append (priv->raw_text, "\n");
    priv->seen_content = FALSE;
  }

  if (priv->seen_content &&
      (g_strcmp0 (element_name, "div") == 0 ||
       g_strcmp0 (element_name, "br") == 0 ||
       g_strcmp0 (element_name, "ul") == 0 ||
       g_strcmp0 (element_name, "ol") == 0 ||
       g_strcmp0 (element_name, "li") == 0)) {
    g_string_append (priv->raw_text, "\n");
    priv->seen_content = FALSE;
  }

  if (g_strcmp0 (element_name, "li") == 0)
    g_string_append (priv->raw_text, "- ");
}
bool MMSXMLServerInterface::funcSendEvent(xmlNodePtr node, string *answer) {
    xmlChar  *heading, *name, *value;/**pluginid*/
    xmlTextReader *reader;
	MMSEvent *event;

    if(!node || !answer) return false;

    /* get attributes */
    heading  = xmlGetProp(node, (const xmlChar*)"heading");
    reader = xmlReaderWalker(node->doc);
    //pluginid = xmlTextReaderGetAttribute(reader, (const xmlChar*)"pluginid");

    if(!heading /*|| !pluginid*/) return false;

    event = new MMSEvent((const char*)heading);

    /* through <func/> childs */
    while(xmlTextReaderRead(reader)) {
        name = (xmlChar*)xmlTextReaderConstName(reader);
        if(name && xmlStrEqual(name, (const xmlChar*)"param")) {
            while(xmlTextReaderMoveToNextAttribute(reader)) {
                name  = xmlTextReaderName(reader);
                value = xmlTextReaderValue(reader);
                event->setData((const char*)name, (const char*)value);
                xmlFree(name);
                xmlFree(value);
            }
        }
    }
	/* build answer */
	*answer = "<ret/>";

    event->send();


    return true;
}
Example #7
0
int XMIResource::loadGeometry(xmlTextReaderPtr reader, const model::BaseObject& o)
{
    assert(o.kind() == BLOCK || o.kind() == ANNOTATION || o.kind() == LINK);

    std::vector<double> geom;
    controller.getObjectProperty(o.id(), o.kind(), GEOMETRY, geom);
    geom.resize(4);

    // iterate on attributes
    for (int rc = xmlTextReaderMoveToFirstAttribute(reader); rc > 0; rc = xmlTextReaderMoveToNextAttribute(reader))
    {
        auto found = std::find(constXcosNames.begin(), constXcosNames.end(), xmlTextReaderConstName(reader));
        enum xcosNames current = static_cast<enum xcosNames>(std::distance(constXcosNames.begin(), found));
        switch (current)
        {
            case e_x:
                geom[0] = to_double(xmlTextReaderConstValue(reader));
                break;
            case e_y:
                geom[1] = to_double(xmlTextReaderConstValue(reader));
                break;
            case e_width:
                geom[2] = to_double(xmlTextReaderConstValue(reader));
                break;
            case e_height:
                geom[3] = to_double(xmlTextReaderConstValue(reader));
                break;
            default:
                // ignore other parameters
                // TODO: Does other metamodels might be managed there ?
                break;
        }
    }

    controller.setObjectProperty(o.id(), o.kind(), GEOMETRY, geom);
    return 1;
}
Example #8
0
void XmlParser::_readTag() {
    std::string k;
    std::string v;
    // Read attributes
    if (xmlTextReaderHasAttributes(_reader) == XmlStatus::TRUE) {
        while (xmlTextReaderMoveToNextAttribute(_reader)) {
            std::string key = (char*) xmlTextReaderConstName(_reader);
            std::string val = (char*) xmlTextReaderConstValue(_reader);
            if (key == "k") {
                k = val;
            } else if (key == "v") {
                v = val;
            }
        }
    }
    
    // Only blast the previous tags for the element once when updating.
    if (_prevTagParentElementId == _parentElementId) {
        _dbBuilder.addTag(_parentElementType, _parentElementId, k, v, false);
    } else {
        _dbBuilder.addTag(_parentElementType, _parentElementId, k, v, true);
        _prevTagParentElementId = _parentElementId;
    }
}
Example #9
0
static gboolean
gstyle_palette_xml_get_header (xmlTextReaderPtr   reader,
                               gchar            **id,
                               gchar            **name,
                               gchar            **domain)
{
  g_assert (reader != NULL);
  g_assert (id != NULL);
  g_assert (name != NULL);
  g_assert (domain != NULL);

  *id = *name = *domain = NULL;
  if (xmlTextReaderRead(reader) == 1 &&
      xmlTextReaderNodeType (reader) == XML_READER_TYPE_ELEMENT &&
      !g_strcmp0 (XML_TO_CHAR (xmlTextReaderConstName (reader)), "palette") &&
      xmlTextReaderDepth (reader) == 0)
    {
      *id = strdup_and_xmlfree (xmlTextReaderGetAttribute (reader, CHAR_TO_XML ("id")));
      *name = strdup_and_xmlfree (xmlTextReaderGetAttribute (reader, CHAR_TO_XML ("name")));
      if (*name == NULL)
        {
          *name = strdup_and_xmlfree (xmlTextReaderGetAttribute (reader, CHAR_TO_XML ("_name")));
          *domain = strdup_and_xmlfree (xmlTextReaderGetAttribute (reader, CHAR_TO_XML ("gettext-domain")));
        }
      if (gstyle_str_empty0 (*id) || gstyle_utf8_is_spaces (*id))
        {
          g_warning ("Palette '%s'has an empty or NULL id\n", *name);
          return FALSE;
        }

      if (gstyle_utf8_is_spaces (*name))
        g_clear_pointer (name, g_free);
    }

  return (*id != NULL);
}
Example #10
0
// ref: http://xmlsoft.org/examples/index.html#reader1.c
void xml::xmlreader(const  char *filename) {
	LIBXML_TEST_VERSION
	xmlTextReaderPtr reader;
	if((reader = xmlReaderForFile(filename, NULL, 0)) != NULL) {
		while(xmlTextReaderRead(reader) == 1) {
			const xmlChar *name;
			const xmlChar *value;
			if((name = xmlTextReaderConstName(reader)) != NULL) {
				value = xmlTextReaderConstValue(reader);
				cout << xmlTextReaderDepth(reader)
					<< " " << xmlTextReaderNodeType(reader)
					<< " " << name
					<< " " << xmlTextReaderIsEmptyElement(reader)
					<< " " << xmlTextReaderHasValue(reader);
				if(value != NULL)
					cout << endl;
				cout.flush();
			}

		}
		xmlFreeTextReader(reader);
	}
	xmlCleanupParser();
}
Example #11
0
static GstyleColor *
gstyle_palette_xml_get_color (xmlTextReaderPtr reader)
{
  GstyleColor *color = NULL;
  g_autofree gchar *name;
  g_autofree gchar *value;

  g_assert (reader != NULL);

  if (xmlTextReaderNodeType (reader) == XML_READER_TYPE_ELEMENT &&
      !g_strcmp0 (XML_TO_CHAR (xmlTextReaderConstName (reader)), "color") &&
      xmlTextReaderDepth (reader) == 1)
    {
      name = strdup_and_xmlfree (xmlTextReaderGetAttribute (reader, CHAR_TO_XML ("name")));
      if (gstyle_utf8_is_spaces (name))
        g_clear_pointer (&name, g_free);

      value = strdup_and_xmlfree (xmlTextReaderGetAttribute (reader, CHAR_TO_XML ("value")));
      if (!gstyle_str_empty0 (value))
        color = gstyle_color_new_from_string (name, value);
    }

  return color;
}
    bool XMLReader::isObjectNode() const
    {
      const xmlChar* name = xmlTextReaderConstName(m_reader) ;

      return isBeginNode() && xmlStrEqual(name, (const xmlChar*) "object") == 1 ;
    }
Example #13
0
/* process a single node in the xml file */
int sechk_lib_process_xml_node(xmlTextReaderPtr reader, sechk_lib_t * lib)
{
	xmlChar *attrib = NULL;
	int idx;
	sechk_name_value_t *nv = NULL;
	static xmlChar *option = NULL;
	static xmlChar *value = NULL;
	static sechk_module_t *current_module = NULL;

	switch (xmlTextReaderNodeType(reader)) {

	case XML_ELEMENT_DECL:	       /* closing tags */
		if (xmlStrEqual(xmlTextReaderConstName(reader), (xmlChar *) SECHK_PARSE_MODULE_TAG) == 1) {
			current_module = NULL;
		} else if (xmlStrEqual(xmlTextReaderConstName(reader), (xmlChar *) SECHK_PARSE_OPTION_TAG) == 1) {
			free(option);
			option = NULL;
		}
		break;

	case XML_ELEMENT_NODE:	       /* opening tags */

		if (xmlStrEqual(xmlTextReaderConstName(reader), (xmlChar *) SECHK_PARSE_SECHECKER_TAG) == 1) {
			/* parsing the <sechecker> tag */
			attrib = xmlTextReaderGetAttribute(reader, (xmlChar *) SECHK_PARSE_VERSION_ATTRIB);
			if (attrib) {
#ifdef SECHECKER_VERSION
				if (atof((const char *)attrib) > atof(SECHECKER_VERSION)) {
					fprintf(stderr,
						"Error: sechecker version in profile is incorrect: expected %1.1f got %1.1f\n",
						atof(SECHECKER_VERSION), atof((const char *)attrib));
					goto exit_err;
				}
#endif

				free(attrib);
				attrib = NULL;
			} else {
				fprintf(stderr, "Warning: sechecker version is not specified.\n");
			}
		} else if (xmlStrEqual(xmlTextReaderConstName(reader), (xmlChar *) SECHK_PARSE_MODULE_TAG) == 1) {
			/* parsing the <module> tag */
			attrib = xmlTextReaderGetAttribute(reader, (xmlChar *) SECHK_PARSE_NAME_ATTRIB);
			if (attrib) {
				if ((idx = sechk_lib_get_module_idx((const char *)attrib, lib)) == -1) {
					fprintf(stderr, "Warning: module %s not found.\n", (const char *)attrib);
					return 1;	/* not a fatal error */
				} else {
					/* set the values on the existing module */
					current_module = apol_vector_get_element(lib->modules, idx);
					current_module->selected = true;
				}
				free(attrib);
				attrib = NULL;
			} else {
				fprintf(stderr, "Error: module name is not specified.\n");
				goto exit_err;
			}
		} else if (xmlStrEqual(xmlTextReaderConstName(reader), (xmlChar *) SECHK_PARSE_OPTION_TAG) == 1) {
			/* parsing the <option> tag */
			if (!current_module) {
				fprintf(stderr, "Error: 'option' specified outside the scope of a module.\n");
				goto exit_err;
			}
			/* read the name of the option */
			option = xmlTextReaderGetAttribute(reader, (xmlChar *) SECHK_PARSE_NAME_ATTRIB);
			if (!option) {
				fprintf(stderr, "Error: option name is not specified.\n");
				goto exit_err;
			}
			/* clear the options with this name that were set by defualt for this module */
			sechk_lib_module_clear_option(current_module, (char *)option);

		} else if (xmlStrEqual(xmlTextReaderConstName(reader), (xmlChar *) SECHK_PARSE_ITEM_TAG) == 1) {
			/* parsing the <item> tag */
			assert(current_module);
			nv = sechk_name_value_new((char *)option, NULL);
			/* read the value for this name value pair */
			value = xmlTextReaderGetAttribute(reader, (xmlChar *) SECHK_PARSE_VALUE_ATTRIB);
			if (!value) {
				fprintf(stderr, "Error: item value is not specified.\n");
				goto exit_err;
			}
			nv->value = strdup((char *)value);
			free(value);
			value = NULL;
			/* add the nv pair to the module options */
			apol_vector_append(current_module->options, (void *)nv);
			nv = NULL;
		} else if (xmlStrEqual(xmlTextReaderConstName(reader), (xmlChar *) SECHK_PARSE_OUTPUT_TAG) == 1) {
			if (!current_module) {
				fprintf(stderr, "Error: 'output' specified outside the scope of a module.\n");
				goto exit_err;
			}
			attrib = xmlTextReaderGetAttribute(reader, (xmlChar *) SECHK_PARSE_VALUE_ATTRIB);
			if (attrib) {
				if (xmlStrEqual(attrib, (xmlChar *) SECHK_PARSE_OUTPUT_QUIET) == 1) {
					current_module->outputformat = SECHK_OUT_QUIET;
				} else if (xmlStrEqual(attrib, (xmlChar *) SECHK_PARSE_OUTPUT_VERBOSE) == 1) {
					current_module->outputformat = SECHK_OUT_VERBOSE;
				} else if (xmlStrEqual(attrib, (xmlChar *) SECHK_PARSE_OUTPUT_SHORT) == 1) {
					current_module->outputformat = SECHK_OUT_SHORT;
				} else if (xmlStrEqual(attrib, (xmlChar *) SECHK_PARSE_OUTPUT_NONE) == 1) {
					current_module->outputformat = SECHK_OUT_NONE;
				} else {
					fprintf(stderr, "Error: invalid output value %s.\n", attrib);
					goto exit_err;
				}
				free(attrib);
				attrib = NULL;
			} else {
				fprintf(stderr, "Error: output value is not specified.\n");
				goto exit_err;
			}
		}
		break;
	}
	return 0;

      exit_err:
	sechk_name_value_free(nv);
	errno = EIO;
	return -1;
}
Example #14
0
/*
 * call-seq:
 *    reader.name -> name
 *
 * Return the qualified name of the node.
 */
static VALUE rxml_reader_name(VALUE self)
{
  const xmlChar *result = xmlTextReaderConstName(rxml_text_reader_get(self));
  return (result == NULL ? Qnil : rb_str_new2((const char*)result));
}
Example #15
0
static void processNode(xmlTextReaderPtr reader, Revision *rev) {
	if (xmlTextReaderNodeType(reader) == 15) { // EndElement
		return;
	}
    const xmlChar *name, *value;

    const xmlChar *node_page = (xmlChar *) "page";
    const xmlChar *node_revision = (xmlChar *) "revision";
    const xmlChar *node_id = (xmlChar *) "id";
    const xmlChar *node_ip = (xmlChar *) "ip";
    const xmlChar *node_parent_id = (xmlChar *) "parent_id";
    const xmlChar *node_timestamp = (xmlChar *) "timestamp";

    name = xmlTextReaderConstName(reader);
    if (name == NULL)
    	return;

    value = xmlTextReaderConstValue(reader);

    if (xmlTextReaderNodeType(reader) == 3) { // Text node
    	if (rev->wait_for_page_id == true) {
			rev->page_id = atoi((char *) value);
    		rev->wait_for_page_id = false;
    		return;
    	}

    	if (rev->wait_for_id == true) {
			rev->id = atoi((char *) value);
    		rev->wait_for_id = false;
    		return;
    	}

    	if (rev->wait_for_parent_id == true) {
        	rev->parent_id = atoi((char *) value);
        	rev->wait_for_parent_id = false;
        	return;
    	}

    	if (rev->wait_for_ip == true) {
    		// TODO: check if PostgreSQL is fine with network byte order
        	rev->ip = inet_addr(value);
        	rev->wait_for_ip = false;
        	return;
    	}

    	if (rev->wait_for_timestamp == true) {
    		struct tm ts;
    		memset(&ts, 0, sizeof(struct tm));
			// TODO: check for a NULL return
    		strptime(value, "%Y-%m-%dT%H:%M:%SZ", &ts);
    		rev->timestamp = mktime(&ts);
    		rev->wait_for_timestamp = false;
    		return;
    	}
    }

    if ((rev->in_page == false) && (xmlStrEqual(name, node_page) == 1)) {
    	rev->in_page = true;
    	rev->in_revision = false;
    }

    if ((rev->in_page == true) && (xmlStrEqual(name, node_revision) == 1)) {
    	rev->in_page = false;
    	rev->in_revision = true;
    }

    if (xmlStrEqual(name, node_id) == 1) {
		if (rev->in_page == true) {
			rev->wait_for_page_id = true;
			return;
		}

		if (rev->in_revision == true) {
			rev->wait_for_id = true;
			return;
		}
    }

    if ((rev->in_revision == true) && (xmlStrEqual(name, node_parent_id) == 1)) {
    	rev->wait_for_parent_id = true;
    	return;
    }
    if ((rev->in_revision == true) && (xmlStrEqual(name, node_ip) == 1)) {
    	rev->wait_for_ip = true;
    	return;
    }

    if ((rev->in_revision == true) && (xmlStrEqual(name, node_timestamp) == 1)) {
    	rev->wait_for_timestamp = true;
    	return;
    }

}
Example #16
0
 const xmlChar* getName()
 {
     return xmlTextReaderConstName(reader);
 }
Example #17
0
static tmx_map *parse_root_map(xmlTextReaderPtr reader, const char *filename) {
	tmx_map *res = NULL;
	int curr_depth;
	const char *name;
	char *value;

	name = (char*) xmlTextReaderConstName(reader);
	curr_depth = xmlTextReaderDepth(reader);

	if (strcmp(name, "map")) {
		tmx_err(E_XDATA, "xml parser: root is not a 'map' element");
		return NULL;
	}

	if (!(res = alloc_map())) return NULL;

	/* parses each attribute */
	if ((value = (char*)xmlTextReaderGetAttribute(reader, (xmlChar*)"orientation"))) { /* orientation */
		if (res->orient = parse_orient(value), res->orient == O_NONE) {
			tmx_err(E_XDATA, "xml parser: unsupported 'orientation' '%s'", value);
			goto cleanup;
		}
		tmx_free_func(value);
	} else {
		tmx_err(E_MISSEL, "xml parser: missing 'orientation' attribute in the 'map' element");
		goto cleanup;
	}

	value = (char*)xmlTextReaderGetAttribute(reader, (xmlChar*)"renderorder"); /* renderorder */
	if (res->renderorder = parse_renderorder(value), res->renderorder == R_NONE) {
		tmx_err(E_XDATA, "xml parser: unsupported 'renderorder' '%s'", value);
		goto cleanup;
	}
	tmx_free_func(value);

	if ((value = (char*)xmlTextReaderGetAttribute(reader, (xmlChar*)"height"))) { /* height */
		res->height = atoi(value);
		tmx_free_func(value);
	} else {
		tmx_err(E_MISSEL, "xml parser: missing 'height' attribute in the 'map' element");
		goto cleanup;
	}

	if ((value = (char*)xmlTextReaderGetAttribute(reader, (xmlChar*)"width"))) { /* width */
		res->width = atoi(value);
		tmx_free_func(value);
	} else {
		tmx_err(E_MISSEL, "xml parser: missing 'width' attribute in the 'map' element");
		goto cleanup;
	}

	if ((value = (char*)xmlTextReaderGetAttribute(reader, (xmlChar*)"tileheight"))) { /* tileheight */
		res->tile_height = atoi(value);
		tmx_free_func(value);
	} else {
		tmx_err(E_MISSEL, "xml parser: missing 'tileheight' attribute in the 'map' element");
		goto cleanup;
	}

	if ((value = (char*)xmlTextReaderGetAttribute(reader, (xmlChar*)"tilewidth"))) { /* tilewidth */
		res->tile_width = atoi(value);
		tmx_free_func(value);
	} else {
		tmx_err(E_MISSEL, "xml parser: missing 'tilewidth' attribute in the 'map' element");
		goto cleanup;
	}

	if ((value = (char*)xmlTextReaderGetAttribute(reader, (xmlChar*)"backgroundcolor"))) { /* backgroundcolor */
		res->backgroundcolor = get_color_rgb(value);
		tmx_free_func(value);
	}

	/* Parse each child */
	do {
		if (xmlTextReaderRead(reader) != 1) goto cleanup; /* error_handler has been called */

		if (xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
			name = (char*)xmlTextReaderConstName(reader);
			if (!strcmp(name, "tileset")) {
				if (!parse_tileset(reader, &(res->ts_head), filename)) goto cleanup;
			} else if (!strcmp(name, "layer")) {
				if (!parse_layer(reader, &(res->ly_head), res->height, res->width, L_LAYER, filename)) goto cleanup;
			} else if (!strcmp(name, "objectgroup")) {
				if (!parse_layer(reader, &(res->ly_head), res->height, res->width, L_OBJGR, filename)) goto cleanup;
			} else if (!strcmp(name, "imagelayer")) {
				if (!parse_layer(reader, &(res->ly_head), res->height, res->width, L_IMAGE, filename)) goto cleanup;
			} else if (!strcmp(name, "properties")) {
				if (!parse_properties(reader, &(res->properties))) goto cleanup;
			} else {
				/* Unknow element, skip its tree */
				if (xmlTextReaderNext(reader) != 1) goto cleanup;
			}
		}
	} while (xmlTextReaderNodeType(reader) != XML_READER_TYPE_END_ELEMENT ||
	         xmlTextReaderDepth(reader) != curr_depth);
	return res;
cleanup:
	tmx_map_free(res);
	return NULL;
}
Example #18
0
daeElementRef
daeLIBXMLPlugin::startParse(daeMetaElement* thisMetaElement, xmlTextReaderPtr reader)
{
	// The original parsing system would drop everything up to the first element open, usually <COLLADA>
	// This behavior will have to be replicated here till we have someplace to put the headers/comments

	int ret = xmlTextReaderRead(reader);
	if(ret != 1)
	{
		// empty or hit end of file
		return NULL;
	}
	  //printf("xmlTextReaderConstBaseUri is %s\n",xmlTextReaderConstBaseUri(reader));
	  //printf("xmlTextReaderConstNamespaceUri is %s\n",xmlTextReaderConstNamespaceUri(reader));
	  //printf("xmlTextReaderConstPrefix is %s\n",xmlTextReaderConstPrefix(reader));
	  //printf("xmlTextReaderName is %s\n",xmlTextReaderName(reader));

	// Process the current element
	// Skip over things we don't understand
	while(xmlTextReaderNodeType(reader) != XML_READER_TYPE_ELEMENT)
	{
		ret = xmlTextReaderRead(reader);
		if(ret != 1)
			return(NULL);
	}

	// Create the element that we found
	daeElementRef element = thisMetaElement->create((const daeString)xmlTextReaderConstName(reader));
	if(!element)
	{
		char err[256];
		memset( err, 0, 256 );
		const xmlChar * mine =xmlTextReaderConstName(reader);
#if LIBXML_VERSION >= 20620
		sprintf(err,"The DOM was unable to create an element type %s at line %d\nProbably a schema violation.\n", mine,xmlTextReaderGetParserLineNumber(reader));
#else
		sprintf(err,"The DOM was unable to create an element type %s\nProbably a schema violation.\n", mine);
#endif
		daeErrorHandler::get()->handleWarning( err );
		xmlTextReaderNext(reader);
		return NULL;
	}
	int currentDepth = xmlTextReaderDepth(reader);

	//try and read attributes
	readAttributes( element, reader );

	//Check COLLADA Version
	if ( strcmp( element->getTypeName(), "COLLADA" ) != 0 ) {
		//invalid root
		daeErrorHandler::get()->handleError("Loading document with invalid root element!");
		return NULL;
	}
	daeURI *xmlns = (daeURI*)(element->getMeta()->getMetaAttribute( "xmlns" )->getWritableMemory( element ));
	if ( strcmp( xmlns->getURI(), COLLADA_NAMESPACE ) != 0 ) {
		//invalid COLLADA version
		daeErrorHandler::get()->handleError("Trying to load an invalid COLLADA version for this DOM build!");
		return NULL;
	}

	
	ret = xmlTextReaderRead(reader);
	// If we're out of data, return the element
	if(ret != 1)
		return(element);

	// Read all the tags that are part of this tag
	bool trew = true;
	while(trew)
	{
		int thisType = xmlTextReaderNodeType(reader);
		if(thisType == XML_READER_TYPE_ELEMENT)
		{
			// Is the new element at the same depth as this one?
			if(currentDepth == xmlTextReaderDepth(reader))
			{
				// Same depth means the current element ended in a /> so this is a sibling
				// so we return and let our parent process it.
				return(element);
			}
			else
			{
				// The element is a child of this one, so we recurse
				if(!element->placeElement(nextElement(element->getMeta(), reader)))
				{
					char err[256];
					memset( err, 0, 256 );
#if LIBXML_VERSION >= 20620
				sprintf(err,"placeElement failed at line %d\n", xmlTextReaderGetParserLineNumber(reader));
#else
				sprintf(err,"placeElement failed\n");
#endif
				daeErrorHandler::get()->handleWarning(err);
				ret = xmlTextReaderRead(reader);
				if ( ret != 1 ) {
					return element;
				}
				}
			}
		}
		else if(thisType == XML_READER_TYPE_TEXT)
		{
			readValue( element, reader );
		}
		else if(thisType == XML_READER_TYPE_END_ELEMENT)
		{
			// Done with this element so read again and return
			ret = xmlTextReaderRead(reader);
			return(element);
		}
		else
		{	// Skip element types we don't care about
			ret = xmlTextReaderRead(reader);
			// If we're out of data, return the element
			if(ret != 1)
				return(element);
		}
	}
	// Return NULL on an error
	return NULL;
}
 std::string XMLReader::getTraitName() const
 {
   const xmlChar* name = xmlTextReaderConstName(m_reader) ;
   return (char*) name ;
 }
Example #20
0
daeElementRef
daeLIBXMLPlugin::nextElement(daeMetaElement* thisMetaElement, xmlTextReaderPtr reader)
{
	int ret;
	// Process the current element
	// Skip over things we don't understand
	while(xmlTextReaderNodeType(reader) != XML_READER_TYPE_ELEMENT)
	{
		ret = xmlTextReaderRead(reader);
		if(ret != 1)
			return(NULL);
	}

	// Create the element that we found
	daeElementRef element = thisMetaElement->create((const daeString)xmlTextReaderConstName(reader));
	if(!element)
	{
		const xmlChar * mine =xmlTextReaderConstName(reader);
		char err[256];
		memset( err, 0, 256 );
#if LIBXML_VERSION >= 20620
		sprintf(err,"The DOM was unable to create an element type %s at line %d\nProbably a schema violation.\n", mine,xmlTextReaderGetParserLineNumber(reader));
#else
		sprintf(err,"The DOM was unable to create an element type %s\nProbably a schema violation.\n", mine);
#endif
		daeErrorHandler::get()->handleWarning( err );
		if ( xmlTextReaderNext(reader) == -1 ) {
			int x = 12312412;
		}
		return NULL;
	}
	int currentDepth = xmlTextReaderDepth(reader);

	//try and read attributes
	readAttributes( element, reader );
	
	ret = xmlTextReaderRead(reader);
	// If we're out of data, return the element
	if(ret != 1)
		return(element);

	// Read all the tags that are part of this tag
	bool trew = true;
	while(trew)
	{
		int thisType = xmlTextReaderNodeType(reader);
		if(thisType == XML_READER_TYPE_ELEMENT)
		{
			// Is the new element at the same depth as this one?
			if(currentDepth == xmlTextReaderDepth(reader))
			{
				// Same depth means the current element ended in a /> so this is a sibling
				// so we return and let our parent process it.
				return(element);
			}
			else
			{
				// The element is a child of this one, so we recurse
				if(!element->placeElement(nextElement(element->getMeta(), reader)))
				{
					char err[256];
					memset( err, 0, 256 );
#if LIBXML_VERSION >= 20620
				sprintf(err,"placeElement failed at line %d\n", xmlTextReaderGetParserLineNumber(reader));
#else
				sprintf(err,"placeElement failed\n");
#endif
				daeErrorHandler::get()->handleWarning( err );
				ret = xmlTextReaderRead(reader);
				if ( ret != 1 ) {
					return element;
				}
				}
			}
		}
		else if(thisType == XML_READER_TYPE_TEXT)
		{
			readValue( element, reader );
		}
		else if(thisType == XML_READER_TYPE_END_ELEMENT)
		{
			// Done with this element so read again and return
			ret = xmlTextReaderRead(reader);
			return(element);
		}
		else
		{	// Skip element types we don't care about
			ret = xmlTextReaderRead(reader);
			// If we're out of data, return the element
			if(ret != 1)
				return(element);
		}
	}
	//program will never get here but this line is needed to supress a warning
	return NULL;
}
static void
process_bijiben_start_elem (BijiLazyDeserializer *self)
{
  BijiLazyDeserializerPrivate *priv = self->priv;
  const gchar *element_name;

  element_name = (const gchar *) xmlTextReaderConstName(priv->inner);

  if (g_strcmp0 (element_name, "note-content")==0)
    return;

  if (g_strcmp0 (element_name, "div")==0)
    priv->html = g_string_append (priv->html, "&#xA;");

  if (g_strcmp0 (element_name, "br")==0)
    priv->html = g_string_append (priv->html, "<br/>");

  if (g_strcmp0 (element_name, "b")==0)
    priv->html = g_string_append (priv->html, "<b>");

  if (g_strcmp0 (element_name, "i")==0)
    priv->html = g_string_append (priv->html, "<i>");

  if (g_strcmp0 (element_name, "strike")==0)
    priv->html = g_string_append (priv->html, "<strike>");

  /* Lists */

  if (g_strcmp0 (element_name, "ul")==0)
    priv->html = g_string_append (priv->html, "<ul>");

  if (g_strcmp0 (element_name, "ol")==0)
    priv->html = g_string_append (priv->html, "<ol>");

  if (g_strcmp0 (element_name, "li")==0)
    priv->html = g_string_append (priv->html, "<li>");

  /* Links: Images */

  if (g_strcmp0 (element_name, "img")==0)
  {
    priv->html = g_string_append (priv->html, "<img ");

    xmlChar *attribute;

    attribute = xmlTextReaderGetAttribute (priv->inner, BAD_CAST "id");
    if (attribute)
    {
      priv->html = g_string_append (priv->html, "id=\"");
      priv->html = g_string_append (priv->html, (gchar*) attribute);
      priv->html = g_string_append (priv->html, "\"");
      xmlFree (attribute);
      attribute = NULL;
    }

    attribute = xmlTextReaderGetAttribute (priv->inner, BAD_CAST "width");
    if (attribute)
    {
      priv->html = g_string_append (priv->html, "width=\"");
      priv->html = g_string_append (priv->html, (gchar*) attribute);
      priv->html = g_string_append (priv->html, "\"");
      xmlFree (attribute);
      attribute = NULL;
    }

    attribute = xmlTextReaderGetAttribute (priv->inner, BAD_CAST "height");
    if (attribute)
    {
      priv->html = g_string_append (priv->html, "height=\"");
      priv->html = g_string_append (priv->html, (gchar*) attribute);
      priv->html = g_string_append (priv->html, "\"");
      xmlFree (attribute);
      attribute = NULL;
    }

    attribute = xmlTextReaderGetAttribute (priv->inner, BAD_CAST "src");
    if (attribute)
    {
      priv->html = g_string_append (priv->html, "src=\"");
      priv->html = g_string_append (priv->html, (gchar*) attribute);
      priv->html = g_string_append (priv->html, "\"");
      xmlFree (attribute);
      attribute = NULL;
    }

    attribute = xmlTextReaderGetAttribute (priv->inner, BAD_CAST "alt");
    if (attribute)
    {
      priv->html = g_string_append (priv->html, "alt=\"");
      priv->html = g_string_append (priv->html, (gchar*) attribute);
      priv->html = g_string_append (priv->html, "\"");
      xmlFree (attribute);
      attribute = NULL;
    }

    priv->html = g_string_append (priv->html, ">");
  }
}
Example #22
0
File: bs.c Project: MSch/MacRuby
bool 
bs_parser_parse(bs_parser_t *parser, const char *path, 
                const char *framework_path, bs_parse_options_t options, 
                bs_parse_callback_t callback, void *context, char **error)
{
  xmlTextReaderPtr reader;
  bs_element_function_t *func;
  bs_element_class_t *klass;
  bs_element_method_t *method;
  unsigned int i;
#define MAX_ARGS 128
  bs_element_arg_t args[MAX_ARGS];
  bs_element_arg_t fptr_args[MAX_ARGS];
  char *protocol_name = NULL;
  int func_ptr_arg_depth;
  bs_element_function_pointer_t *func_ptr;
  bool success;
  CFStringRef cf_path;
  bool nested_func_ptr;
  unsigned int version_number = 0;

  if (callback == NULL)
    return false;

  /* check if the given framework path has not been loaded already */
  cf_path = CFStringCreateWithFileSystemRepresentation(kCFAllocatorMalloc, 
    path);
  CFMakeCollectable(cf_path);
  for (unsigned i = 0, count = CFArrayGetCount(parser->loaded_paths);
       i < count; i++) {
    CFStringRef s = CFArrayGetValueAtIndex(parser->loaded_paths, i);
    if (CFStringCompare(cf_path, s, kCFCompareCaseInsensitive)
        == kCFCompareEqualTo) {
      /* already loaded */
      return true;
    }
  }

  CFArrayAppendValue(parser->loaded_paths, cf_path);

  //printf("parsing %s\n", path);

#define BAIL(fmt, args...)                      \
  do {                                          \
    if (error != NULL) {                        \
      char buf[1024];                           \
      snprintf(buf, sizeof buf,                 \
               "%s:%ld - "fmt, path,            \
               xmlGetLineNo(xmlTextReaderCurrentNode(reader)), \
               ##args);                         \
      *error = strdup(buf);                     \
    }                                           \
    success = false;                            \
    goto bails;                                 \
  }                                             \
  while (0)

#if __LP64__
# define CHECK_TYPE_ATTRIBUTE(var) CHECK_ATTRIBUTE(var, "type")
#else
# define CHECK_TYPE_ATTRIBUTE(var) \
    if (var == NULL && get_type64_attribute(reader) != NULL) { \
	break; \
    } \
    CHECK_ATTRIBUTE(var, "type")
#endif

#define CHECK_ATTRIBUTE_CAN_BE_EMPTY(a, name) \
  CHECK_ATTRIBUTE0(a, name, true)

#define CHECK_ATTRIBUTE(a, name) \
  CHECK_ATTRIBUTE0(a, name, false)

#define CHECK_ATTRIBUTE0(a, name, can_be_empty)         \
  do {                                                  \
    if (a == NULL)                                      \
      BAIL("expected attribute `%s' for element `%s'",  \
           name, xmlTextReaderConstName(reader));       \
    if (!can_be_empty && *a == '\0') {                  \
      free(a);                                          \
      BAIL("empty attribute `%s' for element `%s'",     \
           name, xmlTextReaderConstName(reader));       \
    }                                                   \
  } while (0)                                           \

  reader = xmlNewTextReaderFilename(path);
  if (reader == NULL)
    BAIL("cannot create XML text reader for file at path `%s'", path);

  func = NULL;
  func_ptr = NULL;
  func_ptr_arg_depth = -1;
  nested_func_ptr = false;
  klass = NULL;
  method = NULL;
  protocol_name = NULL;

  while (true) {
    const char *name;
    unsigned int namelen;
    int node_type = -1;
    bool eof = false;
    struct bs_xml_atom *atom;
    void *bs_element;
    bs_element_type_t bs_element_type = 0;

    do {
      int retval = xmlTextReaderRead(reader);
      if (retval == 0) {
        eof = true;
        break;
      }
      else if (retval < 0)
        BAIL("parsing error: %d", retval);

      node_type = xmlTextReaderNodeType(reader);
    }
    while (node_type != XML_READER_TYPE_ELEMENT 
           && node_type != XML_READER_TYPE_END_ELEMENT);    
    
    if (eof)
      break;

    name = (const char *)xmlTextReaderConstName(reader);
    namelen = strlen(name); 

    bs_element = NULL;

    atom = bs_xml_element(name, namelen);
    if (atom == NULL) {
      // TODO: we should include the "signatures" string into the gperf
      // function.
      if (version_number == 0 && strcmp(name, "signatures") == 0) {
        char *str = get_attribute(reader, "version");
        if (str != NULL) {
          char *p = strchr(str, '.');
          if (p != NULL) {
            *p = '\0';
            int major = atoi(str);
            int minor = atoi(&p[1]);
            assert(major < 10 && minor < 10);
            version_number = (major * 10) + minor;
            parser->version_number = version_number;
          }
          free(str);
        }
      }
      continue;
    }

    if (nested_func_ptr) {
      // FIXME: elements nesting function_pointers aren't supported yet by the
      // parser, so we just ignore them.
      if (node_type == XML_READER_TYPE_END_ELEMENT
          && (atom->val == BS_XML_FUNCTION || atom->val == BS_XML_METHOD)) {
        nested_func_ptr = false;
      }
      continue;
    }

    if (node_type == XML_READER_TYPE_ELEMENT) {
      switch (atom->val) {
        case BS_XML_DEPENDS_ON:
        {
          char *depends_on_path;
          char bs_path[PATH_MAX];
          bool bs_path_found;
          
          depends_on_path = get_attribute(reader, "path");
          CHECK_ATTRIBUTE(depends_on_path, "path");

//printf("depends of %s\n", depends_on_path);
          
          bs_path_found = bs_find_path(depends_on_path, bs_path, 
                                       sizeof bs_path);
          if (bs_path_found) {
            if (!bs_parser_parse(parser, bs_path, depends_on_path, options, 
                                 callback, context, error)) {
              free(depends_on_path);
              return false;
	    }
          }
          free(depends_on_path);
          break;
        }

        case BS_XML_CONSTANT: 
        { 
          bs_element_constant_t *bs_const;
          char *const_name;
          char *const_type;

          const_name = get_attribute(reader, "name");
          CHECK_ATTRIBUTE(const_name, "name");
          const_type = get_type_attribute(reader);
          CHECK_TYPE_ATTRIBUTE(const_type);

          bs_const = (bs_element_constant_t *)
            malloc(sizeof(bs_element_constant_t));
          ASSERT_ALLOC(bs_const);

          bs_const->name = const_name;
          bs_const->type = const_type;
          bs_const->ignore = false;
          bs_const->suggestion = NULL;
          bs_const->magic_cookie = get_boolean_attribute(reader,
            "magic_cookie", false);

          bs_element = bs_const;
          bs_element_type = BS_ELEMENT_CONSTANT;
          break;
        }

        case BS_XML_STRING_CONSTANT:
        {
          bs_element_string_constant_t *bs_strconst;
          char *strconst_name;
          char *strconst_value;

          strconst_name = get_attribute(reader, "name");
          CHECK_ATTRIBUTE(strconst_name, "name");
          strconst_value = get_attribute(reader, "value");
          CHECK_ATTRIBUTE_CAN_BE_EMPTY(strconst_value, "value");

          bs_strconst = (bs_element_string_constant_t *)
            malloc(sizeof(bs_element_string_constant_t));
          ASSERT_ALLOC(bs_strconst);

          bs_strconst->name = strconst_name;
          bs_strconst->value = strconst_value;
          bs_strconst->nsstring = get_boolean_attribute(reader, "nsstring", 
            false);

          bs_element = bs_strconst;
          bs_element_type = BS_ELEMENT_STRING_CONSTANT;
          break;
        }

        case BS_XML_ENUM: 
        { 
          char *enum_name;
          char *enum_value;        

          enum_name = get_attribute(reader, "name");
          CHECK_ATTRIBUTE(enum_name, "name");

#if __LP64__
	  enum_value = get_attribute(reader, "value64");
	  if (enum_value == NULL)
#endif
	    enum_value = get_attribute(reader, "value");

#if BYTE_ORDER == BIG_ENDIAN
# define BYTE_ORDER_VALUE_ATTR_NAME "be_value"
#else
# define BYTE_ORDER_VALUE_ATTR_NAME "le_value"
#endif

          if (enum_value == NULL)
            enum_value = get_attribute(reader, BYTE_ORDER_VALUE_ATTR_NAME); 
          
          if (enum_value != NULL) {
            bs_element_enum_t *bs_enum;
   
            bs_enum = (bs_element_enum_t *)malloc(sizeof(bs_element_enum_t));
            ASSERT_ALLOC(bs_enum);

            bs_enum->name = enum_name;
            bs_enum->value = enum_value;
            bs_enum->ignore = get_boolean_attribute(reader, "ignore", false);
            bs_enum->suggestion = get_attribute(reader, "suggestion");
            
            bs_element = bs_enum;
            bs_element_type = BS_ELEMENT_ENUM;
          }
          break;
        }

        case BS_XML_STRUCT: 
        {
          bs_element_struct_t *bs_struct;
          char *struct_decorated_type;
          char *struct_name;
          char type[MAX_ENCODE_LEN];
          bs_element_struct_field_t fields[128];
          int field_count;

          struct_decorated_type = get_type_attribute(reader);
          CHECK_TYPE_ATTRIBUTE(struct_decorated_type);
          struct_name = get_attribute(reader, "name");
          CHECK_ATTRIBUTE(struct_name, "name");

          if (!undecorate_struct_type(struct_decorated_type, type, 
                                      sizeof type, fields, 128, 
                                      &field_count)) {
            BAIL("Can't handle structure '%s' with type '%s'", 
                 struct_name, struct_decorated_type);
          }

          free(struct_decorated_type);

          bs_struct = 
            (bs_element_struct_t *)malloc(sizeof(bs_element_struct_t));
          ASSERT_ALLOC(bs_struct);

          bs_struct->name = struct_name;
          bs_struct->type = strdup(type);
          
          bs_struct->fields = (bs_element_struct_field_t *)malloc(
            sizeof(bs_element_struct_field_t) * field_count);
          ASSERT_ALLOC(bs_struct->fields);
          memcpy(bs_struct->fields, fields, 
                 sizeof(bs_element_struct_field_t) * field_count); 
          
          bs_struct->fields_count = field_count;
          bs_struct->opaque = get_boolean_attribute(reader, "opaque", false);

          bs_element = bs_struct;
          bs_element_type = BS_ELEMENT_STRUCT;
          break;
        }

        case BS_XML_OPAQUE:
        {
          bs_element_opaque_t *bs_opaque;
          char *opaque_name;
          char *opaque_type;

          opaque_name = get_attribute(reader, "name");
          CHECK_ATTRIBUTE(opaque_name, "name");
          opaque_type = get_type_attribute(reader);
          CHECK_TYPE_ATTRIBUTE(opaque_type);

          bs_opaque = 
            (bs_element_opaque_t *)malloc(sizeof(bs_element_opaque_t));
          ASSERT_ALLOC(bs_opaque);
          
          bs_opaque->name = opaque_name;
          bs_opaque->type = opaque_type;
          
          bs_element = bs_opaque;
          bs_element_type = BS_ELEMENT_OPAQUE;
          break;
        }
        
        case BS_XML_CFTYPE:
        {
          bs_element_cftype_t *bs_cftype;
          char *cftype_name;
          char *cftype_type;

          cftype_name = get_attribute(reader, "name");
          CHECK_ATTRIBUTE(cftype_name, "name");
          cftype_type = get_type_attribute(reader);
          CHECK_TYPE_ATTRIBUTE(cftype_type);

          bs_cftype = 
            (bs_element_cftype_t *)malloc(sizeof(bs_element_cftype_t));
          ASSERT_ALLOC(bs_cftype);

          bs_cftype->name = cftype_name;
          bs_cftype->type = cftype_type;

#if 1
          /* the type_id field isn't used in MacRuby */
          bs_cftype->type_id = 0;
#else
          char *cftype_gettypeid_func_name;
          cftype_gettypeid_func_name = get_attribute(reader, "gettypeid_func");
          if (cftype_gettypeid_func_name != NULL) {
            void *sym;

            sym = dlsym(RTLD_DEFAULT, cftype_gettypeid_func_name);
            if (sym == NULL) {
              BAIL("cannot locate gettypeid_func function `%s'",
                   cftype_gettypeid_func_name);
            }
            else {
              CFTypeID (*cb)(void) = sym;
              bs_cftype->type_id = (*cb)();
            }
          }
          else {
            bs_cftype->type_id = 0;
          }
#endif

          bs_cftype->tollfree = get_attribute(reader, "tollfree");

          bs_element = bs_cftype;
          bs_element_type = BS_ELEMENT_CFTYPE;
          break;
        }
        
        case BS_XML_INFORMAL_PROTOCOL: 
        {
	  if (protocol_name != NULL)
	    free(protocol_name);
          protocol_name = get_attribute(reader, "name");
          CHECK_ATTRIBUTE(protocol_name, "name");
          break;
        }

        case BS_XML_FUNCTION: 
        {
          char *func_name;
          
          func_name = get_attribute(reader, "name");
          CHECK_ATTRIBUTE(func_name, "name");

          func = 
            (bs_element_function_t *)malloc(sizeof(bs_element_function_t));
          ASSERT_ALLOC(func);

          func->name = func_name;
          func->variadic = get_boolean_attribute(reader, "variadic", false);
          func->args_count = 0;
          func->args = NULL;
          func->retval = NULL;

          if (xmlTextReaderIsEmptyElement(reader)) {
            bs_element = func;
            bs_element_type = BS_ELEMENT_FUNCTION;
            func = NULL;
          }
          break;
        }

        case BS_XML_FUNCTION_ALIAS: 
        {
          bs_element_function_alias_t *bs_func_alias;
          char *alias_name;
          char *alias_original;

          alias_name = get_attribute(reader, "name"); 
          CHECK_ATTRIBUTE(alias_name, "name");
          alias_original = get_attribute(reader, "original");
          CHECK_ATTRIBUTE(alias_original, "original");

          bs_func_alias = (bs_element_function_alias_t *)malloc(
            sizeof(bs_element_function_alias_t));
          ASSERT_ALLOC(bs_func_alias);
          
          bs_func_alias->name = alias_name;
          bs_func_alias->original = alias_original;

          bs_element = bs_func_alias;
          bs_element_type = BS_ELEMENT_FUNCTION_ALIAS;
          break;
        }

        case BS_XML_CLASS: 
        {
          char *class_name;
          
          class_name = get_attribute(reader, "name");
          CHECK_ATTRIBUTE(class_name, "name");
        
          klass = (bs_element_class_t *)malloc(sizeof(bs_element_class_t));
          ASSERT_ALLOC(klass);
            
          klass->name = class_name;
          klass->class_methods = klass->instance_methods = NULL;
          klass->class_methods_count = klass->instance_methods_count = 0;
          break;
        }

        case BS_XML_ARG:
        {
          if (func != NULL || method != NULL || func_ptr != NULL) {
            bs_element_arg_t *bs_arg; 
            unsigned *argc;

            argc = func_ptr != NULL
              ? &func_ptr->args_count
              : func != NULL 
                ? &func->args_count 
                : &method->args_count;

            if (*argc >= MAX_ARGS) {
              if (func_ptr != NULL)
                BAIL("maximum number of arguments (%d) reached " \
                     "for function pointer", MAX_ARGS);
              else if (func != NULL)
                BAIL("maximum number of arguments (%d) reached " \
                     "for function '%s'", MAX_ARGS, func->name);
              else
                BAIL("maximum number of arguments (%d) reached " \
                     "for method '%s'", MAX_ARGS, (char *)method->name);
            } 

	    bs_element_arg_t *args_from =
		(func_ptr == NULL ? args : fptr_args);
	    bs_arg = &args_from[(*argc)++];

            if (method != NULL && func_ptr == NULL) {
              char *index = get_attribute(reader, "index");
              CHECK_ATTRIBUTE(index, "index");
              bs_arg->index = strtol(index, NULL, 10);
              free(index);
            }
            else {
              bs_arg->index = -1;
            }
            
            get_type_modifier_attribute(reader, &bs_arg->type_modifier);

#if __LP64__
            bs_arg->sel_of_type = get_attribute(reader, "sel_of_type64");
            if (bs_arg->sel_of_type == NULL)
#endif
              bs_arg->sel_of_type = get_attribute(reader, "sel_of_type");

            bs_arg->printf_format = get_boolean_attribute(reader, 
                "printf_format", false); 
            bs_arg->null_accepted = get_boolean_attribute(reader, 
                "null_accepted", true);
            get_c_ary_type_attribute(reader, 
                &bs_arg->carray_type, &bs_arg->carray_type_value); 
  
            bs_arg->type = get_type_attribute(reader);

            if (get_boolean_attribute(reader, "function_pointer", false)) {
              if (func_ptr != NULL) {
                func_ptr = NULL; 
		nested_func_ptr = true;
		break;
	      }
              bs_arg->function_pointer = (bs_element_function_pointer_t *)
                calloc(1, sizeof(bs_element_function_pointer_t));
              ASSERT_ALLOC(bs_arg->function_pointer);
              func_ptr = bs_arg->function_pointer;
              func_ptr_arg_depth = xmlTextReaderDepth(reader);
            }
	    else {
              bs_arg->function_pointer = NULL;
	    }
          }
          else {
            BAIL("argument defined outside of a " \
                 "function/method/function_pointer");
          }
          break;
        }

        case BS_XML_RETVAL: 
        {
          if (func != NULL || method != NULL || func_ptr != NULL) {
            bs_element_retval_t *bs_retval;  

            if (func_ptr != NULL) {
              if (func_ptr->retval != NULL)
                BAIL("function pointer return value defined more than once");
            }
            else if (func != NULL) {
              if (func->retval != NULL)
                BAIL("function '%s' return value defined more than once", 
                     func->name);
            }
            else if (method != NULL) {
              if (method->retval != NULL)
                BAIL("method '%s' return value defined more than once", 
                     (char *)method->name);
            }
    
            bs_retval = 
              (bs_element_retval_t *)malloc(sizeof(bs_element_retval_t));
            ASSERT_ALLOC(bs_retval);

            get_c_ary_type_attribute(reader, &bs_retval->carray_type, 
              &bs_retval->carray_type_value);

            bs_retval->type = get_type_attribute(reader);
            if (bs_retval->type != NULL)
              bs_retval->already_retained = 
                get_boolean_attribute(reader, "already_retained", false);

            if (func_ptr != NULL) {
              if (bs_retval->type != NULL) {
                func_ptr->retval = bs_retval;
              }
              else {
                free(bs_retval);
                BAIL("function pointer return value defined without type"); 
              }
            }
            else if (func != NULL) {
              if (bs_retval->type != NULL) {
                func->retval = bs_retval;
              }
              else {
                free(bs_retval);
#if !defined(__LP64__)
		if (get_type64_attribute(reader) != NULL) {
		    // The function has no 32-bit return value type and we
		    // run in 32-bit mode. We just ignore it.
		    func = NULL;
		    break;
		}
#endif
                BAIL("function '%s' return value defined without type", 
                     func->name);
              }
            }
            else {
              method->retval = bs_retval;
            }

            if (get_boolean_attribute(reader, "function_pointer", false)) {
              if (func_ptr != NULL) {
                func_ptr = NULL; 
		nested_func_ptr = true;
		break;
              }
              bs_retval->function_pointer = (bs_element_function_pointer_t *)
                calloc(1, sizeof(bs_element_function_pointer_t));
              ASSERT_ALLOC(bs_retval->function_pointer);
              func_ptr = bs_retval->function_pointer;
              func_ptr_arg_depth = xmlTextReaderDepth(reader);
            }
	    else {
              bs_retval->function_pointer = NULL;
	    }
          }
          else {
            BAIL("return value defined outside a function/method");
          }
          break;
        }

        case BS_XML_METHOD: 
        {
          if (protocol_name != NULL) {
            bs_element_informal_protocol_method_t *bs_informal_method;
            char *selector;
            char *method_type;

            selector = get_attribute(reader, "selector");
            CHECK_ATTRIBUTE(selector, "selector");
            
            method_type = get_type_attribute(reader);
            CHECK_TYPE_ATTRIBUTE(method_type);

            bs_informal_method = (bs_element_informal_protocol_method_t *)
              malloc(sizeof(bs_element_informal_protocol_method_t));
            ASSERT_ALLOC(bs_informal_method);

            bs_informal_method->name = sel_registerName(selector);
	    free(selector);
            bs_informal_method->class_method = 
              get_boolean_attribute(reader, "class_method", false);
            bs_informal_method->type = method_type;
            bs_informal_method->protocol_name = strdup(protocol_name);

            bs_element = bs_informal_method;
            bs_element_type = BS_ELEMENT_INFORMAL_PROTOCOL_METHOD;
          }
          else if (klass != NULL) {  
            char *selector;

            selector = get_attribute(reader, "selector");
            CHECK_ATTRIBUTE(selector, "selector");

            method = 
              (bs_element_method_t *)malloc(sizeof(bs_element_method_t));
            ASSERT_ALLOC(method);

            method->name = sel_registerName(selector);
	    free(selector);
            method->class_method = 
              get_boolean_attribute(reader, "class_method", false);
            method->variadic = 
              get_boolean_attribute(reader, "variadic", false);
            method->ignore = 
              get_boolean_attribute(reader, "ignore", false);
            method->suggestion = get_attribute(reader, "suggestion");
            method->args_count = 0;
            method->args = NULL;
            method->retval = NULL;

            if (xmlTextReaderIsEmptyElement(reader)) {
              goto index_method;
            }
          }
          else {
            BAIL("method defined outside a class or informal protocol");
          }
          break;
        }
      }
    }
    else if (node_type == XML_READER_TYPE_END_ELEMENT) {
      switch (atom->val) {
        case BS_XML_INFORMAL_PROTOCOL: 
        {
          protocol_name = NULL;
          break;
        }

        case BS_XML_RETVAL:
        case BS_XML_ARG: 
        {
          if (func_ptr != NULL 
              && func_ptr_arg_depth == xmlTextReaderDepth(reader)) {

	      bs_element_retval_t *retval = NULL;
	      bs_element_arg_t *arg = NULL;
	      unsigned args_count;

	      if (atom->val == BS_XML_RETVAL) {
		  retval = func != NULL ? func->retval : method->retval;
	      }
	      else {
		  args_count = func != NULL ? func->args_count
		      : method->args_count;
		  arg = &args[args_count - 1];
	      }

              // Determine if we deal with a block or a function pointer.
	      const char *old_type = (retval ? retval->type : arg->type);
              const char lambda_type = *old_type == '@'
		? _MR_C_LAMBDA_BLOCK
		: _MR_C_LAMBDA_FUNCPTR;

	      char tmp_type[1025]; // 3 less to fit <, type and >
	      char new_type[1028];

	      // Function ptr return type
	      strlcpy(tmp_type, func_ptr->retval->type, sizeof(tmp_type));
	      // Function ptr args
	      for (i = 0; i < func_ptr->args_count; i++) {
		  strlcat(tmp_type, fptr_args[i].type, sizeof(tmp_type));
	      }
	      // Clear the final type string
	      memset(new_type, 0, sizeof(new_type));
	      // Append the function pointer type
	      snprintf(new_type, sizeof(new_type), "%c%c%s%c",
		      _MR_C_LAMBDA_B, lambda_type, tmp_type, _MR_C_LAMBDA_E);

	      // Free the old values
	      if (retval) {
		  free(retval->type);
		  retval->type = strdup(new_type);
	      }
	      else {
		  free(arg->type);
		  arg->type = strdup(new_type);
	      }
            
	      if (func_ptr->args_count > 0) {
		  size_t len;
      
		  len = sizeof(bs_element_arg_t) * func_ptr->args_count;
		  func_ptr->args = (bs_element_arg_t *)malloc(len);
		  ASSERT_ALLOC(func_ptr->args);
		  memcpy(func_ptr->args, fptr_args, len);
	      }
	      else {
		  func_ptr->args = NULL;
	      }
                        
	      func_ptr = NULL;
	      func_ptr_arg_depth = -1;
          }
          break;
        }
 
        case BS_XML_FUNCTION: 
        {
          if (func == NULL) {
            break;
          }
          for (i = 0; i < func->args_count; i++) {
            if (args[i].type == NULL)
              BAIL("function '%s' argument #%d type not provided", 
                   func->name, i);
          }
    
          if (func->args_count > 0) {
            size_t len;
    
            len = sizeof(bs_element_arg_t) * func->args_count;
            func->args = (bs_element_arg_t *)malloc(len);
            ASSERT_ALLOC(func->args);
            memcpy(func->args, args, len);
          }

          bs_element = func;
          bs_element_type = BS_ELEMENT_FUNCTION;
          func = NULL;
          break;
        }

        case BS_XML_METHOD: 
        {
          bs_element_method_t *methods;
          unsigned *methods_count;
          
          if (method->args_count > 0) {
            size_t len;
      
            len = sizeof(bs_element_arg_t) * method->args_count;
            method->args = (bs_element_arg_t *)malloc(len);
            ASSERT_ALLOC(method->args);
            memcpy(method->args, args, len);
          }

index_method:
          methods = method->class_method 
            ? klass->class_methods : klass->instance_methods;

          methods_count = method->class_method
            ? &klass->class_methods_count : &klass->instance_methods_count;

          if (methods == NULL) {
            methods = (bs_element_method_t *)malloc(
              sizeof(bs_element_method_t) * (*methods_count + 1));
          }
          else {
            methods = (bs_element_method_t *)realloc(methods, 
              sizeof(bs_element_method_t) * (*methods_count + 1));
          }
          ASSERT_ALLOC(methods);

    //      methods[*methods_count] = method;
    // FIXME this is inefficient
          memcpy(&methods[*methods_count], method, 
            sizeof(bs_element_method_t));

          (*methods_count)++;
          
          if (method->class_method)
            klass->class_methods = methods;
          else
            klass->instance_methods = methods;
         
          free(method);
          method = NULL;
          break;
        }

        case BS_XML_CLASS: 
        {
          bs_element = klass;
          bs_element_type = BS_ELEMENT_CLASS;
          klass = NULL;
          break;
        }
      }
    }

    if (bs_element != NULL)
      (*callback)(parser, path, bs_element_type, bs_element, context);
  }
  
  success = true;

bails:
  if (protocol_name != NULL)
    free(protocol_name);

  xmlFreeTextReader(reader);

  if (!success) {
      for (unsigned i = 0, count = CFArrayGetCount(parser->loaded_paths);
	      i < count; i++) {
	  CFStringRef s = CFArrayGetValueAtIndex(parser->loaded_paths, i);
	  if (CFStringCompare(cf_path, s, kCFCompareCaseInsensitive)
		  == kCFCompareEqualTo) {
	      CFArrayRemoveValueAtIndex(parser->loaded_paths, i);
	      break;
	  }
      }
  }

  if (success && options == BS_PARSE_OPTIONS_LOAD_DYLIBS && framework_path != NULL) {
    char buf[PATH_MAX];

    if (_bs_find_path(framework_path, buf, sizeof buf, "dylib")) {
      if (dlopen(buf, RTLD_LAZY) == NULL) {
        if (error != NULL) {
          *error = dlerror();
        }
        success = false;
      }
    }
  }

  return success;
}
Example #23
0
static void
dax_dom_document_read_node (DaxDomDocument *document,
                            ParserContext  *ctx)
{
    int type;

    type = xmlTextReaderNodeType (ctx->reader);

    switch (type) {
    case DAX_DOM_NODE_TYPE_ELEMENT:
    {
        const xmlChar *local_name = xmlTextReaderConstLocalName (ctx->reader);
        const gchar *name = (const gchar *)local_name;
        DaxDomElement *new_element;
        gboolean is_empty = FALSE;

        new_element = dax_dom_document_create_element (document, name, NULL);

        if (G_UNLIKELY (new_element == NULL)) {
            g_message ("Unsupported element %s", name);
            new_element =
                dax_dom_document_create_element (document, "desc", NULL);
        }

        DAX_NOTE (PARSING, "Append %s to %s",
                     G_OBJECT_TYPE_NAME (new_element),
                     G_OBJECT_TYPE_NAME (ctx->current_node));

        dax_dom_node_append_child (ctx->current_node,
                                      DAX_DOM_NODE (new_element),
                                      NULL);
        ctx->current_node = DAX_DOM_NODE (new_element);

        if (xmlTextReaderIsEmptyElement (ctx->reader))
            is_empty = TRUE;

        /* Parse attributes */
        while (xmlTextReaderMoveToNextAttribute (ctx->reader) == 1) {
            const xmlChar *_name = xmlTextReaderConstName (ctx->reader);
            const xmlChar *_value = xmlTextReaderConstValue (ctx->reader);
            const xmlChar *_ns = xmlTextReaderConstNamespaceUri (ctx->reader);

            dax_dom_element_set_attribute_ns (new_element,
                                                 (const gchar *)_ns,
                                                 (const gchar *)_name,
                                                 (const gchar *)_value,
                                                 NULL);
        }

        /* if the element is empty a DAX_DOM_NODE_TYPE_END_ELEMENT won't
         * be emited, so update current_node here */
        if (is_empty)
            dax_dom_document_end_element (ctx);

        break;
    }

    case DAX_DOM_NODE_TYPE_END_ELEMENT:
        dax_dom_document_end_element (ctx);
        break;

    case DAX_DOM_NODE_TYPE_TEXT_NODE:
    case DAX_DOM_NODE_TYPE_CDATA_SECTION:
    {
        const xmlChar *value = xmlTextReaderConstValue (ctx->reader);
        const gchar *data = (const gchar *)value;
        DaxDomText *new_text;

        new_text = dax_dom_document_create_text_node (document, data);

        /* Happens if we are short on memory, hopefully never */
        if (G_UNLIKELY (new_text == NULL)) {
            g_critical ("Cannot create text node");
            break;
        }

        DAX_NOTE (PARSING, "Append text node to %s",
                     G_OBJECT_TYPE_NAME (ctx->current_node));

        dax_dom_node_append_child (ctx->current_node,
                                      DAX_DOM_NODE (new_text),
                                      NULL);
        break;
    }
    default:
        break;
    }
}
Example #24
0
File: xml.c Project: jawallace/IOD
const char *getURL(const char *rssfile, const char *logfile) {
    xmlTextReaderPtr reader;
    FILE* log;
    const char *url;
    const char *name, *value;
    const char *msg;
    xmlChar* xmlURL;
    int ret = 0, LOGGING = TRUE;

    log = fopen(logfile, "a");
    if( log == NULL ) {
        // no logfile, disable logging
        LOGGING = FALSE;
    }

    if( LOGGING ) {
        msg = "[INFO]\tAttempting to extract URL from RSS file...";
        myLog(log, msg);
    }

    if( rssfile == NULL ) {
        if( LOGGING ) {
            msg = "[ERROR]\tGiven NULL value for RSS file.";
            myLog(log, msg); 
        }

        return NULL;
    }

    reader = xmlReaderForFile(rssfile, NULL, 0);

    if( reader == NULL ) {
        if( LOGGING ) {
            msg = "[ERROR]\tXML Reader could not open RSS file";
            myLog(log, msg); 
        }

        return NULL;
    }

    ret = xmlTextReaderRead(reader);
    while( ret == 1 ) {
        name = xmlTextReaderConstName(reader);

        if(xmlStrEqual(name, (const xmlChar *) "url") == 1) {
            ret = xmlTextReaderRead(reader);
            if( ret != 1 ) {
                if( LOGGING ) {
                    msg = "[ERROR]\tFailed to read URL.";
                    myLog(log, msg);
                }
                return NULL;
            }

            xmlURL = xmlTextReaderValue(reader);
            url = (const char *) xmlStrdup(xmlURL);

            if( LOGGING ) {
                msg = "[INFO]\t...Succeeded!";
                myLog(log, msg); 
            }

            xmlFree(xmlURL);
            xmlFreeTextReader(reader);
            fclose(log);

            return (const char *) url;
        }

        ret = xmlTextReaderRead(reader);
    }

    goto cleanup;
    return NULL;
cleanup:
    xmlFreeTextReader(reader);
    fclose(log);
}
Example #25
0
/********************************************************************
* FUNCTION mgr_xml_skip_subtree
* 
* Already encountered an error, so advance nodes until the
* matching start-node is reached or a terminating error occurs
*   - end of input
*   - start depth level reached
*
* INPUTS:
*   reader == XmlReader already initialized from File, Memory,
*             or whatever
*   startnode  == xml_node_t of the start node of the sub-tree to skip
* RETURNS:
*   status of the operation
* SIDE EFFECTS:
*   the xmlreader state is advanced until the current node is the
*   end node of the specified start node or a fatal error occurs
*********************************************************************/
status_t 
    mgr_xml_skip_subtree (xmlTextReaderPtr reader,
                          const xml_node_t *startnode)
{
    xml_node_t       node;
    const xmlChar   *qname, *badns;
    uint32           len;
    int              ret, depth, nodetyp;
    xmlns_id_t       nsid;
    boolean          done, justone;
    status_t         res;

#ifdef DEBUG
    if (!reader || !startnode) {
        return SET_ERROR(ERR_INTERNAL_PTR);
    }
#endif

    justone = FALSE;

    switch (startnode->nodetyp) {
    case XML_NT_START:
        break;
    case XML_NT_EMPTY:
        return NO_ERR;
    case XML_NT_STRING:
        justone = TRUE;
        break;
    case XML_NT_END:
        return NO_ERR;
    default:
        return SET_ERROR(ERR_INTERNAL_VAL);
    }
    xml_init_node(&node);
    res = mgr_xml_consume_node_noadv(reader, &node);
    if (res == NO_ERR) {
        res = xml_endnode_match(startnode, &node);
        if (res == NO_ERR) {
            xml_clean_node(&node);
            return NO_ERR;
        }
    }

    xml_clean_node(&node);
    if (justone) {
        return NO_ERR;
    }

    done = FALSE;
    while (!done) {

        /* advance the node pointer */
        ret = xmlTextReaderRead(reader);
        if (ret != 1) {
            /* fatal error */
            return ERR_XML_READER_EOF;
        }

        /* get the node depth to match the end node correctly */
        depth = xmlTextReaderDepth(reader);
        if (depth == -1) {
            /* not sure if this can happen, treat as fatal error */
            return ERR_XML_READER_INTERNAL;
        } else if (depth <= startnode->depth) {
            /* this depth override will cause errors to be ignored
             *   - wrong namespace in matching end node
             *   - unknown namespace in matching end node
             *   - wrong name in 'matching' end node
             */
            done = TRUE;
        }

        /* get the internal nodetype, check it and convert it */
        nodetyp = xmlTextReaderNodeType(reader);

        /* get the element QName */
        qname = xmlTextReaderConstName(reader);
        if (qname) {
            /* check for namespace prefix in the name 
             * only error is 'unregistered namespace ID'
             * which doesn't matter in this case
             */
            nsid = 0;
            (void)xml_check_ns(reader, qname, &nsid, &len, &badns);
        } else {
            qname = (const xmlChar *)"";
        }

        /* check the normal case to see if the search is done */
        if (depth == startnode->depth &&
            !xml_strcmp(qname, startnode->qname) &&
            nodetyp == XML_ELEMENT_DECL) {
            done = TRUE;
        }

#ifdef XML_UTIL_DEBUG
        log_debug3("\nxml_skip: %s L:%d T:%s",
               qname, depth, xml_get_node_name(nodetyp));
#endif
    }

    return NO_ERR;

}  /* mgr_xml_skip_subtree */
Example #26
0
int XMIResource::loadPort(xmlTextReaderPtr reader, const model::BaseObject& o)
{
    assert(o.kind() == PORT);

    // ignore datatype as it is managed as an XML node

    // iterate on attributes
    for (int rc = xmlTextReaderMoveToFirstAttribute(reader); rc > 0; rc = xmlTextReaderMoveToNextAttribute(reader))
    {
        auto found = std::find(constXcosNames.begin(), constXcosNames.end(), xmlTextReaderConstName(reader));
        enum xcosNames current = static_cast<enum xcosNames>(std::distance(constXcosNames.begin(), found));
        switch (current)
        {
            case e_uid:
            {
                std::string uid = to_string(xmlTextReaderConstValue(reader));
                controller.setObjectProperty(o.id(), o.kind(), UID, uid);
                references.insert(std::make_pair(uid, o.id()));
                break;
            }
            case e_firing:
                controller.setObjectProperty(o.id(), o.kind(), FIRING, to_double(xmlTextReaderConstValue(reader)));
                break;
            case e_sourceBlock:
            {
                // not lookup needed thanks to the XML hierarchy
                const model::BaseObject& parent = processed.back();
                controller.setObjectProperty(o.id(), o.kind(), SOURCE_BLOCK, parent.id());
                break;
            }
            case e_kind:
            {
                std::string portKindStr = to_string(xmlTextReaderConstValue(reader));
                int k;
                if ("in" == portKindStr)
                {
                    k = PORT_IN;
                }
                else if ("out" == portKindStr)
                {
                    k = PORT_OUT;
                }
                else if ("ein" == portKindStr)
                {
                    k = PORT_EIN;
                }
                else if ("eout" == portKindStr)
                {
                    k = PORT_EOUT;
                }
                else
                {
                    k = PORT_UNDEF;
                }
                controller.setObjectProperty(o.id(), o.kind(), PORT_KIND, k);
                break;
            }
            case e_implicit:
                controller.setObjectProperty(o.id(), o.kind(), IMPLICIT, to_int(xmlTextReaderConstValue(reader)));
                break;
            case e_connectedSignal:
                // will be resolved later
                unresolved.push_back(
                    unresolvedReference(o.id(), o.kind(), CONNECTED_SIGNALS,
                                        to_string(xmlTextReaderConstValue(reader))));
                break;
            case e_style:
                controller.setObjectProperty(o.id(), o.kind(), STYLE, to_string(xmlTextReaderConstValue(reader)));
                break;
            case e_label:
                controller.setObjectProperty(o.id(), o.kind(), LABEL, to_string(xmlTextReaderConstValue(reader)));
                break;
            default:
                // ignore other parameters
                // TODO: Does other metamodels might be managed there ?
                break;
        }
    }

    return 1;
}
Example #27
0
void daeLIBXMLPlugin::readAttributes( daeElement *element, xmlTextReaderPtr reader ) {
	// See if the element has attributes
	if(xmlTextReaderHasAttributes(reader))
	{
		// Read in and set all the attributes
		while(xmlTextReaderMoveToNextAttribute(reader))
		{
			daeMetaAttribute *ma = element->getMeta()->getMetaAttribute((const daeString)xmlTextReaderConstName(reader));
			if( ( ma != NULL && ma->getType() != NULL && ma->getType()->getUsesStrings() ) || 
				strcmp(element->getMeta()->getName(), "any") == 0 )
			{
				// String is used as one piece
				if(!element->setAttribute( (const daeString)xmlTextReaderConstName(reader), 
					(const daeString)xmlTextReaderConstValue(reader) ) )
				{
					const xmlChar * attName	 = xmlTextReaderConstName(reader);
					const xmlChar * attValue = xmlTextReaderConstValue(reader);
					char err[256];
					memset( err, 0, 256 );
#if LIBXML_VERSION >= 20620
					sprintf(err,"The DOM was unable to create an attribute %s = %s at line %d\nProbably a schema violation.\n", attName, attValue ,xmlTextReaderGetParserLineNumber(reader));
#else
					sprintf(err,"The DOM was unable to create an attribute %s = %s \nProbably a schema violation.\n", attName, attValue);
#endif
					daeErrorHandler::get()->handleWarning( err );
				}
			}
			else
			{
				// String needs to be broken up into whitespace seperated items.  The "set" methods for numbers are smart enough to
				// grab just the first number in a string, but the ones for string lists require a null terminator between each
				// string.  If this could be fixed we could avoid a copy and memory allocation by using xmlTextReaderConstValue(reader)
				if ( ma == NULL ) {
					const xmlChar * attName	 = xmlTextReaderConstName(reader);
					const xmlChar * attValue = xmlTextReaderConstValue(reader);
					char err[256];
					memset( err, 0, 256 );
#if LIBXML_VERSION >= 20620
					sprintf(err,"The DOM was unable to create an attribute %s = %s at line %d\nProbably a schema violation.\n", attName, attValue ,xmlTextReaderGetParserLineNumber(reader));
#else				
					sprintf(err,"The DOM was unable to create an attribute %s = %s \nProbably a schema violation.\n", attName, attValue);
#endif
					daeErrorHandler::get()->handleWarning( err );
					continue;
				}
				xmlChar* value = xmlTextReaderValue(reader);
				daeChar* current = (daeChar *)value;
				while(*current != 0)
				{
					// !!!GAC NEEDS TO BE CHANGED to use XML standard whitespace parsing
					// Skip leading whitespace
					while(*current == ' ' || *current == '\r' || *current == '\n' || *current == '\t') current++;
					if(*current != 0)
					{
						daeChar* start=current;
						// Find end of string and insert a zero terminator
						while(*current != ' ' && *current != '\r' && *current != '\n' && *current != '\t' && *current != 0) current++;
						if(*current != 0)
						{
							*current = 0;
							current++;
						}
						if(!element->setAttribute( (const daeString)xmlTextReaderConstName(reader), start) )
						{
							const xmlChar * attName	 = xmlTextReaderConstName(reader);
							const xmlChar * attValue = xmlTextReaderConstValue(reader);
							char err[256];
							memset( err, 0, 256 );
#if LIBXML_VERSION >= 20620
							sprintf(err,"The DOM was unable to create an attribute %s = %s at line %d\nProbably a schema violation.\n", attName, attValue ,xmlTextReaderGetParserLineNumber(reader));
#else
							sprintf(err,"The DOM was unable to create an attribute %s = %s \nProbably a schema violation.\n", attName, attValue);
#endif
							daeErrorHandler::get()->handleWarning( err );
						}
					}
				}
				xmlFree(value);
			}
		}
	}
}
Example #28
0
int XMIResource::loadLink(xmlTextReaderPtr reader, const model::BaseObject& o)
{
    assert(o.kind() == LINK);

    // load the base class
    int ret = loadAbstractBaseObject(reader, o);
    if (ret != 1)
    {
        return ret;
    }

    // geometry is handled as in independent node
    // controlPoint is handled as in independent node

    // iterate on attributes
    for (int rc = xmlTextReaderMoveToFirstAttribute(reader); rc > 0; rc = xmlTextReaderMoveToNextAttribute(reader))
    {
        auto found = std::find(constXcosNames.begin(), constXcosNames.end(), xmlTextReaderConstName(reader));
        enum xcosNames current = static_cast<enum xcosNames>(std::distance(constXcosNames.begin(), found));
        switch (current)
        {
            case e_uid:
            {
                std::string uid = to_string(xmlTextReaderConstValue(reader));
                controller.setObjectProperty(o.id(), o.kind(), UID, uid);
                references.insert(std::make_pair(uid, o.id()));
                break;
            }
            case e_sourcePort:
                // will be resolved later
                unresolved.push_back(
                    unresolvedReference(o.id(), o.kind(), SOURCE_PORT, to_string(xmlTextReaderConstValue(reader))));
                break;
            case e_destinationPort:
                // will be resolved later
                unresolved.push_back(
                    unresolvedReference(o.id(), o.kind(), DESTINATION_PORT,
                                        to_string(xmlTextReaderConstValue(reader))));
                break;
            case e_style:
                controller.setObjectProperty(o.id(), o.kind(), STYLE, to_string(xmlTextReaderConstValue(reader)));
                break;
            case e_label:
                controller.setObjectProperty(o.id(), o.kind(), LABEL, to_string(xmlTextReaderConstValue(reader)));
                break;
            case e_lineWidth:
            {
                std::vector<double> thick;
                controller.getObjectProperty(o.id(), o.kind(), THICK, thick);
                thick[0] = to_double(xmlTextReaderConstValue(reader));
                controller.setObjectProperty(o.id(), o.kind(), THICK, thick);
                break;
            }
            case e_lineHeight:
            {
                std::vector<double> thick;
                controller.getObjectProperty(o.id(), o.kind(), THICK, thick);
                thick[1] = to_double(xmlTextReaderConstValue(reader));
                controller.setObjectProperty(o.id(), o.kind(), THICK, thick);
                break;
            }
            case e_color:
                controller.setObjectProperty(o.id(), o.kind(), COLOR, to_int(xmlTextReaderConstValue(reader)));
                break;
            default:
                // ignore other parameters
                // TODO: Does other metamodels might be managed there ?
                break;
        }
    }

    return ret;
}
static void
load_iso_entries (int iso,
		  GFunc read_entry_func,
		  gpointer user_data)
{
	xmlTextReaderPtr reader;
	ParserState state = STATE_START;
	xmlChar iso_entries[32], iso_entry[32];
	char *filename;
	int ret = -1;

	cedit_debug_message (DEBUG_PLUGINS, "Loading ISO-%d codes", iso);

	filename = g_strdup_printf (ISO_CODES_PREFIX "/share/xml/iso-codes/iso_%d.xml", iso);
	reader = xmlNewTextReaderFilename (filename);
	if (reader == NULL) goto out;

	xmlStrPrintf (iso_entries, sizeof (iso_entries), (const xmlChar *)"iso_%d_entries", iso);
	xmlStrPrintf (iso_entry, sizeof (iso_entry), (const xmlChar *)"iso_%d_entry", iso);

	ret = xmlTextReaderRead (reader);

	while (ret == 1)
	{
		const xmlChar *tag;
		xmlReaderTypes type;

		tag = xmlTextReaderConstName (reader);
		type = xmlTextReaderNodeType (reader);

		if (state == STATE_ENTRIES &&
		    type == XML_READER_TYPE_ELEMENT &&
		    xmlStrEqual (tag, iso_entry))
		{
			read_entry_func (reader, user_data);
		}
		else if (state == STATE_START &&
			 type == XML_READER_TYPE_ELEMENT &&
			 xmlStrEqual (tag, iso_entries))
		{
			state = STATE_ENTRIES;
		}
		else if (state == STATE_ENTRIES &&
			 type == XML_READER_TYPE_END_ELEMENT &&
			 xmlStrEqual (tag, iso_entries))
		{
			state = STATE_STOP;
		}
		else if (type == XML_READER_TYPE_SIGNIFICANT_WHITESPACE ||
			 type == XML_READER_TYPE_WHITESPACE ||
			 type == XML_READER_TYPE_TEXT ||
			 type == XML_READER_TYPE_COMMENT)
		{
			/* eat it */
		}
		else
		{
			/* ignore it */
		}

		ret = xmlTextReaderRead (reader);
	}

	xmlFreeTextReader (reader);

out:
	if (ret < 0 || state != STATE_STOP)
	{
		g_warning ("Failed to load ISO-%d codes from %s!\n",
			   iso, filename);
	}

	g_free (filename);
}
Example #30
0
int XMIResource::loadBlock(xmlTextReaderPtr reader, const model::BaseObject& o)
{
    assert(o.kind() == BLOCK);

    // load the base class
    int ret = loadAbstractBaseObject(reader, o);
    if (ret != 1)
    {
        return ret;
    }

    // Layer has no attribute so there is no need to decode it there
    // Geometry is handled as an element

    // iterate on attributes
    for (int rc = xmlTextReaderMoveToFirstAttribute(reader); rc > 0; rc = xmlTextReaderMoveToNextAttribute(reader))
    {
        auto found = std::find(constXcosNames.begin(), constXcosNames.end(), xmlTextReaderConstName(reader));
        enum xcosNames current = static_cast<enum xcosNames>(std::distance(constXcosNames.begin(), found));
        switch (current)
        {
            case e_description:
                controller.setObjectProperty(o.id(), o.kind(), DESCRIPTION, to_string(xmlTextReaderConstValue(reader)));
                break;
            case e_label:
                controller.setObjectProperty(o.id(), o.kind(), LABEL, to_string(xmlTextReaderConstValue(reader)));
                break;
            case e_style:
                controller.setObjectProperty(o.id(), o.kind(), STYLE, to_string(xmlTextReaderConstValue(reader)));
                break;
            case e_interfaceFunction:
                controller.setObjectProperty(o.id(), o.kind(), INTERFACE_FUNCTION, to_string(xmlTextReaderConstValue(reader)));
                break;
            case e_functionName:
                controller.setObjectProperty(o.id(), o.kind(), SIM_FUNCTION_NAME, to_string(xmlTextReaderConstValue(reader)));
                break;
            case e_functionAPI:
                controller.setObjectProperty(o.id(), o.kind(), SIM_FUNCTION_API, to_int(xmlTextReaderConstValue(reader)));
                break;
            case e_dependsOnT:
            {
                std::vector<int> dep_ut;
                controller.getObjectProperty(o.id(), o.kind(), SIM_DEP_UT, dep_ut);
                dep_ut.resize(2);

                dep_ut[1] = to_int(xmlTextReaderConstValue(reader));
                controller.setObjectProperty(o.id(), o.kind(), SIM_DEP_UT, dep_ut);
                break;
            }
            case e_dependsOnU:
            {
                std::vector<int> dep_ut;
                controller.getObjectProperty(o.id(), o.kind(), SIM_DEP_UT, dep_ut);
                dep_ut.resize(2);

                dep_ut[0] = to_int(xmlTextReaderConstValue(reader));
                controller.setObjectProperty(o.id(), o.kind(), SIM_DEP_UT, dep_ut);
                break;
            }
            case e_blocktype:
                controller.setObjectProperty(o.id(), o.kind(), SIM_BLOCKTYPE, to_string(xmlTextReaderConstValue(reader)));
                break;
            default:
                // ignore other parameters
                // TODO: Does other metamodels might be managed there ?
                break;
        }
    }

    /*
     * Reset some properties loaded as array and initialized with non-empty value
     */
    std::vector<int> empty_int_array;
    controller.setObjectProperty(o.id(), o.kind(), NZCROSS, empty_int_array);
    controller.setObjectProperty(o.id(), o.kind(), NMODE, empty_int_array);

    return 1;
}