/
TranslatorManagerImpl.java
273 lines (234 loc) · 9.89 KB
/
TranslatorManagerImpl.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/**
*
* Copyright (c) 2006-2016, Speedment, Inc. All Rights Reserved.
*
* 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 com.speedment.generator.internal;
import com.speedment.common.codegen.Generator;
import com.speedment.common.codegen.Meta;
import com.speedment.common.codegen.internal.java.JavaGenerator;
import com.speedment.common.codegen.internal.util.Formatting;
import com.speedment.common.codegen.model.File;
import com.speedment.generator.Translator;
import com.speedment.generator.TranslatorManager;
import com.speedment.generator.component.CodeGenerationComponent;
import com.speedment.generator.event.AfterGenerate;
import com.speedment.generator.event.BeforeGenerate;
import com.speedment.generator.event.FileGenerated;
import com.speedment.generator.component.EventComponent;
import com.speedment.runtime.config.Project;
import com.speedment.runtime.config.Table;
import com.speedment.runtime.config.trait.HasEnabled;
import com.speedment.runtime.exception.SpeedmentException;
import com.speedment.runtime.internal.util.Statistics;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import com.speedment.generator.internal.util.HashUtil;
import com.speedment.runtime.component.InfoComponent;
import java.nio.file.DirectoryStream;
import java.util.stream.Stream;
import static com.speedment.common.codegen.internal.util.NullUtil.requireNonNulls;
import com.speedment.internal.common.injector.annotation.Inject;
import com.speedment.internal.common.logger.Logger;
import com.speedment.internal.common.logger.LoggerManager;
import static com.speedment.runtime.internal.util.document.DocumentDbUtil.traverseOver;
import static java.util.Objects.requireNonNull;
/**
*
* @author Per Minborg
* @author Emil Forslund
*/
public class TranslatorManagerImpl implements TranslatorManager {
private final static Logger LOGGER = LoggerManager.getLogger(TranslatorManagerImpl.class);
private final static String HASH_PREFIX = ".";
private final static String HASH_SUFFIX = ".md5";
private final static boolean PRINT_CODE = false;
private final AtomicInteger fileCounter = new AtomicInteger(0);
private @Inject InfoComponent info;
private @Inject EventComponent eventComponent;
private @Inject CodeGenerationComponent codeGenerationComponent;
protected TranslatorManagerImpl() {}
@Override
public void accept(Project project) {
requireNonNull(project);
Statistics.onGenerate();
final List<Translator<?, ?>> writeOnceTranslators = new ArrayList<>();
final List<Translator<?, ?>> writeAlwaysTranslators = new ArrayList<>();
final Generator gen = new JavaGenerator();
fileCounter.set(0);
Formatting.tab(" ");
eventComponent.notify(new BeforeGenerate(project, gen, this));
codeGenerationComponent.translators(project)
.forEachOrdered(t -> {
if (t.isInGeneratedPackage()) {
writeAlwaysTranslators.add(t);
} else {
writeOnceTranslators.add(t);
}
});
traverseOver(project, Table.class)
.filter(HasEnabled::test)
.forEach(table -> {
codeGenerationComponent.translators(table).forEachOrdered(t -> {
if (t.isInGeneratedPackage()) {
writeAlwaysTranslators.add(t);
} else {
writeOnceTranslators.add(t);
}
});
});
// Erase any previous unmodified files.
clearExistingFiles(project);
// Write generated code to file.
gen.metaOn(writeOnceTranslators.stream()
.map(Translator::get)
.collect(Collectors.toList())
).forEach(meta -> writeToFile(project, meta, false));
gen.metaOn(writeAlwaysTranslators.stream()
.map(Translator::get)
.collect(Collectors.toList())
).forEach(meta -> writeToFile(project, meta, true));
eventComponent.notify(new AfterGenerate(project, gen, this));
}
@Override
public void clearExistingFiles(Project project) {
final Path dir = Paths.get(project.getPackageLocation());
try {
clearExistingFilesIn(dir);
} catch (final IOException ex) {
throw new SpeedmentException(
"Error! Could not delete files in '" + dir.toString() + "'.", ex
);
}
}
private void clearExistingFilesIn(Path directory) throws IOException {
if (Files.exists(directory)) {
try (final DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
for (final Path entry : stream) {
if (Files.isDirectory(entry)) {
clearExistingFilesIn(entry);
if (isDirectoryEmpty(entry)) {
Files.delete(entry);
}
} else {
final String filename = entry.toFile().getName();
if (filename.startsWith(HASH_PREFIX)
&& filename.endsWith(HASH_SUFFIX)) {
final Path original
= entry
.getParent() // The hidden folder
.getParent() // The parent folder
.resolve(filename.substring( // Lookup original .java file
HASH_PREFIX.length(),
filename.length() - HASH_SUFFIX.length()
));
if (original.toFile().exists()
&& HashUtil.compare(original, entry)) {
delete(original);
delete(entry);
}
}
}
}
}
}
}
private static void delete(Path path) throws IOException {
LOGGER.info("Deleting '" + path.toString() + "'.");
Files.delete(path);
}
private static boolean isDirectoryEmpty(Path directory) throws IOException {
try (final DirectoryStream<Path> dirStream = Files.newDirectoryStream(directory)) {
return !dirStream.iterator().hasNext();
}
}
@Override
public void writeToFile(Project project, Meta<File, String> meta, boolean overwriteExisting) {
eventComponent.notify(new FileGenerated(project, meta));
writeToFile(project, meta.getModel().getName(), meta.getResult(), overwriteExisting);
}
@Override
public void writeToFile(Project project, String filename, String content, boolean overwriteExisting) {
final String fname = project.getPackageLocation() + "/" + filename;
writeToFile(Paths.get(fname), content, overwriteExisting);
}
@Override
public void writeToFile(Path codePath, String content, boolean overwriteExisting) {
requireNonNulls(codePath, content);
try {
if (overwriteExisting || !codePath.toFile().exists()) {
final Path hashPath = codePath.getParent()
.resolve(secretFolderName())
.resolve(HASH_PREFIX + codePath.getFileName().toString() + HASH_SUFFIX);
write(hashPath, HashUtil.md5(content), true);
write(codePath, content, false);
fileCounter.incrementAndGet();
}
} catch (final IOException ex) {
LOGGER.error(ex, "Failed to write file " + codePath);
}
if (PRINT_CODE) {
LOGGER.info("*** BEGIN File:" + codePath);
Stream.of(content.split(Formatting.nl())).forEachOrdered(LOGGER::info);
LOGGER.info("*** END File:" + codePath);
}
}
@Override
public int getFilesCreated() {
return fileCounter.get();
}
private static void write(Path path, String content, boolean hidden) throws IOException {
LOGGER.info("Creating '" + path.toString() + "'.");
final Path parent = path.getParent();
try {
if (parent != null) {
Files.createDirectories(parent);
if (hidden) {
setAttributeHidden(parent);
}
}
} catch (final SecurityException se) {
throw new SpeedmentException("Unable to create directory " + parent.toString(), se);
}
Files.write(path, content.getBytes(StandardCharsets.UTF_8),
StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING
);
if (hidden) {
setAttributeHidden(path);
}
}
private static void setAttributeHidden(Path path) {
try {
Files.setAttribute(path, "dos:hidden", true);
} catch (IOException | UnsupportedOperationException e) {
// Ignore. Maybe this is Linux or MacOS
}
}
private String secretFolderName() {
return "." + info.title()
.replace(" ", "")
.replace(".", "")
.replace("/", "")
.toLowerCase();
}
}