Search in sources :

Example 11 with GateRuntimeException

use of gate.util.GateRuntimeException in project gate-core by GateNLP.

the class CreoleXmlHandler method startElement.

// attributes2String()
/**
 * Called when the SAX parser encounts the beginning of an XML element
 */
@Override
public void startElement(String uri, String qName, String elementName, Attributes atts) throws SAXException {
    // call characterActions
    if (readCharacterStatus) {
        readCharacterStatus = false;
        charactersAction(new String(contentBuffer).toCharArray(), 0, contentBuffer.length());
    }
    if (DEBUG) {
        Out.pr("startElement: ");
        Out.println(elementName + " " + attributes2String(atts));
    }
    // create a new ResourceData when it's a RESOURCE element
    if (elementName.toUpperCase().equals("RESOURCE")) {
        resourceData = new ResourceData();
        resourceData.setFeatures(Factory.newFeatureMap());
        currentAutoinstances = new ArrayList<FeatureMap>();
    }
    // End if RESOURCE
    // record the attributes of this element
    currentAttributes = atts;
    // be prepared in order for the resource to be instantiated
    if (elementName.toUpperCase().equals("AUTOINSTANCE")) {
        currentAutoinstanceParams = Factory.newFeatureMap();
    }
    // be prepared in order for the resource to be instantiated
    if (elementName.toUpperCase().equals("HIDDEN-AUTOINSTANCE")) {
        currentAutoinstanceParams = Factory.newFeatureMap();
        Gate.setHiddenAttribute(currentAutoinstanceParams, true);
    }
    // with a value and added to the autoinstanceParams
    if (elementName.toUpperCase().equals("PARAM")) {
        // parser would signal this later....
        if (currentAutoinstanceParams == null)
            currentAutoinstanceParams = Factory.newFeatureMap();
        // Take the param's name and value
        String paramName = currentAttributes.getValue("NAME");
        String paramStrValue = currentAttributes.getValue("VALUE");
        if (paramName == null)
            throw new GateRuntimeException("Found in creole.xml a PARAM element" + " for resource " + resourceData.getClassName() + " without a NAME" + " attribute. Check the file and try again.");
        if (paramStrValue == null)
            throw new GateRuntimeException("Found in creole.xml a PARAM element" + " for resource " + resourceData.getClassName() + " without a VALUE" + " attribute. Check the file and try again.");
        // Add the paramname and its value to the autoinstanceParams
        currentAutoinstanceParams.put(paramName, paramStrValue);
    }
    // process attributes of parameter and GUI elements
    if (elementName.toUpperCase().equals("PARAMETER")) {
        if (DEBUG) {
            for (int i = 0, len = currentAttributes.getLength(); i < len; i++) {
                Out.prln(currentAttributes.getLocalName(i));
                Out.prln(currentAttributes.getValue(i));
            }
        // End for
        }
        // End if
        currentParam.comment = currentAttributes.getValue("COMMENT");
        currentParam.helpURL = currentAttributes.getValue("HELPURL");
        currentParam.defaultValueString = currentAttributes.getValue("DEFAULT");
        currentParam.optional = Boolean.valueOf(currentAttributes.getValue("OPTIONAL")).booleanValue();
        currentParam.name = currentAttributes.getValue("NAME");
        currentParam.runtime = Boolean.valueOf(currentAttributes.getValue("RUNTIME")).booleanValue();
        currentParam.itemClassName = currentAttributes.getValue("ITEM_CLASS_NAME");
        // read the suffixes and transform them to a Set of Strings
        String suffixes = currentAttributes.getValue("SUFFIXES");
        Set<String> suffiexesSet = null;
        if (suffixes != null) {
            suffiexesSet = new HashSet<String>();
            StringTokenizer strTokenizer = new StringTokenizer(suffixes, ";");
            while (strTokenizer.hasMoreTokens()) {
                suffiexesSet.add(strTokenizer.nextToken());
            }
        // End while
        }
        // End if
        currentParam.suffixes = suffiexesSet;
    } else if (elementName.toUpperCase().equals("GUI")) {
        String typeValue = currentAttributes.getValue("TYPE");
        if (typeValue != null) {
            if (typeValue.toUpperCase().equals("LARGE"))
                resourceData.setGuiType(ResourceData.LARGE_GUI);
            if (typeValue.toUpperCase().equals("SMALL"))
                resourceData.setGuiType(ResourceData.SMALL_GUI);
        }
    // End if
    }
    // (note that they're not disjunctive or previous "/OR" would have got 'em)
    if (elementName.toUpperCase().equals("OR")) {
        if (!currentParamDisjunction.isEmpty()) {
            currentParamList.addAll(currentFlattenedDisjunction());
            currentParamDisjunction.clear();
        }
    // End if
    }
// End if
}
Also used : FeatureMap(gate.FeatureMap) StringTokenizer(java.util.StringTokenizer) GateRuntimeException(gate.util.GateRuntimeException)

