Search in sources :

Example 21 with ResourceInstantiationException

use of gate.creole.ResourceInstantiationException in project gate-core by GateNLP.

the class NameBearerHandle method buildViews.

protected void buildViews() {
    viewsBuilt = true;
    fireStatusChanged("Building views...");
    // build the large views
    List<String> largeViewNames = Gate.getCreoleRegister().getLargeVRsForResource(target.getClass().getName());
    if (largeViewNames != null && !largeViewNames.isEmpty()) {
        largeView = new JTabbedPane(JTabbedPane.BOTTOM);
        Iterator<String> classNameIter = largeViewNames.iterator();
        while (classNameIter.hasNext()) {
            try {
                String className = classNameIter.next();
                ResourceData rData = Gate.getCreoleRegister().get(className);
                FeatureMap params = Factory.newFeatureMap();
                FeatureMap features = Factory.newFeatureMap();
                Gate.setHiddenAttribute(features, true);
                VisualResource view = (VisualResource) Factory.createResource(className, params, features);
                try {
                    view.setTarget(target);
                } catch (IllegalArgumentException iae) {
                    // the view cannot display this particular target
                    Factory.deleteResource(view);
                    view = null;
                }
                if (view != null) {
                    view.setHandle(this);
                    ((JTabbedPane) largeView).add((Component) view, rData.getName());
                    // publishers
                    if (view instanceof ActionsPublisher)
                        actionPublishers.add((ActionsPublisher) view);
                }
            } catch (ResourceInstantiationException rie) {
                rie.printStackTrace(Err.getPrintWriter());
            }
        }
        // select the first view by default
        ((JTabbedPane) largeView).setSelectedIndex(0);
    }
    // build the small views
    List<String> smallViewNames = Gate.getCreoleRegister().getSmallVRsForResource(target.getClass().getName());
    if (smallViewNames != null && !smallViewNames.isEmpty()) {
        smallView = new JTabbedPane(JTabbedPane.BOTTOM);
        Iterator<String> classNameIter = smallViewNames.iterator();
        while (classNameIter.hasNext()) {
            try {
                String className = classNameIter.next();
                ResourceData rData = Gate.getCreoleRegister().get(className);
                FeatureMap params = Factory.newFeatureMap();
                FeatureMap features = Factory.newFeatureMap();
                Gate.setHiddenAttribute(features, true);
                VisualResource view = (VisualResource) Factory.createResource(className, params, features);
                try {
                    view.setTarget(target);
                } catch (IllegalArgumentException iae) {
                    // the view cannot display this particular target
                    Factory.deleteResource(view);
                    view = null;
                }
                if (view != null) {
                    view.setHandle(this);
                    ((JTabbedPane) smallView).add((Component) view, rData.getName());
                    if (view instanceof ActionsPublisher)
                        actionPublishers.add((ActionsPublisher) view);
                }
            } catch (ResourceInstantiationException rie) {
                rie.printStackTrace(Err.getPrintWriter());
            }
        }
        ((JTabbedPane) smallView).setSelectedIndex(0);
    }
    fireStatusChanged("Views built!");
    // Add the CTRL +F4 key & action combination to the resource
    JComponent largeView = this.getLargeView();
    if (largeView != null) {
        largeView.getActionMap().put("Close resource", new CloseAction());
        if (target instanceof Controller) {
            largeView.getActionMap().put("Close recursively", new CloseRecursivelyAction());
        }
    /*if(target instanceof gate.TextualDocument) {
        largeView.getActionMap().put("Save As XML", new SaveAsXmlAction());
      }// End if*/
    }
// End if
}
Also used : ResourceData(gate.creole.ResourceData) VisualResource(gate.VisualResource) JTabbedPane(javax.swing.JTabbedPane) JComponent(javax.swing.JComponent) SerialAnalyserController(gate.creole.SerialAnalyserController) Controller(gate.Controller) ConditionalSerialAnalyserController(gate.creole.ConditionalSerialAnalyserController) CorpusController(gate.CorpusController) ConditionalController(gate.creole.ConditionalController) ResourceInstantiationException(gate.creole.ResourceInstantiationException) FeatureMap(gate.FeatureMap)

Example 22 with ResourceInstantiationException

