Search in sources :

Example 1 with SystemException

use of com.torodb.core.exceptions.SystemException in project torodb by torodb.

the class AttributeReferenceToBuilderCallback method nonExistingKeyCase.

@SuppressWarnings({ "unchecked", "rawtypes" })
private static <R, K> R nonExistingKeyCase(BuilderCallback<K> builder, List<AttributeReference.Key<?>> keys, int fromIndex, int toIndex, boolean createIfNecessary, K key, ResolvedCallback<R> callback) throws UpdateException {
    if (!createIfNecessary) {
        return null;
    }
    BuilderCallback newBuilder = builder;
    for (int i = fromIndex; i < toIndex - 1; i++) {
        AttributeReference.Key<?> iestKey = keys.get(i);
        AttributeReference.Key<?> nextKey = keys.get(i + 1);
        if (nextKey instanceof AttributeReference.ObjectKey) {
            newBuilder = new ObjectBuilderCallback(newBuilder.newObject(iestKey.getKeyValue()));
        } else if (nextKey instanceof AttributeReference.ArrayKey) {
            newBuilder = new ArrayBuilderCallback(newBuilder.newArray(iestKey.getKeyValue()));
        } else {
            throw new SystemException("Unexpected key");
        }
    }
    AttributeReference.Key<?> lastKey = keys.get(toIndex - 1);
    if (lastKey instanceof AttributeReference.ObjectKey) {
        assert newBuilder instanceof ObjectBuilderCallback;
        String castedLastKey = ((AttributeReference.ObjectKey) lastKey).getKeyValue();
        return callback.newElementReferenced((ObjectBuilderCallback) newBuilder, castedLastKey);
    } else if (lastKey instanceof AttributeReference.ArrayKey) {
        assert newBuilder instanceof ArrayBuilderCallback;
        Integer castedLastKey = ((AttributeReference.ArrayKey) lastKey).getKeyValue();
        return callback.newElementReferenced((ArrayBuilderCallback) newBuilder, castedLastKey);
    } else {
        throw new SystemException("Unexpected key");
    }
}
Also used : SystemException(com.torodb.core.exceptions.SystemException) AttributeReference(com.torodb.core.language.AttributeReference)

Example 2 with SystemException

use of com.torodb.core.exceptions.SystemException in project torodb by torodb.

the class AbstractBackendDeserializer method deserialize.

