Search in sources :

Example 1 with JseInputStream

use of com.xenoage.utils.jse.io.JseInputStream in project Zong by Xenoage.

the class MusicXmlMassTest method testFile.

// */
private boolean testFile(File file) {
    try {
        // Load the file
        // TIDY
        ScoreDocFactory.setErrorLayoutEnabled(false);
        ScoreDoc score = new MusicXmlScoreDocFileInput().read(new JseInputStream(file), file.getAbsolutePath());
        // TIDY
        ScoreDocFactory.setErrorLayoutEnabled(true);
        // Check layout of loaded file
        if (checkLayout) {
            checkLayout(score, file.getName());
        }
        // Save it as MusicXML
        File mxlSavedFile = getTempOutputPath(file, "-saved.mxl");
        if (saveAsMxl) {
        // new MusicXMLScoreDocFileOutput().write(score, new FileOutputStream(mxlSavedFile), mxlSavedFile);
        }
        // Save it as PDF
        if (saveAsPdf) {
            File pdfFile = getTempOutputPath(file, ".pdf");
            new PdfScoreDocFileOutput().write(score, 0, new JseOutputStream(pdfFile));
        }
        // Save it as MIDI
        if (saveAsMid) {
            File midFile = getTempOutputPath(file, ".mid");
            new MidiScoreDocFileOutput().write(score, 0, new JseOutputStream(midFile));
        }
        // Load it from saved MusicXML
        if (loadFromSavedMxl) {
        // TODO
        }
        // Success
        System.out.print("OK:   " + file.toString().substring(dir.length()) + " (" + score.getScore().getInfo().getTitle() + ")");
        @SuppressWarnings("unchecked") List<String> errorMessages = (List<String>) score.getScore().getMetaData().get("mxlerrors");
        if (errorMessages != null)
            System.out.print("  ! " + errorMessages.size() + " warning(s)");
        System.out.println();
        return true;
    } catch (Throwable ex) {
        ex.printStackTrace();
        // fail("Failed to load file: " + file);
        System.out.println("fail: " + file.toString().substring(dir.length()));
        return false;
    }
}
Also used : MusicXmlScoreDocFileInput(com.xenoage.zong.desktop.io.musicxml.in.MusicXmlScoreDocFileInput) JseInputStream(com.xenoage.utils.jse.io.JseInputStream) JseOutputStream(com.xenoage.utils.jse.io.JseOutputStream) PdfScoreDocFileOutput(com.xenoage.zong.desktop.io.pdf.out.PdfScoreDocFileOutput) List(java.util.List) MidiScoreDocFileOutput(com.xenoage.zong.desktop.io.midi.out.MidiScoreDocFileOutput) File(java.io.File) ScoreDoc(com.xenoage.zong.documents.ScoreDoc)

Example 2 with JseInputStream

use of com.xenoage.utils.jse.io.JseInputStream in project Zong by Xenoage.

the class LanguageReader method read.

/**
 * Creates a {@link Language} from all .xml and .po files in the folder <code>basePath/id</code>.
 * If the language pack can not be loaded, an {@link IOException} is thrown.
 * @param path  path to the language pack directory (without trailing slash)
 * @param id    id of the language pack
 */
public static Language read(String basePath, String id) throws IOException {
    log(remark("Loading language pack \"" + id + "\" from folder \"" + basePath + "\"..."));
    // check if language exists
    String dir = basePath + "/" + id;
    if (false == io().existsFile(dir + "/id.xml"))
        throw new FileNotFoundException("Language " + id + " does not exist");
    // locate vocabulary files
    List<String> langFiles = io().listFiles(dir, orFilter(xmlFilter, poFilter));
    langFiles.remove("id.xml");
    // load entries
    HashMap<String, String> entries = map();
    int entriesCount = 0;
    int entriesOverwrittenCount = 0;
    for (String langFileName : langFiles) {
        JseInputStream langStream = io().openFile(dir + "/" + langFileName);
        // read XML or PO file
        HashMap<String, String> fileEntries = null;
        if (langFileName.endsWith(".po")) {
            log(remark("Reading PO language file \"" + langFileName + "\""));
            fileEntries = readPO(langStream);
        } else {
            log(remark("Reading XML language file \"" + langFileName + "\""));
            fileEntries = readXML(langStream);
        }
        // insert vocabulary data
        for (Entry<String, String> fileEntry : fileEntries.entrySet()) {
            String oldValue = entries.put(fileEntry.getKey(), fileEntry.getValue());
            if (oldValue == null)
                entriesCount++;
            else {
                log(warning("Overwritten entry: " + fileEntry.getKey()));
                entriesOverwrittenCount++;
            }
        }
    }
    log(remark("Language pack loaded. Entries: " + entriesCount + ". Overwritten entries: " + entriesOverwrittenCount));
    // replace all tokens
    for (String key : entries.keySet()) {
        String value = entries.get(key);
        if (value.contains("{")) {
            entries.put(key, replaceTokens(value, entries));
        }
    }
    return new Language(id, entries);
}
Also used : Language(com.xenoage.utils.lang.Language) JseInputStream(com.xenoage.utils.jse.io.JseInputStream) FileNotFoundException(java.io.FileNotFoundException)

