Search in sources :

Example 21 with ConsoleCommand

use of com.orientechnologies.common.console.annotation.ConsoleCommand in project orientdb by orientechnologies.

the class OGremlinConsole method importDatabase.

@Override
@ConsoleCommand(description = "Import a database into the current one", splitInWords = false)
public void importDatabase(@ConsoleParameter(name = "options", description = "Import options") String text) throws IOException {
    checkForDatabase();
    final List<String> items = OStringSerializerHelper.smartSplit(text, ' ');
    final String fileName = items.size() <= 0 || (items.get(1)).charAt(0) == '-' ? null : items.get(1);
    final String optionsAsString = fileName != null ? text.substring((items.get(0)).length() + (items.get(1)).length() + 1).trim() : text;
    final Map<String, List<String>> options = parseOptions(optionsAsString);
    final String format = options.containsKey("-format") ? options.get("-format").get(0) : null;
    if ((format != null && format.equalsIgnoreCase("graphml")) || (fileName != null && (fileName.endsWith(".graphml") || fileName.endsWith(".xml")))) {
        // GRAPHML
        message("\nImporting GRAPHML database from " + fileName + " with options (" + optionsAsString + ")...");
        try {
            final OrientGraph g = (OrientGraph) OrientGraphFactory.getTxGraphImplFactory().getGraph(currentDatabase);
            g.setUseLog(false);
            g.setWarnOnForceClosingTx(false);
            final long totalEdges = g.countEdges();
            final long totalVertices = g.countVertices();
            final File file = new File(fileName);
            if (!file.exists())
                throw new ODatabaseImportException("Input file '" + fileName + "' not exists");
            InputStream is = new FileInputStream(file);
            if (fileName.endsWith(".zip"))
                is = new ZipInputStream(is);
            else if (fileName.endsWith(".gz"))
                is = new GZIPInputStream(is);
            try {
                new OGraphMLReader(g).setOptions(options).setOutput(new OCommandOutputListener() {

                    @Override
                    public void onMessage(final String iText) {
                        System.out.print("\r" + iText);
                    }
                }).inputGraph(is);
                g.commit();
                currentDatabase.commit();
                message("\nDone: imported %d vertices and %d edges", g.countVertices() - totalVertices, g.countEdges() - totalEdges);
            } finally {
                is.close();
            }
        } catch (ODatabaseImportException e) {
            printError(e);
        }
    } else if ((format != null && format.equalsIgnoreCase("graphson")) || (fileName != null && (fileName.endsWith(".graphson")))) {
        // GRAPHSON
        message("\nImporting GRAPHSON database from " + fileName + " with options (" + optionsAsString + ")...");
        try {
            final OrientGraph g = (OrientGraph) OrientGraphFactory.getTxGraphImplFactory().getGraph(currentDatabase);
            g.setUseLog(false);
            g.setWarnOnForceClosingTx(false);
            final long totalEdges = g.countEdges();
            final long totalVertices = g.countVertices();
            final File file = new File(fileName);
            if (!file.exists())
                throw new ODatabaseImportException("Input file '" + fileName + "' not exists");
            InputStream is = new FileInputStream(file);
            if (fileName.endsWith(".zip")) {
                is = new ZipInputStream(is);
            } else if (fileName.endsWith(".gz")) {
                is = new GZIPInputStream(is);
            }
            try {
                new OGraphSONReader(g).setOutput(new OCommandOutputListener() {

                    @Override
                    public void onMessage(final String iText) {
                        System.out.print("\r" + iText);
                    }
                }).inputGraph(is, 10000);
                // new OGraphMLReader(g).setOptions(options).inputGraph(g, fileName);
                g.commit();
                currentDatabase.commit();
                message("\nDone: imported %d vertices and %d edges", g.countVertices() - totalVertices, g.countEdges() - totalEdges);
            } finally {
                is.close();
            }
        } catch (ODatabaseImportException e) {
            printError(e);
        }
    } else if (format == null)
        super.importDatabase(text);
    else
        throw new IllegalArgumentException("Format '" + format + "' is not supported");
}
Also used : OrientGraph(com.tinkerpop.blueprints.impls.orient.OrientGraph) GZIPInputStream(java.util.zip.GZIPInputStream) ZipInputStream(java.util.zip.ZipInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ODatabaseImportException(com.orientechnologies.orient.core.db.tool.ODatabaseImportException) FileInputStream(java.io.FileInputStream) GZIPInputStream(java.util.zip.GZIPInputStream) ZipInputStream(java.util.zip.ZipInputStream) OGraphSONReader(com.orientechnologies.orient.graph.graphml.OGraphSONReader) OGraphMLReader(com.orientechnologies.orient.graph.graphml.OGraphMLReader) List(java.util.List) File(java.io.File) OCommandOutputListener(com.orientechnologies.orient.core.command.OCommandOutputListener) ConsoleCommand(com.orientechnologies.common.console.annotation.ConsoleCommand)

Example 22 with ConsoleCommand

use of com.orientechnologies.common.console.annotation.ConsoleCommand in project orientdb by orientechnologies.

the class OGremlinConsole method repairDatabase.

@Override
@ConsoleCommand(description = "Repair database structure", splitInWords = false)
public void repairDatabase(@ConsoleParameter(name = "options", description = "Options: [--fix-graph] [--fix-links] [-v]] [--fix-ridbags] [--fix-bonsai]", optional = true) String iOptions) throws IOException {
    checkForDatabase();
    final boolean fix_graph = iOptions == null || iOptions.contains("--fix-graph");
    if (fix_graph) {
        // REPAIR GRAPH
        final Map<String, List<String>> options = parseOptions(iOptions);
        new OGraphRepair().repair(OrientGraphFactory.getNoTxGraphImplFactory().getGraph(currentDatabase), this, options);
    }
    final boolean fix_links = iOptions == null || iOptions.contains("--fix-links");
    if (fix_links) {
        // REPAIR DATABASE AT LOW LEVEL
        super.repairDatabase(iOptions);
    }
    if (!currentDatabase.getURL().startsWith("plocal")) {
        message("\n fix-bonsai can be run only on plocal connection \n");
        return;
    }
    final boolean fix_ridbags = iOptions == null || iOptions.contains("--fix-ridbags");
    if (fix_ridbags) {
        OBonsaiTreeRepair repairer = new OBonsaiTreeRepair();
        repairer.repairDatabaseRidbags(currentDatabase, this);
    }
    final boolean fix_bonsai = iOptions == null || iOptions.contains("--fix-bonsai");
    if (fix_bonsai) {
        OBonsaiTreeRepair repairer = new OBonsaiTreeRepair();
        repairer.repairDatabaseRidbags(currentDatabase, this);
    }
}
Also used : OGraphRepair(com.tinkerpop.blueprints.impls.orient.OGraphRepair) List(java.util.List) OBonsaiTreeRepair(com.tinkerpop.blueprints.impls.orient.OBonsaiTreeRepair) ConsoleCommand(com.orientechnologies.common.console.annotation.ConsoleCommand)

Example 23 with ConsoleCommand

use of com.orientechnologies.common.console.annotation.ConsoleCommand in project orientdb by orientechnologies.

the class OConsoleDatabaseApp method listConnections.

@ConsoleCommand(description = "List all the active connections to the server", onlineHelp = "Console-Command-List-Connections")
public void listConnections() throws IOException {
    if (serverAdmin != null) {
        final ODocument serverInfo = serverAdmin.getServerInfo();
        final List<OIdentifiable> resultSet = new ArrayList<OIdentifiable>();
        final List<Map<String, Object>> connections = serverInfo.field("connections");
        for (Map<String, Object> conn : connections) {
            final ODocument row = new ODocument();
            String commandDetail = (String) conn.get("commandInfo");
            if (commandDetail != null && ((String) conn.get("commandDetail")).length() > 1)
                commandDetail += " (" + conn.get("commandDetail") + ")";
            row.fields("ID", conn.get("connectionId"), "REMOTE_ADDRESS", conn.get("remoteAddress"), "PROTOC", conn.get("protocol"), "LAST_OPERATION_ON", conn.get("lastCommandOn"), "DATABASE", conn.get("db"), "USER", conn.get("user"), "COMMAND", commandDetail, "TOT_REQS", conn.get("totalRequests"));
            resultSet.add(row);
        }
        Collections.sort(resultSet, new Comparator<OIdentifiable>() {

            @Override
            public int compare(final OIdentifiable o1, final OIdentifiable o2) {
                final String o1s = ((ODocument) o1).field("LAST_OPERATION_ON");
                final String o2s = ((ODocument) o2).field("LAST_OPERATION_ON");
                return o2s.compareTo(o1s);
            }
        });
        final OTableFormatter formatter = new OTableFormatter(this);
        formatter.writeRecords(resultSet, -1);
    } else {
        message("\nNot connected to the Server instance. You've to connect to the Server using server's credentials (look at orientdb-*server-config.xml file)");
    }
    out.println();
}
Also used : OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) ODocument(com.orientechnologies.orient.core.record.impl.ODocument) ConsoleCommand(com.orientechnologies.common.console.annotation.ConsoleCommand)

