Advertisement
mnaufaldillah

CSVRead Jmeter

Oct 23rd, 2021
686
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.01 KB | None | 0 0
  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to you under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  * http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17.  
  18. package org.apache.jmeter.functions;
  19.  
  20. import java.util.ArrayList;
  21. import java.util.Collection;
  22. import java.util.List;
  23.  
  24. import org.apache.jmeter.engine.util.CompoundVariable;
  25. import org.apache.jmeter.samplers.SampleResult;
  26. import org.apache.jmeter.samplers.Sampler;
  27. import org.apache.jmeter.util.JMeterUtils;
  28. import org.slf4j.Logger;
  29. import org.slf4j.LoggerFactory;
  30.  
  31. /**
  32.  * The function represented by this class allows data to be read from CSV files.
  33.  * Syntax is similar to StringFromFile function. The function allows the test to
  34.  * line-thru the data in the CSV file - one line per each test. E.g. inserting
  35.  * the following in the test scripts :
  36.  *
  37.  * <pre>{@code
  38.  * ${__CSVRead(c:/BOF/abcd.csv,0)} // read (first) line of 'c:/BOF/abcd.csv'
  39.  *     // and return the 1st column (represented by the '0')
  40.  * ${__CSVRead(c:/BOF/abcd.csv,1)} // read (first) line of 'c:/BOF/abcd.csv'
  41.  *     // and return the 2nd column (represented by the '1')
  42.  * ${__CSVRead(c:/BOF/abcd.csv,next())} // Go to next line of 'c:/BOF/abcd.csv'
  43.  * }</pre>
  44.  * NOTE: A single instance of each different file is opened and used for all
  45.  * threads.
  46.  *<p>
  47.  * To open the same file twice, use the alias function: <br>
  48.  * <pre>
  49.  * {@code __CSVRead(abc.csv,*ONE);
  50.  * __CSVRead(abc.csv,*TWO);}
  51.  * </pre>
  52.  * and later use the references to read from the files: <br>
  53.  * {@code __CSVRead(*ONE,1);}, etc.
  54.  * @since 1.9
  55.  */
  56. public class CSVRead extends AbstractFunction {
  57.     private static final Logger log = LoggerFactory.getLogger(CSVRead.class);
  58.  
  59.     private static final String KEY = "__CSVRead"; // Function name //$NON-NLS-1$
  60.  
  61.     private static final List<String> desc = new ArrayList<>();
  62.  
  63.     private Object[] values; // Parameter list
  64.  
  65.     static {
  66.         desc.add(JMeterUtils.getResString("csvread_file_file_name")); //$NON-NLS-1$
  67.         desc.add(JMeterUtils.getResString("column_number")); //$NON-NLS-1$
  68.     }
  69.  
  70.     public CSVRead() {
  71.     }
  72.  
  73.     /** {@inheritDoc} */
  74.     @Override
  75.     public String execute(SampleResult previousResult, Sampler currentSampler)
  76.             throws InvalidVariableException {
  77.         String myValue = ""; //$NON-NLS-1$
  78.  
  79.         String fileName = ((org.apache.jmeter.engine.util.CompoundVariable) values[0]).execute();
  80.         String columnOrNext = ((org.apache.jmeter.engine.util.CompoundVariable) values[1]).execute();
  81.  
  82.         log.debug("execute ({}, {})   ", fileName, columnOrNext);
  83.  
  84.         // Process __CSVRead(filename,*ALIAS)
  85.         if (columnOrNext.startsWith("*")) { //$NON-NLS-1$
  86.             FileWrapper.open(fileName, columnOrNext);
  87.             /*
  88.              * All done, so return
  89.              */
  90.             return ""; //$NON-NLS-1$
  91.         }
  92.  
  93.         // if argument is 'next' - go to the next line
  94.         if (columnOrNext.equals("next()") || columnOrNext.equals("next")) { //$NON-NLS-1$ //$NON-NLS-2$
  95.             FileWrapper.endRow(fileName);
  96.  
  97.             /*
  98.              * All done now, so return the empty string - this allows the caller
  99.              * to append __CSVRead(file,next) to the last instance of
  100.              * __CSVRead(file,col)
  101.              *
  102.              * N.B. It is important not to read any further lines at this point,
  103.              * otherwise the wrong line can be retrieved when using multiple
  104.              * threads.
  105.              */
  106.             return ""; //$NON-NLS-1$
  107.         }
  108.  
  109.         try {
  110.             int columnIndex = Integer.parseInt(columnOrNext); // what column
  111.                                                                 // is wanted?
  112.             myValue = FileWrapper.getColumn(fileName, columnIndex);
  113.         } catch (NumberFormatException e) {
  114.             log.warn("{} - can't parse column number: {} {}",
  115.                     Thread.currentThread().getName(), columnOrNext,
  116.                     e.toString());
  117.         } catch (IndexOutOfBoundsException e) {
  118.             log.warn("{} - invalid column number: {} at row {} {}",
  119.                     Thread.currentThread().getName(), columnOrNext,
  120.                     FileWrapper.getCurrentRow(fileName), e.toString());
  121.         }
  122.  
  123.         log.debug("execute value: {}", myValue);
  124.  
  125.         return myValue;
  126.     }
  127.  
  128.     /** {@inheritDoc} */
  129.     @Override
  130.     public List<String> getArgumentDesc() {
  131.         return desc;
  132.     }
  133.  
  134.     /** {@inheritDoc} */
  135.     @Override
  136.     public String getReferenceKey() {
  137.         return KEY;
  138.     }
  139.  
  140.     /** {@inheritDoc} */
  141.     @Override
  142.     public void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException {
  143.         if (log.isDebugEnabled()) {
  144.             log.debug("setParameter - Collection.size={}", parameters.size());
  145.         }
  146.  
  147.         values = parameters.toArray();
  148.  
  149.         if (log.isDebugEnabled()) {
  150.             for (int i = 0; i < parameters.size(); i++) {
  151.                 log.debug("i: {}", ((CompoundVariable) values[i]).execute());
  152.             }
  153.         }
  154.  
  155.         checkParameterCount(parameters, 2);
  156.  
  157.         /*
  158.          * Need to reset the containers for repeated runs; about the only way
  159.          * for functions to detect that a run is starting seems to be the
  160.          * setParameters() call.
  161.          */
  162.         FileWrapper.clearAll();// TODO only clear the relevant entry - if possible...
  163.  
  164.     }
  165. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement