Search in sources :

Example 6 with TranslationException

use of org.omegat.filters2.TranslationException in project omegat by omegat-org.

the class OpenXMLFilter method processFile.

/**
 * Processes a single OpenXML file, which is actually a ZIP file consisting of many XML files, some of
 * which should be translated.
 */
@Override
public void processFile(File inFile, File outFile, FilterContext fc) throws IOException, TranslationException {
    // Define the documents to read
    defineDOCUMENTSOptions(processOptions);
    ZipOutputStream zipout = null;
    try (ZipFile zipfile = new ZipFile(inFile)) {
        if (outFile != null) {
            zipout = new ZipOutputStream(new FileOutputStream(outFile));
        }
        Enumeration<? extends ZipEntry> unsortedZipcontents = zipfile.entries();
        List<? extends ZipEntry> filelist = Collections.list(unsortedZipcontents);
        // Sort filenames, because zipfile.entries give a random order
        // We use a simplified natural sort, to have slide1, slide2 ...
        // slide10
        // instead of slide1, slide10, slide 2
        // We also order files arbitrarily, to have, for instance
        // documents.xml before comments.xml
        Collections.sort(filelist, this::compareZipEntries);
        for (ZipEntry zipentry : filelist) {
            String shortname = removePath(zipentry.getName());
            if (translatable.matcher(shortname).matches()) {
                File tmpin = tmp();
                FileUtils.copyInputStreamToFile(zipfile.getInputStream(zipentry), tmpin);
                File tmpout = null;
                if (zipout != null) {
                    tmpout = tmp();
                }
                try {
                    createXMLFilter().processFile(tmpin, tmpout, fc);
                } catch (Exception e) {
                    LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
                    throw new TranslationException(e.getLocalizedMessage() + "\n" + OStrings.getString("OpenXML_ERROR_IN_FILE") + inFile, e);
                }
                if (zipout != null) {
                    ZipEntry outEntry = new ZipEntry(zipentry.getName());
                    zipout.putNextEntry(outEntry);
                    FileUtils.copyFile(tmpout, zipout);
                    zipout.closeEntry();
                }
                if (!tmpin.delete()) {
                    tmpin.deleteOnExit();
                }
                if (tmpout != null && !tmpout.delete()) {
                    tmpout.deleteOnExit();
                }
            } else {
                if (zipout != null) {
                    ZipEntry outEntry = new ZipEntry(zipentry.getName());
                    zipout.putNextEntry(outEntry);
                    try (InputStream is = zipfile.getInputStream(zipentry)) {
                        IOUtils.copy(is, zipout);
                    }
                    zipout.closeEntry();
                }
            }
        }
    } finally {
        if (zipout != null) {
            zipout.close();
        }
    }
}
Also used : ZipFile(java.util.zip.ZipFile) ZipOutputStream(java.util.zip.ZipOutputStream) InputStream(java.io.InputStream) FileOutputStream(java.io.FileOutputStream) ZipEntry(java.util.zip.ZipEntry) TranslationException(org.omegat.filters2.TranslationException) ZipFile(java.util.zip.ZipFile) File(java.io.File) TranslationException(org.omegat.filters2.TranslationException) IOException(java.io.IOException)

Example 7 with TranslationException

use of org.omegat.filters2.TranslationException in project omegat by omegat-org.

the class Searcher method searchFiles.