Example 24 with ConsoleCommand

use of com.orientechnologies.common.console.annotation.ConsoleCommand in project orientdb by orientechnologies.

the class OConsoleDatabaseApp method move.

@ConsoleCommand(splitInWords = false, description = "Move from current record by evaluating a predicate against current record")
public void move(@ConsoleParameter(name = "text", description = "The sql predicate to evaluate") final String iText) {
    if (iText == null)
        return;
    if (currentRecord == null)
        return;
    final Object result = new OSQLPredicate(iText).evaluate(currentRecord, null, null);
    if (result != null) {
        if (result instanceof OIdentifiable) {
            setResultset(new ArrayList<OIdentifiable>());
            currentRecord = ((OIdentifiable) result).getRecord();
            dumpRecordDetails();
        } else if (result instanceof List<?>) {
            setResultset((List<OIdentifiable>) result);
            dumpResultSet(-1);
        } else if (result instanceof Iterator<?>) {
            final List<OIdentifiable> list = new ArrayList<OIdentifiable>();
            while (((Iterator) result).hasNext()) list.add(((Iterator<OIdentifiable>) result).next());
            setResultset(list);
            dumpResultSet(-1);
        } else
            setResultset(new ArrayList<OIdentifiable>());
    }
}
Also used : OSQLPredicate(com.orientechnologies.orient.core.sql.filter.OSQLPredicate) OIdentifiableIterator(com.orientechnologies.orient.core.iterator.OIdentifiableIterator) OIdentifiable(com.orientechnologies.orient.core.db.record.OIdentifiable) ConsoleCommand(com.orientechnologies.common.console.annotation.ConsoleCommand)

