Révision 2406

tmp/org.txm.jodconverter.core/src/test/java/org/artofsolving/jodconverter/OfficeDocumentConverterFunctionalTest.java (revision 2406)
27 27
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
28 28
import org.testng.annotations.Test;
29 29

  
30
@Test(groups="functional")
30
@Test(groups = "functional")
31 31
public class OfficeDocumentConverterFunctionalTest {
32

  
33
    public void runAllPossibleConversions() throws IOException {
34
        OfficeManager officeManager = new DefaultOfficeManagerConfiguration().buildOfficeManager();
35
        OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
36
        DocumentFormatRegistry formatRegistry = converter.getFormatRegistry();
37
        
38
        officeManager.start();
39
        try {
40
            File dir = new File("src/test/resources/documents");
41
            File[] files = dir.listFiles(new FilenameFilter() {
42
            	public boolean accept(File dir, String name) {
43
            		return !name.startsWith(".");
44
            	}
45
            });
32
	
33
	public void runAllPossibleConversions() throws IOException {
34
		OfficeManager officeManager = new DefaultOfficeManagerConfiguration().buildOfficeManager();
35
		OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
36
		DocumentFormatRegistry formatRegistry = converter.getFormatRegistry();
37
		
38
		officeManager.start();
39
		try {
40
			File dir = new File("src/test/resources/documents");
41
			File[] files = dir.listFiles(new FilenameFilter() {
42
				
43
				public boolean accept(File dir, String name) {
44
					return !name.startsWith(".");
45
				}
46
			});
46 47
			for (File inputFile : files) {
47
                String inputExtension = FilenameUtils.getExtension(inputFile.getName());
48
                DocumentFormat inputFormat = formatRegistry.getFormatByExtension(inputExtension);
49
                assertNotNull(inputFormat, "unknown input format: " + inputExtension);
50
                Set<DocumentFormat> outputFormats = formatRegistry.getOutputFormats(inputFormat.getInputFamily());
51
                for (DocumentFormat outputFormat : outputFormats) {
52
                    File outputFile = File.createTempFile("test", "." + outputFormat.getExtension());
53
                    outputFile.deleteOnExit();
54
                    System.out.printf("-- converting %s to %s... ", inputFormat.getExtension(), outputFormat.getExtension());
55
                    converter.convert(inputFile, outputFile, outputFormat);
56
                    System.out.printf("done.\n");
57
                    assertTrue(outputFile.isFile() && outputFile.length() > 0);
58
                    //TODO use file detection to make sure outputFile is in the expected format
59
                }
60
            }
61
        } finally {
62
            officeManager.stop();
63
        }
64
    }
65

  
48
				String inputExtension = FilenameUtils.getExtension(inputFile.getName());
49
				DocumentFormat inputFormat = formatRegistry.getFormatByExtension(inputExtension);
50
				assertNotNull(inputFormat, "unknown input format: " + inputExtension);
51
				Set<DocumentFormat> outputFormats = formatRegistry.getOutputFormats(inputFormat.getInputFamily());
52
				for (DocumentFormat outputFormat : outputFormats) {
53
					File outputFile = File.createTempFile("test", "." + outputFormat.getExtension());
54
					outputFile.deleteOnExit();
55
					System.out.printf("-- converting %s to %s... ", inputFormat.getExtension(), outputFormat.getExtension());
56
					converter.convert(inputFile, outputFile, outputFormat);
57
					System.out.printf("done.\n");
58
					assertTrue(outputFile.isFile() && outputFile.length() > 0);
59
					// TODO use file detection to make sure outputFile is in the expected format
60
				}
61
			}
62
		}
63
		finally {
64
			officeManager.stop();
65
		}
66
	}
67
	
66 68
}
tmp/org.txm.jodconverter.core/src/test/java/org/artofsolving/jodconverter/ReflectionUtils.java (revision 2406)
15 15
import java.lang.reflect.Field;
16 16

  
17 17
public class ReflectionUtils {
18

  
19
    private ReflectionUtils() {
20
        throw new AssertionError("utility class must not be instantiated");
21
    }
22

  
23
    public static Object getPrivateField(Object instance, String fieldName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
24
        return getPrivateField(instance.getClass(), instance, fieldName);
25
    }
26

  
27
    public static Object getPrivateField(Class<?> type, Object instance, String fieldName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
28
        Field field = type.getDeclaredField(fieldName);
29
        field.setAccessible(true);
30
        return field.get(instance);
31
    }
32

  
18
	
19
	private ReflectionUtils() {
20
		throw new AssertionError("utility class must not be instantiated");
21
	}
22
	
23
	public static Object getPrivateField(Object instance, String fieldName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
24
		return getPrivateField(instance.getClass(), instance, fieldName);
25
	}
26
	
27
	public static Object getPrivateField(Class<?> type, Object instance, String fieldName) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
28
		Field field = type.getDeclaredField(fieldName);
29
		field.setAccessible(true);
30
		return field.get(instance);
31
	}
32
	