use of gate.creole.ResourceInstantiationException in project gate-core by GateNLP.

the class NewResourceDialog method show.

public synchronized void show(ResourceData rData) {
    if (rData != null) {
        this.resourceData = rData;
        String name = "";
        try {
            // Only try to generate a name for a PR - other types should be named after what they contain, really!
            if (ProcessingResource.class.isAssignableFrom(rData.getResourceClass())) {
                name = rData.getName() + " " + Gate.genSym();
            }
        } catch (ClassNotFoundException e) {
            Err.getPrintWriter().println("Couldn't load input resource class when showing dialogue.");
        }
        nameField.setText(name);
        parametersEditor.init(null, rData, rData.getParameterList().getInitimeParameters());
        pack();
        setLocationRelativeTo(getOwner());
    } else {
    // dialog already populated
    }
    // default case when the dialog just gets closed
    userCanceled = true;
    // show the dialog
    setVisible(true);
    if (userCanceled) {
        // release resources
        dispose();
        return;
    } else {
        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                // create the new resource
                FeatureMap params = parametersEditor.getParameterValues();
                gate.event.StatusListener sListener = (gate.event.StatusListener) Gate.getListeners().get("gate.event.StatusListener");
                if (sListener != null)
                    sListener.statusChanged("Loading " + nameField.getText() + "...");
                gate.event.ProgressListener pListener = (gate.event.ProgressListener) Gate.getListeners().get("gate.event.ProgressListener");
                if (pListener != null) {
                    pListener.progressChanged(0);
                }
                boolean success = true;
                try {
                    long startTime = System.currentTimeMillis();
                    FeatureMap features = Factory.newFeatureMap();
                    String name = nameField.getText();
                    if (name == null || name.length() == 0)
                        name = null;
                    Factory.createResource(resourceData.getClassName(), params, features, name);
                    long endTime = System.currentTimeMillis();
                    if (sListener != null)
                        sListener.statusChanged(nameField.getText() + " loaded in " + NumberFormat.getInstance().format((double) (endTime - startTime) / 1000) + " seconds");
                    if (pListener != null)
                        pListener.processFinished();
                } catch (ResourceInstantiationException rie) {
                    success = false;
                    JOptionPane.showMessageDialog(getOwner(), "Resource could not be created!\n" + rie.toString(), "GATE", JOptionPane.ERROR_MESSAGE);
                    rie.printStackTrace(Err.getPrintWriter());
                    if (sListener != null)
                        sListener.statusChanged("Error loading " + nameField.getText() + "!");
                    if (pListener != null)
                        pListener.processFinished();
                } catch (Throwable thr) {
                    success = false;
                    JOptionPane.showMessageDialog(getOwner(), "Unhandled error!\n" + thr.toString(), "GATE", JOptionPane.ERROR_MESSAGE);
                    thr.printStackTrace(Err.getPrintWriter());
                    if (sListener != null)
                        sListener.statusChanged("Error loading " + nameField.getText() + "!");
                    if (pListener != null)
                        pListener.processFinished();
                } finally {
                    if (!success) {
                        // re-show the dialog, to allow the suer to correct the entry
                        SwingUtilities.invokeLater(new Runnable() {

                            @Override
                            public void run() {
                                show(null);
                            }
                        });
                    } else {
                        dispose();
                    }
                }
            }
        };
        Thread thread = new Thread(runnable, "");
        thread.setPriority(Thread.MIN_PRIORITY);
        thread.start();
    }
}
Also used : ResourceInstantiationException(gate.creole.ResourceInstantiationException) FeatureMap(gate.FeatureMap)

Example 23 with ResourceInstantiationException

use of gate.creole.ResourceInstantiationException in project gate-core by GateNLP.

the class PRPersistence method extractDataFromSource.

/**
 * Populates this Persistence with the data that needs to be stored from the
 * original source object.
 */
