Example usage for java.lang String length

List of usage examples for java.lang String length

Introduction

In this page you can find the example usage for java.lang String length.

Prototype

public int length() 

Source Link

Document

Returns the length of this string.

Usage

From source file:com.l2jfree.loginserver.tools.L2GameServerRegistrar.java

/**
 * Launches the interactive game server registration.
 * /*  w  ww  . j  av  a  2s.  c o  m*/
 * @param args ignored
 */
public static void main(String[] args) {
    // LOW rework this crap
    Util.printSection("Game Server Registration");
    _log.info("Please choose:");
    _log.info("list - list registered game servers");
    _log.info("reg - register a game server");
    _log.info("rem - remove a registered game server");
    _log.info("hexid - generate a legacy hexid file");
    _log.info("quit - exit this application");

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    L2GameServerRegistrar reg = new L2GameServerRegistrar();

    String line;
    try {
        RegistrationState next = RegistrationState.INITIAL_CHOICE;
        while ((line = br.readLine()) != null) {
            line = line.trim().toLowerCase();
            switch (reg.getState()) {
            case GAMESERVER_ID:
                try {
                    int id = Integer.parseInt(line);
                    if (id < 1 || id > 127)
                        throw new IllegalArgumentException("ID must be in [1;127].");
                    reg.setId(id);
                    reg.setState(next);
                } catch (RuntimeException e) {
                    _log.info("You must input a number between 1 and 127");
                }

                if (reg.getState() == RegistrationState.ALLOW_BANS) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con
                                .prepareStatement("SELECT allowBans FROM gameserver WHERE id = ?");
                        ps.setInt(1, reg.getId());
                        ResultSet rs = ps.executeQuery();
                        if (rs.next()) {
                            _log.info("A game server is already registered on ID " + reg.getId());
                            reg.setState(RegistrationState.INITIAL_CHOICE);
                        } else
                            _log.info("Allow account bans from this game server? [y/n]:");
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not remove a game server!", e);
                    } finally {
                        L2Database.close(con);
                    }
                } else if (reg.getState() == RegistrationState.REMOVE) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement("DELETE FROM gameserver WHERE id = ?");
                        ps.setInt(1, reg.getId());
                        int cnt = ps.executeUpdate();
                        if (cnt == 0)
                            _log.info("No game server registered on ID " + reg.getId());
                        else
                            _log.info("Game server removed.");
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not remove a game server!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    reg.setState(RegistrationState.INITIAL_CHOICE);
                } else if (reg.getState() == RegistrationState.GENERATE) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con
                                .prepareStatement("SELECT authData FROM gameserver WHERE id = ?");
                        ps.setInt(1, reg.getId());
                        ResultSet rs = ps.executeQuery();

                        if (rs.next()) {
                            reg.setAuth(rs.getString("authData"));
                            byte[] b = HexUtil.hexStringToBytes(reg.getAuth());

                            Properties pro = new Properties();
                            pro.setProperty("ServerID", String.valueOf(reg.getId()));
                            pro.setProperty("HexID", HexUtil.hexToString(b));

                            BufferedOutputStream os = new BufferedOutputStream(
                                    new FileOutputStream("hexid.txt"));
                            pro.store(os, "the hexID to auth into login");
                            IOUtils.closeQuietly(os);
                            _log.info("hexid.txt has been generated.");
                        } else
                            _log.info("No game server registered on ID " + reg.getId());

                        rs.close();
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not generate hexid.txt!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    reg.setState(RegistrationState.INITIAL_CHOICE);
                }
                break;
            case ALLOW_BANS:
                try {
                    if (line.length() != 1)
                        throw new IllegalArgumentException("One char required.");
                    else if (line.charAt(0) == 'y')
                        reg.setTrusted(true);
                    else if (line.charAt(0) == 'n')
                        reg.setTrusted(false);
                    else
                        throw new IllegalArgumentException("Invalid choice.");

                    byte[] auth = Rnd.nextBytes(new byte[BYTES]);
                    reg.setAuth(HexUtil.bytesToHexString(auth));

                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement(
                                "INSERT INTO gameserver (id, authData, allowBans) VALUES (?, ?, ?)");
                        ps.setInt(1, reg.getId());
                        ps.setString(2, reg.getAuth());
                        ps.setBoolean(3, reg.isTrusted());
                        ps.executeUpdate();
                        ps.close();

                        _log.info("Registered game server on ID " + reg.getId());
                        _log.info("The authorization string is:");
                        _log.info(reg.getAuth());
                        _log.info("Use it when registering this login server.");
                        _log.info("If you need a legacy hexid file, use the 'hexid' command.");
                    } catch (SQLException e) {
                        _log.error("Could not register gameserver!", e);
                    } finally {
                        L2Database.close(con);
                    }

                    reg.setState(RegistrationState.INITIAL_CHOICE);
                } catch (IllegalArgumentException e) {
                    _log.info("[y/n]?");
                }
                break;
            default:
                if (line.equals("list")) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement("SELECT id, allowBans FROM gameserver");
                        ResultSet rs = ps.executeQuery();
                        while (rs.next())
                            _log.info("ID: " + rs.getInt("id") + ", trusted: " + rs.getBoolean("allowBans"));
                        rs.close();
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not register gameserver!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    reg.setState(RegistrationState.INITIAL_CHOICE);
                } else if (line.equals("reg")) {
                    _log.info("Enter the desired ID:");
                    reg.setState(RegistrationState.GAMESERVER_ID);
                    next = RegistrationState.ALLOW_BANS;
                } else if (line.equals("rem")) {
                    _log.info("Enter game server ID:");
                    reg.setState(RegistrationState.GAMESERVER_ID);
                    next = RegistrationState.REMOVE;
                } else if (line.equals("hexid")) {
                    _log.info("Enter game server ID:");
                    reg.setState(RegistrationState.GAMESERVER_ID);
                    next = RegistrationState.GENERATE;
                } else if (line.equals("quit"))
                    Shutdown.exit(TerminationStatus.MANUAL_SHUTDOWN);
                else
                    _log.info("Incorrect command.");
                break;
            }
        }
    } catch (IOException e) {
        _log.fatal("Could not process input!", e);
    } finally {
        IOUtils.closeQuietly(br);
    }
}

From source file:au.com.jwatmuff.eventmanager.Main.java

/**
 * Main method.//from w  ww  .  ja  va2s . c om
 */
