com.martiansoftware.jsap.Switch Java Examples

The following examples show how to use com.martiansoftware.jsap.Switch. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GZIPArchiveWriterTest.java    From BUbiNG with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException, JSAPException {

	SimpleJSAP jsap = new SimpleJSAP(GZIPArchiveReader.class.getName(), "Writes some random records on disk.",
		new Parameter[] {
			new Switch("fully", 'f', "fully",
				"Whether to read fully the record (and do a minimal cosnsistency check)."),
			new UnflaggedOption("path", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY,
				"The path to read from."), });

	JSAPResult jsapResult = jsap.parse(args);
	if (jsap.messagePrinted())
	    System.exit(1);

	final boolean fully = jsapResult.getBoolean("fully");
	GZIPArchiveReader gzar = new GZIPArchiveReader(new FileInputStream(jsapResult.getString("path")));
	for (;;) {
	    ReadEntry e = gzar.getEntry();
	    if (e == null)
		break;
	    InputStream inflater = e.lazyInflater.get();
	    if (fully)
		ByteStreams.toByteArray(inflater);
	    e.lazyInflater.consume();
	    System.out.println(e);
	}
    }
 
Example #2
Source File: LauncherUtils.java    From repairnator with MIT License 5 votes vote down vote up
public static Switch defineArgCreatePR() {
    Switch sw = new Switch("createPR");
    sw.setLongFlag("createPR");
    sw.setDefault("false");
    sw.setHelp("Activate the creation of a Pull Request in case of patch.");
    return sw;
}
 
