<commit_before>/*
 * Copyright 1999-2010 <NAME> (l.garulli--at--orientechnologies.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.
 */
package com.orientechnologies.orient.server.network.protocol.binary;

import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;

import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.db.ODatabaseComplex;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.raw.ODatabaseRaw;
import com.orientechnologies.orient.core.db.record.ODatabaseRecordTx;
import com.orientechnologies.orient.core.exception.OSecurityAccessException;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.metadata.security.OUser;
import com.orientechnologies.orient.core.query.OAsynchQuery;
import com.orientechnologies.orient.core.query.OAsynchQueryResultListener;
import com.orientechnologies.orient.core.query.OQuery;
import com.orientechnologies.orient.core.query.sql.OSQLSynchQuery;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.ORecordSchemaAware;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.record.OSerializationThreadLocal;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerAnyStreamable;
import com.orientechnologies.orient.core.storage.OCluster;
import com.orientechnologies.orient.core.storage.ORawBuffer;
import com.orientechnologies.orient.core.storage.impl.local.OStorageLocal;
import com.orientechnologies.orient.enterprise.channel.OChannel;
import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinary;
import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryProtocol;
import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryServer;
import com.orientechnologies.orient.server.OClientConnection;
import com.orientechnologies.orient.server.OClientConnectionManager;
import com.orientechnologies.orient.server.OServer;
import com.orientechnologies.orient.server.OServerMain;
import com.orientechnologies.orient.server.config.OServerConfiguration;
import com.orientechnologies.orient.server.network.protocol.ONetworkProtocol;
import com.orientechnologies.orient.server.tx.OTransactionOptimisticProxy;

public class ONetworkProtocolBinary extends ONetworkProtocol {
	protected OClientConnection			connection;
	protected OServerConfiguration	configuration;
	protected OChannelBinary				channel;
	protected OUser									account;

	private String									user;
	private String									passwd;
	private ODatabaseRaw						underlyingDatabase;

	public ONetworkProtocolBinary() {
		super(OServer.getThreadGroup(), "net-protocol-binary");
	}