33 33
}
tmp/org.txm.jodconverter.core/src/test/java/org/artofsolving/jodconverter/office/MockOfficeTask.java (revision 2406)
24 24
import com.sun.star.util.XCloseable;
25 25

  
26 26
public class MockOfficeTask implements OfficeTask {
27

  
28
    private long delayTime = 0L;
29

  
30
    private boolean completed = false;
31

  
32
    public MockOfficeTask() {
33
        // default
34
    }
35

  
36
    public MockOfficeTask(long delayTime) {
37
        this.delayTime = delayTime;
38
    }
39

  
40
    public void execute(OfficeContext context) throws OfficeException {
41
        XComponentLoader loader = cast(XComponentLoader.class, context.getService(SERVICE_DESKTOP));
42
        assert loader != null : "desktop object is null";
43
        try {
44
            PropertyValue[] arguments = new PropertyValue[] { property("Hidden", true) };
45
            XComponent document = loader.loadComponentFromURL("private:factory/swriter", "_blank", 0, arguments);
46
            if (delayTime > 0) {
47
                Thread.sleep(delayTime);
48
            }
49
            cast(XCloseable.class, document).close(true);
50
            completed = true;
51
        } catch (Exception exception) {
52
            throw new OfficeException("failed to create document", exception);
53
        }
54
    }
55

  
56
    public boolean isCompleted() {
57
        return completed;
58
    }
59

  
27
	
28
	private long delayTime = 0L;
29
	
30
	private boolean completed = false;
31
	
32
	public MockOfficeTask() {
33
		// default
34
	}
35
	
36
	public MockOfficeTask(long delayTime) {
37
		this.delayTime = delayTime;
38
	}
39
	
40
	public void execute(OfficeContext context) throws OfficeException {
41
		XComponentLoader loader = cast(XComponentLoader.class, context.getService(SERVICE_DESKTOP));
42
		assert loader != null : "desktop object is null";
43
		try {
44
			PropertyValue[] arguments = new PropertyValue[] { property("Hidden", true) };
45
			XComponent document = loader.loadComponentFromURL("private:factory/swriter", "_blank", 0, arguments);
46
			if (delayTime > 0) {
47
				Thread.sleep(delayTime);
48
			}
49
			cast(XCloseable.class, document).close(true);
50
			completed = true;
51
		}
52
		catch (Exception exception) {
53
			throw new OfficeException("failed to create document", exception);
54
		}
55
	}
56
	
57
	public boolean isCompleted() {
58
		return completed;
59
	}
60
	
60 61
}
tmp/org.txm.jodconverter.core/src/test/java/org/artofsolving/jodconverter/office/ExternalOfficeManagerTest.java (revision 2406)
20 20
import org.artofsolving.jodconverter.process.PureJavaProcessManager;
21 21
import org.testng.annotations.Test;
22 22

  
23
@Test(groups="integration")
23
@Test(groups = "integration")
24 24
public class ExternalOfficeManagerTest {
25

  
26
    public void executeTask() throws Exception {
27
        UnoUrl unoUrl = UnoUrl.socket(2002);
28
        OfficeProcess officeProcess = new OfficeProcess(OfficeUtils.getDefaultOfficeHome(), unoUrl,
29
            null, null, new File(System.getProperty("java.io.tmpdir")), new PureJavaProcessManager());
30
        officeProcess.start();
31
        Thread.sleep(2000);
32
        Integer exitCode = officeProcess.getExitCode();
33
        if (exitCode != null && exitCode.equals(Integer.valueOf(81))) {
34
            officeProcess.start(true);
35
            Thread.sleep(2000);
36
        }
37
        
38
        ExternalOfficeManager manager = new ExternalOfficeManager(unoUrl, true);
39
        manager.start();
40
        
41
        MockOfficeTask task = new MockOfficeTask();
42
        manager.execute(task);
43
        assertTrue(task.isCompleted());
44
        
45
        manager.stop();
46
        //TODO replace when OfficeProcess has a forciblyTerminate()
47
        Process process = (Process) ReflectionUtils.getPrivateField(officeProcess, "process");
48
        process.destroy();
49
    }
50

  
51
    //TODO test auto-reconnection
52

  
25
	
26
	public void executeTask() throws Exception {
27
		UnoUrl unoUrl = UnoUrl.socket(2002);
28
		OfficeProcess officeProcess = new OfficeProcess(OfficeUtils.getDefaultOfficeHome(), unoUrl,
29
				null, null, new File(System.getProperty("java.io.tmpdir")), new PureJavaProcessManager());
30
		officeProcess.start();
31
		Thread.sleep(2000);
32
		Integer exitCode = officeProcess.getExitCode();
33
		if (exitCode != null && exitCode.equals(Integer.valueOf(81))) {
34
			officeProcess.start(true);
35
			Thread.sleep(2000);
36
		}
37
		
38
		ExternalOfficeManager manager = new ExternalOfficeManager(unoUrl, true);
39
		manager.start();
40
		
41
		MockOfficeTask task = new MockOfficeTask();
42
		manager.execute(task);
43
		assertTrue(task.isCompleted());
44
		
45
		manager.stop();
46
		// TODO replace when OfficeProcess has a forciblyTerminate()
47
		Process process = (Process) ReflectionUtils.getPrivateField(officeProcess, "process");
48
		process.destroy();
49
	}
50
	
51
	// TODO test auto-reconnection
52
	
53 53
}
tmp/org.txm.jodconverter.core/src/test/java/org/artofsolving/jodconverter/office/PooledOfficeManagerTest.java (revision 2406)
21 21
import java.util.concurrent.CancellationException;
22 22
import java.util.concurrent.TimeoutException;
23 23

  
24

  
25 24
import org.artofsolving.jodconverter.ReflectionUtils;
26 25
import org.artofsolving.jodconverter.office.ManagedOfficeProcess;
27 26
import org.artofsolving.jodconverter.office.PooledOfficeManager;
......
32 31
import org.artofsolving.jodconverter.office.OfficeProcess;
33 32
import org.testng.annotations.Test;
34 33

  
35
@Test(groups="integration")
34
@Test(groups = "integration")
36 35
public class PooledOfficeManagerTest {
37

  
38
    private static final UnoUrl CONNECTION_MODE = UnoUrl.socket(2002);
39
    private static final long RESTART_WAIT_TIME = 2 * 1000;
40

  
41
    public void executeTask() throws Exception {
42
        PooledOfficeManager officeManager = new PooledOfficeManager(CONNECTION_MODE);
43
        ManagedOfficeProcess managedOfficeProcess = (ManagedOfficeProcess) ReflectionUtils.getPrivateField(officeManager, "managedOfficeProcess");
44
        OfficeProcess process = (OfficeProcess) ReflectionUtils.getPrivateField(managedOfficeProcess, "process");
45
        OfficeConnection connection = (OfficeConnection) ReflectionUtils.getPrivateField(managedOfficeProcess, "connection");
46
        
47
        officeManager.start();
48
        assertTrue(process.isRunning());
49
        assertTrue(connection.isConnected());
50
        
51
        MockOfficeTask task = new MockOfficeTask();
52
        officeManager.execute(task);
53
        assertTrue(task.isCompleted());
54
        
55
        officeManager.stop();
56
        assertFalse(connection.isConnected());
57
        assertFalse(process.isRunning());
58
        assertEquals(process.getExitCode(0, 0), 0);
59
    }
60

  
61
    public void restartAfterCrash() throws Exception {
62
        final PooledOfficeManager officeManager = new PooledOfficeManager(CONNECTION_MODE);
63
        ManagedOfficeProcess managedOfficeProcess = (ManagedOfficeProcess) ReflectionUtils.getPrivateField(officeManager, "managedOfficeProcess");
64
        OfficeProcess process = (OfficeProcess) ReflectionUtils.getPrivateField(managedOfficeProcess, "process");
65
        OfficeConnection connection = (OfficeConnection) ReflectionUtils.getPrivateField(managedOfficeProcess, "connection");
66
        assertNotNull(connection);
67
        
68
        officeManager.start();
69
        assertTrue(process.isRunning());
70
        assertTrue(connection.isConnected());
71
        
72
        new Thread() {
73
            public void run() {
74
                MockOfficeTask badTask = new MockOfficeTask(10 * 1000);
75
                try {
76
                    officeManager.execute(badTask);
77
                    fail("task should be cancelled");
78
                    //FIXME being in a separate thread the test won't actually fail
79
                } catch (OfficeException officeException) {
80
                    assertTrue(officeException.getCause() instanceof CancellationException);
81
                }
82
            }
83
        }.start();
84
        Thread.sleep(500);
85
        Process underlyingProcess = (Process) ReflectionUtils.getPrivateField(process, "process");
86
        assertNotNull(underlyingProcess);
87
        underlyingProcess.destroy();  // simulate crash
88

  
89
        Thread.sleep(RESTART_WAIT_TIME);
90
        assertTrue(process.isRunning());
91
        assertTrue(connection.isConnected());
92

  
93
        MockOfficeTask goodTask = new MockOfficeTask();
94
        officeManager.execute(goodTask);
95
        assertTrue(goodTask.isCompleted());
96

  
97
        officeManager.stop();
98
        assertFalse(connection.isConnected());
99
        assertFalse(process.isRunning());
100
        assertEquals(process.getExitCode(0, 0), 0);
101
    }
102

  
103
    public void restartAfterTaskTimeout() throws Exception {
104
        PooledOfficeManagerSettings configuration = new PooledOfficeManagerSettings(CONNECTION_MODE);
105
        configuration.setTaskExecutionTimeout(1500L);
106
        final PooledOfficeManager officeManager = new PooledOfficeManager(configuration);
107
        
108
        ManagedOfficeProcess managedOfficeProcess = (ManagedOfficeProcess) ReflectionUtils.getPrivateField(officeManager, "managedOfficeProcess");
109
        OfficeProcess process = (OfficeProcess) ReflectionUtils.getPrivateField(managedOfficeProcess, "process");
110
        OfficeConnection connection = (OfficeConnection) ReflectionUtils.getPrivateField(managedOfficeProcess, "connection");
111
        assertNotNull(connection);
112
        
113
        officeManager.start();
114
        assertTrue(process.isRunning());
115
        assertTrue(connection.isConnected());
116
        
117
        MockOfficeTask longTask = new MockOfficeTask(2000);
118
        try {
119
            officeManager.execute(longTask);
120
            fail("task should be timed out");
121
        } catch (OfficeException officeException) {
122
            assertTrue(officeException.getCause() instanceof TimeoutException);
123
        }
124

  
125
        Thread.sleep(RESTART_WAIT_TIME);
126
        assertTrue(process.isRunning());
127
        assertTrue(connection.isConnected());
128

  
129
        MockOfficeTask goodTask = new MockOfficeTask();
130
        officeManager.execute(goodTask);
131
        assertTrue(goodTask.isCompleted());
132

  
133
        officeManager.stop();
134
        assertFalse(connection.isConnected());
135
        assertFalse(process.isRunning());
136
        assertEquals(process.getExitCode(0, 0), 0);
137
    }
138

  
139
    public void restartWhenMaxTasksPerProcessReached() throws Exception {
140
        PooledOfficeManagerSettings configuration = new PooledOfficeManagerSettings(CONNECTION_MODE);
141
        configuration.setMaxTasksPerProcess(3);
142
        final PooledOfficeManager officeManager = new PooledOfficeManager(configuration);
143
        
144
        ManagedOfficeProcess managedOfficeProcess = (ManagedOfficeProcess) ReflectionUtils.getPrivateField(officeManager, "managedOfficeProcess");
145
        OfficeProcess process = (OfficeProcess) ReflectionUtils.getPrivateField(managedOfficeProcess, "process");
146
        OfficeConnection connection = (OfficeConnection) ReflectionUtils.getPrivateField(managedOfficeProcess, "connection");
147
        assertNotNull(connection);
148
        
149
        officeManager.start();
150
        assertTrue(process.isRunning());
151
        assertTrue(connection.isConnected());
152
        
153
        for (int i = 0; i < 3; i++) {
154
            MockOfficeTask task = new MockOfficeTask();
155
            officeManager.execute(task);
156
            assertTrue(task.isCompleted());
157
            int taskCount = (Integer) ReflectionUtils.getPrivateField(officeManager, "taskCount");
158
            assertEquals(taskCount, i + 1);
159
        }
160

  
161
        MockOfficeTask task = new MockOfficeTask();
162
        officeManager.execute(task);
163
        assertTrue(task.isCompleted());
164
        int taskCount = (Integer) ReflectionUtils.getPrivateField(officeManager, "taskCount");
165
        assertEquals(taskCount, 0);  //FIXME should be 1 to be precise
166

  
167
        officeManager.stop();
168
        assertFalse(connection.isConnected());
169
        assertFalse(process.isRunning());
170
        assertEquals(process.getExitCode(0, 0), 0);
171
    }
172

  
36
	
37
	private static final UnoUrl CONNECTION_MODE = UnoUrl.socket(2002);
38
	
39
	private static final long RESTART_WAIT_TIME = 2 * 1000;
40
	
41
	public void executeTask() throws Exception {
42
		PooledOfficeManager officeManager = new PooledOfficeManager(CONNECTION_MODE);
43
		ManagedOfficeProcess managedOfficeProcess = (ManagedOfficeProcess) ReflectionUtils.getPrivateField(officeManager, "managedOfficeProcess");
44
		OfficeProcess process = (OfficeProcess) ReflectionUtils.getPrivateField(managedOfficeProcess, "process");
45
		OfficeConnection connection = (OfficeConnection) ReflectionUtils.getPrivateField(managedOfficeProcess, "connection");
46
		
47
		officeManager.start();
48
		assertTrue(process.isRunning());
49
		assertTrue(connection.isConnected());
50
		
51
		MockOfficeTask task = new MockOfficeTask();
52
		officeManager.execute(task);
53
		assertTrue(task.isCompleted());
54
		
55
		officeManager.stop();
56
		assertFalse(connection.isConnected());
57
		assertFalse(process.isRunning());
58
		assertEquals(process.getExitCode(0, 0), 0);
59
	}
60
	
61
	public void restartAfterCrash() throws Exception {
62
		final PooledOfficeManager officeManager = new PooledOfficeManager(CONNECTION_MODE);
63
		ManagedOfficeProcess managedOfficeProcess = (ManagedOfficeProcess) ReflectionUtils.getPrivateField(officeManager, "managedOfficeProcess");
64
		OfficeProcess process = (OfficeProcess) ReflectionUtils.getPrivateField(managedOfficeProcess, "process");
65
		OfficeConnection connection = (OfficeConnection) ReflectionUtils.getPrivateField(managedOfficeProcess, "connection");
66
		assertNotNull(connection);
67
		
68
		officeManager.start();
69
		assertTrue(process.isRunning());
70
		assertTrue(connection.isConnected());
71
		
72
		new Thread() {
73
			
74
			public void run() {
75
				MockOfficeTask badTask = new MockOfficeTask(10 * 1000);
76
				try {
77
					officeManager.execute(badTask);
78
					fail("task should be cancelled");
79
					// FIXME being in a separate thread the test won't actually fail
80
				}
81
				catch (OfficeException officeException) {
82
					assertTrue(officeException.getCause() instanceof CancellationException);
83
				}
84
			}
85
		}.start();
86
		Thread.sleep(500);
87
		Process underlyingProcess = (Process) ReflectionUtils.getPrivateField(process, "process");
88
		assertNotNull(underlyingProcess);
89
		underlyingProcess.destroy();  // simulate crash
90
		
91
		Thread.sleep(RESTART_WAIT_TIME);
92
		assertTrue(process.isRunning());
93
		assertTrue(connection.isConnected());
94
		
95
		MockOfficeTask goodTask = new MockOfficeTask();
96
		officeManager.execute(goodTask);
97
		assertTrue(goodTask.isCompleted());
98
		
99
		officeManager.stop();
100
		assertFalse(connection.isConnected());
101
		assertFalse(process.isRunning());
102
		assertEquals(process.getExitCode(0, 0), 0);
103
	}
104
	
105
	public void restartAfterTaskTimeout() throws Exception {
106
		PooledOfficeManagerSettings configuration = new PooledOfficeManagerSettings(CONNECTION_MODE);
107
		configuration.setTaskExecutionTimeout(1500L);
108
		final PooledOfficeManager officeManager = new PooledOfficeManager(configuration);
109
		
110
		ManagedOfficeProcess managedOfficeProcess = (ManagedOfficeProcess) ReflectionUtils.getPrivateField(officeManager, "managedOfficeProcess");
111
		OfficeProcess process = (OfficeProcess) ReflectionUtils.getPrivateField(managedOfficeProcess, "process");
112
		OfficeConnection connection = (OfficeConnection) ReflectionUtils.getPrivateField(managedOfficeProcess, "connection");
113
		assertNotNull(connection);
114
		
115
		officeManager.start();
116
		assertTrue(process.isRunning());
117
		assertTrue(connection.isConnected());
118
		
119
		MockOfficeTask longTask = new MockOfficeTask(2000);
120
		try {
121
			officeManager.execute(longTask);
122
			fail("task should be timed out");
123
		}
124
		catch (OfficeException officeException) {
125
			assertTrue(officeException.getCause() instanceof TimeoutException);
126
		}
127
		
128
		Thread.sleep(RESTART_WAIT_TIME);
129
		assertTrue(process.isRunning());
130
		assertTrue(connection.isConnected());
131
		
132
		MockOfficeTask goodTask = new MockOfficeTask();
133
		officeManager.execute(goodTask);
134
		assertTrue(goodTask.isCompleted());
135
		
136
		officeManager.stop();
137
		assertFalse(connection.isConnected());
138
		assertFalse(process.isRunning());
139
		assertEquals(process.getExitCode(0, 0), 0);
140
	}
141
	
142
	public void restartWhenMaxTasksPerProcessReached() throws Exception {
143
		PooledOfficeManagerSettings configuration = new PooledOfficeManagerSettings(CONNECTION_MODE);
144
		configuration.setMaxTasksPerProcess(3);
145
		final PooledOfficeManager officeManager = new PooledOfficeManager(configuration);
146
		
147
		ManagedOfficeProcess managedOfficeProcess = (ManagedOfficeProcess) ReflectionUtils.getPrivateField(officeManager, "managedOfficeProcess");
148
		OfficeProcess process = (OfficeProcess) ReflectionUtils.getPrivateField(managedOfficeProcess, "process");
149
		OfficeConnection connection = (OfficeConnection) ReflectionUtils.getPrivateField(managedOfficeProcess, "connection");
150
		assertNotNull(connection);
151
		
152
		officeManager.start();
153
		assertTrue(process.isRunning());
154
		assertTrue(connection.isConnected());
155
		
156
		for (int i = 0; i < 3; i++) {
157
			MockOfficeTask task = new MockOfficeTask();
158
			officeManager.execute(task);
159
			assertTrue(task.isCompleted());
160
			int taskCount = (Integer) ReflectionUtils.getPrivateField(officeManager, "taskCount");
161
			assertEquals(taskCount, i + 1);
162
		}
163
		
164
		MockOfficeTask task = new MockOfficeTask();
165
		officeManager.execute(task);
166
		assertTrue(task.isCompleted());
167
		int taskCount = (Integer) ReflectionUtils.getPrivateField(officeManager, "taskCount");
168
		assertEquals(taskCount, 0);  // FIXME should be 1 to be precise
169
		
170
		officeManager.stop();
171
		assertFalse(connection.isConnected());
172
		assertFalse(process.isRunning());
173
		assertEquals(process.getExitCode(0, 0), 0);
174
	}
175
	
173 176
}
tmp/org.txm.jodconverter.core/src/test/java/org/artofsolving/jodconverter/office/OfficeUtilsTest.java (revision 2406)
18 18
import java.io.File;
19 19

  
20 20
public class OfficeUtilsTest {
21

  
22
    public void testToUrl() {
23
        //TODO create separate tests for Windows
24
        assertEquals(toUrl(new File("/tmp/document.odt")), "file:///tmp/document.odt");
25
        assertEquals(toUrl(new File("/tmp/document with spaces.odt")), "file:///tmp/document%20with%20spaces.odt");
26
    }
27

  
21
	
22
	public void testToUrl() {
23
		// TODO create separate tests for Windows
24
		assertEquals(toUrl(new File("/tmp/document.odt")), "file:///tmp/document.odt");
25
		assertEquals(toUrl(new File("/tmp/document with spaces.odt")), "file:///tmp/document%20with%20spaces.odt");
26
	}
27
	
28 28
}
tmp/org.txm.jodconverter.core/src/test/java/org/artofsolving/jodconverter/document/DumpJsonDefaultDocumentFormatRegistry.java (revision 2406)
17 17
import java.util.List;
18 18
import java.util.Map;
19 19

  
20

  
21 20
import org.artofsolving.jodconverter.ReflectionUtils;
22 21
import org.json.JSONArray;
23 22
import org.json.JSONException;
......
27 26
 * Exectable class that dumps a JSON version of the {@link DefaultDocumentFormatRegistry}