Example 12 with GateRuntimeException

use of gate.util.GateRuntimeException in project gate-core by GateNLP.

the class CreoleXmlHandler method endElement.

// checkStack
/**
 * Called when the SAX parser encounts the end of an XML element.
 * This is where ResourceData objects get values set, and where
 * they are added to the CreoleRegister when we parsed their complete
 * metadata entries.
 */
@Override
public void endElement(String uri, String qName, String elementName) throws GateSaxException, SAXException {
    // call characterActions
    if (readCharacterStatus) {
        readCharacterStatus = false;
        charactersAction(new String(contentBuffer).toCharArray(), 0, contentBuffer.length());
    }
    if (DEBUG)
        Out.prln("endElement: " + elementName);
    // ////////////////////////////////////////////////////////////////
    if (elementName.toUpperCase().equals("RESOURCE")) {
        // check for validity of the resource data
        if (!resourceData.isValid())
            throw new GateSaxException("Invalid resource data: " + resourceData.getValidityMessage());
        // TODO should this be a URI instead of the URL?
        try {
            resourceData.setXmlFileUrl(new URL(plugin.getBaseURL(), "creole.xml"));
        } catch (MalformedURLException e) {
            throw new GateSaxException("Couldn't load autoloading resource: " + resourceData.getName() + "; problem was: " + e, e);
        }
        // add the new resource data object to the creole register
        register.put(resourceData.getClassName(), resourceData);
        // if the resource is auto-loading, try and load it
        if (resourceData.isAutoLoading())
            try {
                @SuppressWarnings("unused") Class<?> resClass = resourceData.getResourceClass();
            // Resource res = Factory.createResource(
            // resourceData.getClassName(), Factory.newFeatureMap()
            // );
            // resourceData.makeInstantiationPersistant(res);
            } catch (ClassNotFoundException e) {
                throw new GateSaxException("Couldn't load autoloading resource: " + resourceData.getName() + "; problem was: " + e);
            }
        // (note that they're not disjunctive or the "/OR" would have got them)
        if (!currentParamDisjunction.isEmpty()) {
            currentParamList.addAll(currentFlattenedDisjunction());
            currentParamDisjunction.clear();
        }
        // End if
        // add the parameter list to the resource (and reinitialise it)
        resourceData.setParameterList(currentParamList);
        currentParamList = new ParameterList();
        // final initialization of the ResourceData
        try {
            resourceData.init();
        } catch (Exception ex) {
            throw new GateSaxException("Couldn't initialize ResourceData for " + resourceData.getName(), ex);
        }
        if (DEBUG)
            Out.println("added: " + resourceData);
        // Iterate through autoinstances and try to instanciate them
        if (currentAutoinstances != null && !currentAutoinstances.isEmpty()) {
            ResourceData rd = Gate.getCreoleRegister().get(resourceData.getClassName());
            ParameterList existingParameters = null;
            if (rd.getReferenceCount() > 1) {
                // we aren't going to redefine a resource but we do need to use the
                // parameters from the new instance so we get the right base URL and
                // default values etc.
                existingParameters = rd.getParameterList();
                rd.setParameterList(resourceData.getParameterList());
            }
            try {
                Iterator<FeatureMap> iter = currentAutoinstances.iterator();
                while (iter.hasNext()) {
                    FeatureMap autoinstanceParams = iter.next();
                    iter.remove();
                    FeatureMap autoinstanceFeatures = null;
                    // map and move the hidden attribute there.
                    if (Gate.getHiddenAttribute(autoinstanceParams)) {
                        autoinstanceFeatures = Factory.newFeatureMap();
                        Gate.setHiddenAttribute(autoinstanceFeatures, true);
                        autoinstanceParams.remove(GateConstants.HIDDEN_FEATURE_KEY);
                    }
                    // Try to create the resource.
                    try {
                        // Resource res =
                        Factory.createResource(resourceData.getClassName(), autoinstanceParams, autoinstanceFeatures);
                    // resourceData.makeInstantiationPersistant(res);
                    // all resource instantiations are persistent
                    } catch (ResourceInstantiationException e) {
                        throw new GateSaxException("Couldn't auto-instantiate resource: " + resourceData.getName() + "; problem was: " + e);
                    }
                // End try
                }
            // End while
            } finally {
                // resource then put them back before we break something
                if (existingParameters != null)
                    rd.setParameterList(existingParameters);
            }
        }
        // End if
        currentAutoinstances = null;
    // End RESOURCE processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("AUTOINSTANCE") || elementName.toUpperCase().equals("HIDDEN-AUTOINSTANCE")) {
        // Cache the auto-instance into the autoins
        if (currentAutoinstanceParams != null)
            currentAutoinstances.add(currentAutoinstanceParams);
    // End AUTOINSTANCE processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("PARAM")) {
    // End PARAM processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("NAME")) {
        checkStack("endElement", "NAME");
        resourceData.setName(contentStack.pop());
    // End NAME processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("IVY")) {
        if (!contentStack.isEmpty())
            contentStack.pop();
    // End IVY processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("REQUIRES")) {
        if (!contentStack.isEmpty())
            contentStack.pop();
    // End REQUIRES processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("JAR")) {
        checkStack("endElement", "JAR");
        // add jar file name
        String jarFileName = contentStack.pop();
        if (resourceData != null) {
            resourceData.setJarFileName(jarFileName);
        }
        // add jar file URL if there is one
        // if(sourceUrl != null) {
        String sourceUrlName = plugin.getBaseURL().toExternalForm();
        String separator = "/";
        if (sourceUrlName.endsWith(separator))
            separator = "";
        URL jarFileUrl = null;
        try {
            jarFileUrl = new URL(sourceUrlName + separator + jarFileName);
            if (resourceData != null) {
                resourceData.setJarFileUrl(jarFileUrl);
            }
        // We no longer need to add the jar URL to the class loader, as this
        // is done before the SAX parse
        } catch (MalformedURLException e) {
            throw new GateSaxException("bad URL " + jarFileUrl + e);
        }
    // End try
    // }// End if
    // End JAR processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("CLASS")) {
        checkStack("endElement", "CLASS");
        resourceData.setClassName(contentStack.pop());
    // End CLASS processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("COMMENT")) {
        checkStack("endElement", "COMMENT");
        resourceData.setComment(contentStack.pop());
    // End COMMENT processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("HELPURL")) {
        checkStack("endElement", "HELPURL");
        resourceData.setHelpURL(contentStack.pop());
    // End HELPURL processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("INTERFACE")) {
        checkStack("endElement", "INTERFACE");
        resourceData.setInterfaceName(contentStack.pop());
    // End INTERFACE processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("ICON")) {
        checkStack("endElement", "ICON");
        resourceData.setIcon(contentStack.pop());
    // End ICON processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("OR")) {
        currentParamList.add(currentFlattenedDisjunction());
        currentParamDisjunction.clear();
    // End OR processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("PARAMETER")) {
        checkStack("endElement", "PARAMETER");
        currentParam.typeName = contentStack.pop();
        String priorityStr = currentAttributes.getValue("PRIORITY");
        // if no priority specified, assume lowest (i.e. parameters with an
        // explicit priority come ahead of those without).
        Integer priority = Integer.MAX_VALUE;
        try {
            if (priorityStr != null)
                priority = Integer.valueOf(priorityStr);
        } catch (NumberFormatException nfe) {
            throw new GateRuntimeException("Found in creole.xml a PARAM element" + " for resource " + resourceData.getClassName() + " with a non-numeric" + " PRIORITY attribute. Check the file and try again.");
        }
        List<Parameter> paramList = currentParamDisjunction.get(priority);
        if (paramList == null) {
            paramList = new ArrayList<Parameter>();
            currentParamDisjunction.put(priority, paramList);
        }
        paramList.add(currentParam);
        if (DEBUG)
            Out.prln("added param: " + currentParam);
        currentParam = new Parameter(plugin);
    // End PARAMETER processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("AUTOLOAD")) {
        resourceData.setAutoLoading(true);
    // End AUTOLOAD processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("PRIVATE")) {
        resourceData.setPrivate(true);
    // End PRIVATE processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("TOOL")) {
        resourceData.setTool(true);
    // End TOOL processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("MAIN_VIEWER")) {
        resourceData.setIsMainView(true);
    // End MAIN_VIEWER processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("RESOURCE_DISPLAYED")) {
        checkStack("endElement", "RESOURCE_DISPLAYED");
        String resourceDisplayed = contentStack.pop();
        resourceData.setResourceDisplayed(resourceDisplayed);
        try {
            @SuppressWarnings("unused") Class<?> resourceDisplayedClass = Gate.getClassLoader().loadClass(resourceDisplayed);
        } catch (ClassNotFoundException ex) {
            throw new GateRuntimeException("Couldn't get resource class from the resource name :" + resourceDisplayed + " " + ex);
        }
    // End try
    // End RESOURCE_DISPLAYED processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("ANNOTATION_TYPE_DISPLAYED")) {
        checkStack("endElement", "ANNOTATION_TYPE_DISPLAYED");
        resourceData.setAnnotationTypeDisplayed(contentStack.pop());
    // End ANNOTATION_TYPE_DISPLAYED processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("GUI")) {
    // End GUI processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("CREOLE")) {
    // End CREOLE processing
    // ////////////////////////////////////////////////////////////////
    } else if (elementName.toUpperCase().equals("CREOLE-DIRECTORY")) {
    // End CREOLE-DIRECTORY processing
    // ////////////////////////////////////////////////////////////////
    } else {
        // arbitrary elements get added as features of the resource data
        if (resourceData != null)
            resourceData.getFeatures().put(elementName.toUpperCase(), ((contentStack.isEmpty()) ? null : contentStack.pop()));
    }
// ////////////////////////////////////////////////////////////////
}
Also used : MalformedURLException(java.net.MalformedURLException) GateSaxException(gate.util.GateSaxException) ArrayList(java.util.ArrayList) URL(java.net.URL) GateRuntimeException(gate.util.GateRuntimeException) MalformedURLException(java.net.MalformedURLException) GateSaxException(gate.util.GateSaxException) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException) FeatureMap(gate.FeatureMap) GateRuntimeException(gate.util.GateRuntimeException) ArrayList(java.util.ArrayList) List(java.util.List)