Example 25 with ConsoleCommand

use of com.orientechnologies.common.console.annotation.ConsoleCommand in project orientdb by orientechnologies.

the class OConsoleDatabaseApp method createDatabase.

@ConsoleCommand(description = "Create a new database. For encrypted database or portion of database, set the variable 'storage.encryptionKey' with the key to use", onlineHelp = "Console-Command-Create-Database")
public void createDatabase(@ConsoleParameter(name = "database-url", description = "The url of the database to create in the format '<mode>:<path>'") String databaseURL, @ConsoleParameter(name = "user", optional = true, description = "Server administrator name") String userName, @ConsoleParameter(name = "password", optional = true, description = "Server administrator password") String userPassword, @ConsoleParameter(name = "storage-type", optional = true, description = "The type of the storage: 'plocal' for disk-based databases and 'memory' for in-memory database") String storageType, @ConsoleParameter(name = "db-type", optional = true, description = "The type of the database used between 'document' and 'graph'. By default is graph.") String databaseType, @ConsoleParameter(name = "[options]", optional = true, description = "Additional options, example: -encryption=aes -compression=snappy") final String options) throws IOException {
    if (userName == null)
        userName = OUser.ADMIN;
    if (userPassword == null)
        userPassword = OUser.ADMIN;
    if (storageType == null) {
        if (databaseURL.startsWith(OEngineRemote.NAME + ":"))
            throw new IllegalArgumentException("Missing storage type for remote database");
        int pos = databaseURL.indexOf(":");
        if (pos == -1)
            throw new IllegalArgumentException("Invalid URL");
        storageType = databaseURL.substring(0, pos);
    }
    if (databaseType == null)
        databaseType = "graph";
    message("\nCreating database [" + databaseURL + "] using the storage type [" + storageType + "]...");
    currentDatabaseUserName = userName;
    currentDatabaseUserPassword = userPassword;
    final Map<String, String> omap = parseCommandOptions(options);
    final String backupPath = omap.remove("-restore");
    if (databaseURL.startsWith(OEngineRemote.NAME)) {
        // REMOTE CONNECTION
        final String dbURL = databaseURL.substring(OEngineRemote.NAME.length() + 1);
        OServerAdmin serverAdmin = new OServerAdmin(dbURL).connect(userName, userPassword);
        serverAdmin.createDatabase(serverAdmin.getStorageName(), databaseType, storageType, backupPath).close();
        connect(databaseURL, userName, userPassword);
    } else {
        // LOCAL CONNECTION
        if (storageType != null) {
            // CHECK STORAGE TYPE
            if (!databaseURL.toLowerCase().startsWith(storageType.toLowerCase()))
                throw new IllegalArgumentException("Storage type '" + storageType + "' is different by storage type in URL");
        }
        currentDatabase = new ODatabaseDocumentTx(databaseURL);
        for (Map.Entry<String, String> oentry : omap.entrySet()) {
            if ("-encryption".equalsIgnoreCase(oentry.getKey()))
                currentDatabase.setProperty(OGlobalConfiguration.STORAGE_ENCRYPTION_METHOD.getKey(), oentry.getValue());
            else if ("-compression".equalsIgnoreCase(oentry.getKey()))
                currentDatabase.setProperty(OGlobalConfiguration.STORAGE_COMPRESSION_METHOD.getKey(), oentry.getValue());
            else
                currentDatabase.setProperty(oentry.getKey(), oentry.getValue());
        }
        if (backupPath == null)
            currentDatabase.create();
        else
            currentDatabase.create(backupPath);
        currentDatabaseName = currentDatabase.getName();
    }
    message("\nDatabase created successfully.");
    message("\n\nCurrent database is: " + databaseURL);
}
Also used : ODatabaseDocumentTx(com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx) OServerAdmin(com.orientechnologies.orient.client.remote.OServerAdmin) ConsoleCommand(com.orientechnologies.common.console.annotation.ConsoleCommand)