28 27
 */
29 28
class DumpJsonDefaultDocumentFormatRegistry {
30

  
31
    private static class SortedJsonObject extends JSONObject {
32
         public SortedJsonObject() {
33
             try {
34
                 Field field = JSONObject.class.getDeclaredField("myHashMap");
35
                 field.setAccessible(true);
36
                 field.set(this, new LinkedHashMap<String,Object>());
37
             } catch (Exception exception) {
38
                 // pass; will not be sorted
39
             }
40
        }
41
    }
42

  
43
    private static JSONObject toJson(DocumentFormat format) throws JSONException {
44
        JSONObject jsonFormat = new SortedJsonObject();
45
        jsonFormat.put("name", format.getName());
46
        jsonFormat.put("extension", format.getExtension());
47
        jsonFormat.put("mediaType", format.getMediaType());
48
        if (format.getInputFamily() != null) {
49
            jsonFormat.put("inputFamily", format.getInputFamily().name());
50
        }
51
        if (format.getLoadProperties() != null) {
52
            jsonFormat.put("loadProperties", toJson(format.getLoadProperties()));
53
        }
54
        if (format.getStorePropertiesByFamily() != null) {
55
            JSONObject jsonStorePropertiesByFamily = new SortedJsonObject();
56
            for (Map.Entry<DocumentFamily,Map<String,?>> entry : format.getStorePropertiesByFamily().entrySet()) {
57
                jsonStorePropertiesByFamily.put(entry.getKey().name(), toJson(entry.getValue()));
58
            }
59
            jsonFormat.put("storePropertiesByFamily", jsonStorePropertiesByFamily);
60
        }
61
        return jsonFormat;
62
    }
63

  
64
    @SuppressWarnings("unchecked")
65
    private static JSONObject toJson(Map<String,?> properties) throws JSONException {
66
        JSONObject jsonProperties = new SortedJsonObject();
67
        for (Map.Entry<String,?> entry : properties.entrySet()) {
68
            if (entry.getValue() instanceof Map) {
69
                Map<String,?> jsonValue = (Map<String,?>) entry.getValue();
70
                jsonProperties.put(entry.getKey(), toJson(jsonValue));
71
            } else {
72
                jsonProperties.put(entry.getKey(), entry.getValue());
73
            }
74
        }
75
        return jsonProperties;
76
    }
77

  
78
    public static void main(String[] args) throws Exception {
79
        DefaultDocumentFormatRegistry registry = new DefaultDocumentFormatRegistry();
80
        @SuppressWarnings("unchecked")
81
        List<DocumentFormat> formats = (List<DocumentFormat>) ReflectionUtils.getPrivateField(SimpleDocumentFormatRegistry.class, registry, "documentFormats");
82
        JSONArray array = new JSONArray();
83
        for (DocumentFormat format : formats) {
84
            array.put(toJson(format));
85
        }
86
        System.out.println(array.toString(2));
87
    }
88

  
29
	
30
	private static class SortedJsonObject extends JSONObject {
31
		
32
		public SortedJsonObject() {
33
			try {
34
				Field field = JSONObject.class.getDeclaredField("myHashMap");
35
				field.setAccessible(true);
36
				field.set(this, new LinkedHashMap<String, Object>());
37
			}
38
			catch (Exception exception) {
39
				// pass; will not be sorted
40
			}
41
		}
42
	}
43
	
44
	private static JSONObject toJson(DocumentFormat format) throws JSONException {
45
		JSONObject jsonFormat = new SortedJsonObject();
46
		jsonFormat.put("name", format.getName());
47
		jsonFormat.put("extension", format.getExtension());
48
		jsonFormat.put("mediaType", format.getMediaType());
49
		if (format.getInputFamily() != null) {
50
			jsonFormat.put("inputFamily", format.getInputFamily().name());
51
		}
52
		if (format.getLoadProperties() != null) {
53
			jsonFormat.put("loadProperties", toJson(format.getLoadProperties()));
54
		}
55
		if (format.getStorePropertiesByFamily() != null) {
56
			JSONObject jsonStorePropertiesByFamily = new SortedJsonObject();
57
			for (Map.Entry<DocumentFamily, Map<String, ?>> entry : format.getStorePropertiesByFamily().entrySet()) {
58
				jsonStorePropertiesByFamily.put(entry.getKey().name(), toJson(entry.getValue()));
59
			}
60
			jsonFormat.put("storePropertiesByFamily", jsonStorePropertiesByFamily);
61
		}
62
		return jsonFormat;
63
	}
64
	
65
	@SuppressWarnings("unchecked")
66
	private static JSONObject toJson(Map<String, ?> properties) throws JSONException {
67
		JSONObject jsonProperties = new SortedJsonObject();
68
		for (Map.Entry<String, ?> entry : properties.entrySet()) {
69
			if (entry.getValue() instanceof Map) {
70
				Map<String, ?> jsonValue = (Map<String, ?>) entry.getValue();
71
				jsonProperties.put(entry.getKey(), toJson(jsonValue));
72
			}
73
			else {
74
				jsonProperties.put(entry.getKey(), entry.getValue());
75
			}
76
		}
77
		return jsonProperties;
78
	}
79
	
80
	public static void main(String[] args) throws Exception {
81
		DefaultDocumentFormatRegistry registry = new DefaultDocumentFormatRegistry();
82
		@SuppressWarnings("unchecked")
83
		List<DocumentFormat> formats = (List<DocumentFormat>) ReflectionUtils.getPrivateField(SimpleDocumentFormatRegistry.class, registry, "documentFormats");
84
		JSONArray array = new JSONArray();
85
		for (DocumentFormat format : formats) {
86
			array.put(toJson(format));
87
		}
88
		System.out.println(array.toString(2));
89
	}
90
	
89 91
}
tmp/org.txm.jodconverter.core/src/test/java/org/artofsolving/jodconverter/document/JsonDocumentFormatRegistryTest.java (revision 2406)
28 28

  
29 29
@Test
30 30
public class JsonDocumentFormatRegistryTest {
31

  
32
    public void readJsonRegistry() throws JSONException, IOException {
33
        InputStream input = getClass().getResourceAsStream("/document-formats.js");
34
        DocumentFormatRegistry registry = null;
35
        try {
36
            registry = new JsonDocumentFormatRegistry(input);
37
        } finally {
38
            IOUtils.closeQuietly(input);
39
        }
40
        DocumentFormat odt = registry.getFormatByExtension("odt");
41
        assertNotNull(odt);
42
        assertNotNull(odt.getStoreProperties(DocumentFamily.TEXT));
43
    }
44

  
31
	
32
	public void readJsonRegistry() throws JSONException, IOException {
33
		InputStream input = getClass().getResourceAsStream("/document-formats.js");
34
		DocumentFormatRegistry registry = null;
35
		try {
36
			registry = new JsonDocumentFormatRegistry(input);
37
		}
38
		finally {
39
			IOUtils.closeQuietly(input);
40
		}
41
		DocumentFormat odt = registry.getFormatByExtension("odt");
42
		assertNotNull(odt);
43
		assertNotNull(odt.getStoreProperties(DocumentFamily.TEXT));
44
	}
45
	
45 46
}
tmp/org.txm.jodconverter.core/src/test/java/org/artofsolving/jodconverter/process/ProcessManagerTest.java (revision 2406)
22 22

  
23 23
@Test
24 24
public class ProcessManagerTest {
25

  
26
    public void linuxProcessManager() throws Exception {
27
        if (!PlatformUtils.isLinux()) {
28
            throw new SkipException("LinuxProcessManager can only be tested on Linux");
29
        }
30

  
31
        ProcessManager processManager = new LinuxProcessManager();
32
        Process process = new ProcessBuilder("sleep", "5s").start();
33
        ProcessQuery query = new ProcessQuery("sleep", "5s");
34
        
35
        long pid = processManager.findPid(query);
36
        assertFalse(pid == ProcessManager.PID_NOT_FOUND);
37
        Integer javaPid = (Integer) ReflectionUtils.getPrivateField(process, "pid");
38
        assertEquals(pid, javaPid.longValue());
39
        
40
        processManager.kill(process, pid);
41
        assertEquals(processManager.findPid(query), ProcessManager.PID_NOT_FOUND);
42
    }
43

  
44
    public void sigarProcessManager() throws Exception {
45
        ProcessManager processManager = new SigarProcessManager();
46
        Process process = new ProcessBuilder("sleep", "5s").start();
47
        ProcessQuery query = new ProcessQuery("sleep", "5s");
48
        
49
        long pid = processManager.findPid(query);
50
        assertFalse(pid == ProcessManager.PID_NOT_FOUND);
51
        if (PlatformUtils.isLinux()) {
52
            Integer javaPid = (Integer) ReflectionUtils.getPrivateField(process, "pid");
53
            assertEquals(pid, javaPid.longValue());
54
        }
55

  
56
        processManager.kill(process, pid);
57
        assertEquals(processManager.findPid(query), ProcessManager.PID_NOT_FOUND);
58
    }
59

  
25
	
26
	public void linuxProcessManager() throws Exception {
27
		if (!PlatformUtils.isLinux()) {
28
			throw new SkipException("LinuxProcessManager can only be tested on Linux");
29
		}
30
		
31
		ProcessManager processManager = new LinuxProcessManager();
32
		Process process = new ProcessBuilder("sleep", "5s").start();
33
		ProcessQuery query = new ProcessQuery("sleep", "5s");
34
		
35
		long pid = processManager.findPid(query);
36
		assertFalse(pid == ProcessManager.PID_NOT_FOUND);
37
		Integer javaPid = (Integer) ReflectionUtils.getPrivateField(process, "pid");
38
		assertEquals(pid, javaPid.longValue());
39
		
40
		processManager.kill(process, pid);
41
		assertEquals(processManager.findPid(query), ProcessManager.PID_NOT_FOUND);
42
	}
43
	
44
	public void sigarProcessManager() throws Exception {
45
		ProcessManager processManager = new SigarProcessManager();
46
		Process process = new ProcessBuilder("sleep", "5s").start();
47
		ProcessQuery query = new ProcessQuery("sleep", "5s");
48
		
49
		long pid = processManager.findPid(query);
50
		assertFalse(pid == ProcessManager.PID_NOT_FOUND);
51
		if (PlatformUtils.isLinux()) {
52
			Integer javaPid = (Integer) ReflectionUtils.getPrivateField(process, "pid");
53
			assertEquals(pid, javaPid.longValue());
54
		}
55
		
56
		processManager.kill(process, pid);
57
		assertEquals(processManager.findPid(query), ProcessManager.PID_NOT_FOUND);
58
	}
59
	
60 60
}
tmp/org.txm.jodconverter.core/src/main/assembly/dist.xml (revision 2406)
1 1
<assembly>
2
  <id>dist</id>