Example 3 with JseInputStream

use of com.xenoage.utils.jse.io.JseInputStream in project Zong by Xenoage.

the class Converter method convert.

public static void convert(String... args) throws IOException {
    // exception for wrong format
    if (args.length < 4 || !args[0].equals("--convert")) {
        System.out.println("Wrong usage of parameters.");
        showHelp();
        return;
    }
    // second argument: input file
    File inputFile = new File(args[1]);
    if (!inputFile.exists()) {
        System.out.println("Input file could not be found at");
        System.out.println(inputFile.getAbsolutePath());
        return;
    }
    // third argument: output file
    File outputFile = new File(args[2]);
    // fourth argument: output format
    String formatId = args[3].toLowerCase();
    FileFormat<ScoreDoc> format = null;
    try {
        format = supportedFormats.getByID(formatId);
    } catch (IllegalArgumentException ex) {
    }
    if (format == null || format.getOutput() == null) {
        System.out.println("Can not save files in format " + formatId);
        System.out.println("Supported formats are:");
        showFormats();
        return;
    }
    // create output dir, if needed
    outputFile.getParentFile().mkdirs();
    // do the conversion
    FileInput<ScoreDoc> input = supportedFormats.getReadDefaultFormat().getInput();
    ScoreDoc doc = input.read(new JseInputStream(new FileInputStream(inputFile)), inputFile.getAbsolutePath());
    // TIDY
    doc.getLayout().updateScoreLayouts(doc.getScore());
    DocumentIO.write(doc, outputFile, format.getOutput());
}
Also used : JseInputStream(com.xenoage.utils.jse.io.JseInputStream) File(java.io.File) FileInputStream(java.io.FileInputStream) ScoreDoc(com.xenoage.zong.documents.ScoreDoc)

Example 4 with JseInputStream

use of com.xenoage.utils.jse.io.JseInputStream in project Zong by Xenoage.

the class DirToMidiConvert method execute.

@Override
public void execute() {
    DirectoryChooser dc = new DirectoryChooser();
    // use last document directory
    File initDir = FileSettings.getLastDir();
    if (initDir != null)
        dc.setInitialDirectory(initDir);
    /* TODO - how to extend the DirectoryChooser in JavaFX?
		//see http://stackoverflow.com/questions/25982945/javafx-filechooser-and-directorychooser-accessory-component
		JCheckBox chkSubdir = new JCheckBox(Lang.get(Voc.IncludeSubdirectories), true);
		JCheckBox chkCancel = new JCheckBox(Lang.get(Voc.CancelAtFirstError), false);
		JPanel pnlOptions = new JPanel();
		pnlOptions.setLayout(new BoxLayout(pnlOptions, BoxLayout.Y_AXIS));
		pnlOptions.add(chkSubdir);
		pnlOptions.add(chkCancel);
		fc.setAccessory(pnlOptions); */
    // TODO
    boolean subDirs = true;
    // TODO
    boolean cancelOnFirstError = false;
    File dir = dc.showDialog(ownerWindow);
    if (dir != null) {
        // remember directory
        FileSettings.rememberDir(dir);
        // start conversion - TODO: show progress
        List<File> files = listFiles(dir, subDirs);
        int countOK = 0;
        int countFailed = 0;
        for (File file : files) {
            try {
                // only process MusicXML files
                FileType fileType = FileTypeReader.getFileType(new JseInputStream(file));
                if (fileType != null) {
                    String filePath = file.getAbsolutePath();
                    List<Score> scores = pApp().loadMxlScores(filePath, new AllFilter<>());
                    if ((scores.size() == 0)) /* TODO && chkCancel.isSelected() */
                    {
                        countFailed++;
                        break;
                    }
                    boolean useNumber = scores.size() > 1;
                    It<Score> scoresIt = new It<>(scores);
                    for (Score score : scoresIt) {
                        Sequence seq = MidiConverter.convertToSequence(score, optionsForFileExport, new JseMidiSequenceWriter()).getSequence();
                        String number = (useNumber ? ("-" + (scoresIt.getIndex() + 1)) : "");
                        String newPath = filePath;
                        if (filePath.toLowerCase().endsWith(".xml") || filePath.toLowerCase().endsWith(".mxl")) {
                            newPath = newPath.substring(0, filePath.length() - 4);
                        }
                        newPath += (number + ".mid");
                        MidiSystem.write(seq, 1, new File(newPath));
                        countOK++;
                    }
                }
            } catch (IOException ex) {
                countFailed++;
                if (cancelOnFirstError) {
                    break;
                }
            }
        }
        app().showMessageDialog(Lang.get(Voc.DirectoryConversionResult, "" + countOK, "" + countFailed));
    }
}
Also used : It(com.xenoage.utils.iterators.It) Sequence(javax.sound.midi.Sequence) IOException(java.io.IOException) Score(com.xenoage.zong.core.Score) FileType(com.xenoage.zong.io.musicxml.FileType) JseInputStream(com.xenoage.utils.jse.io.JseInputStream) JseMidiSequenceWriter(com.xenoage.zong.desktop.io.midi.out.JseMidiSequenceWriter) File(java.io.File) DirectoryChooser(javafx.stage.DirectoryChooser)

