Skip to content

Commit

Permalink
Merge pull request #1 from Terryxxx/smoke_eventdata_test
Browse files Browse the repository at this point in the history
Add event data test case
  • Loading branch information
Terryxxx committed Dec 29, 2017
2 parents a04e1ed + 82e84cf commit abf670c
Show file tree
Hide file tree
Showing 15 changed files with 643 additions and 0 deletions.
1 change: 1 addition & 0 deletions settings.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ include ':test:smoke:appServers'
include ':test:smoke:appServers:Tomcat.7'
include ':test:smoke:testApps'
include ':test:smoke:testApps:SimpleCalculator'
include ':test:smoke:testApps:SimpleEventData'
include ':test:smoke:utils'

if (System.env.'COLLECTD_HOME') {
Expand Down
25 changes: 25 additions & 0 deletions test/smoke/testApps/SimpleEventData/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// apply plugin: 'java-library'
apply plugin: 'war'

dependencies {
compile project(':core')
compile project(':web')
compile 'com.google.guava:guava:20.0'

providedCompile 'javax.servlet:javax.servlet-api:3.0.1'

providedRuntime 'mysql:mysql-connector-java:5.1.44'

smokeTestCompile 'com.google.guava:guava:23.0'

// FIXME these are not necessary; they're a workaround for a VSCode intellisense bug (it doesn't work with only the smokeTest configuration)
testCompile 'com.google.guava:guava:23.0'
}

compileJava.sourceCompatibility = 1.7
compileJava.targetCompatibility = 1.7
compileSmokeTestJava.sourceCompatibility = 1.8
compileSmokeTestJava.targetCompatibility = 1.8

ext.testAppArtifactDir = war.destinationDir
ext.testAppArtifactFilename = war.archiveName
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.microsoft.ajl.simplecalc;

public class CalculationDatabaseConfig {
private final String url;
private final String username;
private final String password;
public CalculationDatabaseConfig(String url, String username, String password) {
this.url = url;
this.username = username;
this.password = password;
}
public String getUrl() {
return url;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
package com.microsoft.ajl.simplecalc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;

import com.microsoft.ajl.simplecalc.model.BinaryCalculation;
import com.microsoft.ajl.simplecalc.model.BinaryCalculation.TimestampedBinaryCalculation;
import com.microsoft.ajl.simplecalc.model.BinaryOperator;

public class CalculationHistoryService implements ICalculationHistoryService {
static {
try {
Class<?> clazz = Class.forName("com.mysql.jdbc.Driver");
clazz.newInstance();
} catch (ClassNotFoundException e) {
System.err.println("Couldn't find mysql jdbc driver");
e.printStackTrace();
} catch (InstantiationException e) {
System.err.println("Couldn't create instance of mysql jdbc driver");
e.printStackTrace();
} catch (IllegalAccessException e) {
System.err.println("Error loading mysql jdbc driver");
e.printStackTrace();
}
}

private final CalculationDatabaseConfig config;
private final String table;
private final String database;

public CalculationHistoryService() {
database = "calc_history";
table = "history";
String url = String.format(
"jdbc:mysql://arlittle-test-db.mysql.database.azure.com:3306/%s?verifyServerCertificate=false&useSSL=false&requireSSL=false",
database);
String username = "arlittle@arlittle-test-db";
String password = "Molson1Molson2";
config = new CalculationDatabaseConfig(url, username, password);
}

@Override
public void addHistoryEntry(BinaryCalculation bc) {
Connection conn = null;
try {
conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(String.format(
"INSERT INTO `%s`.`%s` (`timestamp`, `leftOperand`, `rightOperand`, `operator`) VALUES (?, ?, ?, ?)",
database, table));
int rowsUpdated = stmt.executeUpdate();
System.out.printf("Added history entry. Rows updated: %d%n", rowsUpdated);
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// don't care
}
}
}
}

private Connection getConnection() throws SQLException {
Connection conn = null;
final int maxTries = 3;
SQLException lastException = null;
for (int tries = 0; tries < maxTries; tries++) {
try {
conn = DriverManager.getConnection(config.getUrl(), config.getUsername(), config.getPassword());
Statement testConn = conn.createStatement();
testConn.executeQuery(String.format("SELECT 1 FROM `%s`.`%s` WHERE 1=1", database, table));
return conn;
} catch (SQLException e) {
lastException = e;
System.err.printf("couldn't connect or health check failed: %s%n", e.getLocalizedMessage());
if (conn != null) {
try {
conn.close();
} catch (SQLException e1) {
// don't care
}
}
}
}
if (lastException != null) {
throw lastException;
}
throw new IllegalStateException("Could not return connection and had no exception.");
}

@Override
public Collection<TimestampedBinaryCalculation> getHistoryEntries() {
Connection conn = null;
try {
conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(
"SELECT `timestamp`,`leftOperand`,`operator`,`rightOperand` FROM `calc_history`.`history` LIMIT 10");
ResultSet results = stmt.executeQuery();
try {
int resultCount = 0;
Collection<TimestampedBinaryCalculation> rval = new ArrayList<TimestampedBinaryCalculation>();
while (results.next()) {
resultCount++;
double lo = results.getDouble("leftOperand");
double ro = results.getDouble("rightOperand");
String verb = results.getString("operator");
BinaryOperator op = BinaryOperator.fromVerb(verb);
if (op == null) {
System.err.println("found unknown binary operator: " + verb);
continue;
}
BinaryCalculation bc = new BinaryCalculation(lo, ro, op);
rval.add(new TimestampedBinaryCalculation(bc));
}
System.out.printf("database returned %d results. parsed %d results successfully.%n", resultCount, rval.size());
return rval;
} finally {
results.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// don't care
}
}
}
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.microsoft.ajl.simplecalc;

public class CalculatorParameterException extends Exception {
private static final long serialVersionUID = -8200839910936319857L;

public CalculatorParameterException() {
super();
}

public CalculatorParameterException(String message, Throwable cause) {
super(message, cause);
}

public CalculatorParameterException(String message) {
super(message);
}

public CalculatorParameterException(Throwable cause) {
super(cause);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.microsoft.ajl.simplecalc;

import java.util.Collection;

import com.microsoft.ajl.simplecalc.model.BinaryCalculation;
import com.microsoft.ajl.simplecalc.model.BinaryCalculation.TimestampedBinaryCalculation;

public interface ICalculationHistoryService {
void addHistoryEntry(BinaryCalculation bc);
Collection<TimestampedBinaryCalculation> getHistoryEntries();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.microsoft.ajl.simplecalc;

public class ParameterConstants {
public static final String LEFT_OPERAND = "leftOperand";
public static final String RIGHT_OPERAND = "rightOperand";
public static final String OPERATOR = "operator";
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
package com.microsoft.ajl.simplecalc;

import com.microsoft.ajl.simplecalc.model.BinaryCalculation;
import com.microsoft.ajl.simplecalc.model.BinaryOperator;
import com.microsoft.applicationinsights.TelemetryClient;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import static com.microsoft.ajl.simplecalc.ParameterConstants.*;

/**
* Servlet implementation class SimpleCalculatorServlet
*/
@WebServlet(description = "Performs given calculation", urlPatterns = { "/doCalc" })
public class SimpleCalculatorServlet extends HttpServlet {
private static final long serialVersionUID = -633683109556605395L;

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
BinaryCalculation bc = null;
try {
bc = readParameters(request.getParameterMap());
}
catch (CalculatorParameterException cpe) {
String errMsg = cpe.getLocalizedMessage();
System.err.println(errMsg);
response.sendError(HttpServletResponse.SC_BAD_REQUEST, errMsg);
return;
}

if (bc == null) {
System.out.println("No parameters given.");
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
return;
}

response.setContentType("text/html;charset=UTF-8");
renderHtml(bc, response.getWriter());

new TelemetryClient().trackEvent("EventDataTest");

Map<String, String> properties = new ConcurrentHashMap<String, String>();
properties.put("price", String.valueOf(100));

Map<String, Double> metrics = new ConcurrentHashMap<String, Double>();
metrics.put("score", Double.valueOf(200));

new TelemetryClient().trackEvent("EventDataTest2", properties, metrics);
}

/**
* @param parameterMap
* @return null if parameterMap is empty
*/
private static BinaryCalculation readParameters(Map<String, String[]> parameterMap) throws CalculatorParameterException {
if (parameterMap == null) {
throw new IllegalArgumentException("parameterMap cannot be null");
}

if (parameterMap.isEmpty()) {
return null;
}

// log params
System.out.println("Given parameters:");
for (Entry<String, String[]> entry : parameterMap.entrySet()) {
String pname = entry.getKey();
System.out.printf("%s: %s%n", pname, Arrays.toString(entry.getValue()));
}

// FIXME this could throw, but I don't care
String strLopnd = parameterMap.get(LEFT_OPERAND)[0];
String strRopnd = parameterMap.get(RIGHT_OPERAND)[0];
String strOprtr = parameterMap.get(OPERATOR)[0];

double lopnd = parseParamOrThrow(strLopnd, "Left operand is not a number: %s");
double ropnd = parseParamOrThrow(strRopnd, "Right operand is not a number: %s");

BinaryOperator op = BinaryOperator.fromVerb(strOprtr);
if (op == null) {
throw new CalculatorParameterException("Unknown operator: "+strOprtr);
}

return new BinaryCalculation(lopnd, ropnd, op);
}

private static double parseParamOrThrow(String param, String errMsgFmt) throws CalculatorParameterException {
try {
return Double.parseDouble(param);
} catch (NumberFormatException e) {
throw new CalculatorParameterException(String.format("Left operand is not a number: %s", param), e);
}
}

private static void renderHtml(BinaryCalculation calc, PrintWriter writer) {
writer.println("<html>");
writer.println("<head><title>Calculation Result</title></head>");
writer.println("<body>");
writer.printf("<i>%s</i> %s <i>%s</i> = <b>%s</b>%n",
calc.getLeftOperandFormatted(),
calc.getOperatorSymbol(),
calc.getRightOperandFormatted(),
calc.resultFormatted());
writer.println("<p><a href=\"/SimpleCalculator/\">Do Another Calculation</a></p>");
writer.println("</body></html>");
}

}
Loading

0 comments on commit abf670c

Please sign in to comment.