Search in sources :

Example 16 with GateRuntimeException

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

the class PersistenceManager method getRelativePath.

/**
 * Calculates the relative path for a file: URL starting from a given
 * context which is also a file: URL.
 *
 * @param context the URL to be used as context.
 * @param target the URL for which the relative path is computed.
 * @return a String value representing the relative path. Constructing
 *         a URL from the context URL and the relative path should
 *         result in the target URL.
 */
public static String getRelativePath(URL context, URL target) {
    if (context.getProtocol().equals("file") && target.getProtocol().equals("file")) {
        File contextFile = Files.fileFromURL(context);
        File targetFile = Files.fileFromURL(target);
        // the trailing slash - is just baz.
        if (context.toExternalForm().endsWith("/")) {
            contextFile = new File(contextFile, "__dummy__");
        }
        List<File> targetPathComponents = new ArrayList<File>();
        File aFile = targetFile.getParentFile();
        while (aFile != null) {
            targetPathComponents.add(0, aFile);
            aFile = aFile.getParentFile();
        }
        List<File> contextPathComponents = new ArrayList<File>();
        aFile = contextFile.getParentFile();
        while (aFile != null) {
            contextPathComponents.add(0, aFile);
            aFile = aFile.getParentFile();
        }
        // the two lists can have 0..n common elements (0 when the files
        // are
        // on separate roots
        int commonPathElements = 0;
        while (commonPathElements < targetPathComponents.size() && commonPathElements < contextPathComponents.size() && targetPathComponents.get(commonPathElements).equals(contextPathComponents.get(commonPathElements))) commonPathElements++;
        // construct the string for the relative URL
        String relativePath = "";
        for (int i = commonPathElements; i < contextPathComponents.size(); i++) {
            if (relativePath.length() == 0)
                relativePath += "..";
            else
                relativePath += "/..";
        }
        for (int i = commonPathElements; i < targetPathComponents.size(); i++) {
            String aDirName = targetPathComponents.get(i).getName();
            if (aDirName.length() == 0) {
                aDirName = targetPathComponents.get(i).getAbsolutePath();
                if (aDirName.endsWith(File.separator)) {
                    aDirName = aDirName.substring(0, aDirName.length() - File.separator.length());
                }
            }
            // targetPathComponents.get(i));
            if (relativePath.length() == 0) {
                relativePath += aDirName;
            } else {
                relativePath += "/" + aDirName;
            }
        }
        // we have the directory; add the file name
        if (relativePath.length() == 0) {
            relativePath += targetFile.getName();
        } else {
            relativePath += "/" + targetFile.getName();
        }
        if (target.toExternalForm().endsWith("/")) {
            // original target ended with a slash, so relative path should do too
            relativePath += "/";
        }
        try {
            URI relativeURI = new URI(null, null, relativePath, null, null);
            return relativeURI.getRawPath();
        } catch (URISyntaxException use) {
            throw new GateRuntimeException("Failed to generate relative path " + "between context: " + context + " and target: " + target, use);
        }
    } else {
        throw new GateRuntimeException("Both the target and the context URLs " + "need to be \"file:\" URLs!");
    }
}
Also used : GateRuntimeException(gate.util.GateRuntimeException) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) File(java.io.File) URI(java.net.URI)

Example 17 with GateRuntimeException

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

the class GappModel method buildRelpathsMap.

private void buildRelpathsMap(List<Element> relpathElements, Map<URL, List<Element>> relpathsMap) throws MalformedURLException {
    for (Element el : relpathElements) {
        String elementText = el.getText();
        URL targetURL = null;
        if (elementText.startsWith("$gatehome$")) {
            // complain if gateHomeURL not set
            if (gateHomeURL == null) {
                throw new GateRuntimeException("Found a $gatehome$ relative path in " + "GAPP file, but no GATE home URL provided to resolve against");
            }
            String relativePath = el.getText().substring("$gatehome$".length());
            targetURL = new URL(gateHomeURL, relativePath);
        } else if (elementText.startsWith("$resourceshome$")) {
            // complain if gateHomeURL not set
            if (gateHomeURL == null) {
                throw new GateRuntimeException("Found a $resourceshome$ relative path in " + "GAPP file, but no resources home URL provided to resolve against");
            }
            String relativePath = el.getText().substring("$resourceshome$".length());
            targetURL = new URL(resourcesHomeURL, relativePath);
        } else if (elementText.startsWith("$relpath$")) {
            String relativePath = el.getText().substring("$relpath$".length());
            targetURL = new URL(gappFileURL, relativePath);
        }
        List<Element> eltsForURL = relpathsMap.get(targetURL);
        if (eltsForURL == null) {
            eltsForURL = new ArrayList<Element>();
            relpathsMap.put(targetURL, eltsForURL);
        }
        eltsForURL.add(el);
    }
}
Also used : Element(org.jdom.Element) GateRuntimeException(gate.util.GateRuntimeException) URL(java.net.URL)