public static void main(String args[]) {
    LogUtils.setupUncaughtExceptionHandler();

    /* Set timeout for RMI connections - TODO: move to external file */
    System.setProperty("sun.rmi.transport.tcp.handshakeTimeout", "2000");
    updateRmiHostName();

    /*
     * Set up menu bar for Mac
     */
    System.setProperty("apple.laf.useScreenMenuBar", "true");
    System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Event Manager");

    /*
     * Set look and feel to 'system' style
     */
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        log.info("Failed to set system look and feel");
    }

    /*
     * Set workingDir to a writable folder for storing competitions, settings etc.
     */
    String applicationData = System.getenv("APPDATA");
    if (applicationData != null) {
        workingDir = new File(applicationData, "EventManager");
        if (workingDir.exists() || workingDir.mkdirs()) {
            // redirect logging to writable folder
            LogUtils.reconfigureFileAppenders("log4j.properties", workingDir);
        } else {
            workingDir = new File(".");
        }
    }

    // log version for debugging
    log.info("Running version: " + VISIBLE_VERSION + " (Internal: " + VERSION + ")");

    /*
     * Copy license if necessary
     */
    File license1 = new File("license.lic");
    File license2 = new File(workingDir, "license.lic");
    if (license1.exists() && !license2.exists()) {
        try {
            FileUtils.copyFile(license1, license2);
        } catch (IOException e) {
            log.warn("Failed to copy license from " + license1 + " to " + license2, e);
        }
    }
    if (license1.exists() && license2.exists()) {
        if (license1.lastModified() > license2.lastModified()) {
            try {
                FileUtils.copyFile(license1, license2);
            } catch (IOException e) {
                log.warn("Failed to copy license from " + license1 + " to " + license2, e);
            }
        }
    }

    /*
     * Check if run lock exists, if so ask user if it is ok to continue
     */
    if (!obtainRunLock(false)) {
        int response = JOptionPane.showConfirmDialog(null,
                "Unable to obtain run-lock.\nPlease ensure that no other instances of EventManager are running before continuing.\nDo you wish to continue?",
                "Run-lock detected", JOptionPane.YES_NO_OPTION);
        if (response == JOptionPane.YES_OPTION)
            obtainRunLock(true);
        else
            System.exit(0);
    }

    try {
        LoadWindow loadWindow = new LoadWindow();
        loadWindow.setVisible(true);

        loadWindow.addMessage("Reading settings..");

        /*
         * Read properties from file
         */
        final Properties props = new Properties();
        try {
            Properties defaultProps = PropertiesLoaderUtils
                    .loadProperties(new ClassPathResource("eventmanager.properties"));
            props.putAll(defaultProps);
        } catch (IOException ex) {
            log.error(ex);
        }

        props.putAll(System.getProperties());

        File databaseStore = new File(workingDir, "comps");
        int rmiPort = Integer.parseInt(props.getProperty("eventmanager.rmi.port"));

        loadWindow.addMessage("Loading Peer Manager..");
        log.info("Loading Peer Manager");

        ManualDiscoveryService manualDiscoveryService = new ManualDiscoveryService();
        JmDNSRMIPeerManager peerManager = new JmDNSRMIPeerManager(rmiPort, new File(workingDir, "peerid.dat"));
        peerManager.addDiscoveryService(manualDiscoveryService);

        monitorNetworkInterfaceChanges(peerManager);

        loadWindow.addMessage("Loading Database Manager..");
        log.info("Loading Database Manager");

        DatabaseManager databaseManager = new SQLiteDatabaseManager(databaseStore, peerManager);
        LicenseManager licenseManager = new LicenseManager(workingDir);

        loadWindow.addMessage("Loading Load Competition Dialog..");
        log.info("Loading Load Competition Dialog");

        LoadCompetitionWindow loadCompetitionWindow = new LoadCompetitionWindow(databaseManager, licenseManager,
                peerManager);
        loadCompetitionWindow.setTitle(WINDOW_TITLE);

        loadWindow.dispose();
        log.info("Starting Load Competition Dialog");

        while (true) {
            // reset permission checker to use our license
            licenseManager.updatePermissionChecker();

            GUIUtils.runModalJFrame(loadCompetitionWindow);

            if (loadCompetitionWindow.getSuccess()) {
                DatabaseInfo info = loadCompetitionWindow.getSelectedDatabaseInfo();

                if (!databaseManager.checkLock(info.id)) {
                    String message = "EventManager did not shut down correctly the last time this competition was open. To avoid potential data corruption, you are advised to take the following steps:\n"
                            + "1) Do NOT open this competition\n" + "2) Create a backup of this competition\n"
                            + "3) Delete the competition from this computer\n"
                            + "4) If possible, reload this competition from another computer on the network\n"
                            + "5) Alternatively, you may manually load the backup onto all computers on the network, ensuring the 'Preserve competition ID' option is checked.";
                    String title = "WARNING: Potential Data Corruption Detected";

                    int status = JOptionPane.showOptionDialog(null, message, title, JOptionPane.YES_NO_OPTION,
                            JOptionPane.ERROR_MESSAGE, null,
                            new Object[] { "Cancel (recommended)", "Open anyway" }, "Cancel (recommended)");

                    if (status == 0)
                        continue; // return to load competition window
                }

                SynchronizingWindow syncWindow = new SynchronizingWindow();
                syncWindow.setVisible(true);
                long t = System.nanoTime();
                DistributedDatabase database = databaseManager.activateDatabase(info.id, info.passwordHash);
                long dt = System.nanoTime() - t;
                log.debug(String.format("Initial sync in %dms",
                        TimeUnit.MILLISECONDS.convert(dt, TimeUnit.NANOSECONDS)));
                syncWindow.dispose();

                if (loadCompetitionWindow.isNewDatabase()) {
                    GregorianCalendar calendar = new GregorianCalendar();
                    Date today = calendar.getTime();
                    calendar.set(Calendar.MONTH, Calendar.DECEMBER);
                    calendar.set(Calendar.DAY_OF_MONTH, 31);
                    Date endOfYear = new java.sql.Date(calendar.getTimeInMillis());

                    CompetitionInfo ci = new CompetitionInfo();
                    ci.setName(info.name);
                    ci.setStartDate(today);
                    ci.setEndDate(today);
                    ci.setAgeThresholdDate(endOfYear);
                    //ci.setPasswordHash(info.passwordHash);
                    License license = licenseManager.getLicense();
                    if (license != null) {
                        ci.setLicenseName(license.getName());
                        ci.setLicenseType(license.getType().toString());
                        ci.setLicenseContact(license.getContactPhoneNumber());
                    }
                    database.add(ci);
                }

                // Set PermissionChecker to use database's license type
                String competitionLicenseType = database.get(CompetitionInfo.class, null).getLicenseType();
                PermissionChecker.setLicenseType(LicenseType.valueOf(competitionLicenseType));

                TransactionNotifier notifier = new TransactionNotifier();
                database.setListener(notifier);

                MainWindow mainWindow = new MainWindow();
                mainWindow.setDatabase(database);
                mainWindow.setNotifier(notifier);
                mainWindow.setPeerManager(peerManager);
                mainWindow.setLicenseManager(licenseManager);
                mainWindow.setManualDiscoveryService(manualDiscoveryService);
                mainWindow.setTitle(WINDOW_TITLE);
                mainWindow.afterPropertiesSet();

                TestUtil.setActivatedDatabase(database);

                // show main window (modally)
                GUIUtils.runModalJFrame(mainWindow);

                // shutdown procedures

                // System.exit();

                database.shutdown();
                databaseManager.deactivateDatabase(1500);

                if (mainWindow.getDeleteOnExit()) {
                    for (File file : info.localDirectory.listFiles())
                        if (!file.isDirectory())
                            file.delete();
                    info.localDirectory.deleteOnExit();
                }
            } else {
                // This can cause an RuntimeException - Peer is disconnected
                peerManager.stop();
                System.exit(0);
            }
        }
    } catch (Throwable e) {
        log.error("Error in main function", e);
        String message = e.getMessage();
        if (message == null)
            message = "";
        if (message.length() > 100)
            message = message.substring(0, 97) + "...";
        GUIUtils.displayError(null,
                "An unexpected error has occured.\n\n" + e.getClass().getSimpleName() + "\n" + message);
        System.exit(0);
    }
}

