Friday, December 6, 2019

XML to java Object converter usinn Marshall class and Vise Versa

Converting the XML to Java object instead reading the xml file every time. It will be good approached in terms of performance.




Lets say below is the xml to convert into Object 

    
 







Pre-requests : Includes below dependencies in POM.xml file 









2nd Steps : to  create the  POJO Class  having JAXB Annotation . 
For object that need to convert to / from XML file, it have to annotate with JAXB annotation.

Below is the class format for POJO Class:

import java.util.List;  
  
import javax.xml.bind.annotation.XmlAttribute;  
import javax.xml.bind.annotation.XmlElement;  
import javax.xml.bind.annotation.XmlRootElement;  
  
@XmlRootElement  
public class Question {  
private int id;  
private String questionname;  
private List answers;  
public Question() {}  
public Question(int id, String questionname, List answers) {  
    super();  
    this.id = id;  
    this.questionname = questionname;  
    this.answers = answers;  
}  
@XmlAttribute  
public int getId() {  
    return id;  
}  
public void setId(int id) {  
    this.id = id;  
}  
@XmlElement  
public String getQuestionname() {  
    return questionname;  
}  
public void setQuestionname(String questionname) {  
    this.questionname = questionname;  
}  
@XmlElement  
public List getAnswers() {  
    return answers;  
}  
public void setAnswers(List answers) {  
    this.answers = answers;  
}  
}  


NOTE: 
The Best option to create a such class is "Online tools which generate code , Just search in google with 'XML to JAVA Converter'  " . refer https://codebeautify.org/xml-to-java-converter





3rd Steps. Convert Object to XML: 
JAXB marshalling example, convert customer object into a XML file. The jaxbMarshaller.marshal() contains a lot of overloaded methods, find one that suit your output.



public static void main(String[] args)
   throws JAXBException, SAXException, IOException, ParserConfigurationException {

  JAXBContext jaxbContext = JAXBContext.newInstance(Question.class);
  Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
  // file readers
  InputStream inputStream = new FileInputStream(
    "xmltoobject\\NewFile.xml");
  Reader reader = new InputStreamReader(inputStream, "UTF-8");
  Question customer = null;
  try {
   customer = (Question) jaxbUnmarshaller.unmarshal(reader);

  } catch (Exception e) {
   e.printStackTrace();
  }
  System.out.println(customer.environment); }}
  to get the Below out put :System.out.println(que.getId()+" "+que.getQuestionname());  
        System.out.println("Answers:");  
        List list=que.getAnswers();  
        for(Answer ans:list)  
          System.out.println(ans.getId()+" "+ans.getAnswername()+"  "+ans.getPostedby());  



Out Put : 1 What is java?
          Answers:
         101 java is a programming language ravi
         102 java is a platform john









3th Steps . Convert Object to XML  (ViseVersa):


JAXB marshalling example, convert customer object into a XML file. The jaxbMarshaller.marshal() contains a lot of overloaded methods, find one that suit your output.



import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
 public static void main(String[] args) {

   Customer customer = new Customer();
   customer.setId(100);
   customer.setName("mkyong");
   customer.setAge(29);

   try {

  File file = new File("C:\\file.xml");
  JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
  Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

  // output pretty printed
  jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

  jaxbMarshaller.marshal(customer, file);
  jaxbMarshaller.marshal(customer, System.out);

       } catch (JAXBException e) {
  e.printStackTrace();
       }

 }
}


Out put is XML file 

Reference article : https://www.mkyong.com/java/jaxb-hello-world-example/
https://www.javatpoint.com/jaxb-unmarshalling-example




Thursday, December 5, 2019

Number's Group separator and Decimal separator according to local regional format and Vise-versa

Number's  Group separator and Decimal separator  according to local regional format: 


/** @ Returns the number's Group separator according to local regional format */


 /** @ Returns the number's Group separator according to local regional format */
 protected String getGroupSeparator() {
  DecimalFormat decFormat = new DecimalFormat();
  DecimalFormatSymbols decSymbols = decFormat.getDecimalFormatSymbols();
  return String.valueOf(decSymbols.getGroupingSeparator());
 }





/** @ Returns the number Decimal separator according to local regional format */



 /** @ Returns the number Decimal separator according to local regional format */
 protected String getDecimalSeparator() {
  DecimalFormat decFormat = new DecimalFormat();
  DecimalFormatSymbols decSymbols = decFormat.getDecimalFormatSymbols();
  return String.valueOf(decSymbols.getDecimalSeparator());
 }
 



Number with group-separator and decimal-separator convert into decimal number


ie convert the number "4,471.26" into decimal number "4471.26" dis-respective the number format is (for example it could be 4,294,967,295.00  or 4.294.967.295,000  )