@Override
public T deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    T backend = backendProvider.get();
    ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    ObjectNode node = (ObjectNode) jp.getCodec().readTree(jp);
    JsonNode fieldNode = null;
    Class<? extends BackendImplementation> backendImplementationClass = null;
    Iterator<String> fieldNamesIterator = node.fieldNames();
    while (fieldNamesIterator.hasNext()) {
        String fieldName = fieldNamesIterator.next();
        if (backendImplementationClass != null) {
            throw new JsonParseException("Found multiples backend implementations but only one is " + "allowed");
        }
        fieldNode = node.get(fieldName);
        if (backend.hasBackendImplementation(fieldName)) {
            backendImplementationClass = backend.getBackendImplementationClass(fieldName);
        } else if (setterMap.containsKey(fieldName)) {
            Object value = mapper.treeToValue(fieldNode, setterMap.get(fieldName).v1());
            setterMap.get(fieldName).v2().accept(backend, value);
        } else {
            throw new SystemException("AbstractBackend " + node.fields().next() + " is not valid.");
        }
    }
    if (backendImplementationClass != null) {
        backend.setBackendImplementation(jp.getCodec().treeToValue(fieldNode, backendImplementationClass));
    }
    return backend;
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) SystemException(com.torodb.core.exceptions.SystemException) JsonNode(com.fasterxml.jackson.databind.JsonNode) JsonParseException(org.bson.json.JsonParseException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 3 with SystemException

use of com.torodb.core.exceptions.SystemException in project torodb by torodb.

the class Main method main.

public static void main(String[] args) throws Exception {
    try {
        Console console = JCommander.getConsole();
        ResourceBundle cliBundle = PropertyResourceBundle.getBundle("CliMessages");
        final CliConfig cliConfig = new CliConfig();
        JCommander jCommander = new JCommander(cliConfig, cliBundle, args);
        jCommander.setColumnSize(Integer.MAX_VALUE);
        if (cliConfig.isVersion()) {
            BuildProperties buildProperties = new DefaultBuildProperties();
            console.println(buildProperties.getFullVersion());
            System.exit(0);
        }
        if (cliConfig.isHelp()) {
            jCommander.usage();
            System.exit(0);
        }
        if (cliConfig.isHelpParam()) {
            console.println(cliBundle.getString("cli.help-param-header"));
            ConfigUtils.printParamDescriptionFromConfigSchema(Config.class, cliBundle, console, 0);
            System.exit(0);
        }
        cliConfig.addParams();
        final Config config = CliConfigUtils.readConfig(cliConfig);
        if (cliConfig.isPrintConfig()) {
            ConfigUtils.printYamlConfig(config, console);
            System.exit(0);
        }
        if (cliConfig.isPrintXmlConfig()) {
            ConfigUtils.printXmlConfig(config, console);
            System.exit(0);
        }
        if (cliConfig.isPrintParam()) {
            JsonNode jsonNode = ConfigUtils.getParam(config, cliConfig.getPrintParamPath());
            if (jsonNode != null) {
                console.print(jsonNode.asText());
            }
            System.exit(0);
        }
        configureLogger(cliConfig, config);
        config.getBackend().getBackendImplementation().accept(new BackendImplementationVisitor() {

            @Override
            public void visit(AbstractDerby value) {
                parseToropassFile(value);
            }

            @Override
            public void visit(AbstractPostgres value) {
                parseToropassFile(value);
            }

            public void parseToropassFile(BackendPasswordConfig value) {
                try {
                    ConfigUtils.parseToropassFile(value);
                } catch (Exception ex) {
                    throw new SystemException(ex);
                }
            }
        });
        AbstractReplication replication = config.getReplication();
        if (replication.getAuth().getUser() != null) {
            HostAndPort syncSource = HostAndPort.fromString(replication.getSyncSource()).withDefaultPort(27017);
            ConfigUtils.parseMongopassFile(new MongoPasswordConfig() {

                @Override
                public void setPassword(String password) {
                    replication.getAuth().setPassword(password);
                }

                @Override
                public String getUser() {
                    return replication.getAuth().getUser();
                }

                @Override
                public Integer getPort() {
                    return syncSource.getPort();
                }

                @Override
                public String getPassword() {
                    return replication.getAuth().getPassword();
                }

                @Override
                public String getMongopassFile() {
                    return config.getReplication().getMongopassFile();
                }

                @Override
                public String getHost() {
                    return syncSource.getHostText();
                }

                @Override
                public String getDatabase() {
                    return replication.getAuth().getSource();
                }
            });
        }
        if (config.getBackend().isLike(AbstractPostgres.class)) {
            AbstractPostgres postgres = config.getBackend().as(AbstractPostgres.class);
            if (cliConfig.isAskForPassword()) {
                console.print("Type database user " + postgres.getUser() + "'s password:");
                postgres.setPassword(readPwd());
            }
            if (postgres.getPassword() == null) {
                throw new SystemException("No password provided for database user " + postgres.getUser() + ".\n\n" + "Please add following line to file " + postgres.getToropassFile() + ":\n" + postgres.getHost() + ":" + postgres.getPort() + ":" + postgres.getDatabase() + ":" + postgres.getUser() + ":<password>\n" + "Replace <password> for database user " + postgres.getUser() + "'s password");
            }
        }
        try {
            Clock clock = Clock.systemDefaultZone();
            Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

                @Override
                @SuppressFBWarnings(value = "DM_EXIT", justification = "Since is really hard to stop cleanly all threads when an OOME is thrown we must " + "exit to avoid no more action is performed that could lead to an unespected " + "state")
                public void uncaughtException(Thread t, Throwable e) {
                    if (e instanceof OutOfMemoryError) {
                        try {
                            LOGGER.error("Fatal out of memory: " + e.getLocalizedMessage(), e);
                        } finally {
                            System.exit(1);
                        }
                    }
                }
            });
            Service stampedeService = StampedeBootstrap.createStampedeService(config, clock);
            stampedeService.startAsync();
            stampedeService.awaitTerminated();
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                stampedeService.stopAsync();
                stampedeService.awaitTerminated();
            }));
        } catch (CreationException ex) {
            ex.getErrorMessages().stream().forEach(m -> {
                if (m.getCause() != null) {
                    LOGGER.error(m.getCause().getMessage());
                } else {
                    LOGGER.error(m.getMessage());
                }
            });
            LogManager.shutdown();
            System.exit(1);
        }
    } catch (Throwable ex) {
        LOGGER.debug("Fatal error on initialization", ex);
        Throwable rootCause = Throwables.getRootCause(ex);
        String causeMessage = rootCause.getMessage();
        LogManager.shutdown();
        JCommander.getConsole().println("Fatal error while ToroDB was starting: " + causeMessage);
        System.exit(1);
    }
}
Also used : UncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) Config(com.torodb.stampede.config.model.Config) AbstractPostgres(com.torodb.packaging.config.model.backend.postgres.AbstractPostgres) BackendImplementationVisitor(com.torodb.packaging.config.visitor.BackendImplementationVisitor) DefaultBuildProperties(com.torodb.packaging.DefaultBuildProperties) ConfigUtils(com.torodb.packaging.config.util.ConfigUtils) ResourceBundle(java.util.ResourceBundle) AbstractReplication(com.torodb.packaging.config.model.protocol.mongo.AbstractReplication) JsonNode(com.fasterxml.jackson.databind.JsonNode) MongoPasswordConfig(com.torodb.packaging.config.model.protocol.mongo.MongoPasswordConfig) Charsets(com.google.common.base.Charsets) BackendPasswordConfig(com.torodb.packaging.config.model.backend.BackendPasswordConfig) JCommander(com.beust.jcommander.JCommander) Throwables(com.google.common.base.Throwables) PropertyResourceBundle(java.util.PropertyResourceBundle) IOException(java.io.IOException) Console(com.beust.jcommander.internal.Console) HostAndPort(com.google.common.net.HostAndPort) Service(com.google.common.util.concurrent.Service) SystemException(com.torodb.core.exceptions.SystemException) CreationException(com.google.inject.CreationException) Logger(org.apache.logging.log4j.Logger) BuildProperties(com.torodb.core.BuildProperties) AbstractDerby(com.torodb.packaging.config.model.backend.derby.AbstractDerby) Clock(java.time.Clock) Log4jUtils(com.torodb.packaging.util.Log4jUtils) LogManager(org.apache.logging.log4j.LogManager) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) InputStream(java.io.InputStream) Config(com.torodb.stampede.config.model.Config) MongoPasswordConfig(com.torodb.packaging.config.model.protocol.mongo.MongoPasswordConfig) BackendPasswordConfig(com.torodb.packaging.config.model.backend.BackendPasswordConfig) BackendImplementationVisitor(com.torodb.packaging.config.visitor.BackendImplementationVisitor) MongoPasswordConfig(com.torodb.packaging.config.model.protocol.mongo.MongoPasswordConfig) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) DefaultBuildProperties(com.torodb.packaging.DefaultBuildProperties) JsonNode(com.fasterxml.jackson.databind.JsonNode) Clock(java.time.Clock) HostAndPort(com.google.common.net.HostAndPort) SystemException(com.torodb.core.exceptions.SystemException) JCommander(com.beust.jcommander.JCommander) Console(com.beust.jcommander.internal.Console) UncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) Service(com.google.common.util.concurrent.Service) CreationException(com.google.inject.CreationException) AbstractReplication(com.torodb.packaging.config.model.protocol.mongo.AbstractReplication) AbstractPostgres(com.torodb.packaging.config.model.backend.postgres.AbstractPostgres) IOException(java.io.IOException) SystemException(com.torodb.core.exceptions.SystemException) CreationException(com.google.inject.CreationException) DefaultBuildProperties(com.torodb.packaging.DefaultBuildProperties) BuildProperties(com.torodb.core.BuildProperties) ResourceBundle(java.util.ResourceBundle) PropertyResourceBundle(java.util.PropertyResourceBundle) AbstractDerby(com.torodb.packaging.config.model.backend.derby.AbstractDerby) BackendPasswordConfig(com.torodb.packaging.config.model.backend.BackendPasswordConfig)