Example 13 with GateRuntimeException

use of gate.util.GateRuntimeException in project gate-core by GateNLP.

the class Utils method expandUriString.

/**
 * Expand both namespace prefixes and base-uris, if possible.
 * This will expand the String toExpand according to the following rules:
 * <ul>
 * <li>if toExpand is a qName and does start with a name prefix in the form
 * "somens:" or ":", then the name prefix is looked up in the prefixes
 * map and replaced with the URI prefix found there. If the prefix could not
 * be found a GateRuntimeException is thrown.
 * <li>if toExpand does not start with a name prefix, the entry with
 * an empty string as the key is retrieved from the prefixes map and
 * used as a baseURI: the result is the baseURI and the toExpand String
 * concatenated. If no entry with an empty string is found in the map, a
 * GateRuntimeException is thrown.   *
 * </ul>
 *
 * This method can therefore be used to expand both base uris and namespaces.
 * <p>
 * If the map only contains a basename uri (if the only entry is for the
 * empty string key) then name space prefixes are not checked: in this
 * case, the toExpand string may contain an unescaped colon.
 * If the map does not contain a basename URI (if there is no entry for the
 * empty string key) then all toExpand strings are expected to be qNames.
 * <p>
 * NOTE: the name prefixes in the prefixes map must include the trailing colon!
 *
 * @param toExpand the URI portion to expand as a String
 * @param prefixes a map from name prefixes to URI prefixes
 * @return a String with name prefixes or base URI expanded
 */
public static String expandUriString(String toExpand, Map<String, String> prefixes) {
    // lets see if we have a basename entry in the map
    String baseUri = prefixes.get("");
    // it, no matter what
    if (baseUri != null && prefixes.size() == 1) {
        return baseUri + toExpand;
    }
    // if the toExpand string starts with .*:, interpret this as the name space
    Matcher m = nsQNamePattern.matcher(toExpand);
    if (m.matches()) {
        String prefix = m.group(1);
        String lname = m.group(2);
        String uriPrefix = prefixes.get(prefix);
        if (uriPrefix == null) {
            throw new GateRuntimeException("name prefix not found in prefix map for  " + toExpand);
        } else {
            return uriPrefix + lname;
        }
    } else {
        // this is not a qName, try to expand with the baseURI
        if (baseUri == null) {
            throw new GateRuntimeException("No base Uri in prefix map for " + toExpand);
        } else {
            return baseUri + toExpand;
        }
    }
}
Also used : Matcher(java.util.regex.Matcher) GateRuntimeException(gate.util.GateRuntimeException)

Example 14 with GateRuntimeException

use of gate.util.GateRuntimeException in project gate-core by GateNLP.

the class LuceneDataStoreImpl method documentRemoved.

// Corpus Events
/**
 * This method is invoked whenever a document is removed from a corpus
 */
