TraceReader.java
Home
/
src /
main /
java /
br /
ufrgs /
inf /
prosoft /
trace /
TraceReader.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.ufrgs.inf.prosoft.trace;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
/**
*
* @author romulo
*/
public class TraceReader {
private static final Logger logger = Logger.getLogger(TraceReader.class.getName());
public static List<Trace> partiallyParseFile(String path) {
Traces.PATH = path;
return parseFile(path, true);
}
public static List<Trace> parseFile(String path) {
return parseFile(path, false);
}
public static String getLineCount(String path) throws IOException {
try {
Process process = Runtime.getRuntime().exec("wc -l " + path);
Thread.sleep(2000);
if (process.isAlive()) {
return "timeout";
}
InputStream inputStream = process.getInputStream();
StringBuilder count = new StringBuilder();
int c;
while (true) {
c = inputStream.read();
if (c == 32 || c == -1 || c == 10) {
break;
}
count.append((char) c);
}
return count.toString();
} catch (Exception ex) {
return ex.getMessage();
}
}
private static List<Trace> parseFile(String path, boolean partial) {
List<Trace> traces = new ArrayList<>();
try {
logger.log(Level.INFO, "Parsing {0} traces", getLineCount(path));
Stream<String> lines = Files.lines(Paths.get(path));
Gson gson = new Gson();
lines.forEach(new Consumer<String>() {
int index = 0;
@Override
public void accept(String line) {
try {
Trace trace;
if (partial) {
trace = gson.fromJson(line, TraceReference.class);
((TraceReference) trace).setIndex(index);
} else {
trace = gson.fromJson(line, TraceConcrete.class);
}
traces.add(trace);
System.out.print(".");
System.out.flush();
if (index != 0 && index % 100 == 0) {
System.out.println();
}
} catch (JsonSyntaxException e) {
if (line.length() > 2000) {
line = line.substring(0, 2000);
}
logger.log(Level.INFO, "\nMalformed Trace {0}: {1}", new java.lang.Object[]{index, line});
} finally {
index++;
}
}
});
System.out.println();
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
}
return traces;
}
}