List of usage examples for java.util List remove
E remove(int index);
From source file:acmi.l2.clientmod.l2_version_switcher.Main.java
public static void main(String[] args) { if (args.length != 3 && args.length != 4) { System.out.println("USAGE: l2_version_switcher.jar host game version <--splash> <filter>"); System.out.println("EXAMPLE: l2_version_switcher.jar " + L2.NCWEST_HOST + " " + L2.NCWEST_GAME + " 1 \"system\\*\""); System.out.println(//from w w w . j av a2s. co m " l2_version_switcher.jar " + L2.PLAYNC_TEST_HOST + " " + L2.PLAYNC_TEST_GAME + " 48"); System.exit(0); } List<String> argsList = new ArrayList<>(Arrays.asList(args)); String host = argsList.get(0); String game = argsList.get(1); int version = Integer.parseInt(argsList.get(2)); Helper helper = new Helper(host, game, version); boolean available = false; try { available = helper.isAvailable(); } catch (IOException e) { System.err.print(e.getClass().getSimpleName()); if (e.getMessage() != null) { System.err.print(": " + e.getMessage()); } System.err.println(); } System.out.println(String.format("Version %d available: %b", version, available)); if (!available) { System.exit(0); } List<FileInfo> fileInfoList = null; try { fileInfoList = helper.getFileInfoList(); } catch (IOException e) { System.err.println("Couldn\'t get file info map"); System.exit(1); } boolean splash = argsList.remove("--splash"); if (splash) { Optional<FileInfo> splashObj = fileInfoList.stream() .filter(fi -> fi.getPath().contains("sp_32b_01.bmp")).findAny(); if (splashObj.isPresent()) { try (InputStream is = new FilterInputStream( Util.getUnzipStream(helper.getDownloadStream(splashObj.get().getPath()))) { @Override public int read() throws IOException { int b = super.read(); if (b >= 0) b ^= 0x36; return b; } @Override public int read(byte[] b, int off, int len) throws IOException { int r = super.read(b, off, len); if (r >= 0) { for (int i = 0; i < r; i++) b[off + i] ^= 0x36; } return r; } }) { new DataInputStream(is).readFully(new byte[28]); BufferedImage bi = ImageIO.read(is); JFrame frame = new JFrame("Lineage 2 [" + version + "] " + splashObj.get().getPath()); frame.setContentPane(new JComponent() { { setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight())); } @Override protected void paintComponent(Graphics g) { g.drawImage(bi, 0, 0, null); } }); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println("Splash not found"); } return; } String filter = argsList.size() > 3 ? separatorsToSystem(argsList.get(3)) : null; File l2Folder = new File(System.getProperty("user.dir")); List<FileInfo> toUpdate = fileInfoList.parallelStream().filter(fi -> { String filePath = separatorsToSystem(fi.getPath()); if (filter != null && !wildcardMatch(filePath, filter, IOCase.INSENSITIVE)) return false; File file = new File(l2Folder, filePath); try { if (file.exists() && file.length() == fi.getSize() && Util.hashEquals(file, fi.getHash())) { System.out.println(filePath + ": OK"); return false; } } catch (IOException e) { System.out.println(filePath + ": couldn't check hash: " + e); return true; } System.out.println(filePath + ": need update"); return true; }).collect(Collectors.toList()); List<String> errors = Collections.synchronizedList(new ArrayList<>()); ExecutorService executor = Executors.newFixedThreadPool(16); CompletableFuture[] tasks = toUpdate.stream().map(fi -> CompletableFuture.runAsync(() -> { String filePath = separatorsToSystem(fi.getPath()); File file = new File(l2Folder, filePath); File folder = file.getParentFile(); if (!folder.exists()) { if (!folder.mkdirs()) { errors.add(filePath + ": couldn't create parent dir"); return; } } try (InputStream input = Util .getUnzipStream(new BufferedInputStream(helper.getDownloadStream(fi.getPath()))); OutputStream output = new BufferedOutputStream(new FileOutputStream(file))) { byte[] buffer = new byte[Math.min(fi.getSize(), 1 << 24)]; int pos = 0; int r; while ((r = input.read(buffer, pos, buffer.length - pos)) >= 0) { pos += r; if (pos == buffer.length) { output.write(buffer, 0, pos); pos = 0; } } if (pos != 0) { output.write(buffer, 0, pos); } System.out.println(filePath + ": OK"); } catch (IOException e) { String msg = filePath + ": FAIL: " + e.getClass().getSimpleName(); if (e.getMessage() != null) { msg += ": " + e.getMessage(); } errors.add(msg); } }, executor)).toArray(CompletableFuture[]::new); CompletableFuture.allOf(tasks).thenRun(() -> { for (String err : errors) System.err.println(err); executor.shutdown(); }); }
From source file:com.github.vatbub.awsvpnlauncher.Main.java
public static void main(String[] args) { Common.getInstance().setAppName("awsVpnLauncher"); FOKLogger.enableLoggingOfUncaughtExceptions(); prefs = new Preferences(Main.class.getName()); // enable the shutdown hook Runtime.getRuntime().addShutdownHook(new Thread(() -> { if (session != null) { if (session.isConnected()) { session.disconnect();//from w w w .ja v a 2s . co m } } })); UpdateChecker.completeUpdate(args, (oldVersion, oldFile) -> { if (oldVersion != null) { FOKLogger.info(Main.class.getName(), "Successfully upgraded " + Common.getInstance().getAppName() + " from v" + oldVersion.toString() + " to v" + Common.getInstance().getAppVersion()); } }); List<String> argsAsList = new ArrayList<>(Arrays.asList(args)); for (String arg : args) { if (arg.toLowerCase().matches("mockappversion=.*")) { // Set the mock version String version = arg.substring(arg.toLowerCase().indexOf('=') + 1); Common.getInstance().setMockAppVersion(version); argsAsList.remove(arg); } else if (arg.toLowerCase().matches("mockbuildnumber=.*")) { // Set the mock build number String buildnumber = arg.substring(arg.toLowerCase().indexOf('=') + 1); Common.getInstance().setMockBuildNumber(buildnumber); argsAsList.remove(arg); } else if (arg.toLowerCase().matches("mockpackaging=.*")) { // Set the mock packaging String packaging = arg.substring(arg.toLowerCase().indexOf('=') + 1); Common.getInstance().setMockPackaging(packaging); argsAsList.remove(arg); } } args = argsAsList.toArray(new String[0]); try { mvnRepoConfig = new Config( new URL("https://www.dropbox.com/s/vnhs4nax2lczccf/mavenRepoConfig.properties?dl=1"), Main.class.getResource("mvnRepoFallbackConfig.properties"), true, "mvnRepoCachedConfig", true); projectConfig = new Config( new URL("https://www.dropbox.com/s/d36hwrrufoxfmm7/projectConfig.properties?dl=1"), Main.class.getResource("projectFallbackConfig.properties"), true, "projectCachedConfig", true); } catch (IOException e) { FOKLogger.log(Main.class.getName(), Level.SEVERE, "Could not load the remote config", e); } try { installUpdates(args); } catch (Exception e) { FOKLogger.log(Main.class.getName(), Level.SEVERE, "Could not install updates", e); } if (args.length == 0) { // not enough arguments printHelpMessage(); throw new NotEnoughArgumentsException(); } switch (args[0].toLowerCase()) { case "setup": setup(); break; case "launch": initAWSConnection(); launch(); break; case "terminate": initAWSConnection(); terminate(); break; case "config": // require a second arg if (args.length == 2) { // not enough arguments printHelpMessage(); throw new NotEnoughArgumentsException(); } config(Property.valueOf(args[1]), args[2]); break; case "getconfig": // require a second arg if (args.length == 1) { // not enough arguments printHelpMessage(); throw new NotEnoughArgumentsException(); } getConfig(Property.valueOf(args[1])); break; case "printconfig": printConfig(); break; case "deleteconfig": // require a second arg if (args.length == 1) { // not enough arguments printHelpMessage(); throw new NotEnoughArgumentsException(); } deleteConfig(Property.valueOf(args[1])); break; case "ssh": String sshInstanceId; if (args.length == 2) { // a instanceID is specified sshInstanceId = args[1]; } else { String instanceIdsPrefValue = prefs.getPreference("instanceIDs", ""); if (instanceIdsPrefValue.equals("")) { throw new NotEnoughArgumentsException( "No instanceId was specified to connect to and no instanceId was saved in the preference file. Please either start another instance using the launch command or specify the instance id of the instance to connect to as a additional parameter."); } List<String> instanceIds = Arrays.asList(instanceIdsPrefValue.split(";")); if (instanceIds.size() == 1) { // exactly one instance found sshInstanceId = instanceIds.get(0); } else { FOKLogger.severe(Main.class.getName(), "Multiple instance ids found:"); for (String instanceId : instanceIds) { FOKLogger.severe(Main.class.getName(), instanceId); } throw new NotEnoughArgumentsException( "Multiple instance ids were found in the preference file. Please specify the instance id of the instance to connect to as a additional parameter."); } } initAWSConnection(); ssh(sshInstanceId); break; default: printHelpMessage(); } }
From source file:com.aerospike.load.AerospikeLoad.java
public static void main(String[] args) throws IOException { Thread statPrinter = new Thread(new PrintStat(counters)); try {/*from ww w. j a v a 2 s. c o m*/ log.info("Aerospike loader started"); Options options = new Options(); options.addOption("h", "host", true, "Server hostname (default: localhost)"); options.addOption("p", "port", true, "Server port (default: 3000)"); options.addOption("n", "namespace", true, "Namespace (default: test)"); options.addOption("s", "set", true, "Set name. (default: null)"); options.addOption("c", "config", true, "Column definition file name"); options.addOption("wt", "write-threads", true, "Number of writer threads (default: Number of cores * 5)"); options.addOption("rt", "read-threads", true, "Number of reader threads (default: Number of cores * 1)"); options.addOption("l", "rw-throttle", true, "Throttling of reader to writer(default: 10k) "); options.addOption("tt", "transaction-timeout", true, "write transaction timeout in miliseconds(default: No timeout)"); options.addOption("et", "expiration-time", true, "Expiration time of records in seconds (default: never expire)"); options.addOption("T", "timezone", true, "Timezone of source where data dump is taken (default: local timezone)"); options.addOption("ec", "abort-error-count", true, "Error count to abort (default: 0)"); options.addOption("wa", "write-action", true, "Write action if key already exists (default: update)"); options.addOption("v", "verbose", false, "Logging all"); options.addOption("u", "usage", false, "Print usage."); CommandLineParser parser = new PosixParser(); CommandLine cl = parser.parse(options, args, false); if (args.length == 0 || cl.hasOption("u")) { logUsage(options); return; } if (cl.hasOption("l")) { rwThrottle = Integer.parseInt(cl.getOptionValue("l")); } else { rwThrottle = Constants.READLOAD; } // Get all command line options params = Utils.parseParameters(cl); //Get client instance AerospikeClient client = new AerospikeClient(params.host, params.port); if (!client.isConnected()) { log.error("Client is not able to connect:" + params.host + ":" + params.port); return; } if (params.verbose) { log.setLevel(Level.DEBUG); } // Get available processors to calculate default number of threads int cpus = Runtime.getRuntime().availableProcessors(); nWriterThreads = cpus * scaleFactor; nReaderThreads = cpus; // Get writer thread count if (cl.hasOption("wt")) { nWriterThreads = Integer.parseInt(cl.getOptionValue("wt")); nWriterThreads = (nWriterThreads > 0 ? (nWriterThreads > Constants.MAX_THREADS ? Constants.MAX_THREADS : nWriterThreads) : 1); log.debug("Using writer Threads: " + nWriterThreads); } writerPool = Executors.newFixedThreadPool(nWriterThreads); // Get reader thread count if (cl.hasOption("rt")) { nReaderThreads = Integer.parseInt(cl.getOptionValue("rt")); nReaderThreads = (nReaderThreads > 0 ? (nReaderThreads > Constants.MAX_THREADS ? Constants.MAX_THREADS : nReaderThreads) : 1); log.debug("Using reader Threads: " + nReaderThreads); } String columnDefinitionFileName = cl.getOptionValue("c", null); log.debug("Column definition files/directory: " + columnDefinitionFileName); if (columnDefinitionFileName == null) { log.error("Column definition files/directory not specified. use -c <file name>"); return; } File columnDefinitionFile = new File(columnDefinitionFileName); if (!columnDefinitionFile.exists()) { log.error("Column definition files/directory does not exist: " + Utils.getFileName(columnDefinitionFileName)); return; } // Get data file list String[] files = cl.getArgs(); if (files.length == 0) { log.error("No data file Specified: add <file/dir name> to end of the command "); return; } List<String> allFileNames = new ArrayList<String>(); allFileNames = Utils.getFileNames(files); if (allFileNames.size() == 0) { log.error("Given datafiles/directory does not exist"); return; } for (int i = 0; i < allFileNames.size(); i++) { log.debug("File names:" + Utils.getFileName(allFileNames.get(i))); File file = new File(allFileNames.get(i)); counters.write.recordTotal = counters.write.recordTotal + file.length(); } //remove column definition file from list allFileNames.remove(columnDefinitionFileName); log.info("Number of data files:" + allFileNames.size()); /** * Process column definition file to get meta data and bin mapping. */ metadataColumnDefs = new ArrayList<ColumnDefinition>(); binColumnDefs = new ArrayList<ColumnDefinition>(); metadataConfigs = new HashMap<String, String>(); if (Parser.processJSONColumnDefinitions(columnDefinitionFile, metadataConfigs, metadataColumnDefs, binColumnDefs, params)) { log.info("Config file processed."); } else { throw new Exception("Config file parsing Error"); } // Add metadata of config to parameters String metadata; if ((metadata = metadataConfigs.get(Constants.INPUT_TYPE)) != null) { params.fileType = metadata; if (params.fileType.equals(Constants.CSV_FILE)) { // Version check metadata = metadataConfigs.get(Constants.VERSION); String[] vNumber = metadata.split("\\."); int v1 = Integer.parseInt(vNumber[0]); int v2 = Integer.parseInt(vNumber[1]); if ((v1 <= Constants.MajorV) && (v2 <= Constants.MinorV)) { log.debug("Config version used:" + metadata); } else throw new Exception("\"" + Constants.VERSION + ":" + metadata + "\" is not Supported"); // Set delimiter if ((metadata = metadataConfigs.get(Constants.DELIMITER)) != null && metadata.length() == 1) { params.delimiter = metadata.charAt(0); } else { log.warn("\"" + Constants.DELIMITER + ":" + metadata + "\" is not properly specified in config file. Default is ','"); } if ((metadata = metadataConfigs.get(Constants.IGNORE_FIRST_LINE)) != null) { params.ignoreFirstLine = metadata.equals("true"); } else { log.warn("\"" + Constants.IGNORE_FIRST_LINE + ":" + metadata + "\" is not properly specified in config file. Default is false"); } if ((metadata = metadataConfigs.get(Constants.COLUMNS)) != null) { counters.write.colTotal = Integer.parseInt(metadata); } else { throw new Exception("\"" + Constants.COLUMNS + ":" + metadata + "\" is not properly specified in config file"); } } else { throw new Exception("\"" + params.fileType + "\" is not supported in config file"); } } else { throw new Exception("\"" + Constants.INPUT_TYPE + "\" is not specified in config file"); } // add config input to column definitions if (params.fileType.equals(Constants.CSV_FILE)) { List<String> binName = null; if (params.ignoreFirstLine) { String line; BufferedReader br = new BufferedReader( new InputStreamReader(new FileInputStream(allFileNames.get(0)), "UTF8")); if ((line = br.readLine()) != null) { binName = Parser.getCSVRawColumns(line, params.delimiter); br.close(); if (binName.size() != counters.write.colTotal) { throw new Exception("Number of column in config file and datafile are mismatch." + " Datafile: " + Utils.getFileName(allFileNames.get(0)) + " Configfile: " + Utils.getFileName(columnDefinitionFileName)); } } } //update columndefs for metadata for (int i = 0; i < metadataColumnDefs.size(); i++) { if (metadataColumnDefs.get(i).staticValue) { } else { if (metadataColumnDefs.get(i).binValuePos < 0) { if (metadataColumnDefs.get(i).columnName == null) { if (metadataColumnDefs.get(i).jsonPath == null) { log.error("dynamic metadata having improper info" + metadataColumnDefs.toString()); //TODO } else { //TODO check for json_path } } else { if (params.ignoreFirstLine) { if (binName.indexOf(metadataColumnDefs.get(i).binValueHeader) != -1) { metadataColumnDefs.get(i).binValuePos = binName .indexOf(metadataColumnDefs.get(i).binValueHeader); } else { throw new Exception("binName missing in data file:" + metadataColumnDefs.get(i).binValueHeader); } } } } else { if (params.ignoreFirstLine) metadataColumnDefs.get(i).binValueHeader = binName .get(metadataColumnDefs.get(i).binValuePos); } } if ((!metadataColumnDefs.get(i).staticValue) && (metadataColumnDefs.get(i).binValuePos < 0)) { throw new Exception("Information for bin mapping is missing in config file:" + metadataColumnDefs.get(i)); } if (metadataColumnDefs.get(i).srcType == null) { throw new Exception( "Source data type is not properly mentioned:" + metadataColumnDefs.get(i)); } if (metadataColumnDefs.get(i).binNameHeader == Constants.SET && !metadataColumnDefs.get(i).srcType.equals(SrcColumnType.STRING)) { throw new Exception("Set name should be string type:" + metadataColumnDefs.get(i)); } if (metadataColumnDefs.get(i).binNameHeader.equalsIgnoreCase(Constants.SET) && params.set != null) { throw new Exception( "Set name is given both in config file and commandline. Provide only once."); } } //update columndefs for bins for (int i = 0; i < binColumnDefs.size(); i++) { if (binColumnDefs.get(i).staticName) { } else { if (binColumnDefs.get(i).binNamePos < 0) { if (binColumnDefs.get(i).columnName == null) { if (binColumnDefs.get(i).jsonPath == null) { log.error("dynamic bin having improper info"); //TODO } else { //TODO check for json_path } } else { if (params.ignoreFirstLine) { if (binName.indexOf(binColumnDefs.get(i).binNameHeader) != -1) { binColumnDefs.get(i).binNamePos = binName .indexOf(binColumnDefs.get(i).binNameHeader); } else { throw new Exception("binName missing in data file:" + binColumnDefs.get(i).binNameHeader); } } } } else { if (params.ignoreFirstLine) binColumnDefs.get(i).binNameHeader = binName.get(binColumnDefs.get(i).binNamePos); } } if (binColumnDefs.get(i).staticValue) { } else { if (binColumnDefs.get(i).binValuePos < 0) { if (binColumnDefs.get(i).columnName == null) { if (binColumnDefs.get(i).jsonPath == null) { log.error("dynamic bin having improper info"); //TODO } else { //TODO check for json_path } } else { if (params.ignoreFirstLine) { if (binName.contains(binColumnDefs.get(i).binValueHeader)) { binColumnDefs.get(i).binValuePos = binName .indexOf(binColumnDefs.get(i).binValueHeader); } else if (!binColumnDefs.get(i).binValueHeader.toLowerCase() .equals(Constants.SYSTEM_TIME)) { throw new Exception("Wrong column name mentioned in config file:" + binColumnDefs.get(i).binValueHeader); } } } } else { if (params.ignoreFirstLine) binColumnDefs.get(i).binValueHeader = binName.get(binColumnDefs.get(i).binValuePos); } //check for missing entries in config file if (binColumnDefs.get(i).binValuePos < 0 && binColumnDefs.get(i).binValueHeader == null) { throw new Exception("Information missing(Value header or bin mapping) in config file:" + binColumnDefs.get(i)); } //check for proper data type in config file. if (binColumnDefs.get(i).srcType == null) { throw new Exception( "Source data type is not properly mentioned:" + binColumnDefs.get(i)); } //check for valid destination type if ((binColumnDefs.get(i).srcType.equals(SrcColumnType.TIMESTAMP) || binColumnDefs.get(i).srcType.equals(SrcColumnType.BLOB)) && binColumnDefs.get(i).dstType == null) { throw new Exception("Destination type is not mentioned: " + binColumnDefs.get(i)); } //check for encoding if (binColumnDefs.get(i).dstType != null && binColumnDefs.get(i).encoding == null) { throw new Exception( "Encoding is not given for src-dst type conversion:" + binColumnDefs.get(i)); } //check for valid encoding if (binColumnDefs.get(i).srcType.equals(SrcColumnType.BLOB) && !binColumnDefs.get(i).encoding.equals(Constants.HEX_ENCODING)) { throw new Exception("Wrong encoding for blob data:" + binColumnDefs.get(i)); } } //Check static bin name mapped to dynamic bin value if ((binColumnDefs.get(i).binNamePos == binColumnDefs.get(i).binValuePos) && (binColumnDefs.get(i).binNamePos != -1)) { throw new Exception("Static bin name mapped to dynamic bin value:" + binColumnDefs.get(i)); } //check for missing entries in config file if (binColumnDefs.get(i).binNameHeader == null && binColumnDefs.get(i).binNameHeader.length() > Constants.BIN_NAME_LENGTH) { throw new Exception("Information missing binName or large binName in config file:" + binColumnDefs.get(i)); } } } log.info(params.toString()); log.debug("MetadataConfig:" + metadataColumnDefs); log.debug("BinColumnDefs:" + binColumnDefs); // Start PrintStat thread statPrinter.start(); // Reader pool size ExecutorService readerPool = Executors.newFixedThreadPool( nReaderThreads > allFileNames.size() ? allFileNames.size() : nReaderThreads); log.info("Reader pool size : " + nReaderThreads); // Submit all tasks to writer threadpool. for (String aFile : allFileNames) { log.debug("Submitting task for: " + aFile); readerPool.submit(new AerospikeLoad(aFile, client, params)); } // Wait for reader pool to complete readerPool.shutdown(); log.info("Shutdown down reader thread pool"); while (!readerPool.isTerminated()) ; //readerPool.awaitTermination(20, TimeUnit.MINUTES); log.info("Reader thread pool terminated"); // Wait for writer pool to complete after getting all tasks from reader pool writerPool.shutdown(); log.info("Shutdown down writer thread pool"); while (!writerPool.isTerminated()) ; log.info("Writer thread pool terminated"); // Print final statistic of aerospike-loader. log.info("Final Statistics of importer: (Succesfull Writes = " + counters.write.writeCount.get() + ", " + "Errors=" + (counters.write.writeErrors.get() + counters.write.readErrors.get() + counters.write.processingErrors.get()) + "(" + (counters.write.writeErrors.get()) + "-Write," + counters.write.readErrors.get() + "-Read," + counters.write.processingErrors.get() + "-Processing)"); } catch (Exception e) { log.error(e); if (log.isDebugEnabled()) { e.printStackTrace(); } } finally { // Stop statistic printer thread. statPrinter.interrupt(); log.info("Aerospike loader completed"); } }
From source file:com.px100systems.data.utility.RestoreUtility.java
public static void main(String[] args) { if (args.length < 3) { System.err.println("Usage: java -cp ... com.px100systems.data.utility.RestoreUtility " + "<springXmlConfigFile> <persisterBeanName> <backupDirectory> [compare]"); return;//from w w w . j a v a2 s . co m } FileSystemXmlApplicationContext ctx = new FileSystemXmlApplicationContext("file:" + args[0]); try { PersistenceProvider persister = ctx.getBean(args[1], PersistenceProvider.class); File directory = new File(args[2]); if (!directory.isDirectory()) { System.err.println(directory.getName() + " is not a directory"); return; } List<File> files = new ArrayList<File>(); //noinspection ConstantConditions for (File file : directory.listFiles()) if (BackupFile.isBackup(file)) files.add(file); if (files.isEmpty()) { System.err.println(directory.getName() + " directory has no backup files"); return; } if (args.length == 4 && args[3].equalsIgnoreCase("compare")) { final Map<String, Map<Long, RawRecord>> units = new HashMap<String, Map<Long, RawRecord>>(); for (String storage : persister.storage()) { System.out.println("Storage " + storage); persister.loadByStorage(storage, new PersistenceProvider.LoadCallback() { @Override public void process(RawRecord record) { Map<Long, RawRecord> unitList = units.get(record.getUnitName()); if (unitList == null) { unitList = new HashMap<Long, RawRecord>(); units.put(record.getUnitName(), unitList); } unitList.put(record.getId(), record); } }); for (final Map.Entry<String, Map<Long, RawRecord>> unit : units.entrySet()) { BackupFile file = null; for (int i = 0, n = files.size(); i < n; i++) if (BackupFile.isBackup(files.get(i), unit.getKey())) { file = new BackupFile(files.get(i)); files.remove(i); break; } if (file == null) throw new RuntimeException("Could not find backup file for unit " + unit.getKey()); final Long[] count = new Long[] { 0L }; file.read(new PersistenceProvider.LoadCallback() { @Override public void process(RawRecord record) { RawRecord r = unit.getValue().get(record.getId()); if (r == null) throw new RuntimeException("Could not find persisted record " + record.getId() + " for unit " + unit.getKey()); if (!r.equals(record)) throw new RuntimeException( "Record " + record.getId() + " mismatch for unit " + unit.getKey()); count[0] = count[0] + 1; } }); if (count[0] != unit.getValue().size()) throw new RuntimeException("Extra persisted records for unit " + unit.getKey()); System.out.println(" Unit " + unit.getKey() + ": OK"); } units.clear(); } if (!files.isEmpty()) { System.err.println("Extra backups: "); for (File file : files) System.err.println(" " + file.getName()); } } else { persister.init(); for (File file : files) { InMemoryDatabase.readBackupFile(file, persister); System.out.println("Loaded " + file.getName()); } } } catch (Exception e) { throw new RuntimeException(e); } finally { ctx.close(); } }
From source file:com.l2jfree.tools.ProjectSettingsSynchronizer.java
public static void main(String[] args) throws IOException { final File src = new File(".").getCanonicalFile(); System.out.println("Copying from: " + src); System.out.println();//from w w w . ja v a2s . c o m final List<File> destinations = new ArrayList<File>(); for (File dest : src.getParentFile().listFiles()) { if (dest.isHidden() || !dest.isDirectory()) continue; destinations.add(dest); System.out.println("Copying to: " + dest); } System.out.println(); // .project System.out.println(".project"); System.out.println("================================================================================"); { final List<String> lines = FileUtils.readLines(new File(src, ".project")); for (File dest : destinations) { lines.set(2, lines.get(2).replaceAll(src.getName(), dest.getName())); writeLines(dest, ".project", lines); lines.set(2, lines.get(2).replaceAll(dest.getName(), src.getName())); } } System.out.println(); // .classpath System.out.println(".classpath"); System.out.println("================================================================================"); { final List<String> lines = FileUtils.readLines(new File(src, ".classpath")); for (File dest : destinations) { if (dest.getName().endsWith("-main") || dest.getName().endsWith("-datapack")) { final ArrayList<String> tmp = new ArrayList<String>(); for (String line : lines) if (!line.contains("classpathentry")) tmp.add(line); writeLines(dest, ".classpath", tmp); continue; } writeLines(dest, ".classpath", lines); } } System.out.println(); // .settings System.out.println(".settings"); System.out.println("================================================================================"); for (File settingsFile : new File(src, ".settings").listFiles()) { if (settingsFile.getName().endsWith(".prefs")) { System.out.println(".settings/" + settingsFile.getName()); System.out.println( "--------------------------------------------------------------------------------"); final List<String> lines = FileUtils.readLines(settingsFile); if (lines.get(0).startsWith("#")) lines.remove(0); for (File dest : destinations) { writeLines(new File(dest, ".settings"), settingsFile.getName(), lines); } System.out.println(); } } System.out.println(); }
From source file:io.dockstore.client.cli.Client.java
public static void main(String[] argv) { List<String> args = new ArrayList<>(Arrays.asList(argv)); if (flag(args, "--debug") || flag(args, "--d")) { DEBUG.set(true);//w ww . j a va 2s .co m } // user home dir String userHome = System.getProperty("user.home"); try { String configFile = optVal(args, "--config", userHome + File.separator + ".dockstore" + File.separator + "config"); InputStreamReader f = new InputStreamReader(new FileInputStream(configFile), Charset.defaultCharset()); YamlReader reader = new YamlReader(f); Object object = reader.read(); Map map = (Map) object; // pull out the variables from the config String token = (String) map.get("token"); String serverUrl = (String) map.get("server-url"); if (token == null) { err("The token is missing from your config file."); System.exit(GENERIC_ERROR); } if (serverUrl == null) { err("The server-url is missing from your config file."); System.exit(GENERIC_ERROR); } ApiClient defaultApiClient; defaultApiClient = Configuration.getDefaultApiClient(); defaultApiClient.addDefaultHeader("Authorization", "Bearer " + token); defaultApiClient.setBasePath(serverUrl); containersApi = new ContainersApi(defaultApiClient); usersApi = new UsersApi(defaultApiClient); defaultApiClient.setDebugging(DEBUG.get()); if (isHelp(args, true)) { out(""); out("HELP FOR DOCKSTORE"); out("------------------"); out("See https://www.dockstore.org for more information"); out(""); out("Possible sub-commands include:"); out(""); out(" list : lists all the containers registered by the user "); out(""); out(" search <pattern> : allows a user to search for all containers that match the criteria"); out(""); out(" publish : register a container in the dockstore"); out(""); out(" manual_publish : register a Docker Hub container in the dockstore"); out(""); out(" info <container> : print detailed information about a particular container"); out(""); out(" cwl <container> : returns the Common Workflow Language tool definition for this Docker image "); out(" which enables integration with Global Alliance compliant systems"); out(""); out(" refresh : updates your list of containers stored on Dockstore"); out("------------------"); out(""); out("Flags:"); out(" --debug Print debugging information"); out(" --version Print dockstore's version"); out(" --config <file> Override config file"); } else { try { // check user info after usage so that users can get usage without live webservice user = usersApi.getUser(); if (user == null) { throw new NotFoundException("User not found"); } String cmd = args.remove(0); if (null != cmd) { switch (cmd) { case "-v": case "--version": kill("dockstore: version information is provided by the wrapper script."); break; case "list": list(args); break; case "search": search(args); break; case "publish": publish(args); break; case "manual_publish": manualPublish(args); break; case "info": info(args); break; case "cwl": cwl(args); break; case "refresh": refresh(args); break; case "dev": dev(args); break; default: invalid(cmd); break; } } } catch (Kill k) { System.exit(GENERIC_ERROR); } } } catch (IOException | NotFoundException | ApiException ex) { out("Exception: " + ex); System.exit(GENERIC_ERROR); } catch (ProcessingException ex) { out("Could not connect to Dockstore web service: " + ex); System.exit(CONNECTION_ERROR); } }
From source file:Main.java
public static void rotate(List<Integer> list) { list.add(list.remove(0)); }
From source file:Main.java
public static <T> T removeAt(List<T> list, int pos) { return list.remove(pos); }
From source file:Main.java
public static <T> boolean remove(List<T> list, T value) { return list.remove(value); }
From source file:Main.java
/** * Method removeAndReturn.//from w ww .j av a 2 s .co m * @param list List<E> * @param lookup E * @return E */ public static <E> E removeAndReturn(List<E> list, E lookup) { return list.remove(list.indexOf(lookup)); }