Aggregations

ConsoleCommand (com.orientechnologies.common.console.annotation.ConsoleCommand)36 ODocument (com.orientechnologies.orient.core.record.impl.ODocument)12 OSystemException (com.orientechnologies.common.exception.OSystemException)10 ORetryQueryException (com.orientechnologies.orient.core.exception.ORetryQueryException)9 OIOException (com.orientechnologies.common.io.OIOException)8 OConfigurationException (com.orientechnologies.orient.core.exception.OConfigurationException)8 ODatabaseException (com.orientechnologies.orient.core.exception.ODatabaseException)8 OIdentifiable (com.orientechnologies.orient.core.db.record.OIdentifiable)4 OClass (com.orientechnologies.orient.core.metadata.schema.OClass)4 Method (java.lang.reflect.Method)4 OServerAdmin (com.orientechnologies.orient.client.remote.OServerAdmin)3 OGlobalConfiguration (com.orientechnologies.orient.core.config.OGlobalConfiguration)3 ODatabaseDocumentTx (com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx)3 OIndex (com.orientechnologies.orient.core.index.OIndex)3 OIndexDefinition (com.orientechnologies.orient.core.index.OIndexDefinition)3 OStorage (com.orientechnologies.orient.core.storage.OStorage)3 OServerConfigurationManager (com.orientechnologies.orient.server.config.OServerConfigurationManager)3 OCommandOutputListener (com.orientechnologies.orient.core.command.OCommandOutputListener)2 ODatabaseImportException (com.orientechnologies.orient.core.db.tool.ODatabaseImportException)2 OProperty (com.orientechnologies.orient.core.metadata.schema.OProperty)2