Search in sources :

Example 16 with ConsoleCommand

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

the class OConsoleDatabaseApp method infoClass.

@ConsoleCommand(aliases = { "desc" }, description = "Display a class in the schema", onlineHelp = "Console-Command-Info-Class")
public void infoClass(@ConsoleParameter(name = "class-name", description = "The name of the class") final String iClassName) {
    checkForDatabase();
    final OClass cls = currentDatabase.getMetadata().getImmutableSchemaSnapshot().getClass(iClassName);
    if (cls == null) {
        message("\n! Class '" + iClassName + "' does not exist in the database '" + currentDatabaseName + "'");
        return;
    }
    message("\nCLASS '" + cls.getName() + "'\n");
    final long count = currentDatabase.countClass(cls.getName(), false);
    message("\nRecords..............: " + count);
    if (cls.getShortName() != null)
        message("\nAlias................: " + cls.getShortName());
    if (cls.hasSuperClasses())
        message("\nSuper classes........: " + Arrays.toString(cls.getSuperClassesNames().toArray()));
    message("\nDefault cluster......: " + currentDatabase.getClusterNameById(cls.getDefaultClusterId()) + " (id=" + cls.getDefaultClusterId() + ")");
    final StringBuilder clusters = new StringBuilder();
    for (int clId : cls.getClusterIds()) {
        if (clusters.length() > 0)
            clusters.append(", ");
        clusters.append(currentDatabase.getClusterNameById(clId));
        clusters.append("(");
        clusters.append(clId);
        clusters.append(")");
    }
    message("\nSupported clusters...: " + clusters.toString());
    message("\nCluster selection....: " + cls.getClusterSelection().getName());
    message("\nOversize.............: " + cls.getClassOverSize());
    if (!cls.getSubclasses().isEmpty()) {
        message("\nSubclasses.........: ");
        int i = 0;
        for (OClass c : cls.getSubclasses()) {
            if (i > 0)
                message(", ");
            message(c.getName());
            ++i;
        }
        out.println();
    }
    if (cls.properties().size() > 0) {
        message("\n\nPROPERTIES");
        final List<ODocument> resultSet = new ArrayList<ODocument>();
        for (final OProperty p : cls.properties()) {
            try {
                final ODocument row = new ODocument();
                resultSet.add(row);
                row.field("NAME", p.getName());
                row.field("TYPE", (Object) p.getType());
                row.field("LINKED-TYPE/CLASS", p.getLinkedClass() != null ? p.getLinkedClass() : p.getLinkedType());
                row.field("MANDATORY", p.isMandatory());
                row.field("READONLY", p.isReadonly());
                row.field("NOT-NULL", p.isNotNull());
                row.field("MIN", p.getMin() != null ? p.getMin() : "");
                row.field("MAX", p.getMax() != null ? p.getMax() : "");
                row.field("COLLATE", p.getCollate() != null ? p.getCollate().getName() : "");
                row.field("DEFAULT", p.getDefaultValue() != null ? p.getDefaultValue() : "");
            } catch (Exception ignored) {
            }
        }
        final OTableFormatter formatter = new OTableFormatter(this);
        formatter.writeRecords(resultSet, -1);
    }
    final Set<OIndex<?>> indexes = cls.getClassIndexes();
    if (!indexes.isEmpty()) {
        message("\n\nINDEXES (" + indexes.size() + " altogether)");
        final List<ODocument> resultSet = new ArrayList<ODocument>();
        for (final OIndex<?> index : indexes) {
            final ODocument row = new ODocument();
            resultSet.add(row);
            row.field("NAME", index.getName());
            final OIndexDefinition indexDefinition = index.getDefinition();
            if (indexDefinition != null) {
                final List<String> fields = indexDefinition.getFields();
                row.field("PROPERTIES", fields);
            }
        }
        final OTableFormatter formatter = new OTableFormatter(this);
        formatter.writeRecords(resultSet, -1);
    }
    if (cls.getCustomKeys().size() > 0) {
        message("\n\nCUSTOM ATTRIBUTES");
        final List<ODocument> resultSet = new ArrayList<ODocument>();
        for (final String k : cls.getCustomKeys()) {
            try {
                final ODocument row = new ODocument();
                resultSet.add(row);
                row.field("NAME", k);
                row.field("VALUE", cls.getCustom(k));
            } catch (Exception ignored) {
            // IGNORED
            }
        }
        final OTableFormatter formatter = new OTableFormatter(this);
        formatter.writeRecords(resultSet, -1);
    }
}
Also used : OProperty(com.orientechnologies.orient.core.metadata.schema.OProperty) OIndexDefinition(com.orientechnologies.orient.core.index.OIndexDefinition) OIndex(com.orientechnologies.orient.core.index.OIndex) OSystemException(com.orientechnologies.common.exception.OSystemException) OConfigurationException(com.orientechnologies.orient.core.exception.OConfigurationException) ORetryQueryException(com.orientechnologies.orient.core.exception.ORetryQueryException) OIOException(com.orientechnologies.common.io.OIOException) ODatabaseException(com.orientechnologies.orient.core.exception.ODatabaseException) OClass(com.orientechnologies.orient.core.metadata.schema.OClass) ODocument(com.orientechnologies.orient.core.record.impl.ODocument) ConsoleCommand(com.orientechnologies.common.console.annotation.ConsoleCommand)