Example 18 with GateRuntimeException

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

the class SerialCorpusImpl method unloadDocument.

/**
 * Unloads a document from memory.
 *
 * @param index the index of the document to be unloaded.
 * @param sync should the document be sync'ed (i.e. saved) before
 *          unloading.
 */
public void unloadDocument(int index, boolean sync) {
    // if a persistent doc is not loaded, there's nothing we need to do
    if ((!isDocumentLoaded(index)) && isPersistentDocument(index))
        return;
    // any more
    if (sync) {
        Document doc = documents.get(index);
        try {
            // first
            if (doc.getLRPersistenceId() == null) {
                doc = (Document) this.getDataStore().adopt(doc);
                this.getDataStore().sync(doc);
                this.setDocumentPersistentID(index, doc.getLRPersistenceId());
            } else
                // if it is adopted, just sync it
                this.getDataStore().sync(doc);
        } catch (PersistenceException ex) {
            throw new GateRuntimeException("Error unloading document from corpus" + "because document sync failed: " + ex.getMessage(), ex);
        }
    }
    // 3. remove the document from the memory
    // do this, only if the saving has succeeded
    documents.set(index, null);
}
Also used : GateRuntimeException(gate.util.GateRuntimeException) PersistenceException(gate.persist.PersistenceException) Document(gate.Document)

Example 19 with GateRuntimeException

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

the class DocumentStaxUtils method toXml.

/**
 * Returns a string containing the specified document in GATE XML
 * format.
 *
 * @param doc the document
 */
public static String toXml(Document doc) {
    try {
        if (outputFactory == null) {
            outputFactory = XMLOutputFactory.newInstance();
        }
        StringWriter sw = new StringWriter(doc.getContent().size().intValue() * DocumentXmlUtils.DOC_SIZE_MULTIPLICATION_FACTOR);
        XMLStreamWriter xsw = outputFactory.createXMLStreamWriter(sw);
        // start the document
        if (doc instanceof TextualDocument) {
            xsw.writeStartDocument(((TextualDocument) doc).getEncoding(), "1.0");
        } else {
            xsw.writeStartDocument("1.0");
        }
        newLine(xsw);
        writeDocument(doc, xsw, "");
        xsw.close();
        return sw.toString();
    } catch (XMLStreamException xse) {
        throw new GateRuntimeException("Error converting document to XML", xse);
    }
}
Also used : StringWriter(java.io.StringWriter) XMLStreamException(javax.xml.stream.XMLStreamException) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) TextualDocument(gate.TextualDocument) GateRuntimeException(gate.util.GateRuntimeException)

Example 20 with GateRuntimeException

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

the class DocumentImpl method toXml.

/**
 * Returns an XML document aming to preserve the original markups( the
 * original markup will be in the same place and format as it was before
 * processing the document) and include (if possible) the annotations
 * specified in the aSourceAnnotationSet. <b>Warning:</b> Annotations from
 * the aSourceAnnotationSet will be lost if they will cause a crosed over
 * situation.
 *
 * @param aSourceAnnotationSet
 *          is an annotation set containing all the annotations that will be
 *          combined with the original marup set. If the param is
 *          <code>null</code> it will only dump the original markups.
 * @param includeFeatures
 *          is a boolean that controls whether the annotation features should
 *          be included or not. If false, only the annotation type is included
 *          in the tag.
 * @return a string representing an XML document containing the original
 *         markup + dumped annotations form the aSourceAnnotationSet
 */
