Last active
November 27, 2015 17:37
-
-
Save jabu10245/80351433704e79d4fa2e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SqlAsset implements Asset { | |
private final InputStream stream; | |
private SqlAsset(InputStream stream) { | |
this.stream = Objects.requireNonNull(stream); | |
} | |
public static Asset parse(String ... filenames) { | |
InputStream[] streams = new InputStream[filenames.length]; | |
ClassLoader loader = SqlAsset.class.getClassLoader(); | |
for (int i = 0; i < filenames.length; i++) { | |
streams[i] = loader.getResourceAsStream(filenames[i]); | |
} | |
return parse(streams); | |
} | |
public static Asset parse(InputStream ... streams) { | |
final StringBuffer buffer = new StringBuffer(); | |
boolean waitForDoubleDollars = false; | |
for (InputStream stream : streams) { | |
Objects.requireNonNull(stream); | |
try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, Charsets.UTF_8))) { | |
String line; | |
while ((line = reader.readLine()) != null) { | |
line = StringUtils.trimToNull(line); | |
if (line == null || line.startsWith("--")) { | |
continue; | |
} else if (!waitForDoubleDollars && line.endsWith("$$")) { | |
waitForDoubleDollars = true; | |
buffer.append(line).append(' '); | |
} else if (waitForDoubleDollars && line.startsWith("$$")) { | |
waitForDoubleDollars = false; | |
buffer.append(line).append(line.endsWith(";") ? '\n' : ' '); | |
} else if (!waitForDoubleDollars && line.endsWith(";")) { | |
buffer.append(line).append('\n'); | |
} else { | |
buffer.append(line).append(' '); | |
} | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
String sql = buffer.toString(); | |
return new SqlAsset(new ByteArrayInputStream(sql.getBytes(Charsets.UTF_8))); | |
} | |
@Override | |
public InputStream openStream() { | |
return stream; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using apache commons-lang and commons-codec for this.