CSVSaveService.java

Index Score
org.apache.jmeter.save
JMeter

View: Reasons, Metrics, Source Code

These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.

MetricDescription
EXITSProcedure exits
COMPARISONSNumber of comparison operators
SIZESize of the file in bytes
LOGICAL_LINESNumber of statements
BLOCKSNumber of blocks
OPERATORSNumber of operators
PROGRAM_LENGTHHalstead program length
CYCLOMATICCyclomatic complexity
OPERANDSNumber of operands
ELOCEffective lines of code
LOCLines of code
UNIQUE_OPERANDSNumber of unique operands
LOOPSNumber of loops
LINESNumber of lines in the source file
PROGRAM_VOCABHalstead program vocabulary
LINE_COMMENTNumber of line comments
JAVA0150JAVA0150 java.lang.Error (or subclass) thrown
DECL_COMMENTSComments in declarations
JAVA0034JAVA0034 Missing braces in if statement
RETURNSNumber of return points from functions
INTERFACE_COMPLEXITYInterface complexity
JAVA0067JAVA0067 Array descriptor on identifier name
EXEC_COMMENTSComments in executable code
COMMENTSComment lines
PARAMSNumber of formal parameter declarations
JAVA0132JAVA0132 Method overload with compatible signature
JAVA0270JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
JAVA0117JAVA0117 Missing javadoc: method 'method'
UNIQUE_OPERATORSNumber of unique operators
JAVA0177JAVA0177 Variable declaration missing initializer
JAVA0128JAVA0128 Public constructor in non-public class
PROGRAM_VOLUMEHalstead program volume
DOC_COMMENTNumber of javadoc comment lines
JAVA0032JAVA0032 Switch statement missing default
JAVA0126JAVA0126 Method declares unchecked exception in throws
JAVA0110JAVA0110 Incorrect javadoc: no @return tag
JAVA0064JAVA0064 N variations of identifier name (maximum: M)
WHITESPACENumber of whitespace lines
JAVA0068JAVA0068 Modifiers not declared in recommended order
NEST_DEPTHMaximum nesting depth
JAVA0145JAVA0145 Tab character used in source file
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.jmeter.save; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Vector; import javax.swing.table.DefaultTableModel; import org.apache.commons.collections.map.LinkedMap; import org.apache.commons.lang.CharUtils; import org.apache.commons.lang.StringUtils; import org.apache.jmeter.assertions.AssertionResult; import org.apache.jmeter.reporters.ResultCollector; import org.apache.jmeter.samplers.SampleEvent; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.samplers.SampleSaveConfiguration; import org.apache.jmeter.samplers.StatisticalSampleResult; import org.apache.jmeter.util.JMeterUtils; import org.apache.jmeter.visualizers.Visualizer; import org.apache.jorphan.logging.LoggingManager; import org.apache.jorphan.reflect.Functor; import org.apache.jorphan.util.JMeterError; import org.apache.jorphan.util.JOrphanUtils; import org.apache.log.Logger; import org.apache.oro.text.regex.Pattern; import org.apache.oro.text.regex.PatternMatcherInput; import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Matcher; /** * This class provides a means for saving/reading test results as CSV files. */ public final class CSVSaveService { private static final Logger log = LoggingManager.getLoggerForClass(); // --------------------------------------------------------------------- // XML RESULT FILE CONSTANTS AND FIELD NAME CONSTANTS // --------------------------------------------------------------------- private static final String DATA_TYPE = "dataType"; // $NON-NLS-1$ private static final String FAILURE_MESSAGE = "failureMessage"; // $NON-NLS-1$ private static final String LABEL = "label"; // $NON-NLS-1$ private static final String RESPONSE_CODE = "responseCode"; // $NON-NLS-1$ private static final String RESPONSE_MESSAGE = "responseMessage"; // $NON-NLS-1$ private static final String SUCCESSFUL = "success"; // $NON-NLS-1$ private static final String THREAD_NAME = "threadName"; // $NON-NLS-1$ private static final String TIME_STAMP = "timeStamp"; // $NON-NLS-1$ // --------------------------------------------------------------------- // ADDITIONAL CSV RESULT FILE CONSTANTS AND FIELD NAME CONSTANTS // --------------------------------------------------------------------- private static final String CSV_ELAPSED = "elapsed"; // $NON-NLS-1$ private static final String CSV_BYTES= "bytes"; // $NON-NLS-1$ private static final String CSV_THREAD_COUNT1 = "grpThreads"; // $NON-NLS-1$ private static final String CSV_THREAD_COUNT2 = "allThreads"; // $NON-NLS-1$ private static final String CSV_SAMPLE_COUNT = "SampleCount"; // $NON-NLS-1$ private static final String CSV_ERROR_COUNT = "ErrorCount"; // $NON-NLS-1$ private static final String CSV_URL = "URL"; // $NON-NLS-1$ private static final String CSV_FILENAME = "Filename"; // $NON-NLS-1$ private static final String CSV_LATENCY = "Latency"; // $NON-NLS-1$ private static final String CSV_ENCODING = "Encoding"; // $NON-NLS-1$ private static final String CSV_HOSTNAME = "Hostname"; // $NON-NLS-1$ // Used to enclose variable name labels, to distinguish from any of the above labels private static final String VARIABLE_NAME_QUOTE_CHAR = "\""; // $NON-NLS-1$ // Initial config from properties static private final SampleSaveConfiguration _saveConfig = SampleSaveConfiguration.staticConfig(); // Date format to try if the time format does not parse as milliseconds // (this is the suggested value in jmeter.properties) private static final String DEFAULT_DATE_FORMAT_STRING = "MM/dd/yy HH:mm:ss"; // $NON-NLS-1$ private static final DateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat(DEFAULT_DATE_FORMAT_STRING); /** * Private constructor to prevent instantiation. */ private CSVSaveService() { } /** * Read Samples from a file; handles quoted strings. * * @param filename input file * @param visualizer where to send the results * @param resultCollector the parent collector * @throws IOException */ public static void processSamples(String filename, Visualizer visualizer, ResultCollector resultCollector) throws IOException { BufferedReader dataReader = null; try { dataReader = new BufferedReader(new FileReader(filename)); dataReader.mark(400);// Enough to read the header column names // Get the first line, and see if it is the header String line = dataReader.readLine(); long lineNumber=1; SampleSaveConfiguration saveConfig = CSVSaveService.getSampleSaveConfiguration(line,filename); if (saveConfig == null) {// not a valid header log.info(filename+" does not appear to have a valid header. Using default configuration."); saveConfig = (SampleSaveConfiguration) resultCollector.getSaveConfig().clone(); // may change the format later dataReader.reset(); // restart from beginning lineNumber = 0; } String [] parts; while ((parts = csvReadFile(dataReader, saveConfig.getDelimiter().charAt(0))).length != 0) { lineNumber++; SampleEvent event = CSVSaveService.makeResultFromDelimitedString(parts,saveConfig,lineNumber); if (event != null){ final SampleResult result = event.getResult(); if (resultCollector.isSampleWanted(result.isSuccessful())) { visualizer.add(result); } } } } finally { JOrphanUtils.closeQuietly(dataReader); } } /** * Make a SampleResult given a delimited string. * * @param inputLine - line from CSV file * @param saveConfig - configuration * @param lineNumber - line number for error reporting * @return SampleResult * * @deprecated Does not handle quoted strings; use {@link #processSamples(String, Visualizer, ResultCollector)} instead * * @throws JMeterError */ public static SampleEvent makeResultFromDelimitedString( final String inputLine, final SampleSaveConfiguration saveConfig, // may be updated final long lineNumber) { /* * Bug 40772: replaced StringTokenizer with String.split(), as the * former does not return empty tokens. */ // The \Q prefix is needed to ensure that meta-characters (e.g. ".") work. String parts[]=inputLine.split("\\Q"+saveConfig.getDelimiter());// $NON-NLS-1$ return makeResultFromDelimitedString(parts, saveConfig, lineNumber); } /** * Make a SampleResult given a set of tokens * @param parts tokens parsed from the input * @param saveConfig the save configuration (may be updated) * @param lineNumber * @return the sample result * * @throws JMeterError */ private static SampleEvent makeResultFromDelimitedString( final String[] parts, final SampleSaveConfiguration saveConfig, // may be updated final long lineNumber) { SampleResult result = null; String hostname = "";// $NON-NLS-1$ long timeStamp = 0; long elapsed = 0; String text = null; String field = null; // Save the name for error reporting int i=0; try { if (saveConfig.saveTimestamp()){ field = TIME_STAMP; text = parts[i++]; if (saveConfig.printMilliseconds()) { try { timeStamp = Long.parseLong(text); } catch (NumberFormatException e) {// see if this works log.warn(e.toString()); Date stamp = DEFAULT_DATE_FORMAT.parse(text); timeStamp = stamp.getTime(); log.warn("Setting date format to: "+DEFAULT_DATE_FORMAT_STRING); saveConfig.setFormatter(DEFAULT_DATE_FORMAT); } } else if (saveConfig.formatter() != null) { Date stamp = saveConfig.formatter().parse(text); timeStamp = stamp.getTime(); } else { // can this happen? final String msg = "Unknown timestamp format"; log.warn(msg); throw new JMeterError(msg); } } if (saveConfig.saveTime()) { field = CSV_ELAPSED; text = parts[i++]; elapsed = Long.parseLong(text); } if (saveConfig.saveSampleCount()) { result = new StatisticalSampleResult(timeStamp, elapsed); } else { result = new SampleResult(timeStamp, elapsed); } if (saveConfig.saveLabel()) { field = LABEL; text = parts[i++]; result.setSampleLabel(text); } if (saveConfig.saveCode()) { field = RESPONSE_CODE; text = parts[i++]; result.setResponseCode(text); } if (saveConfig.saveMessage()) { field = RESPONSE_MESSAGE; text = parts[i++]; result.setResponseMessage(text); } if (saveConfig.saveThreadName()) { field = THREAD_NAME; text = parts[i++]; result.setThreadName(text); } if (saveConfig.saveDataType()) { field = DATA_TYPE; text = parts[i++]; result.setDataType(text); } if (saveConfig.saveSuccess()) { field = SUCCESSFUL; text = parts[i++]; result.setSuccessful(Boolean.valueOf(text).booleanValue()); } if (saveConfig.saveAssertionResultsFailureMessage()) { i++; // TODO - should this be restored? } if (saveConfig.saveBytes()) { field = CSV_BYTES; text = parts[i++]; result.setBytes(Integer.parseInt(text)); } if (saveConfig.saveThreadCounts()) { field = CSV_THREAD_COUNT1; text = parts[i++]; result.setGroupThreads(Integer.parseInt(text)); field = CSV_THREAD_COUNT2; text = parts[i++]; result.setAllThreads(Integer.parseInt(text)); } if (saveConfig.saveUrl()) { i++; // TODO: should this be restored? } if (saveConfig.saveFileName()) { field = CSV_FILENAME; text = parts[i++]; result.setResultFileName(text); } if (saveConfig.saveLatency()) { field = CSV_LATENCY; text = parts[i++]; result.setLatency(Long.parseLong(text)); } if (saveConfig.saveEncoding()) { field = CSV_ENCODING; text = parts[i++]; result.setEncodingAndType(text); } if (saveConfig.saveSampleCount()) { field = CSV_SAMPLE_COUNT; text = parts[i++]; result.setSampleCount(Integer.parseInt(text)); field = CSV_ERROR_COUNT; text = parts[i++]; result.setErrorCount(Integer.parseInt(text)); } if (saveConfig.saveHostname()) { field = CSV_HOSTNAME; hostname = parts[i++]; } if (i + saveConfig.getVarCount() < parts.length){ log.warn("Line: "+lineNumber+". Found "+parts.length+" fields, expected "+i+". Extra fields have been ignored."); } } catch (NumberFormatException e) { log.warn("Error parsing field '" + field + "' at line " + lineNumber + " " + e); throw new JMeterError(e); } catch (ParseException e) { log.warn("Error parsing field '" + field + "' at line " + lineNumber + " " + e); throw new JMeterError(e); } catch (ArrayIndexOutOfBoundsException e){ log.warn("Insufficient columns to parse field '" + field + "' at line " + lineNumber); throw new JMeterError(e); } return new SampleEvent(result,"",hostname); } /** * Generates the field names for the output file * * @return the field names as a string */ public static String printableFieldNamesToString() { return printableFieldNamesToString(_saveConfig); } /** * Generates the field names for the output file * * @return the field names as a string */ public static String printableFieldNamesToString(SampleSaveConfiguration saveConfig) { StringBuffer text = new StringBuffer(); String delim = saveConfig.getDelimiter(); if (saveConfig.saveTimestamp()) { text.append(TIME_STAMP); text.append(delim); } if (saveConfig.saveTime()) { text.append(CSV_ELAPSED); text.append(delim); } if (saveConfig.saveLabel()) { text.append(LABEL); text.append(delim); } if (saveConfig.saveCode()) { text.append(RESPONSE_CODE); text.append(delim); } if (saveConfig.saveMessage()) { text.append(RESPONSE_MESSAGE); text.append(delim); } if (saveConfig.saveThreadName()) { text.append(THREAD_NAME); text.append(delim); } if (saveConfig.saveDataType()) { text.append(DATA_TYPE); text.append(delim); } if (saveConfig.saveSuccess()) { text.append(SUCCESSFUL); text.append(delim); } if (saveConfig.saveAssertionResultsFailureMessage()) { text.append(FAILURE_MESSAGE); text.append(delim); } if (saveConfig.saveBytes()) { text.append(CSV_BYTES); text.append(delim); } if (saveConfig.saveThreadCounts()) { text.append(CSV_THREAD_COUNT1); text.append(delim); text.append(CSV_THREAD_COUNT2); text.append(delim); } if (saveConfig.saveUrl()) { text.append(CSV_URL); text.append(delim); } if (saveConfig.saveFileName()) { text.append(CSV_FILENAME); text.append(delim); } if (saveConfig.saveLatency()) { text.append(CSV_LATENCY); text.append(delim); } if (saveConfig.saveEncoding()) { text.append(CSV_ENCODING); text.append(delim); } if (saveConfig.saveSampleCount()) { text.append(CSV_SAMPLE_COUNT); text.append(delim); text.append(CSV_ERROR_COUNT); text.append(delim); } if (saveConfig.saveHostname()) { text.append(CSV_HOSTNAME); text.append(delim); } for (int i = 0; i < SampleEvent.getVarCount(); i++){ text.append(VARIABLE_NAME_QUOTE_CHAR); text.append(SampleEvent.getVarName(i)); text.append(VARIABLE_NAME_QUOTE_CHAR); text.append(delim); } String resultString = null; int size = text.length(); int delSize = delim.length(); // Strip off the trailing delimiter if (size >= delSize) { resultString = text.substring(0, size - delSize); } else { resultString = text.toString(); } return resultString; } // Map header names to set() methods private static final LinkedMap headerLabelMethods = new LinkedMap(); // These entries must be in the same order as columns are saved/restored. static { headerLabelMethods.put(TIME_STAMP, new Functor("setTimestamp")); headerLabelMethods.put(CSV_ELAPSED, new Functor("setTime")); headerLabelMethods.put(LABEL, new Functor("setLabel")); headerLabelMethods.put(RESPONSE_CODE, new Functor("setCode")); headerLabelMethods.put(RESPONSE_MESSAGE, new Functor("setMessage")); headerLabelMethods.put(THREAD_NAME, new Functor("setThreadName")); headerLabelMethods.put(DATA_TYPE, new Functor("setDataType")); headerLabelMethods.put(SUCCESSFUL, new Functor("setSuccess")); headerLabelMethods.put(FAILURE_MESSAGE, new Functor("setAssertionResultsFailureMessage")); headerLabelMethods.put(CSV_BYTES, new Functor("setBytes")); // Both these are needed in the list even though they set the same variable headerLabelMethods.put(CSV_THREAD_COUNT1,new Functor("setThreadCounts")); headerLabelMethods.put(CSV_THREAD_COUNT2,new Functor("setThreadCounts")); headerLabelMethods.put(CSV_URL, new Functor("setUrl")); headerLabelMethods.put(CSV_FILENAME, new Functor("setFileName")); headerLabelMethods.put(CSV_LATENCY, new Functor("setLatency")); headerLabelMethods.put(CSV_ENCODING, new Functor("setEncoding")); // Both these are needed in the list even though they set the same variable headerLabelMethods.put(CSV_SAMPLE_COUNT, new Functor("setSampleCount")); headerLabelMethods.put(CSV_ERROR_COUNT, new Functor("setSampleCount")); headerLabelMethods.put(CSV_HOSTNAME, new Functor("setHostname")); } /** * Parse a CSV header line * @param headerLine from CSV file * @param filename name of file (for log message only) * @return config corresponding to the header items found or null if not a header line */ public static SampleSaveConfiguration getSampleSaveConfiguration(String headerLine, String filename){ String[] parts = splitHeader(headerLine,_saveConfig.getDelimiter()); // Try default delimiter String delim = null; if (parts == null){ Perl5Matcher matcher = JMeterUtils.getMatcher(); PatternMatcherInput input = new PatternMatcherInput(headerLine); Pattern pattern = JMeterUtils.getPatternCache() // This assumes the header names are all single words with no spaces // word followed by 0 or more repeats of (non-word char + word) // where the non-word char (\2) is the same // e.g. abc|def|ghi but not abd|def~ghi .getPattern("\\w+((\\W)\\w+)?(\\2\\w+)*(\\2\"\\w+\")*", // $NON-NLS-1$ // last entries may be quoted strings Perl5Compiler.READ_ONLY_MASK); if (matcher.matches(input, pattern)) { delim = matcher.getMatch().group(2); parts = splitHeader(headerLine,delim);// now validate the result } } if (parts == null) { return null; // failed to recognise the header } // We know the column names all exist, so create the config SampleSaveConfiguration saveConfig=new SampleSaveConfiguration(false); int varCount = 0; for(int i=0;i<parts.length;i++){ String label = parts[i]; if (isVariableName(label)){ varCount++; } else { Functor set = (Functor) headerLabelMethods.get(label); set.invoke(saveConfig,new Boolean[]{Boolean.TRUE}); } } if (delim != null){ log.warn("Default delimiter '"+_saveConfig.getDelimiter()+"' did not work; using alternate '"+delim+"' for reading "+filename); saveConfig.setDelimiter(delim); } saveConfig.setVarCount(varCount); return saveConfig; } private static String[] splitHeader(String headerLine, String delim) { String parts[]=headerLine.split("\\Q"+delim);// $NON-NLS-1$ int previous = -1; // Check if the line is a header for(int i=0;i<parts.length;i++){ final String label = parts[i]; // Check for Quoted variable names if (isVariableName(label)){ previous=Integer.MAX_VALUE; // they are always last continue; } int current = headerLabelMethods.indexOf(label); if (current == -1){ return null; // unknown column name } if (current <= previous){ log.warn("Column header number "+(i+1)+" name "+ label + " is out of order."); return null; // out of order } previous = current; } return parts; } /** * Check if the label is a variable name, i.e. is it enclosed in double-quotes? * * @param label column name from CSV file * @return if the label is enclosed in double-quotes */ private static boolean isVariableName(final String label) { return label.length() > 2 && label.startsWith(VARIABLE_NAME_QUOTE_CHAR) && label.endsWith(VARIABLE_NAME_QUOTE_CHAR); } /** * Method will save aggregate statistics as CSV. For now I put it here. * Not sure if it should go in the newer SaveService instead of here. * if we ever decide to get rid of this class, we'll need to move this * method to the new save service. * @param data vector of data rows * @param writer output file * @throws IOException */ public static void saveCSVStats(Vector data, FileWriter writer) throws IOException { saveCSVStats(data, writer, null); } /** * Method will save aggregate statistics as CSV. For now I put it here. * Not sure if it should go in the newer SaveService instead of here. * if we ever decide to get rid of this class, we'll need to move this * method to the new save service. * @param data vector of data rows * @param writer output file * @param headers header names (if non-null) * @throws IOException */ public static void saveCSVStats(Vector data, FileWriter writer, String headers[]) throws IOException { final char DELIM = ','; final String LINE_SEP = System.getProperty("line.separator"); // $NON-NLS-1$ final char SPECIALS[] = new char[] {DELIM, QUOTING_CHAR}; if (headers != null){ for (int i=0; i < headers.length; i++){ if (i>0) { writer.write(DELIM); } writer.write(quoteDelimiters(headers[i],SPECIALS)); } writer.write(LINE_SEP); } for (int idx=0; idx < data.size(); idx++) { Vector row = (Vector)data.elementAt(idx); for (int idy=0; idy < row.size(); idy++) { if (idy > 0) { writer.write(DELIM); } Object item = row.elementAt(idy); writer.write( quoteDelimiters(String.valueOf(item),SPECIALS)); } writer.write(LINE_SEP); } } /** * Method saves aggregate statistics as CSV from a table model. * Same as {@link #saveCSVStats(Vector, FileWriter, String[])} except * that there is no need to create a Vector containing the data. * * @param model table model containing the data * @param writer output file * @throws IOException */ public static void saveCSVStats(DefaultTableModel model, FileWriter writer) throws IOException { final char DELIM = ','; final String LINE_SEP = System.getProperty("line.separator"); // $NON-NLS-1$ final char SPECIALS[] = new char[] {DELIM, QUOTING_CHAR}; final int columns = model.getColumnCount(); final int rows = model.getRowCount(); for (int i=0; i < columns; i++){ if (i>0) { writer.write(DELIM); } writer.write(quoteDelimiters(model.getColumnName(i),SPECIALS)); } writer.write(LINE_SEP); for (int row=0; row < rows; row++) { for (int column=0; column < columns; column++) { if (column > 0) { writer.write(DELIM); } Object item = model.getValueAt(row, column); writer.write( quoteDelimiters(String.valueOf(item),SPECIALS)); } writer.write(LINE_SEP); } } /** * Convert a result into a string, where the fields of the result are * separated by the default delimiter. * * @param event * the sample event to be converted * @return the separated value representation of the result */ public static String resultToDelimitedString(SampleEvent event) { return resultToDelimitedString(event, event.getResult().getSaveConfig().getDelimiter()); } /** * Convert a result into a string, where the fields of the result are * separated by a specified String. * * @param event * the sample event to be converted * @param delimiter * the separation string * @return the separated value representation of the result */ public static String resultToDelimitedString(SampleEvent event, final String delimiter) { /* * Class to handle generating the delimited string. * - adds the delimiter if not the first call * - quotes any strings that require it */ final class StringQuoter{ final StringBuffer sb = new StringBuffer(); private final char[] specials; private boolean addDelim; public StringQuoter(char delim) { specials = new char[] {delim, QUOTING_CHAR, CharUtils.CR, CharUtils.LF}; addDelim=false; // Don't add delimiter first time round } private void addDelim(){ if (addDelim){ sb.append(specials[0]); } else { addDelim = true; } } // These methods handle parameters that could contain delimiters or quotes: public void append(String s){ addDelim(); //if (s == null) return; sb.append(quoteDelimiters(s,specials)); } public void append(Object obj){ append(String.valueOf(obj)); } // These methods handle parameters that cannot contain delimiters or quotes public void append(int i){ addDelim(); sb.append(i); } public void append(long l){ addDelim(); sb.append(l); } public void append(boolean b){ addDelim(); sb.append(b); } public String toString(){ return sb.toString(); } } StringQuoter text = new StringQuoter(delimiter.charAt(0)); SampleResult sample = event.getResult(); SampleSaveConfiguration saveConfig = sample.getSaveConfig(); if (saveConfig.saveTimestamp()) { if (saveConfig.printMilliseconds()){ text.append(sample.getTimeStamp()); } else if (saveConfig.formatter() != null) { String stamp = saveConfig.formatter().format(new Date(sample.getTimeStamp())); text.append(stamp); } } if (saveConfig.saveTime()) { text.append(sample.getTime()); } if (saveConfig.saveLabel()) { text.append(sample.getSampleLabel()); } if (saveConfig.saveCode()) { text.append(sample.getResponseCode()); } if (saveConfig.saveMessage()) { text.append(sample.getResponseMessage()); } if (saveConfig.saveThreadName()) { text.append(sample.getThreadName()); } if (saveConfig.saveDataType()) { text.append(sample.getDataType()); } if (saveConfig.saveSuccess()) { text.append(sample.isSuccessful()); } if (saveConfig.saveAssertionResultsFailureMessage()) { String message = null; AssertionResult[] results = sample.getAssertionResults(); if (results != null) { // Find the first non-null message for (int i = 0; i < results.length; i++){ message = results[i].getFailureMessage(); if (message != null) { break; } } } if (message != null) { text.append(message); } else { text.append(""); // Need to append something so delimiter is added } } if (saveConfig.saveBytes()) { text.append(sample.getBytes()); } if (saveConfig.saveThreadCounts()) { text.append(sample.getGroupThreads()); text.append(sample.getAllThreads()); } if (saveConfig.saveUrl()) { text.append(sample.getURL()); } if (saveConfig.saveFileName()) { text.append(sample.getResultFileName()); } if (saveConfig.saveLatency()) { text.append(sample.getLatency()); } if (saveConfig.saveEncoding()) { text.append(sample.getDataEncodingWithDefault()); } if (saveConfig.saveSampleCount()) {// Need both sample and error count to be any use text.append(sample.getSampleCount()); text.append(sample.getErrorCount()); } if (saveConfig.saveHostname()) { text.append(event.getHostname()); } for (int i=0; i < SampleEvent.getVarCount(); i++){ text.append(event.getVarValue(i)); } return text.toString(); } // =================================== CSV quote/unquote handling ============================== /* * Private versions of what might eventually be part of Commons-CSV or Commons-Lang/Io... */ /* * <p> * Returns a <code>String</code> value for a character-delimited column value * enclosed in the quote character, if required. * </p> * * <p> * If the value contains a special character, * then the String value is returned enclosed in the quote character. * </p> * * <p> * Any quote characters in the value are doubled up. * </p> * * <p> * If the value does not contain any special characters, * then the String value is returned unchanged. * </p> * * <p> * N.B. The list of special characters includes the quote character. * </p> * * @param input the input column String, may be null (without enclosing delimiters) * @param specialChars special characters; second one must be the quote character * @return the input String, enclosed in quote characters if the value contains a special character, * <code>null</code> for null string input */ private static String quoteDelimiters(String input, char[] specialChars) { if (StringUtils.containsNone(input, specialChars)) { return input; } StringBuffer buffer = new StringBuffer(input.length() + 10); final char quote = specialChars[1]; buffer.append(quote); for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (c == quote) { buffer.append(quote); // double the quote char } buffer.append(c); } buffer.append(quote); return buffer.toString(); } // State of the parser private static final int INITIAL=0, PLAIN = 1, QUOTED = 2, EMBEDDEDQUOTE = 3; public static final char QUOTING_CHAR = '"'; /** * Reads from file and splits input into strings according to the delimiter, * taking note of quoted strings. * * Handles DOS (CRLF), Unix (LF), and Mac (CR) line-endings equally. * * @param infile input file - must support mark(1) * @param delim delimiter (e.g. comma) * @return array of strings * @throws IOException also for unexpected quote characters */ public static String[] csvReadFile(BufferedReader infile, char delim) throws IOException { int ch; int state = INITIAL; List list = new ArrayList(); ByteArrayOutputStream baos = new ByteArrayOutputStream(200); while(-1 != (ch=infile.read())){ boolean push = false; switch(state){ case INITIAL: if (ch == QUOTING_CHAR){ state = QUOTED; } else if (isDelimOrEOL(delim, ch)) { push = true; } else { baos.write(ch); state = PLAIN; } break; case PLAIN: if (ch == QUOTING_CHAR){ baos.write(ch); throw new IOException("Cannot have quote-char in plain field:["+baos.toString()+"]"); } else if (isDelimOrEOL(delim, ch)) { push = true; state = INITIAL; } else { baos.write(ch); } break; case QUOTED: if (ch == QUOTING_CHAR){ state=EMBEDDEDQUOTE; } else { baos.write(ch); } break; case EMBEDDEDQUOTE: if (ch == QUOTING_CHAR){ baos.write(QUOTING_CHAR); // doubled quote => quote state = QUOTED; } else if (isDelimOrEOL(delim, ch)) { push = true; state = INITIAL; } else { baos.write(QUOTING_CHAR); throw new IOException("Cannot have single quote-char in quoted field:["+baos.toString()+"]"); } break; } if (push) { if (ch == '\r') {// Remove following \n if present infile.mark(1); if (infile.read() != '\n'){ infile.reset(); // did not find \n, put the character back } } String s = baos.toString(); list.add(s); baos.reset(); } if ((ch == '\n' || ch == '\r') && state != QUOTED) { break; } } if (ch == -1 && baos.size() > 0){ list.add(baos.toString()); } return (String[]) list.toArray(new String[]{}); } private static boolean isDelimOrEOL(char delim, int ch) { return ch == delim || ch == '\n' || ch == '\r'; } }

The table below shows all metrics for CSVSaveService.java.

MetricValueDescription
BLOCKS150.00Number of blocks
BLOCK_COMMENT58.00Number of block comment lines
COMMENTS205.00Comment lines
COMMENT_DENSITY 0.38Comment density
COMPARISONS119.00Number of comparison operators
CYCLOMATIC146.00Cyclomatic complexity
DECL_COMMENTS29.00Comments in declarations
DOC_COMMENT114.00Number of javadoc comment lines
ELOC543.00Effective lines of code
EXEC_COMMENTS16.00Comments in executable code
EXITS141.00Procedure exits
FUNCTIONS25.00Number of function declarations
HALSTEAD_DIFFICULTY97.95Halstead difficulty
HALSTEAD_EFFORT 0.00Halstead effort
INTERFACE_COMPLEXITY94.00Interface complexity
JAVA0001 0.00JAVA0001 Package name does not contain only lower case letters
JAVA0002 0.00JAVA0002 Package name does not begin with a top level domain name or country code
JAVA0003 0.00JAVA0003 Minimize use of on-demand (.*) imports
JAVA0004 0.00JAVA0004 Unnecessary import from java.lang
JAVA0005 0.00JAVA0005 Imports not in specified order
JAVA0006 0.00JAVA0006 Empty finally block
JAVA0007 0.00JAVA0007 Should not declare public field
JAVA0008 0.00JAVA0008 Empty catch block
JAVA0009 0.00JAVA0009 Protected member in final class
JAVA0010 0.00JAVA0010 Non-instantiable class does not contain a non-private static member
JAVA0011 0.00JAVA0011 Abstract class does not contain an abstract method
JAVA0012 0.00JAVA0012 Non-constructor method with same name as declaring class
JAVA0013 0.00JAVA0013 Non-blank final field is not static
JAVA0014 0.00JAVA0014 Class with only static members has non-private constructor
JAVA0015 0.00JAVA0015 Package class contains public nested type
JAVA0016 0.00JAVA0016 Abstract class contains public constructor
JAVA0017 0.00JAVA0017 Class name does not have required form
JAVA0018 0.00JAVA0018 Method name does not have required form
JAVA0019 0.00JAVA0019 Interface name does not have required form
JAVA0020 0.00JAVA0020 Field name does not have required form
JAVA0021 0.00JAVA0021 Interface method name does not have required form
JAVA0022 1.00JAVA0022 Static final field name does not have required form
JAVA0023 0.00JAVA0023 Empty finalize method
JAVA0024 0.00JAVA0024 Empty class
JAVA0025 0.00JAVA0025 Method override is empty
JAVA0026 0.00JAVA0026 Finalize method with parameters
JAVA0029 0.00JAVA0029 Private method not used
JAVA0030 0.00JAVA0030 Private field not used
JAVA0031 0.00JAVA0031 Case statement not properly closed
JAVA0032 1.00JAVA0032 Switch statement missing default
JAVA0033 0.00JAVA0033 default: not last case in switch statement
JAVA0034 0.00JAVA0034 Missing braces in if statement
JAVA0035 0.00JAVA0035 Missing braces in for statement
JAVA0036 0.00JAVA0036 Missing braces in while statement
JAVA0038 0.00JAVA0038 Non-case label in switch statement
JAVA0039 0.00JAVA0039 Break statement with label
JAVA0040 0.00JAVA0040 Switch statement contains N cases (maximum: M)
JAVA0041 0.00JAVA0041 Nested synchronized block
JAVA0042 0.00JAVA0042 Empty synchronized statement
JAVA0043 0.00JAVA0043 Inner class does not use outer class
JAVA0044 0.00JAVA0044 Serializable class with no instance variables
JAVA0045 0.00JAVA0045 Serializable class with only transient fields
JAVA0046 0.00JAVA0046 Name of class not derived from Exception ends with 'Exception'
JAVA0047 0.00JAVA0047 Serializable class derives from invalid base class
JAVA0048 0.00JAVA0048 Name of class derived from Exception does not end with 'Exception'
JAVA0049 0.00JAVA0049 Nested block at depth N (maximum: M)
JAVA0050 0.00JAVA0050 Class derives from java.lang.Error
JAVA0051 0.00JAVA0051 Class derives from java.lang.RuntimeException
JAVA0052 0.00JAVA0052 Class derives from java.lang.Throwable
JAVA0053 0.00JAVA0053 Unused label
JAVA0054 0.00JAVA0054 Inheritance depth N exceeds maximum M
JAVA0055 0.00JAVA0055 Class should be interface
JAVA0056 0.00JAVA0056 Unnecessary abstract modifier for interface or annotation
JAVA0057 0.00JAVA0057 Unnecessary default constructor
JAVA0058 0.00JAVA0058 Constructor calls super()
JAVA0059 0.00JAVA0059 Method override only calls super()
JAVA0061 0.00JAVA0061 Inaccessible member in anonymous class
JAVA0062 0.00JAVA0062 Public class missing public member or protected constructor
JAVA0063 0.00JAVA0063 Identifier name should not contain '$'
JAVA0064 2.00JAVA0064 N variations of identifier name (maximum: M)
JAVA0065 0.00JAVA0065 Unnecessary final modifier for method in final class
JAVA0066 0.00JAVA0066 Unnecessary modifier for interface nested type
JAVA0067 4.00JAVA0067 Array descriptor on identifier name
JAVA0068 1.00JAVA0068 Modifiers not declared in recommended order
JAVA0071 0.00JAVA0071 Strings compared with ==
JAVA0073 0.00JAVA0073 Integer division in floating-point context
JAVA0074 0.00JAVA0074 Use of Object.notify()
JAVA0075 0.00JAVA0075 Method parameter hides field
JAVA0076 0.00JAVA0076 Use of magic number
JAVA0077 0.00JAVA0077 Private field not used in declaring class
JAVA0078 0.00JAVA0078 Floating point values compared with ==
JAVA0079 0.00JAVA0079 Use of instance to reference static member
JAVA0080 0.00JAVA0080 Import declaration not used
JAVA0081 0.00JAVA0081 Boolean literal in comparison
JAVA0082 0.00JAVA0082 Unnecessary widening cast
JAVA0083 0.00JAVA0083 Unnecessary instanceof test
JAVA0084 0.00JAVA0084 Should use compound assignment operator
JAVA0085 0.00JAVA0085 Use of sun.* class
JAVA0087 0.00JAVA0087 Use of Thread.sleep()
JAVA0089 0.00JAVA0089 Use of restricted package
JAVA0092 0.00JAVA0092 Use of restricted type
JAVA0093 0.00JAVA0093 Redundant assignment
JAVA0094 0.00JAVA0094 Field hides a superclass field
JAVA0095 0.00JAVA0095 Uninitialized private field
JAVA0096 0.00JAVA0096 Field in nested class hides outer field
JAVA0098 0.00JAVA0098 Minimize use of implicit field initializers
JAVA0100 0.00JAVA0100 Class contains N non-final fields (maximum: M)
JAVA0101 0.00JAVA0101 Unnecessary modifier for field in interface
JAVA0102 0.00JAVA0102 Last statement in finalize() not super.finalize()
JAVA0103 0.00JAVA0103 Explicit call to finalize()
JAVA0104 0.00JAVA0104 finalize() only calls super.finalize()
JAVA0105 0.00JAVA0105 Duplicate import declaration
JAVA0106 0.00JAVA0106 Unnecessary import from current package
JAVA0108 1.00JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0109 0.00JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA0110 0.00JAVA0110 Incorrect javadoc: no @return tag
JAVA0111 0.00JAVA0111 Incorrect javadoc: @return tag for void method
JAVA0112 0.00JAVA0112 Incorrect javadoc: no exception 'exception' in throws
JAVA0113 1.00JAVA0113 Incorrect javadoc: no @author tag
JAVA0114 1.00JAVA0114 Incorrect javadoc: no @version tag
JAVA0115 0.00JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0116 1.00JAVA0116 Missing javadoc: field 'field'
JAVA0117 6.00JAVA0117 Missing javadoc: method 'method'
JAVA0118 0.00JAVA0118 Missing javadoc: type 'type'
JAVA0119 0.00JAVA0119 Control variable changed within body of for loop
JAVA0123 0.00JAVA0123 Use all three components of for loop
JAVA0125 0.00JAVA0125 Continue statement with label
JAVA0126 0.00JAVA0126 Method declares unchecked exception in throws
JAVA0128 1.00JAVA0128 Public constructor in non-public class
JAVA0130 0.00JAVA0130 Non-static method does not use instance fields
JAVA0131 0.00JAVA0131 Compatible method does not override base
JAVA0132 4.00JAVA0132 Method overload with compatible signature
JAVA0133 0.00JAVA0133 Non-synchronized method overrides synchronized method
JAVA0135 0.00JAVA0135 Only one of Object.equals and Object.hashCode defined: missing 'method'
JAVA0136 0.00JAVA0136 N methods defined in class (maximum: M)
JAVA0137 0.00JAVA0137 Non-abstract class missing constructor
JAVA0138 0.00JAVA0138 N parameters defined for method (maximum: M)
JAVA0139 0.00JAVA0139 Definition of main other than public static void main(java.lang.String[])
JAVA0141 0.00JAVA0141 Unnecessary modifier for method in interface
JAVA0143 0.00JAVA0143 Synchronized method
JAVA0144 1.00JAVA0144 Line exceeds maximum M characters
JAVA0145 0.00JAVA0145 Tab character used in source file
JAVA0150 4.00JAVA0150 java.lang.Error (or subclass) thrown
JAVA0153 0.00JAVA0153 Inefficient conversion of integer to string
JAVA0159 0.00JAVA0159 Inefficient conversion of string to integer
JAVA0160 0.00JAVA0160 Method does not throw specified exception
JAVA0161 0.00JAVA0161 Conditional wait() not in loop
JAVA0163 0.00JAVA0163 Empty statement
JAVA0165 0.00JAVA0165 Conflicting return statement in finally block
JAVA0166 0.00JAVA0166 Generic exception caught
JAVA0167 0.00JAVA0167 ThreadDeath not rethrown
JAVA0169 0.00JAVA0169 Unnecessary catch block: exception 'exception'
JAVA0170 0.00JAVA0170 Caught exception not derived from java.lang.Exception
JAVA0171 0.00JAVA0171 Unused local variable
JAVA0173 0.00JAVA0173 Unused method parameter
JAVA0174 0.00JAVA0174 Assigned local variable never used
JAVA0175 0.00JAVA0175 Successive assignment to variable
JAVA0176 0.00JAVA0176 Local variable name does not have required form
JAVA0177 2.00JAVA0177 Variable declaration missing initializer
JAVA0179 0.00JAVA0179 Local variable hides visible field
JAVA0233 0.00JAVA0233 Definition of serialVersionUID other than 'private static final long serialVersionUID'
JAVA0234 0.00JAVA0234 Class is Serializable but does not define serialVersionUID
JAVA0235 0.00JAVA0235 Class defines serialVersionUID but does not implement Serializable
JAVA0236 0.00JAVA0236 Attempt to clone an object which does not implement Cloneable
JAVA0237 0.00JAVA0237 Class implements Cloneable but does not have public clone method
JAVA0238 0.00JAVA0238 Clone method does not call super.clone()
JAVA0239 0.00JAVA0239 Class declares 'readObject' or 'writeObject' but does not implement Serializable
JAVA0240 0.00JAVA0240 Serializable class which declares readObject or writeObject but not both
JAVA0241 0.00JAVA0241 'readObject' or 'writeObject' should be declared private in Serializable class
JAVA0242 0.00JAVA0242 Transient field in non-Serializable class
JAVA0243 0.00JAVA0243 'readResolve' or 'writeReplace' should be declared private or protected
JAVA0244 0.00JAVA0244 Field or method name in subclass differs only by case from inherited field or method
JAVA0245 0.00JAVA0245 JUnit TestCase with non-trivial constructor
JAVA0246 0.00JAVA0246 JUnit assertXXX statement missing message parameter
JAVA0247 0.00JAVA0247 JUnit 'setUp()' and 'tearDown()' should call super method
JAVA0248 0.00JAVA0248 JUnit method 'setUp' or 'tearDown' with incorrect signature
JAVA0249 0.00JAVA0249 JUnit TestCase 'suite()' should be declared static
JAVA0250 0.00JAVA0250 JUnit TestCase declares testXXX method with incorrect signature
JAVA0251 0.00JAVA0251 Use '%n' for line breaks in printf/format for platform independence
JAVA0252 0.00JAVA0252 'enum' is a Java 1.5 reserved word
JAVA0253 0.00JAVA0253 Not all enum constants consumed in switch statement
JAVA0254 0.00JAVA0254 Use enhanced for loop construct instead of Iterator
JAVA0255 0.00JAVA0255 Result of method invocation not used
JAVA0256 0.00JAVA0256 Assignment of external collection/array to field
JAVA0257 0.00JAVA0257 Use of 'Constant Interface' anti-pattern
JAVA0258 0.00JAVA0258 Implement Iterable for foreach compatibility
JAVA0259 0.00JAVA0259 Return of collection/array field
JAVA0260 0.00JAVA0260 Use 'enum' instead of Enumerated Type pattern
JAVA0261 0.00JAVA0261 Use specialized Enum collection types
JAVA0262 0.00JAVA0262 Use of char in integer context
JAVA0263 0.00JAVA0263 Long literal ends with 'l' instead of 'L'
JAVA0264 0.00JAVA0264 Integer math in long context - check for overflow
JAVA0265 0.00JAVA0265 Use of Throwable.printStackTrace()
JAVA0266 0.00JAVA0266 Use of System.out
JAVA0267 0.00JAVA0267 Use of System.err
JAVA0269 0.00JAVA0269 Contents of StringBuffer never used
JAVA0270 2.00JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
JAVA0271 0.00JAVA0271 Minimize use of on-demand (.*) static imports
JAVA0272 0.00JAVA0272 Thread.run() called
JAVA0273 0.00JAVA0273 Non-final derivative of Thread calls start() in constructor
JAVA0274 0.00JAVA0274 Serializable class has a synchronized readObject()
JAVA0275 0.00JAVA0275 Serializable class has a synchronized writeObject() and no other synchronized methods
JAVA0276 0.00JAVA0276 Unnecessary use of String constructor
JAVA0277 0.00JAVA0277 Iterator.next() implementation does not throw NoSuchElementException
JAVA0278 0.00JAVA0278 Unnecessary use of Boolean constructor
JAVA0279 0.00JAVA0279 Serialization method readObject or readObjectNoData calls an overridable method
JAVA0280 0.00JAVA0280 IllegalMonitorStateException caught
JAVA0281 0.00JAVA0281 Iterator.next() not called in loop
JAVA0282 0.00JAVA0282 Call to Iterator.next() in loop which does not test Iterator.hasNext()
JAVA0283 0.00JAVA0283 Control variable not updated in loop body
JAVA0284 0.00JAVA0284 Explicit garbage collection
JAVA0285 0.00JAVA0285 Dereference of potentially null variable
JAVA0286 0.00JAVA0286 Dereference of null variable
JAVA0287 0.00JAVA0287 Unnecessary null check
JAVA0288 0.00JAVA0288 Inconsistent null check
LINES989.00Number of lines in the source file
LINE_COMMENT33.00Number of line comments
LOC676.00Lines of code
LOGICAL_LINES399.00Number of statements
LOOPS14.00Number of loops
NEST_DEPTH 5.00Maximum nesting depth
OPERANDS1684.00Number of operands
OPERATORS3148.00Number of operators
PARAMS37.00Number of formal parameter declarations
PROGRAM_LENGTH4832.00Halstead program length
PROGRAM_VOCAB499.00Halstead program vocabulary
PROGRAM_VOLUME 0.00Halstead program volume
RETURNS57.00Number of return points from functions
SIZE36822.00Size of the file in bytes
UNIQUE_OPERANDS447.00Number of unique operands
UNIQUE_OPERATORS52.00Number of unique operators
WHITESPACE108.00Number of whitespace lines