Example 17 with ConsoleCommand

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

the class OGremlinConsole method exportDatabase.

@Override
@ConsoleCommand(description = "Export a database", splitInWords = false, onlineHelp = "Console-Command-Export")
public void exportDatabase(@ConsoleParameter(name = "options", description = "Export options") String iText) throws IOException {
    checkForDatabase();
    final List<String> items = OStringSerializerHelper.smartSplit(iText, ' ');
    final String fileName = items.size() <= 1 || items.get(1).charAt(0) == '-' ? null : items.get(1);
    if (fileName != null && (fileName.endsWith(".graphml") || fileName.endsWith(".xml"))) {
        message("\nExporting database in GRAPHML format to " + iText + "...");
        try {
            final OrientGraph g = (OrientGraph) OrientGraphFactory.getTxGraphImplFactory().getGraph(currentDatabase);
            g.setUseLog(false);
            g.setWarnOnForceClosingTx(false);
            // CREATE THE EXPORT FILE IF NOT EXIST YET
            final File f = new File(fileName);
            if (f.getParentFile() != null) {
                f.getParentFile().mkdirs();
            }
            f.createNewFile();
            new GraphMLWriter(g).outputGraph(fileName);
        } catch (ODatabaseImportException e) {
            printError(e);
        }
    } else
        // BASE EXPORT
        super.exportDatabase(iText);
}
Also used : OrientGraph(com.tinkerpop.blueprints.impls.orient.OrientGraph) GraphMLWriter(com.tinkerpop.blueprints.util.io.graphml.GraphMLWriter) ODatabaseImportException(com.orientechnologies.orient.core.db.tool.ODatabaseImportException) File(java.io.File) ConsoleCommand(com.orientechnologies.common.console.annotation.ConsoleCommand)

Example 18 with ConsoleCommand

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

the class OConsoleApplication method execute.