From source file:CTmousetrack.java

public static void main(String[] args) {

    String outLoc = new String("." + File.separator + "CTdata"); // Location of the base output data folder; only used when writing out CT data to a local folder
    String srcName = "CTmousetrack"; // name of the output CT source
    long blockPts = 10; // points per block flush
    long sampInterval = 10; // time between sampling updates, msec
    double trimTime = 0.0; // amount of data to keep (trim time), sec
    boolean debug = false; // turn on debug?

    // Specify the CT output connection
    CTWriteMode writeMode = CTWriteMode.LOCAL; // The selected mode for writing out CT data
    String serverHost = ""; // Server (FTP or HTTP/S) host:port
    String serverUser = ""; // Server (FTP or HTTPS) username
    String serverPassword = ""; // Server (FTP or HTTPS) password

    // For UDP output mode
    DatagramSocket udpServerSocket = null;
    InetAddress udpServerAddress = null;
    String udpHost = "";
    int udpPort = -1;

    // Concatenate all of the CTWriteMode types
    String possibleWriteModes = "";
    for (CTWriteMode wm : CTWriteMode.values()) {
        possibleWriteModes = possibleWriteModes + ", " + wm.name();
    }//from  www. ja va 2  s. c o m
    // Remove ", " from start of string
    possibleWriteModes = possibleWriteModes.substring(2);

    //
    // Argument processing using Apache Commons CLI
    //
    // 1. Setup command line options
    Options options = new Options();
    options.addOption("h", "help", false, "Print this message.");
    options.addOption(Option.builder("o").argName("base output dir").hasArg().desc(
            "Base output directory when writing data to local folder (i.e., this is the location of CTdata folder); default = \""
                    + outLoc + "\".")
            .build());
    options.addOption(Option.builder("s").argName("source name").hasArg()
            .desc("Name of source to write data to; default = \"" + srcName + "\".").build());
    options.addOption(Option.builder("b").argName("points per block").hasArg()
            .desc("Number of points per block; UDP output mode will use 1 point/block; default = "
                    + Long.toString(blockPts) + ".")
            .build());
    options.addOption(Option.builder("dt").argName("samp interval msec").hasArg()
            .desc("Sampling period in msec; default = " + Long.toString(sampInterval) + ".").build());
    options.addOption(Option.builder("t").argName("trim time sec").hasArg().desc(
            "Trim (ring-buffer loop) time (sec); this is only used when writing data to local folder; specify 0 for indefinite; default = "
                    + Double.toString(trimTime) + ".")
            .build());
    options.addOption(
            Option.builder("w").argName("write mode").hasArg()
                    .desc("Type of write connection; one of " + possibleWriteModes
                            + "; all but UDP mode write out to CT; default = " + writeMode.name() + ".")
                    .build());
    options.addOption(Option.builder("host").argName("host[:port]").hasArg()
            .desc("Host:port when writing via FTP, HTTP, HTTPS, UDP.").build());
    options.addOption(Option.builder("u").argName("username,password").hasArg()
            .desc("Comma-delimited username and password when writing to CT via FTP or HTTPS.").build());
    options.addOption("x", "debug", false, "Enable CloudTurbine debug output.");

    // 2. Parse command line options
    CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException exp) { // oops, something went wrong
        System.err.println("Command line argument parsing failed: " + exp.getMessage());
        return;
    }

    // 3. Retrieve the command line values
    if (line.hasOption("help")) { // Display help message and quit
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp("CTmousetrack", "", options,
                "NOTE: UDP output is a special non-CT output mode where single x,y points are sent via UDP to the specified host:port.");
        return;
    }

    outLoc = line.getOptionValue("o", outLoc);
    if (!outLoc.endsWith("\\") && !outLoc.endsWith("/")) {
        outLoc = outLoc + File.separator;
    }
    // Make sure the base output folder location ends in "CTdata"
    if (!outLoc.endsWith("CTdata\\") && !outLoc.endsWith("CTdata/")) {
        outLoc = outLoc + "CTdata" + File.separator;
    }

    srcName = line.getOptionValue("s", srcName);

    blockPts = Long.parseLong(line.getOptionValue("b", Long.toString(blockPts)));

    sampInterval = Long.parseLong(line.getOptionValue("dt", Long.toString(sampInterval)));

    trimTime = Double.parseDouble(line.getOptionValue("t", Double.toString(trimTime)));

    // Type of output connection
    String writeModeStr = line.getOptionValue("w", writeMode.name());
    boolean bMatch = false;
    for (CTWriteMode wm : CTWriteMode.values()) {
        if (wm.name().toLowerCase().equals(writeModeStr.toLowerCase())) {
            writeMode = wm;
            bMatch = true;
        }
    }
    if (!bMatch) {
        System.err.println("Unrecognized write mode, \"" + writeModeStr + "\"; write mode must be one of "
                + possibleWriteModes);
        System.exit(0);
    }
    if (writeMode != CTWriteMode.LOCAL) {
        // User must have specified the host
        // If FTP or HTTPS, they may also specify username/password
        serverHost = line.getOptionValue("host", serverHost);
        if (serverHost.isEmpty()) {
            System.err.println(
                    "When using write mode \"" + writeModeStr + "\", you must specify the server host.");
            System.exit(0);
        }
        if (writeMode == CTWriteMode.UDP) {
            // Force blockPts to be 1
            blockPts = 1;
            // User must have specified both host and port
            int colonIdx = serverHost.indexOf(':');
            if ((colonIdx == -1) || (colonIdx >= serverHost.length() - 1)) {
                System.err.println(
                        "For UDP output mode, both the host and port (<host>:<port>)) must be specified.");
                System.exit(0);
            }
            udpHost = serverHost.substring(0, colonIdx);
            String udpPortStr = serverHost.substring(colonIdx + 1);
            try {
                udpPort = Integer.parseInt(udpPortStr);
            } catch (NumberFormatException nfe) {
                System.err.println("The UDP port must be a positive integer.");
                System.exit(0);
            }
        }
        if ((writeMode == CTWriteMode.FTP) || (writeMode == CTWriteMode.HTTPS)) {
            String userpassStr = line.getOptionValue("u", "");
            if (!userpassStr.isEmpty()) {
                // This string should be comma-delimited username and password
                String[] userpassCSV = userpassStr.split(",");
                if (userpassCSV.length != 2) {
                    System.err.println("When specifying a username and password for write mode \""
                            + writeModeStr + "\", separate the username and password by a comma.");
                    System.exit(0);
                }
                serverUser = userpassCSV[0];
                serverPassword = userpassCSV[1];
            }
        }
    }

    debug = line.hasOption("debug");

    System.err.println("CTmousetrack parameters:");
    System.err.println("\toutput mode = " + writeMode.name());
    if (writeMode == CTWriteMode.UDP) {
        System.err.println("\twrite to " + udpHost + ":" + udpPort);
    } else {
        System.err.println("\tsource = " + srcName);
        System.err.println("\ttrim time = " + trimTime + " sec");
    }
    System.err.println("\tpoints per block = " + blockPts);
    System.err.println("\tsample interval = " + sampInterval + " msec");

    try {
        //
        // Setup CTwriter or UDP output
        //
        CTwriter ctw = null;
        CTinfo.setDebug(debug);
        if (writeMode == CTWriteMode.LOCAL) {
            ctw = new CTwriter(outLoc + srcName, trimTime);
            System.err.println("\tdata will be written to local folder \"" + outLoc + "\"");
        } else if (writeMode == CTWriteMode.FTP) {
            CTftp ctftp = new CTftp(srcName);
            try {
                ctftp.login(serverHost, serverUser, serverPassword);
            } catch (Exception e) {
                throw new IOException(
                        new String("Error logging into FTP server \"" + serverHost + "\":\n" + e.getMessage()));
            }
            ctw = ctftp; // upcast to CTWriter
            System.err.println("\tdata will be written to FTP server at " + serverHost);
        } else if (writeMode == CTWriteMode.HTTP) {
            // Don't send username/pw in HTTP mode since they will be unencrypted
            CThttp cthttp = new CThttp(srcName, "http://" + serverHost);
            ctw = cthttp; // upcast to CTWriter
            System.err.println("\tdata will be written to HTTP server at " + serverHost);
        } else if (writeMode == CTWriteMode.HTTPS) {
            CThttp cthttp = new CThttp(srcName, "https://" + serverHost);
            // Username/pw are optional for HTTPS mode; only use them if username is not empty
            if (!serverUser.isEmpty()) {
                try {
                    cthttp.login(serverUser, serverPassword);
                } catch (Exception e) {
                    throw new IOException(new String(
                            "Error logging into HTTP server \"" + serverHost + "\":\n" + e.getMessage()));
                }
            }
            ctw = cthttp; // upcast to CTWriter
            System.err.println("\tdata will be written to HTTPS server at " + serverHost);
        } else if (writeMode == CTWriteMode.UDP) {
            try {
                udpServerSocket = new DatagramSocket();
            } catch (SocketException se) {
                System.err.println("Error creating socket for UDP:\n" + se);
                System.exit(0);
            }
            try {
                udpServerAddress = InetAddress.getByName(udpHost);
            } catch (UnknownHostException uhe) {
                System.err.println("Error getting UDP server host address:\n" + uhe);
                System.exit(0);
            }
        }
        if (writeMode != CTWriteMode.UDP) {
            ctw.setBlockMode(blockPts > 1, blockPts > 1);
            ctw.autoFlush(0); // no autoflush
            ctw.autoSegment(1000);
        }

        // screen dims
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        double width = screenSize.getWidth();
        double height = screenSize.getHeight();

        // use Map for consolidated putData
        Map<String, Object> cmap = new LinkedHashMap<String, Object>();

        // loop and write some output
        for (int i = 0; i < 1000000; i++) { // go until killed
            long currentTime = System.currentTimeMillis();
            Point mousePos = MouseInfo.getPointerInfo().getLocation();
            float x_pt = (float) (mousePos.getX() / width); // normalize
            float y_pt = (float) ((height - mousePos.getY()) / height); // flip Y (so bottom=0)
            if (writeMode != CTWriteMode.UDP) {
                // CT output mode
                ctw.setTime(currentTime);
                cmap.clear();
                cmap.put("x", x_pt);
                cmap.put("y", y_pt);
                ctw.putData(cmap);
                if (((i + 1) % blockPts) == 0) {
                    ctw.flush();
                    System.err.print(".");
                }
            } else {
                // UDP output mode
                // We force blockPts to be 1 for UDP output mode, i.e. we "flush" the data every time
                // Write the following data (21 bytes total):
                //     header = "MOUSE", 5 bytes
                //     current time, long, 8 bytes
                //     2 floats (x,y) 4 bytes each, 8 bytes
                int len = 21;
                ByteBuffer bb = ByteBuffer.allocate(len);
                String headerStr = "MOUSE";
                bb.put(headerStr.getBytes("UTF-8"));
                bb.putLong(currentTime);
                bb.putFloat(x_pt);
                bb.putFloat(y_pt);
                // Might be able to use the following, but not sure:
                //     byte[] sendData = bb.array();
                byte[] sendData = new byte[len];
                bb.position(0);
                bb.get(sendData, 0, len);
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, udpServerAddress,
                        udpPort);
                try {
                    udpServerSocket.send(sendPacket);
                } catch (IOException e) {
                    System.err.println("Test server caught exception trying to send data to UDP client:\n" + e);
                }
                System.err.print(".");
            }
            try {
                Thread.sleep(sampInterval);
            } catch (Exception e) {
            }
            ;
        }
        if (writeMode != CTWriteMode.UDP) {
            ctw.flush(); // wrap up
        }
    } catch (Exception e) {
        System.err.println("CTmousetrack exception: " + e);
        e.printStackTrace();
    }
}

