View Javadoc

1   /**
2    * Copyright 2009 Timothy Johnston Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
3    * file except in compliance with the License. You may obtain a copy of the License at
4    * 
5    * http://www.apache.org/licenses/LICENSE-2.0
6    * 
7    * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
8    * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
9    * specific language governing permissions and limitations under the License.
10   */
11  
12  package com.timjohnstondev.unitconverter.model;
13  
14  import java.util.regex.Matcher;
15  import java.util.regex.Pattern;
16  
17  /**
18   * This is a unit of measure with its related conversion factor to some base unit.
19   */
20  public class ConversionFactor implements Conversion
21  {
22    private String unitName;
23    private String unitSymbol;
24    private String factor;
25  
26    /**
27     * Constructs a {@code ConversionFactor} setting its name, symbol and factor.
28     * 
29     * @param newUnitName the name of the unit in unabbreviated words
30     * @param newUnitSymbol the symbol of the unit
31     * @param newFactor the conversion factor from this unit to some base unit
32     */
33    public ConversionFactor(final String newUnitName, final String newUnitSymbol, final String newFactor)
34    {
35      unitName = newUnitName;
36      unitSymbol = newUnitSymbol;
37      factor = newFactor;
38    }
39  
40    @Override
41    public final String getUnitName()
42    {
43      return unitName;
44    }
45  
46    @Override
47    public final String getUnitSymbol()
48    {
49      return unitSymbol;
50    }
51  
52    @Override
53    public final String getFormattedUnitSymbol()
54    {
55      final String patternString = "(^.*)\\^(\\d)(.*$)";
56      final String replacerString = "<html>$1<sup>$2</sup>$3<html>";
57      final Pattern pattern = Pattern.compile(patternString);
58  
59      final Matcher matcher = pattern.matcher(unitSymbol);
60      final String formattedSymbol = matcher.replaceAll(replacerString);
61  
62      return formattedSymbol;
63    }
64  
65    @Override
66    public final String getConversion()
67    {
68      return factor;
69    }
70  
71    @Override
72    public final void setUnitSeparator(final String symbol)
73    {
74      unitSymbol = unitSymbol.replaceAll("\\*", symbol);
75    }
76  }