diff options
Diffstat (limited to 'src')
9 files changed, 618 insertions, 971 deletions
diff --git a/src/main/java/org/onap/music/client/MusicClient.java b/src/main/java/org/onap/music/client/MusicClient.java deleted file mode 100644 index e67c98a4..00000000 --- a/src/main/java/org/onap/music/client/MusicClient.java +++ /dev/null @@ -1,581 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * 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. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ -package org.onap.music.client; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.onap.music.datastore.jsonobjects.JsonInsert; -import org.onap.music.datastore.jsonobjects.JsonKeySpace; -import org.onap.music.datastore.jsonobjects.JsonTable; -import org.onap.music.eelf.logging.EELFLoggerDelegate; -import org.onap.music.lockingservice.MusicLockingService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import com.datastax.driver.core.Cluster; -import com.datastax.driver.core.ColumnDefinitions; -import com.datastax.driver.core.ColumnDefinitions.Definition; -import com.datastax.driver.core.ConsistencyLevel; -import com.datastax.driver.core.DataType; -import com.datastax.driver.core.KeyspaceMetadata; -import com.datastax.driver.core.ResultSet; -import com.datastax.driver.core.Row; -import com.datastax.driver.core.Session; -import com.datastax.driver.core.SimpleStatement; -import com.datastax.driver.core.Statement; -import com.datastax.driver.core.TableMetadata; -import com.datastax.driver.core.querybuilder.Clause; -import com.datastax.driver.core.querybuilder.Delete; -import com.datastax.driver.core.querybuilder.QueryBuilder; -import com.datastax.driver.core.querybuilder.Select; - -/** - * A MUSIC client that talks directly to Cassandra/ZooKeeper. This was taken, and slightly modified, - * from the REST version of the code. - * - * @author Robert Eby - */ -public class MusicClient { - private EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(MusicClient.class); - - private final String[] music_hosts; // array of hosts in the music cluster - private Cluster cluster; // MUSIC Cassandra cluster - private Session session; // MUSIC Cassandra session - private MusicLockingService mls; // ZooKeeper - private final Set<String> lockNames;// set of active lock names - - /** - * Create a MUSIC client that talks to MUSIC on localhost. - */ - public MusicClient() { - this("127.0.0.1"); - } - - /** - * Create a MUSIC client that talks to MUSIC on a remote host. The string <i>hosts</i> is a - * comma-separated list of IP addresses for remote instances of Cassandra/ZooKeeper. - * - * @param hosts the list of hostnames - */ - public MusicClient(String hosts) { - music_hosts = hosts.split(","); - if (cluster == null) { - LOG.debug("Initializing MUSIC Client with endpoints " + hosts); - cluster = Cluster.builder().addContactPoints(music_hosts).build(); - } - session = cluster.connect(); - mls = null; - lockNames = new HashSet<String>(); - } - - /** - * Close the connection to MUSIC. - */ - public void close() { - if (session != null) { - session.close(); - session = null; - } - if (cluster != null) { - cluster.close(); - cluster = null; - } - } - - /** - * Be sure to close the connection to MUSIC when this object is GC-ed. - */ - @Override - protected void finalize() { - close(); - } - - /** - * Return a String representation of the music hosts used by this object. - * - * @return the string - */ - @Override - public String toString() { - List<String> t = Arrays.asList(music_hosts); - return "MUSIC hosts=" + t.toString(); - } - - /** - * Create a lock. - * - * @see org.onap.music.lockingservice.MusicLockingService#createLock(String) - * @param lockName the lock name - * @return FILL IN - */ - public String createLock(String lockName) { - String ln = "/" + lockName; - synchronized (lockNames) { - lockNames.add(ln); - } - return getLockingService().createLockId(ln); - } - - /** - * Acquire a lock. - * - * @see org.onap.music.lockingservice.MusicLockingService#lock(String) - * @param lockName the lock name - * @return FILL IN - */ - public boolean acquireLock(String lockName) { - return getLockingService().isMyTurn(lockName); - } - - /** - * Get the lock holder. - * - * @see org.onap.music.lockingservice.MusicLockingService#currentLockHolder(String) - * @param lockName the lock name - * @return FILL IN - */ - public String getLockHolder(String lockName) { - return getLockingService().whoseTurnIsIt("/" + lockName); - } - - /** - * Unlock a lock. - * - * @see org.onap.music.lockingservice.MusicLockingService#unlock(String) - * @param lockName the lock name - */ - public void unlockLock(String lockName) { - getLockingService().unlockAndDeleteId(lockName); - } - - /** - * Delete a lock. - * - * @see org.onap.music.lockingservice.MusicLockingService#deleteLock(String) - * @param lockName the lock name - */ - public void deleteLock(String lockName) { - String ln = "/" + lockName; - synchronized (lockNames) { - lockNames.remove(ln); - } - getLockingService().deleteLock(ln); - } - - /** - * Delete all locks. - * - * @see org.onap.music.lockingservice.MusicLockingService#deleteLock(String) - * @return true - */ - public boolean deleteAllLocks() { - synchronized (lockNames) { - for (String lockName : lockNames) { - deleteLock(lockName); - } - lockNames.clear(); - } - return true; - } - - /** - * Create a keyspace using the default replication configuration. - * - * @param keyspaceName the name of the keyspace - * @return always true currently - * @throws Exception Cassandra exceptions are passed through - */ - public boolean createKeyspace(String keyspaceName) throws Exception { - Map<String, Object> repl = new HashMap<String, Object>(); - repl.put("class", "SimpleStrategy"); - repl.put("replication_factor", 1); - Map<String, String> consistencyInfo = Collections.singletonMap("type", "eventual"); - JsonKeySpace jsonKp = new JsonKeySpace(); - jsonKp.setConsistencyInfo(consistencyInfo); - jsonKp.setDurabilityOfWrites("true"); - jsonKp.setReplicationInfo(repl); - return createKeyspace(keyspaceName, jsonKp); - } - - public boolean createKeyspace(String keyspaceName, JsonKeySpace kspObject) throws Exception { - String consistency = extractConsistencyInfo(keyspaceName, kspObject.getConsistencyInfo()); - Map<String, Object> replicationInfo = kspObject.getReplicationInfo(); - String durability = ""; - if (kspObject.getDurabilityOfWrites() != null) - durability = " AND durable_writes = " + kspObject.getDurabilityOfWrites(); - String query = String.format( - "CREATE KEYSPACE IF NOT EXISTS %s WITH replication = { %s } %s;", - keyspaceName, jsonMaptoSqlString(replicationInfo, ","), durability); - LOG.info(EELFLoggerDelegate.applicationLogger,query); - executeCreateQuery(query, consistency); - return true; - } - - public boolean dropKeyspace(String keyspaceName, JsonKeySpace kspObject) throws Exception { - String consistency = extractConsistencyInfo(keyspaceName, kspObject.getConsistencyInfo()); - String query = String.format("DROP KEYSPACE %s;", keyspaceName); - LOG.info(EELFLoggerDelegate.applicationLogger,query); - executeCreateQuery(query, consistency); - return false; - } - - public boolean createTable(String tablename, Map<String, String> cols) throws Exception { - JsonTable tableObj = new JsonTable(); - Map<String, String> map = new HashMap<String, String>(); // This should be in the - // consutructor! - map.put("type", "eventual"); - tableObj.setConsistencyInfo(map); - return createTable(tablename, cols, tableObj); - } - - public boolean createTable(String tablename, Map<String, String> cols, JsonTable tableObj) - throws Exception { - // Note: https://docs.datastax.com/en/cql/3.0/cql/cql_reference/create_table_r.html - - // first read the information about the table fields - StringBuilder fields = new StringBuilder(); - String prefix = ""; - for (String key : cols.keySet()) { - fields.append(prefix).append(key).append(" ").append(cols.get(key)); - prefix = ", "; - } - - String query = String.format("CREATE TABLE IF NOT EXISTS %s (%s);", tablename, - fields.toString()); - - LOG.debug(query); - String consistency = extractConsistencyInfo(tablename, tableObj.getConsistencyInfo()); - executeCreateQuery(query, consistency); - return false; - } - - public boolean dropTable(String name) { - // TODO - return false; - } - - public boolean insertRow(String name, Map<String, Object> valuesMap) throws Exception { - Map<String, String> consistencyInfo = Collections.singletonMap("type", "eventual"); - return insertRow(name, valuesMap, consistencyInfo, new JsonInsert()); - } - - public boolean insertRow(String tablename, Map<String, Object> valuesMap, - Map<String, String> consistencyInfo, JsonInsert insObj) throws Exception { - // Note: https://docs.datastax.com/en/cql/3.0/cql/cql_reference/insert_r.html - String[] parts = tablename.split("\\."); - KeyspaceMetadata ks = cluster.getMetadata().getKeyspace(parts[0]); - TableMetadata tableInfo = ks.getTable(parts[1]); - - StringBuilder fields = new StringBuilder(); - StringBuilder values = new StringBuilder(); - String prefix = ""; - for (String key : valuesMap.keySet()) { - fields.append(prefix).append(key); - Object valueObj = valuesMap.get(key); - DataType colType = tableInfo.getColumn(key).getType(); - values.append(prefix).append(convertToSqlDataType(colType, valueObj)); - prefix = ", "; - } - - String suffix = getTTLSuffix(insObj); - String query = String.format("INSERT INTO %s (%s) VALUES (%s)%s;", tablename, - fields.toString(), values.toString(), suffix); - LOG.info(EELFLoggerDelegate.applicationLogger,query); - - String consistency = extractConsistencyInfo(tablename, consistencyInfo); - executeCreateQuery(query, consistency); - return false; - } - - public boolean lockRow(String name, Map<String, String> cols) { - // TODO - return false; - } - - /** - * Select ALL rows in the table. - * - * @param tablename the name of the table - * @return a list of maps, one map per row - */ - public List<Map<String, Object>> selectRows(final String tablename) { - return selectRows(tablename, new HashMap<String, String>()); - } - - public List<Map<String, Object>> selectRows(final String tablename, Map<String, String> cols) { - String ns = ""; - String tbl = tablename; - int ix = tbl.indexOf('.'); - if (ix >= 0) { - ns = tablename.substring(0, ix); - tbl = tablename.substring(ix + 1); - } - Select sel = QueryBuilder.select().all().from(ns, tbl); - Statement stmt = sel; - if (cols.size() == 1) { - // only handles 1 WHERE value right now - String k = cols.keySet().iterator().next(); - Clause eqclause = QueryBuilder.eq(k, cols.get(k)); - stmt = sel.where(eqclause); - } - ResultSet resultset = session.execute(stmt); - List<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); - for (Row row : resultset) { - Map<String, Object> map = new HashMap<String, Object>(); - for (Definition definition : row.getColumnDefinitions()) { - map.put(definition.getName(), - readRow(row, definition.getName(), definition.getType())); - } - results.add(map); - } - return results; - } - - private Object readRow(final Row row, final String name, final DataType colType) { - switch (colType.getName()) { - case BIGINT: - return row.getLong(name); - case BOOLEAN: - return row.getBool(name); - case DOUBLE: - return row.getDouble(name); - case FLOAT: - return row.getFloat(name); - case INT: - return row.getInt(name); - case MAP: - return row.getMap(name, String.class, String.class); - case UUID: - return row.getUUID(name); - case TEXT: - case VARCHAR: - return row.getString(name); - case VARINT: - return row.getVarint(name); - // These are not supported right now.... - // ASCII - // BLOB - // COUNTER - // CUSTOM - // DECIMAL - // INET - // LIST - // SET - // TIMESTAMP - // TIMEUUID - // TUPLE - // UDT - default: - return null; - } - } - - @Deprecated - public List<Map<String, String>> OLDselectRows(String tablename, Map<String, String> cols) { - String query = String.format("SELECT * FROM %s", tablename); - if (cols.size() > 0) { - // add WHERE clause - // String[] parts = tablename.split("\\."); - // KeyspaceMetadata ks = cluster.getMetadata().getKeyspace(parts[0]); - // TableMetadata tableInfo = ks.getTable(parts[1]); - String whereclause = " WHERE"; - String prefix = ""; - for (String key : cols.keySet()) { - String val = cols.get(key); - // DataType colType = tableInfo.getColumn(key).getType(); - whereclause = String.format("%s%s %s = '%s'", whereclause, prefix, key, val); - prefix = " AND"; - } - query += whereclause; - } - LOG.debug(query); - ResultSet resultset = session.execute(query); - List<Map<String, String>> results = new ArrayList<Map<String, String>>(); - for (Row row : resultset) { - ColumnDefinitions colInfo = row.getColumnDefinitions(); - Map<String, String> map = new HashMap<String, String>(); - for (Definition definition : colInfo) { - // map.put(definition.getName(), (String)MusicDataStore.readRow(row, - // definition.getName(), definition.getType())); - } - results.add(map); - } - return results; - } - - public void updateRows(String tablename, Map<String, String> cols, Map<String, Object> vals) - throws Exception { - Map<String, String> consistencyInfo = Collections.singletonMap("type", "eventual"); - updateRows(tablename, cols, vals, consistencyInfo, new JsonInsert()); - } - - public void updateRows(String tablename, Map<String, String> cols, Map<String, Object> vals, - Map<String, String> consistencyInfo, JsonInsert insObj) throws Exception { - // https://docs.datastax.com/en/cql/3.0/cql/cql_reference/update_r.html - - // obtain the field value pairs of the update - String[] parts = tablename.split("\\."); - KeyspaceMetadata ks = cluster.getMetadata().getKeyspace(parts[0]); - TableMetadata tableInfo = ks.getTable(parts[1]); - - StringBuilder fields = new StringBuilder(); - String prefix = ""; - for (String key : vals.keySet()) { - Object valueObj = vals.get(key); - String valueString = convertToSqlDataType(tableInfo.getColumn(key).getType(), valueObj); - fields.append(prefix).append(key).append(" = ").append(valueString); - prefix = ", "; - } - - // get the row specifier - StringBuilder rows = new StringBuilder(); - String primaryKey = ""; - prefix = ""; - for (String key : cols.keySet()) { - String indValue = cols.get(key); - DataType colType = tableInfo.getColumn(key).getType(); - String formattedValue = convertToSqlDataType(colType, indValue); - primaryKey = primaryKey + indValue; - rows.append(prefix).append(key).append(" = ").append(formattedValue); - prefix = " AND "; - } - - String using = getTTLSuffix(insObj); - String query = String.format("UPDATE %s%s SET %s WHERE %s;", tablename, using, - fields.toString(), rows.toString()); - LOG.debug(query); - - String consistency = extractConsistencyInfo(tablename, consistencyInfo); - executeCreateQuery(query, consistency); - } - - public void deleteRows(String tablename, Map<String, String> cols) { - String ns = ""; - String tbl = tablename; - int ix = tbl.indexOf('.'); - if (ix >= 0) { - ns = tablename.substring(0, ix); - tbl = tablename.substring(ix + 1); - } - Delete stmt = QueryBuilder.delete().from(ns, tbl); - if (cols.size() == 1) { - // only handles 1 WHERE value right now - String k = cols.keySet().iterator().next(); - Clause eqclause = QueryBuilder.eq(k, cols.get(k)); - session.execute(stmt.where(eqclause)); - } else { - session.execute(stmt); - } - } - - private String getTTLSuffix(JsonInsert insObj) { - String ttl = insObj.getTtl(); - String timestamp = insObj.getTimestamp(); - if (ttl != null && ttl.length() > 0) { - if (timestamp != null && timestamp.length() > 0) { - return " USING TTL " + ttl + " AND TIMESTAMP " + timestamp; - } else { - return " USING TTL " + ttl; - } - } else if (timestamp != null && timestamp.length() > 0) { - return " USING TIMESTAMP " + timestamp; - } - return ""; - } - - private MusicLockingService getLockingService() { - if (mls == null) { - mls = new MusicLockingService(music_hosts[0]); - } - return mls; - } - - private String extractConsistencyInfo(String key, Map<String, String> consistencyInfo) - throws Exception { - String consistency = ""; - if (consistencyInfo.get("type").equalsIgnoreCase("atomic")) { - String lockId = consistencyInfo.get("lockId"); - String lockName = lockId.substring(lockId.indexOf("$") + 1); - lockName = lockName.substring(0, lockName.indexOf("$")); - - // first ensure that the lock name is correct before seeing if it has access - if (!lockName.equalsIgnoreCase(key)) - throw new Exception("THIS LOCK IS NOT FOR THE KEY: " + key); - - String lockStatus = getLockingService().isMyTurn(lockId) + ""; - if (lockStatus.equalsIgnoreCase("false")) - throw new Exception("YOU DO NOT HAVE THE LOCK"); - return "atomic"; - } - if (consistencyInfo.get("type").equalsIgnoreCase("eventual")) - return "eventual"; - throw new Exception("Consistency type " + consistency + " unknown!!"); - } - - // utility function to parse json map into sql like string - private String jsonMaptoSqlString(Map<String, Object> jMap, String lineDelimiter) { - String sql = ""; - String prefix = ""; - for (Map.Entry<String, Object> entry : jMap.entrySet()) { - Object ot = entry.getValue(); - String value = ot + ""; - if (ot instanceof String) { - value = "'" + value + "'"; - } - sql = String.format("%s%s'%s': %s", sql, prefix, entry.getKey(), value); - prefix = lineDelimiter; - } - return sql; - } - - private String convertToSqlDataType(DataType type, Object valueObj) { - switch (type.getName()) { - case TEXT: - String t = valueObj.toString(); - t = t.replaceAll("'", "''"); - return "'" + t + "'"; - case MAP: - @SuppressWarnings("unchecked") - Map<String, Object> otMap = (Map<String, Object>) valueObj; - return "{" + jsonMaptoSqlString(otMap, ",") + "}"; - default: - case UUID: - return valueObj.toString(); - } - } - - private void executeCreateQuery(String query, String consistency) throws Exception { - Statement statement = new SimpleStatement(query); - if (consistency.equalsIgnoreCase("atomic")) - statement.setConsistencyLevel(ConsistencyLevel.ALL); - else if (consistency.equalsIgnoreCase("eventual")) - statement.setConsistencyLevel(ConsistencyLevel.ONE); - else - throw new Exception("Consistency level " + consistency + " unknown!!"); - session.execute(statement); - } -} diff --git a/src/main/java/org/onap/music/client/MusicRestClient.java b/src/main/java/org/onap/music/client/MusicRestClient.java deleted file mode 100644 index 93a2e12b..00000000 --- a/src/main/java/org/onap/music/client/MusicRestClient.java +++ /dev/null @@ -1,384 +0,0 @@ -/* - * ============LICENSE_START========================================== - * org.onap.music - * =================================================================== - * Copyright (c) 2017 AT&T Intellectual Property - * =================================================================== - * 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. - * - * ============LICENSE_END============================================= - * ==================================================================== - */ -package org.onap.music.client; - -import java.util.HashMap; -import java.util.Map; -import java.util.Random; -import javax.ws.rs.core.MediaType; -import org.onap.music.datastore.jsonobjects.JsonDelete; -import org.onap.music.datastore.jsonobjects.JsonInsert; -import org.onap.music.datastore.jsonobjects.JsonKeySpace; -import org.onap.music.datastore.jsonobjects.JsonTable; -import org.onap.music.main.MusicUtil; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.api.json.JSONConfiguration; - -public class MusicRestClient { - String[] musicNodes; - - public MusicRestClient(String[] musicNodes) { - this.musicNodes = musicNodes; - } - - public MusicRestClient(String oneMusicNode) { - musicNodes = new String[1]; - this.musicNodes[0] = oneMusicNode; - } - - public String getMusicNodeURL() { - String musicurl = "http://" + getMusicNodeIp() + ":8080/MUSIC/rest"; - return musicurl; - } - - private String getMusicNodeIp() { - Random r = new Random(); - int index = r.nextInt(musicNodes.length); - return musicNodes[index]; - } - - public void createKeyspace(String keyspaceName) { - Map<String, Object> replicationInfo = new HashMap<String, Object>(); - replicationInfo.put("class", "SimpleStrategy"); - replicationInfo.put("replication_factor", 1); - String durabilityOfWrites = "false"; - Map<String, String> consistencyInfo = new HashMap<String, String>(); - consistencyInfo.put("type", "eventual"); - org.onap.music.datastore.jsonobjects.JsonKeySpace jsonKp = new JsonKeySpace(); - jsonKp.setConsistencyInfo(consistencyInfo); - jsonKp.setDurabilityOfWrites(durabilityOfWrites); - jsonKp.setReplicationInfo(replicationInfo); - - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - - WebResource webResource = client.resource(getMusicNodeURL() + "/keyspaces/" + keyspaceName); - - ClientResponse response = webResource.accept("application/json").type("application/json") - .post(ClientResponse.class, jsonKp); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - - } - - public void createStringMapTable(String keyspaceName, String tableName, - Map<String, String> fields) { - Map<String, String> consistencyInfo = new HashMap<String, String>(); - consistencyInfo.put("type", "eventual"); - - JsonTable jtab = new JsonTable(); - jtab.setFields(fields); - jtab.setConsistencyInfo(consistencyInfo); - - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - String url = getMusicNodeURL() + "/keyspaces/" + keyspaceName + "/tables/" + tableName; - WebResource webResource = client.resource(url); - - ClientResponse response = webResource.accept("application/json").type("application/json") - .post(ClientResponse.class, jtab); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - - } - - public void checkMusicVersion() { - Client client = Client.create(); - - WebResource webResource = client.resource(getMusicNodeURL() + "/version"); - - ClientResponse response = webResource.accept("text/plain").get(ClientResponse.class); - - if (response.getStatus() != 200) { - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - } - - String output = response.getEntity(String.class); - } - - public void createRow(String keyspaceName, String tableName, Map<String, Object> values) { - Map<String, String> consistencyInfo = new HashMap<String, String>(); - consistencyInfo.put("type", "eventual"); - - JsonInsert jIns = new JsonInsert(); - jIns.setValues(values); - jIns.setConsistencyInfo(consistencyInfo); - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - - String url = getMusicNodeURL() + "/keyspaces/" + keyspaceName + "/tables/" + tableName - + "/rows"; - WebResource webResource = client.resource(url); - - ClientResponse response = webResource.accept("application/json").type("application/json") - .post(ClientResponse.class, jIns); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus() + "url:" - + url + "values:" + values); - - - } - - private void basicUpdateRow(String keyspaceName, String tableName, String primaryKeyName, - String primaryKeyValue, Map<String, Object> values, - Map<String, String> consistencyInfo) { - JsonInsert jIns = new JsonInsert(); - jIns.setValues(values); - jIns.setConsistencyInfo(consistencyInfo); - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - String url = getMusicNodeURL() + "/keyspaces/" + keyspaceName + "/tables/" + tableName - + "/rows?" + primaryKeyName + "=" + primaryKeyValue; - WebResource webResource = client.resource(url); - - ClientResponse response = webResource.accept("application/json").type("application/json") - .put(ClientResponse.class, jIns); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus() + "url:" - + url + " values:" + values); - - } - - public void updateEntry(String keyspaceName, String tableName, String primaryKeyName, - String primaryKeyValue, Map<String, Object> values) { - Map<String, String> consistencyInfo = new HashMap<String, String>(); - consistencyInfo.put("type", "eventual"); - basicUpdateRow(keyspaceName, tableName, primaryKeyName, primaryKeyValue, values, - consistencyInfo); - } - - public void deleteEntry(String keyspaceName, String tableName, String primaryKeyName, - String primaryKeyValue) { - Map<String, String> consistencyInfo = new HashMap<String, String>(); - consistencyInfo.put("type", "eventual"); - - JsonDelete jDel = new JsonDelete(); - jDel.setConsistencyInfo(consistencyInfo); - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - String url = getMusicNodeURL() + "/keyspaces/" + keyspaceName + "/tables/" + tableName - + "/rows?" + primaryKeyName + "=" + primaryKeyValue; - WebResource webResource = client.resource(url); - - ClientResponse response = webResource.accept("application/json").type("application/json") - .delete(ClientResponse.class, jDel); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException( - "Failed : HTTP error code : " + response.getStatus() + "url:" + url); - - } - - public Map<String, Object> readRow(String keyspaceName, String tableName, String primaryKeyName, - String primaryKeyValue) { - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - String url = getMusicNodeURL() + "/keyspaces/" + keyspaceName + "/tables/" + tableName - + "/rows?" + primaryKeyName + "=" + primaryKeyValue; - WebResource webResource = client.resource(url); - - ClientResponse response = webResource.accept("application/json").get(ClientResponse.class); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - - Map<String, Object> output = response.getEntity(Map.class); - return output; - } - - public Map<String, Object> readAllRows(String keyspaceName, String tableName) { - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - String url = getMusicNodeURL() + "/keyspaces/" + keyspaceName + "/tables/" + tableName - + "/rows"; - WebResource webResource = client.resource(url); - - ClientResponse response = webResource.accept("application/json").get(ClientResponse.class); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - - Map<String, Object> output = response.getEntity(Map.class); - return output; - } - - - public void dropKeySpace(String keyspaceName) { - Map<String, String> consistencyInfo = new HashMap<String, String>(); - consistencyInfo.put("type", "eventual"); - - JsonKeySpace jsonKp = new JsonKeySpace(); - jsonKp.setConsistencyInfo(consistencyInfo); - - ClientConfig clientConfig = new DefaultClientConfig(); - - clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - - Client client = Client.create(clientConfig); - - WebResource webResource = client.resource(getMusicNodeURL() + "/keyspaces/" + keyspaceName); - - ClientResponse response = - webResource.type("application/json").delete(ClientResponse.class, jsonKp); - - if (response.getStatus() < 200 || response.getStatus() > 299) - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - } - - public String createLock(String primaryKeyValue) { - Client client = Client.create(); - String msg = getMusicNodeURL() + "/locks/create/" + primaryKeyValue; - WebResource webResource = client.resource(msg); - - WebResource.Builder wb = webResource.accept(MediaType.TEXT_PLAIN); - - ClientResponse response = wb.post(ClientResponse.class); - - if (response.getStatus() != 200) { - throw new RuntimeException( - "Failed : HTTP error code : " + response.getStatus() + "url:" + msg); - } - - String output = response.getEntity(String.class); - - return output; - } - - public boolean acquireLock(String lockId) { - Client client = Client.create(); - String msg = getMusicNodeURL() + "/locks/acquire/" + lockId; - WebResource webResource = client.resource(msg); - - - WebResource.Builder wb = webResource.accept(MediaType.TEXT_PLAIN); - - ClientResponse response = wb.get(ClientResponse.class); - - if (response.getStatus() != 200) { - throw new RuntimeException( - "Failed : HTTP error code : " + response.getStatus() + "url:" + msg); - } - - String output = response.getEntity(String.class); - Boolean status = Boolean.parseBoolean(output); - return status; - } - - public void releaseLock(String lockId) { - Client client = Client.create(); - WebResource webResource = client.resource(getMusicNodeURL() + "/locks/release/" + lockId); - - ClientResponse response = webResource.delete(ClientResponse.class); - - - if (response.getStatus() != 204) { - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - } - } - - - public void updateRowAtomically(String keyspaceName, String tableName, String primaryKeyName, - String primaryKeyValue, Map<String, Object> values) { - /* - * create lock for the candidate. The music API dictates that the lock name must be of the - * form keyspacename.tableName.primaryKeyName - */ - - String lockName = keyspaceName + "." + tableName + "." + primaryKeyValue; - String lockId = createLock(lockName); - while (acquireLock(lockId) != true); - - - Map<String, String> consistencyInfo = new HashMap<String, String>(); - consistencyInfo.put("type", "atomic"); - consistencyInfo.put("lockId", lockId); - - basicUpdateRow(keyspaceName, tableName, primaryKeyName, primaryKeyValue, values, - consistencyInfo); - - // release lock now that the operation is done - releaseLock(lockId); - - } - - public String getMusicId() { - - Client client = Client.create(); - - WebResource webResource = client.resource(getMusicNodeURL() + "/nodeId"); - ClientResponse response = webResource.accept("text/plain").get(ClientResponse.class); - - if (response.getStatus() != 200) { - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - } - - String output = response.getEntity(String.class); - return output; - } - - public void deleteRowAtomically(String keyspaceName, String tableName, String primaryKeyName, - String primaryKeyValue, Map<String, Object> values) { - - } - - public void deleteLock(String lockName) { - Client client = Client.create(); - WebResource webResource = client.resource(getMusicNodeURL() + "/locks/delete/" + lockName); - - ClientResponse response = webResource.delete(ClientResponse.class); - - - if (response.getStatus() != 204) { - throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); - } - } -} - diff --git a/src/main/java/org/onap/music/main/MusicUtil.java b/src/main/java/org/onap/music/main/MusicUtil.java index 317f2560..a31e33f9 100755 --- a/src/main/java/org/onap/music/main/MusicUtil.java +++ b/src/main/java/org/onap/music/main/MusicUtil.java @@ -56,7 +56,7 @@ public class MusicUtil { private static String defaultMusicIp = "localhost"; private static boolean debug = true; private static String version = "2.3.0"; - public static String musicRestIp = "localhost"; + private static String musicRestIp = "localhost"; private static String musicPropertiesFilePath = "/opt/app/music/etc/music.properties"; private static long defaultLockLeasePeriod = 6000; private static final String[] propKeys = new String[] { "zookeeper.host", "cassandra.host", "music.ip", "debug", @@ -70,7 +70,7 @@ public class MusicUtil { public static final String DEFAULTKEYSPACENAME = "TBD"; private static String cassName = "cassandra"; - private static String cassPwd = "cassandra"; + private static String cassPwd; private static String aafEndpointUrl = null; /** @@ -472,9 +472,9 @@ public class MusicUtil { Map<String, HashMap<String, Object>> results = new HashMap<>(); HashMap<String, Object> tempMap = new HashMap<>(); Map<String, Object> result = new HashMap<>(); - result.put("Error Description", ex.getMessage()); - tempMap.put("Error", result); - results.put("Result", tempMap); + result.put("error-description", ex.getMessage()); + tempMap.put("error", result); + results.put("result", tempMap); return results; } } diff --git a/src/test/java/org/onap/music/benchmarks/MicroBenchMarks.java b/src/test/java/org/onap/music/benchmarks/MicroBenchMarks.java index a9b40aec..c267d254 100644 --- a/src/test/java/org/onap/music/benchmarks/MicroBenchMarks.java +++ b/src/test/java/org/onap/music/benchmarks/MicroBenchMarks.java @@ -37,7 +37,7 @@ import com.sun.jersey.api.json.JSONConfiguration; public class MicroBenchMarks { final String keyspaceName = "shankarks"; - final String musicurl = "http://" + MusicUtil.musicRestIp + ":8080/MUSIC/rest/formal"; + final String musicurl = "http://" + MusicUtil.getMusicRestIp() + ":8080/MUSIC/rest/formal"; final String userForGets = "shankarUserForGets"; public MicroBenchMarks() { diff --git a/src/test/java/org/onap/music/unittests/JsonLockResponseTest.java b/src/test/java/org/onap/music/unittests/JsonLockResponseTest.java new file mode 100644 index 00000000..cd5773dc --- /dev/null +++ b/src/test/java/org/onap/music/unittests/JsonLockResponseTest.java @@ -0,0 +1,186 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * 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. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ +package org.onap.music.unittests; + +import static org.junit.Assert.*; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.onap.music.lockingservice.MusicLockState; +import org.onap.music.lockingservice.MusicLockState.LockStatus; +import org.onap.music.main.ResultType; +import org.onap.music.response.jsonobjects.JsonLockResponse; + +public class JsonLockResponseTest { + + JsonLockResponse response = new JsonLockResponse(ResultType.SUCCESS); + + @Test + public void error1() { + Boolean result = false; + response.setError(""); + result = response.getError().equals("error1"); + assertFalse("Success",result); + } + + @Test + public void error() { + Boolean result = false; + response.setError("error1"); + result = response.getError().equals("error1"); + assertTrue("Success",result); + } + + @Test + public void lock1() { + Boolean result = false; + response.setLock(""); + result = response.getLock().equals("lock1"); + assertFalse("Success",result); + } + + @Test + public void lock() { + Boolean result = false; + response.setLock("lock1"); + result = response.getLock().equals("lock1"); + assertTrue("Success",result); + } + + @Test + public void status1() { + Boolean result = false; + response.setStatus(null); + result = response.getStatus() == ResultType.SUCCESS; + assertFalse("Success",result); + } + + @Test + public void status() { + Boolean result = false; + response.setStatus(ResultType.SUCCESS); + result = response.getStatus() == ResultType.SUCCESS; + assertTrue("Success",result); + } + + + + @Test + public void lockHolder1() { + Boolean result = false; + response.setLockHolder(""); + result = response.getLockHolder().equals("LockHolder"); + assertFalse("Success",result); + } + + @Test + public void lockHolder() { + Boolean result = false; + response.setLockHolder("LockHolder"); + result = response.getLockHolder().equals("LockHolder"); + assertTrue("Success",result); + } + + @Test + public void lockLease1() { + Boolean result = false; + response.setLockLease(""); + result = response.getLockLease().equals("lockLease"); + assertFalse("Success",result); + } + + @Test + public void lockLease() { + Boolean result = false; + response.setLockLease("lockLease"); + result = response.getLockLease().equals("lockLease"); + assertTrue("Success",result); + } + + @Test + public void lockStatus1() { + Boolean result = false; + response.setLockStatus(null); + result = response.getLockStatus() == MusicLockState.LockStatus.LOCKED; + assertFalse("Success",result); + } + + @Test + public void lockStatus() { + Boolean result = false; + response.setLockStatus(MusicLockState.LockStatus.LOCKED); + result = response.getLockStatus() == MusicLockState.LockStatus.LOCKED; + assertTrue("Success",result); + } + + @Test + public void message1() { + Boolean result = false; + response.setMessage(""); + result = response.getMessage().equals("message"); + assertFalse("Success",result); + } + + @Test + public void message() { + Boolean result = false; + response.setMessage("message"); + result = response.getMessage().equals("message"); + assertTrue("Success",result); + } + + @Test + public void map() { + Boolean result = false; + response.setMessage("message"); + response.setLockStatus(MusicLockState.LockStatus.LOCKED); + response.setLockHolder("LockHolder"); + response.setLockLease("lockLease"); + response.setStatus(ResultType.SUCCESS); + response.setLock("lock1"); + response.setError("error1"); + Map<String,Object> myMap = response.toMap(); + result = myMap.containsKey("status"); + System.out.println(response.toString()); + assertTrue("Success",result); + } + + @Test + public void map1() { + Boolean result = false; + response.setMessage(null); + response.setLockStatus(null); + response.setLockHolder(null); + response.setLockLease(null); + response.setStatus(null); + response.setLock(null); + response.setError(null); + Map<String,Object> myMap = response.toMap(); + result = myMap.containsKey("error"); + System.out.println(result); + assertFalse("Success",result); + } + + + + +} diff --git a/src/test/java/org/onap/music/unittests/JsonResponseTest.java b/src/test/java/org/onap/music/unittests/JsonResponseTest.java new file mode 100644 index 00000000..55e5965e --- /dev/null +++ b/src/test/java/org/onap/music/unittests/JsonResponseTest.java @@ -0,0 +1,83 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * 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. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.unittests; + +import static org.junit.Assert.*; +import java.util.Map; +import org.junit.Test; +import org.onap.music.response.jsonobjects.JsonResponse; + +public class JsonResponseTest { + + JsonResponse result = null; + + @Test + public void testJsonResponseBooleanStringString() { + result = new JsonResponse(true,"error","version"); + assertEquals("error",result.getError()); + } + + @Test + public void testJsonResponse() { + result = new JsonResponse(); + assertFalse(result.getStatus()); + } + + @Test + public void testStatus() { + result = new JsonResponse(); + result.setStatus(true); + assertTrue(result.getStatus()); + result = new JsonResponse(false,"error","version"); + assertFalse(result.getStatus()); + } + + @Test + public void testError() { + result = new JsonResponse(); + result.setError("error"); + assertTrue(result.getError().equals("error")); + result.setError(""); + assertFalse(result.getError().equals("error")); + } + + @Test + public void testVersion() { + result = new JsonResponse(); + result.setVersion("version"); + assertTrue(result.getVersion().equals("version")); + result.setVersion(""); + assertFalse(result.getVersion().equals("version")); + } + + @Test + public void testToMap() { + result = new JsonResponse(true,"error","version"); + Map<String,Object> myMap = result.toMap(); + assertTrue(myMap.containsKey("status")); + result = new JsonResponse(false,"",""); + myMap = result.toMap(); + assertTrue(myMap.containsKey("status")); + } + +} diff --git a/src/test/java/org/onap/music/unittests/MusicUtilTest.java b/src/test/java/org/onap/music/unittests/MusicUtilTest.java new file mode 100644 index 00000000..35ec3791 --- /dev/null +++ b/src/test/java/org/onap/music/unittests/MusicUtilTest.java @@ -0,0 +1,217 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * 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. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.unittests; + +import static org.junit.Assert.*; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.apache.cassandra.exceptions.PreparedQueryNotFoundException; +import org.junit.Test; +import org.onap.music.datastore.PreparedQueryObject; +import org.onap.music.exceptions.MusicServiceException; +import org.onap.music.main.MusicUtil; +import com.datastax.driver.core.DataType; +import javassist.CodeConverter.ArrayAccessReplacementMethodNames; + +public class MusicUtilTest { + + @Test + public void testGetCassName() { + MusicUtil.setCassName("Cassandra"); + assertTrue(MusicUtil.getCassName().equals("Cassandra")); + } + + @Test + public void testGetCassPwd() { + MusicUtil.setCassPwd("Cassandra"); + assertTrue(MusicUtil.getCassPwd().equals("Cassandra")); + } + + @Test + public void testGetAafEndpointUrl() { + MusicUtil.setAafEndpointUrl("url"); + assertEquals(MusicUtil.getAafEndpointUrl(),"url"); + } + + @Test + public void testGetMyId() { + MusicUtil.setMyId(1); + assertEquals(MusicUtil.getMyId(),1); + } + + @Test + public void testGetAllIds() { + List<String> ids = new ArrayList<String>(); + ids.add("1"); + ids.add("2"); + ids.add("3"); + MusicUtil.setAllIds(ids); + assertEquals(MusicUtil.getAllIds().get(0),"1"); + } + + @Test + public void testGetPublicIp() { + MusicUtil.setPublicIp("10.0.0.1"); + assertEquals(MusicUtil.getPublicIp(),"10.0.0.1"); + } + + @Test + public void testGetAllPublicIps() { + List<String> ips = new ArrayList<String>(); + ips.add("10.0.0.1"); + ips.add("10.0.0.2"); + ips.add("10.0.0.3"); + MusicUtil.setAllPublicIps(ips); + assertEquals(MusicUtil.getAllPublicIps().get(1),"10.0.0.2"); + } + + @Test + public void testGetPropkeys() { + assertEquals(MusicUtil.getPropkeys()[2],"music.ip"); + } + + @Test + public void testGetMusicRestIp() { + MusicUtil.setMusicRestIp("localhost"); + assertEquals(MusicUtil.getMusicRestIp(),"localhost"); + } + + @Test + public void testGetMusicPropertiesFilePath() { + MusicUtil.setMusicPropertiesFilePath("filepath"); + assertEquals(MusicUtil.getMusicPropertiesFilePath(),"filepath"); + } + + @Test + public void testGetDefaultLockLeasePeriod() { + MusicUtil.setDefaultLockLeasePeriod(5000); + assertEquals(MusicUtil.getDefaultLockLeasePeriod(),5000); + } + + @Test + public void testIsDebug() { + MusicUtil.setDebug(true); + assertTrue(MusicUtil.isDebug()); + } + + @Test + public void testGetVersion() { + MusicUtil.setVersion("1.0.0"); + assertEquals(MusicUtil.getVersion(),"1.0.0"); + } + + @Test + public void testGetMyZkHost() { + MusicUtil.setMyZkHost("10.0.0.2"); + assertEquals(MusicUtil.getMyZkHost(),"10.0.0.2"); + } + + @Test + public void testGetMyCassaHost() { + MusicUtil.setMyCassaHost("10.0.0.2"); + assertEquals(MusicUtil.getMyCassaHost(),"10.0.0.2"); + } + + @Test + public void testGetDefaultMusicIp() { + MusicUtil.setDefaultMusicIp("10.0.0.2"); + assertEquals(MusicUtil.getDefaultMusicIp(),"10.0.0.2"); + } + +// @Test +// public void testGetTestType() { +// fail("Not yet implemented"); // TODO +// } + + @Test + public void testIsValidQueryObject() { + PreparedQueryObject myQueryObject = new PreparedQueryObject(); + myQueryObject.appendQueryString("select * from apple where type = ?"); + myQueryObject.addValue("macintosh"); + assertTrue(MusicUtil.isValidQueryObject(true,myQueryObject)); + + myQueryObject.appendQueryString("select * from apple"); + assertTrue(MusicUtil.isValidQueryObject(false,myQueryObject)); + + myQueryObject.appendQueryString("select * from apple where type = ?"); + assertFalse(MusicUtil.isValidQueryObject(true,myQueryObject)); + + myQueryObject = new PreparedQueryObject(); + myQueryObject.appendQueryString(""); + System.out.println("#######" + myQueryObject.getQuery().isEmpty()); + assertFalse(MusicUtil.isValidQueryObject(false,myQueryObject)); + + + } + + @Test + public void testConvertToCQLDataType() { + Map<String,Object> myMap = new HashMap<String,Object>(); + myMap.put("name","tom"); + assertEquals(MusicUtil.convertToCQLDataType(DataType.varchar(),"Happy People"),"'Happy People'"); + assertEquals(MusicUtil.convertToCQLDataType(DataType.uuid(),UUID.fromString("29dc2afa-c2c0-47ae-afae-e72a645308ab")),"29dc2afa-c2c0-47ae-afae-e72a645308ab"); + assertEquals(MusicUtil.convertToCQLDataType(DataType.blob(),"Hi"),"Hi"); + assertEquals(MusicUtil.convertToCQLDataType(DataType.map(DataType.varchar(),DataType.varchar()),myMap),"{'name':'tom'}"); + } + + @Test + public void testConvertToActualDataType() { + assertEquals(MusicUtil.convertToActualDataType(DataType.varchar(),"Happy People"),"Happy People"); + assertEquals(MusicUtil.convertToActualDataType(DataType.uuid(),"29dc2afa-c2c0-47ae-afae-e72a645308ab"),UUID.fromString("29dc2afa-c2c0-47ae-afae-e72a645308ab")); + assertEquals(MusicUtil.convertToActualDataType(DataType.varint(),"1234"),BigInteger.valueOf(Long.parseLong("1234"))); + assertEquals(MusicUtil.convertToActualDataType(DataType.bigint(),"123"),Long.parseLong("123")); + assertEquals(MusicUtil.convertToActualDataType(DataType.cint(),"123"),Integer.parseInt("123")); + assertEquals(MusicUtil.convertToActualDataType(DataType.cfloat(),"123.01"),Float.parseFloat("123.01")); + assertEquals(MusicUtil.convertToActualDataType(DataType.cdouble(),"123.02"),Double.parseDouble("123.02")); + assertEquals(MusicUtil.convertToActualDataType(DataType.cboolean(),"true"),Boolean.parseBoolean("true")); + Map<String,Object> myMap = new HashMap<String,Object>(); + myMap.put("name","tom"); + assertEquals(MusicUtil.convertToActualDataType(DataType.map(DataType.varchar(),DataType.varchar()),myMap),myMap); + + } + + @Test + public void testJsonMaptoSqlString() { + Map<String,Object> myMap = new HashMap<>(); + myMap.put("name","tom"); + myMap.put("value",5); + String result = MusicUtil.jsonMaptoSqlString(myMap,","); + assertTrue(result.contains("name")); + assertTrue(result.contains("value")); + } + + @Test + public void testSetErrorResponse() { + Map<String,Object> myMap = new HashMap<>(); + myMap.put("name","tom"); + Map<String,HashMap<String,Object>> result = MusicUtil.setErrorResponse(new MusicServiceException("This is the error")); + Map<String,Object> testMap = (Map<String,Object>) result.get("result"); + Map<String,Object> error = (Map<String,Object>) testMap.get("error"); + assertTrue(error.containsKey("error-description")); + } + +} diff --git a/src/test/java/org/onap/music/unittests/ResultTypeTest.java b/src/test/java/org/onap/music/unittests/ResultTypeTest.java new file mode 100644 index 00000000..012629e0 --- /dev/null +++ b/src/test/java/org/onap/music/unittests/ResultTypeTest.java @@ -0,0 +1,43 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * 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. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.unittests; + +import static org.junit.Assert.*; +import org.junit.Test; +import org.onap.music.main.ResultType; + +public class ResultTypeTest { + + @Test + public void testResultType() { + assertEquals("SUCCESS",ResultType.SUCCESS.name()); + assertEquals("FAILURE",ResultType.FAILURE.name()); + } + + @Test + public void testGetResult() { + assertEquals("Success",ResultType.SUCCESS.getResult()); + assertEquals("Failure",ResultType.FAILURE.getResult()); + } + +} diff --git a/src/test/java/org/onap/music/unittests/ReturnTypeTest.java b/src/test/java/org/onap/music/unittests/ReturnTypeTest.java new file mode 100644 index 00000000..c22b0155 --- /dev/null +++ b/src/test/java/org/onap/music/unittests/ReturnTypeTest.java @@ -0,0 +1,83 @@ +/* + * ============LICENSE_START========================================== + * org.onap.music + * =================================================================== + * Copyright (c) 2017 AT&T Intellectual Property + * =================================================================== + * 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. + * + * ============LICENSE_END============================================= + * ==================================================================== + */ + +package org.onap.music.unittests; + +import static org.junit.Assert.*; +import java.util.Map; +import org.apache.tools.ant.filters.TokenFilter.ContainsString; +import org.hamcrest.core.AnyOf; +import org.junit.Test; +import org.onap.music.main.ResultType; +import org.onap.music.main.ReturnType; + +public class ReturnTypeTest { + + @Test + public void testReturnType() { + ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); + assertEquals(result.getMessage(),"message"); + assertEquals(result.getResult(),ResultType.SUCCESS); + } + + @Test + public void testTimingInfo() { + ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); + result.setTimingInfo("123"); + assertEquals(result.getTimingInfo(),"123"); + } + + @Test + public void testGetResult() { + ReturnType result = new ReturnType(ResultType.FAILURE,"message"); + assertEquals(result.getResult(),ResultType.FAILURE); + } + + @Test + public void testGetMessage() { + ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); + result.setMessage("NewMessage"); + assertEquals(result.getMessage(),"NewMessage"); + } + + @Test + public void testToJson() { + ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); + String myJson = result.toJson(); + assertTrue(myJson.contains("message")); + } + + @Test + public void testToString() { + ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); + String test = result.toString(); + assertTrue(test.contains("message")); + } + + @Test + public void testToMap() { + ReturnType result = new ReturnType(ResultType.SUCCESS,"message"); + Map<String, Object> myMap = result.toMap(); + assertTrue(myMap.containsKey("message")); + } + +} |