From source file:DIA_Umpire_Quant.DIA_Umpire_Quant.java

/**
 * @param args the command line arguments
 *//*w  w w . j  av a 2  s  . c om*/
public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
    System.out.println(
            "=================================================================================================");
    System.out.println("DIA-Umpire quantitation with targeted re-extraction analysis (version: "
            + UmpireInfo.GetInstance().Version + ")");
    if (args.length != 1) {
        System.out.println(
                "command format error, it should be like: java -jar -Xmx10G DIA_Umpire_Quant.jar diaumpire_quant.params");
        return;
    }
    try {
        ConsoleLogger.SetConsoleLogger(Level.INFO);
        ConsoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "diaumpire_quant.log");
    } catch (Exception e) {
    }

    try {

        Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version);
        Logger.getRootLogger().info("Parameter file:" + args[0]);

        BufferedReader reader = new BufferedReader(new FileReader(args[0]));
        String line = "";
        String WorkFolder = "";
        int NoCPUs = 2;

        String UserMod = "";
        String Combined_Prot = "";
        String InternalLibID = "";
        String ExternalLibPath = "";
        String ExternalLibDecoyTag = "DECOY";
        boolean DefaultProtFiltering = true;
        boolean DataSetLevelPepFDR = false;
        float ProbThreshold = 0.99f;
        float ExtProbThreshold = 0.99f;
        float Freq = 0f;
        int TopNPep = 6;
        int TopNFrag = 6;
        float MinFragMz = 200f;
        String FilterWeight = "GW";
        float MinWeight = 0.9f;
        float RTWindow_Int = -1f;
        float RTWindow_Ext = -1f;

        TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600);
        HashMap<String, File> AssignFiles = new HashMap<>();
        boolean InternalLibSearch = false;
        boolean ExternalLibSearch = false;

        boolean ExportSaint = false;
        boolean SAINT_MS1 = false;
        boolean SAINT_MS2 = true;

        HashMap<String, String[]> BaitList = new HashMap<>();
        HashMap<String, String> BaitName = new HashMap<>();
        HashMap<String, String[]> ControlList = new HashMap<>();
        HashMap<String, String> ControlName = new HashMap<>();

        //<editor-fold defaultstate="collapsed" desc="Reading parameter file">
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            Logger.getRootLogger().info(line);
            if (!"".equals(line) && !line.startsWith("#")) {
                //System.out.println(line);
                if (line.equals("==File list begin")) {
                    do {
                        line = reader.readLine();
                        line = line.trim();
                        if (line.equals("==File list end")) {
                            continue;
                        } else if (!"".equals(line)) {
                            File newfile = new File(line);
                            if (newfile.exists()) {
                                AssignFiles.put(newfile.getAbsolutePath(), newfile);
                            } else {
                                Logger.getRootLogger().info("File: " + newfile + " does not exist.");
                            }
                        }
                    } while (!line.equals("==File list end"));
                }
                if (line.split("=").length < 2) {
                    continue;
                }
                String type = line.split("=")[0].trim();
                String value = line.split("=")[1].trim();
                switch (type) {
                case "TargetedExtraction": {
                    InternalLibSearch = Boolean.parseBoolean(value);
                    break;
                }
                case "InternalLibSearch": {
                    InternalLibSearch = Boolean.parseBoolean(value);
                    break;
                }
                case "ExternalLibSearch": {
                    ExternalLibSearch = Boolean.parseBoolean(value);
                    break;
                }

                case "Path": {
                    WorkFolder = value;
                    break;
                }
                case "path": {
                    WorkFolder = value;
                    break;
                }
                case "Thread": {
                    NoCPUs = Integer.parseInt(value);
                    break;
                }
                case "Fasta": {
                    tandemPara.FastaPath = value;
                    break;
                }
                case "Combined_Prot": {
                    Combined_Prot = value;
                    break;
                }
                case "DefaultProtFiltering": {
                    DefaultProtFiltering = Boolean.parseBoolean(value);
                    break;
                }
                case "DecoyPrefix": {
                    if (!"".equals(value)) {
                        tandemPara.DecoyPrefix = value;
                    }
                    break;
                }
                case "UserMod": {
                    UserMod = value;
                    break;
                }
                case "ProteinFDR": {
                    tandemPara.ProtFDR = Float.parseFloat(value);
                    break;
                }
                case "PeptideFDR": {
                    tandemPara.PepFDR = Float.parseFloat(value);
                    break;
                }
                case "DataSetLevelPepFDR": {
                    DataSetLevelPepFDR = Boolean.parseBoolean(value);
                    break;
                }
                case "InternalLibID": {
                    InternalLibID = value;
                    break;
                }
                case "ExternalLibPath": {
                    ExternalLibPath = value;
                    break;
                }
                case "ExtProbThreshold": {
                    ExtProbThreshold = Float.parseFloat(value);
                    break;
                }
                case "RTWindow_Int": {
                    RTWindow_Int = Float.parseFloat(value);
                    break;
                }
                case "RTWindow_Ext": {
                    RTWindow_Ext = Float.parseFloat(value);
                    break;
                }
                case "ExternalLibDecoyTag": {
                    ExternalLibDecoyTag = value;
                    if (ExternalLibDecoyTag.endsWith("_")) {
                        ExternalLibDecoyTag = ExternalLibDecoyTag.substring(0,
                                ExternalLibDecoyTag.length() - 1);
                    }
                    break;
                }
                case "ProbThreshold": {
                    ProbThreshold = Float.parseFloat(value);
                    break;
                }
                case "ReSearchProb": {
                    //ReSearchProb = Float.parseFloat(value);
                    break;
                }
                case "FilterWeight": {
                    FilterWeight = value;
                    break;
                }
                case "MinWeight": {
                    MinWeight = Float.parseFloat(value);
                    break;
                }
                case "TopNFrag": {
                    TopNFrag = Integer.parseInt(value);
                    break;
                }
                case "TopNPep": {
                    TopNPep = Integer.parseInt(value);
                    break;
                }
                case "Freq": {
                    Freq = Float.parseFloat(value);
                    break;
                }
                case "MinFragMz": {
                    MinFragMz = Float.parseFloat(value);
                    break;
                }

                //<editor-fold defaultstate="collapsed" desc="SaintOutput">
                case "ExportSaintInput": {
                    ExportSaint = Boolean.parseBoolean(value);
                    break;
                }
                case "QuantitationType": {
                    switch (value) {
                    case "MS1": {
                        SAINT_MS1 = true;
                        SAINT_MS2 = false;
                        break;
                    }
                    case "MS2": {
                        SAINT_MS1 = false;
                        SAINT_MS2 = true;
                        break;
                    }
                    case "BOTH": {
                        SAINT_MS1 = true;
                        SAINT_MS2 = true;
                        break;
                    }
                    }
                    break;
                }
                //                    case "BaitInputFile": {
                //                        SaintBaitFile = value;
                //                        break;
                //                    }
                //                    case "PreyInputFile": {
                //                        SaintPreyFile = value;
                //                        break;
                //                    }
                //                    case "InterationInputFile": {
                //                        SaintInteractionFile = value;
                //                        break;
                //                    }
                default: {
                    if (type.startsWith("BaitName_")) {
                        BaitName.put(type.substring(9), value);
                    }
                    if (type.startsWith("BaitFile_")) {
                        BaitList.put(type.substring(9), value.split("\t"));
                    }
                    if (type.startsWith("ControlName_")) {
                        ControlName.put(type.substring(12), value);
                    }
                    if (type.startsWith("ControlFile_")) {
                        ControlList.put(type.substring(12), value.split("\t"));
                    }
                    break;
                }
                //</editor-fold>                    
                }
            }
        }
        //</editor-fold>

        //Initialize PTM manager using compomics library
        PTMManager.GetInstance();
        if (!UserMod.equals("")) {
            PTMManager.GetInstance().ImportUserMod(UserMod);
        }

        //Check if the fasta file can be found
        if (!new File(tandemPara.FastaPath).exists()) {
            Logger.getRootLogger().info("Fasta file :" + tandemPara.FastaPath
                    + " cannot be found, the process will be terminated, please check.");
            System.exit(1);
        }

        //Check if the prot.xml file can be found
        if (!new File(Combined_Prot).exists()) {
            Logger.getRootLogger().info("ProtXML file: " + Combined_Prot
                    + " cannot be found, the export protein summary table will be empty.");
        }

        LCMSID protID = null;

        //Parse prot.xml and generate protein master list given an FDR 
        if (Combined_Prot != null && !Combined_Prot.equals("")) {
            protID = LCMSID.ReadLCMSIDSerialization(Combined_Prot);
            if (!"".equals(Combined_Prot) && protID == null) {
                protID = new LCMSID(Combined_Prot, tandemPara.DecoyPrefix, tandemPara.FastaPath);
                ProtXMLParser protxmlparser = new ProtXMLParser(protID, Combined_Prot, 0f);
                //Use DIA-Umpire default protein FDR calculation
                if (DefaultProtFiltering) {
                    protID.RemoveLowLocalPWProtein(0.8f);
                    protID.RemoveLowMaxIniProbProtein(0.9f);
                    protID.FilterByProteinDecoyFDRUsingMaxIniProb(tandemPara.DecoyPrefix, tandemPara.ProtFDR);
                } //Get protein FDR calculation without other filtering
                else {
                    protID.FilterByProteinDecoyFDRUsingLocalPW(tandemPara.DecoyPrefix, tandemPara.ProtFDR);
                }
                protID.LoadSequence();
                protID.WriteLCMSIDSerialization(Combined_Prot);
            }
            Logger.getRootLogger().info("Protein No.:" + protID.ProteinList.size());
        }
        HashMap<String, HashMap<String, FragmentPeak>> IDSummaryFragments = new HashMap<>();

        //Generate DIA file list
        ArrayList<DIAPack> FileList = new ArrayList<>();

        File folder = new File(WorkFolder);
        if (!folder.exists()) {
            Logger.getRootLogger().info("The path : " + WorkFolder + " cannot be found.");
            System.exit(1);
        }
        for (final File fileEntry : folder.listFiles()) {
            if (fileEntry.isFile()
                    && (fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                            | fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                    && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry);
            }
            if (fileEntry.isDirectory()) {
                for (final File fileEntry2 : fileEntry.listFiles()) {
                    if (fileEntry2.isFile()
                            && (fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml")
                                    | fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzml"))
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml")
                            && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) {
                        AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2);
                    }
                }
            }
        }

        Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size());
        for (File fileEntry : AssignFiles.values()) {
            Logger.getRootLogger().info(fileEntry.getAbsolutePath());
            String mzXMLFile = fileEntry.getAbsolutePath();
            if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) {
                DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs);
                FileList.add(DiaFile);
                HashMap<String, FragmentPeak> FragMap = new HashMap<>();
                IDSummaryFragments.put(FilenameUtils.getBaseName(mzXMLFile), FragMap);
                Logger.getRootLogger().info(
                        "=================================================================================================");
                Logger.getRootLogger().info("Processing " + mzXMLFile);
                if (!DiaFile.LoadDIASetting()) {
                    Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete");
                    System.exit(1);
                }
                if (!DiaFile.LoadParams()) {
                    Logger.getRootLogger().info("Loading parameters failed, job is incomplete");
                    System.exit(1);
                }
            }
        }

        LCMSID combinePepID = null;
        if (DataSetLevelPepFDR) {
            combinePepID = LCMSID.ReadLCMSIDSerialization(WorkFolder + "combinePepID.SerFS");
            if (combinePepID == null) {
                FDR_DataSetLevel fdr = new FDR_DataSetLevel();
                fdr.GeneratePepIonList(FileList, tandemPara, WorkFolder + "combinePepID.SerFS");
                combinePepID = fdr.combineID;
                combinePepID.WriteLCMSIDSerialization(WorkFolder + "combinePepID.SerFS");
            }
        }

        //process each DIA file for quantification based on untargeted identifications
        for (DIAPack DiaFile : FileList) {
            long time = System.currentTimeMillis();
            Logger.getRootLogger().info("Loading identification results " + DiaFile.Filename + "....");

            //If the LCMSID serialization is found
            if (!DiaFile.ReadSerializedLCMSID()) {
                DiaFile.ParsePepXML(tandemPara, combinePepID);
                DiaFile.BuildStructure();
                if (!DiaFile.MS1FeatureMap.ReadPeakCluster()) {
                    Logger.getRootLogger().info("Loading peak and structure failed, job is incomplete");
                    System.exit(1);
                }
                DiaFile.MS1FeatureMap.ClearMonoisotopicPeakOfCluster();
                //Generate mapping between index of precursor feature and pseudo MS/MS scan index 
                DiaFile.GenerateClusterScanNomapping();
                //Doing quantification
                DiaFile.AssignQuant();
                DiaFile.ClearStructure();
            }
            DiaFile.IDsummary.ReduceMemoryUsage();
            time = System.currentTimeMillis() - time;
            Logger.getRootLogger().info(DiaFile.Filename + " processed time:"
                    + String.format("%d hour, %d min, %d sec", TimeUnit.MILLISECONDS.toHours(time),
                            TimeUnit.MILLISECONDS.toMinutes(time)
                                    - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)),
                            TimeUnit.MILLISECONDS.toSeconds(time)
                                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))));
        }

        //<editor-fold defaultstate="collapsed" desc="Targete re-extraction using internal library">            
        Logger.getRootLogger().info(
                "=================================================================================================");
        if (InternalLibSearch && FileList.size() > 1) {
            Logger.getRootLogger().info("Module C: Targeted extraction using internal library");

            FragmentLibManager libManager = FragmentLibManager.ReadFragmentLibSerialization(WorkFolder,
                    InternalLibID);
            if (libManager == null) {
                Logger.getRootLogger().info("Building internal spectral library");
                libManager = new FragmentLibManager(InternalLibID);
                ArrayList<LCMSID> LCMSIDList = new ArrayList<>();
                for (DIAPack dia : FileList) {
                    LCMSIDList.add(dia.IDsummary);
                }
                libManager.ImportFragLibTopFrag(LCMSIDList, Freq, TopNFrag);
                libManager.WriteFragmentLibSerialization(WorkFolder);
            }
            libManager.ReduceMemoryUsage();

            Logger.getRootLogger()
                    .info("Building retention time prediction model and generate candidate peptide list");
            for (int i = 0; i < FileList.size(); i++) {
                FileList.get(i).IDsummary.ClearMappedPep();
            }
            for (int i = 0; i < FileList.size(); i++) {
                for (int j = i + 1; j < FileList.size(); j++) {
                    RTAlignedPepIonMapping alignment = new RTAlignedPepIonMapping(WorkFolder,
                            FileList.get(i).GetParameter(), FileList.get(i).IDsummary,
                            FileList.get(j).IDsummary);
                    alignment.GenerateModel();
                    alignment.GenerateMappedPepIon();
                }
                FileList.get(i).ExportID();
                FileList.get(i).IDsummary = null;
            }

            Logger.getRootLogger().info("Targeted matching........");
            for (DIAPack diafile : FileList) {
                if (diafile.IDsummary == null) {
                    diafile.ReadSerializedLCMSID();
                }
                if (!diafile.IDsummary.GetMappedPepIonList().isEmpty()) {
                    diafile.UseMappedIon = true;
                    diafile.FilterMappedIonByProb = false;
                    diafile.BuildStructure();
                    diafile.MS1FeatureMap.ReadPeakCluster();
                    diafile.MS1FeatureMap.ClearMonoisotopicPeakOfCluster();
                    diafile.GenerateMassCalibrationRTMap();
                    diafile.TargetedExtractionQuant(false, libManager, 1.1f, RTWindow_Int);
                    diafile.MS1FeatureMap.ClearAllPeaks();
                    diafile.IDsummary.ReduceMemoryUsage();
                    diafile.IDsummary.RemoveLowProbMappedIon(ProbThreshold);
                    diafile.ExportID();
                    Logger.getRootLogger().info("Peptide ions: " + diafile.IDsummary.GetPepIonList().size()
                            + " Mapped ions: " + diafile.IDsummary.GetMappedPepIonList().size());
                    diafile.ClearStructure();
                }
                diafile.IDsummary = null;
                System.gc();
            }
            Logger.getRootLogger().info(
                    "=================================================================================================");
        }
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="Targeted re-extraction using external library">
        //External library search
        if (ExternalLibSearch) {
            Logger.getRootLogger().info("Module C: Targeted extraction using external library");

            //Read exteranl library
            FragmentLibManager ExlibManager = FragmentLibManager.ReadFragmentLibSerialization(WorkFolder,
                    FilenameUtils.getBaseName(ExternalLibPath));
            if (ExlibManager == null) {
                ExlibManager = new FragmentLibManager(FilenameUtils.getBaseName(ExternalLibPath));

                //Import traML file
                ExlibManager.ImportFragLibByTraML(ExternalLibPath, ExternalLibDecoyTag);
                //Check if there are decoy spectra
                ExlibManager.CheckDecoys();
                //ExlibManager.ImportFragLibBySPTXT(ExternalLibPath);
                ExlibManager.WriteFragmentLibSerialization(WorkFolder);
            }
            Logger.getRootLogger()
                    .info("No. of peptide ions in external lib:" + ExlibManager.PeptideFragmentLib.size());
            for (DIAPack diafile : FileList) {
                if (diafile.IDsummary == null) {
                    diafile.ReadSerializedLCMSID();
                }
                //Generate RT mapping
                RTMappingExtLib RTmap = new RTMappingExtLib(diafile.IDsummary, ExlibManager,
                        diafile.GetParameter());
                RTmap.GenerateModel();
                RTmap.GenerateMappedPepIon();

                diafile.BuildStructure();
                diafile.MS1FeatureMap.ReadPeakCluster();
                diafile.GenerateMassCalibrationRTMap();
                //Perform targeted re-extraction
                diafile.TargetedExtractionQuant(false, ExlibManager, ProbThreshold, RTWindow_Ext);
                diafile.MS1FeatureMap.ClearAllPeaks();
                diafile.IDsummary.ReduceMemoryUsage();
                //Remove target IDs below the defined probability threshold
                diafile.IDsummary.RemoveLowProbMappedIon(ExtProbThreshold);
                diafile.ExportID();
                diafile.ClearStructure();
                Logger.getRootLogger().info("Peptide ions: " + diafile.IDsummary.GetPepIonList().size()
                        + " Mapped ions: " + diafile.IDsummary.GetMappedPepIonList().size());
            }
        }
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="Peptide and fragment selection">
        Logger.getRootLogger().info("Peptide and fragment selection across the whole dataset");
        ArrayList<LCMSID> SummaryList = new ArrayList<>();
        for (DIAPack diafile : FileList) {
            if (diafile.IDsummary == null) {
                diafile.ReadSerializedLCMSID();
                diafile.IDsummary.ClearAssignPeakCluster();
                //diafile.IDsummary.ClearPSMs();                    
            }
            if (protID != null) {
                //Generate protein list according to mapping of peptide ions for each DIA file to the master protein list
                diafile.IDsummary.GenerateProteinByRefIDByPepSeq(protID, true);
                diafile.IDsummary.ReMapProPep();
            }
            if ("GW".equals(FilterWeight)) {
                diafile.IDsummary.SetFilterByGroupWeight();
            } else if ("PepW".equals(FilterWeight)) {
                diafile.IDsummary.SetFilterByWeight();
            }
            SummaryList.add(diafile.IDsummary);
        }
        FragmentSelection fragselection = new FragmentSelection(SummaryList);
        fragselection.freqPercent = Freq;
        fragselection.MinFragMZ = MinFragMz;
        fragselection.GeneratePepFragScoreMap();
        fragselection.GenerateTopFragMap(TopNFrag);
        fragselection.GenerateProtPepScoreMap(MinWeight);
        fragselection.GenerateTopPepMap(TopNPep);
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="Writing general reports">                 
        ExportTable export = new ExportTable(WorkFolder, SummaryList, IDSummaryFragments, protID,
                fragselection);
        export.Export(TopNPep, TopNFrag, Freq);
        //</editor-fold>

        //<editor-fold defaultstate="collapsed" desc="//<editor-fold defaultstate="collapsed" desc="Generate SAINT input files">
        if (ExportSaint && protID != null) {
            HashMap<String, DIAPack> Filemap = new HashMap<>();
            for (DIAPack DIAfile : FileList) {
                Filemap.put(DIAfile.GetBaseName(), DIAfile);
            }

            FileWriter baitfile = new FileWriter(WorkFolder + "SAINT_Bait_" + DateTimeTag.GetTag() + ".txt");
            FileWriter preyfile = new FileWriter(WorkFolder + "SAINT_Prey_" + DateTimeTag.GetTag() + ".txt");
            FileWriter interactionfileMS1 = null;
            FileWriter interactionfileMS2 = null;
            if (SAINT_MS1) {
                interactionfileMS1 = new FileWriter(
                        WorkFolder + "SAINT_Interaction_MS1_" + DateTimeTag.GetTag() + ".txt");
            }
            if (SAINT_MS2) {
                interactionfileMS2 = new FileWriter(
                        WorkFolder + "SAINT_Interaction_MS2_" + DateTimeTag.GetTag() + ".txt");
            }
            HashMap<String, String> PreyID = new HashMap<>();

            for (String samplekey : ControlName.keySet()) {
                String name = ControlName.get(samplekey);
                for (String file : ControlList.get(samplekey)) {
                    baitfile.write(FilenameUtils.getBaseName(file) + "\t" + name + "\t" + "C\n");
                    LCMSID IDsummary = Filemap.get(FilenameUtils.getBaseName(file)).IDsummary;
                    if (SAINT_MS1) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS1, file, name, PreyID,
                                1);
                    }
                    if (SAINT_MS2) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS2, file, name, PreyID,
                                2);
                    }
                }
            }
            for (String samplekey : BaitName.keySet()) {
                String name = BaitName.get(samplekey);
                for (String file : BaitList.get(samplekey)) {
                    baitfile.write(FilenameUtils.getBaseName(file) + "\t" + name + "\t" + "T\n");
                    LCMSID IDsummary = Filemap.get(FilenameUtils.getBaseName(file)).IDsummary;
                    if (SAINT_MS1) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS1, file, name, PreyID,
                                1);
                    }
                    if (SAINT_MS2) {
                        SaintOutput(protID, IDsummary, fragselection, interactionfileMS2, file, name, PreyID,
                                2);
                    }
                }
            }
            baitfile.close();
            if (SAINT_MS1) {
                interactionfileMS1.close();
            }
            if (SAINT_MS2) {
                interactionfileMS2.close();
            }
            for (String AccNo : PreyID.keySet()) {
                preyfile.write(AccNo + "\t" + PreyID.get(AccNo) + "\n");
            }
            preyfile.close();
        }

        //</editor-fold>

        Logger.getRootLogger().info("Job done");
        Logger.getRootLogger().info(
                "=================================================================================================");

    } catch (Exception e) {
        Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e));
        throw e;
    }
}

