Search in sources :

Example 1 with DatabaseImpl

use of org.exist.xmldb.DatabaseImpl in project exist by eXist-db.

the class JettyStart method run.

public synchronized void run(final String[] args, final Observer observer) {
    if (args.length == 0) {
        logger.error("No configuration file specified!");
        return;
    }
    Path jettyConfig = Paths.get(args[0]).normalize();
    boolean configFromClasspath = false;
    if (Files.notExists(jettyConfig)) {
        logger.warn("Configuration file: {} does not exist!", jettyConfig.toAbsolutePath().toString());
        final String jettyConfigFileName = FileUtils.fileName(jettyConfig.getFileName());
        logger.warn("Fallback... searching for configuration file on classpath: {}!etc/{}", getClass().getPackage().getName(), jettyConfigFileName);
        final URL jettyConfigUrl = getClass().getResource("etc/" + jettyConfigFileName);
        if (jettyConfigUrl != null) {
            try {
                jettyConfig = Paths.get(jettyConfigUrl.toURI()).normalize();
                configFromClasspath = true;
            } catch (final URISyntaxException e) {
                logger.error("Unable to retrieve configuration file from classpath: {}", e.getMessage(), e);
                return;
            }
        } else {
            logger.error("Unable to find configuration file on classpath!");
            return;
        }
    }
    final Map<String, String> configProperties;
    try {
        configProperties = getConfigProperties(jettyConfig.getParent());
        // modify JETTY_HOME and JETTY_BASE properties when running with classpath config
        if (configFromClasspath) {
            final String jettyClasspathHome = jettyConfig.getParent().getParent().toAbsolutePath().toString();
            System.setProperty(JETTY_HOME_PROP, jettyClasspathHome);
            configProperties.put(JETTY_HOME_PROP, jettyClasspathHome);
            configProperties.put(JETTY_BASE_PROP, jettyClasspathHome);
        }
        if (observer != null) {
            addObserver(observer);
        }
        logger.info("Running with Java {} [{} ({}) in {}]", System.getProperty("java.version", "(unknown java.version)"), System.getProperty("java.vendor", "(unknown java.vendor)"), System.getProperty("java.vm.name", "(unknown java.vm.name)"), System.getProperty("java.home", "(unknown java.home)"));
        logger.info("Approximate maximum amount of memory for JVM: {}", FileUtils.humanSize(Runtime.getRuntime().maxMemory()));
        logger.info("Number of processors available to JVM: {}", Runtime.getRuntime().availableProcessors());
        logger.info("Running as user '{}'", System.getProperty("user.name", "(unknown user.name)"));
        logger.info("[eXist Home : {}]", System.getProperty("exist.home", "unknown"));
        logger.info("[eXist Version : {}]", SystemProperties.getInstance().getSystemProperty("product-version", "unknown"));
        logger.info("[eXist Build : {}]", SystemProperties.getInstance().getSystemProperty("product-build", "unknown"));
        logger.info("[Git commit : {}]", SystemProperties.getInstance().getSystemProperty("git-commit", "unknown"));
        logger.info("[Operating System : {} {} {}]", System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch"));
        logger.info("[log4j.configurationFile : {}]", System.getProperty("log4j.configurationFile"));
        logger.info("[jetty Version: {}]", Jetty.VERSION);
        logger.info("[{} : {}]", JETTY_HOME_PROP, configProperties.get(JETTY_HOME_PROP));
        logger.info("[{} : {}]", JETTY_BASE_PROP, configProperties.get(JETTY_BASE_PROP));
        logger.info("[jetty configuration : {}]", jettyConfig.toAbsolutePath().toString());
        // configure the database instance
        SingleInstanceConfiguration config;
        if (args.length == 2) {
            config = new SingleInstanceConfiguration(args[1]);
        } else {
            config = new SingleInstanceConfiguration();
        }
        logger.info("Configuring eXist from {}", config.getConfigFilePath().map(Path::normalize).map(Path::toAbsolutePath).map(Path::toString).orElse("<UNKNOWN>"));
        BrokerPool.configure(1, 5, config, Optional.ofNullable(observer));
        // register the XMLDB driver
        final Database xmldb = new DatabaseImpl();
        xmldb.setProperty("create-database", "false");
        DatabaseManager.registerDatabase(xmldb);
    } catch (final Exception e) {
        logger.error("configuration error: {}", e.getMessage(), e);
        e.printStackTrace();
        return;
    }
    try {
        // load jetty configurations
        final List<Path> configFiles = getEnabledConfigFiles(jettyConfig);
        final List<Object> configuredObjects = new ArrayList<>();
        XmlConfiguration last = null;
        for (final Path confFile : configFiles) {
            logger.info("[loading jetty configuration : {}]", confFile.toString());
            try (final InputStream is = Files.newInputStream(confFile)) {
                final XmlConfiguration configuration = new XmlConfiguration(is);
                if (last != null) {
                    configuration.getIdMap().putAll(last.getIdMap());
                }
                configuration.getProperties().putAll(configProperties);
                configuredObjects.add(configuration.configure());
                last = configuration;
            }
        }
        // start Jetty
        final Optional<Server> maybeServer = startJetty(configuredObjects);
        if (!maybeServer.isPresent()) {
            logger.error("Unable to find a server to start in jetty configurations");
            throw new IllegalStateException();
        }
        final Server server = maybeServer.get();
        final Connector[] connectors = server.getConnectors();
        // Construct description of all ports opened.
        final StringBuilder allPorts = new StringBuilder();
        if (connectors.length > 1) {
            // plural s
            allPorts.append("s");
        }
        boolean establishedPrimaryPort = false;
        for (final Connector connector : connectors) {
            if (connector instanceof NetworkConnector) {
                final NetworkConnector networkConnector = (NetworkConnector) connector;
                if (!establishedPrimaryPort) {
                    this.primaryPort = networkConnector.getLocalPort();
                    establishedPrimaryPort = true;
                }
                allPorts.append(" ");
                allPorts.append(networkConnector.getLocalPort());
            }
        }
        // *************************************************************
        final List<URI> serverUris = getSeverURIs(server);
        if (!serverUris.isEmpty()) {
            this.primaryPort = serverUris.get(0).getPort();
        }
        logger.info("-----------------------------------------------------");
        logger.info("Server has started, listening on:");
        for (final URI serverUri : serverUris) {
            logger.info("{}", serverUri.resolve("/"));
        }
        logger.info("Configured contexts:");
        final LinkedHashSet<Handler> handlers = getAllHandlers(server.getHandler());
        for (final Handler handler : handlers) {
            if (handler instanceof ContextHandler) {
                final ContextHandler contextHandler = (ContextHandler) handler;
                logger.info("{} ({})", contextHandler.getContextPath(), contextHandler.getDisplayName());
            }
            if (handler instanceof ServletContextHandler) {
                final ServletContextHandler contextHandler = (ServletContextHandler) handler;
                final ServiceLoader<ExistExtensionServlet> services = ServiceLoader.load(ExistExtensionServlet.class);
                for (ExistExtensionServlet existExtensionServlet : services) {
                    final String pathSpec = existExtensionServlet.getPathSpec();
                    final String contextPath = contextHandler.getContextPath();
                    // Avoid "//" as logged prefix
                    final String normalizedPath = "/".equals(contextPath) ? pathSpec : contextPath + pathSpec;
                    logger.info("{} ({})", normalizedPath, existExtensionServlet.getServletInfo());
                    // Register servlet
                    contextHandler.addServlet(new ServletHolder(existExtensionServlet), pathSpec);
                }
            }
        }
        logger.info("-----------------------------------------------------");
        setChanged();
        notifyObservers(SIGNAL_STARTED);
    } catch (final MultiException e) {
        // Mute the BindExceptions
        boolean hasBindException = false;
        for (final Throwable t : e.getThrowables()) {
            if (t instanceof java.net.BindException) {
                hasBindException = true;
                logger.error("----------------------------------------------------------");
                logger.error("ERROR: Could not bind to port because {}", t.getMessage());
                logger.error(t.toString());
                logger.error("----------------------------------------------------------");
            }
        }
        // If it is another error, print stacktrace
        if (!hasBindException) {
            e.printStackTrace();
        }
        setChanged();
        notifyObservers(SIGNAL_ERROR);
    } catch (final SocketException e) {
        logger.error("----------------------------------------------------------");
        logger.error("ERROR: Could not bind to port because {}", e.getMessage());
        logger.error(e.toString());
        logger.error("----------------------------------------------------------");
        setChanged();
        notifyObservers(SIGNAL_ERROR);
    } catch (final Exception e) {
        e.printStackTrace();
        setChanged();
        notifyObservers(SIGNAL_ERROR);
    }
}
Also used : ServletHolder(org.eclipse.jetty.servlet.ServletHolder) XmlConfiguration(org.eclipse.jetty.xml.XmlConfiguration) ExistExtensionServlet(org.exist.http.servlets.ExistExtensionServlet) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) Database(org.xmldb.api.base.Database) SingleInstanceConfiguration(org.exist.util.SingleInstanceConfiguration) java.net(java.net) Path(java.nio.file.Path) InputStream(java.io.InputStream) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) StartException(org.exist.start.StartException) MultiException(org.eclipse.jetty.util.MultiException) IOException(java.io.IOException) DatabaseImpl(org.exist.xmldb.DatabaseImpl) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) MultiException(org.eclipse.jetty.util.MultiException)

