Search in sources :

Example 6 with ExceptionUtils.getStackTrace

use of org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace in project bitsquare by bitsquare.

the class StatisticsMain method doExecute.

@Override
protected void doExecute(OptionSet options) {
    final BitsquareEnvironment environment = new BitsquareEnvironment(options);
    Statistics.setEnvironment(environment);
    UserThread.execute(() -> statistics = new Statistics());
    Thread.UncaughtExceptionHandler handler = (thread, throwable) -> {
        if (throwable.getCause() != null && throwable.getCause().getCause() != null && throwable.getCause().getCause() instanceof BlockStoreException) {
            log.error(throwable.getMessage());
        } else {
            log.error("Uncaught Exception from thread " + Thread.currentThread().getName());
            log.error("throwableMessage= " + throwable.getMessage());
            log.error("throwableClass= " + throwable.getClass());
            log.error("Stack trace:\n" + ExceptionUtils.getStackTrace(throwable));
            throwable.printStackTrace();
            log.error("We shut down the app because an unhandled error occurred");
            // We don't use the restart as in case of OutOfMemory errors the restart might fail as well
            // The run loop will restart the node anyway...
            System.exit(EXIT_FAILURE);
        }
    };
    Thread.setDefaultUncaughtExceptionHandler(handler);
    Thread.currentThread().setUncaughtExceptionHandler(handler);
    String maxMemoryOption = environment.getProperty(AppOptionKeys.MAX_MEMORY);
    if (maxMemoryOption != null && !maxMemoryOption.isEmpty()) {
        try {
            maxMemory = Integer.parseInt(maxMemoryOption);
        } catch (Throwable t) {
            log.error(t.getMessage());
        }
    }
    UserThread.runPeriodically(() -> {
        Profiler.printSystemLoad(log);
        long usedMemoryInMB = Profiler.getUsedMemoryInMB();
        if (!stopped) {
            if (usedMemoryInMB > (maxMemory - 100)) {
                log.warn("\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" + "We are over our memory warn limit and call the GC. usedMemoryInMB: {}" + "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n", usedMemoryInMB);
                System.gc();
                usedMemoryInMB = Profiler.getUsedMemoryInMB();
                Profiler.printSystemLoad(log);
            }
            final long finalUsedMemoryInMB = usedMemoryInMB;
            UserThread.runAfter(() -> {
                if (finalUsedMemoryInMB > maxMemory) {
                    log.error("\n\n############################################################\n" + "We shut down as we are over our memory limit. usedMemoryInMB: {}" + "\n############################################################\n\n", finalUsedMemoryInMB);
                    System.exit(EXIT_FAILURE);
                }
            }, 1);
        }
    }, CHECK_MEMORY_PERIOD_SEC);
    while (true) {
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException ignore) {
        }
    }
}
Also used : ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) Logger(org.slf4j.Logger) UserThread(io.bitsquare.common.UserThread) LoggerFactory(org.slf4j.LoggerFactory) IOException(java.io.IOException) DEFAULT_USER_DATA_DIR(io.bitsquare.app.BitsquareEnvironment.DEFAULT_USER_DATA_DIR) Executors(java.util.concurrent.Executors) AppOptionKeys(io.bitsquare.app.AppOptionKeys) OptionException(joptsimple.OptionException) BitsquareEnvironment(io.bitsquare.app.BitsquareEnvironment) BitsquareExecutable(io.bitsquare.app.BitsquareExecutable) OptionParser(joptsimple.OptionParser) RestartUtil(io.bitsquare.common.util.RestartUtil) Profiler(io.bitsquare.common.util.Profiler) BlockStoreException(org.bitcoinj.store.BlockStoreException) ThreadFactory(java.util.concurrent.ThreadFactory) OptionSet(joptsimple.OptionSet) ExceptionUtils(org.apache.commons.lang3.exception.ExceptionUtils) DEFAULT_APP_NAME(io.bitsquare.app.BitsquareEnvironment.DEFAULT_APP_NAME) BlockStoreException(org.bitcoinj.store.BlockStoreException) BitsquareEnvironment(io.bitsquare.app.BitsquareEnvironment) UserThread(io.bitsquare.common.UserThread)

Example 7 with ExceptionUtils.getStackTrace

use of org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace in project bisq-api by mrosseel.

the class ApiMain method doExecute.

@SuppressWarnings("InfiniteLoopStatement")
@Override
protected void doExecute(OptionSet options) {
    final BisqEnvironment bisqEnvironment = getBisqEnvironment(options);
    Api.setEnvironment(bisqEnvironment);
    UserThread.execute(() -> {
        try {
            api = new Api();
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
    Thread.UncaughtExceptionHandler handler = (thread, throwable) -> {
        if (throwable.getCause() != null && throwable.getCause().getCause() != null && throwable.getCause().getCause() instanceof BlockStoreException) {
            log.error(throwable.getMessage());
        } else {
            log.error("Uncaught Exception from thread " + Thread.currentThread().getName());
            log.error("throwableMessage= " + throwable.getMessage());
            log.error("throwableClass= " + throwable.getClass());
            log.error("Stack trace:\n" + ExceptionUtils.getStackTrace(throwable));
            throwable.printStackTrace();
            log.error("We shut down the app because an unhandled error occurred");
            // We don't use the restart as in case of OutOfMemory errors the restart might fail as well
            // The run loop will restart the node anyway...
            System.exit(EXIT_FAILURE);
        }
    };
    Thread.setDefaultUncaughtExceptionHandler(handler);
    Thread.currentThread().setUncaughtExceptionHandler(handler);
    String maxMemoryOption = bisqEnvironment.getProperty(AppOptionKeys.MAX_MEMORY);
    if (maxMemoryOption != null && !maxMemoryOption.isEmpty()) {
        try {
            maxMemory = Integer.parseInt(maxMemoryOption);
        } catch (Throwable t) {
            log.error(t.getMessage());
        }
    }
    UserThread.runPeriodically(() -> {
        Profiler.printSystemLoad(log);
        long usedMemoryInMB = Profiler.getUsedMemoryInMB();
        if (!stopped) {
            if (usedMemoryInMB > (maxMemory - 100)) {
                log.warn("\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n" + "We are over our memory warn limit and call the GC. usedMemoryInMB: {}" + "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n", usedMemoryInMB);
                System.gc();
                usedMemoryInMB = Profiler.getUsedMemoryInMB();
                Profiler.printSystemLoad(log);
            }
            final long finalUsedMemoryInMB = usedMemoryInMB;
            UserThread.runAfter(() -> {
                if (finalUsedMemoryInMB > maxMemory)
                    restart(bisqEnvironment);
            }, 1);
        }
    }, CHECK_MEMORY_PERIOD_SEC);
    while (true) {
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException ignore) {
        }
    }
}
Also used : ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) BisqEnvironment(io.bisq.core.app.BisqEnvironment) BisqExecutable(io.bisq.core.app.BisqExecutable) Profiler(io.bisq.common.util.Profiler) UserThread(io.bisq.common.UserThread) AppOptionKeys(io.bisq.core.app.AppOptionKeys) IOException(java.io.IOException) RestartUtil(io.bisq.common.util.RestartUtil) Executors(java.util.concurrent.Executors) DEFAULT_APP_NAME(io.bisq.core.app.BisqEnvironment.DEFAULT_APP_NAME) DEFAULT_USER_DATA_DIR(io.bisq.core.app.BisqEnvironment.DEFAULT_USER_DATA_DIR) Slf4j(lombok.extern.slf4j.Slf4j) OptionException(joptsimple.OptionException) OptionParser(joptsimple.OptionParser) BlockStoreException(org.bitcoinj.store.BlockStoreException) ThreadFactory(java.util.concurrent.ThreadFactory) OptionSet(joptsimple.OptionSet) ExceptionUtils(org.apache.commons.lang3.exception.ExceptionUtils) BlockStoreException(org.bitcoinj.store.BlockStoreException) BisqEnvironment(io.bisq.core.app.BisqEnvironment) IOException(java.io.IOException) OptionException(joptsimple.OptionException) BlockStoreException(org.bitcoinj.store.BlockStoreException) UserThread(io.bisq.common.UserThread)

Example 8 with ExceptionUtils.getStackTrace

use of org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace in project bisq-api by mrosseel.

the class BisqApiWithUI method start.

@SuppressWarnings("PointlessBooleanExpression")
@Override
public void start(Stage stage) throws IOException {
    BisqApiWithUI.primaryStage = stage;
    String logPath = Paths.get(bisqEnvironment.getProperty(AppOptionKeys.APP_DATA_DIR_KEY), "bisq").toString();
    Log.setup(logPath);
    log.info("Log files under: " + logPath);
    Utilities.printSysInfo();
    Log.setLevel(Level.toLevel(bisqEnvironment.getRequiredProperty(CommonOptionKeys.LOG_LEVEL_KEY)));
    UserThread.setExecutor(Platform::runLater);
    UserThread.setTimerClass(UITimer.class);
    shutDownHandler = this::stop;
    BisqApp.shutDownHandler = shutDownHandler;
    // setup UncaughtExceptionHandler
    Thread.UncaughtExceptionHandler handler = (thread, throwable) -> {
        // Might come from another thread
        if (throwable.getCause() != null && throwable.getCause().getCause() != null && throwable.getCause().getCause() instanceof BlockStoreException) {
            log.error(throwable.getMessage());
        } else if (throwable instanceof ClassCastException && "sun.awt.image.BufImgSurfaceData cannot be cast to sun.java2d.xr.XRSurfaceData".equals(throwable.getMessage())) {
            log.warn(throwable.getMessage());
        } else {
            log.error("Uncaught Exception from thread " + Thread.currentThread().getName());
            log.error("throwableMessage= " + throwable.getMessage());
            log.error("throwableClass= " + throwable.getClass());
            log.error("Stack trace:\n" + ExceptionUtils.getStackTrace(throwable));
            throwable.printStackTrace();
            UserThread.execute(() -> showErrorPopup(throwable, false));
        }
    };
    Thread.setDefaultUncaughtExceptionHandler(handler);
    Thread.currentThread().setUncaughtExceptionHandler(handler);
    try {
        Utilities.checkCryptoPolicySetup();
    } catch (NoSuchAlgorithmException | LimitedKeyStrengthException e) {
        e.printStackTrace();
        UserThread.execute(() -> showErrorPopup(e, true));
    }
    Security.addProvider(new BouncyCastleProvider());
    final BaseCurrencyNetwork baseCurrencyNetwork = BisqEnvironment.getBaseCurrencyNetwork();
    final String currencyCode = baseCurrencyNetwork.getCurrencyCode();
    Res.setBaseCurrencyCode(currencyCode);
    Res.setBaseCurrencyName(baseCurrencyNetwork.getCurrencyName());
    CurrencyUtil.setBaseCurrencyCode(currencyCode);
    try {
        // Guice
        bisqAppModule = new BisqAppModule(bisqEnvironment, primaryStage);
        injector = Guice.createInjector(bisqAppModule);
        injector.getInstance(InjectorViewFactory.class).setInjector(injector);
        injector.getInstance(BisqApiApplication.class).run("server", "bisq-api.yml");
        // All classes which are persisting objects need to be added here
        // Maintain order!
        ArrayList<PersistedDataHost> persistedDataHosts = new ArrayList<>();
        persistedDataHosts.add(injector.getInstance(Preferences.class));
        persistedDataHosts.add(injector.getInstance(User.class));
        persistedDataHosts.add(injector.getInstance(Navigation.class));
        persistedDataHosts.add(injector.getInstance(AddressEntryList.class));
        persistedDataHosts.add(injector.getInstance(TradeManager.class));
        persistedDataHosts.add(injector.getInstance(OpenOfferManager.class));
        persistedDataHosts.add(injector.getInstance(TradeManager.class));
        persistedDataHosts.add(injector.getInstance(ClosedTradableManager.class));
        persistedDataHosts.add(injector.getInstance(FailedTradesManager.class));
        persistedDataHosts.add(injector.getInstance(DisputeManager.class));
        persistedDataHosts.add(injector.getInstance(P2PService.class));
        persistedDataHosts.add(injector.getInstance(VotingManager.class));
        persistedDataHosts.add(injector.getInstance(CompensationRequestManager.class));
        // we apply at startup the reading of persisted data but don't want to get it triggered in the constructor
        persistedDataHosts.stream().forEach(e -> {
            try {
                log.debug("call readPersisted at " + e.getClass().getSimpleName());
                e.readPersisted();
            } catch (Throwable e1) {
                log.error("readPersisted error", e1);
            }
        });
        Version.setBaseCryptoNetworkId(BisqEnvironment.getBaseCurrencyNetwork().ordinal());
        Version.printVersion();
        if (Utilities.isLinux())
            System.setProperty("prism.lcdtext", "false");
        Storage.setDatabaseCorruptionHandler((String fileName) -> {
            corruptedDatabaseFiles.add(fileName);
            if (mainView != null)
                mainView.setPersistedFilesCorrupted(corruptedDatabaseFiles);
        });
        // load the main view and create the main scene
        CachingViewLoader viewLoader = injector.getInstance(CachingViewLoader.class);
        mainView = (MainView) viewLoader.load(MainView.class);
        mainView.setPersistedFilesCorrupted(corruptedDatabaseFiles);
        /* Storage.setDatabaseCorruptionHandler((String fileName) -> {
                corruptedDatabaseFiles.add(fileName);
                if (mainView != null)
                    mainView.setPersistedFilesCorrupted(corruptedDatabaseFiles);
            });*/
        // 740
        scene = new Scene(mainView.getRoot(), 1200, 710);
        Font.loadFont(getClass().getResource("/fonts/Verdana.ttf").toExternalForm(), 13);
        Font.loadFont(getClass().getResource("/fonts/VerdanaBold.ttf").toExternalForm(), 13);
        Font.loadFont(getClass().getResource("/fonts/VerdanaItalic.ttf").toExternalForm(), 13);
        Font.loadFont(getClass().getResource("/fonts/VerdanaBoldItalic.ttf").toExternalForm(), 13);
        scene.getStylesheets().setAll("/io/bisq/gui/bisq.css", "/io/bisq/gui/images.css", "/io/bisq/gui/CandleStickChart.css");
        // configure the system tray
        SystemTray.create(primaryStage, shutDownHandler);
        primaryStage.setOnCloseRequest(event -> {
            event.consume();
            stop();
        });
        scene.addEventHandler(KeyEvent.KEY_RELEASED, keyEvent -> {
            Utilities.isAltOrCtrlPressed(KeyCode.W, keyEvent);
            if (Utilities.isCtrlPressed(KeyCode.W, keyEvent) || Utilities.isCtrlPressed(KeyCode.Q, keyEvent)) {
                stop();
            } else {
                if (Utilities.isAltOrCtrlPressed(KeyCode.E, keyEvent)) {
                    showEmptyWalletPopup(injector.getInstance(BtcWalletService.class));
                } else if (Utilities.isAltOrCtrlPressed(KeyCode.M, keyEvent)) {
                    showSendAlertMessagePopup();
                } else if (Utilities.isAltOrCtrlPressed(KeyCode.F, keyEvent)) {
                    showFilterPopup();
                } else if (Utilities.isAltOrCtrlPressed(KeyCode.J, keyEvent)) {
                    WalletsManager walletsManager = injector.getInstance(WalletsManager.class);
                    if (walletsManager.areWalletsAvailable())
                        new ShowWalletDataWindow(walletsManager).show();
                    else
                        new Popup<>().warning(Res.get("popup.warning.walletNotInitialized")).show();
                } else if (Utilities.isAltOrCtrlPressed(KeyCode.G, keyEvent)) {
                    if (injector.getInstance(BtcWalletService.class).isWalletReady())
                        injector.getInstance(ManualPayoutTxWindow.class).show();
                    else
                        new Popup<>().warning(Res.get("popup.warning.walletNotInitialized")).show();
                } else if (DevEnv.DEV_MODE) {
                    // dev ode only
                    if (Utilities.isAltOrCtrlPressed(KeyCode.B, keyEvent)) {
                        // BSQ empty wallet not public yet
                        showEmptyWalletPopup(injector.getInstance(BsqWalletService.class));
                    } else if (Utilities.isAltOrCtrlPressed(KeyCode.P, keyEvent)) {
                        showFPSWindow();
                    } else if (Utilities.isAltOrCtrlPressed(KeyCode.Z, keyEvent)) {
                        showDebugWindow();
                    }
                }
            }
        });
        // configure the primary stage
        primaryStage.setTitle(bisqEnvironment.getRequiredProperty(AppOptionKeys.APP_NAME_KEY));
        primaryStage.setScene(scene);
        primaryStage.setMinWidth(1020);
        primaryStage.setMinHeight(620);
        // on windows the title icon is also used as task bar icon in a larger size
        // on Linux no title icon is supported but also a large task bar icon is derived from that title icon
        String iconPath;
        if (Utilities.isOSX())
            iconPath = ImageUtil.isRetina() ? "/images/window_icon@2x.png" : "/images/window_icon.png";
        else if (Utilities.isWindows())
            iconPath = "/images/task_bar_icon_windows.png";
        else
            iconPath = "/images/task_bar_icon_linux.png";
        primaryStage.getIcons().add(new Image(getClass().getResourceAsStream(iconPath)));
        // make the UI visible
        primaryStage.show();
        if (!Utilities.isCorrectOSArchitecture()) {
            String osArchitecture = Utilities.getOSArchitecture();
            // We don't force a shutdown as the osArchitecture might in strange cases return a wrong value.
            // Needs at least more testing on different machines...
            new Popup<>().warning(Res.get("popup.warning.wrongVersion", osArchitecture, Utilities.getJVMArchitecture(), osArchitecture)).show();
        }
        UserThread.runPeriodically(() -> Profiler.printSystemLoad(log), LOG_MEMORY_PERIOD_MIN, TimeUnit.MINUTES);
    } catch (Throwable throwable) {
        log.error("Error during app init", throwable);
        showErrorPopup(throwable, false);
    }
}
Also used : StageStyle(javafx.stage.StageStyle) Version(io.bisq.common.app.Version) Key(com.google.inject.Key) User(io.bisq.core.user.User) ImageUtil(io.bisq.gui.util.ImageUtil) LoggerFactory(org.slf4j.LoggerFactory) UserThread(io.bisq.common.UserThread) Security(java.security.Security) StackPane(javafx.scene.layout.StackPane) Application(javafx.application.Application) Parent(javafx.scene.Parent) ClosedTradableManager(io.bisq.core.trade.closed.ClosedTradableManager) ResultHandler(io.bisq.common.handlers.ResultHandler) DisputeManager(io.bisq.core.arbitration.DisputeManager) CurrencyUtil(io.bisq.common.locale.CurrencyUtil) BlockStoreException(org.bitcoinj.store.BlockStoreException) Pane(javafx.scene.layout.Pane) AddressEntryList(io.bisq.core.btc.AddressEntryList) Font(javafx.scene.text.Font) Res(io.bisq.common.locale.Res) KeyEvent(javafx.scene.input.KeyEvent) UITimer(io.bisq.gui.common.UITimer) CommonOptionKeys(io.bisq.common.CommonOptionKeys) Platform(javafx.application.Platform) List(java.util.List) BisqAppModule(io.bisq.gui.app.BisqAppModule) Logger(ch.qos.logback.classic.Logger) OpenOfferManager(io.bisq.core.offer.OpenOfferManager) InjectorViewFactory(io.bisq.gui.common.view.guice.InjectorViewFactory) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) EventStreams(org.reactfx.EventStreams) Storage(io.bisq.common.storage.Storage) VotingManager(io.bisq.core.dao.vote.VotingManager) io.bisq.core.btc.wallet(io.bisq.core.btc.wallet) SystemTray(io.bisq.gui.SystemTray) ExceptionUtils(org.apache.commons.lang3.exception.ExceptionUtils) TradeManager(io.bisq.core.trade.TradeManager) Scene(javafx.scene.Scene) BaseCurrencyNetwork(io.bisq.core.btc.BaseCurrencyNetwork) ArbitratorManager(io.bisq.core.arbitration.ArbitratorManager) Preferences(io.bisq.core.user.Preferences) io.bisq.gui.main.overlays.windows(io.bisq.gui.main.overlays.windows) CompensationRequestManager(io.bisq.core.dao.compensation.CompensationRequestManager) ArrayList(java.util.ArrayList) AlertManager(io.bisq.core.alert.AlertManager) FilterManager(io.bisq.core.filter.FilterManager) FailedTradesManager(io.bisq.core.trade.failed.FailedTradesManager) MainView(io.bisq.gui.main.MainView) LimitedKeyStrengthException(io.bisq.common.crypto.LimitedKeyStrengthException) KeyCode(javafx.scene.input.KeyCode) Modality(javafx.stage.Modality) BisqEnvironment(io.bisq.core.app.BisqEnvironment) Label(javafx.scene.control.Label) Profiler(io.bisq.common.util.Profiler) ViewLoader(io.bisq.gui.common.view.ViewLoader) Popup(io.bisq.gui.main.overlays.popups.Popup) AppOptionKeys(io.bisq.core.app.AppOptionKeys) IOException(java.io.IOException) Names(com.google.inject.name.Names) View(io.bisq.gui.common.view.View) Log(io.bisq.common.app.Log) BisqApiApplication(io.bisq.api.service.BisqApiApplication) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Injector(com.google.inject.Injector) TimeUnit(java.util.concurrent.TimeUnit) Navigation(io.bisq.gui.Navigation) Level(ch.qos.logback.classic.Level) P2PService(io.bisq.network.p2p.P2PService) CachingViewLoader(io.bisq.gui.common.view.CachingViewLoader) Stage(javafx.stage.Stage) Utilities(io.bisq.common.util.Utilities) BisqApp(io.bisq.gui.app.BisqApp) Paths(java.nio.file.Paths) DevEnv(io.bisq.common.app.DevEnv) PersistedDataHost(io.bisq.common.proto.persistable.PersistedDataHost) Guice(com.google.inject.Guice) DebugView(io.bisq.gui.main.debug.DebugView) Image(javafx.scene.image.Image) TradeManager(io.bisq.core.trade.TradeManager) User(io.bisq.core.user.User) Platform(javafx.application.Platform) DisputeManager(io.bisq.core.arbitration.DisputeManager) ArrayList(java.util.ArrayList) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) P2PService(io.bisq.network.p2p.P2PService) Image(javafx.scene.image.Image) BisqApiApplication(io.bisq.api.service.BisqApiApplication) CachingViewLoader(io.bisq.gui.common.view.CachingViewLoader) CompensationRequestManager(io.bisq.core.dao.compensation.CompensationRequestManager) LimitedKeyStrengthException(io.bisq.common.crypto.LimitedKeyStrengthException) Popup(io.bisq.gui.main.overlays.popups.Popup) AddressEntryList(io.bisq.core.btc.AddressEntryList) Preferences(io.bisq.core.user.Preferences) InjectorViewFactory(io.bisq.gui.common.view.guice.InjectorViewFactory) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) FailedTradesManager(io.bisq.core.trade.failed.FailedTradesManager) Navigation(io.bisq.gui.Navigation) BlockStoreException(org.bitcoinj.store.BlockStoreException) VotingManager(io.bisq.core.dao.vote.VotingManager) Scene(javafx.scene.Scene) UserThread(io.bisq.common.UserThread) OpenOfferManager(io.bisq.core.offer.OpenOfferManager) BisqAppModule(io.bisq.gui.app.BisqAppModule) PersistedDataHost(io.bisq.common.proto.persistable.PersistedDataHost) BaseCurrencyNetwork(io.bisq.core.btc.BaseCurrencyNetwork) ClosedTradableManager(io.bisq.core.trade.closed.ClosedTradableManager)

