Search in sources :

Example 1 with CoreException

use of com.biglybt.core.CoreException in project BiglyBT by BiglySoftware.

the class ClientRestarterImpl method runUpdateProcess.

private boolean runUpdateProcess(boolean update_only, boolean no_wait) throws CoreException {
    PluginInterface pi = core.getPluginManager().getPluginInterfaceByID("azupdater");
    if (pi == null) {
        Logger.log(new LogAlert(LogAlert.UNREPEATABLE, LogAlert.AT_ERROR, "Can't update/restart, mandatory plugin 'azupdater' not found"));
        throw (new CoreException("mandatory plugin 'azupdater' not found"));
    }
    String updater_dir = pi.getPluginDirectoryName();
    classpath_prefix = updater_dir + File.separator + UPDATER_JAR;
    String app_path = SystemProperties.getApplicationPath();
    while (app_path.endsWith(File.separator)) {
        app_path = app_path.substring(0, app_path.length() - 1);
    }
    String user_path = SystemProperties.getUserPath();
    while (user_path.endsWith(File.separator)) {
        user_path = user_path.substring(0, user_path.length() - 1);
    }
    String config_override = System.getProperty(SystemProperties.SYS_PROP_CONFIG_OVERRIDE);
    if (config_override == null) {
        config_override = "";
    }
    String[] parameters = { update_only ? "updateonly" : "restart", app_path, user_path, config_override };
    FileOutputStream fos = null;
    try {
        Properties update_properties = new Properties();
        long max_mem = Runtime.getRuntime().maxMemory();
        update_properties.put("max_mem", "" + max_mem);
        update_properties.put("app_name", SystemProperties.getApplicationName());
        update_properties.put("app_entry", SystemProperties.getApplicationEntryPoint());
        if (System.getProperty(SystemProperties.SYSPROP_NATIVELAUNCHER) != null || Constants.isOSX) {
            try {
                String cmd = PlatformManagerFactory.getPlatformManager().getApplicationCommandLine();
                if (cmd != null) {
                    update_properties.put("app_cmd", cmd);
                }
            } catch (Throwable e) {
                Debug.printStackTrace(e);
            }
        }
        if (no_wait) {
            update_properties.put("no_wait", "1");
        }
        update_properties.put("instance_port", String.valueOf(Constants.INSTANCE_PORT));
        fos = new FileOutputStream(new File(user_path, UPDATE_PROPERTIES));
        // this handles unicode chars by writing \\u escapes
        update_properties.store(fos, "BiglyBT restart properties");
    } catch (Throwable e) {
        Debug.printStackTrace(e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (Throwable e) {
                Debug.printStackTrace(e);
            }
        }
    }
    String[] properties = { "-Duser.dir=\"" + app_path + "\"" };
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    boolean res = restartApp(new PrintWriter(os) {

        @Override
        public void println(String str) {
            // we intercept these logs and log immediately
            Logger.log(new LogEvent(LOGID, str));
        }
    }, MAIN_CLASS, properties, parameters, update_only);
    // just check if any non-logged data exists
    byte[] bytes = os.toByteArray();
    if (bytes.length > 0) {
        Logger.log(new LogEvent(LOGID, "BiglyBTUpdater: extra log - " + new String(bytes)));
    }
    return (res);
}
Also used : LogEvent(com.biglybt.core.logging.LogEvent) PluginInterface(com.biglybt.pif.PluginInterface) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SystemProperties(com.biglybt.core.util.SystemProperties) Properties(java.util.Properties) LogAlert(com.biglybt.core.logging.LogAlert) CoreException(com.biglybt.core.CoreException) FileOutputStream(java.io.FileOutputStream) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 2 with CoreException

use of com.biglybt.core.CoreException in project BiglyBT by BiglySoftware.

the class TorrentFilter method matchRange.

/**
 * matches a range of torrents. eg: 3-5 or a single torrent. eg: 3. or from 3 onwards: 3-
 * @param torrents torrents to match
 * @param filter range expression
 * @return list of matched DownloadManager objects
 */
private List matchRange(List torrents, String filter) {
    Matcher matcher = rangePattern.matcher(filter);
    List list = new ArrayList();
    if (matcher.matches()) {
        int minId = Integer.parseInt(matcher.group(1));
        if (minId == 0)
            throw new CoreException("lower range must be greater than 0");
        if (minId > torrents.size())
            throw new CoreException("lower range specified (" + minId + ") is outside number of torrents (" + torrents.size() + ")");
        if (matcher.group(2) == null) {
            // received a single number. eg: 3
            list.add(torrents.get(minId - 1));
            return list;
        }
        int maxId;
        if (matcher.group(3) == null)
            // received bound range. eg: 3-5
            maxId = Integer.parseInt(matcher.group(5));
        else
            // received open ended range. eg: 3-
            maxId = torrents.size();
        if (minId > maxId)
            throw new CoreException("when specifying a range, the max value must be greater than or equal to the min value");
        for (int i = (minId - 1); i < maxId && i < torrents.size(); i++) {
            list.add(torrents.get(i));
        }
    }
    return list;
}
Also used : CoreException(com.biglybt.core.CoreException) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList)