Example 4 with SystemException

use of com.torodb.core.exceptions.SystemException in project torodb by torodb.

the class Log4jUtils method reconfigure.

public static void reconfigure(String configurationFile) {
    try {
        LoggerContext coreContext = (LoggerContext) LogManager.getContext(false);
        coreContext.setConfigLocation(new File(configurationFile).toURI());
    } catch (Exception ex) {
        throw new SystemException(ex);
    }
}
Also used : SystemException(com.torodb.core.exceptions.SystemException) LoggerContext(org.apache.logging.log4j.core.LoggerContext) File(java.io.File) SystemException(com.torodb.core.exceptions.SystemException)

Example 5 with SystemException

use of com.torodb.core.exceptions.SystemException in project torodb by torodb.

the class MongoClientConfigurationFactory method getMongoAuthenticationConfiguration.

private static MongoAuthenticationConfiguration getMongoAuthenticationConfiguration(Auth auth, Ssl ssl) {
    AuthMode authMode = auth.getMode();
    MongoAuthenticationConfiguration.Builder mongoAuthenticationConfigurationBuilder = new MongoAuthenticationConfiguration.Builder(mongoAuthenticationMechanismConverter.get(authMode).apply(authMode));
    mongoAuthenticationConfigurationBuilder.setUser(auth.getUser());
    mongoAuthenticationConfigurationBuilder.setSource(auth.getSource());
    mongoAuthenticationConfigurationBuilder.setPassword(auth.getPassword());
    if (authMode == AuthMode.x509 && auth.getUser() == null) {
        try {
            KeyStore ks = getKeyStore(ssl);
            X509Certificate certificate = (X509Certificate) ks.getCertificate(ks.aliases().nextElement());
            mongoAuthenticationConfigurationBuilder.setUser(Arrays.asList(certificate.getSubjectDN().getName().split(",")).stream().map(dn -> dn.trim()).collect(Collectors.joining(",")));
        } catch (CertificateException | KeyStoreException | NoSuchAlgorithmException | IOException exception) {
            throw new SystemException(exception);
        }
    }
    return mongoAuthenticationConfigurationBuilder.build();
}
Also used : MongoAuthenticationConfiguration(com.eightkdata.mongowp.client.wrapper.MongoAuthenticationConfiguration) SystemException(com.torodb.core.exceptions.SystemException) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) KeyStore(java.security.KeyStore) AuthMode(com.torodb.packaging.config.model.protocol.mongo.AuthMode) X509Certificate(java.security.cert.X509Certificate)

