3 Commits

Author SHA1 Message Date
Patrick McDonagh
d9289a0b4a Working with Postgresql 2017-06-29 17:37:58 -05:00
Patrick McDonagh
a0fd15bade Working on conversion from MongoDB to Postgresql 2017-06-28 08:17:42 -05:00
Patrick McDonagh
b222c5370a Adds database configuration 2017-06-23 13:22:01 -05:00
18 changed files with 1407 additions and 1103 deletions

10
.idea/dbnavigator.xml generated
View File

@@ -2,7 +2,7 @@
<project version="4">
<component name="DBNavigator.Project.DataEditorManager">
<record-view-column-sorting-type value="BY_INDEX" />
<value-preview-text-wrapping value="true" />
<value-preview-text-wrapping value="false" />
<value-preview-pinned value="false" />
</component>
<component name="DBNavigator.Project.DataExportManager">
@@ -25,7 +25,7 @@
<show-object-properties value="true" />
<loaded-nodes>
<connection connection-id="94a6cabe-5b17-467d-a87c-dc17d3749f25">
<schema name="information_schema" object-types="function, table" />
<schema name="information_schema" object-types="table" />
<schema name="pg_catalog" object-types="table" />
<schema name="public" object-types="table" />
</connection>
@@ -58,7 +58,9 @@
<filters />
</component>
<component name="DBNavigator.Project.ScriptExecutionManager" clear-outputs="true">
<recently-used-interfaces />
<recently-used-interfaces>
<mapping database-type="POSTGRES" interface-id="DEFAULT" />
</recently-used-interfaces>
</component>
<component name="DBNavigator.Project.Settings">
<connections>
@@ -75,7 +77,7 @@
<url-type value="DATABASE" />
<host value="localhost" />
<port value="5432" />
<database value="postgres" />
<database value="poc" />
<os-authentication value="true" />
<empty-password value="false" />
<user value="" />

View File

@@ -1,7 +1,7 @@
<component name="libraryTable">
<library name="Gradle: :IOBoard-0.1:">
<library name="Gradle: :IOBoard-RPi-0.1:">
<CLASSES>
<root url="jar://$PROJECT_DIR$/libs/IOBoard-0.1.jar!/" />
<root url="jar://$PROJECT_DIR$/libs/IOBoard-RPi-0.1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />

View File

@@ -0,0 +1,11 @@
<component name="libraryTable">
<library name="Gradle: com.google.code.gson:gson:2.8.1">
<CLASSES>
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/com.google.code.gson/gson/2.8.1/2a8e0aa38a2e21cb39e2f5a7d6704cbdc941da0/gson-2.8.1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/com.google.code.gson/gson/2.8.1/c10732c97eccba635e20596a02c3824fef0605bf/gson-2.8.1-sources.jar!/" />
</SOURCES>
</library>
</component>

View File

@@ -0,0 +1,11 @@
<component name="libraryTable">
<library name="Gradle: org.postgresql:postgresql:42.1.1">
<CLASSES>
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.postgresql/postgresql/42.1.1/8a0b76d763f5382d6357c412eeb14970ba4405f3/postgresql-42.1.1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.postgresql/postgresql/42.1.1/bb754d9f75474fe97636543d0ff0d9f68bea930c/postgresql-42.1.1-sources.jar!/" />
</SOURCES>
</library>
</component>

View File

@@ -13,7 +13,9 @@
<orderEntry type="library" name="Gradle: com.googlecode.json-simple:json-simple:1.1.1" level="project" />
<orderEntry type="library" name="Gradle: org.mongodb:mongodb-driver:3.4.2" level="project" />
<orderEntry type="library" name="Gradle: de.vandermeer:asciitable:0.2.5" level="project" />
<orderEntry type="library" name="Gradle: :IOBoard-0.1:" level="project" />
<orderEntry type="library" name="Gradle: :IOBoard-RPi-0.1:" level="project" />
<orderEntry type="library" name="Gradle: org.postgresql:postgresql:42.1.1" level="project" />
<orderEntry type="library" name="Gradle: com.google.code.gson:gson:2.8.1" level="project" />
<orderEntry type="library" name="Gradle: junit:junit:4.10" level="project" />
<orderEntry type="library" name="Gradle: org.mongodb:bson:3.4.2" level="project" />
<orderEntry type="library" name="Gradle: org.mongodb:mongodb-driver-core:3.4.2" level="project" />

View File

@@ -14,7 +14,9 @@
<orderEntry type="library" name="Gradle: com.googlecode.json-simple:json-simple:1.1.1" level="project" />
<orderEntry type="library" name="Gradle: org.mongodb:mongodb-driver:3.4.2" level="project" />
<orderEntry type="library" name="Gradle: de.vandermeer:asciitable:0.2.5" level="project" />
<orderEntry type="library" name="Gradle: :IOBoard-0.1:" level="project" />
<orderEntry type="library" name="Gradle: :IOBoard-RPi-0.1:" level="project" />
<orderEntry type="library" name="Gradle: org.postgresql:postgresql:42.1.1" level="project" />
<orderEntry type="library" name="Gradle: com.google.code.gson:gson:2.8.1" level="project" />
<orderEntry type="library" name="Gradle: org.mongodb:bson:3.4.2" level="project" />
<orderEntry type="library" name="Gradle: org.mongodb:mongodb-driver-core:3.4.2" level="project" />
<orderEntry type="library" name="Gradle: de.vandermeer:asciilist:0.0.3" level="project" />

954
.idea/workspace.xml generated

File diff suppressed because it is too large Load Diff

View File

@@ -24,7 +24,9 @@ dependencies {
compile group: 'com.googlecode.json-simple', name: 'json-simple', version:'1.1.1'
compile group: 'org.mongodb', name: 'mongodb-driver', version:'3.4.2'
compile group: 'de.vandermeer', name: 'asciitable', version:'0.2.5'
compile name: 'IOBoard-0.1'
compile name: 'IOBoard-RPi-0.1'
compile group: 'org.postgresql', name: 'postgresql', version: '42.1.1'
compile 'com.google.code.gson:gson:2.8.1'
testCompile group: 'junit', name: 'junit', version:'3.8.1'
}

92
db_setup.sql Normal file
View File

@@ -0,0 +1,92 @@
CREATE TABLE IF NOT EXISTS cards(
id SERIAL PRIMARY KEY,
stroke_number INTEGER unique,
surface_position INTEGER ARRAY,
surface_load INTEGER ARRAY,
downhole_position INTEGER ARRAY,
downhole_load INTEGER ARRAY,
ts_added TIMESTAMP DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS measurement_configs (
id SERIAL PRIMARY KEY,
m_name TEXT UNIQUE NOT NULL,
units TEXT,
store_delta REAL NOT NULL,
store_time REAL NOT NULL,
use_total BOOLEAN NOT NULL,
use_average BOOLEAN NOT NULL,
ts_added TIMESTAMP DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS measurements_num (
id SERIAL PRIMARY KEY,
m_id INTEGER references measurement_configs(id),
val REAL NOT NULL,
ts_added TIMESTAMP DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS measurements_text (
id SERIAL PRIMARY KEY,
m_id INTEGER references measurement_configs(id),
val TEXT NOT NULL,
ts_added TIMESTAMP DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS daily_totals (
id SERIAL PRIMARY KEY,
m_id INTEGER references measurement_configs(id),
current_value REAL NOT NULL,
max_value REAL NOT NULL,
min_value REAL NOT NULL,
average_value REAL,
total_value REAL,
ts_added TIMESTAMP DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS well_tests (
id SERIAL PRIMARY KEY,
test_completed_timestamp TIMESTAMP NOT NULL,
test_hours REAL NOT NULL,
total_bbl REAL NOT NULL,
oil_bbl REAL,
h2o_bbl REAL,
gas_mcf REAL,
k_factor REAL,
oil_bbl_ratio REAL,
h2o_bbl_ratio REAL,
gas_mcf_ratio REAL,
ts_added TIMESTAMP DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS fluid_shots (
id SERIAL PRIMARY KEY,
shot_timestamp TIMESTAMP,
pump_intake_pressure REAL NOT NULL,
fluid_level REAL NOT NULL,
friction_estimate REAL NOT NULL,
ts_added TIMESTAMP DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS device_statuses (
id SERIAL PRIMARY KEY,
status TEXT NOT NULL,
initiator TEXT,
status_timestamp TIMESTAMP DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS well_configs (
id SERIAL PRIMARY KEY,
taper_setup JSON NOT NULL,
well_config JSON NOT NULL,
ts_added TIMESTAMP DEFAULT NOW()
);
CREATE TABLE IF NOT EXISTS setpoints (
id SERIAL PRIMARY KEY,
param TEXT UNIQUE NOT NULL,
setpoint_value REAL NOT NULL,
ts_added TIMESTAMP DEFAULT NOW()
);

Binary file not shown.

Binary file not shown.

View File

@@ -1,13 +0,0 @@
package com.henrypump.poc;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}

View File

@@ -4,348 +4,532 @@ package com.henrypump.poc;
* Created by patrickjmcd on 2/2/17.
*/
import com.mongodb.*;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.*;
import org.bson.BSON;
import com.google.gson.*;
import org.bson.Document;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.json.simple.JSONObject;
import org.postgresql.util.PGobject;
import com.mongodb.client.MongoCursor;
import static com.mongodb.client.model.Filters.*;
import javax.print.Doc;
import java.util.*;
import java.util.Date;
public class Database {
private String pocDatabase = "poc";
private MongoClient mongoClient;
private MongoDatabase database;
private MongoCredential credential = MongoCredential.createCredential("poc_java", pocDatabase, "HenryPump@1903".toCharArray());
private MongoCollection<Document> cardCollection, wellDataCollection, gaugeOffCollection, wellTestCollection,
fluidShotsCollection, runStatusCollection, wellConfigCollection, setpointCollection;
public void initCollections(){
cardCollection = database.getCollection("cards");
cardCollection.createIndex(Indexes.ascending("timestamp", "strokeNumber"));
wellDataCollection = database.getCollection("measurements");
wellDataCollection.createIndex(Indexes.ascending("dateStored", "tagName"));
gaugeOffCollection = database.getCollection("gaugeOff");
gaugeOffCollection.createIndex(Indexes.ascending("timestamp", "tagName"));
public class Database{
String dbHost = "localhost";
String dbName = "poc";
Connection dbConn;
wellTestCollection = database.getCollection("wellTests");
wellTestCollection.createIndex(Indexes.ascending("testStartTime"));
fluidShotsCollection = database.getCollection("fluidShots");
fluidShotsCollection.createIndex(Indexes.ascending("timestamp"));
runStatusCollection = database.getCollection("runStatus");
runStatusCollection.createIndex(Indexes.ascending("timestamp"));
wellConfigCollection = database.getCollection("wellConfiguration");
wellConfigCollection.createIndex(Indexes.ascending("timestamp"));
setpointCollection = database.getCollection("setpoints");
setpointCollection.createIndex(Indexes.ascending("name"));
private Connection connectToDatabase() {
Connection conn = null;
try
{
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://" + dbHost + "/"+ dbName;
Properties props = new Properties();
props.setProperty("user","poc");
props.setProperty("password","poc");
conn = DriverManager.getConnection(url, props);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
System.exit(1);
}
catch (SQLException e)
{
e.printStackTrace();
System.exit(2);
}
return conn;
}
Database(){
ServerAddress server = new ServerAddress("localhost", 27017);
List<MongoCredential> credentials = Arrays.asList(credential);
mongoClient = new MongoClient(server, credentials);
database = mongoClient.getDatabase(pocDatabase);
initCollections();
dbConn = connectToDatabase();
}
Database(String dbHostname){
ServerAddress server = new ServerAddress(dbHostname, 27017);
List<MongoCredential> credentials = Arrays.asList(credential);
mongoClient = new MongoClient(server, credentials);
database = mongoClient.getDatabase(pocDatabase);
initCollections();
dbHost = dbHostname;
dbConn = connectToDatabase();
}
public void close(){
mongoClient.close();
static Object[] makeObjectArray(double[] doubleArray) {
Object[] objList = new Object[doubleArray.length];
for (int i = 0; i < doubleArray.length; i++){
objList[i] = (Object) doubleArray[i];
}
return objList;
}
//CARD FUNCTIONS
public long getLastStrokeNum(){
long lastStroke = 0;
MongoCollection<Document> collection = database.getCollection("cards");
MongoCursor<Document> cursor = collection.aggregate(
Arrays.asList(
Aggregates.group("strokeNumber", Accumulators.last("lastStroke", "$strokeNumber"))
)
).iterator();
long lastStroke = -1;
try {
while (cursor.hasNext()) {
long docStroke = cursor.next().getLong("lastStroke");
if (docStroke > lastStroke) { lastStroke = docStroke; }
String selString = "SELECT MAX(id) numCards FROM cards";
PreparedStatement ps = dbConn.prepareStatement(selString);
ResultSet rs = ps.executeQuery();
while (rs.next()){
lastStroke = rs.getInt("numCards");
}
} finally {
cursor.close();
rs.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("Found last stroke to be " + lastStroke);
return lastStroke;
}
public long newCard(Card inpCard){
List<Double> s_p = new ArrayList<Double>();
List<Double> s_l = new ArrayList<Double>();
List<Double> d_p = new ArrayList<Double>();
List<Double> d_l = new ArrayList<Double>();
int numPointsScan = inpCard.getNumPointsUsed();
double[] sp = inpCard.getSurfacePosition();
double[] sl = inpCard.getSurfaceLoad();
double[] dp = inpCard.getDownholePosition();
double[] dl = inpCard.getDownholeLoad();
for(int i = 0; i < numPointsScan; i++ ) {
s_p.add(sp[i]);
s_l.add(sl[i]);
d_p.add(dp[i]);
d_l.add(dl[i]);
}
Document doc = new Document("strokeNumber", inpCard.getStrokeNumber())
.append("surface_position", s_p)
.append("surface_load", s_l)
.append("downhole_position", d_p)
.append("downhole_load", d_l)
.append("timestamp", Date.from(ZonedDateTime.now().toInstant()));
cardCollection.insertOne(doc);
System.out.println("Stored stroke number " + inpCard.getStrokeNumber() + " as " + doc.getObjectId("_id"));
return cardCollection.count();
}
public long newMeasurement(Measurement inpMeasurement){
ZonedDateTime nowDate = ZonedDateTime.now(ZoneId.of("UTC"));
ZonedDateTime todayDate = ZonedDateTime.of(nowDate.getYear(), nowDate.getMonthValue(), nowDate.getDayOfMonth(), 0, 0, 0, 0, ZoneId.of("UTC"));
Date storeDate = Date.from(todayDate.toInstant());
Document nowMeasurement = new Document("values." + nowDate.getHour() + "." + nowDate.getMinute(), inpMeasurement.getCurrentValue())
.append("currentValue", inpMeasurement.getCurrentValue())
.append("maxValue", inpMeasurement.getDailyMax())
.append("minValue", inpMeasurement.getDailyMin())
.append("averageValue", inpMeasurement.getAverage())
.append("totalValue", inpMeasurement.getTotal())
.append("numMeasurements", inpMeasurement.getNumMeasurements())
.append("units", inpMeasurement.getUnits())
.append("storeDelta", inpMeasurement.getSendDelta())
.append("storeTime", inpMeasurement.getSendTimeDelta())
.append("useTotal", inpMeasurement.isUseTotal())
.append("useAverage", inpMeasurement.isUseAverage())
.append("dateStored", storeDate);
wellDataCollection.updateOne(and(eq("tagname", inpMeasurement.getTagName()), eq("dateStored", storeDate)), new Document("$set", nowMeasurement), (new UpdateOptions()).upsert(true));
// wellDataCollection.updateOne(and(eq("tagname", inpMeasurement.getTagName()), eq("dateStored", todayDate)), new Document("$set", aggregateData), (new UpdateOptions()).upsert(true));
System.out.println("Stored " + inpMeasurement.getCurrentValue() + " for " + inpMeasurement.getTagName());
return wellDataCollection.count();
}
public Document getLastStoredMeasurement(String tagName){
MongoCursor<Document> cursor = wellDataCollection.find(eq("tagname", tagName)).sort(Sorts.descending("dateStored")).limit(1).iterator();
Document lastStoredDoc = new Document();
String sqlInsert = "INSERT INTO cards (stroke_number, surface_position, surface_load, downhole_position, downhole_load) VALUES (?, ?, ?, ?, ?)";
long numCards = -1;
try {
while (cursor.hasNext()) {
lastStoredDoc = cursor.next();
Array surf_pos = dbConn.createArrayOf("float4", makeObjectArray(inpCard.getSurfacePosition()));
Array surf_lod = dbConn.createArrayOf("float4", makeObjectArray(inpCard.getSurfaceLoad()));
Array down_pos = dbConn.createArrayOf("float4", makeObjectArray(inpCard.getDownholePosition()));
Array down_lod = dbConn.createArrayOf("float4", makeObjectArray(inpCard.getDownholeLoad()));
PreparedStatement prepInsert = dbConn.prepareStatement(sqlInsert);
prepInsert.setLong(1, inpCard.getStrokeNumber());
prepInsert.setArray(2, surf_pos);
prepInsert.setArray(3, surf_lod);
prepInsert.setArray(4, down_pos);
prepInsert.setArray(5, down_lod);
prepInsert.executeUpdate();
String selString = "SELECT COUNT(id) numCards FROM cards";
PreparedStatement ps = dbConn.prepareStatement(selString);
ResultSet rs = ps.executeQuery();
while (rs.next()){
numCards = rs.getLong("numCards");
}
} finally {
cursor.close();
rs.close();
ps.close();
} catch (SQLException e){
e.printStackTrace();
}
return lastStoredDoc;
return numCards;
}
// MEASUREMENT FUNCTIONS
public long tryNewMeasurementConfig(Measurement inpMeasurement){
String sqlSelect = "SELECT id FROM measurement_configs WHERE m_name = ?";
long dbId = -1;
try {
PreparedStatement ps = dbConn.prepareStatement(sqlSelect);
ps.setString(1, inpMeasurement.getTagName());
ResultSet rs = ps.executeQuery();
while (rs.next()){
dbId = rs.getInt("id");
}
rs.close();
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
//If measurement already exists
if (dbId == -1){
String sqlInsert = "INSERT INTO measurement_configs (m_name, units, store_delta, store_time, use_total, use_average) " +
"VALUES (?, ?, ?, ?, ?, ?)";
try {
PreparedStatement prepInsert = dbConn.prepareStatement(sqlInsert);
prepInsert.setString(1, inpMeasurement.getTagName());
prepInsert.setString(2, inpMeasurement.getUnits());
prepInsert.setDouble(3, inpMeasurement.getSendDelta());
prepInsert.setDouble(4, inpMeasurement.getSendTimeDelta());
prepInsert.setBoolean(5, inpMeasurement.isUseTotal());
prepInsert.setBoolean(6, inpMeasurement.isUseAverage());
prepInsert.executeUpdate();
String selString = "SELECT id FROM measurement_configs WHERE m_name = ?";
PreparedStatement ps = dbConn.prepareStatement(selString);
ps.setString(1, inpMeasurement.getTagName());
ResultSet rs = ps.executeQuery();
while (rs.next()){
dbId = rs.getLong("id");
}
rs.close();
ps.close();
} catch (SQLException e){
e.printStackTrace();
}
}
return dbId;
}
public long newMeasurementValue(Measurement inpMeasurement){
String sqlInsert = "INSERT INTO measurements_num (m_id, val) VALUES (?, ?)";
long numMeasurements = -1;
try {
PreparedStatement prepInsert = dbConn.prepareStatement(sqlInsert);
prepInsert.setLong(1, inpMeasurement.getDbId());
prepInsert.setDouble(2, inpMeasurement.getCurrentValue());
prepInsert.executeUpdate();
String selString = "SELECT COUNT(id) numMeasurements FROM measurements_num";
PreparedStatement ps = dbConn.prepareStatement(selString);
ResultSet rs = ps.executeQuery();
while (rs.next()){
numMeasurements = rs.getLong("numMeasurements");
}
rs.close();
ps.close();
} catch (SQLException e){
e.printStackTrace();
}
return numMeasurements;
}
public double getLastStoredMeasurement(long dbId){
String sqlSelect = "SELECT val FROM measurements_num WHERE id = (SELECT MAX(id) FROM measurements_num WHERE m_id = ?)";
//TODO: Add query to find current average, number of measurements, total, max, and min for today.
double retValue = Double.MIN_VALUE;
try {
PreparedStatement ps = dbConn.prepareStatement(sqlSelect);
ps.setLong(1, dbId);
ResultSet rs = ps.executeQuery();
while (rs.next()){
retValue = rs.getInt("val");
}
rs.close();
ps.close();
} catch (SQLException e){
e.printStackTrace();
}
return retValue;
}
public long newDailyTotal(Measurement inpMeasurement){
Document doc = new Document("tagname", inpMeasurement.getTagName())
.append("currentValue", inpMeasurement.getCurrentValue())
.append("maxDailyValue", inpMeasurement.getDailyMax())
.append("minDailyValue", inpMeasurement.getDailyMin())
.append("dailyAverage", inpMeasurement.getAverage())
.append("dailyTotal", inpMeasurement.getTotal())
.append("timestamp", Date.from(ZonedDateTime.now().toInstant()));
gaugeOffCollection.insertOne(doc);
return gaugeOffCollection.count();
String sqlInsert = "INSERT INTO daily_totals (m_id, current_value, max_value, min_value, average_value, total_value) VALUES (?, ?, ?, ?, ?, ?)";
long numMeasurements = -1;
try {
PreparedStatement prepInsert = dbConn.prepareStatement(sqlInsert);
prepInsert.setLong(1, inpMeasurement.getDbId());
prepInsert.setDouble(2, inpMeasurement.getCurrentValue());
prepInsert.setDouble(3, inpMeasurement.getDailyMax());
prepInsert.setDouble(4, inpMeasurement.getDailyMin());
prepInsert.setDouble(5, inpMeasurement.getAverage());
prepInsert.setDouble(6, inpMeasurement.getTotal());
prepInsert.executeUpdate();
String selString = "SELECT COUNT(id) numMeasurements FROM daily_totals";
PreparedStatement ps = dbConn.prepareStatement(selString);
ResultSet rs = ps.executeQuery();
while (rs.next()){
numMeasurements = rs.getLong("numMeasurements");
}
rs.close();
ps.close();
} catch (SQLException e){
e.printStackTrace();
}
return numMeasurements;
}
public double getPreviousDailyTotal(ZonedDateTime inpDateTime){
String isoInpDateTime = inpDateTime.toString();
MongoCursor<Document> cursor = wellTestCollection.find(and(eq("tagname", "Fluid Produced"), lte("timestamp", isoInpDateTime)))
.sort(Sorts.descending("timestamp")).limit(1).iterator();
double lastTotal = -1.0;
String sqlSelect = "SELECT total_value FROM daily_totals WHERE id = (SELECT MAX(id) FROM daily_totals WHERE m_id = " +
"(SELECT m_id FROM well_configs WHERE m_name = 'Fluid Produced'))";
double lastTotal = -1;
try {
while (cursor.hasNext()) {
lastTotal = cursor.next().getDouble("dailyTotal");
PreparedStatement ps = dbConn.prepareStatement(sqlSelect);
ResultSet rs = ps.executeQuery();
while (rs.next()){
lastTotal = rs.getInt("total_value");
}
} finally {
cursor.close();
rs.close();
ps.close();
} catch (SQLException e){
e.printStackTrace();
}
return lastTotal;
};
public long newWellTest(WellTest inp){
Document doc = new Document("testStartTime", Date.from(inp.getTestStart().toInstant()))
.append("testHours", inp.getTestHours())
.append("testTotalBBL", inp.getTotalFluidBBL())
.append("testOilBBL", inp.getTestOilBBL())
.append("testWaterBBL", inp.getTestWaterBBL())
.append("testGasMCF", inp.getTestGasMCF())
.append("kFactor", inp.getkFactor())
.append("oilRatio", inp.getOilRatio())
.append("waterRatio", inp.getWaterRatio())
.append("gasMCFRatio", inp.getGasMCFRatio());
wellTestCollection.insertOne(doc);
return wellTestCollection.count();
}
public Document getPreviousWellTest(ZonedDateTime inpDateTime){
MongoCursor<Document> cursor = wellTestCollection.find(lte("testStartTime", Date.from(inpDateTime.toInstant())))
.sort(Sorts.descending("testStartTime")).limit(1).iterator();
Document lastTest = new Document("kFactor", (Double) 1.0);
public long newWellTest(WellTest inp){
String sqlInsert = "INSERT INTO well_tests (test_completed_timestamp, test_hours, total_bbl, oil_bbl, h2o_bbl, gas_mcf," +
" k_factor, oil_bbl_ratio, h2o_bbl_ratio, gas_mcf_ratio) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
long numTests = -1;
try {
while (cursor.hasNext()) {
lastTest = cursor.next();
PreparedStatement prepInsert = dbConn.prepareStatement(sqlInsert);
prepInsert.setTimestamp(1, new Timestamp(Date.from(inp.getTestStart().toInstant()).getTime()));
prepInsert.setDouble(2, inp.getTestHours());
prepInsert.setDouble(3, inp.getTotalFluidBBL());
prepInsert.setDouble(4, inp.getTestOilBBL());
prepInsert.setDouble(5, inp.getTestWaterBBL());
prepInsert.setDouble(6, inp.getTestGasMCF());
prepInsert.setDouble(7, inp.getkFactor());
prepInsert.setDouble(8, inp.getOilRatio());
prepInsert.setDouble(9, inp.getWaterRatio());
prepInsert.setDouble(10, inp.getGasMCFRatio());
prepInsert.executeUpdate();
String selString = "SELECT COUNT(id) numTests FROM well_tests";
PreparedStatement ps = dbConn.prepareStatement(selString);
ResultSet rs = ps.executeQuery();
while (rs.next()){
numTests = rs.getLong("numTests");
}
} finally {
cursor.close();
rs.close();
ps.close();
} catch (SQLException e){
e.printStackTrace();
}
return lastTest;
return numTests;
}
public WellTest getPreviousWellTest(ZonedDateTime inpDateTime){
String selectSql = "SELECT * FROM well_tests WHERE test_completed_timestamp <= ? ORDER BY test_completed_timestamp DESC LIMIT 1";
WellTest wt = null;
try {
PreparedStatement ps = dbConn.prepareStatement(selectSql);
ps.setTimestamp(1, new Timestamp(Date.from(inpDateTime.toInstant()).getTime()));
ResultSet rs = ps.executeQuery();
while (rs.next()){
wt = new WellTest(rs.getTimestamp("test_completed_timestamp").toInstant().atZone(ZoneId.of("GMT")), rs.getDouble("test_hours"),
rs.getDouble("total_bbl"), rs.getDouble("oil_bbl"), rs.getDouble("h20_bbl"),
rs.getDouble("gas_mcf"), rs.getDouble("k_factor"));
}
rs.close();
ps.close();
} catch (SQLException e){
e.printStackTrace();
}
return wt;
};
public double getLatestKFactor(){
MongoCursor<Document> cursor = wellTestCollection.find().sort(Sorts.descending("testStartTime")).limit(1).iterator();
String selectSql = "SELECT k_factor from well_tests WHERE id = (SELECT MAX(id) FROM well_tests)";
double kFactor = 1.0;
try {
while (cursor.hasNext()) {
kFactor = cursor.next().getDouble("kFactor");
PreparedStatement ps = dbConn.prepareStatement(selectSql);
ResultSet rs = ps.executeQuery();
while (rs.next()){
kFactor = rs.getDouble("k_factor");
}
} finally {
cursor.close();
rs.close();
ps.close();
} catch (SQLException e){
e.printStackTrace();
}
return kFactor;
}
public long newFluidShot(FluidShot inp){
String df = ZonedDateTime.now().toString();
Document doc = new Document("timestamp", Date.from(ZonedDateTime.now().toInstant()))
.append("fluidLevel", inp.getFluidLevel())
.append("pumpIntakePressure", inp.getPumpIntakePressure())
.append("frictionEstimate", inp.getFrictionEstimate());
fluidShotsCollection.insertOne(doc);
return fluidShotsCollection.count();
String sqlInsert = "INSERT INTO fluid_shots (shot_timestamp, fluid_level, pump_intake_pressure, friction_estimate) VALUES (?, ?, ?, ?)";
Timestamp ts = new Timestamp(Date.from(ZonedDateTime.now().toInstant()).getTime());
long numShots = -1;
try {
PreparedStatement prepInsert = dbConn.prepareStatement(sqlInsert);
prepInsert.setTimestamp(1, ts);
prepInsert.setDouble(2, inp.getFluidLevel());
prepInsert.setDouble(3, inp.getPumpIntakePressure());
prepInsert.setDouble(4, inp.getFrictionEstimate());
prepInsert.executeUpdate();
String selString = "SELECT COUNT(id) numShots FROM fluid_shots";
PreparedStatement ps = dbConn.prepareStatement(selString);
ResultSet rs = ps.executeQuery();
while (rs.next()){
numShots = rs.getLong("numShots");
}
rs.close();
ps.close();
} catch (SQLException e){
e.printStackTrace();
}
return numShots;
}
public double getLatestFrictionEstimate(){
MongoCursor<Document> cursor = fluidShotsCollection.find().sort(Sorts.descending("timestamp")).limit(1).iterator();
double frictionEstimate = -1;
String selectSql = "SELECT friction_estimate from fluid_shots WHERE id = (SELECT MAX(id) FROM fluid_shots)";
double frictionEstimate = 1.0;
try {
while (cursor.hasNext()) {
frictionEstimate = cursor.next().getDouble("frictionEstimate");
PreparedStatement ps = dbConn.prepareStatement(selectSql);
ResultSet rs = ps.executeQuery();
while (rs.next()){
frictionEstimate = rs.getDouble("friction_estimate");
}
} finally {
cursor.close();
rs.close();
ps.close();
} catch (SQLException e){
e.printStackTrace();
}
return frictionEstimate;
}
public long newRunStatus(String runStatus, String initiator){
Document doc = new Document("status", runStatus)
.append("initiator", initiator)
.append("timestamp", Date.from(ZonedDateTime.now().toInstant()));
runStatusCollection.insertOne(doc);
return runStatusCollection.count();
String sqlInsert = "INSERT INTO device_statuses (status, initiator) VALUES (?, ?)";
long numStatuses = -1;
try {
PreparedStatement prepInsert = dbConn.prepareStatement(sqlInsert);
prepInsert.setString(1, runStatus);
prepInsert.setString(2, initiator);
prepInsert.executeUpdate();
String selString = "SELECT COUNT(id) numStatuses FROM device_statuses";
PreparedStatement ps = dbConn.prepareStatement(selString);
ResultSet rs = ps.executeQuery();
while (rs.next()){
numStatuses = rs.getLong("numStatuses");
}
rs.close();
ps.close();
} catch (SQLException e){
e.printStackTrace();
}
return numStatuses;
}
public long storeWellSetup(Well thisWell){
ArrayList<Document> taperArr = new ArrayList<Document>();
Gson gson = new Gson();
JsonObject wellConfig = new JsonObject();
JsonArray taperArr = new JsonArray();
PGobject wellConfigObj = new PGobject();
wellConfigObj.setType("json");
PGobject taperArrayObj = new PGobject();
taperArrayObj.setType("json");
for (int i = 1; i <= thisWell.getNumTapers(); i++){
Document tap = new Document("length", thisWell.getRodLength(i))
.append("diameter", thisWell.getRodDiameter(i))
.append("material", thisWell.getRodMaterial(i))
.append("dampingFactor", thisWell.getDampingFactor(i));
JsonObject tap = new JsonObject();
tap.add("length", new JsonPrimitive(thisWell.getRodLength(i)));
tap.add("diameter", new JsonPrimitive(thisWell.getRodDiameter(i)));
tap.add("material", new JsonPrimitive(thisWell.getRodMaterial(i)));
tap.add("dampingFactor", new JsonPrimitive(thisWell.getDampingFactor(i)));
taperArr.add(tap);
}
wellConfig.add("wellName", new JsonPrimitive(thisWell.getWellName()));
wellConfig.add("deltaT", new JsonPrimitive(thisWell.getDt()));
wellConfig.add("pumpDiameter", new JsonPrimitive(thisWell.getPumpDiameter()));
wellConfig.add("fluidGradient", new JsonPrimitive(thisWell.getFluidGradient()));
wellConfig.add("tubingID", new JsonPrimitive(thisWell.getTubingID()));
wellConfig.add("tubingOD", new JsonPrimitive(thisWell.getTubingOD()));
wellConfig.add("tubingAnchorDepth", new JsonPrimitive(thisWell.getTubingAnchorDepth()));
wellConfig.add("structuralRating", new JsonPrimitive(thisWell.getStructuralRating()));
wellConfig.add("stuffingBoxFriction", new JsonPrimitive(thisWell.getSbfriction()));
wellConfig.add("tubingHeadPressure", new JsonPrimitive(thisWell.getTubingHeadPressure()));
wellConfig.add("tapers", taperArr);
wellConfig.add("storedBy", new JsonPrimitive("poc"));
Document doc = new Document("timestamp", Date.from(ZonedDateTime.now().toInstant()))
.append("wellName", thisWell.getWellName())
.append("deltaT", thisWell.getDt())
.append("pumpDiameter", thisWell.getPumpDiameter())
.append("fluidGradient", thisWell.getFluidGradient())
.append("tubingID", thisWell.getTubingID())
.append("tubingOD", thisWell.getTubingOD())
.append("tubingAnchorDepth", thisWell.getTubingAnchorDepth())
.append("structuralRating", thisWell.getStructuralRating())
.append("stuffingBoxFriction", thisWell.getSbfriction())
.append("tubingHeadPressure", thisWell.getTubingHeadPressure())
.append("tapers", taperArr)
.append("storedBy", "poc");
String sqlInsert = "INSERT INTO well_configs (taper_setup, well_config) VALUES (?, ?)";
long numConfigs = -1;
try {
wellConfigCollection.insertOne(doc);
return wellConfigCollection.count();
PreparedStatement prepInsert = dbConn.prepareStatement(sqlInsert);
taperArrayObj.setValue(gson.toJson(taperArr));
prepInsert.setObject(1, taperArrayObj);
wellConfigObj.setValue(gson.toJson(wellConfig));
prepInsert.setObject(2, wellConfigObj);
prepInsert.executeUpdate();
String selString = "SELECT COUNT(id) numConfigs FROM well_configs";
PreparedStatement ps = dbConn.prepareStatement(selString);
ResultSet rs = ps.executeQuery();
while (rs.next()){
numConfigs = rs.getLong("numConfigs");
}
rs.close();
ps.close();
} catch (SQLException e){
e.printStackTrace();
}
return numConfigs;
}
public Document getLatestWellConfiguration(){
MongoCursor<Document> cursor = wellConfigCollection.find().sort(Sorts.descending("timestamp")).limit(1).iterator();
Document lastConfig = new Document();
public JsonObject getLatestWellConfiguration(){
Gson gson = new Gson();
String selectSql = "SELECT * from well_configs WHERE id = (SELECT MAX(id) FROM well_configs)";
JsonObject config = new JsonObject();
try {
while (cursor.hasNext()) {
lastConfig = cursor.next();
PreparedStatement ps = dbConn.prepareStatement(selectSql);
ResultSet rs = ps.executeQuery();
while (rs.next()){
config.add("tapers", new JsonPrimitive(rs.getString("taper_setup")));
config.add("well_config", new JsonPrimitive(rs.getString("well_config")));
}
} finally {
cursor.close();
rs.close();
ps.close();
} catch (SQLException e){
e.printStackTrace();
}
return lastConfig;
return config;
}
public long storeSetpoint(String setpointName, double setpointValue){
Document newSetpoint = new Document("name", setpointName)
.append("value", setpointValue)
.append("lastStored", Date.from(ZonedDateTime.now().toInstant()))
.append("storedBy", "poc");
setpointCollection.updateOne(eq("name", setpointName), new Document("$set", newSetpoint), (new UpdateOptions()).upsert(true));
return setpointCollection.count();
String sqlInsert = "INSERT INTO setpoints (param, setpoint_value) VALUES (?, ?) ON CONFLICT DO UPDATE setpoints SET setpoint_value = ? WHERE param = ?";
long numSetpoints = -1;
try {
PreparedStatement prepInsert = dbConn.prepareStatement(sqlInsert);
prepInsert.setString(1, setpointName);
prepInsert.setDouble(2, setpointValue);
prepInsert.setDouble(3, setpointValue);
prepInsert.setString(4, setpointName);
prepInsert.executeUpdate();
String selString = "SELECT COUNT(id) numSetpoints FROM well_configs";
PreparedStatement ps = dbConn.prepareStatement(selString);
ResultSet rs = ps.executeQuery();
while (rs.next()){
numSetpoints = rs.getLong("numSetpoints");
}
rs.close();
ps.close();
} catch (SQLException e){
e.printStackTrace();
}
return numSetpoints;
}
public Double getSetpoint(String setpointName){
Document setpointDoc = setpointCollection.find(eq("name", setpointName)).first();
double setpoint;
String sqlSelect = "SELECT setpoint_value FROM setpoints WHERE param = ?";
double setpoint = -1;
try {
setpoint = setpointDoc.getDouble("value");
String storedBy = setpointDoc.getString("storedBy");
System.out.println("Setpoint retrieved from database: [" + setpointName + " = " + setpoint + " stored by " + storedBy + "]");
} catch (ClassCastException e){
setpoint = Double.parseDouble(setpointDoc.get("value").toString());
String storedBy = setpointDoc.getString("storedBy");
System.out.println("Setpoint retrieved from database: [" + setpointName + " = " + setpoint + " stored by " + storedBy + "]");
} catch (NullPointerException e){
setpoint = Double.MIN_VALUE;
System.out.println("Could not find a value for " + setpointName + " in the database.");
PreparedStatement ps = dbConn.prepareStatement(sqlSelect);
ps.setString(1, setpointName);
ResultSet rs = ps.executeQuery();
while (rs.next()){
setpoint = rs.getDouble("setpoint_value");
}
rs.close();
ps.close();
} catch (SQLException e){
e.printStackTrace();
}
return setpoint;
}
}

View File

@@ -1,8 +1,8 @@
package com.henrypump.poc;
import com.henrypump.io.DigitalIn;
import com.henrypump.io.DigitalOut;
import com.henrypump.io.MuxSetup;
import com.henrypump.rpio.DigitalIn;
import com.henrypump.rpio.DigitalOut;
import com.henrypump.rpio.MuxSetup;
/**
* Created by patrickjmcd on 2/10/17.

View File

@@ -31,9 +31,15 @@ public class Measurement {
private String units = null;
private boolean useTotal;
private boolean useAverage;
private long dbId;
Measurement(String tagName, Database db){
Measurement(String tagName, Database db, String units, double sendDelta, long sendTimeDelta, boolean useTotal, boolean useAverage){
this.tagName = tagName;
this.units = units;
this.sendDelta = sendDelta;
this.sendTimeDelta = sendTimeDelta;
this.useTotal = useTotal;
this.useAverage = useAverage;
average = 0;
total = 0;
numMeasurements = 0;
@@ -44,40 +50,46 @@ public class Measurement {
this.db = db;
this.lastSentValue = 0.0;
Document lastStored = this.db.getLastStoredMeasurement(this.tagName);
try {
Date lastStoredTimestamp = (Date) lastStored.get("dateStored");
ZonedDateTime timestamp = ZonedDateTime.ofInstant(lastStoredTimestamp.toInstant(),
ZoneId.systemDefault());
if (isToday(timestamp)){
this.average = lastStored.getDouble("averageValue");
this.total = lastStored.getDouble("totalValue");
// this.lastSentValue = lastStored.getDouble("currentValue");
this.dailyMax = lastStored.getDouble("maxValue");
this.dailyMin = lastStored.getDouble("minValue");
this.sendDelta = lastStored.getDouble("storeDelta");
this.sendTimeDelta = lastStored.getLong("storeTime");
this.units = lastStored.getString("units");
// this.lastSentTimestamp = timestamp.toEpochSecond();
Document values = (Document) lastStored.get("values");
Object[] hours = values.keySet().toArray();
String maxHour = (String) hours[hours.length - 1];
Document maxHourDoc = (Document) values.get(maxHour);
Object[] minutes = maxHourDoc.keySet().toArray();
String maxMinute = (String) minutes[minutes.length - 1];
this.lastSentValue = maxHourDoc.getDouble(maxMinute);
this.numMeasurements = lastStored.getLong("numMeasurements");
this.dbId = this.db.tryNewMeasurementConfig(this);
System.out.println("Using stored value from " + ZonedDateTime.of(timestamp.getYear(),
timestamp.getMonthValue(), timestamp.getDayOfMonth(), Integer.parseInt(maxHour),
Integer.parseInt(maxMinute), 0, 0, timestamp.getZone()).toString() + " for " + this.tagName);
} else {
System.out.println("Cannot use stored value from " + timestamp.toString() + " for " + this.tagName);
}
} catch (NullPointerException e){
System.out.println("There was no previous measurement in the database for " + this.tagName);
double lastStored = this.db.getLastStoredMeasurement(this.dbId);
if (lastStored != Double.MIN_VALUE) {
this.lastSentValue = this.db.getLastStoredMeasurement(this.dbId);
}
// try {
// Date lastStoredTimestamp = (Date) lastStored.get("dateStored");
// ZonedDateTime timestamp = ZonedDateTime.ofInstant(lastStoredTimestamp.toInstant(),
// ZoneId.systemDefault());
// if (isToday(timestamp)){
// this.average = lastStored.getDouble("averageValue");
// this.total = lastStored.getDouble("totalValue");
//// this.lastSentValue = lastStored.getDouble("currentValue");
// this.dailyMax = lastStored.getDouble("maxValue");
// this.dailyMin = lastStored.getDouble("minValue");
// this.sendDelta = lastStored.getDouble("storeDelta");
// this.sendTimeDelta = lastStored.getLong("storeTime");
// this.units = lastStored.getString("units");
//// this.lastSentTimestamp = timestamp.toEpochSecond();
// Document values = (Document) lastStored.get("values");
// Object[] hours = values.keySet().toArray();
// String maxHour = (String) hours[hours.length - 1];
// Document maxHourDoc = (Document) values.get(maxHour);
// Object[] minutes = maxHourDoc.keySet().toArray();
// String maxMinute = (String) minutes[minutes.length - 1];
// this.lastSentValue = maxHourDoc.getDouble(maxMinute);
// this.numMeasurements = lastStored.getLong("numMeasurements");
//
//
// System.out.println("Using stored value from " + ZonedDateTime.of(timestamp.getYear(),
// timestamp.getMonthValue(), timestamp.getDayOfMonth(), Integer.parseInt(maxHour),
// Integer.parseInt(maxMinute), 0, 0, timestamp.getZone()).toString() + " for " + this.tagName);
// } else {
// System.out.println("Cannot use stored value from " + timestamp.toString() + " for " + this.tagName);
// }
// } catch (NullPointerException e){
// System.out.println("There was no previous measurement in the database for " + this.tagName);
// }
}
@@ -154,9 +166,9 @@ public class Measurement {
this.useAverage = useAverage;
}
public long getDbId() {
return dbId;
}
private static boolean isToday(ZonedDateTime inpZDT){
ZonedDateTime now = ZonedDateTime.now();
@@ -180,7 +192,7 @@ public class Measurement {
dailyMin = Math.min(dailyMin, currentValue);
if(abs(currentValue - lastSentValue) > sendDelta || (currentTimestamp - lastSentTimestamp) > (sendTimeDelta)){
long l = db.newMeasurement(this);
long l = db.newMeasurementValue(this);
lastSentValue = currentValue;
lastSentTimestamp = currentTimestamp;
}

View File

@@ -0,0 +1,347 @@
package com.henrypump.poc;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.*;
import org.bson.Document;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.lte;
/**
* Created by patrickjmcd on 6/28/17.
*/
public class MongoDatabase {
private String pocDatabase = "poc";
private MongoClient mongoClient;
private com.mongodb.client.MongoDatabase database;
private MongoCredential credential = MongoCredential.createCredential("poc_java", pocDatabase, "HenryPump@1903".toCharArray());
private MongoCollection<Document> cardCollection, wellDataCollection, gaugeOffCollection, wellTestCollection,
fluidShotsCollection, runStatusCollection, wellConfigCollection, setpointCollection;
public void initCollections(){
cardCollection = database.getCollection("cards");
cardCollection.createIndex(Indexes.ascending("timestamp", "strokeNumber"));
wellDataCollection = database.getCollection("measurements");
wellDataCollection.createIndex(Indexes.ascending("dateStored", "tagName"));
gaugeOffCollection = database.getCollection("gaugeOff");
gaugeOffCollection.createIndex(Indexes.ascending("timestamp", "tagName"));
wellTestCollection = database.getCollection("wellTests");
wellTestCollection.createIndex(Indexes.ascending("testStartTime"));
fluidShotsCollection = database.getCollection("fluidShots");
fluidShotsCollection.createIndex(Indexes.ascending("timestamp"));
runStatusCollection = database.getCollection("runStatus");
runStatusCollection.createIndex(Indexes.ascending("timestamp"));
wellConfigCollection = database.getCollection("wellConfiguration");
wellConfigCollection.createIndex(Indexes.ascending("timestamp"));
setpointCollection = database.getCollection("setpoints");
setpointCollection.createIndex(Indexes.ascending("name"));
}
MongoDatabase(){
ServerAddress server = new ServerAddress("localhost", 27017);
List<MongoCredential> credentials = Arrays.asList(credential);
mongoClient = new MongoClient(server, credentials);
database = mongoClient.getDatabase(pocDatabase);
initCollections();
}
MongoDatabase(String dbHostname){
ServerAddress server = new ServerAddress(dbHostname, 27017);
List<MongoCredential> credentials = Arrays.asList(credential);
mongoClient = new MongoClient(server, credentials);
database = mongoClient.getDatabase(pocDatabase);
initCollections();
}
public void close(){
mongoClient.close();
}
public long getLastStrokeNum(){
long lastStroke = 0;
MongoCollection<Document> collection = database.getCollection("cards");
MongoCursor<Document> cursor = collection.aggregate(
Arrays.asList(
Aggregates.group("strokeNumber", Accumulators.last("lastStroke", "$strokeNumber"))
)
).iterator();
try {
while (cursor.hasNext()) {
long docStroke = cursor.next().getLong("lastStroke");
if (docStroke > lastStroke) { lastStroke = docStroke; }
}
} finally {
cursor.close();
}
System.out.println("Found last stroke to be " + lastStroke);
return lastStroke;
}
public long newCard(Card inpCard){
List<Double> s_p = new ArrayList<Double>();
List<Double> s_l = new ArrayList<Double>();
List<Double> d_p = new ArrayList<Double>();
List<Double> d_l = new ArrayList<Double>();
int numPointsScan = inpCard.getNumPointsUsed();
double[] sp = inpCard.getSurfacePosition();
double[] sl = inpCard.getSurfaceLoad();
double[] dp = inpCard.getDownholePosition();
double[] dl = inpCard.getDownholeLoad();
for(int i = 0; i < numPointsScan; i++ ) {
s_p.add(sp[i]);
s_l.add(sl[i]);
d_p.add(dp[i]);
d_l.add(dl[i]);
}
Document doc = new Document("strokeNumber", inpCard.getStrokeNumber())
.append("surface_position", s_p)
.append("surface_load", s_l)
.append("downhole_position", d_p)
.append("downhole_load", d_l)
.append("timestamp", Date.from(ZonedDateTime.now().toInstant()));
cardCollection.insertOne(doc);
System.out.println("Stored stroke number " + inpCard.getStrokeNumber() + " as " + doc.getObjectId("_id"));
return cardCollection.count();
}
public long newMeasurement(Measurement inpMeasurement){
ZonedDateTime nowDate = ZonedDateTime.now(ZoneId.of("UTC"));
ZonedDateTime todayDate = ZonedDateTime.of(nowDate.getYear(), nowDate.getMonthValue(), nowDate.getDayOfMonth(), 0, 0, 0, 0, ZoneId.of("UTC"));
Date storeDate = Date.from(todayDate.toInstant());
Document nowMeasurement = new Document("values." + nowDate.getHour() + "." + nowDate.getMinute(), inpMeasurement.getCurrentValue())
.append("currentValue", inpMeasurement.getCurrentValue())
.append("maxValue", inpMeasurement.getDailyMax())
.append("minValue", inpMeasurement.getDailyMin())
.append("averageValue", inpMeasurement.getAverage())
.append("totalValue", inpMeasurement.getTotal())
.append("numMeasurements", inpMeasurement.getNumMeasurements())
.append("units", inpMeasurement.getUnits())
.append("storeDelta", inpMeasurement.getSendDelta())
.append("storeTime", inpMeasurement.getSendTimeDelta())
.append("useTotal", inpMeasurement.isUseTotal())
.append("useAverage", inpMeasurement.isUseAverage())
.append("dateStored", storeDate);
wellDataCollection.updateOne(and(eq("tagname", inpMeasurement.getTagName()), eq("dateStored", storeDate)), new Document("$set", nowMeasurement), (new UpdateOptions()).upsert(true));
// wellDataCollection.updateOne(and(eq("tagname", inpMeasurement.getTagName()), eq("dateStored", todayDate)), new Document("$set", aggregateData), (new UpdateOptions()).upsert(true));
System.out.println("Stored " + inpMeasurement.getCurrentValue() + " for " + inpMeasurement.getTagName());
return wellDataCollection.count();
}
public Document getLastStoredMeasurement(String tagName){
MongoCursor<Document> cursor = wellDataCollection.find(eq("tagname", tagName)).sort(Sorts.descending("dateStored")).limit(1).iterator();
Document lastStoredDoc = new Document();
try {
while (cursor.hasNext()) {
lastStoredDoc = cursor.next();
}
} finally {
cursor.close();
}
return lastStoredDoc;
}
public long newDailyTotal(Measurement inpMeasurement){
Document doc = new Document("tagname", inpMeasurement.getTagName())
.append("currentValue", inpMeasurement.getCurrentValue())
.append("maxDailyValue", inpMeasurement.getDailyMax())
.append("minDailyValue", inpMeasurement.getDailyMin())
.append("dailyAverage", inpMeasurement.getAverage())
.append("dailyTotal", inpMeasurement.getTotal())
.append("timestamp", Date.from(ZonedDateTime.now().toInstant()));
gaugeOffCollection.insertOne(doc);
return gaugeOffCollection.count();
}
public double getPreviousDailyTotal(ZonedDateTime inpDateTime){
String isoInpDateTime = inpDateTime.toString();
MongoCursor<Document> cursor = wellTestCollection.find(and(eq("tagname", "Fluid Produced"), lte("timestamp", isoInpDateTime)))
.sort(Sorts.descending("timestamp")).limit(1).iterator();
double lastTotal = -1.0;
try {
while (cursor.hasNext()) {
lastTotal = cursor.next().getDouble("dailyTotal");
}
} finally {
cursor.close();
}
return lastTotal;
};
public long newWellTest(WellTest inp){
Document doc = new Document("testStartTime", Date.from(inp.getTestStart().toInstant()))
.append("testHours", inp.getTestHours())
.append("testTotalBBL", inp.getTotalFluidBBL())
.append("testOilBBL", inp.getTestOilBBL())
.append("testWaterBBL", inp.getTestWaterBBL())
.append("testGasMCF", inp.getTestGasMCF())
.append("kFactor", inp.getkFactor())
.append("oilRatio", inp.getOilRatio())
.append("waterRatio", inp.getWaterRatio())
.append("gasMCFRatio", inp.getGasMCFRatio());
wellTestCollection.insertOne(doc);
return wellTestCollection.count();
}
public Document getPreviousWellTest(ZonedDateTime inpDateTime){
MongoCursor<Document> cursor = wellTestCollection.find(lte("testStartTime", Date.from(inpDateTime.toInstant())))
.sort(Sorts.descending("testStartTime")).limit(1).iterator();
Document lastTest = new Document("kFactor", (Double) 1.0);
try {
while (cursor.hasNext()) {
lastTest = cursor.next();
}
} finally {
cursor.close();
}
return lastTest;
};
public double getLatestKFactor(){
MongoCursor<Document> cursor = wellTestCollection.find().sort(Sorts.descending("testStartTime")).limit(1).iterator();
double kFactor = 1.0;
try {
while (cursor.hasNext()) {
kFactor = cursor.next().getDouble("kFactor");
}
} finally {
cursor.close();
}
return kFactor;
}
public long newFluidShot(FluidShot inp){
String df = ZonedDateTime.now().toString();
Document doc = new Document("timestamp", Date.from(ZonedDateTime.now().toInstant()))
.append("fluidLevel", inp.getFluidLevel())
.append("pumpIntakePressure", inp.getPumpIntakePressure())
.append("frictionEstimate", inp.getFrictionEstimate());
fluidShotsCollection.insertOne(doc);
return fluidShotsCollection.count();
}
public double getLatestFrictionEstimate(){
MongoCursor<Document> cursor = fluidShotsCollection.find().sort(Sorts.descending("timestamp")).limit(1).iterator();
double frictionEstimate = -1;
try {
while (cursor.hasNext()) {
frictionEstimate = cursor.next().getDouble("frictionEstimate");
}
} finally {
cursor.close();
}
return frictionEstimate;
}
public long newRunStatus(String runStatus, String initiator){
Document doc = new Document("status", runStatus)
.append("initiator", initiator)
.append("timestamp", Date.from(ZonedDateTime.now().toInstant()));
runStatusCollection.insertOne(doc);
return runStatusCollection.count();
}
public long storeWellSetup(Well thisWell){
ArrayList<Document> taperArr = new ArrayList<Document>();
for (int i = 1; i <= thisWell.getNumTapers(); i++){
Document tap = new Document("length", thisWell.getRodLength(i))
.append("diameter", thisWell.getRodDiameter(i))
.append("material", thisWell.getRodMaterial(i))
.append("dampingFactor", thisWell.getDampingFactor(i));
taperArr.add(tap);
}
Document doc = new Document("timestamp", Date.from(ZonedDateTime.now().toInstant()))
.append("wellName", thisWell.getWellName())
.append("deltaT", thisWell.getDt())
.append("pumpDiameter", thisWell.getPumpDiameter())
.append("fluidGradient", thisWell.getFluidGradient())
.append("tubingID", thisWell.getTubingID())
.append("tubingOD", thisWell.getTubingOD())
.append("tubingAnchorDepth", thisWell.getTubingAnchorDepth())
.append("structuralRating", thisWell.getStructuralRating())
.append("stuffingBoxFriction", thisWell.getSbfriction())
.append("tubingHeadPressure", thisWell.getTubingHeadPressure())
.append("tapers", taperArr)
.append("storedBy", "poc");
wellConfigCollection.insertOne(doc);
return wellConfigCollection.count();
}
public Document getLatestWellConfiguration(){
MongoCursor<Document> cursor = wellConfigCollection.find().sort(Sorts.descending("timestamp")).limit(1).iterator();
Document lastConfig = new Document();
try {
while (cursor.hasNext()) {
lastConfig = cursor.next();
}
} finally {
cursor.close();
}
return lastConfig;
}
public long storeSetpoint(String setpointName, double setpointValue){
Document newSetpoint = new Document("name", setpointName)
.append("value", setpointValue)
.append("lastStored", Date.from(ZonedDateTime.now().toInstant()))
.append("storedBy", "poc");
setpointCollection.updateOne(eq("name", setpointName), new Document("$set", newSetpoint), (new UpdateOptions()).upsert(true));
return setpointCollection.count();
}
public Double getSetpoint(String setpointName){
Document setpointDoc = setpointCollection.find(eq("name", setpointName)).first();
double setpoint;
try {
setpoint = setpointDoc.getDouble("value");
String storedBy = setpointDoc.getString("storedBy");
System.out.println("Setpoint retrieved from database: [" + setpointName + " = " + setpoint + " stored by " + storedBy + "]");
} catch (ClassCastException e){
setpoint = Double.parseDouble(setpointDoc.get("value").toString());
String storedBy = setpointDoc.getString("storedBy");
System.out.println("Setpoint retrieved from database: [" + setpointName + " = " + setpoint + " stored by " + storedBy + "]");
} catch (NullPointerException e){
setpoint = Double.MIN_VALUE;
System.out.println("Could not find a value for " + setpointName + " in the database.");
}
return setpoint;
}
}

View File

@@ -1,7 +1,5 @@
package com.henrypump.poc;
import java.time.ZonedDateTime;
/**
* Created by patrickjmcd on 2/1/17.
* POC Class

View File

@@ -1,8 +1,10 @@
package com.henrypump.poc;
import com.henrypump.io.AnalogIn;
import com.henrypump.io.MuxSetup;
import com.google.gson.*;
import com.google.gson.internal.bind.JsonTreeReader;
import com.henrypump.rpio.AnalogIn;
import com.henrypump.rpio.MuxSetup;
import de.vandermeer.asciitable.v2.RenderedTable;
import de.vandermeer.asciitable.v2.V2_AsciiTable;
import de.vandermeer.asciitable.v2.render.V2_AsciiTableRenderer;
@@ -242,12 +244,12 @@ public class Well {
int minRaw = Integer.MAX_VALUE;
while (Duration.between(startTime, Instant.now()).toMillis() < 30000){
inclinometer.read(ioMux);
if (inclinometer.rawValue > maxRaw){
maxRaw = inclinometer.rawValue;
if (inclinometer.getRawValue() > maxRaw){
maxRaw = inclinometer.getRawValue();
}
if (inclinometer.rawValue < minRaw){
minRaw = inclinometer.rawValue;
if (inclinometer.getRawValue() < minRaw){
minRaw = inclinometer.getRawValue();
}
try {
Thread.sleep(10);
@@ -351,167 +353,27 @@ public class Well {
}
private void initializeMeasurements(){
strokeSpeed = new Measurement("Stroke Speed", db);
if (strokeSpeed.getUnits() == null) {
strokeSpeed.setUnits("SPM");
strokeSpeed.setSendDelta(0.5);
strokeSpeed.setSendTimeDelta(600);
strokeSpeed.setUseAverage(true);
strokeSpeed.setUseTotal(false);
}
strokeSpeed = new Measurement("Stroke Speed", db, "SPM", 0.5, 600, true, false);
downholeGrossStroke = new Measurement("Downhole Gross Stroke", db, "in.", 0.5, 600, true, false);
downholeNetStroke = new Measurement("Downhole Net Stroke", db, "in.", 0.5, 600, true, false);
fluidLevel = new Measurement("Fluid Level", db, "ft.", 10.0, 600, true, false);
fluidLoad = new Measurement("Fluid Load", db, "lbs.", 20.0, 600, true, false);
inflowRate = new Measurement("Inflow Rate", db, "BBL/day", 0.5, 600, true, false);
peakPolishedRodLoad = new Measurement("Peak PRL", db, "lbs.", 50, 600, true, false);
minPolishedRodLoad = new Measurement("Min PRL", db, "lbs.", 50.0, 600, true,false);
percentRun = new Measurement("Percent Run", db, "%", 0.5, 600, false, false);
polishedRodHP = new Measurement("Polished Rod HP", db, "HP", 0.25, 600, true,false);
pumpHP = new Measurement("Pump HP", db, "HP", 0.25, 600, true, false);
fluidProduced = new Measurement("Fluid Produced", db, "BBL", 1.0, 600, true, true);
fluidProducedAdjusted = new Measurement("Fluid Produced (adjusted)", db, "BBL", 1.0, 600, true, true);
oilProduced = new Measurement("Oil Produced", db, "BBL", 0.5, 600, true, true);
waterProduced = new Measurement("Water Produced", db, "BBL", 1.0, 600, true, true);
gasProduced = new Measurement("Gas Produced", db, "MCF", 1.0, 600, true, true);
pumpIntakePressure = new Measurement("Pump Intake Pressure", db, "PSI", 5.0, 600, true, false);
surfaceStrokeLength = new Measurement("Surface Stroke", db, "in.", 0.5, 600, true, false);
tubingMovement = new Measurement("Tubing Movement", db, "in.", 0.5, 600, true, false);
pumpFillPercent = new Measurement("Pump Fill Percent", db, "%", 1.0, 600, true, false);
downholeGrossStroke = new Measurement("Downhole Gross Stroke", db);
if (downholeGrossStroke.getUnits() == null) {
downholeGrossStroke.setUnits("in.");
downholeGrossStroke.setSendDelta(0.5);
downholeGrossStroke.setSendTimeDelta(600);
downholeGrossStroke.setUseAverage(true);
downholeGrossStroke.setUseTotal(false);
}
downholeNetStroke = new Measurement("Downhole Net Stroke", db);
if (downholeNetStroke.getUnits() == null) {
downholeNetStroke.setUnits("in.");
downholeNetStroke.setSendDelta(0.5);
downholeNetStroke.setSendTimeDelta(600);
downholeNetStroke.setUseAverage(true);
downholeNetStroke.setUseTotal(false);
}
fluidLevel = new Measurement("Fluid Level", db);
if (fluidLevel.getUnits() == null) {
fluidLevel.setUnits("ft.");
fluidLevel.setSendDelta(10.0);
fluidLevel.setSendTimeDelta(600);
fluidLevel.setUseAverage(true);
fluidLevel.setUseTotal(false);
}
fluidLoad = new Measurement("Fluid Load", db);
if (fluidLoad.getUnits() == null) {
fluidLoad.setUnits("lbs.");
fluidLoad.setSendDelta(20.0);
fluidLoad.setSendTimeDelta(600);
fluidLoad.setUseAverage(true);
fluidLoad.setUseTotal(false);
}
inflowRate = new Measurement("Inflow Rate", db);
if (inflowRate.getUnits() == null) {
inflowRate.setUnits("BBL/day");
inflowRate.setSendDelta(0.5);
inflowRate.setSendTimeDelta(600);
inflowRate.setUseAverage(true);
inflowRate.setUseTotal(false);
}
peakPolishedRodLoad = new Measurement("Peak PRL", db);
if (peakPolishedRodLoad.getUnits() == null) {
peakPolishedRodLoad.setUnits("lbs.");
peakPolishedRodLoad.setSendDelta(50);
peakPolishedRodLoad.setSendTimeDelta(600);
peakPolishedRodLoad.setUseAverage(true);
peakPolishedRodLoad.setUseTotal(false);
}
minPolishedRodLoad = new Measurement("Min PRL", db);
if (minPolishedRodLoad.getUnits() == null) {
minPolishedRodLoad.setUnits("lbs.");
minPolishedRodLoad.setSendDelta(50.0);
minPolishedRodLoad.setSendTimeDelta(600);
minPolishedRodLoad.setUseAverage(true);
minPolishedRodLoad.setUseTotal(false);
}
percentRun = new Measurement("Percent Run", db);
if (percentRun.getUnits() == null) {
percentRun.setUnits("%");
percentRun.setSendDelta(0.5);
percentRun.setSendTimeDelta(600);
percentRun.setUseAverage(false);
percentRun.setUseTotal(false);
}
polishedRodHP = new Measurement("Polished Rod HP", db);
if (polishedRodHP.getUnits() == null) {
polishedRodHP.setUnits("HP");
polishedRodHP.setSendDelta(0.25);
polishedRodHP.setSendTimeDelta(600);
polishedRodHP.setUseAverage(true);
polishedRodHP.setUseTotal(false);
}
pumpHP = new Measurement("Pump HP", db);
if (pumpHP.getUnits() == null) {
pumpHP.setUnits("HP");
pumpHP.setSendDelta(0.25);
pumpHP.setSendTimeDelta(600);
pumpHP.setUseAverage(true);
pumpHP.setUseTotal(false);
}
fluidProduced = new Measurement("Fluid Produced", db);
if (fluidProduced.getUnits() == null) {
fluidProduced.setUnits("BBL");
fluidProduced.setSendDelta(1.0);
fluidProduced.setSendTimeDelta(600);
fluidProduced.setUseAverage(true);
fluidProduced.setUseTotal(true);
}
fluidProducedAdjusted = new Measurement("Fluid Produced (adjusted)", db);
if (fluidProducedAdjusted.getUnits() == null) {
fluidProducedAdjusted.setUnits("BBL");
fluidProducedAdjusted.setSendDelta(1.0);
fluidProducedAdjusted.setSendTimeDelta(600);
fluidProducedAdjusted.setUseAverage(true);
fluidProducedAdjusted.setUseTotal(true);
}
oilProduced = new Measurement("Oil Produced", db);
if (oilProduced.getUnits() == null) {
oilProduced.setUnits("BBL");
oilProduced.setSendDelta(0.5);
oilProduced.setSendTimeDelta(600);
oilProduced.setUseAverage(true);
oilProduced.setUseTotal(true);
}
waterProduced = new Measurement("Water Produced", db);
if (waterProduced.getUnits() == null) {
waterProduced.setUnits("BBL");
waterProduced.setSendDelta(1.0);
waterProduced.setSendTimeDelta(600);
waterProduced.setUseAverage(true);
waterProduced.setUseTotal(true);
}
gasProduced = new Measurement("Gas Produced", db);
if (gasProduced.getUnits() == null) {
gasProduced.setUnits("MCF");
gasProduced.setSendDelta(1.0);
gasProduced.setSendTimeDelta(600);
gasProduced.setUseAverage(true);
gasProduced.setUseTotal(true);
}
pumpIntakePressure = new Measurement("Pump Intake Pressure", db);
if (pumpIntakePressure.getUnits() == null) {
pumpIntakePressure.setUnits("PSI");
pumpIntakePressure.setSendDelta(5.0);
pumpIntakePressure.setSendTimeDelta(600);
pumpIntakePressure.setUseAverage(true);
pumpIntakePressure.setUseTotal(false);
}
surfaceStrokeLength = new Measurement("Surface Stroke", db);
if (surfaceStrokeLength.getUnits() == null) {
surfaceStrokeLength.setUnits("in.");
surfaceStrokeLength.setSendDelta(0.5);
surfaceStrokeLength.setSendTimeDelta(600);
surfaceStrokeLength.setUseAverage(true);
surfaceStrokeLength.setUseTotal(false);
}
tubingMovement = new Measurement("Tubing Movement", db);
if (tubingMovement.getUnits() == null) {
tubingMovement.setUnits("in.");
tubingMovement.setSendDelta(0.5);
tubingMovement.setSendTimeDelta(600);
tubingMovement.setUseAverage(true);
tubingMovement.setUseTotal(false);
}
pumpFillPercent = new Measurement("Pump Fill Percent", db);
if (pumpFillPercent.getUnits() == null) {
pumpFillPercent.setUnits("%");
pumpFillPercent.setSendDelta(1.0);
pumpFillPercent.setSendTimeDelta(600);
pumpFillPercent.setUseAverage(true);
pumpFillPercent.setUseTotal(false);
}
}
public double getDt() {
@@ -867,7 +729,7 @@ public class Well {
pumpStartTime = ZonedDateTime.now();
db.newRunStatus(getRunStatusString(), initiator);
int[] inclMinMax = calibrateInclinometer();
inclinometer = new AnalogIn(inclinometer.channel, inclMinMax[0], inclMinMax[1], inclinometer.euMin, inclinometer.euMax);
inclinometer = new AnalogIn(inclinometer.getChannel(), inclMinMax[0], inclMinMax[1], inclinometer.getEuMin(), inclinometer.getEuMax());
}
}
@@ -959,6 +821,7 @@ public class Well {
};
void getWellSetup(){
Gson gson = new Gson();
String jsonFilename = "wellSetup.json";
JSONParser parser = new JSONParser();
try {
@@ -1028,55 +891,70 @@ public class Well {
} catch (FileNotFoundException e) {
System.out.println("No configuration file found. Pulling latest value from database.");
Document newConfigDoc = db.getLatestWellConfiguration();
JsonObject newConfigDoc = db.getLatestWellConfiguration();
Object newWellName = newConfigDoc.get("wellName");
if (newWellName != null) wellName = (String) newWellName;
Object newDeltaT = newConfigDoc.get("deltaT");
if (newDeltaT != null) dt = (Double) newDeltaT;
JsonPrimitive wellConfigPrimitive = newConfigDoc.getAsJsonPrimitive("well_config");
String wellConfigString = wellConfigPrimitive.getAsString();
JsonObject wellConfig = gson.fromJson(wellConfigString, JsonObject.class);
Object newPumpDiameter = newConfigDoc.get("pumpDiameter");
if (newPumpDiameter != null) setPumpDiameter((Double) newPumpDiameter);
Object newFluidGradient = newConfigDoc.get("fluidGradient");
if (newFluidGradient != null) fluidGradient = (Double) newFluidGradient;
JsonElement newWellName = wellConfig.get("wellName");
if (newWellName != null) wellName = newWellName.getAsString();
Object newTubingID = newConfigDoc.get("tubingID");
if (newTubingID != null) setTubingID((Double) newTubingID);
JsonElement newDeltaT = wellConfig.get("deltaT");
if (newDeltaT != null) dt = newDeltaT.getAsDouble();
Object newTubingOD = newConfigDoc.get("tubingOD");
if (newTubingOD != null) setTubingOD((Double) newTubingOD);
JsonElement newPumpDiameter = wellConfig.get("pumpDiameter");
if (newPumpDiameter != null) setPumpDiameter(newPumpDiameter.getAsDouble());
Object newTubingAnchorDepth = newConfigDoc.get("tubingAnchorDepth");
if (newTubingAnchorDepth != null) tubingAnchorDepth = (Double) newTubingAnchorDepth;
JsonElement newFluidGradient = wellConfig.get("fluidGradient");
if (newFluidGradient != null) fluidGradient = newFluidGradient.getAsDouble();
Object newStructuralRating = newConfigDoc.get("structuralRating");
if (newStructuralRating != null) structuralRating = (Double) newStructuralRating;
JsonElement newTubingID = wellConfig.get("tubingID");
if (newTubingID != null) setTubingID(newTubingID.getAsDouble());
Object newStuffingBoxFriction = newConfigDoc.get("stuffingBoxFriction");
if (newStuffingBoxFriction != null) setSbfriction((Double) newStuffingBoxFriction);
JsonElement newTubingOD = wellConfig.get("tubingOD");
if (newTubingOD != null) setTubingOD(newTubingOD.getAsDouble());
Object newTubingHeadPressure = newConfigDoc.get("tubingOD");
if (newTubingHeadPressure != null) setTubingOD((Double) newTubingHeadPressure);
JsonElement newTubingAnchorDepth = wellConfig.get("tubingAnchorDepth");
if (newTubingAnchorDepth != null) tubingAnchorDepth = newTubingAnchorDepth.getAsDouble();
ArrayList<Document> tapers = (ArrayList<Document>) newConfigDoc.get("tapers");
numTapers = tapers.size();
for (int i = 0; i < numTapers; i++) {
int currentTaperNum = i + 1;
Document taperObj = tapers.get(i);
JsonElement newStructuralRating = wellConfig.get("structuralRating");
if (newStructuralRating != null) structuralRating = newStructuralRating.getAsDouble();
Object newLength = taperObj.get("length");
if (newLength != null) setRodLength(currentTaperNum, (Double) newLength);
JsonElement newStuffingBoxFriction = wellConfig.get("stuffingBoxFriction");
if (newStuffingBoxFriction != null) setSbfriction(newStuffingBoxFriction.getAsDouble());
Object newDiameter = taperObj.get("diameter");
if (newDiameter != null) setRodDiameter(currentTaperNum, (Double) newDiameter);
JsonElement newTubingHeadPressure = wellConfig.get("tubingOD");
if (newTubingHeadPressure != null) setTubingOD(newTubingHeadPressure.getAsDouble());
Object newMaterial = taperObj.get("material");
if (newMaterial != null) setRodYM(currentTaperNum, (String) newMaterial);
JSONParser jparser = new JSONParser();
JsonPrimitive taperPrimitive = newConfigDoc.getAsJsonPrimitive("tapers");
String taperString = taperPrimitive.getAsString();
try {
JSONArray tapers = (JSONArray) parser.parse(taperString);
Object newDampingFactor = taperObj.get("dampingFactor");
if (newDampingFactor != null) setDampingFactor(currentTaperNum, (Double) newDampingFactor);
// JsonObject tapers = gson.fromJson(taperString, JsonObject.class);
numTapers = tapers.size();
for (int i = 0; i < numTapers; i++) {
int currentTaperNum = i + 1;
JSONObject taperObj = (JSONObject) tapers.get(i);
Object newLength = taperObj.get("length");
if (newLength != null) setRodLength(currentTaperNum, (Double) newLength);
Object newDiameter = taperObj.get("diameter");
if (newDiameter != null) setRodDiameter(currentTaperNum, (Double) newDiameter);
Object newMaterial = taperObj.get("material");
if (newMaterial != null) setRodYM(currentTaperNum, (String) newMaterial);
Object newDampingFactor = taperObj.get("dampingFactor");
if (newDampingFactor != null) setDampingFactor(currentTaperNum, (Double) newDampingFactor);
}
} catch (ParseException e1) {
e1.printStackTrace();
}
updateTapers(false);
} catch (IOException | ParseException e) {