-
Notifications
You must be signed in to change notification settings - Fork 32
/
RemotePlantumlGenerator.java
69 lines (60 loc) · 2.75 KB
/
RemotePlantumlGenerator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
* Copyright 2016-2022 Talsma ICT
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.talsmasoftware.umldoclet.uml.plantuml;
import net.sourceforge.plantuml.FileFormat;
import net.sourceforge.plantuml.code.ArobaseStringCompressor;
import net.sourceforge.plantuml.code.AsciiEncoder;
import net.sourceforge.plantuml.code.CompressionZlib;
import net.sourceforge.plantuml.code.Transcoder;
import net.sourceforge.plantuml.code.TranscoderImpl;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Objects;
import static java.util.Objects.requireNonNull;
public class RemotePlantumlGenerator implements PlantumlGenerator {
private static final String DEFAULT_PLANTUML_BASE_URL = "https://www.plantuml.com/plantuml/";
private static final Transcoder TRANSCODER =
TranscoderImpl.utf8(new AsciiEncoder(), new ArobaseStringCompressor(), new CompressionZlib());
private final String baseUrl;
public RemotePlantumlGenerator(final String baseUrl) {
String url = Objects.toString(baseUrl, DEFAULT_PLANTUML_BASE_URL);
if (!url.endsWith("/")) url += "/";
this.baseUrl = url;
}
@Override
public void generatePlantumlDiagramFromSource(String plantumlSource, FileFormat format, OutputStream out) {
final String encodedDiagram = encodeDiagram(plantumlSource);
final String diagramUrl = baseUrl + format.name().toLowerCase() + '/' + encodedDiagram;
try (InputStream in = new URL(diagramUrl).openConnection().getInputStream()) {
final byte[] buf = new byte[4096];
for (int read = in.read(buf); read >= 0; read = in.read(buf)) {
out.write(buf, 0, read);
}
} catch (IOException | RuntimeException e) {
throw new RuntimeException(e);
}
}
private String encodeDiagram(final String diagramSource) {
try {
// TODO internalize transcoder to be able to remove PlantUML dependency altogether.
return TRANSCODER.encode(requireNonNull(diagramSource, "UML diagram source was <null>."));
} catch (IOException ioe) {
throw new IllegalStateException("Error encoding diagram: " + ioe.getMessage(), ioe);
}
}
}