Aggregations

SystemException (com.torodb.core.exceptions.SystemException)13 IOException (java.io.IOException)6 SQLException (java.sql.SQLException)4 HostAndPort (com.google.common.net.HostAndPort)3 InputStream (java.io.InputStream)3 Connection (java.sql.Connection)3 ResultSet (java.sql.ResultSet)3 JCommander (com.beust.jcommander.JCommander)2 Console (com.beust.jcommander.internal.Console)2 MongoAuthenticationConfiguration (com.eightkdata.mongowp.client.wrapper.MongoAuthenticationConfiguration)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 Charsets (com.google.common.base.Charsets)2 Throwables (com.google.common.base.Throwables)2 Service (com.google.common.util.concurrent.Service)2 CreationException (com.google.inject.CreationException)2 BackendPasswordConfig (com.torodb.packaging.config.model.backend.BackendPasswordConfig)2 AbstractDerby (com.torodb.packaging.config.model.backend.derby.AbstractDerby)2 AbstractPostgres (com.torodb.packaging.config.model.backend.postgres.AbstractPostgres)2 AbstractReplication (com.torodb.packaging.config.model.protocol.mongo.AbstractReplication)2 MongoPasswordConfig (com.torodb.packaging.config.model.protocol.mongo.MongoPasswordConfig)2