	public void config(final Socket iSocket, final OClientConnection iConnection) throws IOException {
		channel = (OChannelBinary) new OChannelBinaryServer(iSocket);
		connection = iConnection;
		configuration = new OServerConfiguration();

		start();
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void execute() throws Exception {
		try {
			short type = channel.readByte();
			switch (type) {

			case OChannelBinaryProtocol.CONNECT: {
				user = channel.readString();
				passwd = channel.readString();
				sendOk();
				channel.writeString(connection.id);
				break;
			}

			case OChannelBinaryProtocol.DB_OPEN: {
				String dbURL = channel.readString();
				String dbName = dbURL.substring(dbURL.lastIndexOf(":") + 1);

				user = channel.readString();
				passwd = channel.readString();

				connection.database = new ODatabaseDocumentTx("local:" + OServerMain.server().getStoragePath(dbName));
				if (connection.database.isClosed())
					connection.database.open(user, passwd);

				underlyingDatabase = ((ODatabaseRaw) ((ODatabaseComplex<?>) connection.database.getUnderlying()).getUnderlying());

				if (!loadUserFromSchema(user, passwd)) {
					sendError(new OSecurityAccessException("Access denied to database '" + connection.database.getName() + "' for user: "
							+ user));
				} else {
					sendOk();
					channel.writeString(connection.id);
					channel.writeInt(connection.database.getClusterNames().size());
					for (OCluster c : ((OStorageLocal) connection.database.getStorage()).getClusters()) {
						channel.writeString(c.getName());
						channel.writeInt(c.getId());
					}
				}
				break;
			}

			case OChannelBinaryProtocol.DB_CREATE: {
				String dbURL = channel.readString();
				String dbName = dbURL.substring(dbURL.lastIndexOf(":") + 1);
				String storageMode = channel.readString();

				connection.database = new ODatabaseDocumentTx("local:" + OServerMain.server().getStoragePath(dbName));
				connection.database.create(storageMode);
				underlyingDatabase = ((ODatabaseRaw) ((ODatabaseComplex<?>) connection.database.getUnderlying()).getUnderlying());

				sendOk();
				break;
			}

			case OChannelBinaryProtocol.DB_CLOSE:
				// connection.storage.close();
				break;

			case OChannelBinaryProtocol.DB_EXIST:
				channel.writeByte((byte) (connection.database.exists() ? 1 : 0));

				sendOk();
				break;

			case OChannelBinaryProtocol.CLUSTER_COUNT:
				int[] ids = new int[channel.readShort()];
				for (int i = 0; i < ids.length; ++i)
					ids[i] = channel.readShort();

				long count = connection.database.countClusterElements(ids);
<commit_msg>- Fixed problem on 'create database' and 'create cluster' console commands. - Removed buggy 'create record' command in favor of new SQL 'insert' available   in the next days.<commit_after>/*
 * Copyright 1999-2010 <NAME> (<EMAIL>--at--<EMAIL>)
 *
 * 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.
 */
package com.orientechnologies.orient.server.network.protocol.binary;

import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;

import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.parser.OSystemVariableResolver;
import com.orientechnologies.orient.core.db.ODatabaseComplex;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.raw.ODatabaseRaw;
import com.orientechnologies.orient.core.db.record.ODatabaseRecordTx;
import com.orientechnologies.orient.core.exception.OSecurityAccessException;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.metadata.security.OUser;
import com.orientechnologies.orient.core.query.OAsynchQuery;
import com.orientechnologies.orient.core.query.OAsynchQueryResultListener;
import com.orientechnologies.orient.core.query.OQuery;
import com.orientechnologies.orient.core.query.sql.OSQLSynchQuery;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.ORecordSchemaAware;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.record.OSerializationThreadLocal;
import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerAnyStreamable;
import com.orientechnologies.orient.core.storage.OCluster;
import com.orientechnologies.orient.core.storage.ORawBuffer;
import com.orientechnologies.orient.core.storage.impl.local.OStorageLocal;
import com.orientechnologies.orient.enterprise.channel.OChannel;
import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinary;
import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryProtocol;
import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryServer;
import com.orientechnologies.orient.server.OClientConnection;
import com.orientechnologies.orient.server.OClientConnectionManager;
import com.orientechnologies.orient.server.OServer;
import com.orientechnologies.orient.server.OServerMain;
import com.orientechnologies.orient.server.config.OServerStorageConfiguration;
import com.orientechnologies.orient.server.network.protocol.ONetworkProtocol;
import com.orientechnologies.orient.server.tx.OTransactionOptimisticProxy;

public class ONetworkProtocolBinary extends ONetworkProtocol {
	protected OClientConnection	connection;
	protected OChannelBinary		channel;
	protected OUser							account;

	private String							user;
	private String							passwd;
	private ODatabaseRaw				underlyingDatabase;

	public ONetworkProtocolBinary() {
		super(OServer.getThreadGroup(), "net-protocol-binary");
	}

	public void config(final Socket iSocket, final OClientConnection iConnection) throws IOException {
		channel = (OChannelBinary) new OChannelBinaryServer(iSocket);
		connection = iConnection;

		start();
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void execute() throws Exception {
		try {
			short type = channel.readByte();
			switch (type) {

			case OChannelBinaryProtocol.CONNECT: {
				user = channel.readString();
				passwd = channel.readString();
				sendOk();
				channel.writeString(connection.id);
				break;
			}

			case OChannelBinaryProtocol.DB_OPEN: {
				String dbURL = channel.readString();
				String dbName = dbURL.substring(dbURL.lastIndexOf(":") + 1);

				user = channel.readString();
				passwd = channel.readString();

				connection.database = new ODatabaseDocumentTx("local:" + OServerMain.server().getStoragePath(dbName));
				if (connection.database.isClosed())
					connection.database.open(user, passwd);

				underlyingDatabase = ((ODatabaseRaw) ((ODatabaseComplex<?>) connection.database.getUnderlying()).getUnderlying());

				if (!loadUserFromSchema(user, passwd)) {
					sendError(new OSecurityAccessException("Access denied to database '" + connection.database.getName() + "' for user: "
							+ user));
				} else {
					sendOk();
					channel.writeString(connection.id);
					channel.writeInt(connection.database.getClusterNames().size());
					for (OCluster c : ((OStorageLocal) connection.database.getStorage()).getClusters()) {
						channel.writeString(c.getName());
						channel.writeInt(c.getId());
					}
				}
				break;
			}

			case OChannelBinaryProtocol.DB_CREATE: {
				String dbURL = channel.readString();
				String dbName = dbURL.substring(channel.readString().lastIndexOf(":") + 1);
				String storageMode = channel.readString();

				if (OServerMain.server().existsStoragePath(dbName))
					throw new IllegalArgumentException("Database '" + dbName + "' already exists.");

				final String path = "${ORIENT_HOME}/databases/" + dbName + "/" + dbName;
				final String realPath = OSystemVariableResolver.resolveSystemVariables("${ORIENT_HOME}") + "/databases/" + dbName + "/"
						+ dbName;

				connection.database = new ODatabaseDocumentTx("local:" + realPath);
				connection.database.create(storageMode);
				connection.database.close();

				OServerMain.server().getConfiguration().storages.add(new OServerStorageConfiguration(dbName, path));

				OServerMain.server().saveConfiguration();

				underlyingDatabase = ((ODatabaseRaw) ((ODatabaseComplex<?>) connection.database.getUnderlying()).getUnderlying());

				sendOk();
				break;
			}

			case OChannelBinaryProtocol.DB_CLOSE:
				// connection.storage.close();
				break;

			case OChannelBinaryProtocol.DB_EXIST:
				channel.writeByte((byte) (connection.database.exists() ? 1 : 0));

				sendOk();
				break;

			case OChannelBinaryProtocol.CLUSTER_COUNT:
				int[] ids = new int[channel.readShort()];
				for (int i = 0; i < ids.length; ++i)
					ids[i] = channel.readShort();

				long count = connection.database.countClusterElements(ids);

{'fraction_non_alphanumeric': 0.10886695738658098, 'fraction_numerical': 0.002601178180705378, 'mean_word_length': 5.119850187265918, 'pattern_counts': {'":': 4, '<': 13, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1925027', 'n_tokens_mistral': 4212, 'n_tokens_neox': 3739, 'n_words': 718}