@Override
@SuppressWarnings("unused")
public String toXml(Set<Annotation> aSourceAnnotationSet, boolean includeFeatures) {
    if (hasOriginalContentFeatures()) {
        return saveAnnotationSetAsXmlInOrig(aSourceAnnotationSet, // if
        includeFeatures);
    }
    AnnotationSet originalMarkupsAnnotSet = this.getAnnotations(GateConstants.ORIGINAL_MARKUPS_ANNOT_SET_NAME);
    // Create a dumping annotation set on the document. It will be used for
    // dumping annotations...
    // AnnotationSet dumpingSet = new AnnotationSetImpl((Document) this);
    List<Annotation> dumpingList = new ArrayList<Annotation>(originalMarkupsAnnotSet.size());
    // This set will be constructed inside this method. If is not empty, the
    // annotation contained will be lost.
    /*
     * if (!dumpingSet.isEmpty()){ Out.prln("WARNING: The dumping annotation set
     * was not empty."+ "All annotation it contained were lost.");
     * dumpingSet.clear(); }// End if
     */
    StatusListener sListener = (StatusListener) gate.Gate.getListeners().get("gate.event.StatusListener");
    // First add all annotation from the original markups
    if (sListener != null)
        sListener.statusChanged("Constructing the dumping annotation set.");
    // dumpingSet.addAll(originalMarkupsAnnotSet);
    dumpingList.addAll(originalMarkupsAnnotSet);
    // report.
    if (aSourceAnnotationSet != null) {
        Iterator<Annotation> iter = aSourceAnnotationSet.iterator();
        while (iter.hasNext()) {
            Annotation currentAnnot = iter.next();
            if (insertsSafety(dumpingList, currentAnnot)) {
                // dumpingSet.add(currentAnnot);
                dumpingList.add(currentAnnot);
            } else if (crossedOverAnnotation != null && DEBUG) {
                try {
                    Out.prln("Warning: Annotations were found to violate the " + "crossed over condition: \n" + "1. [" + getContent().getContent(crossedOverAnnotation.getStartNode().getOffset(), crossedOverAnnotation.getEndNode().getOffset()) + " (" + crossedOverAnnotation.getType() + ": " + crossedOverAnnotation.getStartNode().getOffset() + ";" + crossedOverAnnotation.getEndNode().getOffset() + ")]\n" + "2. [" + getContent().getContent(currentAnnot.getStartNode().getOffset(), currentAnnot.getEndNode().getOffset()) + " (" + currentAnnot.getType() + ": " + currentAnnot.getStartNode().getOffset() + ";" + currentAnnot.getEndNode().getOffset() + ")]\nThe second one will be discarded.\n");
                } catch (gate.util.InvalidOffsetException ex) {
                    throw new GateRuntimeException(ex.getMessage());
                }
            }
        // End if
        }
    // End while
    }
    // End if
    // kalina: order the dumping list by start offset
    Collections.sort(dumpingList, new gate.util.OffsetComparator());
    // Here we go.
    if (sListener != null)
        sListener.statusChanged("Dumping annotations as XML");
    StringBuffer xmlDoc = new StringBuffer(DocumentXmlUtils.DOC_SIZE_MULTIPLICATION_FACTOR * (this.getContent().size().intValue()));
    // Add xml header if original format was xml
    String mimeType = (String) getFeatures().get("MimeType");
    boolean wasXML = mimeType != null && mimeType.equalsIgnoreCase("text/xml");
    if (wasXML) {
        xmlDoc.append("<?xml version=\"1.0\" encoding=\"");
        xmlDoc.append(getEncoding());
        xmlDoc.append("\" ?>");
        xmlDoc.append(Strings.getNl());
    }
    // ENd if
    // Identify and extract the root annotation from the dumpingSet.
    theRootAnnotation = identifyTheRootAnnotation(dumpingList);
    // beginning of the document
    if (theRootAnnotation != null) {
        dumpingList.remove(theRootAnnotation);
        xmlDoc.append(writeStartTag(theRootAnnotation, includeFeatures));
    }
    // End if
    // Construct and append the rest of the document
    xmlDoc.append(saveAnnotationSetAsXml(dumpingList, includeFeatures));
    // end of the document
    if (theRootAnnotation != null) {
        xmlDoc.append(writeEndTag(theRootAnnotation));
    }
    // End if
    if (sListener != null)
        sListener.statusChanged("Done.");
    return xmlDoc.toString();
}
Also used : ArrayList(java.util.ArrayList) AnnotationSet(gate.AnnotationSet) InvalidOffsetException(gate.util.InvalidOffsetException) Annotation(gate.Annotation) GateRuntimeException(gate.util.GateRuntimeException) StatusListener(gate.event.StatusListener)

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