Example #3
Source File: LiterallySignedStringMap.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static void main( final String[] arg ) throws IOException, JSAPException, ClassNotFoundException, SecurityException, NoSuchMethodException {

	final SimpleJSAP jsap = new SimpleJSAP( LiterallySignedStringMap.class.getName(), "Builds a shift-add-xor signed string map by reading a newline-separated list of strings and a function built on the same list of strings.",
			new Parameter[] {
		new FlaggedOption( "encoding", ForNameStringParser.getParser( Charset.class ), "UTF-8", JSAP.NOT_REQUIRED, 'e', "encoding", "The string file encoding." ),
		new Switch( "zipped", 'z', "zipped", "The string list is compressed in gzip format." ),
		new Switch( "text", 't', "text", "The string list actually a text file, with one string per line." ),
		new UnflaggedOption( "function", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The filename of the function to be signed." ),
		new UnflaggedOption( "list", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The filename of the serialised list of strings, or of a text file containing a list of strings, if -t is specified." ),
		new UnflaggedOption( "map", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The filename of the resulting map." ),
	});

	JSAPResult jsapResult = jsap.parse( arg );
	if ( jsap.messagePrinted() ) return;

	final String functionName = jsapResult.getString( "function" );
	final String listName = jsapResult.getString( "list" );
	final String mapName = jsapResult.getString( "map" );

	
	final Charset encoding = (Charset)jsapResult.getObject( "encoding" );
	final boolean zipped = jsapResult.getBoolean( "zipped" );
	final boolean text = jsapResult.getBoolean( "text" );
	
	ObjectList<MutableString> list = text ? new FileLinesCollection( listName, encoding.toString(), zipped ).allLines() : (ObjectList)BinIO.loadObject( listName );
	
	LOGGER.info( "Signing..." );
	BinIO.storeObject( new LiterallySignedStringMap( (Object2LongFunction)BinIO.loadObject( functionName ), list ), mapName );
	LOGGER.info( "Completed." );
}
 
Example #4
Source File: FrontCodedStringList.java    From database with GNU General Public License v2.0 5 votes vote down vote up
public static void main( final String[] arg ) throws IOException, JSAPException, NoSuchMethodException {
	
	final SimpleJSAP jsap = new SimpleJSAP( FrontCodedStringList.class.getName(), "Builds a front-coded string list reading from standard input a newline-separated ordered list of terms.",
			new Parameter[] {
				new FlaggedOption( "bufferSize", IntSizeStringParser.getParser(), "64Ki", JSAP.NOT_REQUIRED, 'b',  "buffer-size", "The size of the I/O buffer used to read terms." ),
				new FlaggedOption( "encoding", ForNameStringParser.getParser( Charset.class ), "UTF-8", JSAP.NOT_REQUIRED, 'e', "encoding", "The term file encoding." ),
				new FlaggedOption( "ratio", IntSizeStringParser.getParser(), "4", JSAP.NOT_REQUIRED, 'r',  "ratio", "The compression ratio." ),
				new Switch( "utf8", 'u', "utf8", "Store the strings as UTF-8 byte arrays." ),
				new Switch( "zipped", 'z', "zipped", "The term list is compressed in gzip format." ),
				new UnflaggedOption( "frontCodedList", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The filename for the serialised front-coded list." )
	});
	
	JSAPResult jsapResult = jsap.parse( arg );
	if ( jsap.messagePrinted() ) return;
	
	final int bufferSize = jsapResult.getInt( "bufferSize" );
	final int ratio = jsapResult.getInt( "ratio" );
	final boolean utf8 = jsapResult.getBoolean( "utf8" );
	final boolean zipped = jsapResult.getBoolean( "zipped" );
	final String listName = jsapResult.getString( "frontCodedList" );
	final Charset encoding = (Charset)jsapResult.getObject( "encoding" );
	
	final ProgressLogger pl = new ProgressLogger();
	pl.itemsName = "words";
	pl.start( "Reading words..." );
	final FrontCodedStringList frontCodedStringList = new FrontCodedStringList( new LineIterator( new FastBufferedReader( 
			new InputStreamReader( zipped ? new GZIPInputStream( System.in ) : System.in, encoding ), bufferSize ), pl ), ratio, utf8 );
	pl.done();

	System.err.print( "Writing to file..." );
	BinIO.storeObject( frontCodedStringList, listName );
	System.err.println( " done." );
}
 
Example #5
Source File: ShiftAddXorSignedStringMap.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static void main( final String[] arg ) throws NoSuchMethodException, IOException, JSAPException, ClassNotFoundException {

	final SimpleJSAP jsap = new SimpleJSAP( ShiftAddXorSignedStringMap.class.getName(), "Builds a shift-add-xor signed string map by reading a newline-separated list of strings and a function built on the same list of strings.",
			new Parameter[] {
		new FlaggedOption( "bufferSize", JSAP.INTSIZE_PARSER, "64Ki", JSAP.NOT_REQUIRED, 'b',  "buffer-size", "The size of the I/O buffer used to read strings." ),
		new FlaggedOption( "encoding", ForNameStringParser.getParser( Charset.class ), "UTF-8", JSAP.NOT_REQUIRED, 'e', "encoding", "The string file encoding." ),
		new Switch( "zipped", 'z', "zipped", "The string list is compressed in gzip format." ),
		new FlaggedOption( "width", JSAP.INTEGER_PARSER, Integer.toString( Integer.SIZE ), JSAP.NOT_REQUIRED, 'w', "width", "The signature width in bits." ),
		new UnflaggedOption( "function", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The filename of the function to be signed." ),
		new UnflaggedOption( "map", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The filename of the resulting serialised signed string map." ),
		new UnflaggedOption( "stringFile", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, JSAP.NOT_GREEDY, "Read strings from this file instead of standard input." ),
	});

	JSAPResult jsapResult = jsap.parse( arg );
	if ( jsap.messagePrinted() ) return;

	final int bufferSize = jsapResult.getInt( "bufferSize" );
	final String functionName = jsapResult.getString( "function" );
	final String mapName = jsapResult.getString( "map" );
	final String stringFile = jsapResult.getString( "stringFile" );
	final Charset encoding = (Charset)jsapResult.getObject( "encoding" );
	final int width = jsapResult.getInt( "width" );
	final boolean zipped = jsapResult.getBoolean( "zipped" );

	final InputStream inputStream = stringFile != null ? new FileInputStream( stringFile ) : System.in;
	final Iterator<MutableString> iterator = new LineIterator( new FastBufferedReader( new InputStreamReader( zipped ? new GZIPInputStream( inputStream ) : inputStream, encoding ), bufferSize ) );
	final Object2LongFunction<CharSequence> function = (Object2LongFunction<CharSequence>)BinIO.loadObject( functionName );
	LOGGER.info( "Signing..." );
	BinIO.storeObject( new ShiftAddXorSignedStringMap( iterator, function, width ), mapName );
	LOGGER.info( "Completed." );
}
 
Example #6
Source File: PermutedFrontCodedStringList.java    From database with GNU General Public License v2.0 5 votes vote down vote up
public static void main( final String[] arg ) throws IOException, ClassNotFoundException, JSAPException {

		SimpleJSAP jsap = new SimpleJSAP( PermutedFrontCodedStringList.class.getName(), "Builds a permuted front-coded list of strings using a given front-coded string list and permutation",  
				new Parameter[] {
					new Switch( "invert", 'i', "invert", "Invert permutation before creating the permuted list." ),
					new UnflaggedOption( "list", JSAP.STRING_PARSER, JSAP.REQUIRED, "A front-coded string list." ),
					new UnflaggedOption( "permutation", JSAP.STRING_PARSER, JSAP.REQUIRED, "A permutation for the indices of the list." ),
					new UnflaggedOption( "permutedList", JSAP.STRING_PARSER, JSAP.REQUIRED, "A the filename for the resulting permuted list." ),
			} );

		JSAPResult jsapResult = jsap.parse( arg ); 
		if ( jsap.messagePrinted() ) return;
		
		int[] basePermutation =  BinIO.loadInts( jsapResult.getString( "permutation" ) ), permutation;
		if ( jsapResult.getBoolean( "invert" ) ) {
			int i = basePermutation.length;
			permutation = new int[ i ];
			while( i-- != 0 ) permutation[ basePermutation[ i ] ] = i;
		}
		else permutation = basePermutation;
		
		basePermutation = null;
		
		BinIO.storeObject( 
				new PermutedFrontCodedStringList( (FrontCodedStringList)BinIO.loadObject( jsapResult.getString( "list" ) ), permutation ), 
				jsapResult.getString( "permutedList" ) 
		);
	}
 
Example #7
Source File: LauncherUtils.java    From repairnator with MIT License 5 votes vote down vote up
public static Switch defineArgSkipDelete() {
    Switch sw = new Switch("skipDelete");
    sw.setLongFlag("skipDelete");
    sw.setDefault("false");
    sw.setHelp("Skip the deletion of docker container.");
    return sw;
}
 
Example #8
Source File: LauncherUtils.java    From repairnator with MIT License 5 votes vote down vote up
public static Switch defineArgCreateOutputDir() {
    Switch sw = new Switch("createOutputDir");
    sw.setLongFlag("createOutputDir");
    sw.setDefault("false");
    sw.setHelp("Create a specific directory for output.");
    return sw;
}
 
Example #9
Source File: LauncherUtils.java    From repairnator with MIT License 5 votes vote down vote up
public static Switch defineArgSmtpTLS() {
    Switch sw = new Switch("smtpTLS");
    sw.setLongFlag("smtpTLS");
    sw.setDefault("false");
    sw.setHelp("Decides whether to use TLS for email communication.");
    return sw;
}
 
Example #10
Source File: LauncherUtils.java    From repairnator with MIT License 5 votes vote down vote up
public static Switch defineArgBearsMode() {
    Switch sw = new Switch("bears");
    sw.setLongFlag("bears");
    sw.setDefault("false");
    sw.setHelp("This mode allows to use repairnator to analyze pairs of bugs and human-produced patches.");
    return sw;
}
 
Example #11
Source File: LauncherUtils.java    From repairnator with MIT License 5 votes vote down vote up
public static Switch defineArgCheckstyleMode() {
    Switch sw = new Switch("checkstyle");
    sw.setLongFlag("checkstyle");
    sw.setDefault("false");
    sw.setHelp("This mode allows to use repairnator to analyze build failing because of checkstyle.");
    return sw;
}
 
Example #12
Source File: Agent.java    From BUbiNG with Apache License 2.0 5 votes vote down vote up
public static void main(final String arg[]) throws Exception {
	final SimpleJSAP jsap = new SimpleJSAP(Agent.class.getName(), "Starts a BUbiNG agent (note that you must enable JMX by means of the standard Java system properties).",
			new Parameter[] {
				new FlaggedOption("weight", JSAP.INTEGER_PARSER, "1", JSAP.NOT_REQUIRED, 'w', "weight", "The agent weight."),
				new FlaggedOption("group", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'g', "group", "The JGroups group identifier (must be the same for all cooperating agents)."),
				new FlaggedOption("jmxHost", JSAP.STRING_PARSER, InetAddress.getLocalHost().getHostAddress(), JSAP.REQUIRED, 'h', "jmx-host", "The IP address (possibly specified by a host name) that will be used to expose the JMX RMI connector to other agents."),
				new FlaggedOption("rootDir", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'r', "root-dir", "The root directory."),
				new Switch("new", 'n', "new", "Start a new crawl"),
				new FlaggedOption("properties", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'P', "properties", "The properties used to configure the agent."),
				new UnflaggedOption("name", JSAP.STRING_PARSER, JSAP.REQUIRED, "The agent name (an identifier that must be unique across the group).")
		});

		final JSAPResult jsapResult = jsap.parse(arg);
		if (jsap.messagePrinted()) System.exit(1);

		// JMX *must* be set up.
		final String portProperty = System.getProperty(JMX_REMOTE_PORT_SYSTEM_PROPERTY);
		if (portProperty == null) throw new IllegalArgumentException("You must specify a JMX service port using the property " + JMX_REMOTE_PORT_SYSTEM_PROPERTY);

		final String name = jsapResult.getString("name");
		final int weight = jsapResult.getInt("weight");
		final String group = jsapResult.getString("group");
		final String host = jsapResult.getString("jmxHost");
		final int port = Integer.parseInt(portProperty);

		final BaseConfiguration additional = new BaseConfiguration();
		additional.addProperty("name", name);
		additional.addProperty("group", group);
		additional.addProperty("weight", Integer.toString(weight));
		additional.addProperty("crawlIsNew", Boolean.valueOf(jsapResult.getBoolean("new")));
		if (jsapResult.userSpecified("rootDir")) additional.addProperty("rootDir", jsapResult.getString("rootDir"));

		new Agent(host, port, new RuntimeConfiguration(new StartupConfiguration(jsapResult.getString("properties"), additional)));
		System.exit(0); // Kills remaining FetchingThread instances, if any.
}
 
Example #13
Source File: LauncherUtils.java    From repairnator with MIT License 5 votes vote down vote up
public static Switch defineArgNotifyEndProcess() {
    Switch sw = new Switch("notifyEndProcess");
    sw.setLongFlag("notifyEndProcess");
    sw.setDefault("false");
    sw.setHelp("Activate the notification when the process ends.");
    return sw;
}
 
Example #14
Source File: LauncherUtils.java    From repairnator with MIT License 5 votes vote down vote up
public static Switch defineArgDebug() {
    Switch sw = new Switch("debug");
    sw.setShortFlag('d');
    sw.setLongFlag("debug");
    sw.setDefault("false");
    return sw;
}
 
Example #15
Source File: LauncherUtils.java    From repairnator with MIT License 5 votes vote down vote up
public static Switch defineArgHelp() {
    Switch sw = new Switch("help");
    sw.setShortFlag('h');
    sw.setLongFlag("help");
    sw.setDefault("false");
    return sw;
}
 
Example #16
Source File: GitRepositoryLauncherUtils.java    From repairnator with MIT License 5 votes vote down vote up
public static Switch defineArgGitRepositoryFirstCommit() {
    Switch sw = new Switch("gitRepositoryFirstCommit");
    sw.setLongFlag("gitrepofirstcommit");
    sw.setDefault("false");
    sw.setHelp("Decides whether to clone the first commit of the specified branch (only in GIT_REPOSITORY mode).");
    return sw;
}
 
Example #17
Source File: GitRepositoryLauncherUtils.java    From repairnator with MIT License 5 votes vote down vote up
public static Switch defineArgGitRepositoryMode() {
    Switch sw = new Switch("gitRepo");
    sw.setLongFlag("gitrepo");
    sw.setDefault("false");
    sw.setHelp("This mode allows to use Repairnator to analyze bugs present in a Git repository.");
    return sw;
}
 
Example #18
Source File: RandomReadWritesTest.java    From BUbiNG with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws JSAPException, IOException, InterruptedException {
	final SimpleJSAP jsap = new SimpleJSAP(RandomReadWritesTest.class.getName(), "Writes some random records on disk.",
		new Parameter[] {
			new FlaggedOption("random", JSAP.INTEGER_PARSER, "100", JSAP.NOT_REQUIRED, 'r', "random", "The number of random record to sample from."),
			new FlaggedOption("body", JSAP.INTSIZE_PARSER, "4K", JSAP.NOT_REQUIRED, 'b', "body", "The maximum size of the random generated body (in bytes)."),
			new Switch("fully", 'f', "fully", "Whether to read fully the record (and do a minimal sequential cosnsistency check)."),
			new Switch("writeonly", 'w', "writeonly", "Whether to skip the read part (if present, 'fully' will be ignored."),
			new UnflaggedOption("path", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The path to write to."),
			new UnflaggedOption("records", JSAP.INTSIZE_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The numer of records to write."),
	});

	final JSAPResult jsapResult = jsap.parse(args);
	if (jsap.messagePrinted()) System.exit(1);

	final String path = jsapResult.getString("path");
	final boolean compress = path.endsWith(".gz");
	final boolean fully = jsapResult.getBoolean("fully");
	final int parallel = compress ? 1 : 0;

	final int body = jsapResult.getInt("body");

	final WarcRecord[] rnd = prepareRndRecords(jsapResult.getInt("random"), RESPONSE_PROBABILITY, MAX_NUMBER_OF_HEADERS, MAX_LENGTH_OF_HEADER, body);
	final int[] sequence = writeRecords(path, jsapResult.getInt("records"), rnd, parallel);
	if (! jsapResult.getBoolean("writeonly"))
		readRecords(path, sequence, body, fully, compress);

}
 
Example #19
Source File: CheckBranchLauncher.java    From repairnator with MIT License 4 votes vote down vote up
private JSAP defineArgs() throws JSAPException {
    // Verbose output
    JSAP jsap = new JSAP();

    // -h or --help
    jsap.registerParameter(LauncherUtils.defineArgHelp());
    // -d or --debug
    jsap.registerParameter(LauncherUtils.defineArgDebug());
    // --runId
    jsap.registerParameter(LauncherUtils.defineArgRunId());
    // --bears
    jsap.registerParameter(LauncherUtils.defineArgBearsMode());
    // -i or --input
    jsap.registerParameter(LauncherUtils.defineArgBranchInput());
    // -o or --output
    jsap.registerParameter(LauncherUtils.defineArgOutput(LauncherType.CHECKBRANCHES, "Specify where to put output data"));
    // --notifyEndProcess
    jsap.registerParameter(LauncherUtils.defineArgNotifyEndProcess());
    // --smtpServer
    jsap.registerParameter(LauncherUtils.defineArgSmtpServer());
    //--smtpPort
    jsap.registerParameter(LauncherUtils.defineArgSmtpPort());
    //--smtpTLS
    jsap.registerParameter(LauncherUtils.defineArgSmtpTLS());
    // --smtpUsername
    jsap.registerParameter(LauncherUtils.defineArgSmtpUsername());
    // --smtpPassword
    jsap.registerParameter(LauncherUtils.defineArgSmtpPassword());
    // --notifyto
    jsap.registerParameter(LauncherUtils.defineArgNotifyto());
    // -n or --name
    jsap.registerParameter(LauncherUtils.defineArgDockerImageName());
    // --skipDelete
    jsap.registerParameter(LauncherUtils.defineArgSkipDelete());
    // -t or --threads
    jsap.registerParameter(LauncherUtils.defineArgNbThreads());
    // -g or --globalTimeout
    jsap.registerParameter(LauncherUtils.defineArgGlobalTimeout());

    Switch sw1 = new Switch("humanPatch");
    sw1.setShortFlag('p');
    sw1.setLongFlag("humanPatch");
    sw1.setDefault("false");
    jsap.registerParameter(sw1);

    FlaggedOption opt2 = new FlaggedOption("repository");
    opt2.setShortFlag('r');
    opt2.setLongFlag("repository");
    opt2.setStringParser(JSAP.STRING_PARSER);
    opt2.setRequired(true);
    opt2.setHelp("Specify where to collect branches");
    jsap.registerParameter(opt2);

    return jsap;
}
 
Example #20
Source File: ImmutableExternalPrefixMap.java    From database with GNU General Public License v2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public static void main( final String[] arg ) throws ClassNotFoundException, IOException, JSAPException, SecurityException, NoSuchMethodException {

	final SimpleJSAP jsap = new SimpleJSAP( ImmutableExternalPrefixMap.class.getName(), "Builds an external map reading from standard input a newline-separated list of terms or a serialised term list. If the dump stream name is not specified, the map will be self-contained.", 
			new Parameter[] {
				new FlaggedOption( "blockSize", JSAP.INTSIZE_PARSER, ( STD_BLOCK_SIZE / 1024 ) + "Ki", JSAP.NOT_REQUIRED, 'b', "block-size", "The size of a block in the dump stream." ),
				new Switch( "serialised", 's', "serialised", "The data source (file or standard input) provides a serialised java.util.List of terms." ),
				new Switch( "zipped", 'z', "zipped", "Standard input is compressed in gzip format." ),
				new FlaggedOption( "termFile", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'o', "offline", "Read terms from this file instead of standard input." ),					
				new FlaggedOption( "encoding", ForNameStringParser.getParser( Charset.class ), "UTF-8", JSAP.NOT_REQUIRED, 'e', "encoding", "The term list encoding." ),
				new UnflaggedOption( "map", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.NOT_GREEDY, "The filename for the serialised map." ),
				new UnflaggedOption( "dump", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, JSAP.NOT_GREEDY, "An optional dump stream (the resulting map will not be self-contained)." )
		}
	);

	JSAPResult jsapResult = jsap.parse( arg );
	if ( jsap.messagePrinted() ) return;
	
	Collection<? extends CharSequence> termList;
	
	final String termFile = jsapResult.getString( "termFile" );
	final Charset encoding = (Charset)jsapResult.getObject( "encoding" );
	final boolean zipped = jsapResult.getBoolean( "zipped" );
	final boolean serialised = jsapResult.getBoolean( "serialised" );

	if ( zipped && serialised ) throw new IllegalArgumentException( "The zipped and serialised options are incompatible" );

	if ( serialised ) termList = (List<? extends CharSequence>) ( termFile != null ? BinIO.loadObject( termFile ) : BinIO.loadObject( System.in ) );
	else {
		if ( termFile != null ) termList = new FileLinesCollection( termFile, encoding.name(), zipped );
		else {
			final ObjectArrayList<MutableString> list = new ObjectArrayList<MutableString>();
			termList = list;
			final FastBufferedReader terms = new FastBufferedReader( new InputStreamReader( 
					zipped ? new GZIPInputStream( System.in ) : System.in, encoding.name() ) );
			final MutableString term = new MutableString();
			while( terms.readLine( term ) != null ) list.add( term.copy() );
			terms.close();
		}
	}

	BinIO.storeObject( new ImmutableExternalPrefixMap( termList, jsapResult.getInt( "blockSize" ), jsapResult.getString( "dump" ) ), jsapResult.getString( "map" ) );
}
 
Example #21
Source File: ParallelFilteredProcessorRunner.java    From BUbiNG with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] arg) throws Exception {
	final SimpleJSAP jsap = new SimpleJSAP(ParallelFilteredProcessorRunner.class.getName(), "Processes a store.",
			new Parameter[] {
			new FlaggedOption("filter", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'f', "filter", "A WarcRecord filter that recods must pass in order to be processed."),
	 		new FlaggedOption("processor", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'p', "processor", "A processor to be applied to data.").setAllowMultipleDeclarations(true),
		 	new FlaggedOption("writer", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'w', "writer", "A writer to be applied to the results.").setAllowMultipleDeclarations(true),
			new FlaggedOption("output", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'o', "output", "The output filename  (- for stdout).").setAllowMultipleDeclarations(true),
			new FlaggedOption("threads", JSAP.INTSIZE_PARSER, Integer.toString(Runtime.getRuntime().availableProcessors()), JSAP.NOT_REQUIRED, 'T', "threads", "The number of threads to be used."),
			new Switch("sequential", 'S', "sequential"),
			new UnflaggedOption("store", JSAP.STRING_PARSER, JSAP.NOT_REQUIRED, "The name of the store (if omitted, stdin)."),
	});

	final JSAPResult jsapResult = jsap.parse(arg);
	if (jsap.messagePrinted()) return;

	final String filterSpec = jsapResult.getString("filter");
	final Filter<WarcRecord> filter;
	if (filterSpec != null) {
		final FilterParser<WarcRecord> parser = new FilterParser<>(WarcRecord.class);
		filter = parser.parse(filterSpec);
	} else
		filter = null;
	final InputStream in = jsapResult.userSpecified("store") ? new FastBufferedInputStream(new FileInputStream(jsapResult.getString("store"))) : System.in;
	final ParallelFilteredProcessorRunner parallelFilteredProcessorRunner = new ParallelFilteredProcessorRunner(in, filter);

	final String[] processor =  jsapResult.getStringArray("processor");
	final String[] writer =  jsapResult.getStringArray("writer");
	final String[] output =  jsapResult.getStringArray("output");
	if (processor.length != writer.length) throw new IllegalArgumentException("You must specify the same number or processors and writers");
	if (output.length != writer.length) throw new IllegalArgumentException("You must specify the same number or output specifications and writers");

	final String[] packages = new String[] { ParallelFilteredProcessorRunner.class.getPackage().getName() };
	final PrintStream[] ops = new PrintStream[processor.length];
	for (int i = 0; i < processor.length; i++) {
		ops[i] = "-".equals(output[i]) ? System.out : new PrintStream(new FastBufferedOutputStream(new FileOutputStream(output[i])), false, "UTF-8");
		// TODO: these casts to SOMETHING<Object> are necessary for compilation under Eclipse. Check in the future.
		parallelFilteredProcessorRunner.add((Processor<Object>)ObjectParser.fromSpec(processor[i], Processor.class, packages, new String[] { "getInstance" }),
				(Writer<Object>)ObjectParser.fromSpec(writer[i], Writer.class,  packages, new String[] { "getInstance" }),
				ops[i]);
	}

	if (jsapResult.userSpecified("sequential")) parallelFilteredProcessorRunner.runSequentially();
	else parallelFilteredProcessorRunner.run(jsapResult.getInt("threads"));

	for (int i = 0; i < processor.length; i++) ops[i].close();

}
 
Example #22
Source File: HTMLParser.java    From BUbiNG with Apache License 2.0 4 votes vote down vote up
public static void main(final String arg[]) throws IllegalArgumentException, IOException, URISyntaxException, JSAPException, NoSuchAlgorithmException {

		final SimpleJSAP jsap = new SimpleJSAP(HTMLParser.class.getName(), "Produce the digest of a page: the page is downloaded or passed as argument by specifying a file",
				new Parameter[] {
					new UnflaggedOption("url", JSAP.STRING_PARSER, JSAP.REQUIRED, "The url of the page."),
					new Switch("crossAuthorityDuplicates", 'c', "cross-authority-duplicates"),
					new FlaggedOption("charBufferSize", JSAP.INTSIZE_PARSER, Integer.toString(CHAR_BUFFER_SIZE), JSAP.NOT_REQUIRED, 'b', "buffer", "The size of the parser character buffer (0 for dynamic sizing)."),
					new FlaggedOption("file", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'f', "file", "The page to be processed."),
					new FlaggedOption("digester", JSAP.STRING_PARSER, "MD5", JSAP.NOT_REQUIRED, 'd', "digester", "The digester to be used.")
			});

			final JSAPResult jsapResult = jsap.parse(arg);
			if (jsap.messagePrinted()) System.exit(1);

		final String url = jsapResult.getString("url");
		final String digester = jsapResult.getString("digester");
		final boolean crossAuthorityDuplicates = jsapResult.userSpecified("crossAuthorityDuplicates");
		final int charBufferSize = jsapResult.getInt("charBufferSize");

		final HTMLParser<Void> htmlParser =  new HTMLParser<>(BinaryParser.forName(digester), (TextProcessor<Void>)null, crossAuthorityDuplicates, charBufferSize);
		final SetLinkReceiver linkReceiver = new SetLinkReceiver();
		final byte[] digest;

		if (!jsapResult.userSpecified("file")) {
			final URI uri = new URI(url);
			final HttpGet request = new HttpGet(uri);
			request.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build());
			digest = htmlParser.parse(uri, HttpClients.createDefault().execute(request), linkReceiver);
		}
		else {
			final String file = jsapResult.getString("file");
			final String content = IOUtils.toString(new InputStreamReader(new FileInputStream(file)));
			digest = htmlParser.parse(BURL.parse(url) , new StringHttpMessages.HttpResponse(content), linkReceiver);
		}

		System.out.println("DigestHexString: " + Hex.encodeHexString(digest));
		System.out.println("Links: " + linkReceiver.urls);

		final Set<String> urlStrings = new ObjectOpenHashSet<>();
		for (final URI link: linkReceiver.urls) urlStrings.add(link.toString());
		if (urlStrings.size() != linkReceiver.urls.size()) System.out.println("There are " + linkReceiver.urls.size() + " URIs but " + urlStrings.size() + " strings");

	}