Example 5 with JseInputStream

use of com.xenoage.utils.jse.io.JseInputStream in project Zong by Xenoage.

the class OpenAction method loadDocument.

/**
 * Loads the {@link Doc} at the given URL and stores information about
 * the score in the database, if it is not already present.
 */
public Tuple2<ScoreDoc, Doc> loadDocument(String url, @MaybeNull UUID publicID) throws SQLException {
    Connection db = Webserver.instance.getDBConnection();
    ScoreDoc scoreDoc;
    // public ID of the document
    if (publicID == null)
        publicID = UUID.randomUUID();
    // may not exist yet
    PreparedStatement stmt = stmt(db, "SELECT public_id FROM docs WHERE public_id = ?", publicID);
    ResultSet res = stmt.executeQuery();
    boolean error = res.next();
    stmt.close();
    if (error)
        throw new SQLException("A document with this public ID already exists");
    // load MusicXML document
    try {
        // open local or remote file
        InputStream inputStream;
        if (URLUtils.isAbsoluteURL(url)) {
            inputStream = new URL(url).openStream();
        } else {
            inputStream = new FileInputStream(Webserver.webPath + url);
        }
        MusicXmlScoreDocFileInput in = new MusicXmlScoreDocFileInput();
        scoreDoc = in.read(new JseInputStream(inputStream), null);
    } catch (FileNotFoundException ex) {
        throw new RuntimeException("file not found");
    } catch (MalformedURLException ex) {
        throw new RuntimeException("invalid URL: " + url);
    } catch (IOException ex) {
        throw new RuntimeException("can not read from URL: " + url);
    }
    // register file in database, if not already known
    Layout layout = scoreDoc.getLayout();
    boolean isDocKnown = Database.exists(db, "docs", "url = ?", "" + url);
    if (!isDocKnown) {
        Database.insert(db, "docs", "url, public_id, pages, last_access", "" + url, "" + publicID, layout.getPages().size(), unixTime());
    }
    // read information about the document
    Doc doc = Doc.fromDB(db, "" + url);
    // for new documents: save information
    if (!isDocKnown) {
        // page information
        for (int iPage : range(layout.getPages())) {
            Size2f pageSize = layout.getPages().get(iPage).getFormat().getSize();
            new Page(doc.id, iPage, pageSize.width, pageSize.height).insertIntoDB(db);
        }
    }
    return t(scoreDoc, doc);
}
Also used : MusicXmlScoreDocFileInput(com.xenoage.zong.desktop.io.musicxml.in.MusicXmlScoreDocFileInput) MalformedURLException(java.net.MalformedURLException) SQLException(java.sql.SQLException) JseInputStream(com.xenoage.utils.jse.io.JseInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Connection(java.sql.Connection) FileNotFoundException(java.io.FileNotFoundException) PreparedStatement(java.sql.PreparedStatement) Page(com.xenoage.zong.webserver.model.Page) ScaledPage(com.xenoage.zong.webserver.model.ScaledPage) IOException(java.io.IOException) URL(java.net.URL) FileInputStream(java.io.FileInputStream) ScoreDoc(com.xenoage.zong.documents.ScoreDoc) JseInputStream(com.xenoage.utils.jse.io.JseInputStream) Layout(com.xenoage.zong.layout.Layout) Size2f(com.xenoage.utils.math.geom.Size2f) ResultSet(java.sql.ResultSet) Doc(com.xenoage.zong.webserver.model.Doc) ScoreDoc(com.xenoage.zong.documents.ScoreDoc)

Aggregations

JseInputStream (com.xenoage.utils.jse.io.JseInputStream)5 ScoreDoc (com.xenoage.zong.documents.ScoreDoc)3 File (java.io.File)3 MusicXmlScoreDocFileInput (com.xenoage.zong.desktop.io.musicxml.in.MusicXmlScoreDocFileInput)2 FileInputStream (java.io.FileInputStream)2 FileNotFoundException (java.io.FileNotFoundException)2 IOException (java.io.IOException)2 It (com.xenoage.utils.iterators.It)1 JseOutputStream (com.xenoage.utils.jse.io.JseOutputStream)1 Language (com.xenoage.utils.lang.Language)1 Size2f (com.xenoage.utils.math.geom.Size2f)1 Score (com.xenoage.zong.core.Score)1 JseMidiSequenceWriter (com.xenoage.zong.desktop.io.midi.out.JseMidiSequenceWriter)1 MidiScoreDocFileOutput (com.xenoage.zong.desktop.io.midi.out.MidiScoreDocFileOutput)1 PdfScoreDocFileOutput (com.xenoage.zong.desktop.io.pdf.out.PdfScoreDocFileOutput)1 FileType (com.xenoage.zong.io.musicxml.FileType)1 Layout (com.xenoage.zong.layout.Layout)1 Doc (com.xenoage.zong.webserver.model.Doc)1 Page (com.xenoage.zong.webserver.model.Page)1 ScaledPage (com.xenoage.zong.webserver.model.ScaledPage)1