public static void geoSp() {
    String a = "4.233,19";
    NumberFormat as = NumberFormat.getInstance();
    double myNumber = 0;
    try {
        myNumber = as.parse(a).doubleValue();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    System.out.println(String.valueOf(myNumber));
}

   gives  Out put :- 4233.19



Get currency symbol from currency code

 @ Returns the currency symbol  according to respective countries 

 private SortedMap currencyLocaleMap() {
  SortedMap currencyLocMap = new TreeMap(new Comparator() {
   @Override
   public int compare(Currency c1, Currency c2) {
    return c1.getCurrencyCode().compareTo(c2.getCurrencyCode());
   }
  });

  for (Locale locale : Locale.getAvailableLocales()) {
   try {
    Currency currency = Currency.getInstance(locale);
    currencyLocMap.put(currency, locale);
   } catch (Exception e) {
   }
  }
  return currencyLocMap;
 }

/** @Calling method to get currency symbol */

 /** @Calling method to get currency symbol */
 /** @ Returns the currency symbole according to respective currencies */
 public String getCurrencySymbol(String currencyCode) {
  Currency currency = Currency.getInstance(currencyCode);
  return currency.getSymbol(currencyLocaleMap().get(currency));
 }
NOTE::
Where as "currencyCode " be any of the below 
  * {AED=ar_AE, ALL=sq_AL, ARS=es_AR, AUD=en_AU, BAM=sr_BA, BGN=bg_BG, BHD=ar_BH,
  * BOB=es_BO, BRL=pt_BR, BYN=be_BY, CAD=en_CA, CHF=it_CH, CLP=es_CL, CNY=zh_CN,
  * COP=es_CO, CRC=es_CR, CSD=sr_CS, CUP=es_CU, CZK=cs_CZ, DKK=da_DK, DOP=es_DO,
  * DZD=ar_DZ, EGP=ar_EG, EUR=sl_SI, GBP=en_GB, GTQ=es_GT, HKD=zh_HK, HNL=es_HN,
  * HRK=hr_HR, HUF=hu_HU, IDR=in_ID, ILS=iw_IL, INR=en_IN, IQD=ar_IQ, ISK=is_IS,
  * JOD=ar_JO, JPY=ja_JP, KRW=ko_KR, KWD=ar_KW, LBP=ar_LB, LYD=ar_LY, MAD=ar_MA,
  * MKD=mk_MK, MXN=es_MX, MYR=ms_MY, NIO=es_NI, NOK=no_NO, NZD=en_NZ, OMR=ar_OM,
  * PAB=es_PA, PEN=es_PE, PHP=en_PH, PLN=pl_PL, PYG=es_PY, QAR=ar_QA, RON=ro_RO,
  * RSD=sr_RS_#Latn, RUB=ru_RU, SAR=ar_SA, SDG=ar_SD, SEK=sv_SE, SGD=zh_SG,
  * SVC=es_SV, SYP=ar_SY, THB=th_TH_TH_#u-nu-thai, TND=ar_TN, TRY=tr_TR,
  * TWD=zh_TW, UAH=uk_UA, USD=es_US, UYU=es_UY, VEF=es_VE, VND=vi_VN, YER=ar_YE,
  * ZAR=en_ZA}
  */




To round-up till desire digits decimal format

/** @ To round-up digits two decimal format */


 /** @ To round-up digits two decimal format */
 private double RoundTo2Decimals(double val) {
  DecimalFormat df2 = new DecimalFormat("###.##");
  String as = df2.format(val);
  return Double.valueOf(as.replace(getDecimalSeparator(), "."));
 }



/** @ truncate decimal till desire  digits */

/** @ truncate decimal till 2 digits */
 protected double truncateDecimal(double x, int numberofDecimals) {
  BigDecimal num;
  if (x > 0) {
   num = new BigDecimal(String.valueOf(x)).setScale(numberofDecimals, BigDecimal.ROUND_FLOOR);
   return num.doubleValue();

  } else {
   num = new BigDecimal(String.valueOf(x)).setScale(numberofDecimals, BigDecimal.ROUND_CEILING);
   return num.doubleValue();
  }
 }
}



/** @ To round-up  till desire  digits decimal format with conditions */
protected  BigDecimal decimalDigiRoundUp(double x, int numberofDecimals) {
  BigDecimal num; String round1="###.#", round2="###.##";
  if (numberofDecimals ==2) {
   logger.info(new BigDecimal (new DecimalFormat(round2).format(x).replace(getDecimalSeparator(),".")));
          return new BigDecimal (new DecimalFormat(round2).format(x).replace(getDecimalSeparator(),"."));
  }else {
   logger.info(new DecimalFormat("###.#").format(x)+" Shree");
   return new BigDecimal (new DecimalFormat("###.#").format(x).replace(getDecimalSeparator(),".")+"0");
  }
 }



Different Methods to convert object into String

  1. String.valueOf() 
  2. Object.toString()
  3. Integer.toString(int i)
  4.  new String()

String.valueOf() vs. Object.toString(): 

  • Primitive types don't have a "toString".. so String.valueOf is used. 
  • if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
public static void main(String args[]) {  
    String str = null;
    System.out.println(String.valueOf(str));  // This will print a String equal to "null"        
    System.out.println(str.toString()); // This will throw a NullPointerException
} 


Integer.toString(int i) vs String.valueOf(int i)

One huge difference is that if you invoke toString() in a null object you'll get a NullPointerException whereas, using String.valueOf() you may not check for null.



In String type we have several method valueOf
static String   valueOf(boolean b) 
static String   valueOf(char c) 
static String   valueOf(char[] data) 
static String   valueOf(char[] data, int offset, int count) 
static String   valueOf(double d) 
static String   valueOf(float f) 
static String   valueOf(int i) 
static String   valueOf(long l) 
static String   valueOf(Object obj) 
So for integers we have
Integer.toString(int i)
for double
Double.toString(double d)

 new String()  : 
create new instance of string