@Override
public void extractDataFromSource(Object source) throws PersistenceException {
    if (!(source instanceof ProcessingResource)) {
        throw new UnsupportedOperationException(getClass().getName() + " can only be used for " + ProcessingResource.class.getName() + " objects!\n" + source.getClass().getName() + " is not a " + ProcessingResource.class.getName());
    }
    super.extractDataFromSource(source);
    Resource res = (Resource) source;
    ResourceData rData = Gate.getCreoleRegister().get(res.getClass().getName());
    if (rData == null)
        throw new PersistenceException("Could not find CREOLE data for " + res.getClass().getName());
    // now get the runtime params
    ParameterList params = rData.getParameterList();
    try {
        // get the values for the init time parameters
        runtimeParams = Factory.newFeatureMap();
        // this is a list of lists
        Iterator<List<Parameter>> parDisjIter = params.getRuntimeParameters().iterator();
        while (parDisjIter.hasNext()) {
            Iterator<Parameter> parIter = parDisjIter.next().iterator();
            while (parIter.hasNext()) {
                Parameter parameter = parIter.next();
                String parName = parameter.getName();
                Object parValue = res.getParameterValue(parName);
                if (storeParameterValue(parValue, parameter.getDefaultValue())) {
                    ((FeatureMap) runtimeParams).put(parName, parValue);
                }
            }
        }
        runtimeParams = PersistenceManager.getPersistentRepresentation(runtimeParams);
    } catch (ResourceInstantiationException | ParameterException rie) {
        throw new PersistenceException(rie);
    }
}
Also used : ResourceData(gate.creole.ResourceData) ProcessingResource(gate.ProcessingResource) Resource(gate.Resource) ProcessingResource(gate.ProcessingResource) ResourceInstantiationException(gate.creole.ResourceInstantiationException) FeatureMap(gate.FeatureMap) PersistenceException(gate.persist.PersistenceException) ParameterList(gate.creole.ParameterList) Parameter(gate.creole.Parameter) ParameterList(gate.creole.ParameterList) List(java.util.List) ParameterException(gate.creole.ParameterException)

Example 24 with ResourceInstantiationException

use of gate.creole.ResourceInstantiationException in project gate-core by GateNLP.

the class PersistenceManager method loadObjectFromUrl.