Example 9 with ExceptionUtils.getStackTrace

use of org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace in project rpki-validator-3 by RIPE-NCC.

the class CertificateTreeValidationService method validateCertificateAuthority.

private List<RpkiObject> validateCertificateAuthority(TrustAnchor trustAnchor, Map<URI, RpkiRepository> registeredRepositories, CertificateRepositoryObjectValidationContext context, ValidationResult validationResult) {
    final List<RpkiObject> validatedObjects = new ArrayList<>();
    ValidationLocation certificateLocation = validationResult.getCurrentLocation();
    ValidationResult temporary = ValidationResult.withLocation(certificateLocation);
    try {
        RpkiRepository rpkiRepository = registerRepository(trustAnchor, registeredRepositories, context);
        temporary.warnIfTrue(rpkiRepository.isPending(), VALIDATOR_RPKI_REPOSITORY_PENDING, rpkiRepository.getLocationUri());
        if (rpkiRepository.isPending()) {
            return validatedObjects;
        }
        X509ResourceCertificate certificate = context.getCertificate();
        URI manifestUri = certificate.getManifestUri();
        temporary.setLocation(new ValidationLocation(manifestUri));
        Optional<RpkiObject> manifestObject = rpkiObjects.findLatestByTypeAndAuthorityKeyIdentifier(RpkiObject.Type.MFT, context.getSubjectKeyIdentifier());
        if (!manifestObject.isPresent()) {
            if (rpkiRepository.getStatus() == RpkiRepository.Status.FAILED) {
                temporary.error(ValidationString.VALIDATOR_NO_MANIFEST_REPOSITORY_FAILED, rpkiRepository.getLocationUri());
            } else {
                temporary.error(ValidationString.VALIDATOR_NO_LOCAL_MANIFEST_NO_MANIFEST_IN_REPOSITORY, rpkiRepository.getLocationUri());
            }
        }
        Optional<ManifestCms> maybeManifest = manifestObject.flatMap(x -> rpkiObjects.findCertificateRepositoryObject(x.getId(), ManifestCms.class, temporary));
        temporary.rejectIfTrue(manifestObject.isPresent() && rpkiRepository.getStatus() == RpkiRepository.Status.FAILED && maybeManifest.isPresent() && maybeManifest.get().isPastValidityTime(), ValidationString.VALIDATOR_OLD_LOCAL_MANIFEST_REPOSITORY_FAILED, rpkiRepository.getLocationUri());
        if (temporary.hasFailureForCurrentLocation()) {
            return validatedObjects;
        }
        ManifestCms manifest = maybeManifest.get();
        List<Map.Entry<String, byte[]>> crlEntries = manifest.getFiles().entrySet().stream().filter((entry) -> RepositoryObjectType.parse(entry.getKey()) == RepositoryObjectType.Crl).collect(toList());
        temporary.rejectIfFalse(crlEntries.size() == 1, VALIDATOR_MANIFEST_CONTAINS_ONE_CRL_ENTRY, String.valueOf(crlEntries.size()));
        if (temporary.hasFailureForCurrentLocation()) {
            return validatedObjects;
        }
        Map.Entry<String, byte[]> crlEntry = crlEntries.get(0);
        URI crlUri = manifestUri.resolve(crlEntry.getKey());
        Optional<RpkiObject> crlObject = rpkiObjects.findBySha256(crlEntry.getValue());
        temporary.rejectIfFalse(crlObject.isPresent(), VALIDATOR_CRL_FOUND, crlUri.toASCIIString());
        if (temporary.hasFailureForCurrentLocation()) {
            return validatedObjects;
        }
        temporary.setLocation(new ValidationLocation(crlUri));
        Optional<X509Crl> crl = crlObject.flatMap(x -> rpkiObjects.findCertificateRepositoryObject(x.getId(), X509Crl.class, temporary));
        if (temporary.hasFailureForCurrentLocation()) {
            return validatedObjects;
        }
        crl.get().validate(crlUri.toASCIIString(), context, null, VALIDATION_OPTIONS, temporary);
        if (temporary.hasFailureForCurrentLocation()) {
            return validatedObjects;
        }
        temporary.setLocation(new ValidationLocation(manifestUri));
        manifest.validate(manifestUri.toASCIIString(), context, crl.get(), manifest.getCrlUri(), VALIDATION_OPTIONS, temporary);
        if (temporary.hasFailureForCurrentLocation()) {
            return validatedObjects;
        }
        validatedObjects.add(manifestObject.get());
        Map<URI, RpkiObject> manifestEntries = retrieveManifestEntries(manifest, manifestUri, temporary);
        manifestEntries.forEach((location, obj) -> {
            temporary.setLocation(new ValidationLocation(location));
            Optional<CertificateRepositoryObject> maybeCertificateRepositoryObject = rpkiObjects.findCertificateRepositoryObject(obj.getId(), CertificateRepositoryObject.class, temporary);
            if (temporary.hasFailureForCurrentLocation()) {
                return;
            }
            maybeCertificateRepositoryObject.ifPresent(certificateRepositoryObject -> {
                certificateRepositoryObject.validate(location.toASCIIString(), context, crl.get(), crlUri, VALIDATION_OPTIONS, temporary);
                if (!temporary.hasFailureForCurrentLocation()) {
                    validatedObjects.add(obj);
                }
                if (certificateRepositoryObject instanceof X509ResourceCertificate && ((X509ResourceCertificate) certificateRepositoryObject).isCa() && !temporary.hasFailureForCurrentLocation()) {
                    CertificateRepositoryObjectValidationContext childContext = context.createChildContext(location, (X509ResourceCertificate) certificateRepositoryObject);
                    validatedObjects.addAll(validateCertificateAuthority(trustAnchor, registeredRepositories, childContext, temporary));
                }
            });
        });
    } catch (Exception e) {
        log.debug("e", e);
        validationResult.error(ErrorCodes.UNHANDLED_EXCEPTION, e.toString(), ExceptionUtils.getStackTrace(e));
    } finally {
        validationResult.addAll(temporary);
    }
    return validatedObjects;
}
Also used : RpkiRepository(net.ripe.rpki.validator3.domain.RpkiRepository) ValidationRuns(net.ripe.rpki.validator3.domain.ValidationRuns) Arrays(java.util.Arrays) CertificateRepositoryObject(net.ripe.rpki.commons.crypto.CertificateRepositoryObject) Autowired(org.springframework.beans.factory.annotation.Autowired) FlushModeType(javax.persistence.FlushModeType) HashMap(java.util.HashMap) ErrorCodes(net.ripe.rpki.validator3.domain.ErrorCodes) ArrayList(java.util.ArrayList) ValidationOptions(net.ripe.rpki.commons.validation.ValidationOptions) LinkedHashMap(java.util.LinkedHashMap) RpkiRepositories(net.ripe.rpki.validator3.domain.RpkiRepositories) CertificateRepositoryObjectValidationContext(net.ripe.rpki.commons.validation.objectvalidators.CertificateRepositoryObjectValidationContext) X509ResourceCertificate(net.ripe.rpki.commons.crypto.x509cert.X509ResourceCertificate) RpkiObjects(net.ripe.rpki.validator3.domain.RpkiObjects) Service(org.springframework.stereotype.Service) Map(java.util.Map) URI(java.net.URI) Objects(com.google.common.base.Objects) CertificateTreeValidationRun(net.ripe.rpki.validator3.domain.CertificateTreeValidationRun) TrustAnchor(net.ripe.rpki.validator3.domain.TrustAnchor) ValidationStatus(net.ripe.rpki.commons.validation.ValidationStatus) ValidatedRpkiObjects(net.ripe.rpki.validator3.domain.ValidatedRpkiObjects) Transactional(javax.transaction.Transactional) TrustAnchors(net.ripe.rpki.validator3.domain.TrustAnchors) RpkiObject(net.ripe.rpki.validator3.domain.RpkiObject) EntityManager(javax.persistence.EntityManager) X509Crl(net.ripe.rpki.commons.crypto.crl.X509Crl) RepositoryObjectType(net.ripe.rpki.commons.util.RepositoryObjectType) ValidationLocation(net.ripe.rpki.commons.validation.ValidationLocation) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) ValidationResult(net.ripe.rpki.commons.validation.ValidationResult) Optional(java.util.Optional) Settings(net.ripe.rpki.validator3.domain.Settings) ManifestCms(net.ripe.rpki.commons.crypto.cms.manifest.ManifestCms) ValidationString(net.ripe.rpki.commons.validation.ValidationString) ExceptionUtils(org.apache.commons.lang3.exception.ExceptionUtils) X509Crl(net.ripe.rpki.commons.crypto.crl.X509Crl) CertificateRepositoryObjectValidationContext(net.ripe.rpki.commons.validation.objectvalidators.CertificateRepositoryObjectValidationContext) RpkiRepository(net.ripe.rpki.validator3.domain.RpkiRepository) ArrayList(java.util.ArrayList) ValidationLocation(net.ripe.rpki.commons.validation.ValidationLocation) ValidationString(net.ripe.rpki.commons.validation.ValidationString) ValidationResult(net.ripe.rpki.commons.validation.ValidationResult) URI(java.net.URI) RpkiObject(net.ripe.rpki.validator3.domain.RpkiObject) ManifestCms(net.ripe.rpki.commons.crypto.cms.manifest.ManifestCms) CertificateRepositoryObject(net.ripe.rpki.commons.crypto.CertificateRepositoryObject) X509ResourceCertificate(net.ripe.rpki.commons.crypto.x509cert.X509ResourceCertificate) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 10 with ExceptionUtils.getStackTrace

