Updated copyright message.
[meviz.git] / src / main / java / eu / svjatoslav / meviz / encoder / EncodingTask.java
1 /*
2  * Meviz - Various tools collection to work with multimedia.
3  * Copyright (C) 2012 -- 2018, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of version 2 of the GNU General Public License
7  * as published by the Free Software Foundation.
8  */
9
10 package eu.svjatoslav.meviz.encoder;
11
12 import eu.svjatoslav.meviz.encoder.converters.AbstractConverter;
13
14 import java.io.File;
15
16 public class EncodingTask {
17
18     /**
19      * Source file to encode
20      */
21     private final File source;
22
23     /**
24      * Target file.
25      */
26     private final File target;
27
28     private final AbstractConverter converter;
29     private final String targetFormat;
30     private boolean useTerminal;
31
32     public EncodingTask(final File source, final File target, final AbstractConverter converter,
33                         final String targetFormat) {
34
35         this.source = source;
36         this.target = target;
37         this.converter = converter;
38         this.targetFormat = targetFormat;
39     }
40
41     /**
42      * @return the useTerminal
43      */
44     private boolean doUseTerminal() {
45         return useTerminal;
46     }
47
48     private String encodeApostrophes(final String input) {
49         final StringBuilder result = new StringBuilder();
50
51         for (final char c : input.toCharArray()) {
52             if (c == '\'') {
53                 result.append("'\\''");
54                 continue;
55             }
56             result.append(c);
57         }
58
59         return result.toString();
60     }
61
62     public void execute(final EncodingOptions encodingOptions) {
63         try {
64             String command = getCommand(encodingOptions);
65
66             if (doUseTerminal())
67                 command = "xterm -e '" + encodeApostrophes(command) + "'";
68
69             System.out.println("Executing command: " + command);
70
71             final Runtime runtime = Runtime.getRuntime();
72             final Process process = runtime.exec(new String[]{"/bin/bash", "-c", command});
73
74             process.waitFor();
75
76         } catch (final Exception e) {
77             System.out.println(e.toString());
78             e.printStackTrace();
79         }
80
81     }
82
83     private String getCommand(final EncodingOptions encodingOptions) {
84         return converter.getCommand(source, target, encodingOptions, targetFormat);
85     }
86
87     /**
88      * @param useTerminal the useTerminal to set
89      */
90     public void setUseTerminal(final boolean useTerminal) {
91         this.useTerminal = useTerminal;
92     }
93 }