Langsung ke konten utama

Spring Boot generate XML File dengan Jackson

 



Requirement: 
- java 1.8
- ide
- maven

Structure Project : 
├── HELP.md
├── mvnw
├── mvnw.cmd
├── pom.xml
├── spring-boot-generate-file-xml.iml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── fluex404
│   │   │           └── springbootgeneratefilexml
│   │   │               ├── controller
│   │   │               │   └── UserController.java
│   │   │               ├── model
│   │   │               │   ├── Address.java
│   │   │               │   ├── Root.java
│   │   │               │   └── User.java
│   │   │               └── SpringBootGenerateFileXmlApplication.java
│   │   └── resources
│   │       ├── application.properties
│   │       ├── static
│   │       └── templates
│   └── test
│       └── java
│           └── com
│               └── fluex404
│                   └── springbootgeneratefilexml
│                       └── SpringBootGenerateFileXmlApplicationTests.java
└── target
    ├── classes
    │   ├── application.properties
    │   └── com
    │       └── fluex404
    │           └── springbootgeneratefilexml
    │               ├── controller
    │               │   └── UserController.class
    │               ├── model
    │               │   ├── Address.class
    │               │   ├── Root.class
    │               │   └── User.class
    │               └── SpringBootGenerateFileXmlApplication.class
    ├── generated-sources
    │   └── annotations
    ├── generated-test-sources
    │   └── test-annotations
    └── test-classes
        └── com
            └── fluex404
                └── springbootgeneratefilexml
                    └── SpringBootGenerateFileXmlApplicationTests.class

How To

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.2</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.fluex404</groupId>
	<artifactId>spring-boot-generate-file-xml</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>spring-boot-generate-file-xml</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.dataformat</groupId>
			<artifactId>jackson-dataformat-xml</artifactId>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.16</version>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

buat beberapa model seperti Root.java, User.java dan Address.java

Address.java
package com.fluex404.springbootgeneratefilexml.model;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import lombok.Getter;
import lombok.Setter;

import javax.xml.bind.annotation.XmlRootElement;

@Getter
@Setter
@XmlRootElement
public class Address {
    @JacksonXmlProperty(localName = "PROVINCE")
    private String province;
    @JacksonXmlProperty(localName = "CITY")
    private String city;
}

User.java
package com.fluex404.springbootgeneratefilexml.model;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import lombok.Getter;
import lombok.Setter;

import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;

@Getter
@Setter
@XmlRootElement
public class User {

    @JacksonXmlProperty(localName = "ADDRESS")
    @JacksonXmlElementWrapper(useWrapping = false)
    private Address address;

    @JacksonXmlProperty(localName = "NAMA")
    private String nama;
    @JacksonXmlProperty(localName = "EMAIL")
    private String email;
    @JacksonXmlProperty(localName = "PHONE")
    private String phone;
}

Root.java
package com.fluex404.springbootgeneratefilexml.model;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import lombok.Getter;
import lombok.Setter;

import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;

@Getter
@Setter
@XmlRootElement
@JacksonXmlRootElement(localName = "root")
public class Root {
    // attributes
    @JacksonXmlProperty(isAttribute = true, localName = "xmlns")
    private String attr1 = "http://abcabc/abc/xyz/html";
    @JacksonXmlProperty(isAttribute = true, localName = "xmlns:vc")
    private String attr2 = "http://abcabc/abc/xyz/xhtml";

    @JacksonXmlProperty(localName = "VERSION")
    private String version;

    @JacksonXmlElementWrapper(localName = "USERS")
    @JacksonXmlProperty(localName="USER")
    private List<User> users;
}

lalu buat controller nya dan buat beberapa data fake user di method getUsers. 