3
  <formats>
4
    <format>zip</format>
5
  </formats>
6
  <dependencySets>
7
    <dependencySet>
8
      <outputDirectory>lib</outputDirectory>
9
      <excludes>
10
        <exclude>org.hyperic:sigar</exclude>
11
      </excludes>
12
    </dependencySet>
13
  </dependencySets>
14
  <fileSets>
15
    <fileSet>
16
      <includes>
17
        <include>LICENSE.txt</include>
18
        <include>README.txt</include>
19
      </includes>
20
    </fileSet>
21
    <fileSet>
22
      <directory>target</directory>
23
      <outputDirectory>/</outputDirectory>
24
      <includes>
25
        <include>${project.artifactId}-${project.version}-javadoc.jar</include>
26
        <include>${project.artifactId}-${project.version}-sources.jar</include>
27
      </includes>
28
    </fileSet>
29
    <fileSet>
30
      <directory>src/main/resources</directory>
31
      <outputDirectory>/conf</outputDirectory>
32
      <includes>
33
        <include>document-formats.js</include>
34
      </includes>
35
    </fileSet>
36
  </fileSets>
2
	<id>dist</id>
3
	<formats>
4
		<format>zip</format>
5
	</formats>
6
	<dependencySets>
7
		<dependencySet>
8
			<outputDirectory>lib</outputDirectory>
9
			<excludes>
10
				<exclude>org.hyperic:sigar</exclude>
11
			</excludes>
12
		</dependencySet>
13
	</dependencySets>
14
	<fileSets>
15
		<fileSet>
16
			<includes>
17
				<include>LICENSE.txt</include>
18
				<include>README.txt</include>
19
			</includes>
20
		</fileSet>
21
		<fileSet>
22
			<directory>target</directory>
23
			<outputDirectory>/</outputDirectory>
24
			<includes>
25
				<include>${project.artifactId}-${project.version}-javadoc.jar</include>
26
				<include>${project.artifactId}-${project.version}-sources.jar</include>
27
			</includes>
28
		</fileSet>
29
		<fileSet>
30
			<directory>src/main/resources</directory>
31
			<outputDirectory>/conf</outputDirectory>
32
			<includes>
33
				<include>document-formats.js</include>
34
			</includes>
35
		</fileSet>
36
	</fileSets>
37 37
</assembly>
tmp/org.txm.jodconverter.core/src/main/java/org/artofsolving/jodconverter/cli/Convert.java (revision 2406)
36 36
 * Command line interface executable.
37 37
 */
38 38
public class Convert {
39

  
40
    public static final int STATUS_OK = 0;
41
    public static final int STATUS_MISSING_INPUT_FILE = 1;
42
    public static final int STATUS_INVALID_ARGUMENTS = 255;
43

  
44
    private static final Option OPTION_OUTPUT_FORMAT = new Option("o", "output-format", true, "output format (e.g. pdf)");
45
    private static final Option OPTION_PORT = new Option("p", "port", true, "office socket port (optional; defaults to 2002)");
46
    private static final Option OPTION_REGISTRY = new Option("r", "registry", true, "document formats registry configuration file (optional)");
47
    private static final Option OPTION_TIMEOUT = new Option("t", "timeout", true, "maximum conversion time in seconds (optional; defaults to 120)");
48
    private static final Option OPTION_USER_PROFILE = new Option("u", "user-profile", true, "use settings from the given user installation dir (optional)");
49
    private static final Options OPTIONS = initOptions();
50

  
51
    private static final int DEFAULT_OFFICE_PORT = 2002;
52

  
53
    private static Options initOptions() {
54
        Options options = new Options();
55
        options.addOption(OPTION_OUTPUT_FORMAT);
56
        options.addOption(OPTION_PORT);
57
        options.addOption(OPTION_REGISTRY);
58
        options.addOption(OPTION_TIMEOUT);
59
        options.addOption(OPTION_USER_PROFILE);
60
        return options;
61
    }
62

  
63
    public static void main(String[] arguments) throws ParseException, JSONException, IOException {
64
        CommandLineParser commandLineParser = new PosixParser();
65
        CommandLine commandLine = commandLineParser.parse(OPTIONS, arguments);
66

  
67
        String outputFormat = null;
68
        if (commandLine.hasOption(OPTION_OUTPUT_FORMAT.getOpt())) {
69
            outputFormat = commandLine.getOptionValue(OPTION_OUTPUT_FORMAT.getOpt());
70
        }
71

  
72
        int port = DEFAULT_OFFICE_PORT;
73
        if (commandLine.hasOption(OPTION_PORT.getOpt())) {
74
            port = Integer.parseInt(commandLine.getOptionValue(OPTION_PORT.getOpt()));
75
        }
76

  
77
        String[] fileNames = commandLine.getArgs();
78
        if ((outputFormat == null && fileNames.length != 2) || fileNames.length < 1) {
79
            String syntax = "java -jar jodconverter-core.jar [options] input-file output-file\n"
80
                    + "or [options] -o output-format input-file [input-file...]";
81
            HelpFormatter helpFormatter = new HelpFormatter();
82
            helpFormatter.printHelp(syntax, OPTIONS);
83
//            System.exit(STATUS_INVALID_ARGUMENTS);
84
        }
85

  
86
        DocumentFormatRegistry registry;
87
        if (commandLine.hasOption(OPTION_REGISTRY.getOpt())) {
88
            File registryFile = new File(commandLine.getOptionValue(OPTION_REGISTRY.getOpt()));
89
            registry = new JsonDocumentFormatRegistry(FileUtils.readFileToString(registryFile));
90
        } else {
91
            registry = new DefaultDocumentFormatRegistry();
92
        }
93

  
94
        DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
95
        configuration.setPortNumber(port);
96
        if (commandLine.hasOption(OPTION_TIMEOUT.getOpt())) {
97
            int timeout = Integer.parseInt(commandLine.getOptionValue(OPTION_TIMEOUT.getOpt()));
98
            configuration.setTaskExecutionTimeout(timeout * 1000);
99
        }
100
        if (commandLine.hasOption(OPTION_USER_PROFILE.getOpt())) {
101
            String templateProfileDir = commandLine.getOptionValue(OPTION_USER_PROFILE.getOpt());
102
            configuration.setTemplateProfileDir(new File(templateProfileDir));
103
        }
104

  
105
        OfficeManager officeManager = configuration.buildOfficeManager();
106
        officeManager.start();
107
        OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager, registry);
108
        try {
109
            if (outputFormat == null) {
110
                File inputFile = new File(fileNames[0]);
111
                File outputFile = new File(fileNames[1]);
112
                converter.convert(inputFile, outputFile);
113
            } else {
114
                for (int i = 0; i < fileNames.length; i++) {
115
                    File inputFile = new File(fileNames[i]);
116
                    String outputName = FilenameUtils.getBaseName(fileNames[i]) + "." + outputFormat;
117
                    File outputFile = new File(FilenameUtils.getFullPath(fileNames[i]) + outputName);
118
                    converter.convert(inputFile, outputFile);
119
                }
120
            }
121
        } finally {
122
            officeManager.stop();
123
        }
124
    }