From source file:org.aksw.facete2.web.main.DebuggingTest.java

public static void main(String[] args) throws Exception {
    String qs;
    //http://localhost:7532/cache/sparql
    //String qs = "Select ?p_1 ?_c_ {{{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/hasEndpoints>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/url>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://www.w3.org/2000/01/rdf-schema#label>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/owner>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/hasDownloads>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/version>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/hasDefaultGraphs>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/groupId>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/artifactId>)))}  Limit 1000 }}  }} Group By ?p_1  }}}  Limit 1000";
    //String qs = "Select ?p_1 ?_c_ {{{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/hasEndpoints>)))}  Limit 1000 }}  }} Group By ?p_1  }}}  Limit 1000";

    //qs = "Select ?p_1 ?_c_ {{{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/hasEndpoints>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/url>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://www.w3.org/2000/01/rdf-schema#label>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/owner>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/hasDownloads>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/version>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>)))}  Limit 1000 }}  }} Group By ?p_1  }}  Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/hasDefaultGraphs>)))}  Limit 1000 }}  }} Group By ?p_1  }}}";

    String lastWorking = "Select ?p_1 ?_c_ {{{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/hasEndpoints>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/url>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://www.w3.org/2000/01/rdf-schema#label>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/owner>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/hasDownloads>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/version>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>)))}  Limit 1000 }}  }}                                               Group By ?p_1  }}}";
    String firstNotWorking = "Select ?p_1 ?_c_ {{{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/hasEndpoints>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/url>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://www.w3.org/2000/01/rdf-schema#label>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/owner>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/hasDownloads>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/version>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>)))}  Limit 1000 }}  }}                                                Group By ?p_1  }}}";

    //qs = lastWorking;
    qs = firstNotWorking;// ww  w . ja  v  a 2 s  .  co  m

    System.out.println(qs.length());
    //qs = "Select ?p_1 ?_c_ {{{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/hasEndpoints>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/url>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://www.w3.org/2000/01/rdf-schema#label>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/owner>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/hasDownloads>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://dcat.cc/ontology/version>)))}  Limit 1000 }}  }} Group By ?p_1  }} Union {{ Select ?p_1 (Count(*) As ?_c_) {{ Select ?p_1 ?o_1 {{ Select ?p_1 ?o_1 {?s ?p_1 ?o_1 . Filter((?p_1 In (<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>)))}  Limit 1000 }}  }} Group By ?p_1  }}}";

    //String qs = "Select * { ?s ?p ?o }";
    QueryEngineHTTP qe = new QueryEngineHTTP("http://localhost:7533/api/sparql", qs);
    ResultSet rs = qe.execSelect();
    String str = ResultSetFormatter.asText(rs);
    System.out.println(str);
}

From source file:Main.java

public static String capitalize(String s) {
    if (s.length() == 0) {
        return s;
    }/*ww w.j  a v a 2  s  .co  m*/

    return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}

From source file:Main.java

public static boolean isJavaIdentifier(String s) {
    if (s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0))) {
        return false;
    }// ww  w.ja va 2 s .c o  m
    for (int i = 1; i < s.length(); i++) {
        if (!Character.isJavaIdentifierPart(s.charAt(i))) {
            return false;
        }
    }
    return true;
}

From source file:Main.java

private static String removeLastChar(String str) {
    return str.substring(0, str.length() - 1);
}

From source file:Main.java

public static boolean containsOnlyNumbers(String str) {
    for (int i = 0; i < str.length(); i++) {
        if (!Character.isDigit(str.charAt(i)))
            return false;
    }//from www.ja  v a 2s . c om
    return true;
}

From source file:Main.java

public static String compare(String st1, String st2) {
    if (st1.length() > st2.length()) {
        return st1;
    } else {/*from   ww  w  .j a  v a 2  s.c  o m*/
        return st2;
    }
}