private void searchFiles() throws Exception {
    Path root = Paths.get(expression.rootDir);
    FilterMaster fm = Core.getFilterMaster();
    final SearchCallback searchCallback = new SearchCallback(m_project.getProjectProperties());
    int depth = expression.recursive ? Integer.MAX_VALUE : 0;
    Files.walk(root, depth, FileVisitOption.FOLLOW_LINKS).forEach(path -> {
        String filename = path.toString();
        FileInfo fi = new FileInfo();
        // determine actual file name w/ no root path info
        fi.filePath = root.relativize(path).toString();
        searchCallback.setCurrentFile(fi);
        try {
            fm.loadFile(filename, new FilterContext(m_project.getProjectProperties()), searchCallback);
        } catch (TranslationException | IOException ex) {
            Log.log(ex);
        }
        searchCallback.fileFinished();
        checkStop.checkInterrupted();
    });
}
Also used : Path(java.nio.file.Path) FileInfo(org.omegat.core.data.IProject.FileInfo) FilterMaster(org.omegat.filters2.master.FilterMaster) TranslationException(org.omegat.filters2.TranslationException) IOException(java.io.IOException) FilterContext(org.omegat.filters2.FilterContext)

Example 8 with TranslationException

use of org.omegat.filters2.TranslationException in project omegat by omegat-org.

the class PdfFilterTest method testPasswordProtected.

@Test
public void testPasswordProtected() throws Exception {
    String f = "test/data/filters/pdf/file-PdfFilter-password.pdf";
    try {
        loadSourceFiles(new PdfFilter(), f);
        fail("Password-protected PDFs are not supported");
    } catch (TranslationException ex) {
    // OK
    }
}
Also used : TranslationException(org.omegat.filters2.TranslationException) PdfFilter(org.omegat.filters2.pdf.PdfFilter) Test(org.junit.Test)

Example 9 with TranslationException

use of org.omegat.filters2.TranslationException in project omegat by omegat-org.

the class PreferencesXML method load.

/**
 * Loads the preferences from disk, from the specified file or, if the
 * file is null, it attempts to load from a prefs file bundled inside
 * the JAR (not supplied by default).
 */