125
    
39
	
40
	public static final int STATUS_OK = 0;
41
	
42
	public static final int STATUS_MISSING_INPUT_FILE = 1;
43
	
44
	public static final int STATUS_INVALID_ARGUMENTS = 255;
45
	
46
	private static final Option OPTION_OUTPUT_FORMAT = new Option("o", "output-format", true, "output format (e.g. pdf)");
47
	
48
	private static final Option OPTION_PORT = new Option("p", "port", true, "office socket port (optional; defaults to 2002)");
49
	
50
	private static final Option OPTION_REGISTRY = new Option("r", "registry", true, "document formats registry configuration file (optional)");
51
	
52
	private static final Option OPTION_TIMEOUT = new Option("t", "timeout", true, "maximum conversion time in seconds (optional; defaults to 120)");
53
	
54
	private static final Option OPTION_USER_PROFILE = new Option("u", "user-profile", true, "use settings from the given user installation dir (optional)");
55
	
56
	private static final Options OPTIONS = initOptions();
57
	
58
	private static final int DEFAULT_OFFICE_PORT = 2002;
59
	
60
	private static Options initOptions() {
61
		Options options = new Options();
62
		options.addOption(OPTION_OUTPUT_FORMAT);
63
		options.addOption(OPTION_PORT);
64
		options.addOption(OPTION_REGISTRY);
65
		options.addOption(OPTION_TIMEOUT);
66
		options.addOption(OPTION_USER_PROFILE);
67
		return options;
68
	}
69
	
70
	public static void main(String[] arguments) throws ParseException, JSONException, IOException {
71
		CommandLineParser commandLineParser = new PosixParser();
72
		CommandLine commandLine = commandLineParser.parse(OPTIONS, arguments);
73
		
74
		String outputFormat = null;
75
		if (commandLine.hasOption(OPTION_OUTPUT_FORMAT.getOpt())) {
76
			outputFormat = commandLine.getOptionValue(OPTION_OUTPUT_FORMAT.getOpt());
77
		}
78
		
79
		int port = DEFAULT_OFFICE_PORT;
80
		if (commandLine.hasOption(OPTION_PORT.getOpt())) {
81
			port = Integer.parseInt(commandLine.getOptionValue(OPTION_PORT.getOpt()));
82
		}
83
		
84
		String[] fileNames = commandLine.getArgs();
85
		if ((outputFormat == null && fileNames.length != 2) || fileNames.length < 1) {
86
			String syntax = "java -jar jodconverter-core.jar [options] input-file output-file\n"
87
					+ "or [options] -o output-format input-file [input-file...]";
88
			HelpFormatter helpFormatter = new HelpFormatter();
89
			helpFormatter.printHelp(syntax, OPTIONS);
90
			// System.exit(STATUS_INVALID_ARGUMENTS);
91
		}
92
		
93
		DocumentFormatRegistry registry;
94
		if (commandLine.hasOption(OPTION_REGISTRY.getOpt())) {
95
			File registryFile = new File(commandLine.getOptionValue(OPTION_REGISTRY.getOpt()));
96
			registry = new JsonDocumentFormatRegistry(FileUtils.readFileToString(registryFile));
97
		}
98
		else {
99
			registry = new DefaultDocumentFormatRegistry();
100
		}
101
		
102
		DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
103
		configuration.setPortNumber(port);
104
		if (commandLine.hasOption(OPTION_TIMEOUT.getOpt())) {
105
			int timeout = Integer.parseInt(commandLine.getOptionValue(OPTION_TIMEOUT.getOpt()));
106
			configuration.setTaskExecutionTimeout(timeout * 1000);
107
		}
108
		if (commandLine.hasOption(OPTION_USER_PROFILE.getOpt())) {
109
			String templateProfileDir = commandLine.getOptionValue(OPTION_USER_PROFILE.getOpt());
110
			configuration.setTemplateProfileDir(new File(templateProfileDir));
111
		}
112
		
113
		OfficeManager officeManager = configuration.buildOfficeManager();
114
		officeManager.start();
115
		OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager, registry);
