List of usage examples for java.lang Integer toString
@HotSpotIntrinsicCandidate public static String toString(int i)
From source file:com.artistech.tuio.dispatch.TuioPublish.java
public static void main(String[] args) throws InterruptedException { //read off the TUIO port from the command line int tuio_port = 3333; int zeromq_port = 5565; TuioSink.SerializeType serialize_method = TuioSink.SerializeType.PROTOBUF; Options options = new Options(); options.addOption("t", "tuio-port", true, "TUIO Port to listen on. (Default = 3333)"); options.addOption("z", "zeromq-port", true, "ZeroMQ Port to publish on. (Default = 5565)"); options.addOption("s", "serialize-method", true, "Serialization Method (JSON, OBJECT, Default = PROTOBUF)."); options.addOption("h", "help", false, "Show this message."); HelpFormatter formatter = new HelpFormatter(); try {/* w ww .ja va 2s. c om*/ CommandLineParser parser = new org.apache.commons.cli.BasicParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { formatter.printHelp("tuio-zeromq-publish", options); return; } else { if (cmd.hasOption("t") || cmd.hasOption("tuio-port")) { tuio_port = Integer.parseInt(cmd.getOptionValue("t")); } if (cmd.hasOption("z") || cmd.hasOption("zeromq-port")) { zeromq_port = Integer.parseInt(cmd.getOptionValue("z")); } if (cmd.hasOption("s") || cmd.hasOption("serialize-method")) { serialize_method = (TuioSink.SerializeType) Enum.valueOf(TuioSink.SerializeType.class, cmd.getOptionValue("s")); } } } catch (ParseException | IllegalArgumentException ex) { System.err.println("Error Processing Command Options:"); formatter.printHelp("tuio-zeromq-publish", options); return; } //start up the zmq publisher ZMQ.Context context = ZMQ.context(1); // We send updates via this socket try (ZMQ.Socket publisher = context.socket(ZMQ.PUB)) { // We send updates via this socket publisher.bind("tcp://*:" + Integer.toString(zeromq_port)); //create a new TUIO sink connected at the specified port TuioSink sink = new TuioSink(); sink.setSerializationType(serialize_method); TuioClient client = new TuioClient(tuio_port); System.out.println( MessageFormat.format("Listening to TUIO message at port: {0}", Integer.toString(tuio_port))); System.out.println( MessageFormat.format("Publishing to ZeroMQ at port: {0}", Integer.toString(zeromq_port))); System.out.println(MessageFormat.format("Serializing as: {0}", serialize_method)); client.addTuioListener(sink); client.connect(); //while not halted (infinite loop...) //read any available messages and publish while (!sink.mailbox.isHalted()) { ImmutablePair<String, byte[]> msg = sink.mailbox.getMessage(); publisher.sendMore(msg.left + "." + serialize_method.toString()); publisher.send(msg.right, 0); } //cleanup } context.term(); }
From source file:com.amazonaws.services.kinesis.leases.impl.LeaseCoordinatorExerciser.java
public static void main(String[] args) throws InterruptedException, DependencyException, InvalidStateException, ProvisionedThroughputException, IOException { int numCoordinators = 9; int numLeases = 73; int leaseDurationMillis = 10000; int epsilonMillis = 100; AWSCredentialsProvider creds = new DefaultAWSCredentialsProviderChain(); AmazonDynamoDBClient ddb = new AmazonDynamoDBClient(creds); ILeaseManager<KinesisClientLease> leaseManager = new KinesisClientLeaseManager("nagl_ShardProgress", ddb); if (leaseManager.createLeaseTableIfNotExists(10L, 50L)) { LOG.info("Waiting for newly created lease table"); if (!leaseManager.waitUntilLeaseTableExists(10, 300)) { LOG.error("Table was not created in time"); return; }/*from w w w . j ava 2 s. c om*/ } CWMetricsFactory metricsFactory = new CWMetricsFactory(creds, "testNamespace", 30 * 1000, 1000); final List<LeaseCoordinator<KinesisClientLease>> coordinators = new ArrayList<LeaseCoordinator<KinesisClientLease>>(); for (int i = 0; i < numCoordinators; i++) { String workerIdentifier = "worker-" + Integer.toString(i); LeaseCoordinator<KinesisClientLease> coord = new LeaseCoordinator<KinesisClientLease>(leaseManager, workerIdentifier, leaseDurationMillis, epsilonMillis, metricsFactory); coordinators.add(coord); } leaseManager.deleteAll(); for (int i = 0; i < numLeases; i++) { KinesisClientLease lease = new KinesisClientLease(); lease.setLeaseKey(Integer.toString(i)); lease.setCheckpoint(new ExtendedSequenceNumber("checkpoint")); leaseManager.createLeaseIfNotExists(lease); } final JFrame frame = new JFrame("Test Visualizer"); frame.setPreferredSize(new Dimension(800, 600)); final JPanel panel = new JPanel(new GridLayout(coordinators.size() + 1, 0)); final JLabel ticker = new JLabel("tick"); panel.add(ticker); frame.getContentPane().add(panel); final Map<String, JLabel> labels = new HashMap<String, JLabel>(); for (final LeaseCoordinator<KinesisClientLease> coord : coordinators) { JPanel coordPanel = new JPanel(); coordPanel.setLayout(new BoxLayout(coordPanel, BoxLayout.X_AXIS)); final Button button = new Button("Stop " + coord.getWorkerIdentifier()); button.setMaximumSize(new Dimension(200, 50)); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { if (coord.isRunning()) { coord.stop(); button.setLabel("Start " + coord.getWorkerIdentifier()); } else { try { coord.start(); } catch (LeasingException e) { LOG.error(e); } button.setLabel("Stop " + coord.getWorkerIdentifier()); } } }); coordPanel.add(button); JLabel label = new JLabel(); coordPanel.add(label); labels.put(coord.getWorkerIdentifier(), label); panel.add(coordPanel); } frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); new Thread() { // Key is lease key, value is green-ness as a value from 0 to 255. // Great variable name, huh? private Map<String, Integer> greenNesses = new HashMap<String, Integer>(); // Key is lease key, value is last owning worker private Map<String, String> lastOwners = new HashMap<String, String>(); @Override public void run() { while (true) { for (LeaseCoordinator<KinesisClientLease> coord : coordinators) { String workerIdentifier = coord.getWorkerIdentifier(); JLabel label = labels.get(workerIdentifier); List<KinesisClientLease> asgn = new ArrayList<KinesisClientLease>(coord.getAssignments()); Collections.sort(asgn, new Comparator<KinesisClientLease>() { @Override public int compare(KinesisClientLease arg0, KinesisClientLease arg1) { return arg0.getLeaseKey().compareTo(arg1.getLeaseKey()); } }); StringBuilder builder = new StringBuilder(); builder.append("<html>"); builder.append(workerIdentifier).append(":").append(asgn.size()).append(" "); for (KinesisClientLease lease : asgn) { String leaseKey = lease.getLeaseKey(); String lastOwner = lastOwners.get(leaseKey); // Color things green when they switch owners, decay the green-ness over time. Integer greenNess = greenNesses.get(leaseKey); if (greenNess == null || lastOwner == null || !lastOwner.equals(lease.getLeaseOwner())) { greenNess = 200; } else { greenNess = Math.max(0, greenNess - 20); } greenNesses.put(leaseKey, greenNess); lastOwners.put(leaseKey, lease.getLeaseOwner()); builder.append(String.format("<font color=\"%s\">%03d</font>", String.format("#00%02x00", greenNess), Integer.parseInt(leaseKey))).append(" "); } builder.append("</html>"); label.setText(builder.toString()); label.revalidate(); label.repaint(); } if (ticker.getText().equals("tick")) { ticker.setText("tock"); } else { ticker.setText("tick"); } try { Thread.sleep(200); } catch (InterruptedException e) { } } } }.start(); frame.pack(); frame.setVisible(true); for (LeaseCoordinator<KinesisClientLease> coord : coordinators) { coord.start(); } }
From source file:com.cloudera.oryx.app.traffic.TrafficUtil.java
public static void main(String[] args) throws Exception { if (args.length < 3) { System.err.println("usage: TrafficUtil [hosts] [requestIntervalMS] [threads] [... other args]"); return;//from www.ja v a 2 s .c om } String[] hostStrings = COMMA.split(args[0]); Preconditions.checkArgument(hostStrings.length >= 1); int requestIntervalMS = Integer.parseInt(args[1]); Preconditions.checkArgument(requestIntervalMS >= 0); int numThreads = Integer.parseInt(args[2]); Preconditions.checkArgument(numThreads >= 1); String[] otherArgs = new String[args.length - 3]; System.arraycopy(args, 3, otherArgs, 0, otherArgs.length); List<URI> hosts = Arrays.stream(hostStrings).map(URI::create).collect(Collectors.toList()); int perClientRequestIntervalMS = numThreads * requestIntervalMS; Endpoints alsEndpoints = new Endpoints(ALSEndpoint.buildALSEndpoints()); AtomicLong requestCount = new AtomicLong(); AtomicLong serverErrorCount = new AtomicLong(); AtomicLong clientErrorCount = new AtomicLong(); AtomicLong exceptionCount = new AtomicLong(); long start = System.currentTimeMillis(); ExecUtils.doInParallel(numThreads, numThreads, true, i -> { RandomGenerator random = RandomManager.getRandom(Integer.toString(i).hashCode() ^ System.nanoTime()); ExponentialDistribution msBetweenRequests; if (perClientRequestIntervalMS > 0) { msBetweenRequests = new ExponentialDistribution(random, perClientRequestIntervalMS); } else { msBetweenRequests = null; } ClientConfig clientConfig = new ClientConfig(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(numThreads); connectionManager.setDefaultMaxPerRoute(numThreads); clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager); clientConfig.connectorProvider(new ApacheConnectorProvider()); Client client = ClientBuilder.newClient(clientConfig); try { while (true) { try { WebTarget target = client.target("http://" + hosts.get(random.nextInt(hosts.size()))); Endpoint endpoint = alsEndpoints.chooseEndpoint(random); Invocation invocation = endpoint.makeInvocation(target, otherArgs, random); long startTime = System.currentTimeMillis(); Response response = invocation.invoke(); try { response.readEntity(String.class); } finally { response.close(); } long elapsedMS = System.currentTimeMillis() - startTime; int statusCode = response.getStatusInfo().getStatusCode(); if (statusCode >= 400) { if (statusCode >= 500) { serverErrorCount.incrementAndGet(); } else { clientErrorCount.incrementAndGet(); } } endpoint.recordTiming(elapsedMS); if (requestCount.incrementAndGet() % 10000 == 0) { long elapsed = System.currentTimeMillis() - start; log.info("{}ms:\t{} requests\t({} client errors\t{} server errors\t{} exceptions)", elapsed, requestCount.get(), clientErrorCount.get(), serverErrorCount.get(), exceptionCount.get()); for (Endpoint e : alsEndpoints.getEndpoints()) { log.info("{}", e); } } if (msBetweenRequests != null) { int desiredElapsedMS = (int) Math.round(msBetweenRequests.sample()); if (elapsedMS < desiredElapsedMS) { Thread.sleep(desiredElapsedMS - elapsedMS); } } } catch (Exception e) { exceptionCount.incrementAndGet(); log.warn("{}", e.getMessage()); } } } finally { client.close(); } }); }
From source file:gobblin.restli.throttling.LocalStressTest.java
public static void main(String[] args) throws Exception { CommandLine cli = StressTestUtils.parseCommandLine(OPTIONS, args); int stressorThreads = Integer.parseInt( cli.getOptionValue(STRESSOR_THREADS.getOpt(), Integer.toString(DEFAULT_STRESSOR_THREADS))); int processorThreads = Integer.parseInt( cli.getOptionValue(PROCESSOR_THREADS.getOpt(), Integer.toString(DEFAULT_PROCESSOR_THREADS))); int artificialLatency = Integer.parseInt( cli.getOptionValue(ARTIFICIAL_LATENCY.getOpt(), Integer.toString(DEFAULT_ARTIFICIAL_LATENCY))); long targetQps = Integer.parseInt(cli.getOptionValue(QPS.getOpt(), Integer.toString(DEFAULT_TARGET_QPS))); Configuration configuration = new Configuration(); StressTestUtils.populateConfigFromCli(configuration, cli); String resourceLimited = LocalStressTest.class.getSimpleName(); Map<String, String> configMap = Maps.newHashMap(); ThrottlingPolicyFactory factory = new ThrottlingPolicyFactory(); SharedLimiterKey res1key = new SharedLimiterKey(resourceLimited); configMap.put(BrokerConfigurationKeyGenerator.generateKey(factory, res1key, null, ThrottlingPolicyFactory.POLICY_KEY), QPSPolicy.FACTORY_ALIAS); configMap.put(BrokerConfigurationKeyGenerator.generateKey(factory, res1key, null, QPSPolicy.QPS), Long.toString(targetQps)); ThrottlingGuiceServletConfig guiceServletConfig = new ThrottlingGuiceServletConfig(); guiceServletConfig.initialize(ConfigFactory.parseMap(configMap)); LimiterServerResource limiterServer = guiceServletConfig.getInjector() .getInstance(LimiterServerResource.class); RateComputingLimiterContainer limiterContainer = new RateComputingLimiterContainer(); Class<? extends Stressor> stressorClass = configuration.getClass(StressTestUtils.STRESSOR_CLASS, StressTestUtils.DEFAULT_STRESSOR_CLASS, Stressor.class); ExecutorService executorService = Executors.newFixedThreadPool(stressorThreads); SharedResourcesBroker broker = guiceServletConfig.getInjector().getInstance( Key.get(SharedResourcesBroker.class, Names.named(LimiterServerResource.BROKER_INJECT_NAME))); ThrottlingPolicy policy = (ThrottlingPolicy) broker.getSharedResource(new ThrottlingPolicyFactory(), new SharedLimiterKey(resourceLimited)); ScheduledExecutorService reportingThread = Executors.newSingleThreadScheduledExecutor(); reportingThread.scheduleAtFixedRate(new Reporter(limiterContainer, policy), 0, 15, TimeUnit.SECONDS); Queue<Future<?>> futures = new LinkedList<>(); MockRequester requester = new MockRequester(limiterServer, artificialLatency, processorThreads); requester.start();//from w ww.j a va 2 s.c o m for (int i = 0; i < stressorThreads; i++) { RestliServiceBasedLimiter restliLimiter = RestliServiceBasedLimiter.builder() .resourceLimited(resourceLimited).requestSender(requester).serviceIdentifier("stressor" + i) .build(); Stressor stressor = stressorClass.newInstance(); stressor.configure(configuration); futures.add(executorService .submit(new StressorRunner(limiterContainer.decorateLimiter(restliLimiter), stressor))); } int stressorFailures = 0; for (Future<?> future : futures) { try { future.get(); } catch (ExecutionException ee) { stressorFailures++; } } requester.stop(); executorService.shutdownNow(); if (stressorFailures > 0) { log.error("There were " + stressorFailures + " failed stressor threads."); } System.exit(stressorFailures); }
From source file:net.morphbank.webclient.ProcessFiles.java
/** * @param args//ww w . jav a 2 s.co m * args[0] directory including terminal '/' * args[1] prefix of request files * args[2] number of digits in file index value * args[3] number of files * args[4] index of first file (default 0) * args[5] prefix of service * args[6] prefix of response files (default args[1] + "Resp") */ public static void main(String[] args) { ProcessFiles fileProcessor = new ProcessFiles(); // restTest.processRequest(URL, UPLOAD_FILE); String zeros = "0000000"; if (args.length < 4) { System.out.println("Too few parameters"); } else { try { // get parameters String reqDir = args[0]; String reqPrefix = args[1]; int numDigits = Integer.valueOf(args[2]); if (numDigits > zeros.length()) numDigits = zeros.length(); NumberFormat intFormat = new DecimalFormat(zeros.substring(0, numDigits)); int numFiles = Integer.valueOf(args[3]); int firstFile = 0; BufferedReader fileIn = new BufferedReader(new FileReader(FILE_IN_PATH)); String line = fileIn.readLine(); fileIn.close(); firstFile = Integer.valueOf(line); // firstFile = 189; // numFiles = 1; int lastFile = firstFile + numFiles - 1; String url = URL; String respPrefix = reqPrefix + "Resp"; if (args.length > 5) respPrefix = args[5]; if (args.length > 6) url = args[6]; // process files for (int i = firstFile; i <= lastFile; i++) { String xmlOutputFile = null; String requestFile = reqDir + reqPrefix + intFormat.format(i) + ".xml"; System.out.println("Processing request file " + requestFile); String responseFile = reqDir + respPrefix + intFormat.format(i) + ".xml"; System.out.println("Response file " + responseFile); // restTest.processRequest(URL, UPLOAD_FILE); fileProcessor.processRequest(url, requestFile, responseFile); Writer fileOut = new FileWriter(FILE_IN_PATH, false); fileOut.append(Integer.toString(i + 1)); fileOut.close(); } } catch (Exception e) { e.printStackTrace(); } } }
From source file:friendsandfollowers.FilesThreaderFriendsIDs.java
public static void main(String[] args) throws InterruptedException { // Check how many arguments were passed in if ((args == null) || (args.length < 4)) { System.err.println("4 Parameters are required plus one optional " + "parameter to launch a Job."); System.err.println("First: String 'INPUT: /path/to/files/'"); System.err.println("Second: String 'OUTPUT: /output/path/'"); System.err.println("Third: (int) Total Number Of Jobs"); System.err.println("Fourth: (int) Number of seconds to pause"); System.err/*from w w w .j a v a 2 s . com*/ .println("Fifth: (int) Number of ids to fetch. " + "Provide number which increment by 5000 eg " + "(5000, 10000, 15000 etc) " + "or -1 to fetch all ids."); System.err.println("Example: fileToRun /input/path/ " + "/output/path/ 10 2 75000"); System.exit(-1); } // to write output in a file ThreadPrintStream.replaceSystemOut(); try { INPUT = StringEscapeUtils.escapeJava(args[0]); } catch (Exception e) { System.err.println("Argument" + args[0] + " must be an String."); System.exit(-1); } try { OUTPUT = StringEscapeUtils.escapeJava(args[1]); } catch (Exception e) { System.err.println("Argument" + args[1] + " must be an String."); System.exit(-1); } try { TOTAL_JOBS_STR = StringEscapeUtils.escapeJava(args[2]); } catch (Exception e) { System.err.println("Argument" + args[2] + " must be an integer."); System.exit(-1); } try { PAUSE_STR = StringEscapeUtils.escapeJava(args[3]); } catch (Exception e) { System.err.println("Argument" + args[3] + " must be an integer."); System.exit(-1); } if (args.length == 5) { try { IDS_TO_FETCH = StringEscapeUtils.escapeJava(args[4]); } catch (Exception e) { System.err.println("Argument" + args[4] + " must be an integer."); System.exit(-1); } } try { PAUSE = Integer.parseInt(args[3]); } catch (NumberFormatException e) { System.err.println("Argument" + args[3] + " must be an integer."); System.exit(-1); } try { TOTAL_JOBS = Integer.parseInt(TOTAL_JOBS_STR); } catch (NumberFormatException e) { System.err.println("Argument" + TOTAL_JOBS_STR + " must be an integer."); System.exit(-1); } System.out.println("Going to launch jobs. " + "Please see logs files to track jobs."); ExecutorService threadPool = Executors.newFixedThreadPool(TOTAL_JOBS); for (int i = 0; i < TOTAL_JOBS; i++) { final String JOB_NO = Integer.toString(i); threadPool.submit(new Runnable() { public void run() { try { // Creating a text file where System.out.println() // will send its output for this thread. String name = Thread.currentThread().getName(); FileOutputStream fos = null; try { fos = new FileOutputStream(name + "-logs.txt"); } catch (Exception e) { System.err.println(e.getMessage()); System.exit(0); } // Create a PrintStream that will write to the new file. PrintStream stream = new PrintStream(new BufferedOutputStream(fos)); // Install the PrintStream to be used as // System.out for this thread. ((ThreadPrintStream) System.out).setThreadOut(stream); // Output three messages to System.out. System.out.println(name); System.out.println(); System.out.println(); FilesThreaderFriendsIDs.execTask(INPUT, OUTPUT, TOTAL_JOBS_STR, JOB_NO, PAUSE_STR, IDS_TO_FETCH); } catch (IOException | ClassNotFoundException | SQLException | JSONException e) { // e.printStackTrace(); System.out.println(e.getMessage()); } } }); helpers.pause(PAUSE); } threadPool.shutdown(); }
From source file:friendsandfollowers.FilesThreaderFollowersIDs.java
public static void main(String[] args) throws InterruptedException { // Check how many arguments were passed in if ((args == null) || (args.length < 4)) { System.err.println("4 Parameters are required plus one optional " + "parameter to launch a Job."); System.err.println("First: String 'INPUT: /path/to/files/'"); System.err.println("Second: String 'OUTPUT: /output/path/'"); System.err.println("Third: (int) Total Number Of Jobs"); System.err.println("Fourth: (int) Number of seconds to pause"); System.err//from ww w .ja v a 2 s . c o m .println("Fifth: (int) Number of ids to fetch. " + "Provide number which increment by 5000 eg " + "(5000, 10000, 15000 etc) " + "or -1 to fetch all ids."); System.err.println("Example: fileToRun /input/path/ " + "/output/path/ 10 2 75000"); System.exit(-1); } // to write output in a file ThreadPrintStream.replaceSystemOut(); try { INPUT = StringEscapeUtils.escapeJava(args[0]); } catch (Exception e) { System.err.println("Argument" + args[0] + " must be an String."); System.exit(-1); } try { OUTPUT = StringEscapeUtils.escapeJava(args[1]); } catch (Exception e) { System.err.println("Argument" + args[1] + " must be an String."); System.exit(-1); } try { TOTAL_JOBS_STR = StringEscapeUtils.escapeJava(args[2]); } catch (Exception e) { System.err.println("Argument" + args[2] + " must be an integer."); System.exit(-1); } try { PAUSE_STR = StringEscapeUtils.escapeJava(args[3]); } catch (Exception e) { System.err.println("Argument" + args[3] + " must be an integer."); System.exit(-1); } if (args.length == 5) { try { IDS_TO_FETCH = StringEscapeUtils.escapeJava(args[4]); } catch (Exception e) { System.err.println("Argument" + args[4] + " must be an integer."); System.exit(-1); } } try { PAUSE = Integer.parseInt(args[3]); } catch (NumberFormatException e) { System.err.println("Argument" + args[3] + " must be an integer."); System.exit(-1); } try { TOTAL_JOBS = Integer.parseInt(TOTAL_JOBS_STR); } catch (NumberFormatException e) { System.err.println("Argument" + TOTAL_JOBS_STR + " must be an integer."); System.exit(-1); } System.out.println("Going to launch jobs. " + "Please see logs files to track jobs."); ExecutorService threadPool = Executors.newFixedThreadPool(TOTAL_JOBS); for (int i = 0; i < TOTAL_JOBS; i++) { final String JOB_NO = Integer.toString(i); threadPool.submit(new Runnable() { public void run() { try { // Creating a text file where System.out.println() // will send its output for this thread. String name = Thread.currentThread().getName(); FileOutputStream fos = null; try { fos = new FileOutputStream(name + "-logs.txt"); } catch (Exception e) { System.err.println(e.getMessage()); System.exit(0); } // Create a PrintStream that will write to the new file. PrintStream stream = new PrintStream(new BufferedOutputStream(fos)); // Install the PrintStream to be used as // System.out for this thread. ((ThreadPrintStream) System.out).setThreadOut(stream); // Output three messages to System.out. System.out.println(name); System.out.println(); System.out.println(); FilesThreaderFollowersIDs.execTask(INPUT, OUTPUT, TOTAL_JOBS_STR, JOB_NO, PAUSE_STR, IDS_TO_FETCH); } catch (IOException | ClassNotFoundException | SQLException | JSONException e) { // e.printStackTrace(); System.out.println(e.getMessage()); } } }); helpers.pause(PAUSE); } threadPool.shutdown(); }
From source file:eu.annocultor.converter.Analyser.java
static public void main(String... args) throws Exception { // Handling command line parameters with Apache Commons CLI Options options = new Options(); options.addOption(OptionBuilder.withArgName(OPT_FN).hasArg().isRequired() .withDescription("XML file name to be analysed").withValueSeparator(',').create(OPT_FN)); options.addOption(OptionBuilder.withArgName(OPT_MAX_VALUE_SIZE).hasArg().withDescription( "Maximal size when values are counted separately. Longer values are counted altogether. Reasonable values are 100, 300, etc.") .create(OPT_MAX_VALUE_SIZE)); options.addOption(OptionBuilder.withArgName(OPT_VALUES).hasArg().withDescription( "Maximal number of most frequent values displayed in the report. Reasonable values are 10, 25, 50") .create(OPT_VALUES));/*from w ww. j ava 2 s.c o m*/ // now lets parse the input CommandLineParser parser = new BasicParser(); CommandLine cmd; try { cmd = parser.parse(options, Utils.getCommandLineFromANNOCULTOR_ARGS(args)); } catch (ParseException pe) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("analyse", options); return; } MAX_VALUE_SIZE = Integer.parseInt(cmd.getOptionValue(OPT_MAX_VALUE_SIZE, Integer.toString(MAX_VALUE_SIZE))); MAX_VALUES = Integer.parseInt(cmd.getOptionValue(OPT_VALUES, Integer.toString(MAX_VALUES))); Analyser analyser = new Analyser(new EnvironmentImpl()); // undo: /* analyser.task.setSrcFiles(new File("."), cmd.getOptionValue(OPT_FN)); if (analyser.task.getSrcFiles().size() > 1) { analyser.task.mergeSourceFiles(); } if (analyser.task.getSrcFiles().size() == 0) { throw new Exception("No files to analyze, pattern " + cmd.getOptionValue(OPT_FN)); } File trg = new File(analyser.task.getSrcFiles().get(0).getParentFile(), "rdf"); if (!trg.exists()) trg.mkdir(); System.out.println("[Analysis] Analysing files " + cmd.getOptionValue(OPT_FN) + ", writing analysis to " + trg.getCanonicalPath() + ", max value length (long values are aggregated into one 'long value' value) " + MAX_VALUE_SIZE + ", number most fequently used values per field shown in report " + MAX_VALUES); */ if (true) throw new Exception("unimplemented"); System.exit(analyser.run()); }
From source file:OCRRestAPI.java
public static void main(String[] args) throws Exception { /*/*from www .j a va 2 s . com*/ Sample project for OCRWebService.com (REST API). Extract text from scanned images and convert into editable formats. Please create new account with ocrwebservice.com via http://www.ocrwebservice.com/account/signup and get license code */ // Provide your user name and license code String license_code = "88EF173D-CDEA-41B6-8D64-C04578ED8C4D"; String user_name = "FERGOID"; /* You should specify OCR settings. See full description http://www.ocrwebservice.com/service/restguide Input parameters: [language] - Specifies the recognition language. This parameter can contain several language names separated with commas. For example "language=english,german,spanish". Optional parameter. By default:english [pagerange] - Enter page numbers and/or page ranges separated by commas. For example "pagerange=1,3,5-12" or "pagerange=allpages". Optional parameter. By default:allpages [tobw] - Convert image to black and white (recommend for color image and photo). For example "tobw=false" Optional parameter. By default:false [zone] - Specifies the region on the image for zonal OCR. The coordinates in pixels relative to the left top corner in the following format: top:left:height:width. This parameter can contain several zones separated with commas. For example "zone=0:0:100:100,50:50:50:50" Optional parameter. [outputformat] - Specifies the output file format. Can be specified up to two output formats, separated with commas. For example "outputformat=pdf,txt" Optional parameter. By default:doc [gettext] - Specifies that extracted text will be returned. For example "tobw=true" Optional parameter. By default:false [description] - Specifies your task description. Will be returned in response. Optional parameter. !!!! For getting result you must specify "gettext" or "outputformat" !!!! */ // Build your OCR: // Extraction text with English language String ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?gettext=true"; // Extraction text with English and German language using zonal OCR ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?language=english,german&zone=0:0:600:400,500:1000:150:400"; // Convert first 5 pages of multipage document into doc and txt // ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?language=english&pagerange=1-5&outputformat=doc,txt"; // Full path to uploaded document String filePath = "sarah-morgan.jpg"; byte[] fileContent = Files.readAllBytes(Paths.get(filePath)); URL url = new URL(ocrURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString((user_name + ":" + license_code).getBytes())); // Specify Response format to JSON or XML (application/json or application/xml) connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Length", Integer.toString(fileContent.length)); int httpCode; try (OutputStream stream = connection.getOutputStream()) { // Send POST request stream.write(fileContent); stream.close(); } catch (Exception e) { System.out.println(e.toString()); } httpCode = connection.getResponseCode(); System.out.println("HTTP Response code: " + httpCode); // Success request if (httpCode == HttpURLConnection.HTTP_OK) { // Get response stream String jsonResponse = GetResponseToString(connection.getInputStream()); // Parse and print response from OCR server PrintOCRResponse(jsonResponse); } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println("OCR Error Message: Unauthorizied request"); } else { // Error occurred String jsonResponse = GetResponseToString(connection.getErrorStream()); JSONParser parser = new JSONParser(); JSONObject jsonObj = (JSONObject) parser.parse(jsonResponse); // Error message System.out.println("Error Message: " + jsonObj.get("ErrorMessage")); } connection.disconnect(); }
From source file:ega.projekt.graphDraw.DrawGraph.java
/** * @param args the command line arguments *//*ww w. j a v a 2 s . c om*/ public static void main(String[] args) { ega.projekt.graph.Graph dataGraph = new ega.projekt.graph.Graph(5, 100, 295, 295); if (dataGraph.getEdges().isEmpty()) System.out.println("Error initializing graph"); DrawGraph graphView = new DrawGraph(dataGraph); // This builds the graph // Layout<V, E>, VisualizationComponent<V,E> Layout<Node, Edge> layout = new StaticLayout(graphView.drawGraph); for (Node n : graphView.drawGraph.getVertices()) { layout.setLocation(n, new java.awt.geom.Point2D.Double(n.getX(), n.getY())); } layout.setSize(new Dimension(300, 300)); BasicVisualizationServer<Node, Edge> vv = new BasicVisualizationServer<>(layout); vv.setPreferredSize(new Dimension(350, 350)); // Setup up a new vertex to paint transformer... Transformer<Node, Paint> vertexPaint = new Transformer<Node, Paint>() { public Paint transform(Node i) { return Color.GREEN; } }; // Set up a new stroke Transformer for the edges //float dash[] = {10.0f}; final Stroke edgeStroke = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER); Transformer<Edge, Stroke> edgeStrokeTransformer = new Transformer<Edge, Stroke>() { public Stroke transform(Edge e) { if (e.isMarked()) { final Stroke modStroke = new BasicStroke(5.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER); return modStroke; } return edgeStroke; } }; Transformer<Edge, Paint> edgePaint = new Transformer<Edge, Paint>() { public Paint transform(Edge e) { if (e.isMarked()) { return Color.RED; } return Color.BLACK; } }; vv.getRenderContext().setVertexFillPaintTransformer(vertexPaint); vv.getRenderContext().setEdgeStrokeTransformer(edgeStrokeTransformer); vv.getRenderContext().setEdgeShapeTransformer(new EdgeShape.QuadCurve<Node, Edge>()); vv.getRenderContext().setEdgeLabelTransformer(new Transformer<Edge, String>() { public String transform(Edge e) { return (e.getFlowString() + "/" + Integer.toString(e.getCapacity())); } }); vv.getRenderContext().setVertexLabelTransformer(new Transformer<Node, String>() { public String transform(Node n) { return (Integer.toString(n.getID())); } }); vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR); JFrame frame = new JFrame("Simple Graph View 2"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(vv); frame.pack(); frame.setVisible(true); }