public static Object loadObjectFromUrl(URL url) throws PersistenceException, IOException, ResourceInstantiationException {
    if (!Gate.isInitialised())
        throw new ResourceInstantiationException("You must call Gate.init() before you can restore resources");
    ProgressListener pListener = (ProgressListener) Gate.getListeners().get("gate.event.ProgressListener");
    StatusListener sListener = (gate.event.StatusListener) Gate.getListeners().get("gate.event.StatusListener");
    if (pListener != null)
        pListener.progressChanged(0);
    startLoadingFrom(url);
    // the actual stream obtained from the URL. We keep a reference to this
    // so we can ensure it gets closed.
    InputStream rawStream = null;
    try {
        long startTime = System.currentTimeMillis();
        // Determine whether the file contains an application serialized in
        // xml
        // format. Otherwise we will assume that it contains native
        // serializations.
        boolean xmlStream = isXmlApplicationFile(url);
        ObjectInputStream ois = null;
        HierarchicalStreamReader reader = null;
        XStream xstream = null;
        // whether serialization is native or xml.
        if (xmlStream) {
            // we don't want to strip the BOM on XML.
            Reader inputReader = new InputStreamReader(rawStream = url.openStream());
            try {
                XMLInputFactory inputFactory = XMLInputFactory.newInstance();
                inputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
                XMLStreamReader xsr = inputFactory.createXMLStreamReader(url.toExternalForm(), inputReader);
                reader = new StaxReader(new QNameMap(), xsr);
            } catch (XMLStreamException xse) {
                // make sure the stream is closed, on error
                inputReader.close();
                throw new PersistenceException("Error creating reader", xse);
            }
            xstream = new XStream(new StaxDriver(new XStream11NameCoder())) {

                @Override
                protected boolean useXStream11XmlFriendlyMapper() {
                    return true;
                }
            };
            // make XStream load classes through the GATE ClassLoader
            xstream.setClassLoader(Gate.getClassLoader());
            // make the XML stream appear as a normal ObjectInputStream
            ois = xstream.createObjectInputStream(reader);
        } else {
            // use GateAwareObjectInputStream to load classes through the
            // GATE ClassLoader if they can't be loaded through the one
            // ObjectInputStream would normally use
            ois = new GateAwareObjectInputStream(url.openStream());
        }
        Object res = null;
        try {
            // first read the list of creole URLs.
            @SuppressWarnings("unchecked") Iterator<?> urlIter = ((Collection<?>) getTransientRepresentation(ois.readObject())).iterator();
            // and re-register them
            while (urlIter.hasNext()) {
                Object anUrl = urlIter.next();
                try {
                    if (anUrl instanceof URL)
                        Gate.getCreoleRegister().registerPlugin(new Plugin.Directory((URL) anUrl), false);
                    else if (anUrl instanceof Plugin)
                        Gate.getCreoleRegister().registerPlugin((Plugin) anUrl, false);
                } catch (GateException ge) {
                    System.out.println("We've hit an error!");
                    ge.printStackTrace();
                    ge.printStackTrace(Err.getPrintWriter());
                    Err.prln("Could not reload creole directory " + anUrl);
                }
            }
            // now we can read the saved object in the presence of all
            // the right plugins
            res = ois.readObject();
            // ensure a fresh start
            clearCurrentTransients();
            res = getTransientRepresentation(res);
            long endTime = System.currentTimeMillis();
            if (sListener != null)
                sListener.statusChanged("Loading completed in " + NumberFormat.getInstance().format((double) (endTime - startTime) / 1000) + " seconds");
            return res;
        } catch (ResourceInstantiationException rie) {
            if (sListener != null)
                sListener.statusChanged("Failure during instantiation of resources.");
            throw rie;
        } catch (PersistenceException pe) {
            if (sListener != null)
                sListener.statusChanged("Failure during persistence operations.");
            throw pe;
        } catch (Exception ex) {
            if (sListener != null)
                sListener.statusChanged("Loading failed!");
            throw new PersistenceException(ex);
        } finally {
            // make sure the stream gets closed
            if (ois != null)
                ois.close();
            if (reader != null)
                reader.close();
        }
    } finally {
        if (rawStream != null)
            rawStream.close();
        finishedLoading();
        if (pListener != null)
            pListener.processFinished();
    }
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) XMLStreamReader(javax.xml.stream.XMLStreamReader) Reader(java.io.Reader) HierarchicalStreamReader(com.thoughtworks.xstream.io.HierarchicalStreamReader) BomStrippingInputStreamReader(gate.util.BomStrippingInputStreamReader) StaxReader(com.thoughtworks.xstream.io.xml.StaxReader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) URL(java.net.URL) StaxDriver(com.thoughtworks.xstream.io.xml.StaxDriver) HierarchicalStreamReader(com.thoughtworks.xstream.io.HierarchicalStreamReader) QNameMap(com.thoughtworks.xstream.io.xml.QNameMap) StaxReader(com.thoughtworks.xstream.io.xml.StaxReader) BomStrippingInputStreamReader(gate.util.BomStrippingInputStreamReader) InputStreamReader(java.io.InputStreamReader) GateAwareObjectInputStream(gate.persist.GateAwareObjectInputStream) ObjectInputStream(java.io.ObjectInputStream) GateAwareObjectInputStream(gate.persist.GateAwareObjectInputStream) InputStream(java.io.InputStream) XStream(com.thoughtworks.xstream.XStream) GateException(gate.util.GateException) URISyntaxException(java.net.URISyntaxException) XMLStreamException(javax.xml.stream.XMLStreamException) PersistenceException(gate.persist.PersistenceException) GateRuntimeException(gate.util.GateRuntimeException) ResourceInstantiationException(gate.creole.ResourceInstantiationException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) GateException(gate.util.GateException) ResourceInstantiationException(gate.creole.ResourceInstantiationException) ProgressListener(gate.event.ProgressListener) XMLStreamException(javax.xml.stream.XMLStreamException) XStream11NameCoder(com.thoughtworks.xstream.io.xml.XStream11NameCoder) PersistenceException(gate.persist.PersistenceException) Collection(java.util.Collection) StatusListener(gate.event.StatusListener) XMLInputFactory(javax.xml.stream.XMLInputFactory) ObjectInputStream(java.io.ObjectInputStream) GateAwareObjectInputStream(gate.persist.GateAwareObjectInputStream) Plugin(gate.creole.Plugin)

Example 25 with ResourceInstantiationException

use of gate.creole.ResourceInstantiationException in project gate-core by GateNLP.

the class CorpusBenchmarkTool method evaluateTwoDocs.

