use of com.orientechnologies.common.exception.OException in project orientdb by orientechnologies.
the class ONetworkProtocolBinary method openDatabase.
protected void openDatabase(OClientConnection connection) throws IOException {
setDataCommandInfo(connection, "Open database");
readConnectionData(connection);
final String dbURL = channel.readString();
String dbType = ODatabaseDocument.TYPE;
if (connection.getData().protocolVersion <= OChannelBinaryProtocol.PROTOCOL_VERSION_32)
// READ DB-TYPE FROM THE CLIENT. NOT USED ANYMORE
dbType = channel.readString();
final String user = channel.readString();
final String passwd = channel.readString();
for (OBeforeDatabaseOpenNetworkEventListener l : listener.getBeforeDatabaseOpenNetworkEventListener()) l.onBeforeDatabaseOpen(dbURL);
try {
connection.setDatabase((ODatabaseDocumentTx) server.openDatabase(dbURL, user, passwd, connection.getData()));
} catch (OException e) {
server.getClientConnectionManager().disconnect(connection);
throw e;
}
byte[] token = null;
if (Boolean.TRUE.equals(connection.getTokenBased())) {
token = server.getTokenHandler().getSignedBinaryToken(connection.getDatabase(), connection.getDatabase().getUser(), connection.getData());
// TODO: do not use the parse split getSignedBinaryToken in two methods.
getServer().getClientConnectionManager().connect(this, connection, token, server.getTokenHandler());
}
if (connection.getDatabase().getStorage() instanceof OStorageProxy && !loadUserFromSchema(connection, user, passwd)) {
sendErrorOrDropConnection(connection, clientTxId, new OSecurityAccessException(connection.getDatabase().getName(), "User or password not valid for database: '" + connection.getDatabase().getName() + "'"));
} else {
beginResponse();
try {
sendOk(connection, clientTxId);
channel.writeInt(connection.getId());
if (connection.getData().protocolVersion > OChannelBinaryProtocol.PROTOCOL_VERSION_26) {
if (Boolean.TRUE.equals(connection.getTokenBased())) {
channel.writeBytes(token);
} else
channel.writeBytes(OCommonConst.EMPTY_BYTE_ARRAY);
}
sendDatabaseInformation(connection);
final OServerPlugin plugin = server.getPlugin("cluster");
ODocument distributedCfg = null;
if (plugin != null && plugin instanceof ODistributedServerManager) {
distributedCfg = ((ODistributedServerManager) plugin).getClusterConfiguration();
final ODistributedConfiguration dbCfg = ((ODistributedServerManager) plugin).getDatabaseConfiguration(connection.getDatabase().getName());
if (dbCfg != null) {
// ENHANCE SERVER CFG WITH DATABASE CFG
distributedCfg.field("database", dbCfg.getDocument(), OType.EMBEDDED);
}
}
channel.writeBytes(distributedCfg != null ? getRecordBytes(connection, distributedCfg) : null);
if (connection.getData().protocolVersion >= 14)
channel.writeString(OConstants.getVersion());
} finally {
endResponse(connection);
}
}
}
use of com.orientechnologies.common.exception.OException in project orientdb by orientechnologies.
the class OStorageRemote method baseNetworkOperation.
public <T> T baseNetworkOperation(final OStorageRemoteOperation<T> operation, final String errorMessage, int retry) {
OStorageRemoteSession session = getCurrentSession();
if (session.commandExecuting)
throw new ODatabaseException("Cannot execute the request because an asynchronous operation is in progress. Please use a different connection");
String serverUrl = null;
do {
OChannelBinaryAsynchClient network = null;
if (serverUrl == null)
serverUrl = getNextAvailableServerURL(false, session);
do {
try {
network = getNetwork(serverUrl);
} catch (OException e) {
serverUrl = useNewServerURL(serverUrl);
if (serverUrl == null)
throw e;
}
} while (network == null);
try {
// In case i do not have a token or i'm switching between server i've to execute a open operation.
OStorageRemoteNodeSession nodeSession = session.getServerSession(network.getServerURL());
if (nodeSession == null || !nodeSession.isValid()) {
openRemoteDatabase(network);
if (!network.tryLock()) {
connectionManager.release(network);
continue;
}
}
return operation.execute(network, session);
} catch (ODistributedRedirectException e) {
connectionManager.release(network);
OLogManager.instance().debug(this, "Redirecting the request from server '%s' to the server '%s' because %s", e.getFromServer(), e.toString(), e.getMessage());
// RECONNECT TO THE SERVER SUGGESTED IN THE EXCEPTION
serverUrl = e.getToServerAddress();
} catch (OModificationOperationProhibitedException mope) {
connectionManager.release(network);
handleDBFreeze();
serverUrl = null;
} catch (OTokenException e) {
connectionManager.release(network);
session.removeServerSession(network.getServerURL());
if (--retry <= 0)
throw OException.wrapException(new OStorageException(errorMessage), e);
serverUrl = null;
} catch (OTokenSecurityException e) {
connectionManager.release(network);
session.removeServerSession(network.getServerURL());
if (--retry <= 0)
throw OException.wrapException(new OStorageException(errorMessage), e);
serverUrl = null;
} catch (OOfflineNodeException e) {
connectionManager.release(network);
// Remove the current url because the node is offline
synchronized (serverURLs) {
serverURLs.remove(serverUrl);
}
for (OStorageRemoteSession activeSession : sessions) {
// Not thread Safe ...
activeSession.removeServerSession(serverUrl);
}
serverUrl = null;
} catch (IOException e) {
connectionManager.release(network);
retry = handleIOException(retry, network, e);
serverUrl = null;
} catch (OIOException e) {
connectionManager.release(network);
retry = handleIOException(retry, network, e);
serverUrl = null;
} catch (OException e) {
connectionManager.release(network);
throw e;
} catch (Exception e) {
connectionManager.release(network);
throw OException.wrapException(new OStorageException(errorMessage), e);
}
} while (true);
}
use of com.orientechnologies.common.exception.OException in project orientdb by orientechnologies.
the class ODatabaseDocumentTx method executeSaveRecord.
/**
* This method is internal, it can be subject to signature change or be removed, do not use.
*
* @Internal
*/
public <RET extends ORecord> RET executeSaveRecord(final ORecord record, String clusterName, final int ver, final OPERATION_MODE mode, boolean forceCreate, final ORecordCallback<? extends Number> recordCreatedCallback, ORecordCallback<Integer> recordUpdatedCallback) {
checkOpeness();
checkIfActive();
if (!record.isDirty())
return (RET) record;
final ORecordId rid = (ORecordId) record.getIdentity();
if (rid == null)
throw new ODatabaseException("Cannot create record because it has no identity. Probably is not a regular record or contains projections of fields rather than a full record");
record.setInternalStatus(ORecordElement.STATUS.MARSHALLING);
try {
byte[] stream = null;
final OStorageOperationResult<Integer> operationResult;
getMetadata().makeThreadLocalSchemaSnapshot();
if (record instanceof ODocument)
ODocumentInternal.checkClass((ODocument) record, this);
ORecordSerializationContext.pushContext();
final boolean isNew = forceCreate || rid.isNew();
try {
final ORecordHook.TYPE triggerType;
if (isNew) {
// NOTIFY IDENTITY HAS CHANGED
ORecordInternal.onBeforeIdentityChanged(record);
int id = assignAndCheckCluster(record, clusterName);
clusterName = getClusterNameById(id);
checkSecurity(ORule.ResourceGeneric.CLUSTER, ORole.PERMISSION_CREATE, clusterName);
triggerType = ORecordHook.TYPE.BEFORE_CREATE;
} else {
clusterName = getClusterNameById(record.getIdentity().getClusterId());
checkSecurity(ORule.ResourceGeneric.CLUSTER, ORole.PERMISSION_UPDATE, clusterName);
triggerType = ORecordHook.TYPE.BEFORE_UPDATE;
}
stream = record.toStream();
final ORecordHook.RESULT hookResult = callbackHooks(triggerType, record);
if (hookResult == ORecordHook.RESULT.RECORD_CHANGED) {
if (record instanceof ODocument)
((ODocument) record).validate();
stream = updateStream(record);
} else if (hookResult == ORecordHook.RESULT.SKIP_IO)
return (RET) record;
else if (hookResult == ORecordHook.RESULT.RECORD_REPLACED)
// RETURNED THE REPLACED RECORD
return (RET) OHookReplacedRecordThreadLocal.INSTANCE.get();
ORecordSaveThreadLocal.setLast(record);
try {
// SAVE IT
boolean updateContent = ORecordInternal.isContentChanged(record);
byte[] content = (stream == null) ? OCommonConst.EMPTY_BYTE_ARRAY : stream;
byte recordType = ORecordInternal.getRecordType(record);
final int modeIndex = mode.ordinal();
// CHECK IF RECORD TYPE IS SUPPORTED
Orient.instance().getRecordFactoryManager().getRecordTypeClass(recordType);
if (forceCreate || ORecordId.isNew(rid.getClusterPosition())) {
// CREATE
final OStorageOperationResult<OPhysicalPosition> ppos = storage.createRecord(rid, content, ver, recordType, modeIndex, (ORecordCallback<Long>) recordCreatedCallback);
operationResult = new OStorageOperationResult<Integer>(ppos.getResult().recordVersion, ppos.isMoved());
} else {
// UPDATE
operationResult = storage.updateRecord(rid, updateContent, content, ver, recordType, modeIndex, recordUpdatedCallback);
}
final int version = operationResult.getResult();
if (isNew) {
// UPDATE INFORMATION: CLUSTER ID+POSITION
((ORecordId) record.getIdentity()).copyFrom(rid);
// NOTIFY IDENTITY HAS CHANGED
ORecordInternal.onAfterIdentityChanged(record);
// UPDATE INFORMATION: CLUSTER ID+POSITION
}
if (operationResult.getModifiedRecordContent() != null)
stream = operationResult.getModifiedRecordContent();
else if (version > record.getVersion() + 1)
// IN CASE OF REMOTE CONFLICT STRATEGY FORCE UNLOAD DUE TO INVALID CONTENT
record.unload();
ORecordInternal.fill(record, rid, version, stream, false);
callbackHookSuccess(record, isNew, stream, operationResult);
} catch (Exception t) {
callbackHookFailure(record, isNew, stream);
throw t;
}
} finally {
callbackHookFinalize(record, isNew, stream);
ORecordSerializationContext.pullContext();
getMetadata().clearThreadLocalSchemaSnapshot();
ORecordSaveThreadLocal.removeLast();
}
if (stream != null && stream.length > 0 && !operationResult.isMoved())
// ADD/UPDATE IT IN CACHE IF IT'S ACTIVE
getLocalCache().updateRecord(record);
} catch (OException e) {
throw e;
} catch (Exception t) {
if (!ORecordId.isValid(record.getIdentity().getClusterPosition()))
throw OException.wrapException(new ODatabaseException("Error on saving record in cluster #" + record.getIdentity().getClusterId()), t);
else
throw OException.wrapException(new ODatabaseException("Error on saving record " + record.getIdentity()), t);
} finally {
record.setInternalStatus(ORecordElement.STATUS.LOADED);
}
return (RET) record;
}
use of com.orientechnologies.common.exception.OException in project orientdb by orientechnologies.
the class ODatabaseDocumentTx method executeDeleteRecord.
/**
* This method is internal, it can be subject to signature change or be removed, do not use.
*
* @Internal
*/
public void executeDeleteRecord(OIdentifiable record, final int iVersion, final boolean iRequired, final OPERATION_MODE iMode, boolean prohibitTombstones) {
checkOpeness();
checkIfActive();
final ORecordId rid = (ORecordId) record.getIdentity();
if (rid == null)
throw new ODatabaseException("Cannot delete record because it has no identity. Probably was created from scratch or contains projections of fields rather than a full record");
if (!rid.isValid())
return;
record = record.getRecord();
if (record == null)
return;
checkSecurity(ORule.ResourceGeneric.CLUSTER, ORole.PERMISSION_DELETE, getClusterNameById(rid.getClusterId()));
ORecordSerializationContext.pushContext();
getMetadata().makeThreadLocalSchemaSnapshot();
try {
if (record instanceof ODocument) {
ODocumentInternal.checkClass((ODocument) record, this);
}
try {
// if cache is switched off record will be unreachable after delete.
ORecord rec = record.getRecord();
if (rec != null) {
callbackHooks(ORecordHook.TYPE.BEFORE_DELETE, rec);
if (rec instanceof ODocument)
ORidBagDeleter.deleteAllRidBags((ODocument) rec);
}
final OStorageOperationResult<Boolean> operationResult;
try {
if (prohibitTombstones) {
final boolean result = storage.cleanOutRecord(rid, iVersion, iMode.ordinal(), null);
if (!result && iRequired)
throw new ORecordNotFoundException(rid);
operationResult = new OStorageOperationResult<Boolean>(result);
} else {
final OStorageOperationResult<Boolean> result = storage.deleteRecord(rid, iVersion, iMode.ordinal(), null);
if (!result.getResult() && iRequired)
throw new ORecordNotFoundException(rid);
operationResult = new OStorageOperationResult<Boolean>(result.getResult());
}
if (!operationResult.isMoved() && rec != null)
callbackHooks(ORecordHook.TYPE.AFTER_DELETE, rec);
else if (rec != null)
callbackHooks(ORecordHook.TYPE.DELETE_REPLICATED, rec);
} catch (Exception t) {
callbackHooks(ORecordHook.TYPE.DELETE_FAILED, rec);
throw t;
} finally {
callbackHooks(ORecordHook.TYPE.FINALIZE_DELETION, rec);
}
clearDocumentTracking(rec);
// REMOVE THE RECORD FROM 1 AND 2 LEVEL CACHES
if (!operationResult.isMoved()) {
getLocalCache().deleteRecord(rid);
}
} catch (OException e) {
// RE-THROW THE EXCEPTION
throw e;
} catch (Exception t) {
// WRAP IT AS ODATABASE EXCEPTION
throw OException.wrapException(new ODatabaseException("Error on deleting record in cluster #" + record.getIdentity().getClusterId()), t);
}
} finally {
ORecordSerializationContext.pullContext();
getMetadata().clearThreadLocalSchemaSnapshot();
}
}
use of com.orientechnologies.common.exception.OException in project orientdb by orientechnologies.
the class UniqueHashIndexForDate method testSimpleUniqueDateIndex.
@Test
public void testSimpleUniqueDateIndex() throws ParseException {
ODatabaseDocument db = new ODatabaseDocumentTx("memory:" + UniqueHashIndexForDate.class.getSimpleName());
db.create();
try {
OClass clazz = db.getMetadata().getSchema().createClass("test_edge");
OProperty prop = clazz.createProperty("date", OType.DATETIME);
prop.createIndex(INDEX_TYPE.UNIQUE);
ODocument doc = new ODocument("test_edge");
doc.field("date", "2015-03-24 08:54:49");
ODocument doc1 = new ODocument("test_edge");
doc1.field("date", "2015-03-24 08:54:49");
db.save(doc);
try {
db.begin();
db.save(doc1);
doc1.field("date", "2015-03-24 08:54:49");
db.save(doc1);
db.commit();
Assert.fail("expected exception for duplicate ");
} catch (OException e) {
}
} finally {
db.drop();
}
}
Aggregations