Example 3 with CoreException

use of com.biglybt.core.CoreException in project BiglyBT by BiglySoftware.

the class AddFind method execute.

@Override
public void execute(String commandName, ConsoleInput ci, CommandLine commands) {
    if (commands.hasOption('l')) {
        ci.out.println("> -----");
        showAdds(ci);
        ci.out.println("> -----");
        return;
    } else if (commands.hasOption('h') || commands.getArgs().length == 0) {
        printHelp(ci.out, (String) null);
        return;
    }
    String outputDir = ".";
    if (commands.hasOption('o'))
        outputDir = commands.getOptionValue('o');
    else
        outputDir = ci.getDefaultSaveDirectory();
    File f = new File(outputDir);
    if (!f.isAbsolute()) {
        // make it relative to current directory
        try {
            outputDir = new File(".", outputDir).getCanonicalPath();
        } catch (IOException e) {
            throw new CoreException("exception occurred while converting directory: ./" + outputDir + " to its canonical path");
        }
    }
    boolean scansubdir = commands.hasOption('r');
    boolean finding = commands.hasOption('f');
    String[] whatelse = commands.getArgs();
    for (int i = 0; i < whatelse.length; i++) {
        String arg = whatelse[i];
        try {
            // firstly check if it is a valid URL
            new URL(arg);
            addRemote(ci, arg, outputDir);
        } catch (MalformedURLException e) {
            // assume that it's a local file or file id from a previous find
            addLocal(ci, arg, outputDir, scansubdir, finding);
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) CoreException(com.biglybt.core.CoreException) IOException(java.io.IOException) File(java.io.File) URL(java.net.URL)

Example 4 with CoreException

use of com.biglybt.core.CoreException in project BiglyBT by BiglySoftware.

the class UserManager method getInstance.

public static UserManager getInstance(PluginInterface pi) {
    synchronized (UserManager.class) {
        if (instance == null) {
            String userDir = pi.getUtilities().getUserDir();
            File dbFile = new File(userDir, USER_DB_CONFIG_FILE);
            try {
                instance = new UserManager(dbFile.getCanonicalPath());
                if (dbFile.exists()) {
                    System.out.println("loading user configuration from: " + dbFile.getCanonicalPath());
                    instance.load();
                } else {
                    System.out.println("file: " + dbFile.getCanonicalPath() + " does not exist. using 'null' user manager");
                }
            } catch (IOException e) {
                throw new CoreException("Unable to instantiate default user manager");
            }
        }
        return instance;
    }
}
Also used : CoreException(com.biglybt.core.CoreException)

Example 5 with CoreException

use of com.biglybt.core.CoreException in project BiglyBT by BiglySoftware.

the class Main method main.

public static void main(String[] args) {
    if (DEBUG_STARTUPTIME) {
        lastDebugTime = System.currentTimeMillis();
    }
    if (Launcher.checkAndLaunch(Main.class, args))
        return;
    // This *has* to be done first as it sets system properties that are read and cached by Java
    COConfigurationManager.preInitialise();
    if (DEBUG_STARTUPTIME) {
        logTime("args: " + Arrays.toString(args));
    }
    Thread.currentThread().setName(Constants.APP_NAME);
    String mi_str = System.getProperty("MULTI_INSTANCE");
    boolean mi = mi_str != null && mi_str.equalsIgnoreCase("true");
    if (DEBUG_STARTUPTIME) {
        logTime("preInit");
    }
    try {
        // Build a list of UIS
        Options uiOptions = new Options();
        Builder builder = Option.builder("u").longOpt("ui").argName("uis").hasArg();
        uiOptions.addOption(builder.build());
        if (Constants.isWindows) {
            builder = Option.builder("console");
            uiOptions.addOption(builder.build());
        }
        try {
            CommandLine commandLine = new DefaultParser().parse(uiOptions, args, true);
            buildUIList(commandLine);
        } catch (ParseException e) {
        }
        // Add UIS Command Line Options
        Options options = UIConst.buildOptions();
        commands = UIConst.buildCommandLine(options, args);
        if (commands == null) {
            System.exit(0);
        }
        if (DEBUG_STARTUPTIME) {
            logTime("buildCommandLine");
        }
        if (!mi) {
            startServer = new StartServer();
            if (startServer.getServerState() == StartServer.STATE_FAULTY) {
                System.setProperty("transitory.startup", "1");
                // looks like there's already a process listening on 127.0.0.1:<port>
                // attempt to pass args to existing instance
                // First, do some OSX magic because parameters are passed via OpenDocument API and other callbacks
                args = CocoaMagic(args);
                if (!new CoreSingleInstanceClient().sendArgs(args, 5000)) {
                    // arg passing attempt failed, so start core anyway
                    String msg = "There appears to be another process already listening on socket [127.0.0.1:" + Constants.INSTANCE_PORT + "].\n\nLocate and terminate the other program or change the control port - <a href=\"" + Constants.URL_WIKI + "w/Commandline_options#Changing_the_Control_Port\">see the wiki for details</a>.";
                    System.err.println(msg);
                    return;
                } else {
                    // we sent params to other core, don't init the core
                    return;
                }
            }
            if (commands.hasOption("closedown") || commands.hasOption("shutdown") || commands.hasOption("restart")) {
                return;
            }
            if (DEBUG_STARTUPTIME) {
                logTime("StartServer");
            }
        } else {
            System.out.println("MULTI_INSTANCE enabled");
        }
        // Special Exit if user ask for help
        if (commands != null && commands.hasOption('h')) {
            HelpFormatter hf = new HelpFormatter();
            hf.setOptionComparator(null);
            hf.printHelp("[options] [torrent [torrent ...]]", options);
            if (startServer != null) {
                startServer.stopIt();
            }
            System.exit(0);
        }
        boolean isFirst = true;
        for (IUserInterface ui : UIConst.UIS.values()) {
            ui.init(isFirst, (UIConst.UIS.size() > 1));
            isFirst = false;
        }
        neverStarted = true;
        core = CoreFactory.create();
        if (DEBUG_STARTUPTIME) {
            logTime("Core Create");
        }
        for (IUserInterface ui : UIConst.UIS.values()) {
            ui.coreCreated(core);
        }
        if (DEBUG_STARTUPTIME) {
            logTime("UIConst.set" + Constants.AZUREUS_NAME + "Core");
        }
        UIConst.processArgs(commands, options, args);
        if (DEBUG_STARTUPTIME) {
            logTime("UIConst.processArgs");
        }
        if (startServer != null) {
            startServer.setDaemon(true);
            startServer.start();
        }
        neverStarted = !core.isStarted();
        core.addLifecycleListener(new CoreLifecycleAdapter() {

            @Override
            public void started(Core core) {
                Main.neverStarted = false;
            }

            @Override
            public void stopping(Core core) {
                Main.stopping = true;
            }

            @Override
            public void stopped(Core core) {
                if (startServer != null) {
                    startServer.stopIt();
                }
                Main.stopped = true;
            }
        });
        for (IUserInterface ui : UIConst.UIS.values()) {
            ui.takeMainThread();
            if (stopping) {
                break;
            }
        }
        if (neverStarted) {
            if (DEBUG_STARTUPTIME) {
                logTime("takeMainThread");
            }
            core.start();
            if (DEBUG_STARTUPTIME) {
                logTime("coreStart");
            }
        }
        if (!stopping) {
            // no one took the main thread!
            while (!stopped) {
                try {
                    Thread.sleep(200);
                    // (not case "-u console,Swt")
                    if (newUI != null) {
                        IUserInterface threadTaker = newUI;
                        newUI = null;
                        threadTaker.takeMainThread();
                    }
                } catch (InterruptedException e) {
                }
            }
        }
    } catch (CoreException e) {
        System.out.println("Start fails:");
        e.printStackTrace();
    }
    if (DEBUG_STARTUPTIME) {
        logTime("DONE");
    }
}
Also used : CoreSingleInstanceClient(com.biglybt.core.impl.CoreSingleInstanceClient) CoreLifecycleAdapter(com.biglybt.core.CoreLifecycleAdapter) IUserInterface(com.biglybt.ui.common.IUserInterface) Builder(org.apache.commons.cli.Option.Builder) CoreException(com.biglybt.core.CoreException) StartServer(com.biglybt.ui.common.StartServer) Core(com.biglybt.core.Core)

Aggregations

CoreException (com.biglybt.core.CoreException)6 File (java.io.File)2 Core (com.biglybt.core.Core)1 CoreLifecycleAdapter (com.biglybt.core.CoreLifecycleAdapter)1 CoreSingleInstanceClient (com.biglybt.core.impl.CoreSingleInstanceClient)1 LogAlert (com.biglybt.core.logging.LogAlert)1 LogEvent (com.biglybt.core.logging.LogEvent)1 SystemProperties (com.biglybt.core.util.SystemProperties)1 PluginInterface (com.biglybt.pif.PluginInterface)1 IUserInterface (com.biglybt.ui.common.IUserInterface)1 StartServer (com.biglybt.ui.common.StartServer)1 StringEncrypter (com.biglybt.ui.console.util.StringEncrypter)1 EncryptionException (com.biglybt.ui.console.util.StringEncrypter.EncryptionException)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1 PrintWriter (java.io.PrintWriter)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 ArrayList (java.util.ArrayList)1