// evaluateAllThree
protected void evaluateTwoDocs(Document keyDoc, Document respDoc, File errDir) throws ResourceInstantiationException {
    // first start the table and its header
    printTableHeader();
    // store annotation diff in .err file
    Writer errWriter = null;
    if (isMoreInfoMode && errDir != null) {
        StringBuffer docName = new StringBuffer(keyDoc.getName());
        docName.replace(keyDoc.getName().lastIndexOf("."), docName.length(), ".err");
        File errFile = new File(errDir, docName.toString());
        // String encoding = ( (gate.corpora.DocumentImpl) keyDoc).getEncoding();
        try {
            errWriter = new FileWriter(errFile, false);
        /*
                 if(encoding == null) {
          errWriter = new OutputStreamWriter(
              new FileOutputStream(errFile, false));
                 } else {
          errWriter = new OutputStreamWriter(
              new FileOutputStream(errFile, false), encoding);
                 }*/
        } catch (Exception ex) {
            Out.prln("Exception when creating the error file " + errFile + ": " + ex.getMessage());
            errWriter = null;
        }
    }
    for (int jj = 0; jj < annotTypes.size(); jj++) {
        String annotType = annotTypes.get(jj);
        AnnotationDiffer annotDiff = measureDocs(keyDoc, respDoc, annotType);
        // we don't have this annotation type in this document
        if (annotDiff == null)
            continue;
        // increase the number of processed documents
        docNumber++;
        // add precison and recall to the sums
        updateStatistics(annotDiff, annotType);
        Out.prln("<TR>");
        Out.prln("<TD>" + annotType + "</TD>");
        if (isMoreInfoMode) {
            Out.prln("<TD>" + annotDiff.getCorrectMatches() + "</TD>");
            Out.prln("<TD>" + annotDiff.getPartiallyCorrectMatches() + "</TD>");
            Out.prln("<TD>" + annotDiff.getMissing() + "</TD>");
            Out.prln("<TD>" + annotDiff.getSpurious() + "</TD>");
        }
        Out.prln("<TD>" + annotDiff.getPrecisionAverage() + "</TD>");
        Out.prln("<TD>" + annotDiff.getRecallAverage() + "</TD>");
        // check the recall now
        if (isVerboseMode) {
            Out.prln("<TD>");
            if (annotDiff.getRecallAverage() < threshold || annotDiff.getPrecisionAverage() < threshold) {
                printAnnotations(annotDiff, keyDoc, respDoc);
            } else {
                Out.prln("&nbsp;");
            }
            Out.prln("</TD>");
        }
        Out.prln("</TR>");
        if (isMoreInfoMode && errDir != null)
            storeAnnotations(annotType, annotDiff, keyDoc, respDoc, errWriter);
    }
    // for loop through annotation types
    Out.prln("</TABLE>");
    try {
        if (errWriter != null)
            errWriter.close();
    } catch (Exception ex) {
        Out.prln("Exception on close of error file " + errWriter + ": " + ex.getMessage());
    }
}
Also used : FileWriter(java.io.FileWriter) File(java.io.File) FileWriter(java.io.FileWriter) Writer(java.io.Writer) ResourceInstantiationException(gate.creole.ResourceInstantiationException) ExecutionException(gate.creole.ExecutionException) IOException(java.io.IOException) PersistenceException(gate.persist.PersistenceException)

Aggregations

ResourceInstantiationException (gate.creole.ResourceInstantiationException)29 FeatureMap (gate.FeatureMap)10 PersistenceException (gate.persist.PersistenceException)10 ResourceData (gate.creole.ResourceData)9 GateRuntimeException (gate.util.GateRuntimeException)6 Document (gate.Document)5 File (java.io.File)5 ParameterException (gate.creole.ParameterException)4 SerialDataStore (gate.persist.SerialDataStore)4 IOException (java.io.IOException)4 List (java.util.List)4 ProcessingResource (gate.ProcessingResource)3 Resource (gate.Resource)3 ExecutionException (gate.creole.ExecutionException)3 Parameter (gate.creole.Parameter)3 ParameterList (gate.creole.ParameterList)3 Plugin (gate.creole.Plugin)3 Dimension (java.awt.Dimension)3 BeanInfo (java.beans.BeanInfo)3 URL (java.net.URL)3