From f9748246e486ceb5056410d06aaf43355880bd68 Mon Sep 17 00:00:00 2001 From: Tglman Date: Mon, 23 Dec 2024 19:56:16 +0000 Subject: [PATCH] refactor: removed legacy command classes with relative implementations --- .../server/OEnterpriseServerImpl.java | 9 - .../SimpleValueFetchPlanCommandListener.java | 9 - .../remote/message/OCommandRequest.java | 4 +- .../remote/message/OCommandResponse.java | 52 +- .../common/parser/OBaseParser.java | 246 ------- .../common/parser/OStringParser.java | 152 ---- .../common/stream/BreakingForEach.java | 29 - .../common/util/OCollections.java | 32 - .../core/command/OBasicCommandContext.java | 17 - .../orient/core/command/OCommand.java | 36 - .../orient/core/command/OCommandExecutor.java | 97 --- .../command/OCommandExecutorAbstract.java | 194 ------ .../core/command/OCommandPredicate.java | 28 - .../orient/core/command/OCommandRequest.java | 133 ---- .../core/command/OCommandRequestAbstract.java | 169 ----- .../core/command/OCommandRequestAsynch.java | 28 - .../core/command/OCommandRequestInternal.java | 36 - .../core/command/OCommandRequestText.java | 37 - .../command/OCommandRequestTextAbstract.java | 188 ----- .../core/command/OCommandResultListener.java | 40 -- .../command/ODocumentEqualityWrapper.java | 38 - .../core/command/OSqlScriptExecutor.java | 17 +- .../OAbstractScriptExecutor.java | 2 +- .../script/OCommandExecutorFunction.java | 136 ---- .../core/command/script/OCommandFunction.java | 47 -- .../core/command/script/OCommandScript.java | 124 ---- .../command/script/OJsr223ScriptExecutor.java | 1 - .../script/OPolyglotScriptExecutor.java | 1 - .../core/command/script/OScriptManager.java | 35 +- .../orient/core/db/ODatabaseListener.java | 7 - .../orient/core/query/OQueryHelper.java | 57 -- .../orient/core/sql/OChainedIndexProxy.java | 649 ------------------ .../orient/core/sql/OSQLEngine.java | 6 +- .../orient/core/sql/OSQLScriptEngine.java | 167 ----- .../core/sql/OSQLScriptEngineFactory.java | 105 --- .../graph/OSQLFunctionPathFinder.java | 6 +- .../graph/OSQLFunctionShortestPath.java | 6 +- .../orient/core/sql/parser/OLikeOperator.java | 37 +- .../sql/functions/sql/OFunctionSqlTest.java | 6 +- .../gremlin/orientdb/OrientGraph.java | 6 - .../executor/OCommandGremlinExecutor.java | 2 +- .../security/auditing/OAuditingHook.java | 11 - .../server/OClientConnectionManager.java | 71 +- .../server/OConnectionBinaryExecutor.java | 2 +- .../protocol/ONetworkProtocolData.java | 2 - .../OAbstractCommandResultListener.java | 73 -- .../binary/OAsyncCommandResultListener.java | 150 ---- .../binary/OLiveCommandResultListener.java | 256 ------- .../binary/OSyncCommandResultListener.java | 121 ---- .../OLiveCommandResultListenerTest.java | 90 --- .../test/database/auto/DbListenerTest.java | 13 - ...LSelectByLinkedPropertyIndexReuseTest.java | 2 - .../test/database/auto/StringsTest.java | 32 - .../database/auto/TransactionAtomicTest.java | 9 - .../speed/SQLSynchQuerySpeedTest.java | 11 +- 55 files changed, 117 insertions(+), 3717 deletions(-) delete mode 100644 client/src/main/java/com/orientechnologies/orient/client/remote/SimpleValueFetchPlanCommandListener.java delete mode 100644 core/src/main/java/com/orientechnologies/common/parser/OBaseParser.java delete mode 100644 core/src/main/java/com/orientechnologies/common/stream/BreakingForEach.java delete mode 100644 core/src/main/java/com/orientechnologies/orient/core/command/OCommand.java delete mode 100644 core/src/main/java/com/orientechnologies/orient/core/command/OCommandExecutor.java delete mode 100755 core/src/main/java/com/orientechnologies/orient/core/command/OCommandExecutorAbstract.java delete mode 100644 core/src/main/java/com/orientechnologies/orient/core/command/OCommandPredicate.java delete mode 100644 core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequest.java delete mode 100755 core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAbstract.java delete mode 100644 core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAsynch.java delete mode 100644 core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestInternal.java delete mode 100644 core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestText.java delete mode 100755 core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestTextAbstract.java delete mode 100644 core/src/main/java/com/orientechnologies/orient/core/command/OCommandResultListener.java delete mode 100755 core/src/main/java/com/orientechnologies/orient/core/command/ODocumentEqualityWrapper.java rename core/src/main/java/com/orientechnologies/orient/core/command/{traverse => script}/OAbstractScriptExecutor.java (94%) delete mode 100755 core/src/main/java/com/orientechnologies/orient/core/command/script/OCommandExecutorFunction.java delete mode 100644 core/src/main/java/com/orientechnologies/orient/core/command/script/OCommandFunction.java delete mode 100755 core/src/main/java/com/orientechnologies/orient/core/command/script/OCommandScript.java delete mode 100644 core/src/main/java/com/orientechnologies/orient/core/query/OQueryHelper.java delete mode 100755 core/src/main/java/com/orientechnologies/orient/core/sql/OChainedIndexProxy.java delete mode 100644 core/src/main/java/com/orientechnologies/orient/core/sql/OSQLScriptEngine.java delete mode 100755 core/src/main/java/com/orientechnologies/orient/core/sql/OSQLScriptEngineFactory.java delete mode 100644 server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/OAbstractCommandResultListener.java delete mode 100644 server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/OAsyncCommandResultListener.java delete mode 100755 server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/OLiveCommandResultListener.java delete mode 100644 server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/OSyncCommandResultListener.java delete mode 100644 server/src/test/java/com/orientechnologies/orient/server/OLiveCommandResultListenerTest.java diff --git a/agent/src/main/java/com/orientechnologies/enterprise/server/OEnterpriseServerImpl.java b/agent/src/main/java/com/orientechnologies/enterprise/server/OEnterpriseServerImpl.java index 814ab410c92..80b03c87175 100755 --- a/agent/src/main/java/com/orientechnologies/enterprise/server/OEnterpriseServerImpl.java +++ b/agent/src/main/java/com/orientechnologies/enterprise/server/OEnterpriseServerImpl.java @@ -10,8 +10,6 @@ import com.orientechnologies.enterprise.server.listener.OEnterpriseConnectionListener; import com.orientechnologies.enterprise.server.listener.OEnterpriseStorageListener; import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.command.OCommandExecutor; -import com.orientechnologies.orient.core.command.OCommandRequestText; import com.orientechnologies.orient.core.db.*; import com.orientechnologies.orient.core.db.OSystemDatabase; import com.orientechnologies.orient.core.db.document.OQueryDatabaseState; @@ -406,13 +404,6 @@ public void onAfterTxCommit(ODatabase iDatabase) {} @Override public void onClose(ODatabase iDatabase) {} - @Override - public void onBeforeCommand(OCommandRequestText iCommand, OCommandExecutor executor) {} - - @Override - public void onAfterCommand( - OCommandRequestText iCommand, OCommandExecutor executor, Object result) {} - @Override public void onCommandStart(ODatabase database, OResultSet result) { this.dbListeners.forEach((c -> c.onCommandStart(database, result))); diff --git a/client/src/main/java/com/orientechnologies/orient/client/remote/SimpleValueFetchPlanCommandListener.java b/client/src/main/java/com/orientechnologies/orient/client/remote/SimpleValueFetchPlanCommandListener.java deleted file mode 100644 index 3fa6b83df41..00000000000 --- a/client/src/main/java/com/orientechnologies/orient/client/remote/SimpleValueFetchPlanCommandListener.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.orientechnologies.orient.client.remote; - -import com.orientechnologies.orient.core.command.OCommandResultListener; -import com.orientechnologies.orient.core.record.impl.ODocument; - -public interface SimpleValueFetchPlanCommandListener extends OCommandResultListener { - - void linkdedBySimpleValue(ODocument doc); -} diff --git a/client/src/main/java/com/orientechnologies/orient/client/remote/message/OCommandRequest.java b/client/src/main/java/com/orientechnologies/orient/client/remote/message/OCommandRequest.java index 00de1907c48..30d96b9091a 100644 --- a/client/src/main/java/com/orientechnologies/orient/client/remote/message/OCommandRequest.java +++ b/client/src/main/java/com/orientechnologies/orient/client/remote/message/OCommandRequest.java @@ -30,7 +30,6 @@ import com.orientechnologies.orient.client.remote.OStorageRemoteSession; import com.orientechnologies.orient.core.command.OCommandDistributedReplicateRequest; import com.orientechnologies.orient.core.command.OCommandDistributedReplicateRequest.DISTRIBUTED_EXECUTION_MODE; -import com.orientechnologies.orient.core.command.OCommandRequestText; import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.exception.OSerializationException; @@ -205,7 +204,6 @@ public Map getParameters() { private ODatabaseDocumentInternal database; private boolean asynch; - private OCommandRequestText query; private boolean live; private OQuery queryD; private OCommand commandD; @@ -613,7 +611,7 @@ public boolean isLive() { @Override public OCommandResponse createResponse() { - return new OCommandResponse(this.query.getResultListener(), database, live); + return new OCommandResponse(database, live); } @Override diff --git a/client/src/main/java/com/orientechnologies/orient/client/remote/message/OCommandResponse.java b/client/src/main/java/com/orientechnologies/orient/client/remote/message/OCommandResponse.java index fa7b90124b4..4348461a709 100644 --- a/client/src/main/java/com/orientechnologies/orient/client/remote/message/OCommandResponse.java +++ b/client/src/main/java/com/orientechnologies/orient/client/remote/message/OCommandResponse.java @@ -23,10 +23,7 @@ import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.common.log.OLogger; import com.orientechnologies.orient.client.remote.OBinaryResponse; -import com.orientechnologies.orient.client.remote.OFetchPlanResults; import com.orientechnologies.orient.client.remote.OStorageRemoteSession; -import com.orientechnologies.orient.client.remote.SimpleValueFetchPlanCommandListener; -import com.orientechnologies.orient.core.command.OCommandResultListener; import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.orientechnologies.orient.core.db.record.OIdentifiable; @@ -51,26 +48,19 @@ public final class OCommandResponse implements OBinaryResponse { private static final OLogger logger = OLogManager.instance().logger(OCommandResponse.class); - private final OCommandResultListener listener; private final ODatabaseDocumentInternal database; private boolean live; private Object result; private boolean isRecordResultSet; public OCommandResponse( - Object result, - SimpleValueFetchPlanCommandListener listener, - boolean isRecordResultSet, - ODatabaseDocumentInternal database) { + Object result, boolean isRecordResultSet, ODatabaseDocumentInternal database) { this.result = result; - this.listener = listener; this.isRecordResultSet = isRecordResultSet; this.database = database; } - public OCommandResponse( - OCommandResultListener listener, ODatabaseDocumentInternal database, boolean live) { - this.listener = listener; + public OCommandResponse(ODatabaseDocumentInternal database, boolean live) { this.database = database; this.live = live; } @@ -78,30 +68,12 @@ public OCommandResponse( public void write(OChannelDataOutput channel, int protocolVersion, ORecordSerializer serializer) throws IOException { - serializeValue( - channel, - (SimpleValueFetchPlanCommandListener) listener, - result, - false, - isRecordResultSet, - protocolVersion, - serializer); - if (listener instanceof OFetchPlanResults) { - // SEND FETCHED RECORDS TO LOAD IN CLIENT CACHE - for (ORecord rec : ((OFetchPlanResults) listener).getFetchedRecordsToSend()) { - channel.writeByte((byte) 2); // CLIENT CACHE RECORD. IT - // ISN'T PART OF THE - // RESULT SET - OMessageHelper.writeIdentifiable(channel, rec, serializer); - } - - channel.writeByte((byte) 0); // NO MORE RECORDS - } + serializeValue(channel, result, false, isRecordResultSet, protocolVersion, serializer); + channel.writeByte((byte) 0); // NO MORE RECORDS } public void serializeValue( OChannelDataOutput channel, - final SimpleValueFetchPlanCommandListener listener, Object result, boolean load, boolean isRecordResultSet, @@ -116,10 +88,9 @@ public void serializeValue( channel.writeByte((byte) 'r'); if (load && result instanceof ORecordId) result = ((ORecordId) result).getRecord(); - if (listener != null) listener.result(result); OMessageHelper.writeIdentifiable(channel, (OIdentifiable) result, recordSerializer); } else if (!isRecordResultSet) { - writeSimpleValue(channel, listener, result, protocolVersion, recordSerializer); + writeSimpleValue(channel, result, protocolVersion, recordSerializer); } else if (OMultiValue.isMultiValue(result)) { final byte collectionType = result instanceof Set ? (byte) 's' : (byte) 'l'; channel.writeByte(collectionType); @@ -127,7 +98,6 @@ public void serializeValue( for (Object o : OMultiValue.getMultiValueIterable(result, false)) { try { if (load && o instanceof ORecordId) o = ((ORecordId) o).getRecord(); - if (listener != null) listener.result(o); OMessageHelper.writeIdentifiable(channel, (OIdentifiable) o, recordSerializer); } catch (Exception e) { @@ -142,7 +112,6 @@ public void serializeValue( for (Object o : OMultiValue.getMultiValueIterable(result)) { try { if (load && o instanceof ORecordId) o = ((ORecordId) o).getRecord(); - if (listener != null) listener.result(o); channel.writeByte((byte) 1); // ONE MORE RECORD OMessageHelper.writeIdentifiable(channel, (OIdentifiable) o, recordSerializer); @@ -159,7 +128,6 @@ public void serializeValue( for (Object o : OMultiValue.getMultiValueIterable(result)) { try { if (load && o instanceof ORecordId) o = ((ORecordId) o).getRecord(); - if (listener != null) listener.result(o); OMessageHelper.writeIdentifiable(channel, (OIdentifiable) o, recordSerializer); } catch (Exception e) { @@ -170,13 +138,12 @@ public void serializeValue( } else { // ANY OTHER (INCLUDING LITERALS) - writeSimpleValue(channel, listener, result, protocolVersion, recordSerializer); + writeSimpleValue(channel, result, protocolVersion, recordSerializer); } } private void writeSimpleValue( OChannelDataOutput channel, - SimpleValueFetchPlanCommandListener listener, Object result, int protocolVersion, ORecordSerializer recordSerializer) @@ -187,15 +154,9 @@ private void writeSimpleValue( ODocument document = new ODocument(); document.field("result", result); OMessageHelper.writeIdentifiable(channel, document, recordSerializer); - if (listener != null) listener.linkdedBySimpleValue(document); } else { channel.writeByte((byte) 'a'); final StringBuilder value = new StringBuilder(64); - if (listener != null) { - ODocument document = new ODocument(); - document.field("result", result); - listener.linkdedBySimpleValue(document); - } ORecordSerializerStringAbstract.fieldTypeToString( value, OType.getTypeByClass(result.getClass()), result); channel.writeString(value.toString()); @@ -222,7 +183,6 @@ public void read(OChannelDataInput network, OStorageRemoteSession session) throw } finally { // TODO: this is here because we allow query in end listener. session.commandExecuting = false; - if (listener != null && !live) listener.end(); } } diff --git a/core/src/main/java/com/orientechnologies/common/parser/OBaseParser.java b/core/src/main/java/com/orientechnologies/common/parser/OBaseParser.java deleted file mode 100644 index 62b32b9f29a..00000000000 --- a/core/src/main/java/com/orientechnologies/common/parser/OBaseParser.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ -package com.orientechnologies.common.parser; - -/** - * Abstract generic command to parse. - * - * @author Luca Garulli (l.garulli--(at)--orientdb.com) - */ -public abstract class OBaseParser { - public String parserText; - - private transient StringBuilder parserLastWord = new StringBuilder(256); - private transient int parserEscapeSequenceCount = 0; - private transient int parserCurrentPos = 0; - private transient int parserPreviousPos = 0; - private transient char parserLastSeparator = ' '; - - public static int nextWord( - final String iText, - final String iTextUpperCase, - int ioCurrentPosition, - final StringBuilder ioWord, - final boolean iForceUpperCase) { - return nextWord(iText, iTextUpperCase, ioCurrentPosition, ioWord, iForceUpperCase, " =><(),"); - } - - public static int nextWord( - final String iText, - final String iTextUpperCase, - int ioCurrentPosition, - final StringBuilder ioWord, - final boolean iForceUpperCase, - final String iSeparatorChars) { - ioWord.setLength(0); - - ioCurrentPosition = OStringParser.jumpWhiteSpaces(iText, ioCurrentPosition, -1); - if (ioCurrentPosition < 0) return -1; - - getWordStatic( - iForceUpperCase ? iTextUpperCase : iText, ioCurrentPosition, iSeparatorChars, ioWord); - - if (ioWord.length() > 0) ioCurrentPosition += ioWord.length(); - - return ioCurrentPosition; - } - - /** - * @param iText Text where to search - * @param iBeginIndex Begin index - * @param iSeparatorChars Separators as a String of multiple characters - * @param ioBuffer StringBuilder object with the word found - */ - public static void getWordStatic( - final CharSequence iText, - int iBeginIndex, - final String iSeparatorChars, - final StringBuilder ioBuffer) { - ioBuffer.setLength(0); - - char stringBeginChar = ' '; - char c; - - for (int i = iBeginIndex; i < iText.length(); ++i) { - c = iText.charAt(i); - boolean found = false; - for (int sepIndex = 0; sepIndex < iSeparatorChars.length(); ++sepIndex) { - if (iSeparatorChars.charAt(sepIndex) == c) { - // SEPARATOR AT THE BEGINNING: JUMP IT - found = true; - break; - } - } - if (!found) break; - - iBeginIndex++; - } - - for (int i = iBeginIndex; i < iText.length(); ++i) { - c = iText.charAt(i); - - if (c == '\'' || c == '"' || c == '`') { - if (stringBeginChar != ' ') { - // CLOSE THE STRING? - if (stringBeginChar == c) { - // SAME CHAR AS THE BEGIN OF THE STRING: CLOSE IT AND PUSH - stringBeginChar = ' '; - } - } else { - // START STRING - stringBeginChar = c; - } - } else if (stringBeginChar == ' ') { - for (int sepIndex = 0; sepIndex < iSeparatorChars.length(); ++sepIndex) { - if (iSeparatorChars.charAt(sepIndex) == c && ioBuffer.length() > 0) { - // SEPARATOR (OUTSIDE A STRING): PUSH - return; - } - } - } - - ioBuffer.append(c); - } - } - - public String getSyntax() { - return "?"; - } - - /** Returns the last separator encountered, otherwise returns a blank (' '). */ - public char parserGetLastSeparator() { - return parserLastSeparator; - } - - /** Overwrites the last separator. To ignore it set it to blank (' '). */ - public void parserSetLastSeparator(final char iSeparator) { - parserLastSeparator = iSeparator; - } - - /** - * Returns the stream position before last parsing. - * - * @return Offset from the beginning - */ - public int parserGetPreviousPosition() { - return parserPreviousPos; - } - - /** - * Tells if the parsing has reached the end of the content. - * - * @return True if is ended, otherwise false - */ - public boolean parserIsEnded() { - return parserCurrentPos == -1; - } - - /** - * Returns the current stream position. - * - * @return Offset from the beginning - */ - public int parserGetCurrentPosition() { - return parserCurrentPos; - } - - /** - * Returns the current character in the current stream position - * - * @return The current character in the current stream position. If the end is reached, then a - * blank (' ') is returned - */ - public char parserGetCurrentChar() { - if (parserCurrentPos < 0) return ' '; - return parserText.charAt(parserCurrentPos); - } - - /** - * Returns the last parsed word. - * - * @return Last parsed word as String - */ - public String parserGetLastWord() { - return parserLastWord.toString(); - } - - public int getLastWordLength() { - return parserLastWord.length() + parserEscapeSequenceCount; - } - - /** - * Throws a syntax error exception. - * - * @param iText Text about the problem. - */ - protected abstract void throwSyntaxErrorException(final String iText); - - /** - * Goes back to the previous position. - * - * @return The previous position - */ - protected int parserGoBack() { - parserCurrentPos = parserPreviousPos; - return parserCurrentPos; - } - - /** - * Skips not valid characters like spaces and line feeds. - * - * @return True if the string is not ended, otherwise false - */ - protected boolean parserSkipWhiteSpaces() { - if (parserCurrentPos == -1) return false; - - parserCurrentPos = OStringParser.jumpWhiteSpaces(parserText, parserCurrentPos, -1); - return parserCurrentPos > -1; - } - - /** - * Overwrites the current stream position. - * - * @param iPosition New position - * @return True if the string is not ended, otherwise false - */ - protected boolean parserSetCurrentPosition(final int iPosition) { - parserCurrentPos = iPosition; - if (parserCurrentPos >= parserText.length()) - // END OF TEXT - parserCurrentPos = -1; - return parserCurrentPos > -1; - } - - /** Sets the end of text as position */ - protected void parserSetEndOfText() { - parserCurrentPos = -1; - } - - /** - * Moves the current stream position forward or backward of iOffset characters - * - * @param iOffset Number of characters to move. Negative numbers means backwards - * @return True if the string is not ended, otherwise false - */ - protected boolean parserMoveCurrentPosition(final int iOffset) { - if (parserCurrentPos < 0) return false; - return parserSetCurrentPosition(parserCurrentPos + iOffset); - } -} diff --git a/core/src/main/java/com/orientechnologies/common/parser/OStringParser.java b/core/src/main/java/com/orientechnologies/common/parser/OStringParser.java index 1d998789da7..0217c0045d3 100644 --- a/core/src/main/java/com/orientechnologies/common/parser/OStringParser.java +++ b/core/src/main/java/com/orientechnologies/common/parser/OStringParser.java @@ -158,75 +158,6 @@ else if (openBraket == 0 && openGraph == 0) { return result; } - public static String[] split(String iText, final char iSplitChar, String iJumpChars) { - iText = iText.trim(); - - ArrayList fields = new ArrayList(); - StringBuilder buffer = new StringBuilder(256); - char c; - char stringChar = ' '; - boolean escape = false; - boolean jumpSplitChar = false; - boolean charFound; - - for (int i = 0; i < iText.length(); i++) { - c = iText.charAt(i); - - if (!escape && c == '\\' && ((i + 1) < iText.length())) { - if (iText.charAt(i + 1) == 'u') { - i = readUnicode(iText, i + 2, buffer); - } else { - escape = true; - buffer.append(c); - } - continue; - } - - if (c == '\'' || c == '"') { - if (!jumpSplitChar) { - jumpSplitChar = true; - stringChar = c; - } else { - if (!escape && c == stringChar) jumpSplitChar = false; - } - } - - if (c == iSplitChar) { - if (!jumpSplitChar) { - fields.add(buffer.toString()); - buffer.setLength(0); - continue; - } - } - - // CHECK IF IT MUST JUMP THE CHAR - if (buffer.length() == 0) { - charFound = false; - - for (int jumpIndex = 0; jumpIndex < iJumpChars.length(); ++jumpIndex) { - if (iJumpChars.charAt(jumpIndex) == c) { - charFound = true; - break; - } - } - - if (charFound) continue; - } - - buffer.append(c); - - if (escape) escape = false; - } - - if (buffer.length() > 0) { - fields.add(buffer.toString()); - buffer.setLength(0); - } - String[] result = new String[fields.size()]; - fields.toArray(result); - return result; - } - /** * Finds a character inside a string specyfing the limits and direction. If iFrom is minor than * iTo, then it moves forward, otherwise backward. @@ -278,55 +209,6 @@ public static int indexOfOutsideStrings( return -1; } - /** - * Jump white spaces. - * - * @param iText String to analyze - * @param iCurrentPosition Current position in text - * @param iMaxPosition TODO - * @return The new offset inside the string analyzed - */ - public static int jumpWhiteSpaces( - final CharSequence iText, final int iCurrentPosition, final int iMaxPosition) { - return jump(iText, iCurrentPosition, iMaxPosition, COMMON_JUMP); - } - - /** - * Jump some characters reading from an offset of a String. - * - * @param iText String to analyze - * @param iCurrentPosition Current position in text - * @param iMaxPosition Maximum position to read - * @param iJumpChars String as char array of chars to jump - * @return The new offset inside the string analyzed - */ - public static int jump( - final CharSequence iText, - int iCurrentPosition, - final int iMaxPosition, - final String iJumpChars) { - if (iCurrentPosition < 0) return -1; - - final int size = iMaxPosition > -1 ? Math.min(iMaxPosition, iText.length()) : iText.length(); - final int jumpCharSize = iJumpChars.length(); - boolean found = true; - char c; - for (; iCurrentPosition < size; ++iCurrentPosition) { - found = false; - c = iText.charAt(iCurrentPosition); - for (int jumpIndex = 0; jumpIndex < jumpCharSize; ++jumpIndex) { - if (iJumpChars.charAt(jumpIndex) == c) { - found = true; - break; - } - } - - if (!found) break; - } - - return iCurrentPosition >= size ? -1 : iCurrentPosition; - } - public static int readUnicode(String iText, int position, final StringBuilder buffer) { // DECODE UNICODE CHAR final StringBuilder buff = new StringBuilder(64); @@ -336,38 +218,4 @@ public static int readUnicode(String iText, int position, final StringBuilder bu buffer.append((char) Integer.parseInt(buff.toString(), 16)); return position - 1; } - - public static int readUnicode(char[] iText, int position, final StringBuilder buffer) { - // DECODE UNICODE CHAR - final StringBuilder buff = new StringBuilder(64); - final int lastPos = position + 4; - for (; position < lastPos; ++position) buff.append(iText[position]); - - buffer.append((char) Integer.parseInt(buff.toString(), 16)); - return position - 1; - } - - public static String replaceAll( - final String iText, final String iToReplace, final String iReplacement) { - if (iText == null || iText.length() <= 0 || iToReplace == null || iToReplace.length() <= 0) - return iText; - int pos = iText.indexOf(iToReplace); - int lastAppend = 0; - final StringBuffer buffer = new StringBuffer(1024); - while (pos > -1) { - buffer.append(iText.substring(lastAppend, pos)); - buffer.append(iReplacement); - lastAppend = pos + iToReplace.length(); - pos = iText.indexOf(iToReplace, lastAppend); - } - buffer.append(iText.substring(lastAppend)); - return buffer.toString(); - } - - /** Like String.startsWith() but ignoring case */ - public static boolean startsWithIgnoreCase(final String iText, final String iToFind) { - if (iText.length() < iToFind.length()) return false; - - return iText.substring(0, iToFind.length()).equalsIgnoreCase(iToFind); - } } diff --git a/core/src/main/java/com/orientechnologies/common/stream/BreakingForEach.java b/core/src/main/java/com/orientechnologies/common/stream/BreakingForEach.java deleted file mode 100644 index 310f1c7e6ce..00000000000 --- a/core/src/main/java/com/orientechnologies/common/stream/BreakingForEach.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.orientechnologies.common.stream; - -import java.util.Spliterator; -import java.util.function.BiConsumer; -import java.util.stream.Stream; - -public class BreakingForEach { - public static class Breaker { - private boolean shouldBreak = false; - - public void stop() { - shouldBreak = true; - } - } - - public static void forEach(Stream stream, BiConsumer consumer) { - Spliterator spliterator = stream.spliterator(); - boolean hadNext = true; - Breaker breaker = new Breaker(); - - while (hadNext && !breaker.shouldBreak) { - hadNext = - spliterator.tryAdvance( - elem -> { - consumer.accept(elem, breaker); - }); - } - } -} diff --git a/core/src/main/java/com/orientechnologies/common/util/OCollections.java b/core/src/main/java/com/orientechnologies/common/util/OCollections.java index c32b9a415fc..50ed7d623fd 100644 --- a/core/src/main/java/com/orientechnologies/common/util/OCollections.java +++ b/core/src/main/java/com/orientechnologies/common/util/OCollections.java @@ -46,38 +46,6 @@ public static int indexOf( return -1; } - /** - * This method is used to find an item in an array. - * - * @param array Array in which value should be found. - * @param object Object to find. - * @return Index of found item or -1 otherwise. - */ - public static int indexOf(final Object[] array, final Comparable object) { - for (int i = 0; i < array.length; ++i) { - if (object.compareTo(array[i]) == 0) - // FOUND - return i; - } - return -1; - } - - /** - * This method is used to find a number in an array. - * - * @param array Array of integers in which value should be found. - * @param object number to find. - * @return Index of found item or -1 otherwise. - */ - public static int indexOf(final int[] array, final int object) { - for (int i = 0; i < array.length; ++i) { - if (array[i] == object) - // FOUND - return i; - } - return -1; - } - /** * Create a string representation of all objects in the given Iterable. example : * [value1,value2,value3] diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OBasicCommandContext.java b/core/src/main/java/com/orientechnologies/orient/core/command/OBasicCommandContext.java index 36b2b64059d..96318383e81 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OBasicCommandContext.java +++ b/core/src/main/java/com/orientechnologies/orient/core/command/OBasicCommandContext.java @@ -25,7 +25,6 @@ import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; import com.orientechnologies.orient.core.db.ODatabaseSession; import com.orientechnologies.orient.core.metadata.schema.OType; -import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.record.impl.ODocumentHelper; import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper; import com.orientechnologies.orient.core.sql.executor.OExecutionStep; @@ -70,7 +69,6 @@ public class OBasicCommandContext implements OCommandContext { private long timeoutMs; private OCommandContext.TIMEOUT_STRATEGY timeoutStrategy; protected AtomicLong resultsProcessed = new AtomicLong(0); - protected Set uniqueResult = new HashSet(); private Map stepStats = new IdentityHashMap<>(); private LinkedList currentStepStats = new LinkedList<>(); private boolean indexStats = true; @@ -430,21 +428,6 @@ public AtomicLong getResultsProcessed() { return resultsProcessed; } - /** - * adds an item to the unique result set - * - * @param o the result item to add - * @return true if the element is successfully added (it was not present yet), false otherwise (it - * was already present) - */ - public synchronized boolean addToUniqueResult(Object o) { - Object toAdd = o; - if (o instanceof ODocument && ((ODocument) o).getIdentity().isNew()) { - toAdd = new ODocumentEqualityWrapper((ODocument) o); - } - return this.uniqueResult.add(toAdd); - } - public ODatabaseSession getDatabase() { if (database != null) { return database; diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommand.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommand.java deleted file mode 100644 index 2833015790f..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommand.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ -package com.orientechnologies.orient.core.command; - -/** - * Generic GOF command pattern implementation. - * - * @author Luca Garulli (l.garulli--(at)--orientdb.com) - */ -public interface OCommand { - /** - * Executes command. - * - * @return The result of command if any, otherwise null - */ - public Object execute(); - - public OCommandContext getContext(); -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandExecutor.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandExecutor.java deleted file mode 100644 index b5ac0d62cf4..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandExecutor.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ -package com.orientechnologies.orient.core.command; - -import com.orientechnologies.common.listener.OProgressListener; -import java.util.Map; -import java.util.Set; - -/** - * Generic GOF command pattern implementation. - * - * @author Luca Garulli (l.garulli--(at)--orientdb.com) - */ -public interface OCommandExecutor { - - /** - * Parse the request. Once parsed the command can be executed multiple times by using the - * execute() method. - * - * @param iRequest Command request implementation. - * @see #execute(Map...) - * @return - */ - RET parse(OCommandRequest iRequest); - - /** - * Execute the requested command parsed previously. - * - * @param iArgs Optional variable arguments to pass to the command. - * @see #parse(OCommandRequest) - * @return - */ - Object execute(final Map iArgs); - - /** - * Set the listener invoked while the command is executing. - * - * @param progressListener OProgressListener implementation - * @return - */ - RET setProgressListener(OProgressListener progressListener); - - RET setLimit(int iLimit); - - String getFetchPlan(); - - Map getParameters(); - - OCommandContext getContext(); - - void setContext(OCommandContext context); - - /** Returns true if the command doesn't change the database, otherwise false. */ - boolean isIdempotent(); - - /** Returns the involved clusters. */ - Set getInvolvedClusters(); - - /** - * Returns the security operation type use to check about security. - * - * @see com.orientechnologies.orient.core.metadata.security.ORole PERMISSION_* - * @return - */ - int getSecurityOperationType(); - - boolean involveSchema(); - - String getSyntax(); - - /** Returns true if the command must be executed on local node on distributed configuration. */ - boolean isLocalExecution(); - - /** Returns true if the command results can be cached. */ - boolean isCacheable(); - - long getDistributedTimeout(); - - Object mergeResults(Map results) throws Exception; -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandExecutorAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandExecutorAbstract.java deleted file mode 100755 index 91a101c01f8..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandExecutorAbstract.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ -package com.orientechnologies.orient.core.command; - -import com.orientechnologies.common.collection.OMultiValue; -import com.orientechnologies.common.listener.OProgressListener; -import com.orientechnologies.common.parser.OBaseParser; -import com.orientechnologies.orient.core.config.OGlobalConfiguration; -import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; -import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; -import com.orientechnologies.orient.core.db.OExecutionThreadLocal; -import com.orientechnologies.orient.core.db.record.OIdentifiable; -import com.orientechnologies.orient.core.exception.OCommandInterruptedException; -import com.orientechnologies.orient.core.metadata.security.ORole; -import com.orientechnologies.orient.core.metadata.security.ORule; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Abstract implementation of Executor Command interface. - * - * @author Luca Garulli (l.garulli--(at)--orientdb.com) - */ -@SuppressWarnings("unchecked") -public abstract class OCommandExecutorAbstract extends OBaseParser implements OCommandExecutor { - protected OProgressListener progressListener; - protected int limit = -1; - protected Map parameters; - protected OCommandContext context; - - public static ODatabaseDocumentInternal getDatabase() { - return ODatabaseRecordThreadLocal.instance().get(); - } - - public OCommandExecutorAbstract init(final OCommandRequestText iRequest) { - getDatabase().checkSecurity(ORule.ResourceGeneric.COMMAND, ORole.PERMISSION_READ); - parserText = iRequest.getText().trim(); - return this; - } - - @Override - public String toString() { - return getClass().getSimpleName() + " [text=" + parserText + "]"; - } - - public OProgressListener getProgressListener() { - return progressListener; - } - - public RET setProgressListener( - final OProgressListener progressListener) { - this.progressListener = progressListener; - return (RET) this; - } - - public String getUndoCommand() { - return null; - } - - public long getDistributedTimeout() { - return getDatabase() - .getConfiguration() - .getValueAsLong(OGlobalConfiguration.DISTRIBUTED_COMMAND_LONG_TASK_SYNCH_TIMEOUT); - } - - public int getLimit() { - return limit; - } - - public RET setLimit(final int iLimit) { - this.limit = iLimit; - return (RET) this; - } - - public Map getParameters() { - return parameters; - } - - @Override - public String getFetchPlan() { - return null; - } - - public OCommandContext getContext() { - if (context == null) { - context = new OBasicCommandContext(ODatabaseRecordThreadLocal.instance().getIfDefined()); - } - return context; - } - - public void setContext(final OCommandContext iContext) { - context = iContext; - } - - @Override - public Set getInvolvedClusters() { - return Collections.EMPTY_SET; - } - - @Override - public int getSecurityOperationType() { - return ORole.PERMISSION_READ; - } - - public boolean involveSchema() { - return false; - } - - protected boolean checkInterruption() { - return checkInterruption(this.context); - } - - public static boolean checkInterruption(final OCommandContext iContext) { - if (OExecutionThreadLocal.isInterruptCurrentOperation()) - throw new OCommandInterruptedException("The command has been interrupted"); - - if (iContext != null && !iContext.checkTimeout()) return false; - - return true; - } - - public OCommandDistributedReplicateRequest.DISTRIBUTED_RESULT_MGMT - getDistributedResultManagement() { - return OCommandDistributedReplicateRequest.DISTRIBUTED_RESULT_MGMT.CHECK_FOR_EQUALS; - } - - @Override - public boolean isLocalExecution() { - return false; - } - - @Override - public boolean isCacheable() { - return false; - } - - public Object mergeResults(final Map results) throws Exception { - - if (results.isEmpty()) return null; - - Object aggregatedResult = null; - - for (Map.Entry entry : results.entrySet()) { - final String nodeName = entry.getKey(); - final Object nodeResult = entry.getValue(); - - if (nodeResult instanceof Collection) { - if (aggregatedResult == null) aggregatedResult = new ArrayList(); - - ((List) aggregatedResult).addAll((Collection) nodeResult); - - } else if (nodeResult instanceof Exception) - - // RECEIVED EXCEPTION - throw (Exception) nodeResult; - else if (nodeResult instanceof OIdentifiable) { - if (aggregatedResult == null) aggregatedResult = new ArrayList(); - - ((List) aggregatedResult).add(nodeResult); - - } else if (nodeResult instanceof Number) { - if (aggregatedResult == null) aggregatedResult = nodeResult; - else OMultiValue.add(aggregatedResult, nodeResult); - } - } - - return aggregatedResult; - } - - public boolean isDistributedExecutingOnLocalNodeFirst() { - return true; - } -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandPredicate.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandPredicate.java deleted file mode 100644 index 609084c0342..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandPredicate.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ - -package com.orientechnologies.orient.core.command; - -/** - * Command predicate to be evaluated against a record and a context. - * - * @author Luca Garulli (l.garulli--(at)--orientdb.com) - */ -public interface OCommandPredicate {} diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequest.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequest.java deleted file mode 100644 index a2eb37d0e90..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequest.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ -package com.orientechnologies.orient.core.command; - -import com.orientechnologies.orient.core.command.OCommandContext.TIMEOUT_STRATEGY; - -/** - * Generic GOF command pattern implementation. Execute a command passing the optional arguments - * "iArgs" and returns an Object. - * - * @author Luca Garulli (l.garulli--(at)--orientdb.com) - */ -public interface OCommandRequest { - RET execute(Object... iArgs); - - /** - * This api is deprecated use sql keyword "LIMIT" instead - * - *

Returns the limit of result set. -1 means no limits. - */ - int getLimit(); - - /** - * This api is deprecated use sql keyword "LIMIT" instead - * - *

Sets the maximum items the command can returns. -1 means no limits. - * - * @param iLimit -1 = no limit. 1 to N to limit the result set. - * @return - */ - @Deprecated - OCommandRequest setLimit(int iLimit); - - /** - * This api is deprecated use sql keyword "TIMEOUT" instead - * - *

Returns the command timeout. 0 means no timeout. - * - * @return - */ - @Deprecated - long getTimeoutTime(); - - /** - * This api is deprecated use sql keyword "TIMEOUT" instead - * - *

Returns the command timeout strategy between the defined ones. - * - * @return - */ - @Deprecated - TIMEOUT_STRATEGY getTimeoutStrategy(); - - /** - * This api is deprecated use sql keyword "TIMEOUT" instead - * - *

Sets the command timeout. When the command execution time is major than the timeout the - * command returns - * - * @param timeout - */ - @Deprecated - void setTimeout(long timeout, TIMEOUT_STRATEGY strategy); - - /** Returns true if the command doesn't change the database, otherwise false. */ - boolean isIdempotent(); - - /** - * This api is deprecated use sql keyword "FETCHPLAN" instead - * - *

Returns the fetch plan if any - * - * @return Fetch plan as unique string or null if it was not defined. - */ - @Deprecated - String getFetchPlan(); - - /** - * This api is deprecated use sql keyword "FETCHPLAN" instead - * - *

Set the fetch plan. The format is: - * - *

-   * <field>:<depth-level>*
-   * 
- * - * Where: - * - *
    - *
  • field is the name of the field to specify the depth-level. * wildcard means - * any fields - *
  • depth-level is the depth level to fetch. -1 means infinite, 0 means no fetch at - * all and 1-N the depth level value. - *
- * - * Uses the blank spaces to separate the fields strategies.
- * Example: - * - *
-   * children:-1 parent:0 sibling:3 *:0
-   * 
- * - *
- * - * @param iFetchPlan - * @return - */ - @Deprecated - RET setFetchPlan(String iFetchPlan); - - void setUseCache(boolean iUseCache); - - OCommandContext getContext(); - - OCommandRequest setContext(final OCommandContext iContext); -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAbstract.java deleted file mode 100755 index c99bc7dd1d3..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAbstract.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ -package com.orientechnologies.orient.core.command; - -import com.orientechnologies.common.listener.OProgressListener; -import com.orientechnologies.orient.core.command.OCommandContext.TIMEOUT_STRATEGY; -import com.orientechnologies.orient.core.config.OGlobalConfiguration; -import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; -import com.orientechnologies.orient.core.db.record.OIdentifiable; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -/** - * Text based Command Request abstract class. - * - * @author Luca Garulli (l.garulli--(at)--orientdb.com) - */ -@SuppressWarnings("serial") -public abstract class OCommandRequestAbstract implements OCommandRequestInternal { - protected OCommandResultListener resultListener; - protected OProgressListener progressListener; - protected int limit = -1; - protected long timeoutMs = OGlobalConfiguration.COMMAND_TIMEOUT.getValueAsLong(); - protected TIMEOUT_STRATEGY timeoutStrategy = TIMEOUT_STRATEGY.EXCEPTION; - protected Map parameters; - protected String fetchPlan = null; - protected boolean useCache = false; - protected boolean cacheableResult = false; - protected OCommandContext context; - - private final Set nodesToExclude = new HashSet(); - private boolean recordResultSet = true; - - protected OCommandRequestAbstract() {} - - public OCommandResultListener getResultListener() { - return resultListener; - } - - public void setResultListener(OCommandResultListener iListener) { - resultListener = iListener; - } - - public Map getParameters() { - return parameters; - } - - protected void setParameters(final Object... iArgs) { - if (iArgs != null && iArgs.length > 0) { - parameters = convertToParameters(iArgs); - } - } - - @SuppressWarnings("unchecked") - protected Map convertToParameters(Object... iArgs) { - final Map params; - - if (iArgs.length == 1 && iArgs[0] instanceof Map) { - params = (Map) iArgs[0]; - } else { - if (iArgs.length == 1 - && iArgs[0] != null - && iArgs[0].getClass().isArray() - && iArgs[0] instanceof Object[]) iArgs = (Object[]) iArgs[0]; - - params = new HashMap(iArgs.length); - for (int i = 0; i < iArgs.length; ++i) { - Object par = iArgs[i]; - - if (par instanceof OIdentifiable && ((OIdentifiable) par).getIdentity().isValid()) - // USE THE RID ONLY - par = ((OIdentifiable) par).getIdentity(); - - params.put(i, par); - } - } - return params; - } - - public OProgressListener getProgressListener() { - return progressListener; - } - - public OCommandRequestAbstract setProgressListener(OProgressListener progressListener) { - this.progressListener = progressListener; - return this; - } - - public void reset() {} - - public int getLimit() { - return limit; - } - - public OCommandRequestAbstract setLimit(final int limit) { - this.limit = limit; - return this; - } - - public String getFetchPlan() { - return fetchPlan; - } - - @SuppressWarnings("unchecked") - public RET setFetchPlan(String fetchPlan) { - this.fetchPlan = fetchPlan; - return (RET) this; - } - - public boolean isUseCache() { - return useCache; - } - - public void setUseCache(boolean useCache) { - this.useCache = useCache; - } - - @Override - public OCommandContext getContext() { - if (context == null) - context = new OBasicCommandContext(ODatabaseRecordThreadLocal.instance().getIfDefined()); - return context; - } - - public OCommandRequestAbstract setContext(final OCommandContext iContext) { - context = iContext; - return this; - } - - public long getTimeoutTime() { - return timeoutMs; - } - - public void setTimeout(final long timeout, final TIMEOUT_STRATEGY strategy) { - this.timeoutMs = timeout; - this.timeoutStrategy = strategy; - } - - public TIMEOUT_STRATEGY getTimeoutStrategy() { - return timeoutStrategy; - } - - public void addExcludedNode(String node) { - nodesToExclude.add(node); - } - - public void removeExcludedNode(String node) { - nodesToExclude.remove(node); - } -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAsynch.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAsynch.java deleted file mode 100644 index 4908ec195f6..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestAsynch.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ -package com.orientechnologies.orient.core.command; - -public interface OCommandRequestAsynch { - public OCommandResultListener getResultListener(); - - public void setResultListener(OCommandResultListener iListener); - - public boolean isAsynchronous(); -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestInternal.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestInternal.java deleted file mode 100644 index 50b5cbc3073..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestInternal.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ -package com.orientechnologies.orient.core.command; - -import java.util.Map; - -/** - * Internal specialization of generic OCommand interface. - * - * @author Luca Garulli (l.garulli--(at)--orientdb.com) - */ -public interface OCommandRequestInternal extends OCommandRequest { - - Map getParameters(); - - OCommandResultListener getResultListener(); - - void reset(); -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestText.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestText.java deleted file mode 100644 index 456f0796f82..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestText.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ -package com.orientechnologies.orient.core.command; - -import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer; - -/** - * Internal specialization of generic OCommand interface based on a text command. - * - * @author Luca Garulli (l.garulli--(at)--orientdb.com) - */ -public interface OCommandRequestText extends OCommandRequestInternal { - String getText(); - - OCommandRequestText setText(String iText); - - OCommandRequestText fromStream(byte[] bytes, ORecordSerializer serializer); - - byte[] toStream(); -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestTextAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestTextAbstract.java deleted file mode 100755 index d78da5b792b..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandRequestTextAbstract.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ -package com.orientechnologies.orient.core.command; - -import com.orientechnologies.orient.core.exception.OSerializationException; -import com.orientechnologies.orient.core.index.OCompositeKey; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.serialization.OMemoryStream; -import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper; -import com.orientechnologies.orient.core.serialization.serializer.binary.impl.index.OCompositeKeySerializer; -import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer; -import com.orientechnologies.orient.core.serialization.serializer.record.string.ORecordSerializerStringAbstract; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -/** - * Text based Command Request abstract class. - * - * @author Luca Garulli (l.garulli--(at)--orientdb.com) - */ -@SuppressWarnings("serial") -public abstract class OCommandRequestTextAbstract extends OCommandRequestAbstract - implements OCommandRequestText { - protected String text; - - protected OCommandRequestTextAbstract() {} - - protected OCommandRequestTextAbstract(final String iText) { - if (iText == null) throw new IllegalArgumentException("Text cannot be null"); - - text = iText.trim(); - } - - /** Delegates the execution to the configured command executor. */ - @SuppressWarnings("unchecked") - public RET execute(final Object... iArgs) { - setParameters(iArgs); - - return null; - } - - public String getText() { - return text; - } - - public OCommandRequestText setText(final String iText) { - this.text = iText; - return this; - } - - public OCommandRequestText fromStream(final byte[] iStream, ORecordSerializer serializer) - throws OSerializationException { - final OMemoryStream buffer = new OMemoryStream(iStream); - fromStream(buffer, serializer); - return this; - } - - public byte[] toStream() throws OSerializationException { - final OMemoryStream buffer = new OMemoryStream(); - return toStream(buffer); - } - - @Override - public String toString() { - return "?." + text; - } - - protected byte[] toStream(final OMemoryStream buffer) { - buffer.setUtf8(text); - - if (parameters == null || parameters.size() == 0) { - // simple params are absent - buffer.set(false); - // composite keys are absent - buffer.set(false); - } else { - final Map params = new HashMap(); - final Map> compositeKeyParams = new HashMap>(); - - for (final Entry paramEntry : parameters.entrySet()) - if (paramEntry.getValue() instanceof OCompositeKey) { - final OCompositeKey compositeKey = (OCompositeKey) paramEntry.getValue(); - compositeKeyParams.put(paramEntry.getKey(), compositeKey.getKeys()); - } else params.put(paramEntry.getKey(), paramEntry.getValue()); - - buffer.set(!params.isEmpty()); - if (!params.isEmpty()) { - final ODocument param = new ODocument(); - param.field("parameters", params); - buffer.set(param.toStream()); - } - - buffer.set(!compositeKeyParams.isEmpty()); - if (!compositeKeyParams.isEmpty()) { - final ODocument compositeKey = new ODocument(); - compositeKey.field("compositeKeyParams", compositeKeyParams); - buffer.set(compositeKey.toStream()); - } - } - - return buffer.toByteArray(); - } - - protected void fromStream(final OMemoryStream buffer, ORecordSerializer serializer) { - text = buffer.getAsString(); - - parameters = null; - - final boolean simpleParams = buffer.getAsBoolean(); - if (simpleParams) { - final byte[] paramBuffer = buffer.getAsByteArray(); - final ODocument param = new ODocument(); - if (serializer != null) serializer.fromStream(paramBuffer, param, null); - else param.fromStream(paramBuffer); - - Map params = param.field("params"); - parameters = new HashMap(); - if (params != null) { - for (Entry p : params.entrySet()) { - final Object value; - if (p.getValue() instanceof String) - value = ORecordSerializerStringAbstract.getTypeValue((String) p.getValue()); - else value = p.getValue(); - - if (p.getKey() instanceof String && Character.isDigit(((String) p.getKey()).charAt(0))) - parameters.put(Integer.parseInt((String) p.getKey()), value); - else parameters.put(p.getKey(), value); - } - } else { - params = param.field("parameters"); - for (Entry p : params.entrySet()) { - if (p.getKey() instanceof String && Character.isDigit(((String) p.getKey()).charAt(0))) - parameters.put(Integer.parseInt((String) p.getKey()), p.getValue()); - else parameters.put(p.getKey(), p.getValue()); - } - } - } - - final boolean compositeKeyParamsPresent = buffer.getAsBoolean(); - if (compositeKeyParamsPresent) { - final byte[] paramBuffer = buffer.getAsByteArray(); - final ODocument param = new ODocument(); - if (serializer != null) serializer.fromStream(paramBuffer, param, null); - else param.fromStream(paramBuffer); - - final Map compositeKeyParams = param.field("compositeKeyParams"); - - if (parameters == null) parameters = new HashMap(); - - for (final Entry p : compositeKeyParams.entrySet()) { - if (p.getValue() instanceof List) { - final OCompositeKey compositeKey = new OCompositeKey((List) p.getValue()); - if (p.getKey() instanceof String && Character.isDigit(((String) p.getKey()).charAt(0))) - parameters.put(Integer.parseInt((String) p.getKey()), compositeKey); - else parameters.put(p.getKey(), compositeKey); - - } else { - final Object value = - OCompositeKeySerializer.INSTANCE.deserialize( - OStringSerializerHelper.getBinaryContent(p.getValue()), 0); - - if (p.getKey() instanceof String && Character.isDigit(((String) p.getKey()).charAt(0))) - parameters.put(Integer.parseInt((String) p.getKey()), value); - else parameters.put(p.getKey(), value); - } - } - } - } -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandResultListener.java b/core/src/main/java/com/orientechnologies/orient/core/command/OCommandResultListener.java deleted file mode 100644 index 93d2e043571..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OCommandResultListener.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ -package com.orientechnologies.orient.core.command; - -/** - * Callback interface called when the command returns results. - * - * @author Luca Garulli (l.garulli--(at)--orientdb.com) - */ -public interface OCommandResultListener { - /** - * This method is called for each result. - * - * @param iRecord Current record - * @return True to continue the query, otherwise false - */ - boolean result(Object iRecord); - - /** Called at the end of processing. This is useful to clean-up local attributes. */ - void end(); - - Object getResult(); -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/ODocumentEqualityWrapper.java b/core/src/main/java/com/orientechnologies/orient/core/command/ODocumentEqualityWrapper.java deleted file mode 100755 index 186e1536ceb..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/command/ODocumentEqualityWrapper.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.orientechnologies.orient.core.command; - -import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; -import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.record.impl.ODocumentHelper; - -/** This class is designed to compare documents based on deep equality (to be used in Sets) */ -public class ODocumentEqualityWrapper { - private final ODocument internal; - - ODocumentEqualityWrapper(ODocument internal) { - - this.internal = internal; - } - - public boolean equals(Object obj) { - if (obj instanceof ODocumentEqualityWrapper) { - ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.instance().getIfDefined(); - return ODocumentHelper.hasSameContentOf( - internal, db, ((ODocumentEqualityWrapper) obj).internal, db, null); - } - return false; - } - - @Override - public int hashCode() { - int result = 0; - for (String fieldName : internal.fieldNames()) { - result += fieldName.hashCode(); - Object value = internal.field(fieldName); - if (value != null) { - result += value.hashCode(); - } - } - return result; - } -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/OSqlScriptExecutor.java b/core/src/main/java/com/orientechnologies/orient/core/command/OSqlScriptExecutor.java index 39d72be7ccf..53a4edecf9a 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/command/OSqlScriptExecutor.java +++ b/core/src/main/java/com/orientechnologies/orient/core/command/OSqlScriptExecutor.java @@ -1,11 +1,13 @@ package com.orientechnologies.orient.core.command; -import com.orientechnologies.orient.core.command.script.OCommandExecutorFunction; -import com.orientechnologies.orient.core.command.script.OCommandFunction; -import com.orientechnologies.orient.core.command.traverse.OAbstractScriptExecutor; +import com.orientechnologies.orient.core.command.script.OAbstractScriptExecutor; +import com.orientechnologies.orient.core.command.script.OScriptManager; import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; import com.orientechnologies.orient.core.exception.OCommandExecutionException; +import com.orientechnologies.orient.core.metadata.function.OFunction; +import com.orientechnologies.orient.core.metadata.security.ORole; +import com.orientechnologies.orient.core.metadata.security.ORule; import com.orientechnologies.orient.core.sql.OCommandSQLParsingException; import com.orientechnologies.orient.core.sql.OSQLEngine; import com.orientechnologies.orient.core.sql.executor.OResultSet; @@ -139,8 +141,11 @@ public Object executeFunction( db = ODatabaseRecordThreadLocal.instance().get(); } - final OCommandExecutorFunction command = new OCommandExecutorFunction(); - command.parse(new OCommandFunction(functionName)); - return command.executeInContext(context, iArgs); + OFunction function = db.getMetadata().getFunctionLibrary().getFunction(functionName); + + db.checkSecurity(ORule.ResourceGeneric.FUNCTION, ORole.PERMISSION_READ, function.getName()); + final OScriptManager scriptManager = db.getSharedContext().getOrientDB().getScriptManager(); + final Object[] args = iArgs == null ? null : iArgs.values().toArray(); + return execute(db, scriptManager.getFunctionInvoke(function, args), iArgs); } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/traverse/OAbstractScriptExecutor.java b/core/src/main/java/com/orientechnologies/orient/core/command/script/OAbstractScriptExecutor.java similarity index 94% rename from core/src/main/java/com/orientechnologies/orient/core/command/traverse/OAbstractScriptExecutor.java rename to core/src/main/java/com/orientechnologies/orient/core/command/script/OAbstractScriptExecutor.java index 5afcf1123c5..b7a464f97ae 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/command/traverse/OAbstractScriptExecutor.java +++ b/core/src/main/java/com/orientechnologies/orient/core/command/script/OAbstractScriptExecutor.java @@ -1,4 +1,4 @@ -package com.orientechnologies.orient.core.command.traverse; +package com.orientechnologies.orient.core.command.script; import com.orientechnologies.orient.core.command.OScriptExecutor; import com.orientechnologies.orient.core.command.OScriptInterceptor; diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/script/OCommandExecutorFunction.java b/core/src/main/java/com/orientechnologies/orient/core/command/script/OCommandExecutorFunction.java deleted file mode 100755 index b1a0788da57..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/command/script/OCommandExecutorFunction.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ -package com.orientechnologies.orient.core.command.script; - -import com.orientechnologies.common.exception.OException; -import com.orientechnologies.common.util.OCommonConst; -import com.orientechnologies.orient.core.command.OCommandContext; -import com.orientechnologies.orient.core.command.OCommandExecutorAbstract; -import com.orientechnologies.orient.core.command.OCommandRequest; -import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; -import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; -import com.orientechnologies.orient.core.metadata.function.OFunction; -import com.orientechnologies.orient.core.metadata.security.ORole; -import com.orientechnologies.orient.core.metadata.security.ORule; -import java.util.Map; -import java.util.Map.Entry; -import javax.script.Bindings; -import javax.script.Invocable; -import javax.script.ScriptContext; -import javax.script.ScriptEngine; -import javax.script.ScriptException; - -/** - * Executes Script Commands. - * - * @author Luca Garulli (l.garulli--(at)--orientdb.com) - */ -public class OCommandExecutorFunction extends OCommandExecutorAbstract { - protected OCommandFunction request; - - public OCommandExecutorFunction() {} - - @SuppressWarnings("unchecked") - public OCommandExecutorFunction parse(final OCommandRequest iRequest) { - request = (OCommandFunction) iRequest; - return this; - } - - public Object execute(final Map iArgs) { - return executeInContext(null, iArgs); - } - - public Object executeInContext(final OCommandContext iContext, final Map iArgs) { - - parserText = request.getText(); - - ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.instance().get(); - final OFunction f = db.getMetadata().getFunctionLibrary().getFunction(parserText); - - db.checkSecurity(ORule.ResourceGeneric.FUNCTION, ORole.PERMISSION_READ, f.getName()); - - final OScriptManager scriptManager = db.getSharedContext().getOrientDB().getScriptManager(); - - final ScriptEngine scriptEngine = - scriptManager.acquireDatabaseEngine(db.getName(), f.getLanguage()); - try { - final Bindings binding = - scriptManager.bind( - scriptEngine, - scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE), - db, - iContext, - iArgs); - - try { - final Object result; - - if (scriptEngine instanceof Invocable) { - // INVOKE AS FUNCTION. PARAMS ARE PASSED BY POSITION - final Invocable invocableEngine = (Invocable) scriptEngine; - Object[] args = null; - if (iArgs != null) { - args = new Object[iArgs.size()]; - int i = 0; - for (Entry arg : iArgs.entrySet()) args[i++] = arg.getValue(); - } else { - args = OCommonConst.EMPTY_OBJECT_ARRAY; - } - result = invocableEngine.invokeFunction(parserText, args); - - } else { - // INVOKE THE CODE SNIPPET - final Object[] args = iArgs == null ? null : iArgs.values().toArray(); - result = scriptEngine.eval(scriptManager.getFunctionInvoke(f, args), binding); - } - return OCommandExecutorUtility.transformResult( - scriptManager.handleResult(f.getLanguage(), result, scriptEngine, binding, db)); - - } catch (ScriptException e) { - throw OException.wrapException( - new OCommandScriptException( - "Error on execution of the script", request.getText(), e.getColumnNumber()), - e); - } catch (NoSuchMethodException e) { - throw OException.wrapException( - new OCommandScriptException("Error on execution of the script", request.getText(), 0), - e); - } catch (OCommandScriptException e) { - // PASS THROUGH - throw e; - - } finally { - scriptManager.unbind(scriptEngine, binding, iContext, iArgs); - } - } finally { - scriptManager.releaseDatabaseEngine(f.getLanguage(), db.getName(), scriptEngine); - } - } - - public boolean isIdempotent() { - return false; - } - - @Override - protected void throwSyntaxErrorException(String iText) { - throw new OCommandScriptException( - "Error on execution of the script: " + iText, request.getText(), 0); - } -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/script/OCommandFunction.java b/core/src/main/java/com/orientechnologies/orient/core/command/script/OCommandFunction.java deleted file mode 100644 index 545ee80e512..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/command/script/OCommandFunction.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ -package com.orientechnologies.orient.core.command.script; - -import com.orientechnologies.orient.core.command.OCommandRequestTextAbstract; - -/** - * Execute a configured function. - * - * @see OCommandExecutorFunction - * @author Luca Garulli (l.garulli--(at)--orientdb.com) - */ -public class OCommandFunction extends OCommandRequestTextAbstract { - private static final long serialVersionUID = 1L; - - public OCommandFunction() {} - - public OCommandFunction(final String iName) { - super(iName); - } - - public boolean isIdempotent() { - return false; - } - - @Override - public String toString() { - return "function." + text; - } -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/script/OCommandScript.java b/core/src/main/java/com/orientechnologies/orient/core/command/script/OCommandScript.java deleted file mode 100755 index a8ad2b75e03..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/command/script/OCommandScript.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ -package com.orientechnologies.orient.core.command.script; - -import com.orientechnologies.orient.core.command.OCommandDistributedReplicateRequest; -import com.orientechnologies.orient.core.command.OCommandRequestText; -import com.orientechnologies.orient.core.command.OCommandRequestTextAbstract; -import com.orientechnologies.orient.core.exception.OSerializationException; -import com.orientechnologies.orient.core.serialization.OMemoryStream; -import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer; -import javax.script.CompiledScript; - -/** - * Script command request implementation. It just stores the request and delegated the execution to - * the configured OCommandExecutor. - * - * @see OCommandExecutorScript - * @author Luca Garulli (l.garulli--(at)--orientdb.com) - */ -@SuppressWarnings("serial") -public class OCommandScript extends OCommandRequestTextAbstract { - private String language; - private CompiledScript compiledScript; - - private OCommandDistributedReplicateRequest.DISTRIBUTED_EXECUTION_MODE executionMode = - OCommandDistributedReplicateRequest.DISTRIBUTED_EXECUTION_MODE.LOCAL; - - public OCommandScript() { - useCache = true; - } - - public OCommandScript(final String iLanguage, final String iText) { - super(iText); - setLanguage(iLanguage); - useCache = true; - } - - public OCommandScript(final String iText) { - this("sql", iText); - } - - public boolean isIdempotent() { - return false; - } - - public String getLanguage() { - return language; - } - - public OCommandScript setLanguage(String language) { - if (language == null || language.isEmpty()) { - throw new IllegalArgumentException("Not a valid script language specified: " + language); - } - this.language = language; - return this; - } - - public OCommandRequestText fromStream(byte[] iStream, ORecordSerializer serializer) - throws OSerializationException { - final OMemoryStream buffer = new OMemoryStream(iStream); - language = buffer.getAsString(); - - // FIX TO HANDLE USAGE OF EXECUTION MODE STARTING FROM v2.1.3 - final int currPosition = buffer.getPosition(); - final String value = buffer.getAsString(); - try { - executionMode = OCommandDistributedReplicateRequest.DISTRIBUTED_EXECUTION_MODE.valueOf(value); - } catch (IllegalArgumentException ignore) { - // OLD VERSION: RESET TO THE OLD POSITION - buffer.setPosition(currPosition); - } - - fromStream(buffer, serializer); - return this; - } - - public byte[] toStream() throws OSerializationException { - final OMemoryStream buffer = new OMemoryStream(); - buffer.setUtf8(language); - buffer.setUtf8(executionMode.name()); - return toStream(buffer); - } - - public CompiledScript getCompiledScript() { - return compiledScript; - } - - public void setCompiledScript(CompiledScript script) { - compiledScript = script; - } - - @Override - public String toString() { - if (language != null) return language + "." + text; - return "script." + text; - } - - public OCommandDistributedReplicateRequest.DISTRIBUTED_EXECUTION_MODE getExecutionMode() { - return executionMode; - } - - public OCommandScript setExecutionMode( - OCommandDistributedReplicateRequest.DISTRIBUTED_EXECUTION_MODE executionMode) { - this.executionMode = executionMode; - return this; - } -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/script/OJsr223ScriptExecutor.java b/core/src/main/java/com/orientechnologies/orient/core/command/script/OJsr223ScriptExecutor.java index e5761e7cc2b..5352e1f31a7 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/command/script/OJsr223ScriptExecutor.java +++ b/core/src/main/java/com/orientechnologies/orient/core/command/script/OJsr223ScriptExecutor.java @@ -4,7 +4,6 @@ import com.orientechnologies.common.util.OCommonConst; import com.orientechnologies.orient.core.command.OCommandContext; import com.orientechnologies.orient.core.command.script.transformer.OScriptTransformer; -import com.orientechnologies.orient.core.command.traverse.OAbstractScriptExecutor; import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; import com.orientechnologies.orient.core.exception.OCommandExecutionException; diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/script/OPolyglotScriptExecutor.java b/core/src/main/java/com/orientechnologies/orient/core/command/script/OPolyglotScriptExecutor.java index c108b390c4f..b7004a1fe29 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/command/script/OPolyglotScriptExecutor.java +++ b/core/src/main/java/com/orientechnologies/orient/core/command/script/OPolyglotScriptExecutor.java @@ -6,7 +6,6 @@ import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.orient.core.command.OCommandContext; import com.orientechnologies.orient.core.command.script.transformer.OScriptTransformer; -import com.orientechnologies.orient.core.command.traverse.OAbstractScriptExecutor; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; diff --git a/core/src/main/java/com/orientechnologies/orient/core/command/script/OScriptManager.java b/core/src/main/java/com/orientechnologies/orient/core/command/script/OScriptManager.java index 6b1f173717f..52051d5dea6 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/command/script/OScriptManager.java +++ b/core/src/main/java/com/orientechnologies/orient/core/command/script/OScriptManager.java @@ -42,8 +42,6 @@ import com.orientechnologies.orient.core.exception.OConfigurationException; import com.orientechnologies.orient.core.metadata.function.OFunction; import com.orientechnologies.orient.core.metadata.function.OFunctionUtilWrapper; -import com.orientechnologies.orient.core.sql.OSQLScriptEngine; -import com.orientechnologies.orient.core.sql.OSQLScriptEngineFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -81,25 +79,11 @@ public class OScriptManager { new ConcurrentHashMap(); protected Map handlers = new HashMap(); - protected Map> executorsFactories = new HashMap<>(); protected OCommandManager commandManager = new OCommandManager(); public OScriptManager() { scriptEngineManager = new ScriptEngineManager(); - final boolean useGraal = OGlobalConfiguration.SCRIPT_POLYGLOT_USE_GRAAL.getValueAsBoolean(); - executorsFactories.put( - "javascript", - (lang) -> - useGraal - ? new OPolyglotScriptExecutor(lang, new OScriptTransformerImpl()) - : new OJsr223ScriptExecutor(lang, new OScriptTransformerImpl())); - executorsFactories.put( - "ecmascript", - (lang) -> - useGraal - ? new OPolyglotScriptExecutor(lang, new OScriptTransformerImpl()) - : new OJsr223ScriptExecutor(lang, new OScriptTransformerImpl())); for (ScriptEngineFactory f : scriptEngineManager.getEngineFactories()) { registerEngine(f.getLanguageName().toLowerCase(Locale.ENGLISH), f); @@ -125,10 +109,24 @@ public OScriptManager() { } } - registerFormatter(OSQLScriptEngine.NAME, new OSQLScriptFormatter()); + registerFormatter("sql", new OSQLScriptFormatter()); registerFormatter(DEF_LANGUAGE, new OJSScriptFormatter()); registerFormatter("ruby", new ORubyScriptFormatter()); registerFormatter("groovy", new OGroovyScriptFormatter()); + Map> executorsFactories = new HashMap<>(); + + executorsFactories.put( + "javascript", + (lang) -> + useGraal + ? new OPolyglotScriptExecutor(lang, new OScriptTransformerImpl()) + : new OJsr223ScriptExecutor(lang, new OScriptTransformerImpl())); + executorsFactories.put( + "ecmascript", + (lang) -> + useGraal + ? new OPolyglotScriptExecutor(lang, new OScriptTransformerImpl()) + : new OJsr223ScriptExecutor(lang, new OScriptTransformerImpl())); for (String lang : engines.keySet()) { Function factory = executorsFactories.get(lang); OScriptExecutor executor = null; @@ -140,9 +138,6 @@ public OScriptManager() { commandManager.registerScriptExecutor(lang, executor); } - // Registring sql script engine after for not fight with the basic engine - registerEngine(OSQLScriptEngine.NAME, new OSQLScriptEngineFactory()); - Iterator customExecutors = lookupProviderWithOrientClassLoader(OScriptExecutorRegister.class); diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseListener.java b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseListener.java index 159d08f70bd..afa05467d59 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseListener.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseListener.java @@ -19,8 +19,6 @@ */ package com.orientechnologies.orient.core.db; -import com.orientechnologies.orient.core.command.OCommandExecutor; -import com.orientechnologies.orient.core.command.OCommandRequestText; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OView; import com.orientechnologies.orient.core.sql.executor.OResultSet; @@ -53,11 +51,6 @@ public interface ODatabaseListener { void onClose(final ODatabase iDatabase); - void onBeforeCommand(final OCommandRequestText iCommand, final OCommandExecutor executor); - - void onAfterCommand( - final OCommandRequestText iCommand, final OCommandExecutor executor, Object result); - default void onCreateClass(ODatabase iDatabase, OClass iClass) {} default void onDropClass(ODatabase iDatabase, OClass iClass) {} diff --git a/core/src/main/java/com/orientechnologies/orient/core/query/OQueryHelper.java b/core/src/main/java/com/orientechnologies/orient/core/query/OQueryHelper.java deleted file mode 100644 index e7aab2a7bd1..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/query/OQueryHelper.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ -package com.orientechnologies.orient.core.query; - -import java.util.Locale; - -public class OQueryHelper { - protected static final String WILDCARD_ANYCHAR = "?"; - protected static final String WILDCARD_ANY = "%"; - - public static boolean like(String currentValue, String iValue) { - if (currentValue == null - || currentValue.length() == 0 - || iValue == null - || iValue.length() == 0) - // EMPTY/NULL PARAMETERS - return false; - - iValue = iValue.toLowerCase(Locale.ENGLISH); - currentValue = currentValue.toLowerCase(Locale.ENGLISH); - - iValue = iValue.replace("\\", "\\\\"); - iValue = iValue.replace("[", "\\["); - iValue = iValue.replace("]", "\\]"); - iValue = iValue.replace("{", "\\{"); - iValue = iValue.replace("}", "\\}"); - iValue = iValue.replace("(", "\\("); - iValue = iValue.replace(")", "\\)"); - iValue = iValue.replace("|", "\\|"); - iValue = iValue.replace("*", "\\*"); - iValue = iValue.replace("+", "\\+"); - iValue = iValue.replace("$", "\\$"); - iValue = iValue.replace("^", "\\^"); - iValue = iValue.replace(".", "\\."); - iValue = iValue.replace(WILDCARD_ANY, ".*"); - iValue = iValue.replace(WILDCARD_ANYCHAR, "."); - - return currentValue.matches(iValue); - } -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OChainedIndexProxy.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OChainedIndexProxy.java deleted file mode 100755 index 73b548bcab4..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OChainedIndexProxy.java +++ /dev/null @@ -1,649 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ -package com.orientechnologies.orient.core.sql; - -import com.orientechnologies.common.listener.OProgressListener; -import com.orientechnologies.common.profiler.OProfiler; -import com.orientechnologies.common.profiler.OProfilerStub; -import com.orientechnologies.common.util.ORawPair; -import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.db.record.OIdentifiable; -import com.orientechnologies.orient.core.id.ORID; -import com.orientechnologies.orient.core.index.OIndex; -import com.orientechnologies.orient.core.index.OIndexCursor; -import com.orientechnologies.orient.core.index.OIndexDefinition; -import com.orientechnologies.orient.core.index.OIndexInternal; -import com.orientechnologies.orient.core.index.OIndexKeyCursor; -import com.orientechnologies.orient.core.index.OIndexMetadata; -import com.orientechnologies.orient.core.metadata.schema.OClass; -import com.orientechnologies.orient.core.metadata.schema.OType; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.tx.OTransactionIndexChangesPerKey; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -/** - * There are some cases when we need to create index for some class by traversed property. - * Unfortunately, such functionality is not supported yet. But we can do that by creating index for - * each element of (which define "way" to our property), and - * then process operations consequently using previously created indexes. - * - *

This class provides possibility to find optimal chain of indexes and then use it just like it - * was index for traversed property. - * - *

IMPORTANT: this class is only for internal usage! - * - * @author Artem Orobets - */ -@SuppressWarnings({"unchecked", "rawtypes"}) -public class OChainedIndexProxy implements OIndexInternal { - private final OIndex firstIndex; - - private final List indexChain; - private final OIndex lastIndex; - - private OChainedIndexProxy(List indexChain) { - this.firstIndex = indexChain.get(0); - this.indexChain = Collections.unmodifiableList(indexChain); - lastIndex = indexChain.get(indexChain.size() - 1); - } - - private static boolean isComposite(OIndex currentIndex) { - return currentIndex.getDefinition().getParamCount() > 1; - } - - /** - * Finds the index that fits better as a base index in chain. Requirements to the base index: - * - *

    - *
  • Should be unique or not unique. Other types cannot be used to get all documents with - * required links. - *
  • Should not be composite hash index. As soon as hash index does not support partial match - * search. - *
  • Composite index that ignores null values should not be used. - *
  • Hash index is better than tree based indexes. - *
  • Non composite indexes is better that composite. - *
- * - * @param indexes where search - * @return the index that fits better as a base index in chain - */ - protected static OIndex findBestIndex(Iterable indexes) { - OIndex bestIndex = null; - for (OIndex index : indexes) { - if (priorityOfUsage(index) > priorityOfUsage(bestIndex)) bestIndex = index; - } - return bestIndex; - } - - private static int priorityOfUsage(OIndex index) { - if (index == null) return -1; - - final OClass.INDEX_TYPE indexType = OClass.INDEX_TYPE.valueOf(index.getType()); - final boolean isComposite = isComposite(index); - final boolean supportNullValues = supportNullValues(index); - - int priority = 1; - - if (isComposite) { - if (!supportNullValues) return -1; - } else { - priority += 10; - } - - switch (indexType) { - case UNIQUE_HASH_INDEX: - case NOTUNIQUE_HASH_INDEX: - if (isComposite) return -1; - else priority += 10; - break; - case UNIQUE: - case NOTUNIQUE: - priority += 5; - break; - case PROXY: - case FULLTEXT: - //noinspection deprecation - case DICTIONARY: - case DICTIONARY_HASH_INDEX: - case SPATIAL: - return -1; - } - - return priority; - } - - /** - * Checks if index can be used as base index. Requirements to the base index: - * - *
    - *
  • Should be unique or not unique. Other types cannot be used to get all documents with - * required links. - *
  • Should not be composite hash index. As soon as hash index does not support partial match - * search. - *
  • Composite index that ignores null values should not be used. - *
- * - * @param index to check - * @return true if index usage is allowed as base index. - */ - public static boolean isAppropriateAsBase(OIndex index) { - return priorityOfUsage(index) > 0; - } - - private static boolean supportNullValues(OIndex index) { - final ODocument metadata = index.getMetadata(); - if (metadata == null) return false; - - final Boolean ignoreNullValues = metadata.field("ignoreNullValues"); - return Boolean.FALSE.equals(ignoreNullValues); - } - - public String getDatabaseName() { - return firstIndex.getDatabaseName(); - } - - public List getIndexNames() { - final ArrayList names = new ArrayList<>(indexChain.size()); - for (OIndex oIndex : indexChain) { - names.add(oIndex.getName()); - } - - return names; - } - - @Override - public String getName() { - final StringBuilder res = new StringBuilder("IndexChain{"); - final List indexNames = getIndexNames(); - - for (int i = 0; i < indexNames.size(); i++) { - String indexName = indexNames.get(i); - if (i > 0) res.append(", "); - res.append(indexName); - } - - res.append("}"); - - return res.toString(); - } - - /** {@inheritDoc} */ - @Override - @Deprecated - public T get(Object key) { - final List lastIndexResult; - try (Stream stream = lastIndex.getInternal().getRids(key)) { - lastIndexResult = stream.collect(Collectors.toList()); - } - - final Set result = new HashSet<>(applyTailIndexes(lastIndexResult)); - return (T) result; - } - - @Override - public Stream getRidsIgnoreTx(Object key) { - final List lastIndexResult; - try (Stream stream = lastIndex.getInternal().getRids(key)) { - lastIndexResult = stream.collect(Collectors.toList()); - } - - final Set result = new HashSet<>(applyTailIndexes(lastIndexResult)); - return result.stream().map(OIdentifiable::getIdentity); - } - - @Override - public Stream getRids(Object key) { - final List lastIndexResult; - try (Stream stream = lastIndex.getInternal().getRids(key)) { - lastIndexResult = stream.collect(Collectors.toList()); - } - - final Set result = new HashSet<>(applyTailIndexes(lastIndexResult)); - return result.stream().map(OIdentifiable::getIdentity); - } - - /** - * Returns internal index of last chain index, because proxy applicable to all operations that - * last index applicable. - */ - public OIndexInternal getInternal() { - return this; - } - - /** {@inheritDoc} */ - public OIndexDefinition getDefinition() { - return lastIndex.getDefinition(); - } - - private List applyTailIndexes(final Object lastIndexResult) { - final OIndex beforeTheLastIndex = indexChain.get(indexChain.size() - 2); - Set currentKeys = prepareKeys(beforeTheLastIndex, lastIndexResult); - - for (int j = indexChain.size() - 2; j > 0; j--) { - final OIndex currentIndex = indexChain.get(j); - final OIndex nextIndex = indexChain.get(j - 1); - - final Set newKeys; - if (isComposite(currentIndex)) { - //noinspection ObjectAllocationInLoop - newKeys = new TreeSet<>(); - for (Comparable currentKey : currentKeys) { - final List currentResult = getFromCompositeIndex(currentKey, currentIndex); - newKeys.addAll(prepareKeys(nextIndex, currentResult)); - } - } else { - final List keys; - try (Stream> stream = - currentIndex.getInternal().streamEntries(currentKeys, true)) { - keys = stream.map((pair) -> pair.second).collect(Collectors.toList()); - } - newKeys = prepareKeys(nextIndex, keys); - } - - updateStatistic(currentIndex); - - currentKeys = newKeys; - } - - return applyFirstIndex(currentKeys); - } - - private List applyFirstIndex(Collection currentKeys) { - final List result; - if (isComposite(firstIndex)) { - result = new ArrayList<>(); - for (Comparable key : currentKeys) { - result.addAll(getFromCompositeIndex(key, firstIndex)); - } - } else { - try (Stream> stream = - firstIndex.getInternal().streamEntries(currentKeys, true)) { - result = stream.map((pair) -> pair.second).collect(Collectors.toList()); - } - } - - updateStatistic(firstIndex); - - return result; - } - - private static List getFromCompositeIndex(Comparable currentKey, OIndex currentIndex) { - try (Stream> stream = - currentIndex.getInternal().streamEntriesBetween(currentKey, true, currentKey, true, true)) { - return stream.map((pair) -> pair.second).collect(Collectors.toList()); - } - } - - /** - * Make type conversion of keys for specific index. - * - * @param index - index for which keys prepared for. - * @param keys - which should be prepared. - * @return keys converted to necessary type. - */ - private static Set prepareKeys(OIndex index, Object keys) { - final OIndexDefinition indexDefinition = index.getDefinition(); - if (keys instanceof Collection) { - final Set newKeys = new TreeSet<>(); - for (Object o : ((Collection) keys)) { - newKeys.add((Comparable) indexDefinition.createValue(o)); - } - return newKeys; - } else { - return Collections.singleton((Comparable) indexDefinition.createValue(keys)); - } - } - - /** - * Register statistic information about usage of index in {@link OProfilerStub}. - * - * @param index which usage is registering. - */ - private static void updateStatistic(OIndex index) { - - final OProfiler profiler = Orient.instance().getProfiler(); - if (profiler.isRecording()) { - Orient.instance() - .getProfiler() - .updateCounter( - profiler.getDatabaseMetric(index.getDatabaseName(), "query.indexUsed"), - "Used index in query", - +1); - - final int paramCount = index.getDefinition().getParamCount(); - if (paramCount > 1) { - final String profiler_prefix = - profiler.getDatabaseMetric(index.getDatabaseName(), "query.compositeIndexUsed"); - profiler.updateCounter(profiler_prefix, "Used composite index in query", +1); - profiler.updateCounter( - profiler_prefix + "." + paramCount, - "Used composite index in query with " + paramCount + " params", - +1); - } - } - } - - // - // Following methods are not allowed for proxy. - // - - @Override - public OIndex create( - OIndexMetadata indexMetadat, boolean rebuild, OProgressListener progressListener) { - throw new UnsupportedOperationException("Not allowed operation"); - } - - public OType[] getKeyTypes() { - throw new UnsupportedOperationException("Not allowed operation"); - } - - public Iterator> iterator() { - throw new UnsupportedOperationException("Not allowed operation"); - } - - public OIndex put(Object key, OIdentifiable value) { - throw new UnsupportedOperationException("Not allowed operation"); - } - - public boolean remove(Object key) { - throw new UnsupportedOperationException("Not allowed operation"); - } - - public boolean remove(Object key, OIdentifiable rid) { - throw new UnsupportedOperationException("Not allowed operation"); - } - - /** - * {@inheritDoc} - * - * @deprecated Manual indexes are deprecated and will be removed - */ - @Deprecated - @Override - public OIndex clear() { - throw new UnsupportedOperationException("Not allowed operation"); - } - - @Override - public long getSize() { - throw new UnsupportedOperationException(); - } - - @Override - public long count(Object iKey) { - throw new UnsupportedOperationException(); - } - - @Override - public long getKeySize() { - throw new UnsupportedOperationException(); - } - - @Override - public void flush() {} - - @Override - public long getRebuildVersion() { - return 0; - } - - @Override - public boolean isRebuilding() { - return false; - } - - @Override - public Object getFirstKey() { - throw new UnsupportedOperationException(); - } - - @Override - public Object getLastKey() { - throw new UnsupportedOperationException(); - } - - @Override - public OIndexCursor cursor() { - throw new UnsupportedOperationException(); - } - - @Override - public OIndexCursor descCursor() { - throw new UnsupportedOperationException(); - } - - @Override - public OIndexKeyCursor keyCursor() { - throw new UnsupportedOperationException(); - } - - @Override - public Object getCollatingValue(Object key) { - return this.lastIndex.getInternal().getCollatingValue(key); - } - - @Override - public boolean loadFromConfiguration(ODocument iConfig) { - throw new UnsupportedOperationException(); - } - - @Override - public ODocument updateConfiguration() { - throw new UnsupportedOperationException(); - } - - @Override - public OIndex addCluster(String iClusterName) { - throw new UnsupportedOperationException(); - } - - @Override - public OIndex removeCluster(String iClusterName) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean canBeUsedInEqualityOperators() { - return this.lastIndex.getInternal().canBeUsedInEqualityOperators(); - } - - @Override - public boolean hasRangeQuerySupport() { - return this.lastIndex.getInternal().hasRangeQuerySupport(); - } - - @Override - public OIndexMetadata loadMetadata(ODocument iConfig) { - throw new UnsupportedOperationException(); - } - - @Override - public void close() { - throw new UnsupportedOperationException(); - } - - @Override - public String getIndexNameByKey(Object key) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean acquireAtomicExclusiveLock(Object key) { - throw new UnsupportedOperationException(); - } - - public long size() { - throw new UnsupportedOperationException("Not allowed operation"); - } - - public OIndex delete() { - throw new UnsupportedOperationException("Not allowed operation"); - } - - public String getType() { - return lastIndex.getType(); - } - - @Override - public String getAlgorithm() { - return lastIndex.getAlgorithm(); - } - - public boolean isAutomatic() { - throw new UnsupportedOperationException("Not allowed operation"); - } - - public long rebuild() { - throw new UnsupportedOperationException("Not allowed operation"); - } - - public long rebuild(OProgressListener iProgressListener) { - throw new UnsupportedOperationException("Not allowed operation"); - } - - public ODocument getConfiguration() { - throw new UnsupportedOperationException("Not allowed operation"); - } - - @Override - public ODocument getMetadata() { - throw new UnsupportedOperationException("Not allowed operation"); - } - - public Set getClusters() { - throw new UnsupportedOperationException("Not allowed operation"); - } - - @Override - public OIndexCursor iterateEntries(Collection keys, boolean ascSortOrder) { - return null; - } - - @Override - public OIndexCursor iterateEntriesBetween( - Object fromKey, boolean fromInclusive, Object toKey, boolean toInclusive, boolean ascOrder) { - return null; - } - - @Override - public OIndexCursor iterateEntriesMajor(Object fromKey, boolean fromInclusive, boolean ascOrder) { - return null; - } - - @Override - public OIndexCursor iterateEntriesMinor(Object toKey, boolean toInclusive, boolean ascOrder) { - return null; - } - - @Override - public int getIndexId() { - throw new UnsupportedOperationException("Not allowed operation"); - } - - @Override - public boolean isUnique() { - return firstIndex.isUnique(); - } - - @Override - public Stream> stream() { - throw new UnsupportedOperationException("Not allowed operation"); - } - - @Override - public Stream> descStream() { - throw new UnsupportedOperationException("Not allowed operation"); - } - - @Override - public Stream keyStream() { - throw new UnsupportedOperationException("Not allowed operation"); - } - - @Override - public int getVersion() { - throw new UnsupportedOperationException("Not allowed operation"); - } - - public boolean supportsOrderedIterations() { - return false; - } - - @Override - public Stream> streamEntries(Collection keys, boolean ascSortOrder) { - return applyTailIndexes(lastIndex.getInternal().streamEntries(keys, ascSortOrder)); - } - - @Override - public Stream> streamEntriesBetween( - Object fromKey, boolean fromInclusive, Object toKey, boolean toInclusive, boolean ascOrder) { - return applyTailIndexes( - lastIndex - .getInternal() - .streamEntriesBetween(fromKey, fromInclusive, toKey, toInclusive, ascOrder)); - } - - @Override - public Stream> streamEntriesMajor( - Object fromKey, boolean fromInclusive, boolean ascOrder) { - return applyTailIndexes( - lastIndex.getInternal().streamEntriesMajor(fromKey, fromInclusive, ascOrder)); - } - - @Override - public Stream> streamEntriesMinor( - Object toKey, boolean toInclusive, boolean ascOrder) { - return applyTailIndexes( - lastIndex.getInternal().streamEntriesMinor(toKey, toInclusive, ascOrder)); - } - - @Override - public boolean isNativeTxSupported() { - return false; - } - - @Override - public Iterable interpretTxKeyChanges( - OTransactionIndexChangesPerKey changes) { - throw new UnsupportedOperationException("Not allowed operation"); - } - - private Stream> applyTailIndexes( - Stream> indexStream) { - //noinspection resource - return indexStream.flatMap( - (entry) -> applyTailIndexes(entry.second).stream().map((rid) -> new ORawPair<>(null, rid))); - } - - @Override - public int compareTo(OIndex o) { - throw new UnsupportedOperationException(); - } -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OSQLEngine.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OSQLEngine.java index 43b370738ce..731827f3442 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OSQLEngine.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/OSQLEngine.java @@ -31,10 +31,11 @@ import com.orientechnologies.orient.core.collate.OCollate; import com.orientechnologies.orient.core.collate.OCollateFactory; import com.orientechnologies.orient.core.command.OCommandContext; -import com.orientechnologies.orient.core.command.OCommandExecutorAbstract; import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; +import com.orientechnologies.orient.core.db.OExecutionThreadLocal; import com.orientechnologies.orient.core.db.OrientDBInternal; import com.orientechnologies.orient.core.db.record.OIdentifiable; +import com.orientechnologies.orient.core.exception.OCommandInterruptedException; import com.orientechnologies.orient.core.sql.executor.OResult; import com.orientechnologies.orient.core.sql.functions.OSQLFunction; import com.orientechnologies.orient.core.sql.functions.OSQLFunctionFactory; @@ -282,7 +283,8 @@ public static Object foreachRecord( final OCommandContext iContext) { if (iCurrent == null) return null; - if (!OCommandExecutorAbstract.checkInterruption(iContext)) return null; + if (OExecutionThreadLocal.isInterruptCurrentOperation()) + throw new OCommandInterruptedException("The command has been interrupted"); if (iCurrent instanceof Iterable && !(iCurrent instanceof OIdentifiable)) { iCurrent = ((Iterable) iCurrent).iterator(); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OSQLScriptEngine.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OSQLScriptEngine.java deleted file mode 100644 index c9f41997f20..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OSQLScriptEngine.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ - -package com.orientechnologies.orient.core.sql; - -import com.orientechnologies.orient.core.command.script.OCommandScript; -import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; -import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; -import com.orientechnologies.orient.core.db.record.OIdentifiable; -import com.orientechnologies.orient.core.exception.OCommandExecutionException; -import com.orientechnologies.orient.core.sql.executor.OResultSet; -import com.orientechnologies.orient.core.sql.query.OBasicLegacyResultSet; -import com.orientechnologies.orient.core.sql.query.OLegacyResultSet; -import java.io.IOException; -import java.io.Reader; -import java.util.HashMap; -import java.util.Map; -import javax.script.Bindings; -import javax.script.ScriptContext; -import javax.script.ScriptEngine; -import javax.script.ScriptEngineFactory; -import javax.script.ScriptException; -import javax.script.SimpleBindings; - -/** - * Dynamic script engine for OrientDB SQL commands. This implementation is multi-threads. - * - * @author Luca Garulli (l.garulli--(at)--orientdb.com) - */ -public class OSQLScriptEngine implements ScriptEngine { - - public static final String NAME = "sql"; - private ScriptEngineFactory factory; - - public OSQLScriptEngine(ScriptEngineFactory factory) { - this.factory = factory; - } - - @Override - public Object eval(String script, ScriptContext context) throws ScriptException { - return eval(script, (Bindings) null); - } - - @Override - public Object eval(Reader reader, ScriptContext context) throws ScriptException { - return eval(reader, (Bindings) null); - } - - @Override - public Object eval(String script) throws ScriptException { - return eval(script, (Bindings) null); - } - - @Override - public Object eval(Reader reader) throws ScriptException { - return eval(reader, (Bindings) null); - } - - @Override - public Object eval(String script, Bindings n) throws ScriptException { - ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.instance().getIfDefined(); - if (db == null) { - throw new OCommandExecutionException("No database available in threadlocal"); - } - Map params = convertToParameters(n); - OResultSet queryResult; - if (params.keySet().stream().anyMatch(x -> !(x instanceof String))) { - queryResult = db.execute("sql", script, params); - } else { - queryResult = db.execute("sql", script, (Map) params); - } - try (OResultSet res = queryResult) { - OLegacyResultSet finalResult = new OBasicLegacyResultSet(); - res.stream().forEach(x -> finalResult.add(x)); - return finalResult; - } - } - - @SuppressWarnings("unchecked") - protected Map convertToParameters(Object... iArgs) { - final Map params; - - if (iArgs.length == 1 && iArgs[0] instanceof Map) { - params = (Map) iArgs[0]; - } else { - if (iArgs.length == 1 - && iArgs[0] != null - && iArgs[0].getClass().isArray() - && iArgs[0] instanceof Object[]) iArgs = (Object[]) iArgs[0]; - - params = new HashMap(iArgs.length); - for (int i = 0; i < iArgs.length; ++i) { - Object par = iArgs[i]; - - if (par instanceof OIdentifiable && ((OIdentifiable) par).getIdentity().isValid()) - // USE THE RID ONLY - par = ((OIdentifiable) par).getIdentity(); - - params.put(i, par); - } - } - return params; - } - - @Override - public Object eval(Reader reader, Bindings n) throws ScriptException { - final StringBuilder buffer = new StringBuilder(); - try { - while (reader.ready()) buffer.append((char) reader.read()); - } catch (IOException e) { - throw new ScriptException(e); - } - - return new OCommandScript(buffer.toString()).execute(n); - } - - @Override - public void put(String key, Object value) {} - - @Override - public Object get(String key) { - return null; - } - - @Override - public Bindings getBindings(int scope) { - return new SimpleBindings(); - } - - @Override - public void setBindings(Bindings bindings, int scope) {} - - @Override - public Bindings createBindings() { - return new SimpleBindings(); - } - - @Override - public ScriptContext getContext() { - return null; - } - - @Override - public void setContext(ScriptContext context) {} - - @Override - public ScriptEngineFactory getFactory() { - return factory; - } -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/OSQLScriptEngineFactory.java b/core/src/main/java/com/orientechnologies/orient/core/sql/OSQLScriptEngineFactory.java deleted file mode 100755 index 9b1bcc2d53f..00000000000 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/OSQLScriptEngineFactory.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ - -package com.orientechnologies.orient.core.sql; - -import com.orientechnologies.orient.core.OConstants; -import java.util.ArrayList; -import java.util.List; -import javax.script.ScriptEngine; -import javax.script.ScriptEngineFactory; - -/** - * Dynamic script engine factory for OrientDB SQL commands. - * - * @author Luca Garulli (l.garulli--(at)--orientdb.com) - */ -public class OSQLScriptEngineFactory implements ScriptEngineFactory { - - private static final List NAMES = new ArrayList(); - private static final List EXTENSIONS = new ArrayList(); - - static { - NAMES.add(OSQLScriptEngine.NAME); - EXTENSIONS.add(OSQLScriptEngine.NAME); - } - - @Override - public String getEngineName() { - return OSQLScriptEngine.NAME; - } - - @Override - public String getEngineVersion() { - return OConstants.getVersion(); - } - - @Override - public List getExtensions() { - return EXTENSIONS; - } - - @Override - public List getMimeTypes() { - return null; - } - - @Override - public List getNames() { - return NAMES; - } - - @Override - public String getLanguageName() { - return OSQLScriptEngine.NAME; - } - - @Override - public String getLanguageVersion() { - return OConstants.getVersion(); - } - - @Override - public Object getParameter(String key) { - return null; - } - - @Override - public String getMethodCallSyntax(String obj, String m, String... args) { - return null; - } - - @Override - public String getOutputStatement(String toDisplay) { - return null; - } - - @Override - public String getProgram(String... statements) { - final StringBuilder buffer = new StringBuilder(); - for (String s : statements) buffer.append(s).append(";\n"); - return buffer.toString(); - } - - @Override - public ScriptEngine getScriptEngine() { - return new OSQLScriptEngine(this); - } -} diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/functions/graph/OSQLFunctionPathFinder.java b/core/src/main/java/com/orientechnologies/orient/core/sql/functions/graph/OSQLFunctionPathFinder.java index b2a5a95011b..12d9957b3e0 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/functions/graph/OSQLFunctionPathFinder.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/functions/graph/OSQLFunctionPathFinder.java @@ -20,7 +20,8 @@ package com.orientechnologies.orient.core.sql.functions.graph; import com.orientechnologies.orient.core.command.OCommandContext; -import com.orientechnologies.orient.core.command.OCommandExecutorAbstract; +import com.orientechnologies.orient.core.db.OExecutionThreadLocal; +import com.orientechnologies.orient.core.exception.OCommandInterruptedException; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.record.ODirection; import com.orientechnologies.orient.core.record.OVertex; @@ -79,7 +80,8 @@ protected LinkedList execute(final OCommandContext iContext) { // FOUND break; - if (!OCommandExecutorAbstract.checkInterruption(context)) break; + if (OExecutionThreadLocal.isInterruptCurrentOperation()) + throw new OCommandInterruptedException("The command has been interrupted"); } context.setVariable("maxDistances", maxDistances); diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/functions/graph/OSQLFunctionShortestPath.java b/core/src/main/java/com/orientechnologies/orient/core/sql/functions/graph/OSQLFunctionShortestPath.java index 5acf7974381..e032c37a195 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/functions/graph/OSQLFunctionShortestPath.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/functions/graph/OSQLFunctionShortestPath.java @@ -3,9 +3,10 @@ import com.orientechnologies.common.collection.OMultiCollectionIterator; import com.orientechnologies.common.util.ORawPair; import com.orientechnologies.orient.core.command.OCommandContext; -import com.orientechnologies.orient.core.command.OCommandExecutorAbstract; +import com.orientechnologies.orient.core.db.OExecutionThreadLocal; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.exception.OCommandExecutionException; +import com.orientechnologies.orient.core.exception.OCommandInterruptedException; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.record.ODirection; import com.orientechnologies.orient.core.record.OEdge; @@ -164,7 +165,8 @@ public List execute( if (Thread.interrupted()) throw new OCommandExecutionException("The shortestPath() function has been interrupted"); - if (!OCommandExecutorAbstract.checkInterruption(iContext)) break; + if (OExecutionThreadLocal.isInterruptCurrentOperation()) + throw new OCommandInterruptedException("The command has been interrupted"); List neighborIdentity; diff --git a/core/src/main/java/com/orientechnologies/orient/core/sql/parser/OLikeOperator.java b/core/src/main/java/com/orientechnologies/orient/core/sql/parser/OLikeOperator.java index f33b54742f4..8760ebcbf69 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/sql/parser/OLikeOperator.java +++ b/core/src/main/java/com/orientechnologies/orient/core/sql/parser/OLikeOperator.java @@ -4,11 +4,14 @@ import com.orientechnologies.common.collection.OMultiValue; import com.orientechnologies.orient.core.command.OCommandContext; -import com.orientechnologies.orient.core.query.OQueryHelper; import com.orientechnologies.orient.core.sql.executor.metadata.OIndexFinder.Operation; +import java.util.Locale; import java.util.Map; public class OLikeOperator extends SimpleNode implements OBinaryCompareOperator { + protected static final String WILDCARD_ANYCHAR = "?"; + protected static final String WILDCARD_ANY = "%"; + public OLikeOperator(int id) { super(id); } @@ -24,7 +27,37 @@ public boolean execute(Object iLeft, Object iRight, OCommandContext ctx) { if (iLeft == null || iRight == null) { return false; } - return OQueryHelper.like(iLeft.toString(), iRight.toString()); + return like(iLeft.toString(), iRight.toString()); + } + + public static boolean like(String currentValue, String iValue) { + if (currentValue == null + || currentValue.length() == 0 + || iValue == null + || iValue.length() == 0) + // EMPTY/NULL PARAMETERS + return false; + + iValue = iValue.toLowerCase(Locale.ENGLISH); + currentValue = currentValue.toLowerCase(Locale.ENGLISH); + + iValue = iValue.replace("\\", "\\\\"); + iValue = iValue.replace("[", "\\["); + iValue = iValue.replace("]", "\\]"); + iValue = iValue.replace("{", "\\{"); + iValue = iValue.replace("}", "\\}"); + iValue = iValue.replace("(", "\\("); + iValue = iValue.replace(")", "\\)"); + iValue = iValue.replace("|", "\\|"); + iValue = iValue.replace("*", "\\*"); + iValue = iValue.replace("+", "\\+"); + iValue = iValue.replace("$", "\\$"); + iValue = iValue.replace("^", "\\^"); + iValue = iValue.replace(".", "\\."); + iValue = iValue.replace(WILDCARD_ANY, ".*"); + iValue = iValue.replace(WILDCARD_ANYCHAR, "."); + + return currentValue.matches(iValue); } @Override diff --git a/core/src/test/java/com/orientechnologies/orient/core/sql/functions/sql/OFunctionSqlTest.java b/core/src/test/java/com/orientechnologies/orient/core/sql/functions/sql/OFunctionSqlTest.java index 13bd4d052e4..2391b776439 100755 --- a/core/src/test/java/com/orientechnologies/orient/core/sql/functions/sql/OFunctionSqlTest.java +++ b/core/src/test/java/com/orientechnologies/orient/core/sql/functions/sql/OFunctionSqlTest.java @@ -4,7 +4,7 @@ import com.orientechnologies.orient.core.command.OBasicCommandContext; import com.orientechnologies.orient.core.metadata.function.OFunction; import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.sql.query.OLegacyResultSet; +import com.orientechnologies.orient.core.sql.executor.OResultSet; import java.util.ArrayList; import org.junit.Assert; import org.junit.Test; @@ -36,7 +36,7 @@ public void functionSqlWithParameters() { function.save(db); Object result = function.executeInContext(new OBasicCommandContext(), "Enrico"); - Assert.assertEquals(((OLegacyResultSet) result).size(), 1); + Assert.assertEquals(((OResultSet) result).stream().count(), 1); } @Test @@ -75,6 +75,6 @@ public void functionSqlWithInnerFunctionJs() { function1.save(db); Object result = function.executeInContext(new OBasicCommandContext(), "Enrico"); - Assert.assertEquals(((OLegacyResultSet) result).size(), 1); + Assert.assertEquals(((OResultSet) result).stream().count(), 1); } } diff --git a/gremlin/driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java b/gremlin/driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java index 1f52f9aca4f..c6b8b2ae2c7 100755 --- a/gremlin/driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java +++ b/gremlin/driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/OrientGraph.java @@ -7,7 +7,6 @@ import com.orientechnologies.common.log.OLogManager; import com.orientechnologies.common.log.OLogger; import com.orientechnologies.common.util.OCallable; -import com.orientechnologies.orient.core.command.OCommandRequest; import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; import com.orientechnologies.orient.core.db.document.ODatabaseDocument; @@ -272,11 +271,6 @@ public OGremlinResultSet execute(String language, String script, Map params) { return new OGremlinResultSet(this, resultSet); } - @Deprecated - public Object executeCommand(OCommandRequest command) { - return command.execute(); - } - @Override public C compute(Class graphComputerClass) throws IllegalArgumentException { diff --git a/gremlin/driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/executor/OCommandGremlinExecutor.java b/gremlin/driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/executor/OCommandGremlinExecutor.java index 78767138848..fbbdd06991d 100644 --- a/gremlin/driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/executor/OCommandGremlinExecutor.java +++ b/gremlin/driver/src/main/java/org/apache/tinkerpop/gremlin/orientdb/executor/OCommandGremlinExecutor.java @@ -22,6 +22,7 @@ import com.orientechnologies.common.exception.OException; import com.orientechnologies.common.util.OCommonConst; import com.orientechnologies.orient.core.command.OCommandContext; +import com.orientechnologies.orient.core.command.script.OAbstractScriptExecutor; import com.orientechnologies.orient.core.command.script.OCommandExecutorUtility; import com.orientechnologies.orient.core.command.script.OCommandScriptException; import com.orientechnologies.orient.core.command.script.OScriptInjection; @@ -29,7 +30,6 @@ import com.orientechnologies.orient.core.command.script.OScriptResultHandler; import com.orientechnologies.orient.core.command.script.formatter.OGroovyScriptFormatter; import com.orientechnologies.orient.core.command.script.transformer.OScriptTransformer; -import com.orientechnologies.orient.core.command.traverse.OAbstractScriptExecutor; import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; import com.orientechnologies.orient.core.db.document.ODatabaseDocument; diff --git a/security/src/main/java/com/orientechnologies/security/auditing/OAuditingHook.java b/security/src/main/java/com/orientechnologies/security/auditing/OAuditingHook.java index f976778c738..e0739e11844 100644 --- a/security/src/main/java/com/orientechnologies/security/auditing/OAuditingHook.java +++ b/security/src/main/java/com/orientechnologies/security/auditing/OAuditingHook.java @@ -17,8 +17,6 @@ import com.orientechnologies.common.parser.OVariableParser; import com.orientechnologies.common.parser.OVariableParserListener; -import com.orientechnologies.orient.core.command.OCommandExecutor; -import com.orientechnologies.orient.core.command.OCommandRequestText; import com.orientechnologies.orient.core.db.ODatabase; import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; import com.orientechnologies.orient.core.db.ODatabaseListener; @@ -260,15 +258,6 @@ public void onAfterTxCommit(ODatabase iDatabase) { @Override public void onClose(ODatabase iDatabase) {} - @Override - public void onBeforeCommand(OCommandRequestText iCommand, OCommandExecutor executor) {} - - @Override - public void onAfterCommand( - OCommandRequestText iCommand, OCommandExecutor executor, Object result) { - logCommand(iCommand.getText()); - } - @Override public boolean onCorruptionRepairDatabase( ODatabase iDatabase, String iReason, String iWhatWillbeFixed) { diff --git a/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java b/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java index 7cdd15bda8e..ee4be601bab 100755 --- a/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java +++ b/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java @@ -25,7 +25,6 @@ import com.orientechnologies.common.profiler.OAbstractProfiler.OProfilerHookValue; import com.orientechnologies.common.profiler.OProfiler.METRIC_TYPE; import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.command.OCommandRequestText; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.security.OParsedToken; @@ -114,11 +113,6 @@ public void cleanExpiredConnections() { "[OClientConnectionManager] found and removed pending closed channel %d (%s)", entry.getKey(), socket); try { - OCommandRequestText command = entry.getValue().getData().command; - if (command != null && command.isIdempotent()) { - entry.getValue().getProtocol().sendShutdown(); - entry.getValue().getProtocol().interrupt(); - } removeConnectionFromSession(entry.getValue()); entry.getValue().close(); @@ -455,46 +449,41 @@ public void shutdown() { logger.debug("Sending shutdown to thread %s", protocol); - OCommandRequestText command = entry.getValue().getData().command; - if (command != null && command.isIdempotent()) { - protocol.interrupt(); - } else { - if (protocol instanceof ONetworkProtocolBinary - && ((ONetworkProtocolBinary) protocol).getRequestType() - == OChannelBinaryProtocol.REQUEST_SHUTDOWN) { - continue; - } + if (protocol instanceof ONetworkProtocolBinary + && ((ONetworkProtocolBinary) protocol).getRequestType() + == OChannelBinaryProtocol.REQUEST_SHUTDOWN) { + continue; + } - final Socket socket; - if (protocol == null || protocol.getChannel() == null) socket = null; - else socket = protocol.getChannel().socket; + final Socket socket; + if (protocol == null || protocol.getChannel() == null) socket = null; + else socket = protocol.getChannel().socket; - if (socket != null && !socket.isClosed() && !socket.isInputShutdown()) { - try { - logger.debug("Closing input socket of thread %s", protocol); - if (!(socket - instanceof SSLSocket)) // An SSLSocket will throw an UnsupportedOperationException. - socket.shutdownInput(); - } catch (IOException e) { - logger.debug( - "Error on closing connection of %s client during shutdown", - e, entry.getValue().getRemoteAddress()); - } + if (socket != null && !socket.isClosed() && !socket.isInputShutdown()) { + try { + logger.debug("Closing input socket of thread %s", protocol); + if (!(socket + instanceof SSLSocket)) // An SSLSocket will throw an UnsupportedOperationException. + socket.shutdownInput(); + } catch (IOException e) { + logger.debug( + "Error on closing connection of %s client during shutdown", + e, entry.getValue().getRemoteAddress()); } - if (protocol.isAlive()) { - if (protocol instanceof ONetworkProtocolBinary - && ((ONetworkProtocolBinary) protocol).getRequestType() == -1) { - try { - logger.debug("Closing socket of thread %s", protocol); - protocol.getChannel().close(); - } catch (Exception e) { - logger.debug("Error during chanel close at shutdown", e); - } - logger.debug("Sending interrupt signal to thread %s", protocol); - protocol.interrupt(); + } + if (protocol.isAlive()) { + if (protocol instanceof ONetworkProtocolBinary + && ((ONetworkProtocolBinary) protocol).getRequestType() == -1) { + try { + logger.debug("Closing socket of thread %s", protocol); + protocol.getChannel().close(); + } catch (Exception e) { + logger.debug("Error during chanel close at shutdown", e); } - toWait.add(protocol); + logger.debug("Sending interrupt signal to thread %s", protocol); + protocol.interrupt(); } + toWait.add(protocol); } } diff --git a/server/src/main/java/com/orientechnologies/orient/server/OConnectionBinaryExecutor.java b/server/src/main/java/com/orientechnologies/orient/server/OConnectionBinaryExecutor.java index de7fc2e35a6..a336105d130 100755 --- a/server/src/main/java/com/orientechnologies/orient/server/OConnectionBinaryExecutor.java +++ b/server/src/main/java/com/orientechnologies/orient/server/OConnectionBinaryExecutor.java @@ -598,7 +598,7 @@ public OBinaryResponse executeCommand(OCommandRequest request) { result = new ArrayList<>(); } - response = new OCommandResponse(result, null, true, connection.getDatabase()); + response = new OCommandResponse(result, true, connection.getDatabase()); return response; } finally { connection.getDatabase().swapTx(oldTx); diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/ONetworkProtocolData.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/ONetworkProtocolData.java index ae8200f5425..e9a580a1291 100644 --- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/ONetworkProtocolData.java +++ b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/ONetworkProtocolData.java @@ -19,7 +19,6 @@ */ package com.orientechnologies.orient.server.network.protocol; -import com.orientechnologies.orient.core.command.OCommandRequestText; import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer; import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializerFactory; import com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializerBinary; @@ -47,7 +46,6 @@ public class ONetworkProtocolData { private String serializationImpl = null; public boolean serverUser = false; public String serverUsername = null; - public OCommandRequestText command = null; public boolean supportsLegacyPushMessages = true; public boolean collectStats = true; private ORecordSerializer serializer; diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/OAbstractCommandResultListener.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/OAbstractCommandResultListener.java deleted file mode 100644 index 472b81c5456..00000000000 --- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/OAbstractCommandResultListener.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ -package com.orientechnologies.orient.server.network.protocol.binary; - -import com.orientechnologies.orient.client.remote.SimpleValueFetchPlanCommandListener; -import com.orientechnologies.orient.core.command.OCommandResultListener; -import com.orientechnologies.orient.core.fetch.OFetchContext; -import com.orientechnologies.orient.core.fetch.OFetchHelper; -import com.orientechnologies.orient.core.fetch.OFetchListener; -import com.orientechnologies.orient.core.fetch.OFetchPlan; -import com.orientechnologies.orient.core.fetch.remote.ORemoteFetchContext; -import com.orientechnologies.orient.core.record.ORecord; - -/** - * Abstract class to manage command results. - * - * @author Luca Garulli (l.garulli--(at)--orientdb.com) - */ -public abstract class OAbstractCommandResultListener - implements SimpleValueFetchPlanCommandListener { - protected final OCommandResultListener wrappedResultListener; - - private OFetchPlan fetchPlan; - - protected OAbstractCommandResultListener(final OCommandResultListener wrappedResultListener) { - this.wrappedResultListener = wrappedResultListener; - } - - public abstract boolean isEmpty(); - - @Override - public void end() { - if (wrappedResultListener != null) wrappedResultListener.end(); - } - - public void setFetchPlan(final String iText) { - fetchPlan = OFetchHelper.buildFetchPlan(iText); - } - - protected void fetchRecord(final Object iRecord, final OFetchListener iFetchListener) { - if (fetchPlan != null - && fetchPlan != OFetchHelper.DEFAULT_FETCHPLAN - && iRecord instanceof ORecord) { - final ORecord record = (ORecord) iRecord; - final OFetchContext context = new ORemoteFetchContext(); - OFetchHelper.fetch(record, record, fetchPlan, iFetchListener, context, ""); - } - } - - @Override - public Object getResult() { - if (wrappedResultListener != null) return wrappedResultListener.getResult(); - - return null; - } -} diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/OAsyncCommandResultListener.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/OAsyncCommandResultListener.java deleted file mode 100644 index a68b393afcd..00000000000 --- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/OAsyncCommandResultListener.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ - -package com.orientechnologies.orient.server.network.protocol.binary; - -import com.orientechnologies.common.log.OLogManager; -import com.orientechnologies.common.log.OLogger; -import com.orientechnologies.orient.core.command.OCommandResultListener; -import com.orientechnologies.orient.core.db.record.OIdentifiable; -import com.orientechnologies.orient.core.exception.OFetchException; -import com.orientechnologies.orient.core.fetch.OFetchContext; -import com.orientechnologies.orient.core.fetch.OFetchHelper; -import com.orientechnologies.orient.core.fetch.remote.ORemoteFetchContext; -import com.orientechnologies.orient.core.fetch.remote.ORemoteFetchListener; -import com.orientechnologies.orient.core.id.ORID; -import com.orientechnologies.orient.core.record.ORecord; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.server.OClientConnection; -import java.io.IOException; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Asynchronous command result manager. As soon as a record is returned by the command is sent over - * the wire. - * - * @author Luca Garulli (l.garulli--(at)--orientdb.com) - */ -public class OAsyncCommandResultListener extends OAbstractCommandResultListener { - - private static final OLogger logger = - OLogManager.instance().logger(OAsyncCommandResultListener.class); - - private final ONetworkProtocolBinary protocol; - private final AtomicBoolean empty = new AtomicBoolean(true); - private final int txId; - private final Set alreadySent = new HashSet(); - private final OClientConnection connection; - - public OAsyncCommandResultListener( - OClientConnection connection, final OCommandResultListener wrappedResultListener) { - super(wrappedResultListener); - this.protocol = (ONetworkProtocolBinary) connection.getProtocol(); - this.txId = connection.getId(); - this.connection = connection; - } - - @Override - public boolean result(final Object iRecord) { - empty.compareAndSet(true, false); - - try { - fetchRecord( - iRecord, - new ORemoteFetchListener() { - @Override - protected void sendRecord(ORecord iLinked) { - if (!alreadySent.contains(iLinked.getIdentity())) { - alreadySent.add(iLinked.getIdentity()); - try { - protocol.channel.writeByte((byte) 2); // CACHE IT ON THE CLIENT - protocol.writeIdentifiable(protocol.channel, connection, iLinked); - } catch (IOException e) { - logger.error("Cannot write against channel", e); - } - } - } - }); - alreadySent.add(((OIdentifiable) iRecord).getIdentity()); - protocol.channel.writeByte((byte) 1); // ONE MORE RECORD - protocol.writeIdentifiable( - protocol.channel, connection, ((OIdentifiable) iRecord).getRecord()); - protocol.channel.flush(); // TODO review this flush... it's for non blocking... - - if (wrappedResultListener != null) - // NOTIFY THE WRAPPED LISTENER - wrappedResultListener.result(iRecord); - - } catch (IOException e) { - return false; - } - - return true; - } - - public boolean isEmpty() { - return empty.get(); - } - - @Override - public void linkdedBySimpleValue(ODocument doc) { - ORemoteFetchListener listener = - new ORemoteFetchListener() { - @Override - protected void sendRecord(ORecord iLinked) { - if (!alreadySent.contains(iLinked.getIdentity())) { - alreadySent.add(iLinked.getIdentity()); - try { - protocol.channel.writeByte((byte) 2); // CACHE IT ON THE CLIENT - protocol.writeIdentifiable(protocol.channel, connection, iLinked); - } catch (IOException e) { - logger.error("Cannot write against channel", e); - } - } - } - - @Override - public void parseLinked( - ODocument iRootRecord, - OIdentifiable iLinked, - Object iUserObject, - String iFieldName, - OFetchContext iContext) - throws OFetchException { - if (iLinked instanceof ORecord) sendRecord((ORecord) iLinked); - } - - @Override - public void parseLinkedCollectionValue( - ODocument iRootRecord, - OIdentifiable iLinked, - Object iUserObject, - String iFieldName, - OFetchContext iContext) - throws OFetchException { - if (iLinked instanceof ORecord) sendRecord((ORecord) iLinked); - } - }; - final OFetchContext context = new ORemoteFetchContext(); - OFetchHelper.fetch(doc, doc, OFetchHelper.buildFetchPlan(""), listener, context, ""); - } -} diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/OLiveCommandResultListener.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/OLiveCommandResultListener.java deleted file mode 100755 index 16874fd2ea0..00000000000 --- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/OLiveCommandResultListener.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ - -package com.orientechnologies.orient.server.network.protocol.binary; - -import com.orientechnologies.common.exception.OException; -import com.orientechnologies.common.log.OLogManager; -import com.orientechnologies.common.log.OLogger; -import com.orientechnologies.orient.core.command.OCommandResultListener; -import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal; -import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; -import com.orientechnologies.orient.core.db.record.OIdentifiable; -import com.orientechnologies.orient.core.db.record.ORecordOperation; -import com.orientechnologies.orient.core.fetch.remote.ORemoteFetchListener; -import com.orientechnologies.orient.core.id.ORID; -import com.orientechnologies.orient.core.id.ORecordId; -import com.orientechnologies.orient.core.query.live.OLiveQueryHook; -import com.orientechnologies.orient.core.record.ORecord; -import com.orientechnologies.orient.core.record.ORecordInternal; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.sql.query.OLiveResultListener; -import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinary; -import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryProtocol; -import com.orientechnologies.orient.server.OClientConnection; -import com.orientechnologies.orient.server.OClientSessions; -import com.orientechnologies.orient.server.OServer; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Asynchronous command result manager. As soon as a record is returned by the command is sent over - * the wire. - * - * @author Luca Garulli (l.garulli--(at)--orientdb.com) - */ -public class OLiveCommandResultListener extends OAbstractCommandResultListener - implements OLiveResultListener { - private static final OLogger logger = - OLogManager.instance().logger(OLiveCommandResultListener.class); - - private OClientConnection connection; - private final AtomicBoolean empty = new AtomicBoolean(true); - private final int sessionId; - private final Set alreadySent = new HashSet(); - private OClientSessions session; - - public OLiveCommandResultListener( - OServer server, - final OClientConnection connection, - OCommandResultListener wrappedResultListener) { - super(wrappedResultListener); - this.connection = connection; - session = server.getClientConnectionManager().getSession(connection); - this.sessionId = connection.getId(); - } - - @Override - public boolean result(final Object iRecord) { - final ONetworkProtocolBinary protocol = ((ONetworkProtocolBinary) connection.getProtocol()); - if (empty.compareAndSet(true, false)) - try { - protocol.channel.writeByte(OChannelBinaryProtocol.RESPONSE_STATUS_OK); - protocol.channel.writeInt(protocol.clientTxId); - protocol.okSent = true; - if (connection != null - && Boolean.TRUE.equals(connection.getTokenBased()) - && connection.getToken() != null - && protocol.requestType != OChannelBinaryProtocol.REQUEST_CONNECT - && protocol.requestType != OChannelBinaryProtocol.REQUEST_DB_OPEN) { - // TODO: Check if the token is expiring and if it is send a new token - byte[] renewedToken = - protocol.getServer().getTokenHandler().renewIfNeeded(connection.getToken()); - protocol.channel.writeBytes(renewedToken); - } - } catch (IOException ignored) { - } - try { - fetchRecord( - iRecord, - new ORemoteFetchListener() { - @Override - protected void sendRecord(ORecord iLinked) { - if (!alreadySent.contains(iLinked.getIdentity())) { - alreadySent.add(iLinked.getIdentity()); - try { - protocol.channel.writeByte((byte) 2); // CACHE IT ON THE CLIENT - protocol.writeIdentifiable(protocol.channel, connection, iLinked); - } catch (IOException e) { - logger.error("Cannot write against channel", e); - } - } - } - }); - alreadySent.add(((OIdentifiable) iRecord).getIdentity()); - protocol.channel.writeByte((byte) 1); // ONE MORE RECORD - protocol.writeIdentifiable( - protocol.channel, connection, ((OIdentifiable) iRecord).getRecord()); - protocol.channel.flush(); - } catch (IOException e) { - return false; - } - return true; - } - - public boolean isEmpty() { - return empty.get(); - } - - public void onLiveResult(int iToken, ORecordOperation iOp) throws OException { - boolean sendFail = true; - do { - List connections = session.getConnections(); - if (connections.size() == 0) { - try { - ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.instance().get(); - logger.warn("Unsubscribing live query for connection %s", null, connection); - OLiveQueryHook.unsubscribe(iToken, db); - } catch (Exception e) { - logger.warn("Unsubscribing live query for connection %s", e, connection); - } - break; - } - OClientConnection curConnection = connections.get(0); - ONetworkProtocolBinary protocol = (ONetworkProtocolBinary) curConnection.getProtocol(); - - OChannelBinary channel = protocol.getChannel(); - try { - channel.acquireWriteLock(); - try { - - ByteArrayOutputStream content = new ByteArrayOutputStream(); - - DataOutputStream out = new DataOutputStream(content); - out.writeByte('r'); - out.writeByte(iOp.type); - out.writeInt(iToken); - out.writeByte(ORecordInternal.getRecordType(iOp.getRecord())); - writeVersion(out, iOp.getRecord().getVersion()); - writeRID(out, (ORecordId) iOp.getRecord().getIdentity()); - writeBytes(out, protocol.getRecordBytes(connection, iOp.getRecord())); - channel.writeByte(OChannelBinaryProtocol.PUSH_DATA); - channel.writeInt(Integer.MIN_VALUE); - channel.writeByte(OChannelBinaryProtocol.REQUEST_PUSH_LIVE_QUERY); - channel.writeBytes(content.toByteArray()); - channel.flush(); - - } finally { - channel.releaseWriteLock(); - } - sendFail = false; - } catch (IOException e) { - session.removeConnection(curConnection); - connections = session.getConnections(); - if (connections.isEmpty()) { - ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.instance().get(); - OLiveQueryHook.unsubscribe(iToken, db); - break; - } - } catch (Exception e) { - logger.warn( - "Cannot push cluster configuration to the client %s", e, protocol.getRemoteAddress()); - protocol.getServer().getClientConnectionManager().disconnect(connection); - OLiveQueryHook.unsubscribe(iToken, connection.getDatabase()); - break; - } - - } while (sendFail); - } - - @Override - public void onError(int iLiveToken) {} - - @Override - public void onUnsubscribe(int iLiveToken) { - boolean sendFail = true; - do { - List connections = session.getConnections(); - if (connections.size() == 0) { - break; - } - ONetworkProtocolBinary protocol = (ONetworkProtocolBinary) connections.get(0).getProtocol(); - - OChannelBinary channel = protocol.getChannel(); - try { - channel.acquireWriteLock(); - try { - - ByteArrayOutputStream content = new ByteArrayOutputStream(); - - DataOutputStream out = new DataOutputStream(content); - out.writeByte('u'); - out.writeInt(iLiveToken); - channel.writeByte(OChannelBinaryProtocol.PUSH_DATA); - channel.writeInt(Integer.MIN_VALUE); - channel.writeByte(OChannelBinaryProtocol.REQUEST_PUSH_LIVE_QUERY); - channel.writeBytes(content.toByteArray()); - channel.flush(); - - } finally { - channel.releaseWriteLock(); - } - sendFail = false; - } catch (IOException e) { - connections = session.getConnections(); - if (connections.isEmpty()) { - break; - } - } catch (Exception e) { - logger.warn( - "Cannot push cluster configuration to the client %s", e, protocol.getRemoteAddress()); - protocol.getServer().getClientConnectionManager().disconnect(connection); - break; - } - - } while (sendFail); - } - - private void writeVersion(DataOutputStream out, int v) throws IOException { - out.writeInt(v); - } - - private void writeRID(DataOutputStream out, ORecordId record) throws IOException { - out.writeShort((short) record.getClusterId()); - out.writeLong(record.getClusterPosition()); - } - - public void writeBytes(DataOutputStream out, byte[] bytes) throws IOException { - out.writeInt(bytes.length); - out.write(bytes); - } - - @Override - public void linkdedBySimpleValue(ODocument doc) {} -} diff --git a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/OSyncCommandResultListener.java b/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/OSyncCommandResultListener.java deleted file mode 100644 index 7e4dace11bf..00000000000 --- a/server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/OSyncCommandResultListener.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * - * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) - * * - * * Licensed under the Apache License, Version 2.0 (the "License"); - * * you may not use this file except in compliance with the License. - * * You may obtain a copy of the License at - * * - * * http://www.apache.org/licenses/LICENSE-2.0 - * * - * * Unless required by applicable law or agreed to in writing, software - * * distributed under the License is distributed on an "AS IS" BASIS, - * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * * See the License for the specific language governing permissions and - * * limitations under the License. - * * - * * For more information: http://orientdb.com - * - */ - -package com.orientechnologies.orient.server.network.protocol.binary; - -import com.orientechnologies.orient.client.remote.OFetchPlanResults; -import com.orientechnologies.orient.core.command.OCommandResultListener; -import com.orientechnologies.orient.core.db.record.OIdentifiable; -import com.orientechnologies.orient.core.exception.OFetchException; -import com.orientechnologies.orient.core.fetch.OFetchContext; -import com.orientechnologies.orient.core.fetch.OFetchHelper; -import com.orientechnologies.orient.core.fetch.remote.ORemoteFetchContext; -import com.orientechnologies.orient.core.fetch.remote.ORemoteFetchListener; -import com.orientechnologies.orient.core.id.ORecordId; -import com.orientechnologies.orient.core.record.ORecord; -import com.orientechnologies.orient.core.record.impl.ODocument; -import java.util.HashSet; -import java.util.Set; - -/** - * Synchronous command result manager. - * - * @author Luca Garulli (l.garulli--(at)--orientdb.com) - */ -public class OSyncCommandResultListener extends OAbstractCommandResultListener - implements OFetchPlanResults { - private final Set fetchedRecordsToSend = new HashSet(); - private final Set alreadySent = new HashSet(); - - public OSyncCommandResultListener(final OCommandResultListener wrappedResultListener) { - super(wrappedResultListener); - } - - @Override - public boolean result(final Object iRecord) { - if (iRecord instanceof ORecord) { - alreadySent.add((ORecord) iRecord); - fetchedRecordsToSend.remove(iRecord); - } - - if (wrappedResultListener != null) - // NOTIFY THE WRAPPED LISTENER - wrappedResultListener.result(iRecord); - - fetchRecord( - iRecord, - new ORemoteFetchListener() { - @Override - protected void sendRecord(ORecord iLinked) { - if (!alreadySent.contains(iLinked)) fetchedRecordsToSend.add(iLinked); - } - }); - return true; - } - - public Set getFetchedRecordsToSend() { - return fetchedRecordsToSend; - } - - public boolean isEmpty() { - return false; - } - - @Override - public void linkdedBySimpleValue(ODocument doc) { - - ORemoteFetchListener listener = - new ORemoteFetchListener() { - @Override - protected void sendRecord(ORecord iLinked) { - if (!alreadySent.contains(iLinked)) fetchedRecordsToSend.add(iLinked); - } - - @Override - public void parseLinked( - ODocument iRootRecord, - OIdentifiable iLinked, - Object iUserObject, - String iFieldName, - OFetchContext iContext) - throws OFetchException { - if (!(iLinked instanceof ORecordId)) { - sendRecord(iLinked.getRecord()); - } - } - - @Override - public void parseLinkedCollectionValue( - ODocument iRootRecord, - OIdentifiable iLinked, - Object iUserObject, - String iFieldName, - OFetchContext iContext) - throws OFetchException { - - if (!(iLinked instanceof ORecordId)) { - sendRecord(iLinked.getRecord()); - } - } - }; - final OFetchContext context = new ORemoteFetchContext(); - OFetchHelper.fetch(doc, doc, OFetchHelper.buildFetchPlan(""), listener, context, ""); - } -} diff --git a/server/src/test/java/com/orientechnologies/orient/server/OLiveCommandResultListenerTest.java b/server/src/test/java/com/orientechnologies/orient/server/OLiveCommandResultListenerTest.java deleted file mode 100644 index 4f504dc20b6..00000000000 --- a/server/src/test/java/com/orientechnologies/orient/server/OLiveCommandResultListenerTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.orientechnologies.orient.server; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.atLeastOnce; - -import com.orientechnologies.orient.core.command.OCommandResultListener; -import com.orientechnologies.orient.core.config.OContextConfiguration; -import com.orientechnologies.orient.core.db.record.ORecordOperation; -import com.orientechnologies.orient.core.query.live.OLiveQueryHook; -import com.orientechnologies.orient.core.query.live.OLiveQueryListener; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializerNetwork; -import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryServer; -import com.orientechnologies.orient.server.network.protocol.binary.OLiveCommandResultListener; -import com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary; -import com.orientechnologies.orient.server.token.OTokenHandlerImpl; -import java.io.IOException; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; - -/** Created by tglman on 07/06/16. */ -public class OLiveCommandResultListenerTest extends BaseMemoryInternalDatabase { - - @Mock private OServer server; - @Mock private OChannelBinaryServer channelBinary; - - @Mock private OLiveQueryListener rawListener; - - private ONetworkProtocolBinary protocol; - private OClientConnection connection; - - private static class TestResultListener implements OCommandResultListener { - @Override - public boolean result(Object iRecord) { - return false; - } - - @Override - public void end() {} - - @Override - public Object getResult() { - return null; - } - } - - @Before - public void beforeTests() { - MockitoAnnotations.initMocks(this); - Mockito.when(server.getContextConfiguration()).thenReturn(new OContextConfiguration()); - - OClientConnectionManager manager = new OClientConnectionManager(server); - protocol = new ONetworkProtocolBinary(server); - protocol.initVariables(server, channelBinary); - connection = manager.connect(protocol); - OTokenHandlerImpl tokenHandler = new OTokenHandlerImpl(new OContextConfiguration()); - Mockito.when(server.getTokenHandler()).thenReturn(tokenHandler); - byte[] token = tokenHandler.getSignedBinaryToken(db, db.getUser(), connection.getData()); - connection = manager.connect(protocol, connection, token); - connection.setDatabase(db); - connection.getData().setSerializationImpl(ORecordSerializerNetwork.NAME); - Mockito.when(server.getClientConnectionManager()).thenReturn(manager); - } - - @Test - public void testSimpleMessageSend() throws IOException { - OLiveCommandResultListener listener = - new OLiveCommandResultListener(server, connection, new TestResultListener()); - ORecordOperation op = new ORecordOperation(new ODocument(), ORecordOperation.CREATED); - listener.onLiveResult(10, op); - Mockito.verify(channelBinary, atLeastOnce()).writeBytes(Mockito.any(byte[].class)); - } - - @Test - public void testNetworkError() throws IOException { - Mockito.when(channelBinary.writeInt(Mockito.anyInt())) - .thenThrow(new IOException("Mock Exception")); - OLiveCommandResultListener listener = - new OLiveCommandResultListener(server, connection, new TestResultListener()); - OLiveQueryHook.subscribe(10, rawListener, db); - assertTrue(OLiveQueryHook.getOpsReference(db).getQueueThread().hasToken(10)); - ORecordOperation op = new ORecordOperation(new ODocument(), ORecordOperation.CREATED); - listener.onLiveResult(10, op); - assertFalse(OLiveQueryHook.getOpsReference(db).getQueueThread().hasToken(10)); - } -} diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/DbListenerTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/DbListenerTest.java index 8544bafcbaa..dad3949ef82 100755 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/DbListenerTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/DbListenerTest.java @@ -15,8 +15,6 @@ */ package com.orientechnologies.orient.test.database.auto; -import com.orientechnologies.orient.core.command.OCommandExecutor; -import com.orientechnologies.orient.core.command.OCommandRequestText; import com.orientechnologies.orient.core.db.ODatabase; import com.orientechnologies.orient.core.db.ODatabaseListener; import com.orientechnologies.orient.core.db.document.ODatabaseDocument; @@ -122,17 +120,6 @@ public void onClose(ODatabase iDatabase) { onClose++; } - @Override - public void onBeforeCommand(OCommandRequestText iCommand, OCommandExecutor executor) { - command = iCommand.getText(); - } - - @Override - public void onAfterCommand( - OCommandRequestText iCommand, OCommandExecutor executor, Object result) { - commandResult = result; - } - @Override public void onCreate(ODatabase iDatabase) { onCreate++; diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectByLinkedPropertyIndexReuseTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectByLinkedPropertyIndexReuseTest.java index e7f800c6d72..3e98ba52538 100755 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectByLinkedPropertyIndexReuseTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/SQLSelectByLinkedPropertyIndexReuseTest.java @@ -7,7 +7,6 @@ import com.orientechnologies.orient.core.metadata.schema.OSchema; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.sql.OChainedIndexProxy; import com.orientechnologies.orient.core.sql.executor.OResult; import java.util.Arrays; import java.util.List; @@ -18,7 +17,6 @@ import org.testng.annotations.Test; /** - * Testing functionality of {@link OChainedIndexProxy}. * *

Each test method tests different traverse index combination with different operations. * diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/StringsTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/StringsTest.java index dfeab821408..7cc26ffb947 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/StringsTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/StringsTest.java @@ -15,7 +15,6 @@ */ package com.orientechnologies.orient.test.database.auto; -import com.orientechnologies.common.parser.OStringParser; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper; import java.util.List; @@ -45,37 +44,6 @@ public void splitArray() { Assert.assertTrue(pieces.get(1).contains("this is mine")); } - public void replaceAll() { - String test1 = "test string number 1"; - String test2 = - "test \\string\\ \"number\" \\2\\ \\\\ \"\"\"\" test String number 2 test string number 2"; - Assert.assertEquals(OStringParser.replaceAll(test1, "", ""), test1); - Assert.assertEquals(OStringParser.replaceAll(test1, "1", "10"), test1 + "0"); - Assert.assertEquals( - OStringParser.replaceAll(test1, "string", "number"), "test number number 1"); - Assert.assertEquals(OStringParser.replaceAll(test1, "string", "test"), "test test number 1"); - Assert.assertEquals( - OStringParser.replaceAll(test1, "test", "string"), "string string number 1"); - Assert.assertEquals(OStringParser.replaceAll(test2, "", ""), test2); - Assert.assertEquals( - OStringParser.replaceAll(test2, "\\", ""), - "test string \"number\" 2 \"\"\"\" test String number 2 test string number 2"); - Assert.assertEquals( - OStringParser.replaceAll(test2, "\"", "'"), - "test \\string\\ 'number' \\2\\ \\\\ '''' test String number 2 test string number 2"); - Assert.assertEquals( - OStringParser.replaceAll(test2, "\\\\", "replacement"), - "test \\string\\ \"number\" \\2\\ replacement \"\"\"\" test String number 2 test string" - + " number 2"); - String subsequentReplaceTest = OStringParser.replaceAll(test2, "\\", ""); - subsequentReplaceTest = OStringParser.replaceAll(subsequentReplaceTest, "\"", ""); - subsequentReplaceTest = - OStringParser.replaceAll( - subsequentReplaceTest, "test string number 2", "text replacement 1"); - Assert.assertEquals( - subsequentReplaceTest, "text replacement 1 test String number 2 text replacement 1"); - } - public void testNoEmptyFields() { List pieces = OStringSerializerHelper.split( diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TransactionAtomicTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TransactionAtomicTest.java index 207c565f620..2f8831ca6a3 100755 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TransactionAtomicTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/auto/TransactionAtomicTest.java @@ -15,8 +15,6 @@ */ package com.orientechnologies.orient.test.database.auto; -import com.orientechnologies.orient.core.command.OCommandExecutor; -import com.orientechnologies.orient.core.command.OCommandRequestText; import com.orientechnologies.orient.core.db.ODatabase; import com.orientechnologies.orient.core.db.ODatabaseListener; import com.orientechnologies.orient.core.db.document.ODatabaseDocument; @@ -122,13 +120,6 @@ public void onBeforeTxRollback(ODatabase iDatabase) {} @Override public void onClose(ODatabase iDatabase) {} - @Override - public void onBeforeCommand(OCommandRequestText iCommand, OCommandExecutor executor) {} - - @Override - public void onAfterCommand( - OCommandRequestText iCommand, OCommandExecutor executor, Object result) {} - @Override public void onCreate(ODatabase iDatabase) {} diff --git a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/SQLSynchQuerySpeedTest.java b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/SQLSynchQuerySpeedTest.java index 21ace1ca5e4..214fa59750c 100644 --- a/tests/src/test/java/com/orientechnologies/orient/test/database/speed/SQLSynchQuerySpeedTest.java +++ b/tests/src/test/java/com/orientechnologies/orient/test/database/speed/SQLSynchQuerySpeedTest.java @@ -16,7 +16,6 @@ package com.orientechnologies.orient.test.database.speed; import com.orientechnologies.common.test.SpeedTestMonoThread; -import com.orientechnologies.orient.core.command.OCommandResultListener; import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.sql.executor.OResultSet; @@ -25,7 +24,7 @@ import org.testng.annotations.Test; @Test(enabled = false) -public class SQLSynchQuerySpeedTest extends SpeedTestMonoThread implements OCommandResultListener { +public class SQLSynchQuerySpeedTest extends SpeedTestMonoThread { protected int resultCount = 0; private ODatabaseDocument database; @@ -52,12 +51,4 @@ public boolean result(final Object iRecord) { OrientTest.printRecord(resultCount++, iRecord); return true; } - - @Override - public void end() {} - - @Override - public Object getResult() { - return null; - } }