protected RESULT execute(String iCommand) {
    iCommand = iCommand.trim();
    if (iCommand.length() == 0)
        // NULL LINE: JUMP IT
        return RESULT.OK;
    if (isComment(iCommand))
        // COMMENT: JUMP IT
        return RESULT.OK;
    String[] commandWords = OStringParser.getWords(iCommand, wordSeparator);
    for (String cmd : helpCommands) if (cmd.equals(commandWords[0])) {
        if (iCommand.length() > cmd.length())
            help(iCommand.substring(cmd.length() + 1));
        else
            help(null);
        return RESULT.OK;
    }
    for (String cmd : exitCommands) if (cmd.equalsIgnoreCase(commandWords[0])) {
        return RESULT.EXIT;
    }
    Method lastMethodInvoked = null;
    final StringBuilder lastCommandInvoked = new StringBuilder(1024);
    String commandLowerCase = "";
    for (int i = 0; i < commandWords.length; i++) {
        if (i > 0) {
            commandLowerCase += " ";
        }
        commandLowerCase += commandWords[i].toLowerCase();
    }
    for (Entry<Method, Object> entry : getConsoleMethods().entrySet()) {
        final Method m = entry.getKey();
        final String methodName = m.getName();
        final ConsoleCommand ann = m.getAnnotation(ConsoleCommand.class);
        final StringBuilder commandName = new StringBuilder();
        char ch;
        int commandWordCount = 1;
        for (int i = 0; i < methodName.length(); ++i) {
            ch = methodName.charAt(i);
            if (Character.isUpperCase(ch)) {
                commandName.append(" ");
                ch = Character.toLowerCase(ch);
                commandWordCount++;
            }
            commandName.append(ch);
        }
        if (!commandLowerCase.equals(commandName.toString()) && !commandLowerCase.startsWith(commandName.toString() + " ")) {
            if (ann == null)
                continue;
            String[] aliases = ann.aliases();
            if (aliases == null || aliases.length == 0)
                continue;
            boolean aliasMatch = false;
            for (String alias : aliases) {
                if (iCommand.startsWith(alias.split(" ")[0])) {
                    aliasMatch = true;
                    commandWordCount = 1;
                    break;
                }
            }
            if (!aliasMatch)
                continue;
        }
        Object[] methodArgs;
        // BUILD PARAMETERS
        if (ann != null && !ann.splitInWords()) {
            methodArgs = new String[] { iCommand.substring(iCommand.indexOf(' ') + 1) };
        } else {
            final int actualParamCount = commandWords.length - commandWordCount;
            if (m.getParameterTypes().length > actualParamCount) {
                // METHOD PARAMS AND USED PARAMS MISMATCH: CHECK FOR OPTIONALS
                for (int paramNum = m.getParameterAnnotations().length - 1; paramNum > actualParamCount - 1; paramNum--) {
                    final Annotation[] paramAnn = m.getParameterAnnotations()[paramNum];
                    if (paramAnn != null)
                        for (int annNum = paramAnn.length - 1; annNum > -1; annNum--) {
                            if (paramAnn[annNum] instanceof ConsoleParameter) {
                                final ConsoleParameter annotation = (ConsoleParameter) paramAnn[annNum];
                                if (annotation.optional())
                                    commandWords = OArrays.copyOf(commandWords, commandWords.length + 1);
                                break;
                            }
                        }
                }
            }
            methodArgs = OArrays.copyOfRange(commandWords, commandWordCount, commandWords.length);
        }
        try {
            m.invoke(entry.getValue(), methodArgs);
        } catch (IllegalArgumentException e) {
            lastMethodInvoked = m;
            // GET THE COMMAND NAME
            lastCommandInvoked.setLength(0);
            for (int i = 0; i < commandWordCount; ++i) {
                if (lastCommandInvoked.length() > 0)
                    lastCommandInvoked.append(" ");
                lastCommandInvoked.append(commandWords[i]);
            }
            continue;
        } catch (Exception e) {
            if (e.getCause() != null)
                onException(e.getCause());
            else
                e.printStackTrace(err);
            return RESULT.ERROR;
        }
        return RESULT.OK;
    }
    if (lastMethodInvoked != null)
        syntaxError(lastCommandInvoked.toString(), lastMethodInvoked);
    error("\n!Unrecognized command: '%s'", iCommand);
    return RESULT.ERROR;
}
Also used : Method(java.lang.reflect.Method) ConsoleCommand(com.orientechnologies.common.console.annotation.ConsoleCommand) Annotation(java.lang.annotation.Annotation) ConsoleParameter(com.orientechnologies.common.console.annotation.ConsoleParameter)

Example 19 with ConsoleCommand

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

the class OConsoleApplication method getConsoleMethods.

/**
   * Returns a map of all console method and the object they can be called on.
   *
   * @return Map&lt;Method,Object&gt;
   */
