i am new to Servlets and testing. I have to get the Code Coverage up for my University Project but it seems like i cant get an idea of how and where to start. Our Prof. gave us Code we need to Cover with tests, can anybody give me a hint where to start ?
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String cmd = request.getParameter("cmd");
System.out.println( cmd + " requested: " + request.getQueryString());
switch ( cmd ){
case "config":
// Overwrite Parkhaus config parameters
// Max, open_from, open_to, delay, simulation_speed
out.println( config() );
break;
case "sum":
// ToDo: insert algorithm for calculating sum here
out.println( "sum = server side calculated sum" );
break;
case "avg":
// ToDo
break;
case "min":
// ToDo: insert algorithm for calculating min here
out.println( "min = server side calculated min" );
break;
case "max":
// ToDo: insert algorithm for calculating max here
out.println( "max = server side calculated max" );
break;
case "cars":
// TODO: Send list of cars stored on the server to the client.
// Cars are separated by comma.
// Values of a single car are separated by slash.
// Format: Nr, timer begin, duration, price, Ticket, color, space, client category, vehicle type, license (PKW Kennzeichen)
// For example:
// TODO replace by real list of cars
// out.println("1/1648465400000/_/_/Ticket1/#0d1e0a/2/any/PKW/1,2/1648465499999/_/_/Ticket2/#dd10aa/3/any/PKW/2");
break;
case "chart":
// TODO send chart infos as JSON object to client
break;
default:
System.out.println("Invalid Command: " + request.getQueryString());
}
I tried different things with Jmockit but didn't get really far
Related
I'm just getting started on stream processing using Apache Flink, the thing is that I'm receiving a stream of Json that look like this:
{
token_id: “tok_afgtryuo”,
ip_address: “128.123.45.1“,
device_fingerprint: “abcghift”,
card_hash: “hgtyuigash”,
“bin_number”: “424242”,
“last4”: “4242”,
“name”: “Seu Jorge”
}
And was asked if i could fulfill the following business rules:
Decline if number of tokens > 5 for this IP in last 10 seconds
Decline if number of tokens > 15 for this IP in last minute
Decline if number of tokens > 60 for this IP in last hour
I made 2 classes, main class when I'm making an instance to call the Window function with different parameters to avoid duplicate code:
Main.java
public static void main(String[] args) throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
//This DataStream Would be Converting the Json to a Token Object
DataStream<Token> baseStream =
env.addSource(new SocketTextStreamFunction("localhost",
9999,
"\n",
1))
.map(new MapTokens());
// 1- First rule Decline if number of tokens > 5 for this IP in last 10 seconds
DataStreamSink<String> response1 = new RuleMaker().getStreamKeyCount(baseStream, "ip", Time.seconds(10),
5, "seconds").print();
//2 -Decline if number of tokens > 15 for this IP in last minute
DataStreamSink<String> response2 = new RuleMaker().getStreamKeyCount(baseStream, "ip", Time.minutes(1),
62, "minutes").print();
//3- Decline if number of tokens > 60 for this IP in last hour
DataStreamSink<String> response3 = new RuleMaker().getStreamKeyCount(baseStream, "ip", Time.hours(1),
60, "Hours").print();
env.execute("Job2");
}
And another class where I'm doing all the logic for rules, I'm counting the times where an IP address appears and, if it is more than the allowed number in the time window I'm returning a message with some information:
Rulemaker.java
public class RuleMaker {
public DataStream<String> getStreamKeyCount(DataStream<Token> stream,
String tokenProp,
Time time,
Integer maxPetitions,
String ruleType){
return
stream
.flatMap(new FlatMapFunction<Token, Tuple3<String, Integer, String>>() {
#Override
public void flatMap(Token token, Collector<Tuple3<String, Integer, String>> collector) throws Exception {
String tokenSelection = "";
switch (tokenProp)
{
case "ip":
tokenSelection = token.getIpAddress();
break;
case "device":
tokenSelection = token.getDeviceFingerprint();
break;
case "cardHash":
tokenSelection = token.getCardHash();
break;
}
collector.collect(new Tuple3<>(tokenSelection, 1, token.get_tokenId()));
}
})
.keyBy(0)
.timeWindow(time)
.process(new MyProcessWindowFunction(maxPetitions, ruleType));
}
//Class to process the elements from the window
private class MyProcessWindowFunction extends ProcessWindowFunction<
Tuple3<String, Integer, String>,
String,
Tuple,
TimeWindow
> {
private Integer _maxPetitions;
private String _ruleType;
public MyProcessWindowFunction(Integer maxPetitions, String ruleType) {
this._maxPetitions = maxPetitions;
this._ruleType = ruleType;
}
#Override
public void process(Tuple tuple, Context context, Iterable<Tuple3<String, Integer, String>> iterable, Collector<String> out) throws Exception {
Integer counter = 0;
for (Tuple3<String, Integer, String> element : iterable) {
counter += element.f1++;
if(counter > _maxPetitions){
out.collect("El elemeto ha sido declinado: " + element.f2 + " Num elements: " + counter + " rule type: " + _ruleType + " token: " + element.f0 );
counter = 0;
}
}
}
}
}
So far, i think this code is working but I'm a begginer on Apache Flink, and I'll appreciate a lot if you could tell me if it's something wrong about the way I'm trying to work with this and point me to the right direction.
Thanks a lot.
General approach looks very good, although I would have thought that Table API would be powerful enough to help you (more concise) which supports Json out of the box.
If you want to stick to DataStream API, in getStreamKeyCount, the switch around tokenProp should be replaced by passing a key extractor to getStreamKeyCount to have only one place to add new rules.
public DataStream<String> getStreamKeyCount(DataStream<Token> stream,
KeySelector<Token, String> keyExtractor,
Time time,
Integer maxPetitions,
String ruleType){
return stream
.map(token -> new Tuple3<>(keyExtractor.getKey(token), 1, token.get_tokenId()))
.keyBy(0)
.timeWindow(time)
.process(new MyProcessWindowFunction(maxPetitions, ruleType));
}
Then the invocation becomes
DataStreamSink<String> response2 = ruleMaker.getStreamKeyCount(baseStream,
Token::getIpAddress, Time.minutes(1), 62, "minutes");
I am evaluating the AppEngine Document Indexes Fulltext Search, and run into some problems while using the Stem Operator '~'.
Basically I created an index of a few test documents, all with a title field. Some of the example values of the field are:
"Houses Desks Tables"
"referer image vod event"
"events with cats and dogs and"
"names very interesting days"
I'm using Java, and a snippet of my query code looks like below:
Document doc = Document.newBuilder().setId(key)
.addField(Field.newBuilder().setName("title").setText(title))
.addField(Field.newBuilder().setName("type").setText(type))
.addField(Field.newBuilder().setName("username").setText(username))
.build();
DocumentSearchIndexService.getInstance().indexDocument(indexName, doc);
IndexSpec indexSpec = IndexSpec.newBuilder().setName(indexName).build();
Index index = SearchServiceFactory.getSearchService().getIndex(indexSpec);
return index.search("title = ~"+searchText);
However, the returned result will always only matching the exact singular or plural form:
query cat, return nothing
query dog, return nothing
query name, return nothing
query house, return nothing
query cats, return "events with cats and dogs and"
query dogs, return "events with cats and dogs and"
query names, return "names very interesting days"
query houses, return "Houses Desks Tables"
So I am really lost as in how the entries are returned, or if the way my query constructed is not correct.
Notice that stemming is not implemented if you are using the Java Development Server for Java 8 on the Standard Environment.
If you are deploying your application on App Engine use the Utils.java class found here to properly index your document.
I cloned the repository for the java-docs-samples for Google Cloud Platform, went to the appengine-java8/search folder and modified the code for the SearchServlet.java class in the following way in order to include queries with the stem operator "~":
...
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter out = resp.getWriter();
Document doc =
Document.newBuilder()
.setId("theOnlyPiano")
.addField(Field.newBuilder().setName("product").setText("cats and dogs"))
.addField(Field.newBuilder().setName("maker").setText("Yamaha"))
.addField(Field.newBuilder().setName("price").setNumber(4000))
.build();
try {
Utils.indexADocument(SEARCH_INDEX, doc);
} catch (InterruptedException e) {
// ignore
}
// [START search_document]
final int maxRetry = 3;
int attempts = 0;
int delay = 2;
while (true) {
try {
String searchText = "cat";
String queryString = "product = ~"+searchText;
Results<ScoredDocument> results = getIndex().search(queryString);
// Iterate over the documents in the results
for (ScoredDocument document : results) {
// handle results
out.print("product: " + document.getOnlyField("product").getText());
//out.println(", price: " + document.getOnlyField("price").getNumber());
}
} catch (SearchException e) {
if (StatusCode.TRANSIENT_ERROR.equals(e.getOperationResult().getCode())
&& ++attempts < maxRetry) {
// retry
try {
Thread.sleep(delay * 1000);
} catch (InterruptedException e1) {
// ignore
}
delay *= 2; // easy exponential backoff
continue;
} else {
throw e;
}
}
break;
}
// [END search_document]
// We don't test the search result below, but we're fine if it runs without errors.
out.println(" Search performed");
Index index = getIndex();
// [START simple_search_1]
index.search("rose water");
// [END simple_search_1]
// [START simple_search_2]
index.search("1776-07-04");
// [END simple_search_2]
// [START simple_search_3]
// search for documents with pianos that cost less than $5000
index.search("product = ~cat AND price < 5000");
// [END simple_search_3]
}
}
and I was able to verify that the stem operator works "~" correctly for plurals (with words like cats, dogs, etc.). But notice that as mentioned on the documentation the stemming algorithm has its limitations.
Note. If you want to replicate the steps I made don't forget to comment the testing section on the SearchServletTest.java class prior deploying the application to App Engine with mvn appengine:deploy. The file should look like this:
...
#After
public void tearDown() {
helper.tearDown();
}
#Test
public void doGet_successfulyInvoked() throws Exception {
// servletUnderTest.doGet(mockRequest, mockResponse);
// String content = responseWriter.toString();
// assertWithMessage("SearchServlet response").that(content).contains("maker: Yamaha");
// assertWithMessage("SearchServlet response").that(content).contains("price: 4000.0");
}
}
I don't understand why a variable work in one part of code but in other part no. is the same variable, is referencied with the same value. this is my code
// Variables
String patologicos="";
String ginecologicos="";
String valuePanel="";
JTextArea ja;
here is built the constructor
public BaseHistorialPanelNoEditable(int typePanel){
// constructor
ja = new JTextArea();
ja.setPreferredSize(new Dimension(900, 280));
setBackground(Layout.pac_background);
ja.setEditable(false);
this.add(ja);
showInformation(typePanel);
}
Method to show some information
public void showInformation(int value){
// getting data from DB
getPatientData();
switch (value) {
case 1:
valuePanel = patologicos;
break;
case 2:
valuePanel = ginecologicos;
break;
default:
break;
}
// show message
Main.buildDialog(value + " " +valuePanel, "Mensaje informativo", JOptionPane.INFORMATION_MESSAGE);
// set a value to text area
ja.setText(valuePanel);
}
Method to get information from database
public void getPatientData(){
Main.readdb.select(
"select * from clinic where no_paciente=" +
Paciente.getPac_no());
if (Main.readdb.getNext()) {
patologicos = Main.readdb.getString("historia_clinic");
ginecologicos = Main.readdb.getString("gineco");
}
this fragment of code show a message
Main.buildDialog(value + " " +valuePanel, "Mensaje informativo", JOptionPane.INFORMATION_MESSAGE);
using the same variable it works.
why when I use the same variable one line after, it doesn't have any value?
ja.setText(valuePanel);
Thanks for your time.
Not sure but just an idea..
When you use setEditable(false).. It might be internal implementation that won't allow to set value..
try this:
ja.setEditable(true);
ja.setText(valuePanel);
ja.setEditable(false);
Hope this make sense..
Using Following Code I am able to add test cases in to newly created test set in RALLY.
But it add only first 200 test cases from the Test case list.
private static String createTestSet(RallyRestApi restApi, String TSName, String points)throws IOException, URISyntaxException {
QueryRequest testcases = new QueryRequest("Test Case");
testcases.setFetch(new Fetch("FormattedID", "Name", "Owner","Test Folder"));
// All Test cases
testcases.setQueryFilter(new QueryFilter("TestFolder.Name", "=","testFolder").and(new QueryFilter("Method", "=", "Manual")));
testcases.setOrder("FormattedID ASC");
QueryResponse queryResponse = restApi.query(testcases);
JsonArray testCaseList = new JsonArray();
if (queryResponse.wasSuccessful()) {
System.out.println(String.format("\nTotal results: %d", queryResponse.getTotalResultCount()));
testCaseList=queryResponse.getResults().getAsJsonArray();
}else{
for (String err : queryResponse.getErrors()) {
System.err.println("\t" + err);
}
}
String ref = "null";
System.out.println("Creating TestSet: "+TSName);
try {
if(!testCaseList.isJsonNull()){
restApi.setApplicationName("PSN");
JsonObject newTS = new JsonObject();
newTS.addProperty("Name", TSName);
newTS.addProperty("PlanEstimate", points);
newTS.addProperty("Project", Project_ID);
newTS.addProperty("Release", Release_ID);
newTS.addProperty("Iteration", Iteration_ID);
newTS.add("TestCases", testCaseList);
CreateRequest createRequest = new CreateRequest("testset",newTS);
CreateResponse createResponse = restApi.create(createRequest);
ref = createResponse.getObject().get("_ref").getAsString();
}
} catch (Exception e) {
//System.out.println("Exception Caught: " + e.getMessage());
}
return ref;
}
Although the Total Result count of Test case query filter is greater than 200, Test Set is getting created with only 200 Test case in it.
#Brian's comment above is correct. By default RallyRestApi.query() will only return one page of data (with the default page size being 200). QueryResponse.getTotalResultCount() will return the total number of records that matched on the server. In order to get more than one page of data simply use QueryRequest.setLimit() first to set an upper bound on the number of results you'd like returned.
I want to detect the device through serial port using RxTx in java and device is programmed that if it recieves a specific word from computer it will reply "ok" and if the computer receives ok.. it will stop sending the word and highlight that the device is attached. PLEASE HELP ME. and one more thing.. i have to check for every port.. please will you code a method that auto-cycle through the ports till the device is detected.
My code sends the word only one time even being in a infinite loop.
code:
private void cb1KeyPressed(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
try{
l1.setText("Port: "+cb1.getSelectedItem().toString()+" is Selected");
selectedPort = cb1.getSelectedItem().toString();// TODO add your handling code here
rs.connect(selectedPort);
for(;;)
{
CommPortSender.send(new ProtocolImpl().getMessage("KITM"));//send message
if(pi.rmess().equalsIgnoreCase("OK"))//received message
{
l1.setText("The Device is attached to: "+selectedPort);
CommPortSender.send(new ProtocolImpl().getMessage("OK ACK"));//send message
break;
}
else
{
rs.disconnect(selectedPort);
continue;
}
}
}
catch(Exception e){}
}
static void listPorts()
{
java.util.Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
while ( portEnum.hasMoreElements() )
{
CommPortIdentifier portIdentifier = portEnum.nextElement();
System.out.println(portIdentifier.getName() + " - " + getPortTypeName(portIdentifier.getPortType()) );
}
}
static String getPortTypeName ( int portType )
{
switch ( portType )
{
case CommPortIdentifier.PORT_I2C:
return "I2C";
case CommPortIdentifier.PORT_PARALLEL:
return "Parallel";
case CommPortIdentifier.PORT_RAW:
return "Raw";
case CommPortIdentifier.PORT_RS485:
return "RS485";
case CommPortIdentifier.PORT_SERIAL:
return "Serial";
default:
return "unknown type";
}
}
5 minutes of googling could have told you the same thing.