List of usage examples for java.util List size
int size();
From source file:hudson.plugins.vcloud.VCloudDirector.java
public static void main(String args[]) throws VCloudException, TimeoutException, KeyManagementException, UnrecoverableKeyException { String vcloudHost = "https://res01.ilandcloud.com"; String vdDescription = "vdc1"; String vdOrganization = "Splunk-130810582"; String vdcConfiguration = "Splunk RES vDC"; String username = "ilandsplunk@Splunk-130810582"; String password = "splunk1235"; int maxOnlineSlaves = Integer.parseInt("9"); String vAppTemplateName = "centos-gold"; VCloudDirector splunkVcd = new VCloudDirector(vcloudHost, vdDescription, vdOrganization, vdcConfiguration, username, password, maxOnlineSlaves); Vdc vdc = splunkVcd.getVdcByName(splunkVcd.vdconfiguration); if (vdc != null) { log.info(String.format("We found the actual VDC with name=%s", vdc.getResource().getName())); }//from w ww. jav a2s. c o m ReferenceType refType = splunkVcd.getVappTemplateByName(vdc, vAppTemplateName); if (refType != null) { log.info(String.format("We found the actual template with name=%s", refType.getName())); } Vapp vapp = splunkVcd.newvAppFromTemplate(vAppTemplateName, vdc); List<Task> tasks = vapp.getTasks(); if (tasks.size() > 0) { tasks.get(0).waitForTask(0); } splunkVcd.getListOfVappTemplates(); splunkVcd.configureVMsIPAddressingMode(vapp.getReference(), vdc); String vappName = vapp.getReference().getName(); log.info("Deploying the " + vappName); vapp.deploy(false, 1000000, false).waitForTask(0); log.info("PowerOn the " + vappName); vapp.powerOn().waitForTask(0); log.info("Suspend the " + vappName); vapp.suspend().waitForTask(0); log.info("PowerOn the " + vappName); vapp.powerOn().waitForTask(0); log.info("PowerOff the " + vappName); vapp.powerOff().waitForTask(0); log.info("Undeploy the " + vappName); vapp.undeploy(UndeployPowerActionType.SHUTDOWN).waitForTask(0); log.info("Delete the " + vappName); vapp.delete().waitForTask(0); }
From source file:dk.alexandra.fresco.framework.configuration.ConfigurationGenerator.java
public static void main(String args[]) { if (args.length == 0) { usage();/*from w ww .j a v a2 s. c om*/ } if (args.length % 2 != 0) { System.out.println("Incorrect number of arguments: " + Arrays.asList(args) + "."); System.out.println(); usage(); } List<Pair<String, Integer>> hosts = new LinkedList<Pair<String, Integer>>(); int inx = 0; try { for (; inx < args.length; inx = inx + 2) { hosts.add(new Pair<String, Integer>(args[inx], new Integer(args[inx + 1]))); } } catch (NumberFormatException ex) { System.out.println("Invalid argument for port: \"" + args[inx + 1] + "\"."); System.exit(1); } inx = 1; try { for (; inx < hosts.size() + 1; inx++) { String filename = "party-" + inx + ".ini"; OutputStream out = new FileOutputStream(filename); new ConfigurationGenerator().generate(inx, out, hosts); out.close(); System.out.println("Created configuration file: " + filename + "."); } } catch (Exception ex) { System.out.println("Could not write to file: party-" + inx + ".ini."); System.exit(1); } }
From source file:io.apicurio.studio.tools.release.ReleaseTool.java
/** * Main method./*from w w w .j av a2 s . c o m*/ * @param args */ public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("n", "release-name", true, "The name of the new release."); options.addOption("p", "prerelease", false, "Indicate that this is a pre-release."); options.addOption("t", "release-tag", true, "The tag name of the new release."); options.addOption("o", "previous-tag", true, "The tag name of the previous release."); options.addOption("g", "github-pat", true, "The GitHub PAT (for authentication/authorization)."); options.addOption("a", "artifact", true, "The binary release artifact (full path)."); options.addOption("d", "output-directory", true, "Where to store output file(s)."); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args); if (!cmd.hasOption("n") || !cmd.hasOption("t") || !cmd.hasOption("o") || !cmd.hasOption("g") || !cmd.hasOption("a")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("release-studio", options); System.exit(1); } // Arguments (command line) String releaseName = cmd.getOptionValue("n"); boolean isPrerelease = cmd.hasOption("p"); String releaseTag = cmd.getOptionValue("t"); String oldReleaseTag = cmd.getOptionValue("o"); String githubPAT = cmd.getOptionValue("g"); String artifact = cmd.getOptionValue("a"); File outputDir = new File(""); if (cmd.hasOption("d")) { outputDir = new File(cmd.getOptionValue("d")); if (!outputDir.exists()) { outputDir.mkdirs(); } } File releaseArtifactFile = new File(artifact); File releaseArtifactSigFile = new File(artifact + ".asc"); String releaseArtifact = releaseArtifactFile.getName(); String releaseArtifactSig = releaseArtifactSigFile.getName(); if (!releaseArtifactFile.isFile()) { System.err.println("Missing file: " + releaseArtifactFile.getAbsolutePath()); System.exit(1); } if (!releaseArtifactSigFile.isFile()) { System.err.println("Missing file: " + releaseArtifactSigFile.getAbsolutePath()); System.exit(1); } System.out.println("========================================="); System.out.println("Creating Release: " + releaseTag); System.out.println("Previous Release: " + oldReleaseTag); System.out.println(" Name: " + releaseName); System.out.println(" Artifact: " + releaseArtifact); System.out.println(" Pre-Release: " + isPrerelease); System.out.println("========================================="); String releaseNotes = ""; // Step #1 - Generate Release Notes // * Grab info about the previous release (extract publish date) // * Query all Issues for ones closed since that date // * Generate Release Notes from the resulting Issues try { System.out.println("Getting info about release " + oldReleaseTag); HttpResponse<JsonNode> response = Unirest .get("https://api.github.com/repos/apicurio/apicurio-studio/releases/tags/v" + oldReleaseTag) .header("Accept", "application/json").header("Authorization", "token " + githubPAT).asJson(); if (response.getStatus() != 200) { throw new Exception("Failed to get old release info: " + response.getStatusText()); } JsonNode body = response.getBody(); String publishedDate = body.getObject().getString("published_at"); if (publishedDate == null) { throw new Exception("Could not find Published Date for previous release " + oldReleaseTag); } System.out.println("Release " + oldReleaseTag + " was published on " + publishedDate); List<JSONObject> issues = getIssuesForRelease(publishedDate, githubPAT); System.out.println("Found " + issues.size() + " issues closed in release " + releaseTag); System.out.println("Generating Release Notes"); releaseNotes = generateReleaseNotes(releaseName, releaseTag, issues); System.out.println("------------ Release Notes --------------"); System.out.println(releaseNotes); System.out.println("-----------------------------------------"); } catch (Exception e) { e.printStackTrace(); System.exit(1); } String assetUploadUrl = null; // Step #2 - Create a GitHub Release try { System.out.println("\nCreating GitHub Release " + releaseTag); JSONObject body = new JSONObject(); body.put("tag_name", "v" + releaseTag); body.put("name", releaseName); body.put("body", releaseNotes); body.put("prerelease", isPrerelease); HttpResponse<JsonNode> response = Unirest .post("https://api.github.com/repos/apicurio/apicurio-studio/releases") .header("Accept", "application/json").header("Content-Type", "application/json") .header("Authorization", "token " + githubPAT).body(body).asJson(); if (response.getStatus() != 201) { throw new Exception("Failed to create release in GitHub: " + response.getStatusText()); } assetUploadUrl = response.getBody().getObject().getString("upload_url"); if (assetUploadUrl == null || assetUploadUrl.trim().isEmpty()) { throw new Exception("Failed to get Asset Upload URL for newly created release!"); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } // Step #3 - Upload Release Artifact (zip file) System.out.println("\nUploading Quickstart Artifact: " + releaseArtifact); try { String artifactUploadUrl = createUploadUrl(assetUploadUrl, releaseArtifact); byte[] artifactData = loadArtifactData(releaseArtifactFile); System.out.println("Uploading artifact asset: " + artifactUploadUrl); HttpResponse<JsonNode> response = Unirest.post(artifactUploadUrl).header("Accept", "application/json") .header("Content-Type", "application/zip").header("Authorization", "token " + githubPAT) .body(artifactData).asJson(); if (response.getStatus() != 201) { throw new Exception("Failed to upload asset: " + releaseArtifact, new Exception(response.getStatus() + "::" + response.getStatusText())); } Thread.sleep(1000); artifactUploadUrl = createUploadUrl(assetUploadUrl, releaseArtifactSig); artifactData = loadArtifactData(releaseArtifactSigFile); System.out.println("Uploading artifact asset: " + artifactUploadUrl); response = Unirest.post(artifactUploadUrl).header("Accept", "application/json") .header("Content-Type", "text/plain").header("Authorization", "token " + githubPAT) .body(artifactData).asJson(); if (response.getStatus() != 201) { throw new Exception("Failed to upload asset: " + releaseArtifactSig, new Exception(response.getStatus() + "::" + response.getStatusText())); } } catch (Exception e) { e.printStackTrace(); System.exit(1); } Thread.sleep(1000); // Step #4 - Download Latest Release JSON for inclusion in the project web site try { System.out.println("Getting info about the release."); HttpResponse<JsonNode> response = Unirest .get("https://api.github.com/repos/apicurio/apicurio-studio/releases/latest") .header("Accept", "application/json").asJson(); if (response.getStatus() != 200) { throw new Exception("Failed to get release info: " + response.getStatusText()); } JsonNode body = response.getBody(); String publishedDate = body.getObject().getString("published_at"); if (publishedDate == null) { throw new Exception("Could not find Published Date for release."); } String fname = publishedDate.replace(':', '-'); File outFile = new File(outputDir, fname + ".json"); System.out.println("Writing latest release info to: " + outFile.getAbsolutePath()); String output = body.getObject().toString(4); try (FileOutputStream fos = new FileOutputStream(outFile)) { fos.write(output.getBytes("UTF-8")); fos.flush(); } System.out.println("Release info successfully written."); } catch (Exception e) { e.printStackTrace(); System.exit(1); } System.out.println("========================================="); System.out.println("All Done!"); System.out.println("========================================="); }
From source file:cli.Main.java
public static void main(String[] args) { // Workaround for BKS truststore Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1); Namespace ns = parseArgs(args); if (ns == null) { System.exit(1);/*from w w w. j a va 2 s. c om*/ } final String username = ns.getString("username"); final Manager m = new Manager(username); if (m.userExists()) { try { m.load(); } catch (Exception e) { System.err.println("Error loading state file \"" + m.getFileName() + "\": " + e.getMessage()); System.exit(2); } } switch (ns.getString("command")) { case "register": if (!m.userHasKeys()) { m.createNewIdentity(); } try { m.register(ns.getBoolean("voice")); } catch (IOException e) { System.err.println("Request verify error: " + e.getMessage()); System.exit(3); } break; case "verify": if (!m.userHasKeys()) { System.err.println("User has no keys, first call register."); System.exit(1); } if (m.isRegistered()) { System.err.println("User registration is already verified"); System.exit(1); } try { m.verifyAccount(ns.getString("verificationCode")); } catch (IOException e) { System.err.println("Verify error: " + e.getMessage()); System.exit(3); } break; case "send": if (!m.isRegistered()) { System.err.println("User is not registered."); System.exit(1); } String messageText = ns.getString("message"); if (messageText == null) { try { messageText = IOUtils.toString(System.in); } catch (IOException e) { System.err.println("Failed to read message from stdin: " + e.getMessage()); System.exit(1); } } final List<String> attachments = ns.getList("attachment"); List<TextSecureAttachment> textSecureAttachments = null; if (attachments != null) { textSecureAttachments = new ArrayList<>(attachments.size()); for (String attachment : attachments) { try { File attachmentFile = new File(attachment); InputStream attachmentStream = new FileInputStream(attachmentFile); final long attachmentSize = attachmentFile.length(); String mime = Files.probeContentType(Paths.get(attachment)); textSecureAttachments .add(new TextSecureAttachmentStream(attachmentStream, mime, attachmentSize, null)); } catch (IOException e) { System.err.println("Failed to add attachment \"" + attachment + "\": " + e.getMessage()); System.err.println("Aborting sending."); System.exit(1); } } } List<TextSecureAddress> recipients = new ArrayList<>(ns.<String>getList("recipient").size()); for (String recipient : ns.<String>getList("recipient")) { try { recipients.add(m.getPushAddress(recipient)); } catch (InvalidNumberException e) { System.err.println("Failed to add recipient \"" + recipient + "\": " + e.getMessage()); System.err.println("Aborting sending."); System.exit(1); } } sendMessage(m, messageText, textSecureAttachments, recipients); break; case "receive": if (!m.isRegistered()) { System.err.println("User is not registered."); System.exit(1); } try { m.receiveMessages(5, true, new ReceiveMessageHandler(m)); } catch (IOException e) { System.err.println("Error while receiving message: " + e.getMessage()); System.exit(3); } catch (AssertionError e) { System.err.println("Failed to receive message (Assertion): " + e.getMessage()); System.err.println(e.getStackTrace()); System.err.println( "If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README"); System.exit(1); } break; } m.save(); System.exit(0); }
From source file:com.act.lcms.db.analysis.IonSearchAnalysis.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());//from w ww . ja v a 2 s .c o m } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY)); if (!lcmsDir.isDirectory()) { System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } Double fontScale = null; if (cl.hasOption("font-scale")) { try { fontScale = Double.parseDouble(cl.getOptionValue("font-scale")); } catch (IllegalArgumentException e) { System.err.format("Argument for font-scale must be a floating point number.\n"); System.exit(1); } } try (DB db = DB.openDBFromCLI(cl)) { Set<String> includeIons = null; if (cl.hasOption("include-ions")) { String[] ionNames = cl.getOptionValues("include-ions"); includeIons = new HashSet<>(Arrays.asList(ionNames)); System.out.format("Including ions in search: %s\n", StringUtils.join(includeIons, ", ")); } Set<String> excludeIons = null; if (cl.hasOption("exclude-ions")) { String[] ionNames = cl.getOptionValues("exclude-ions"); excludeIons = new HashSet<>(Arrays.asList(ionNames)); System.out.format("Excluding ions from search: %s\n", StringUtils.join(excludeIons, ", ")); } Set<Integer> takeSamplesFromPlateIds = null; if (cl.hasOption(OPTION_FILTER_BY_PLATE_BARCODE)) { String[] plateBarcodes = cl.getOptionValues(OPTION_FILTER_BY_PLATE_BARCODE); System.out.format("Considering only sample wells in plates: %s\n", StringUtils.join(plateBarcodes, ", ")); takeSamplesFromPlateIds = new HashSet<>(plateBarcodes.length); for (String plateBarcode : plateBarcodes) { Plate p = Plate.getPlateByBarcode(db, plateBarcode); if (p == null) { System.err.format("WARNING: unable to find plate in DB with barcode %s\n", plateBarcode); } else { takeSamplesFromPlateIds.add(p.getId()); } } // Allow filtering on barcode even if we couldn't find any in the DB. } System.out.format("Loading/updating LCMS scan files into DB\n"); ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir); System.out.format("Processing LCMS scans\n"); Pair<List<LCMSWell>, Set<Integer>> positiveWellsAndPlateIds = Utils.extractWellsAndPlateIds(db, cl.getOptionValues(OPTION_STRAINS), cl.getOptionValues(OPTION_CONSTRUCTS), takeSamplesFromPlateIds, false); List<LCMSWell> positiveWells = positiveWellsAndPlateIds.getLeft(); if (positiveWells.size() == 0) { throw new RuntimeException("Found no LCMS wells for specified strains/constructs"); } // Only take negative samples from the plates where we found the positive samples. Pair<List<LCMSWell>, Set<Integer>> negativeWellsAndPlateIds = Utils.extractWellsAndPlateIds(db, cl.getOptionValues(OPTION_NEGATIVE_STRAINS), cl.getOptionValues(OPTION_NEGATIVE_CONSTRUCTS), positiveWellsAndPlateIds.getRight(), true); List<LCMSWell> negativeWells = negativeWellsAndPlateIds.getLeft(); if (negativeWells == null || negativeWells.size() == 0) { System.err.format("WARNING: no valid negative samples found in same plates as positive samples\n"); } // Extract the reference MZ that will be used in the LCMS trace processing. List<Pair<String, Double>> searchMZs = null; Set<CuratedChemical> standardChemicals = null; List<ChemicalAssociatedWithPathway> pathwayChems = null; if (cl.hasOption(OPTION_SEARCH_MZ)) { // Assume mz can be an FP number of a chemical name. String massStr = cl.getOptionValue(OPTION_SEARCH_MZ); Pair<String, Double> searchMZ = Utils.extractMassFromString(db, massStr); if (searchMZ != null) { searchMZs = Collections.singletonList(searchMZ); } standardChemicals = Utils.extractTargetsForWells(db, positiveWells); } else { CuratedChemical targetChemical = Utils.requireOneTarget(db, positiveWells); if (targetChemical == null) { throw new RuntimeException( "Unable to find a curated chemical entry for specified strains'/constructs' targets. " + "Please specify a chemical name or m/z explicitly or update the curated chemicals list in the DB."); } System.out.format("Using reference M/Z for positive target %s (%f)\n", targetChemical.getName(), targetChemical.getMass()); searchMZs = Collections.singletonList(Pair.of(targetChemical.getName(), targetChemical.getMass())); standardChemicals = Collections.singleton(targetChemical); } // Look up the standard by name, or use the target if none is specified. List<StandardWell> standardWells = null; if (cl.hasOption(OPTION_NO_STANDARD)) { System.err.format("WARNING: skipping standard comparison (no-standard option specified)\n"); standardWells = new ArrayList<>(0); } else if (cl.hasOption(OPTION_STANDARD_WELLS)) { String[] standardCoordinates = cl.getOptionValues(OPTION_STANDARD_WELLS); standardWells = new ArrayList<>(standardCoordinates.length); Plate standardPlate = Plate.getPlateByBarcode(db, cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE)); List<String> foundCoordinates = new ArrayList<>(standardCoordinates.length); for (String stringCoords : standardCoordinates) { Pair<Integer, Integer> coords = Utils.parsePlateCoordinates(stringCoords); StandardWell well = StandardWell.getInstance().getStandardWellsByPlateIdAndCoordinates(db, standardPlate.getId(), coords.getLeft(), coords.getRight()); if (well == null) { System.err.format("Unable to find standard well at %s [%s]\n", standardPlate.getBarcode(), stringCoords); continue; } standardWells.add(well); foundCoordinates.add(stringCoords); } System.out.format("Using explicitly specified standard wells %s [%s]\n", standardPlate.getBarcode(), StringUtils.join(foundCoordinates, ", ")); } else if (cl.hasOption(OPTION_STANDARD_NAME)) { String standardName = cl.getOptionValue(OPTION_STANDARD_NAME); System.out.format("Using explicitly specified standard %s\n", standardName); standardWells = Collections.singletonList(Utils.extractStandardWellFromPlate(db, cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE), standardName)); } else if (standardChemicals != null && standardChemicals.size() > 0) { // Default to using the target chemical(s) as a standard if none is specified. standardWells = new ArrayList<>(standardChemicals.size()); for (CuratedChemical c : standardChemicals) { String standardName = c.getName(); System.out.format("Searching for well containing standard %s\n", standardName); standardWells.add(Utils.extractStandardWellFromPlate(db, cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE), standardName)); } } boolean useFineGrainedMZ = cl.hasOption("fine-grained-mz"); boolean useSNR = cl.hasOption(OPTION_USE_SNR); /* Process the standard, positive, and negative wells, producing ScanData containers that will allow them to be * iterated over for graph writing. */ HashMap<Integer, Plate> plateCache = new HashMap<>(); Pair<List<ScanData<StandardWell>>, Double> allStandardScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.STANDARD, plateCache, standardWells, useFineGrainedMZ, includeIons, excludeIons, useSNR); Pair<List<ScanData<LCMSWell>>, Double> allPositiveScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.POS_SAMPLE, plateCache, positiveWells, useFineGrainedMZ, includeIons, excludeIons, useSNR); Pair<List<ScanData<LCMSWell>>, Double> allNegativeScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.NEG_CONTROL, plateCache, negativeWells, useFineGrainedMZ, includeIons, excludeIons, useSNR); String fmt = "pdf"; String outImg = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + "." + fmt; String outData = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + ".data"; System.err.format("Writing combined scan data to %s and graphs to %s\n", outData, outImg); produceLCMSSearchPlots(lcmsDir, outData, outImg, allStandardScans, allPositiveScans, allNegativeScans, fontScale, useFineGrainedMZ, cl.hasOption(OPTION_USE_HEATMAP), useSNR); } }
From source file:ensen.controler.DBpediaSpotlightClient.java
public static void main(String[] args) throws Exception { DBpediaSpotlightClient c = new DBpediaSpotlightClient(); //c.local = true; List<EnsenDBpediaResource> res = c.ensenExtract(new Text( "President Obama on Monday will call for a new minimum tax rate for individuals making more than $1 million a year to ensure that they pay at least the same percentage of their earnings as other taxpayers, according to administration officials.")); for (int i = 0; i < res.size(); i++) { EnsenDBpediaResource R = res.get(i); //System.out.println(R.getFullUri()); }// w ww . java 2 s . co m }
From source file:movierecommend.MovieRecommend.java
public static void main(String[] args) throws ClassNotFoundException, SQLException { String url = "jdbc:sqlserver://localhost;databaseName=MovieDB;integratedSecurity=true"; Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); Connection conn = DriverManager.getConnection(url); Statement stm = conn.createStatement(); ResultSet rsRecnik = stm.executeQuery("SELECT Recnik FROM Recnik WHERE (ID_Zanra = 1)"); //citam recnik iz baze za odredjeni zanr String recnik[] = null;/*from w w w.j a v a 2 s.c o m*/ while (rsRecnik.next()) { recnik = rsRecnik.getString("Recnik").split(","); //delim recnik na reci } ResultSet rsFilmovi = stm.executeQuery( "SELECT TOP (200) Naziv_Filma, LemmaPlots, " + "ID_Filma FROM Film WHERE (ID_Zanra = 1)"); List<Film> listaFilmova = new ArrayList<>(); Film f = null; int rb = 0; while (rsFilmovi.next()) { f = new Film(rb, Integer.parseInt(rsFilmovi.getString("ID_Filma")), rsFilmovi.getString("Naziv_Filma"), rsFilmovi.getString("LemmaPlots")); listaFilmova.add(f); rb++; } //kreiranje vektorskog modela M = MatrixUtils.createRealMatrix(recnik.length, listaFilmova.size()); System.out.println("Prva tezinska matrica"); for (int i = 0; i < recnik.length; i++) { String recBaza = recnik[i]; for (Film film : listaFilmova) { for (String lemmaRec : film.getPlotLema()) { if (recBaza.equals(lemmaRec)) { M.setEntry(i, film.getRb(), M.getEntry(i, film.getRb()) + 1); } } } } //racunanje tf-idf System.out.println("td-idf"); M = LSA.calculateTfIdf(M); System.out.println("SVD"); //SVD SingularValueDecomposition svd = new SingularValueDecomposition(M); RealMatrix V = svd.getV(); RealMatrix Vk = V.getSubMatrix(0, V.getRowDimension() - 1, 0, brojDimenzija - 1); //dimenzija je poslednji argument //kosinusna slicnost System.out.println("Cosin simmilarity"); CallableStatement stmTop = conn.prepareCall("{call Dodaj_TopList(?,?,?)}"); for (int j = 0; j < listaFilmova.size(); j++) { Film fl = listaFilmova.get(j); List<Film> lFilmova1 = new ArrayList<>(); lFilmova1.add(listaFilmova.get(j)); double sim = 0.0; for (int k = 0; k < listaFilmova.size(); k++) { // System.out.println(listaFilmova.size()); sim = LSA.cosinSim(j, k, Vk.transpose()); listaFilmova.get(k).setSimilarity(sim); lFilmova1.add(listaFilmova.get(k)); } Collections.sort(lFilmova1); for (int k = 2; k < 13; k++) { stmTop.setString(1, fl.getID() + ""); stmTop.setString(2, lFilmova1.get(k).getID() + ""); stmTop.setString(3, lFilmova1.get(k).getSimilarity() + ""); stmTop.execute(); } } stm.close(); rsRecnik.close(); rsFilmovi.close(); conn.close(); }
From source file:example.client.CamelMongoJmsStockClient.java
@SuppressWarnings("resource") public static void main(final String[] args) throws Exception { systemProps = loadProperties();//from w ww .j av a 2s . c o m AbstractApplicationContext context = new ClassPathXmlApplicationContext("camel-client.xml"); ProducerTemplate camelTemplate = context.getBean("camelTemplate", ProducerTemplate.class); List<Map<String, Object>> stocks = readJsonsFromMongoDB(); for (Map<String, Object> stock : stocks) { stock.remove("_id"); stock.remove("Earnings Date"); camelTemplate.sendBody(String.format("jms:queue:%s", systemProps.getProperty("ticker.queue.name")), ExchangePattern.InOnly, stock); } new Timer().schedule(new TimerTask() { @Override public void run() { Map<String, Object> aRandomStock = stocks.get(RandomUtils.nextInt(0, stocks.size())); aRandomStock.put("Price", ((Double) aRandomStock.get("Price")) + RandomUtils.nextFloat(0.1f, 9.99f)); camelTemplate.sendBody(String.format("jms:queue:%s", systemProps.getProperty("ticker.queue.name")), ExchangePattern.InOnly, aRandomStock); } }, 1000, 2000); }
From source file:com.strider.datadefender.DataDefender.java
@SuppressWarnings("unchecked") public static void main(final String[] args) throws ParseException, DatabaseDiscoveryException, IOException, SAXException, TikaException, java.text.ParseException, FileDiscoveryException { final long startTime = System.currentTimeMillis(); // Ensure we are not trying to run second instance of the same program final ApplicationLock al = new ApplicationLock("DataDefender"); if (al.isAppActive()) { LOG.error("Another instance of this program is already active"); displayExecutionTime(startTime); System.exit(1);//ww w. j a va 2 s .co m } LOG.info("Command-line arguments: " + Arrays.toString(args)); final Options options = createOptions(); final CommandLine line = getCommandLine(options, args); @SuppressWarnings("unchecked") List<String> unparsedArgs = line.getArgList(); if (line.hasOption("help") || (args.length == 0) || (unparsedArgs.size() < 1)) { help(options); displayExecutionTime(startTime); return; } if (line.hasOption("debug")) { LogManager.getRootLogger().setLevel(Level.DEBUG); } else { LogManager.getRootLogger().setLevel(Level.INFO); } final String cmd = unparsedArgs.get(0); // get & remove command arg unparsedArgs = unparsedArgs.subList(1, unparsedArgs.size()); List<String> errors = new ArrayList(); if ("file-discovery".equals(cmd)) { errors = PropertyCheck.check(cmd, ' '); if (errors.size() > 0) { displayErrors(errors); displayExecutionTime(startTime); return; } final String fileDiscoveryPropertyFile = line.getOptionValue('F', "filediscovery.properties"); final Properties fileDiscoveryProperties = loadPropertiesFromClassPath(fileDiscoveryPropertyFile); final FileDiscoverer discoverer = new FileDiscoverer(); discoverer.discover(fileDiscoveryProperties); displayExecutionTime(startTime); return; } // Get db properties file from command line argument or use default db.properties final String dbPropertiesFile = line.getOptionValue('P', "db.properties"); errors = PropertyCheck.checkDtabaseProperties(dbPropertiesFile); if (errors.size() > 0) { displayErrors(errors); displayExecutionTime(startTime); return; } final Properties props = loadProperties(dbPropertiesFile); try (final IDBFactory dbFactory = IDBFactory.get(props);) { switch (cmd) { case "anonymize": errors = PropertyCheck.check(cmd, ' '); if (errors.size() > 0) { displayErrors(errors); displayExecutionTime(startTime); return; } final String anonymizerPropertyFile = line.getOptionValue('A', "anonymizer.properties"); final Properties anonymizerProperties = loadProperties(anonymizerPropertyFile); final IAnonymizer anonymizer = new DatabaseAnonymizer(); anonymizer.anonymize(dbFactory, anonymizerProperties); break; case "generate": errors = PropertyCheck.check(cmd, ' '); if (errors.size() > 0) { displayErrors(errors); displayExecutionTime(startTime); return; } final IGenerator generator = new DataGenerator(); final String generatorPropertyFile = line.getOptionValue('A', "anonymizer.properties"); final Properties generatorProperties = loadProperties(generatorPropertyFile); generator.generate(dbFactory, generatorProperties); break; case "database-discovery": if (line.hasOption('c')) { errors = PropertyCheck.check(cmd, 'c'); if (errors.size() > 0) { displayErrors(errors); displayExecutionTime(startTime); return; } final String columnPropertyFile = line.getOptionValue('C', "columndiscovery.properties"); final Properties columnProperties = loadProperties(columnPropertyFile); final ColumnDiscoverer discoverer = new ColumnDiscoverer(); discoverer.discover(dbFactory, columnProperties, props.getProperty("vendor")); if (line.hasOption('r')) { discoverer.createRequirement("Sample-Requirement.xml"); } } else if (line.hasOption('d')) { errors = PropertyCheck.check(cmd, 'd'); if (errors.size() > 0) { displayErrors(errors); displayExecutionTime(startTime); return; } final String datadiscoveryPropertyFile = line.getOptionValue('D', "datadiscovery.properties"); final Properties dataDiscoveryProperties = loadProperties(datadiscoveryPropertyFile); final DatabaseDiscoverer discoverer = new DatabaseDiscoverer(); discoverer.discover(dbFactory, dataDiscoveryProperties, props.getProperty("vendor")); if (line.hasOption('r')) { discoverer.createRequirement("Sample-Requirement.xml"); } } break; default: help(options); break; } } displayExecutionTime(startTime); }
From source file:com.twinsoft.convertigo.beans.CheckBeans.java
public static void main(String[] args) { Engine.logBeans = Logger.getLogger(BeansDoc.class); srcBase = args[0];//from ww w . j av a 2s . c o m System.out.println("Loading database objects XML DB in " + srcBase); try { defaultDocumentBuilderFactory = DocumentBuilderFactory.newInstance(); defaultDocumentBuilder = defaultDocumentBuilderFactory.newDocumentBuilder(); dboXmlDeclaredDatabaseObjects = new ArrayList<String>(); Document dboXmlDocument = defaultDocumentBuilder.parse( new FileInputStream(new File(srcBase + "/com/twinsoft/convertigo/beans/database_objects.xml"))); NodeList beanList = dboXmlDocument.getElementsByTagName("bean"); int n = beanList.getLength(); for (int i = 0; i < n; i++) { Element element = (Element) beanList.item(i); dboXmlDeclaredDatabaseObjects.add(element.getAttribute("classname")); } } catch (Exception e) { System.out.println("Error while loading DBO XML DB"); e.printStackTrace(); System.exit(-1); } System.out.println("Browsing sources in " + srcBase); browsePackages(srcBase + "com/twinsoft/convertigo/beans"); System.out.println(); System.out.println("Found " + javaClassNames.size() + " classes"); for (String javaClassName : javaClassNames) { analyzeJavaClass(javaClassName); } for (String icon : icons) { Error.BEAN_ICON_NOT_USED.add(icon); } System.out.println(); for (Error error : Error.values()) { List<String> errorList = errors.get(error); if (errorList == null) continue; int nError = errorList.size(); System.out.println(error + " (" + nError + ")"); for (String errorMessage : errorList) { System.out.println(" " + errorMessage); } System.out.println(); } System.out.println(); System.out.println("======="); System.out.println("Summary"); System.out.println("======="); System.out.println(); System.out.println("Found " + nBeanClass + " bean classes (including abstract classes)"); System.out.println("Found " + nBeanClassNotAbstract + " instantiable bean classes"); System.out.println(); int nTotalError = 0; for (Error error : Error.values()) { List<String> errorList = errors.get(error); int nError = 0; if (errorList != null) nError = errorList.size(); nTotalError += nError; System.out.println(error + ": found " + nError + " error(s)"); } System.out.println(); System.out.println("Found " + nTotalError + " error(s)"); System.out.println(); System.out.println("Beans check finished!"); System.exit(nTotalError); }