@Override
public void documentRemoved(CorpusEvent ce) {
    Object docLRID = ce.getDocumentLRID();
    /*
     * we need to remove this document from the index
     */
    if (docLRID != null) {
        ArrayList<Object> removed = new ArrayList<Object>();
        removed.add(docLRID);
        try {
            synchronized (indexer) {
                indexer.remove(removed);
            }
        } catch (IndexException ie) {
            throw new GateRuntimeException(ie);
        }
    // queueForIndexing(docLRID);
    }
}
Also used : IndexException(gate.creole.annic.IndexException) GateRuntimeException(gate.util.GateRuntimeException) ArrayList(java.util.ArrayList)

Example 15 with GateRuntimeException

use of gate.util.GateRuntimeException in project gate-core by GateNLP.

the class SerialDataStore method adopt.

// delete(lr)
/**
 * Adopt a resource for persistence.
 */
@Override
public LanguageResource adopt(LanguageResource lr) throws PersistenceException {
    // ignore security info
    // check the LR's current DS
    DataStore currentDS = lr.getDataStore();
    if (currentDS == null) {
        // an orphan - do the adoption
        LanguageResource res = lr;
        if (lr instanceof Corpus) {
            FeatureMap features1 = Factory.newFeatureMap();
            features1.put("transientSource", lr);
            try {
                // here we create the persistent LR via Factory, so it's registered
                // in GATE
                res = (LanguageResource) Factory.createResource("gate.corpora.SerialCorpusImpl", features1);
            // Here the transient corpus is not deleted from the CRI, because
            // this might not always be the desired behaviour
            // since we chose that it is for the GUI, this functionality is
            // now move to the 'Save to' action code in NameBearerHandle
            } catch (gate.creole.ResourceInstantiationException ex) {
                throw new GateRuntimeException(ex.getMessage());
            }
        }
        res.setDataStore(this);
        // let the world know
        fireResourceAdopted(new DatastoreEvent(this, DatastoreEvent.RESOURCE_ADOPTED, lr, null));
        return res;
    } else if (// adopted already here
    currentDS.equals(this))
        return lr;
    else {
        // someone else's child
        throw new PersistenceException("Can't adopt a resource which is already in a different datastore");
    }
}
Also used : FeatureMap(gate.FeatureMap) LanguageResource(gate.LanguageResource) DataStore(gate.DataStore) GateRuntimeException(gate.util.GateRuntimeException) DatastoreEvent(gate.event.DatastoreEvent) Corpus(gate.Corpus)

Aggregations

GateRuntimeException (gate.util.GateRuntimeException)42 ArrayList (java.util.ArrayList)12 URL (java.net.URL)6 FeatureMap (gate.FeatureMap)5 PersistenceException (gate.persist.PersistenceException)5 GateException (gate.util.GateException)5 Point (java.awt.Point)5 LinkedList (java.util.LinkedList)5 DataStore (gate.DataStore)4 ResourceInstantiationException (gate.creole.ResourceInstantiationException)4 InvalidOffsetException (gate.util.InvalidOffsetException)4 GridBagConstraints (java.awt.GridBagConstraints)4 GridBagLayout (java.awt.GridBagLayout)4 MalformedURLException (java.net.MalformedURLException)4 List (java.util.List)4 JButton (javax.swing.JButton)4 JPanel (javax.swing.JPanel)4 Annotation (gate.Annotation)3 AnnotationSet (gate.AnnotationSet)3 Corpus (gate.Corpus)3