protected Map<Method, Object> getConsoleMethods() {
    if (methods != null)
        return methods;
    // search for declared command collections
    final Iterator<OConsoleCommandCollection> ite = ServiceLoader.load(OConsoleCommandCollection.class).iterator();
    final Collection<Object> candidates = new ArrayList<Object>();
    candidates.add(this);
    while (ite.hasNext()) {
        try {
            // make a copy and set it's context
            final OConsoleCommandCollection cc = ite.next().getClass().newInstance();
            cc.setContext(this);
            candidates.add(cc);
        } catch (InstantiationException ex) {
            Logger.getLogger(OConsoleApplication.class.getName()).log(Level.WARNING, ex.getMessage());
        } catch (IllegalAccessException ex) {
            Logger.getLogger(OConsoleApplication.class.getName()).log(Level.WARNING, ex.getMessage());
        }
    }
    methods = new TreeMap<Method, Object>(new Comparator<Method>() {

        public int compare(Method o1, Method o2) {
            final ConsoleCommand ann1 = o1.getAnnotation(ConsoleCommand.class);
            final ConsoleCommand ann2 = o2.getAnnotation(ConsoleCommand.class);
            if (ann1 != null && ann2 != null) {
                if (ann1.priority() != ann2.priority())
                    // PRIORITY WINS
                    return ann1.priority() - ann2.priority();
            }
            int res = o1.getName().compareTo(o2.getName());
            if (res == 0)
                res = o1.toString().compareTo(o2.toString());
            return res;
        }
    });
    for (final Object candidate : candidates) {
        final Method[] classMethods = candidate.getClass().getMethods();
        for (Method m : classMethods) {
            if (Modifier.isAbstract(m.getModifiers()) || Modifier.isStatic(m.getModifiers()) || !Modifier.isPublic(m.getModifiers())) {
                continue;
            }
            if (m.getReturnType() != Void.TYPE) {
                continue;
            }
            methods.put(m, candidate);
        }
    }
    return methods;
}
Also used : Method(java.lang.reflect.Method) ConsoleCommand(com.orientechnologies.common.console.annotation.ConsoleCommand)

Example 20 with ConsoleCommand

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

the class OConsoleApplication method getMethod.

protected Method getMethod(String iCommand) {
    iCommand = iCommand.trim();
    if (iCommand.length() == 0)
        // NULL LINE: JUMP IT
        return null;
    if (isComment(iCommand))
        // COMMENT: JUMP IT
        return null;
    Method lastMethodInvoked = null;
    final StringBuilder lastCommandInvoked = new StringBuilder(1024);
    final String commandLowerCase = iCommand.toLowerCase();
    final Map<Method, Object> methodMap = getConsoleMethods();
    final StringBuilder commandSignature = new StringBuilder();
    boolean separator = false;
    for (int i = 0; i < iCommand.length(); ++i) {
        final char ch = iCommand.charAt(i);
        if (ch == ' ')
            separator = true;
        else {
            if (separator) {
                separator = false;
                commandSignature.append(Character.toUpperCase(ch));
            } else
                commandSignature.append(ch);
        }
    }
    final String commandSignatureToCheck = commandSignature.toString();
    for (Entry<Method, Object> entry : methodMap.entrySet()) {
        final Method m = entry.getKey();
        if (m.getName().equals(commandSignatureToCheck))
            // FOUND EXACT MATCH
            return m;
    }
    for (Entry<Method, Object> entry : methodMap.entrySet()) {
        final Method m = entry.getKey();
        final String methodName = m.getName();
        final ConsoleCommand ann = m.getAnnotation(ConsoleCommand.class);
        final StringBuilder commandName = new StringBuilder();
        char ch;
        for (int i = 0; i < methodName.length(); ++i) {
            ch = methodName.charAt(i);
            if (Character.isUpperCase(ch)) {
                commandName.append(" ");
                ch = Character.toLowerCase(ch);
            }
            commandName.append(ch);
        }
        if (!commandLowerCase.equals(commandName.toString()) && !commandLowerCase.startsWith(commandName.toString() + " ")) {
            if (ann == null)
                continue;
            String[] aliases = ann.aliases();
            if (aliases == null || aliases.length == 0)
                continue;
            for (String alias : aliases) {
                if (iCommand.startsWith(alias.split(" ")[0])) {
                    return m;
                }
            }
        } else
            return m;
    }
    if (lastMethodInvoked != null)
        syntaxError(lastCommandInvoked.toString(), lastMethodInvoked);
    error("\n!Unrecognized command: '%s'", iCommand);
    return null;
}
Also used : Method(java.lang.reflect.Method) 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