Debian Codegraph @

current/fun/Foo7.java

raw symbols SCIP
1 package fun;
2
3 import java.io.PrintStream;
4 import java.text.SimpleDateFormat;
5 import java.util.Date;
6 import java.util.TimeZone;
7
8 import fileIO.ByteFile;
9 import fileIO.ByteFile1;
10 import fileIO.ByteFile2;
11 import fileIO.ByteStreamWriter;
12 import fileIO.FileFormat;
13 import fileIO.ReadWrite;
14 import shared.LineParser;
15 import shared.LineParser1;
16 import shared.LineParser2;
17 import shared.Parse;
18 import shared.Parser;
19 import shared.PreParser;
20 import shared.Shared;
21 import shared.Timer;
22 import shared.Tools;
23 import structures.LongList;
24
25 /**
26 * Reads a text file.
27 * Prints it to another text file.
28 * Filters out invalid lines and prints them to an optional third file.
29 * @author Brian Bushnell
30 * @date May 9, 2016
31 *
32 */
33 public class Foo7 {
34
35 /*--------------------------------------------------------------*/
36 /*---------------- Initialization ----------------*/
37 /*--------------------------------------------------------------*/
38
39 /**
40 * Code entrance from the command line.
41 * @param args Command line arguments
42 */
43 public static void main(String[] args){
44 //Start a timer immediately upon code entrance.
45 Timer t=new Timer();
46
47 //Create an instance of this class
48 Foo7 x=new Foo7(args);
49
50 //Run the object
51 x.process(t);
52
53 //Close the print stream if it was redirected
54 Shared.closeStream(x.outstream);
55 }
56
57 /**
58 * Constructor.
59 * @param args Command line arguments
60 */
61 public Foo7(String[] args){
62
63 {//Preparse block for help, config files, and outstream
64 PreParser pp=new PreParser(args, /*getClass()*/null, false);
65 args=pp.args;
66 outstream=pp.outstream;
67 }
68
69 //Set shared static variables prior to parsing
70 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
71 ReadWrite.setZipThreads(Shared.threads());
72
73 {//Parse the arguments
74 final Parser parser=parse(args);
75 overwrite=parser.overwrite;
76 append=parser.append;
77
78 in1=parser.in1;
79
80 out1=parser.out1;
81 }
82
83 validateParams();
84 fixExtensions(); //Add or remove .gz or .bz2 as needed
85 checkFileExistence(); //Ensure files can be read and written
86 checkStatics(); //Adjust file-related static fields as needed for this program
87
88 ffout1=FileFormat.testOutput(out1, FileFormat.TXT, null, true, overwrite, append, false);
89 ffoutInvalid=FileFormat.testOutput(outInvalid, FileFormat.TXT, null, true, overwrite, append, false);
90 ffin1=FileFormat.testInput(in1, FileFormat.TXT, null, true, true);
91 lp=(useLP2 ? new LineParser2(delimiter) : new LineParser1(delimiter));
92 }
93
94 /*--------------------------------------------------------------*/
95 /*---------------- Initialization Helpers ----------------*/
96 /*--------------------------------------------------------------*/
97
98 /** Parse arguments from the command line */
99 private Parser parse(String[] args){
100
101 //Create a parser object
102 Parser parser=new Parser();
103
104 //Set any necessary Parser defaults here
105 //parser.foo=bar;
106 // parser.out1="stdout";
107
108 //Parse each argument
109 for(int i=0; i<args.length; i++){
110 String arg=args[i];
111
112 //Break arguments into their constituent parts, in the form of "a=b"
113 String[] split=arg.split("=");
114 String a=split[0].toLowerCase();
115 String b=split.length>1 ? split[1] : null;
116 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
117
118 if(a.equals("invalid")){
119 outInvalid=b;
120 }else if(a.equals("lines")){
121 maxLines=Long.parseLong(b);
122 if(maxLines<0){maxLines=Long.MAX_VALUE;}
123 }else if(a.equals("lp2")){
124 useLP2=Parse.parseBoolean(b);
125 }else if(a.equals("verbose")){
126 verbose=Parse.parseBoolean(b);
127 ByteFile1.verbose=verbose;
128 ByteFile2.verbose=verbose;
129 ReadWrite.verbose=verbose;
130 }else if(a.equals("parse_flag_goes_here")){
131 long fake_variable=Parse.parseKMG(b);
132 //Set a variable here
133 }else if(parser.parse(arg, a, b)){
134 //do nothing
135 }else{
136 outstream.println("Unknown parameter "+args[i]);
137 assert(false) : "Unknown parameter "+args[i];
138 throw new RuntimeException("Unknown parameter "+args[i]);
139 }
140 }
141
142 return parser;
143 }
144
145 /** Add or remove .gz or .bz2 as needed */
146 private void fixExtensions(){
147 in1=Tools.fixExtension(in1);
148 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
149 }
150
151 /** Ensure files can be read and written */
152 private void checkFileExistence(){
153 //Ensure output files can be written
154 if(!Tools.testOutputFiles(overwrite, append, false, out1)){
155 outstream.println((out1==null)+", "+out1);
156 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output file "+out1+"\n");
157 }
158
159 //Ensure input files can be read
160 if(!Tools.testInputFiles(false, true, in1)){
161 throw new RuntimeException("\nCan't read some input files.\n");
162 }
163
164 //Ensure that no file was specified multiple times
165 if(!Tools.testForDuplicateFiles(true, in1, out1)){
166 throw new RuntimeException("\nSome file names were specified multiple times.\n");
167 }
168 }
169
170 /** Adjust file-related static fields as needed for this program */
171 private static void checkStatics(){
172 //Adjust the number of threads for input file reading
173 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
174 ByteFile.FORCE_MODE_BF2=true;
175 }
176
177 // if(!ByteFile.FORCE_MODE_BF2){
178 // ByteFile.FORCE_MODE_BF2=false;
179 // ByteFile.FORCE_MODE_BF1=true;
180 // }
181 }
182
183 /** Ensure parameter ranges are within bounds and required parameters are set */
184 private boolean validateParams(){
185 // assert(minfoo>0 && minfoo<=maxfoo) : minfoo+", "+maxfoo;
186 // assert(false) : "TODO";
187 return true;
188 }
189
190 /*--------------------------------------------------------------*/
191 /*---------------- Outer Methods ----------------*/
192 /*--------------------------------------------------------------*/
193
194 /** Create streams and process all data */
195 void process(Timer t){
196
197 ByteFile bf=ByteFile.makeByteFile(ffin1);
198 ByteStreamWriter bsw=makeBSW(ffout1);
199 ByteStreamWriter bswInvalid=makeBSW(ffoutInvalid);
200
201 // assert(false) : "Header goes here.";
202 if(bsw!=null){
203 // assert(false) : "Header goes here.";
204 }
205
206 processInner(bf, bsw, bswInvalid);
207
208 errorState|=bf.close();
209 if(bsw!=null){errorState|=bsw.poisonAndWait();}
210 if(bswInvalid!=null){errorState|=bswInvalid.poisonAndWait();}
211
212 t.stop();
213
214 // outstream.println(Tools.timeLinesBytesProcessed(t, linesProcessed, bytesProcessed, 8));
215 //
216 // outstream.println();
217 // outstream.println("Valid Lines: \t"+linesOut);
218 // outstream.println("Invalid Lines: \t"+(linesProcessed-linesOut));
219
220 //Throw an exception of there was an error in a thread
221 if(errorState){
222 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
223 }
224 }
225
226 /*--------------------------------------------------------------*/
227 /*---------------- Inner Methods ----------------*/
228 /*--------------------------------------------------------------*/
229
230 private void processInner(ByteFile bf, ByteStreamWriter bsw, ByteStreamWriter bswInvalid){
231
232 Timer t=new Timer();
233
234 byte[] line=bf.nextLine();
235 LongList list=new LongList(100000000);
236
237 long sum=0;
238 while(line!=null){
239 linesProcessed++;
240 bytesProcessed+=(line.length+1);
241 long size=processLine(line, list);
242 if(size>=0){sum+=size;}
243 if(linesProcessed>=maxLines) {break;}
244 line=bf.nextLine();
245 }
246
247 t.stop("parsing: ");
248 t.start();
249
250 final long tebi=1024L*1024L*1024L*1024L;
251 final long tera=1000L*1000L*1000L*1000L;
252
253 {
254 list.sort();
255 t.stop("sorting1: ");
256 t.start();
257 final int[] idxArray=new int[] {10, 20, 30, 40, 50, 60, 70, 80, 90, 95};
258 final int[] pairArray=idxArray.clone();
259 for(int i=0; i<idxArray.length; i++) {pairArray[i]=(int)(idxArray[i]*.01*list.size);}
260 long tsum=0;
261
262 for(int i=0, nextIdx=0, nextPair=pairArray[0]; i<list.size && nextIdx<idxArray.length; i++) {
263 final long v=list.get(i);
264 final long size=getSize(v), time=getTime(v);
265 tsum+=size;
266 if(i>=nextPair) {
267 String s=idxArray[nextIdx]+" percent of files have not been accessed since: "+
268 timeString(time*1000)+" ("+(tsum/tebi)+" tebibytes)";
269 System.out.println(s);
270 nextIdx++;
271 if(nextIdx<idxArray.length) {nextPair=pairArray[nextIdx];}
272 }
273 }
274 t.stop("stats1: ");
275 t.start();
276 }
277
278 for(int i=0; i<list.size; i++) {list.array[i]=getSize(list.array[i]);}
279 t.stop("recoding: ");
280 t.start();
281 list.sort();
282 t.stop("sorting2: ");
283 t.start();
284 long mean=sum/list.size;
285 long median=list.get((int)(list.size*0.5));
286 System.out.println("total size: \t"+(sum/tera)+" TB \t("+sum+")"+"\t"+"("+((sum/tebi))+" tebibytes)");
287 System.out.println("mean size: \t"+mean+" bytes");
288 System.out.println("P50 size: \t"+median+" bytes");
289 System.out.println("P80 size: \t"+list.get((int)(list.size*0.8))+" bytes");
290 System.out.println("P90 size: \t"+list.get((int)(list.size*0.9))+" bytes");
291 System.out.println("P95 size: \t"+list.get((int)(list.size*0.95))+" bytes");
292 t.stop("stats2: ");
293 t.start();
294 }
295
296 long processLine(byte[] line, LongList list) {
297 lp.set(line, 11);
298
299 long size=lp.parseLong(3);
300 byte type=lp.parseByte(6, 0);
301 if(type!='F') {return -1;}
302
303 long time=lp.parseLong(11);
304
305 linesOut++;
306 list.add(combine(time, size));
307 return size;
308 }
309
310 private static ByteStreamWriter makeBSW(FileFormat ff){
311 if(ff==null){return null;}
312 ByteStreamWriter bsw=new ByteStreamWriter(ff);
313 bsw.start();
314 return bsw;
315 }
316
317 static String timeString(long time){
318 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
319 sdf.setTimeZone(TimeZone.getTimeZone("PST"));
320 // sdf.setTimeZone(TimeZone.getDefault());
321 return sdf.format(new Date(time));
322 }
323
324 static final int LOWER_BITS=31;
325 static final int MANTISSA_BITS=24;
326 static final int EXP_BITS=LOWER_BITS-MANTISSA_BITS;
327 static final int UPPER_BITS=64-MANTISSA_BITS;
328 static final long LOWER_MASK=~((-1L)<<LOWER_BITS);
329 static final long MANTISSA_MASK=~((-1L)<<MANTISSA_BITS);
330 static final long compress(long raw) {
331 if(raw<=MANTISSA_MASK){return raw;}
332 int leading=Long.numberOfLeadingZeros(raw);
333 int exp=UPPER_BITS-leading;
334 assert(exp>=1);
335 return (raw>>>exp)|(exp<<MANTISSA_BITS);
336 }
337 static final long decompress(long f) {
338 if(f<=MANTISSA_MASK){return f;}
339 int exp=(int)(f>>>MANTISSA_BITS);
340 assert(exp>=1);
341 return (f&MANTISSA_MASK)<<exp;
342 }
343 static final long combine(long time, long size) {
344 return (time<<LOWER_BITS) | compress(size);
345 }
346 static final long getTime(long combined) {
347 return combined>>>LOWER_BITS;
348 }
349 static final long getSize(long combined) {
350 return decompress(combined&LOWER_MASK);
351 }
352
353 /*--------------------------------------------------------------*/
354 /*---------------- Fields ----------------*/
355 /*--------------------------------------------------------------*/
356
357 /** Primary input file path */
358 private String in1=null;
359
360 /** Primary output file path */
361 private String out1=null;
362
363 /** Junk output file path */
364 private String outInvalid=null;
365
366 private boolean useLP2=false;
367
368 private static final byte delimiter=(byte)'|';
369 private final LineParser lp;
370
371 /*--------------------------------------------------------------*/
372
373 private long linesProcessed=0;
374 private long linesOut=0;
375 private long bytesProcessed=0;
376 private long bytesOut=0;
377
378 private long maxLines=Long.MAX_VALUE;
379
380 /*--------------------------------------------------------------*/
381 /*---------------- Final Fields ----------------*/
382 /*--------------------------------------------------------------*/
383
384 /** Input File */
385 private final FileFormat ffin1;
386 /** Output File */
387 private final FileFormat ffout1;
388 /** Optional Output File for Junk */
389 private final FileFormat ffoutInvalid;
390
391 /*--------------------------------------------------------------*/
392 /*---------------- Common Fields ----------------*/
393 /*--------------------------------------------------------------*/
394
395 /** Print status messages to this output stream */
396 private PrintStream outstream=System.err;
397 /** Print verbose messages */
398 public static boolean verbose=false;
399 /** True if an error was encountered */
400 public boolean errorState=false;
401 /** Overwrite existing output files */
402 private boolean overwrite=true;
403 /** Append to existing output files */
404 private boolean append=false;
405
406 }