Example 2 with DatabaseImpl

use of org.exist.xmldb.DatabaseImpl in project exist by eXist-db.

the class UpdateRecoverTest method startDb.

private BrokerPool startDb() throws EXistException, IOException, DatabaseConfigurationException, XMLDBException {
    existEmbeddedServer.startDb();
    final Database database = new DatabaseImpl();
    database.setProperty("create-database", "true");
    DatabaseManager.registerDatabase(database);
    return existEmbeddedServer.getBrokerPool();
}
Also used : DatabaseImpl(org.exist.xmldb.DatabaseImpl) Database(org.xmldb.api.base.Database)

Example 3 with DatabaseImpl

use of org.exist.xmldb.DatabaseImpl in project exist by eXist-db.

the class MoveResourceRecoveryTest method storeAndReadXmldb.

@Test
public void storeAndReadXmldb() throws XMLDBException, DatabaseConfigurationException, IOException, EXistException, URISyntaxException {
    // initialize xml:db driver
    final Database database = new DatabaseImpl();
    database.setProperty("create-database", "true");
    DatabaseManager.registerDatabase(database);
    BrokerPool.FORCE_CORRUPTION = true;
    xmldbStore();
    existEmbeddedServer.restart();
    BrokerPool.FORCE_CORRUPTION = false;
    xmldbRead();
}
Also used : DatabaseImpl(org.exist.xmldb.DatabaseImpl) Database(org.xmldb.api.base.Database)