116
		try {
117
			if (outputFormat == null) {
118
				File inputFile = new File(fileNames[0]);
119
				File outputFile = new File(fileNames[1]);
120
				converter.convert(inputFile, outputFile);
121
			}
122
			else {
123
				for (int i = 0; i < fileNames.length; i++) {
124
					File inputFile = new File(fileNames[i]);
125
					String outputName = FilenameUtils.getBaseName(fileNames[i]) + "." + outputFormat;
126
					File outputFile = new File(FilenameUtils.getFullPath(fileNames[i]) + outputName);
127
					converter.convert(inputFile, outputFile);
128
				}
129
			}
130
		}
131
		finally {
132
			officeManager.stop();
133
		}
134
	}
135
	
126 136
}
tmp/org.txm.jodconverter.core/src/main/java/org/artofsolving/jodconverter/StandardConversionTask.java (revision 2406)
26 26
import com.sun.star.util.XRefreshable;
27 27

  
28 28
public class StandardConversionTask extends AbstractConversionTask {
29

  
30
    private final DocumentFormat outputFormat;
31

  
32
    private Map<String,?> defaultLoadProperties;
33
    private DocumentFormat inputFormat;
34

  
35
    public StandardConversionTask(File inputFile, File outputFile, DocumentFormat outputFormat) {
36
        super(inputFile, outputFile);
37
        this.outputFormat = outputFormat;
38
    }
39

  
40
    public void setDefaultLoadProperties(Map<String, ?> defaultLoadProperties) {
41
        this.defaultLoadProperties = defaultLoadProperties;
42
    }
43

  
44
    public void setInputFormat(DocumentFormat inputFormat) {
45
        this.inputFormat = inputFormat;
46
    }
47

  
48
    @Override
49
    protected void modifyDocument(XComponent document) throws OfficeException {
50
        XRefreshable refreshable = cast(XRefreshable.class, document);
51
        if (refreshable != null) {
52
            refreshable.refresh();
53
        }
54
    }
55

  
56
    @Override
57
    protected Map<String,?> getLoadProperties(File inputFile) {
58
        Map<String,Object> loadProperties = new HashMap<String,Object>();
59
        if (defaultLoadProperties != null) {
60
            loadProperties.putAll(defaultLoadProperties);
61
        }
62
        if (inputFormat != null && inputFormat.getLoadProperties() != null) {
63
            loadProperties.putAll(inputFormat.getLoadProperties());
64
        }
65
        return loadProperties;
66
    }
67

  
68
    @Override
69
    protected Map<String,?> getStoreProperties(File outputFile, XComponent document) {
70
        DocumentFamily family = OfficeDocumentUtils.getDocumentFamily(document);
71
        return outputFormat.getStoreProperties(family);
72
    }
73

  
29
	
30
	private final DocumentFormat outputFormat;
31
	
32
	private Map<String, ?> defaultLoadProperties;
33
	
34
	private DocumentFormat inputFormat;
35
	
36
	public StandardConversionTask(File inputFile, File outputFile, DocumentFormat outputFormat) {
37
		super(inputFile, outputFile);
38
		this.outputFormat = outputFormat;
39
	}
40
	
41
	public void setDefaultLoadProperties(Map<String, ?> defaultLoadProperties) {
42
		this.defaultLoadProperties = defaultLoadProperties;
43
	}
44
	
45
	public void setInputFormat(DocumentFormat inputFormat) {
46
		this.inputFormat = inputFormat;
47
	}
48
	
49
	@Override
50
	protected void modifyDocument(XComponent document) throws OfficeException {
51
		XRefreshable refreshable = cast(XRefreshable.class, document);
52
		if (refreshable != null) {
53
			refreshable.refresh();
54
		}
55
	}
56
	
57
	@Override
58
	protected Map<String, ?> getLoadProperties(File inputFile) {
59
		Map<String, Object> loadProperties = new HashMap<String, Object>();
60
		if (defaultLoadProperties != null) {
61
			loadProperties.putAll(defaultLoadProperties);
62
		}
63
		if (inputFormat != null && inputFormat.getLoadProperties() != null) {
64
			loadProperties.putAll(inputFormat.getLoadProperties());
65
		}
66
		return loadProperties;
67
	}
68
	
69
	@Override
70
	protected Map<String, ?> getStoreProperties(File outputFile, XComponent document) {
71
		DocumentFamily family = OfficeDocumentUtils.getDocumentFamily(document);
72
		return outputFormat.getStoreProperties(family);
73
	}
74
	
74 75
}
tmp/org.txm.jodconverter.core/src/main/java/org/artofsolving/jodconverter/OfficeDocumentUtils.java (revision 2406)
17 17
import org.artofsolving.jodconverter.document.DocumentFamily;
18 18
import org.artofsolving.jodconverter.office.OfficeException;
19 19

  
20

  
21 20
import com.sun.star.lang.XComponent;
22 21
import com.sun.star.lang.XServiceInfo;
23 22

  
24 23
class OfficeDocumentUtils {
25

  
26
    private OfficeDocumentUtils() {
27
        throw new AssertionError("utility class must not be instantiated");
28
    }
29

  
30
    public static DocumentFamily getDocumentFamily(XComponent document) throws OfficeException {
31
        XServiceInfo serviceInfo = cast(XServiceInfo.class, document);
32
        if (serviceInfo.supportsService("com.sun.star.text.GenericTextDocument")) {
33
            // NOTE: a GenericTextDocument is either a TextDocument, a WebDocument, or a GlobalDocument
34
            // but this further distinction doesn't seem to matter for conversions
35
            return DocumentFamily.TEXT;
36
        } else if (serviceInfo.supportsService("com.sun.star.sheet.SpreadsheetDocument")) {
37
            return DocumentFamily.SPREADSHEET;
38
        } else if (serviceInfo.supportsService("com.sun.star.presentation.PresentationDocument")) {
39
            return DocumentFamily.PRESENTATION;
40
        } else if (serviceInfo.supportsService("com.sun.star.drawing.DrawingDocument")) {
41
            return DocumentFamily.DRAWING;
42
        } else {
43
            throw new OfficeException("document of unknown family: " + serviceInfo.getImplementationName());
44
        }
45
    }
46

  
24
	
25
	private OfficeDocumentUtils() {
26
		throw new AssertionError("utility class must not be instantiated");
27
	}
28
	
29
	public static DocumentFamily getDocumentFamily(XComponent document) throws OfficeException {
30
		XServiceInfo serviceInfo = cast(XServiceInfo.class, document);
31
		if (serviceInfo.supportsService("com.sun.star.text.GenericTextDocument")) {
32
			// NOTE: a GenericTextDocument is either a TextDocument, a WebDocument, or a GlobalDocument
33
			// but this further distinction doesn't seem to matter for conversions
34
			return DocumentFamily.TEXT;
35
		}
36
		else if (serviceInfo.supportsService("com.sun.star.sheet.SpreadsheetDocument")) {
37
			return DocumentFamily.SPREADSHEET;
38
		}
39
		else if (serviceInfo.supportsService("com.sun.star.presentation.PresentationDocument")) {
40
			return DocumentFamily.PRESENTATION;
41
		}
42
		else if (serviceInfo.supportsService("com.sun.star.drawing.DrawingDocument")) {
43
			return DocumentFamily.DRAWING;
44
		}
45
		else {
46
			throw new OfficeException("document of unknown family: " + serviceInfo.getImplementationName());
47
		}
48
	}
49
	
47 50
}
tmp/org.txm.jodconverter.core/src/main/java/org/artofsolving/jodconverter/office/ManagedOfficeProcessSettings.java (revision 2406)
18 18
import org.artofsolving.jodconverter.process.PureJavaProcessManager;
19 19

  
20 20
class ManagedOfficeProcessSettings {
21

  
22
    public static final long DEFAULT_RETRY_INTERVAL = 250L;
23

  
24
    private final UnoUrl unoUrl;
25
    private File officeHome = OfficeUtils.getDefaultOfficeHome();
26
    private String[] runAsArgs;
27
    private File templateProfileDir;
28
    private File workDir = new File(System.getProperty("java.io.tmpdir"));
29
    private ProcessManager processManager = new PureJavaProcessManager();
30
    private long retryTimeout = DefaultOfficeManagerConfiguration.DEFAULT_RETRY_TIMEOUT;
31
    private long retryInterval = DEFAULT_RETRY_INTERVAL;
32

  
33
    public ManagedOfficeProcessSettings(UnoUrl unoUrl) {
34
        this.unoUrl = unoUrl;
35
    }
36

  
37
    public UnoUrl getUnoUrl() {
38
        return unoUrl;
39
    }
40

  
41
    public File getOfficeHome() {
42
        return officeHome;
43
    }
44

  
45
    public void setOfficeHome(File officeHome) {
46
        this.officeHome = officeHome;
47
    }
48

  
49
    public String[] getRunAsArgs() {
21
	
22
	public static final long DEFAULT_RETRY_INTERVAL = 250L;
23
	
24
	private final UnoUrl unoUrl;
25
	
26
	private File officeHome = OfficeUtils.getDefaultOfficeHome();
27
	
28
	private String[] runAsArgs;
29
	
30
	private File templateProfileDir;
31
	
32
	private File workDir = new File(System.getProperty("java.io.tmpdir"));
33
	
34
	private ProcessManager processManager = new PureJavaProcessManager();
35
	
36
	private long retryTimeout = DefaultOfficeManagerConfiguration.DEFAULT_RETRY_TIMEOUT;
37
	
38
	private long retryInterval = DEFAULT_RETRY_INTERVAL;
39
	
40
	public ManagedOfficeProcessSettings(UnoUrl unoUrl) {
41
		this.unoUrl = unoUrl;
42
	}
43
	
44
	public UnoUrl getUnoUrl() {
45
		return unoUrl;
46
	}
47
	
48
	public File getOfficeHome() {
49
		return officeHome;
50
	}
51
	
52
	public void setOfficeHome(File officeHome) {
53
		this.officeHome = officeHome;
54
	}
55
	
56
	public String[] getRunAsArgs() {
50 57
		return runAsArgs;
51 58
	}
52

  
53
    public void setRunAsArgs(String[] runAsArgs) {
59
	
60
	public void setRunAsArgs(String[] runAsArgs) {
54 61
		this.runAsArgs = runAsArgs;
55 62
	}
56

  
57
    public File getTemplateProfileDir() {
58
        return templateProfileDir;
59
    }
60

  
61
    public void setTemplateProfileDir(File templateProfileDir) {
62
        this.templateProfileDir = templateProfileDir;
63
    }
64

  
65
    public File getWorkDir() {
66
        return workDir;
67
    }
68

  
69
    public void setWorkDir(File workDir) {
70
        this.workDir = workDir;
71
    }
72

  
73
    public ProcessManager getProcessManager() {
74
        return processManager;
75
    }
76

  
77
    public void setProcessManager(ProcessManager processManager) {
78
        this.processManager = processManager;
79
    }
80

  
81
    public long getRetryTimeout() {
82
        return retryTimeout;
83
    }
84

  
85
    public void setRetryTimeout(long retryTimeout) {
86
        this.retryTimeout = retryTimeout;
87
    }
88

  
89
    public long getRetryInterval() {
90
        return retryInterval;
91
    }
92

  
93
    public void setRetryInterval(long retryInterval) {
94
        this.retryInterval = retryInterval;
95
    }
96

  
63
	
64
	public File getTemplateProfileDir() {
65
		return templateProfileDir;
66
	}
67
	
68
	public void setTemplateProfileDir(File templateProfileDir) {
69
		this.templateProfileDir = templateProfileDir;
70
	}
71
	
72
	public File getWorkDir() {
73
		return workDir;
74
	}
75
	
76
	public void setWorkDir(File workDir) {
77
		this.workDir = workDir;
78
	}
79
	
80
	public ProcessManager getProcessManager() {
81
		return processManager;
82
	}
83
	
84
	public void setProcessManager(ProcessManager processManager) {
85
		this.processManager = processManager;
86
	}
87
	
88
	public long getRetryTimeout() {
89
		return retryTimeout;
90
	}
91
	
92
	public void setRetryTimeout(long retryTimeout) {
93
		this.retryTimeout = retryTimeout;
94
	}
95
	
96
	public long getRetryInterval() {
97
		return retryInterval;
98
	}
99
	
100
	public void setRetryInterval(long retryInterval) {
101
		this.retryInterval = retryInterval;
102
	}
103
	
97 104
}
tmp/org.txm.jodconverter.core/src/main/java/org/artofsolving/jodconverter/office/Retryable.java (revision 2406)
13 13
package org.artofsolving.jodconverter.office;
14 14

  
15 15
abstract class Retryable {
16

  
17
    /**
18
     * @throws TemporaryException for an error condition that can be temporary - i.e. retrying later could be successful
19
     * @throws Exception for all other error conditions
20
     */
21
    protected abstract void attempt() throws TemporaryException, Exception;
22

  
23
    public void execute(long interval, long timeout) throws RetryTimeoutException, Exception {
24
        execute(0L, interval, timeout);
25
    }
26

  
27
    public void execute(long delay, long interval, long timeout) throws RetryTimeoutException, Exception {
28
        long start = System.currentTimeMillis();
29
        if (delay > 0L) {
30
            sleep(delay);
31
        }
32
        while (true) {
33
            try {
34
                attempt();
35
                return;
36
            } catch (TemporaryException temporaryException) {
37
                if (System.currentTimeMillis() - start < timeout) {
38
                    sleep(interval);
39
                    // continue
40
                } else {
41
                    throw new RetryTimeoutException(temporaryException.getCause());
42
                }
43
            }
44
        }
45
    }
46

  
47
    private void sleep(long millis) {
48
        try {
49
            Thread.sleep(millis);
50
        } catch (InterruptedException interruptedException) {
51
            // continue
52
        }
53
    }
54

  
16
	
17
	/**
18
	 * @throws TemporaryException for an error condition that can be temporary - i.e. retrying later could be successful
19
	 * @throws Exception for all other error conditions
20
	 */
21
	protected abstract void attempt() throws TemporaryException, Exception;
22
	
23
	public void execute(long interval, long timeout) throws RetryTimeoutException, Exception {
24
		execute(0L, interval, timeout);
25
	}
26
	
27
	public void execute(long delay, long interval, long timeout) throws RetryTimeoutException, Exception {
28
		long start = System.currentTimeMillis();
29
		if (delay > 0L) {
30
			sleep(delay);
31
		}
32
		while (true) {
33
			try {
34
				attempt();
... Ce différentiel a été tronqué car il excède la taille maximale pouvant être affichée.

Formats disponibles : Unified diff