use of org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace in project streamline by hortonworks.

the class DefaultStreamlineAuthorizer method mayBeAddAdminUsers.

private void mayBeAddAdminUsers() {
    LOG.info("Checking user entries for admin users");
    adminUsers.stream().filter(name -> {
        User user = catalogService.getUser(name);
        if (user != null) {
            LOG.info("Entry for user '{}' already exists", name);
            return false;
        } else {
            return true;
        }
    }).forEach(name -> {
        User user = new User();
        user.setName(name);
        user.setEmail(name + "@auto-generated.com");
        user.setMetadata("{\"colorCode\":\"#8261be\",\"colorLabel\":\"purple\",\"icon\":\"gears\"}");
        try {
            User addedUser = catalogService.addUser(user);
            LOG.info("Added admin user entry: {}", addedUser);
        } catch (DuplicateEntityException exception) {
            // In HA setup the other server may have already added the user.
            LOG.info("Caught exception: " + ExceptionUtils.getStackTrace(exception));
            LOG.info("Admin user entry: {} already exists.", user);
        }
    });
}
Also used : DuplicateEntityException(com.hortonworks.streamline.common.exception.DuplicateEntityException) SecurityUtil(com.hortonworks.streamline.streams.security.SecurityUtil) AclEntry(com.hortonworks.streamline.streams.security.catalog.AclEntry) Roles(com.hortonworks.streamline.streams.security.Roles) User(com.hortonworks.streamline.streams.security.catalog.User) Logger(org.slf4j.Logger) Permission(com.hortonworks.streamline.streams.security.Permission) SecurityCatalogService(com.hortonworks.streamline.streams.security.service.SecurityCatalogService) LoggerFactory(org.slf4j.LoggerFactory) AuthorizationException(com.hortonworks.streamline.streams.security.AuthorizationException) Set(java.util.Set) Collectors(java.util.stream.Collectors) Map(java.util.Map) Optional(java.util.Optional) AuthenticationContext(com.hortonworks.streamline.streams.security.AuthenticationContext) StreamlineAuthorizer(com.hortonworks.streamline.streams.security.StreamlineAuthorizer) Role(com.hortonworks.streamline.streams.security.catalog.Role) EnumSet(java.util.EnumSet) ExceptionUtils(org.apache.commons.lang3.exception.ExceptionUtils) User(com.hortonworks.streamline.streams.security.catalog.User) DuplicateEntityException(com.hortonworks.streamline.common.exception.DuplicateEntityException)

Aggregations

ExceptionUtils (org.apache.commons.lang3.exception.ExceptionUtils)16 IOException (java.io.IOException)11 List (java.util.List)11 LoggerFactory (org.slf4j.LoggerFactory)9 Map (java.util.Map)7 ArrayList (java.util.ArrayList)6 TimeUnit (java.util.concurrent.TimeUnit)6 BlockStoreException (org.bitcoinj.store.BlockStoreException)6 Logger (org.slf4j.Logger)6 Paths (java.nio.file.Paths)4 Arrays (java.util.Arrays)4 Executors (java.util.concurrent.Executors)4 Level (ch.qos.logback.classic.Level)3 Logger (ch.qos.logback.classic.Logger)3 ThreadFactoryBuilder (com.google.common.util.concurrent.ThreadFactoryBuilder)3 Guice (com.google.inject.Guice)3 Injector (com.google.inject.Injector)3 URI (java.net.URI)3 HashMap (java.util.HashMap)3 Optional (java.util.Optional)3