Example 4 with DatabaseImpl

use of org.exist.xmldb.DatabaseImpl in project exist by eXist-db.

the class MoveCollectionRecoveryTest method storeAndReadXmldb.

@Test
public void storeAndReadXmldb() throws DatabaseConfigurationException, XMLDBException, EXistException, IOException {
    // initialize xml:db driver
    final Database database = new DatabaseImpl();
    database.setProperty("create-database", "true");
    DatabaseManager.registerDatabase(database);
    BrokerPool.FORCE_CORRUPTION = false;
    xmldbStore();
    existEmbeddedServer.restart();
    BrokerPool.FORCE_CORRUPTION = false;
    xmldbRead();
}
Also used : DatabaseImpl(org.exist.xmldb.DatabaseImpl) Database(org.xmldb.api.base.Database) Test(org.junit.Test)

Example 5 with DatabaseImpl

use of org.exist.xmldb.DatabaseImpl in project exist by eXist-db.

the class CDataIntergationTest method cdataXmlDbApi.

@Test
public void cdataXmlDbApi() throws XMLDBException {
    final String docName = "xmldb-cdata-test.xml";
    final Database database = new DatabaseImpl();
    DatabaseManager.registerDatabase(database);
    // store document
    Collection root = DatabaseManager.getCollection(XmldbURI.LOCAL_DB, TestUtils.ADMIN_DB_USER, TestUtils.ADMIN_DB_PWD);
    try {
        final Resource resource = root.createResource(docName, XMLResource.RESOURCE_TYPE);
        resource.setContent(cdata_xml);
        root.storeResource(resource);
    } finally {
        root.close();
    }
    // retrieve document
    root = DatabaseManager.getCollection(XmldbURI.LOCAL_DB, TestUtils.ADMIN_DB_USER, TestUtils.ADMIN_DB_PWD);
    try {
        final Resource resource = root.getResource(docName);
        assertNotNull(resource);
        assertEquals(cdata_xml, resource.getContent().toString());
    } finally {
        root.close();
    }
}
Also used : DatabaseImpl(org.exist.xmldb.DatabaseImpl) Database(org.xmldb.api.base.Database) XMLResource(org.xmldb.api.modules.XMLResource) Resource(org.xmldb.api.base.Resource) Collection(org.xmldb.api.base.Collection) Test(org.junit.Test)

Aggregations

DatabaseImpl (org.exist.xmldb.DatabaseImpl)7 Database (org.xmldb.api.base.Database)6 Test (org.junit.Test)3 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 java.net (java.net)1 Path (java.nio.file.Path)1 ContextHandler (org.eclipse.jetty.server.handler.ContextHandler)1 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)1 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)1 MultiException (org.eclipse.jetty.util.MultiException)1 XmlConfiguration (org.eclipse.jetty.xml.XmlConfiguration)1 ExistExtensionServlet (org.exist.http.servlets.ExistExtensionServlet)1 StartException (org.exist.start.StartException)1 SingleInstanceConfiguration (org.exist.util.SingleInstanceConfiguration)1 BeforeClass (org.junit.BeforeClass)1 Collection (org.xmldb.api.base.Collection)1 Resource (org.xmldb.api.base.Resource)1 XMLResource (org.xmldb.api.modules.XMLResource)1