UserController.java
package com.fluex404.springbootgeneratefilexml.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;
import com.fluex404.springbootgeneratefilexml.model.Address;
import com.fluex404.springbootgeneratefilexml.model.Root;
import com.fluex404.springbootgeneratefilexml.model.User;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    private List<User> getUsers(){
        List<User> users = new ArrayList<>();

        Address address1 = new Address();
        address1.setCity("BOGOR");
        address1.setProvince("JAWA BARAT");

        Address address2 = new Address();
        address2.setCity("JAKARTA BARAT");
        address2.setProvince("JAWA BARAT");

        User user1 = new User();
        user1.setAddress(address1);
        user1.setEmail("abcabc@gmail.com");
        user1.setNama("Isa");
        user1.setPhone("123123");

        User user2 = new User();
        user2.setAddress(address2);
        user2.setEmail("xzyxzy26@gmail.com");
        user2.setNama("Rara");
        user2.setPhone("00221");

        User user3 = new User();
        user3.setAddress(address1);
        user3.setEmail("kkjj26@gmail.com");
        user3.setNama("Test");
        user3.setPhone("321321");

        users.add(user1);
        users.add(user2);
        users.add(user3);


        return users;
    }

    @GetMapping("/download/xml")
    public ResponseEntity download() throws JsonProcessingException {
        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.configure( ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true );


        Root root = new Root();
        List<User> users = getUsers();

        root.setVersion("1.10.20");
        root.setUsers(users);

        byte[] byteArr = xmlMapper.writeValueAsString(root).getBytes();

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=abcabc.xml");

        return ResponseEntity.ok().headers(headers).body(new InputStreamResource(new ByteArrayInputStream(byteArr)));
    }
}

Testing: 
buka browser lalu masuk ke url ini http://localhost:8080/user/download/xml
download filenya dan isi filenya akan seperti ini






Komentar

Postingan populer dari blog ini

whois

  Pengertian:  whois adalah tools yang digunakan untuk melihat informasi mengenai kepemilikan domain dan website. ICANN meregulasikan domain name dan kepemelikian, tapi record listnya di adakan di semua company dikenal sebagai registrasi.  jadi orang bisa query list of records, dan register akan menghandle request anda dan mengirim detail dari whois record yang sesuai. How to Install whois :  sudo apt-get install whois How to use:  whois cnn.com dan hasilnya akan seperti ini. Domain Name: CNN.COM Registry Domain ID: 3269879_DOMAIN_COM-VRSN Registrar WHOIS Server: whois.corporatedomains.com Registrar URL: http://www.cscglobal.com/global/web/csc/digital-brand-services.html Updated Date: 2018-04-10T16:43:38Z Creation Date: 1993-09-22T04:00:00Z Registry Expiry Date: 2026-09-21T04:00:00Z Registrar: CSC Corporate Domains, Inc. Registrar IANA ID: 299 Registrar Abuse Contact Email: domainabuse@cscglobal.com Registrar Abuse Contact Phone: 8887802723 Domain Status: clien...

Membuat export dan import Excel di spring boot

Membuat export dan import Excel  di spring boot           Adakalanya seorang developer diminta untuk membuat fitur export dan import berbentuk excel dan sebenarnya java sudah menyediakan suatu liblary yang memudahkan kita untuk bekerja dengan MS-Office yaitu Apache POI. Disini saya akan menggunakan Apache POI untuk membaca dan menulis Excel. Catatan : Disini saya sarankan untuk belajar Apache POI Excel terlebih dahulu agar anda mengerti kode yang saya buat di bawah ini. Bahan : -  IntelliJ IDEA -  PostgreSQL -  Maven -  Java 8 Jika sudah tersedia bahan - bahan di atas langsung saja kunjungi situs ini Tambahkan dependency Apache POI di pom.xml seperti di bawah ini. <?xml version="1.0" encoding="UTF-8"?> <project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0...

Spring Boot CRUD Thymeleaf-Pagination + Bootstrap Dynamic Modals

Spring Boot CRUD Thymeeaf-Pagination + Bootstrap Dynamic Modals                Sebelumnya saya sudah sharing bagaimana cara membuat Spring Boot CRUD sederhana di artikel sebelumnya yang blum lihat silahkan lihat disini . Sekarang saya akan membuat Spring Boot CRUD lagi ala pagination dan Dynamic Modals dengan bootstrap. Bahan : - IntelliJ IDEA - PostgreSQL - Maven - JDK1.8 Jika bahan nya sudah tersedia agan bisa kunjungi situs resmi spring nya https://start.spring.io/  buat seperti ini lalu download dan exract. Buat database yang bernama "springbootcrud2" disini saya menggunakan pgadmin4. Buka intelliJ atau IDE kesayangan kalian buka file application.properties di dalam resources dan isikan ini untuk configurasi databasenya sesuai kan dengan database kalian lalu save. ## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties) spring.datasource.url = jdbc:postgresql://loc...