@Override
public void load(List<String> keys, List<String> values) {
    try (XMLStreamReader xml = new XMLStreamReader()) {
        xml.killEmptyBlocks();
        if (loadFile == null) {
            // defaults. Useful for e.g. Web Start.
            try (InputStream is = getClass().getResourceAsStream(Preferences.FILE_PREFERENCES)) {
                if (is != null) {
                    xml.setStream(is);
                    readXmlPrefs(xml, keys, values);
                }
            }
        } else {
            xml.setStream(loadFile);
            readXmlPrefs(xml, keys, values);
        }
    } catch (TranslationException te) {
        // error loading preference file - keep whatever was
        // loaded then return gracefully to calling function
        // print an error to the console as an FYI
        Log.logWarningRB("PM_WARNING_PARSEERROR_ON_READ");
        Log.log(te);
        makeBackup(loadFile);
    } catch (IndexOutOfBoundsException e3) {
        // error loading preference file - keep whatever was
        // loaded then return gracefully to calling function
        // print an error to the console as an FYI
        Log.logWarningRB("PM_WARNING_PARSEERROR_ON_READ");
        Log.log(e3);
        makeBackup(loadFile);
    } catch (UnsupportedEncodingException e3) {
        // unsupported encoding - forget about it
        Log.logErrorRB(e3, "PM_UNSUPPORTED_ENCODING");
        makeBackup(loadFile);
    } catch (IOException e4) {
        // can't read file - forget about it and move on
        Log.logErrorRB(e4, "PM_ERROR_READING_FILE");
        makeBackup(loadFile);
    }
}
Also used : XMLStreamReader(org.omegat.util.xml.XMLStreamReader) InputStream(java.io.InputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TranslationException(org.omegat.filters2.TranslationException) IOException(java.io.IOException)

Example 10 with TranslationException

use of org.omegat.filters2.TranslationException in project omegat by omegat-org.

the class ProjectFileStorage method loadPropertiesFile.

static ProjectProperties loadPropertiesFile(File projectDir, Omegat om) throws Exception {
    if (!projectDir.isDirectory()) {
        throw new IllegalArgumentException("Project directory was not a directory");
    }
    ProjectProperties result = new ProjectProperties(projectDir);
    if (!OConsts.PROJ_CUR_VERSION.equals(om.getProject().getVersion())) {
        throw new TranslationException(StringUtil.format(OStrings.getString("PFR_ERROR_UNSUPPORTED_PROJECT_VERSION"), om.getProject().getVersion()));
    }
    result.setTargetRoot(normalizeLoadedPath(om.getProject().getTargetDir(), OConsts.DEFAULT_TARGET));
    result.setSourceRoot(normalizeLoadedPath(om.getProject().getSourceDir(), OConsts.DEFAULT_SOURCE));
    result.getSourceRootExcludes().clear();
    if (om.getProject().getSourceDirExcludes() != null) {
        result.getSourceRootExcludes().addAll(om.getProject().getSourceDirExcludes().getMask());
    } else {
        // sourceRootExclude was not defined
        result.getSourceRootExcludes().addAll(ProjectProperties.getDefaultExcludes());
    }
    result.setTMRoot(normalizeLoadedPath(om.getProject().getTmDir(), OConsts.DEFAULT_TM));
    result.setGlossaryRoot(normalizeLoadedPath(om.getProject().getGlossaryDir(), OConsts.DEFAULT_GLOSSARY));
    // Compute glossary file location
    String glossaryFile = om.getProject().getGlossaryFile();
    if (StringUtil.isEmpty(glossaryFile)) {
        glossaryFile = DEFAULT_FOLDER_MARKER;
    }
    if (glossaryFile.equalsIgnoreCase(DEFAULT_FOLDER_MARKER)) {
        glossaryFile = result.computeDefaultWriteableGlossaryFile();
    } else {
        glossaryFile = result.getGlossaryDir().getAsString() + glossaryFile;
    }
    result.setWriteableGlossary(glossaryFile);
    result.setDictRoot(normalizeLoadedPath(om.getProject().getDictionaryDir(), OConsts.DEFAULT_DICT));
    result.setSourceLanguage(om.getProject().getSourceLang());
    result.setTargetLanguage(om.getProject().getTargetLang());
    result.setSourceTokenizer(loadTokenizer(om.getProject().getSourceTok(), result.getSourceLanguage()));
    result.setTargetTokenizer(loadTokenizer(om.getProject().getTargetTok(), result.getTargetLanguage()));
    if (om.getProject().isSentenceSeg() != null) {
        result.setSentenceSegmentingEnabled(om.getProject().isSentenceSeg());
    }
    if (om.getProject().isSupportDefaultTranslations() != null) {
        result.setSupportDefaultTranslations(om.getProject().isSupportDefaultTranslations());
    }
    if (om.getProject().isRemoveTags() != null) {
        result.setRemoveTags(om.getProject().isRemoveTags());
    }
    if (om.getProject().getExternalCommand() != null) {
        result.setExternalCommand(om.getProject().getExternalCommand());
    }
    if (om.getProject().getRepositories() != null) {
        result.setRepositories(om.getProject().getRepositories().getRepository());
    }
    return result;
}
Also used : TranslationException(org.omegat.filters2.TranslationException) ProjectProperties(org.omegat.core.data.ProjectProperties)

Aggregations

TranslationException (org.omegat.filters2.TranslationException)16 IOException (java.io.IOException)7 File (java.io.File)6 Test (org.junit.Test)4 IFilter (org.omegat.filters2.IFilter)3 BufferedReader (java.io.BufferedReader)2 FileOutputStream (java.io.FileOutputStream)2 InputStream (java.io.InputStream)2 ZipEntry (java.util.zip.ZipEntry)2 ZipFile (java.util.zip.ZipFile)2 ZipOutputStream (java.util.zip.ZipOutputStream)2 XMLStreamReader (org.omegat.util.xml.XMLStreamReader)2 SAXException (org.xml.sax.SAXException)2 Files (gen.core.filters.Files)1 Filter (gen.core.filters.Filter)1 StringReader (java.io.StringReader)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 Path (java.nio.file.Path)1 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)1 SAXParser (javax.xml.parsers.SAXParser)1