Advertisement
mnaufaldillah

Converter Jmeter

Oct 23rd, 2021
726
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 18.79 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.jorphan.util;
  19.  
  20. import java.io.File;
  21. import java.text.DateFormat;
  22. import java.text.ParseException;
  23. import java.text.SimpleDateFormat;
  24. import java.util.Calendar;
  25. import java.util.Date;
  26. import java.util.GregorianCalendar;
  27. import java.util.Optional;
  28. import java.util.StringTokenizer;
  29. import java.util.stream.Stream;
  30.  
  31. /**
  32.  * Converter utilities for TestBeans
  33.  */
  34. public class Converter {
  35.  
  36.     /**
  37.      * Convert the given value object to an object of the given type
  38.      *
  39.      * @param value  object to convert
  40.      * @param toType type to convert object to
  41.      * @return converted object or original value if no conversion could be applied
  42.      */
  43.     public static Object convert(Object value, Class<?> toType) {
  44.         Object convertedValue = value;
  45.         if (value == null || toType == null) {
  46.             convertedValue = ""; // TODO should we allow null for non-primitive types?
  47.         } else if (toType.isAssignableFrom(value.getClass())) {
  48.             convertedValue = value;
  49.         } else if (toType.equals(float.class) || toType.equals(Float.class)) {
  50.             convertedValue = getFloat(value);
  51.         } else if (toType.equals(double.class) || toType.equals(Double.class)) {
  52.             convertedValue = getDouble(value);
  53.         } else if (toType.equals(String.class)) {
  54.             convertedValue = getString(value);
  55.         } else if (toType.equals(int.class) || toType.equals(Integer.class)) {
  56.             convertedValue = getInt(value);
  57.         } else if (toType.equals(char.class) || toType.equals(Character.class)) {
  58.             convertedValue = getChar(value);
  59.         } else if (toType.equals(long.class) || toType.equals(Long.class)) {
  60.             convertedValue = getLong(value);
  61.         } else if (toType.equals(boolean.class) || toType.equals(Boolean.class)) {
  62.             convertedValue = getBoolean(value);
  63.         } else if (toType.equals(java.util.Date.class)) {
  64.             convertedValue = getDate(value);
  65.         } else if (toType.equals(Calendar.class)) {
  66.             convertedValue = getCalendar(value);
  67.         } else if (toType.equals(File.class)) {
  68.             convertedValue = getFile(value);
  69.         } else if (toType.equals(Class.class)) {
  70.             try {
  71.                 convertedValue = Class.forName(value.toString());
  72.             } catch (Exception ignored) {
  73.                 // Intentionally left blank
  74.             }
  75.         }
  76.         return convertedValue;
  77.     }
  78.  
  79.     /**
  80.      * Converts the given object to a calendar object. Defaults to the
  81.      * <code>defaultValue</code> if the given object can't be converted.
  82.      *
  83.      * @param date
  84.      *            object that should be converted to a {@link Calendar}
  85.      * @param defaultValue
  86.      *            default value that will be returned if <code>date</code> can
  87.      *            not be converted
  88.      * @return {@link Calendar} representing the given <code>date</code> or
  89.      *         <code>defaultValue</code> if conversion failed
  90.      */
  91.     public static Calendar getCalendar(Object date, Calendar defaultValue) {
  92.         Calendar cal = new GregorianCalendar();
  93.         if (date instanceof java.util.Date) {
  94.             cal.setTime((java.util.Date) date);
  95.             return cal;
  96.         } else if (date != null) {
  97.             Optional<Date> d = tryToParseDate(date);
  98.             if (!d.isPresent()) {
  99.                 return defaultValue;
  100.             }
  101.             cal.setTime(d.get());
  102.         } else {
  103.             cal = defaultValue;
  104.         }
  105.         return cal;
  106.     }
  107.  
  108.     /**
  109.      * Converts the given object to a calendar object. Defaults to a calendar
  110.      * using the current time if the given object can't be converted.
  111.      *
  112.      * @param o
  113.      *            object that should be converted to a {@link Calendar}
  114.      * @return {@link Calendar} representing the given <code>o</code> or a new
  115.      *         {@link GregorianCalendar} using the current time if conversion
  116.      *         failed
  117.      */
  118.     public static Calendar getCalendar(Object o) {
  119.         return getCalendar(o, new GregorianCalendar());
  120.     }
  121.  
  122.     /**
  123.      * Converts the given object to a {@link Date} object. Defaults to the
  124.      * current time if the given object can't be converted.
  125.      *
  126.      * @param date
  127.      *            object that should be converted to a {@link Date}
  128.      * @return {@link Date} representing the given <code>date</code> or
  129.      *         the current time if conversion failed
  130.      */
  131.     public static Date getDate(Object date) {
  132.         return getDate(date, Calendar.getInstance().getTime());
  133.     }
  134.  
  135.     /**
  136.      * Converts the given object to a {@link Date} object. Defaults to the
  137.      * <code>defaultValue</code> if the given object can't be converted.
  138.      *
  139.      * @param date
  140.      *            object that should be converted to a {@link Date}
  141.      * @param defaultValue
  142.      *            default value that will be returned if <code>date</code> can
  143.      *            not be converted
  144.      * @return {@link Date} representing the given <code>date</code> or
  145.      *         <code>defaultValue</code> if conversion failed
  146.      */
  147.     public static Date getDate(Object date, Date defaultValue) {
  148.         if (date instanceof java.util.Date) {
  149.             return (Date) date;
  150.         } else if (date != null) {
  151.             return tryToParseDate(date).orElse(defaultValue);
  152.         } else {
  153.             return defaultValue;
  154.         }
  155.     }
  156.  
  157.     private static Optional<Date> tryToParseDate(Object date) {
  158.         return Stream.of(DateFormat.SHORT, DateFormat.MEDIUM, DateFormat.LONG, DateFormat.FULL)
  159.                 .map(DateFormat::getDateInstance)
  160.                 .map(formatter -> tryToParseDate(formatter, date.toString()))
  161.                 .filter(Optional::isPresent)
  162.                 .map(Optional::get)
  163.                 .findFirst();
  164.     }
  165.  
  166.     private static Optional<Date> tryToParseDate(DateFormat formatter, String dateString) {
  167.         try {
  168.             return Optional.of(formatter.parse(dateString));
  169.         } catch (ParseException e) {
  170.             return Optional.empty();
  171.         }
  172.     }
  173.  
  174.     /**
  175.      * Convert object to float, or <code>defaultValue</code> if conversion failed
  176.      *
  177.      * @param o object to convert
  178.      * @param defaultValue default value to use, when conversion failed
  179.      * @return converted float or <code>defaultValue</code> if conversion failed
  180.      */
  181.     public static float getFloat(Object o, float defaultValue) {
  182.         if (o == null) {
  183.             return defaultValue;
  184.         }
  185.         if (o instanceof Number) {
  186.             return ((Number) o).floatValue();
  187.         }
  188.         try {
  189.             return Float.parseFloat(o.toString());
  190.         } catch (NumberFormatException e) {
  191.             return defaultValue;
  192.         }
  193.     }
  194.  
  195.     /**
  196.      * Convert object to float, or <code>0</code> if conversion
  197.      * failed
  198.      *
  199.      * @param o
  200.      *            object to convert
  201.      * @return converted float or <code>0</code> if conversion
  202.      *         failed
  203.      */
  204.     public static float getFloat(Object o) {
  205.         return getFloat(o, 0);
  206.     }
  207.  
  208.     /**
  209.      * Convert object to double, or <code>defaultValue</code> if conversion
  210.      * failed
  211.      *
  212.      * @param o
  213.      *            object to convert
  214.      * @param defaultValue
  215.      *            default value to use, when conversion failed
  216.      * @return converted double or <code>defaultValue</code> if conversion
  217.      *         failed
  218.      */
  219.     public static double getDouble(Object o, double defaultValue) {
  220.         try {
  221.             if (o == null) {
  222.                 return defaultValue;
  223.             }
  224.             if (o instanceof Number) {
  225.                 return ((Number) o).doubleValue();
  226.             }
  227.             return Double.parseDouble(o.toString());
  228.         } catch (NumberFormatException e) {
  229.             return defaultValue;
  230.         }
  231.     }
  232.  
  233.     /**
  234.      * Convert object to double, or <code>0</code> if conversion
  235.      * failed
  236.      *
  237.      * @param o
  238.      *            object to convert
  239.      * @return converted double or <code>0</code> if conversion
  240.      *         failed
  241.      */
  242.     public static double getDouble(Object o) {
  243.         return getDouble(o, 0);
  244.     }
  245.  
  246.     /**
  247.      * Convert object to boolean, or <code>false</code> if conversion
  248.      * failed
  249.      *
  250.      * @param o
  251.      *            object to convert
  252.      * @return converted boolean or <code>false</code> if conversion
  253.      *         failed
  254.      */
  255.     public static boolean getBoolean(Object o) {
  256.         return getBoolean(o, false);
  257.     }
  258.  
  259.     /**
  260.      * Convert object to boolean, or <code>defaultValue</code> if conversion
  261.      * failed
  262.      *
  263.      * @param o
  264.      *            object to convert
  265.      * @param defaultValue
  266.      *            default value to use, when conversion failed
  267.      * @return converted boolean or <code>defaultValue</code> if conversion
  268.      *         failed
  269.      */
  270.     public static boolean getBoolean(Object o, boolean defaultValue) {
  271.         if (o == null) {
  272.             return defaultValue;
  273.         } else if (o instanceof Boolean) {
  274.             return (Boolean) o;
  275.         }
  276.         return Boolean.parseBoolean(o.toString());
  277.     }
  278.  
  279.     /**
  280.      * Convert object to integer, return <code>defaultValue</code> if object is not
  281.      * convertible or is <code>null</code>.
  282.      *
  283.      * @param o
  284.      *            object to convert
  285.      * @param defaultValue
  286.      *            default value to be used when no conversion can be done
  287.      * @return converted int or default value if conversion failed
  288.      */
  289.     public static int getInt(Object o, int defaultValue) {
  290.         try {
  291.             if (o == null) {
  292.                 return defaultValue;
  293.             }
  294.             if (o instanceof Number) {
  295.                 return ((Number) o).intValue();
  296.             }
  297.             return Integer.parseInt(o.toString());
  298.         } catch (NumberFormatException e) {
  299.             return defaultValue;
  300.         }
  301.     }
  302.  
  303.     /**
  304.      * Convert object to char, or ' ' if no conversion can
  305.      * be applied
  306.      *
  307.      * @param o
  308.      *            object to convert
  309.      * @return converted char or ' ' if conversion failed
  310.      */
  311.     public static char getChar(Object o) {
  312.         return getChar(o, ' ');
  313.     }
  314.  
  315.     /**
  316.      * Convert object to char, or <code>defaultValue</code> if no conversion can
  317.      * be applied
  318.      *
  319.      * @param o
  320.      *            object to convert
  321.      * @param defaultValue
  322.      *            default value to use, when conversion failed
  323.      * @return converted char or <code>defaultValue</code> if conversion failed
  324.      */
  325.     public static char getChar(Object o, char defaultValue) {
  326.         try {
  327.             if (o == null) {
  328.                 return defaultValue;
  329.             }
  330.             if (o instanceof Character) {
  331.                 return (Character) o;
  332.             } else if (o instanceof Byte) {
  333.                 return (char) ((Byte) o).byteValue();
  334.             } else if (o instanceof Integer) {
  335.                 return (char) ((Integer) o).intValue();
  336.             } else {
  337.                 String s = o.toString();
  338.                 if (s.length() > 0) {
  339.                     return o.toString().charAt(0);
  340.                 }
  341.                 return defaultValue;
  342.             }
  343.         } catch (Exception e) {
  344.             return defaultValue;
  345.         }
  346.     }
  347.  
  348.     /**
  349.      * Converts object to an integer, defaults to <code>0</code> if object is
  350.      * not convertible or is <code>null</code>.
  351.      *
  352.      * @param o
  353.      *            object to convert
  354.      * @return converted int, or <code>0</code> if conversion failed
  355.      */
  356.     public static int getInt(Object o) {
  357.         return getInt(o, 0);
  358.     }
  359.  
  360.     /**
  361.      * Converts object to a long, return <code>defaultValue</code> if object is
  362.      * not convertible or is <code>null</code>.
  363.      *
  364.      * @param o
  365.      *            object to convert
  366.      * @param defaultValue
  367.      *            default value to use, when conversion failed
  368.      * @return converted long or <code>defaultValue</code> when conversion
  369.      *         failed
  370.      */
  371.     public static long getLong(Object o, long defaultValue) {
  372.         try {
  373.             if (o == null) {
  374.                 return defaultValue;
  375.             }
  376.             if (o instanceof Number) {
  377.                 return ((Number) o).longValue();
  378.             }
  379.             return Long.parseLong(o.toString());
  380.         } catch (NumberFormatException e) {
  381.             return defaultValue;
  382.         }
  383.     }
  384.  
  385.     /**
  386.      * Converts object to a long, defaults to <code>0</code> if object is not
  387.      * convertible or is <code>null</code>
  388.      *
  389.      * @param o
  390.      *            object to convert
  391.      * @return converted long or <code>0</code> if conversion failed
  392.      */
  393.     public static long getLong(Object o) {
  394.         return getLong(o, 0);
  395.     }
  396.  
  397.     /**
  398.      * Format a date using a given pattern
  399.      *
  400.      * @param date
  401.      *            date to format
  402.      * @param pattern
  403.      *            pattern to use for formatting
  404.      * @return formatted date, or empty string if date was <code>null</code>
  405.      * @throws IllegalArgumentException
  406.      *             when <code>pattern</code> is invalid
  407.      */
  408.     public static String formatDate(Date date, String pattern) {
  409.         if (date == null) {
  410.             return "";
  411.         }
  412.         SimpleDateFormat format = new SimpleDateFormat(pattern);
  413.         return format.format(date);
  414.     }
  415.  
  416.     /**
  417.      * Format a date using a given pattern
  418.      *
  419.      * @param date
  420.      *            date to format
  421.      * @param pattern
  422.      *            pattern to use for formatting
  423.      * @return formatted date, or empty string if date was <code>null</code>
  424.      * @throws IllegalArgumentException
  425.      *             when <code>pattern</code> is invalid
  426.      */
  427.     public static String formatDate(java.sql.Date date, String pattern) {
  428.         if (date == null) {
  429.             return "";
  430.         }
  431.         SimpleDateFormat format = new SimpleDateFormat(pattern);
  432.         return format.format(date);
  433.     }
  434.  
  435.     /**
  436.      * Format a date using a given pattern
  437.      *
  438.      * @param date
  439.      *            date to format
  440.      * @param pattern
  441.      *            pattern to use for formatting
  442.      * @return formatted date, or empty string if date was <code>null</code>
  443.      * @throws IllegalArgumentException
  444.      *             when <code>pattern</code> is invalid
  445.      */
  446.     public static String formatDate(String date, String pattern) {
  447.         return formatDate(getCalendar(date, null), pattern);
  448.     }
  449.  
  450.     /**
  451.      * Format a date using a given pattern
  452.      *
  453.      * @param date
  454.      *            date to format
  455.      * @param pattern
  456.      *            pattern to use for formatting
  457.      * @return formatted date, or empty string if date was <code>null</code>
  458.      * @throws IllegalArgumentException
  459.      *             when <code>pattern</code> is invalid
  460.      */
  461.     public static String formatDate(Calendar date, String pattern) {
  462.         return formatCalendar(date, pattern);
  463.     }
  464.  
  465.     /**
  466.      * Format a calendar using a given pattern
  467.      *
  468.      * @param date
  469.      *            calendar to format
  470.      * @param pattern
  471.      *            pattern to use for formatting
  472.      * @return formatted date, or empty string if date was <code>null</code>
  473.      * @throws IllegalArgumentException
  474.      *             when <code>pattern</code> is invalid
  475.      */
  476.     public static String formatCalendar(Calendar date, String pattern) {
  477.         if (date == null) {
  478.             return "";
  479.         }
  480.         SimpleDateFormat format = new SimpleDateFormat(pattern);
  481.         return format.format(date.getTime());
  482.     }
  483.  
  484.     /**
  485.      * Converts object to a String, return <code>defaultValue</code> if object
  486.      * is <code>null</code>.
  487.      *
  488.      * @param o
  489.      *            object to convert
  490.      * @param defaultValue
  491.      *            default value to use when conversion failed
  492.      * @return converted String or <code>defaultValue</code> when conversion
  493.      *         failed
  494.      */
  495.     public static String getString(Object o, String defaultValue) {
  496.         if (o == null) {
  497.             return defaultValue;
  498.         }
  499.         return o.toString();
  500.     }
  501.  
  502.     /**
  503.      * Replace newlines "\n" with <code>insertion</code>
  504.      *
  505.      * @param v
  506.      *            String in which the newlines should be replaced
  507.      * @param insertion
  508.      *            new string which should be used instead of "\n"
  509.      * @return new string with newlines replaced by <code>insertion</code>
  510.      */
  511.     public static String insertLineBreaks(String v, String insertion) {
  512.         if (v == null) {
  513.             return "";
  514.         }
  515.         StringBuilder replacement = new StringBuilder();
  516.         StringTokenizer tokens = new StringTokenizer(v, "\n", true);
  517.         while (tokens.hasMoreTokens()) {
  518.             String token = tokens.nextToken();
  519.             if (token.compareTo("\n") == 0) {
  520.                 replacement.append(insertion);
  521.             } else {
  522.                 replacement.append(token);
  523.             }
  524.         }
  525.         return replacement.toString();
  526.     }
  527.  
  528.     /**
  529.      * Converts object to a String, defaults to empty string if object is null.
  530.      *
  531.      * @param o
  532.      *            object to convert
  533.      * @return converted String or empty string when conversion failed
  534.      */
  535.     public static String getString(Object o) {
  536.         return getString(o, "");
  537.     }
  538.  
  539.     /**
  540.      * Converts an object to a {@link File}
  541.      *
  542.      * @param o
  543.      *            object to convert (must be a {@link String} or a {@link File})
  544.      * @return converted file
  545.      * @throws IllegalArgumentException
  546.      *             when object can not be converted
  547.      */
  548.     public static File getFile(Object o){
  549.         if (o instanceof File) {
  550.             return (File) o;
  551.         }
  552.         if (o instanceof String) {
  553.             return new File((String) o);
  554.         }
  555.         throw new IllegalArgumentException("Expected String or file, actual "+o.getClass().getName());
  556.     }
  557. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement