Converting MultiPartFile to XWPFDocument - java

I need to know how to convert a multipartFile to a XWPFDocument in order to read it as a word file ( the file that I uploaded is in fact a .docx ) however I receive the error :
org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoClassDefFoundError: org/apache/poi/UnsupportedFileFormatException
Here is my code :
#Override
public void addReport(MultipartFile report) throws ApcException {
try{
File convFile = new File(report.getOriginalFilename());
convFile.createNewFile();
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(report.getBytes());
fos.close();
FileInputStream fis = new FileInputStream(convFile.getAbsolutePath());
XWPFDocument docx = new XWPFDocument(fis);
List<XWPFTable> tables =docx.getTables();
invokeUpdate(ADD_REPORT,new Object[]{
tables.get(0).getRow(1).getCell(0),
tables.get(1).getRow(0).getCell(0),
tables.get(2).getRow(0).getCell(0),
tables.get(3).getRow(2).getCell(1),
tables.get(4).getRow(1).getCell(1)});
}
catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here are my Apache Dependencies in my pom.xml :
For Apache POI i have these :
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.7</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
Thank you for your help !

You need to replace your apache poi version from 3.7 to 3.17.
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
The latest stable release is Apache POI 3.17

Related

DOCX4j : space removed in pdf by deploying war file into tomcat

I am using below code to convert docx to pdf using DOCX4j.While running this code into IDE it is working fine and space preserved after conversion. For deployment I created war and put it into tomcat server. But into test server space is not preserved into document after conversion.
pom.xml
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.docx4j/docx4j-JAXB-Internal -->
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-Internal</artifactId>
<version>8.3.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.docx4j/docx4j-JAXB-ReferenceImpl -->
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-ReferenceImpl</artifactId>
<version>8.3.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.docx4j/docx4j-JAXB-MOXy -->
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-MOXy</artifactId>
<version>8.3.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.docx4j/docx4j-export-fo -->
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-export-fo</artifactId>
<version>8.3.7</version>
</dependency>
code for conversion
private byte[] docxToPdfBytes() {
InputStream templateInputStream = null;
try {
templateInputStream = new FileInputStream(ApplicationConstants.TEMP_DOCX_PATH);
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateInputStream);
FileOutputStream os = new FileOutputStream(ApplicationConstants.TEMP_PDF_PATH);
Docx4J.toPDF(wordMLPackage, os);
os.flush();
os.close();
return Files.readAllBytes(Paths.get(ApplicationConstants.TEMP_PDF_PATH));
} catch (Throwable e) {
logger.info(XrefSubscriberServiceService.class.getName() + "==> Method : docxToPdfBytes");
logger.error(e.getMessage(), e);
}
finally {
if(null != templateInputStream) {
try {
templateInputStream.close();
} catch (IOException e) {
logger.info(XrefSubscriberServiceService.class.getName() + "==> Method : docxToPdfBytes");
logger.error(e.getMessage(), e);
}
}
}
return null;
}
So can anyone have idea why this type of behaviour is happened ??
this question is resolved. Just need to correct docx styling of font in docx document.

java ObjectOutputStream create csv file with gibberish data

I have over 300 tables which i want to export to CSV files. However i see gibberish data.
I send the tablename and the retrieve the data using jdbctemplate I can see the data but when i export I see gibberish values
sr1org.springframework.util.LinkedCaseInsensitiveMapiEkMÑ=f$LcaseInsensitiveKeystLjava/util/HashMap
sr1org.springframework.util.LinkedCaseInsensitiveMapiEkMÑ=f$LcaseInsensitiveKeystLjava/util/HashMap
q~q~q~q~xq~sq~?#wq~sq~q~trivera92q~
Below is the code:
exportData.java
public List getTableData(String tableName){
return jdbcTemplate.queryForList("select * FROM " + tableName + " LIMIT 10");
}
To create csv file
#Autowired
ExportData exportData;
public void CreateCsvData(){
String tableName = "user_details";
String folderPath = "/tmp/Data/";
List data = this.exportData.getTableData(tableName);
try {
FileOutputStream fis = new FileOutputStream(folderPath + tableName + ".csv",true);
ObjectOutputStream os = new ObjectOutputStream(fis);
for (int i = 0; i < data.size(); i++) {
os.writeObject(data.get(i));
os.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
here is pom.xml
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jdbc -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
<dependencies>
I saw many examples with resultsetextractor and RowMapper but its difficult to write models for 300 tables.
Sorry my bad; I did iterate over the object forgot to paste it here;

Exception in PortForwarder when adding swagger support to org.glassfish.jersey.server

I am trying to add swagger support to javax rest apis and ended up having the following exception. Any insights will be helpful.
Exception in thread "PortForwarder" java.lang.NoSuchMethodError: org.apache.commons.lang3.Validate.inclusiveBetween(JJJ)V
at com.offbynull.portmapper.mappers.upnpigd.externalmessages.ServiceDiscoveryUpnpIgdRequest$ProbeDeviceType.<init>(ServiceDiscoveryUpnpIgdRequest.java:128)
at com.offbynull.portmapper.mappers.upnpigd.externalmessages.ServiceDiscoveryUpnpIgdRequest$ProbeDeviceType.<clinit>(ServiceDiscoveryUpnpIgdRequest.java:104)
at com.offbynull.portmapper.mappers.upnpigd.UpnpIgdPortMapper.identify(UpnpIgdPortMapper.java:202)
at com.offbynull.portmapper.PortMapperFactory.discover(PortMapperFactory.java:58)
at com.swirlds.p2p.portforwarding.portmapper.PortMapperPortForwarder.execute(PortMapperPortForwarder.java:60)
at com.swirlds.p2p.portforwarding.portmapper.PortMapperPortForwarder.run(PortMapperPortForwarder.java:172)
at java.lang.Thread.run(Thread.java:748)
Code to initialise the server
public static void initREST(int port, String[] packages) {
URI baseUri = UriBuilder.fromUri("http://0.0.0.0").port(port).build();
ResourceConfig config = new ResourceConfig()
.register(new CORSFilter())
.register(JacksonFeature.class);
configureSwagger(config);
for (String pkg : packages) {
config.packages(pkg);
}
System.out.println("Attempting to start Grizzly on " + baseUri);
GrizzlyHttpServerFactory.createHttpServer(baseUri, config);
} catch (IOException e1) {
e1.printStackTrace();
}
}
Code to configure swagger:
private static void configureSwagger(ResourceConfig resourceConfig) {
resourceConfig.register(ApiListingResource.class);
resourceConfig.register(SwaggerSerializers.class);
BeanConfig config = new BeanConfig();
config.setVersion("v1");
config.setBasePath("/");
config.setResourcePackage("ipos.hashgraph.rest");
config.setPrettyPrint(true);
config.setScan(true);
}
Maven Dependencies:
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jaxrs</artifactId>
<version>1.5.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-grizzly2-servlet</artifactId>
</dependency>

Maven Junit test case crashing with java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory

I have been trying to implement a Junit test case for a service which returns what are the different type of resources as shown in the Tester code below:
public class Tester {
MyInfoService myInfoService=null;
#Before
public void setUp() throws Exception{
myInfoService = new MyInfoService();
System.out.println(" ##$## myInfoService ="+myInfoService.getAllMyResourceTypes().size());
}
#Test
public void testResTypeAll() {
List<MyTypeInfoBean> resTypeBeanList = myInfoService.getAllMyResourceTypes();
assertEquals("Testing size for res type...", 18, resTypeBeanList.size());
}
}
Service class where the error occurs:
public class MyInfoService implements MyInfoServiceRemote {
// some code here
#Override
public List<MyTypeInfoBean> getAllMyResourceTypes() {
List<MyResourceTypeInfoDTO> resourceList = new ArrayList<>();
List<MyTypeInfoBean> resourceListBean = new ArrayList<>();
MyResourceTypeInfoDTO myResTypeInfoDTO = null;
try {
HashMap<Integer,MyConstantsUtilClass.MyResourceTypes> restypemap = (HashMap<Integer, MyResourceTypes>)MyConstantsUtilClass.MyResourceTypes.getRestypemap();
Set<Map.Entry<Integer, MyConstantsUtilClass.MyResourceTypes>> restypemapEntrySet = restypemap.entrySet();
for (Entry<Integer, MyResourceTypes> entry : restypemapEntrySet) {
myResTypeInfoDTO = new MyResourceTypeInfoDTO();
// code to read the entry values and populate my DTO
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// size gets printed, so everything is fine till now
System.out.println("##$## resourceList ="+resourceList.size());
// The resource list is printed correctly above.The problem begins below
Mapper mapper=null;
if (resourceList != null) {
System.out.println("resourceList is not null object");
System.out.print("Original contents of al: ");
try {
// this does not work and get a NoClassDefError
mapper= DozerBeanMapperSingletonWrapper.getInstance(); } catch(Exception e) {
e.printStackTrace();
}
Iterator<MyResourceTypeInfoDTO> itr = resourceList.iterator();
while (itr.hasNext()) {
MyResourceTypeInfoDTO element = (MyResourceTypeInfoDTO) itr.next();
if (mapper == null)
System.out.println("Mapper is NULL");
MyTypeInfoBean beanElement = mapper.map(element, MyTypeInfoBean.class);
resourceListBean.add(beanElement);
}
return resourceListBean;
}
// other methods here
}
Below is the error log I get on running the Junit test case:
java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at org.dozer.DozerBeanMapper.<clinit>(DozerBeanMapper.java:58)
at org.dozer.DozerBeanMapperSingletonWrapper.getInstance(DozerBeanMapperSingletonWrapper.java:43)
at com.inv.service.MyInfoService.getAllResourceTypes(MyInfoService.java:508)
at com.bel.tropo.tester.Tester.setUp(Tester.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
My pom.xml file has the dozer dependency correctly mentioned as :
<dependency>
<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
<version>5.3.2</version>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
The dependencies required by dozer are already resolved through mvn dependency:resolve.
Should I downgrade to a lower version of dozer and check if it works?
These two (How can I resolve java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory? and dozer with maven) questions don't seem to give me a solution or am I missing something?
Any help would be great.
Restate your dozer dependency as follows:
<dependency>
<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
<version>5.3.2</version>
</dependency>
The dozer-5.3.2-pom declares SLF4J as a transitive dependency so it will be provided for you as soon as you remove the unwanted exclusions from your Dozer declaration.
<dependency>
<groupId>
net.sf.dozer
</groupId>
<artifactId>
dozer
</artifactId>
<version>
5.5.1
</version>
</dependency>
Updating the dozer version and doing a maven compile/install solved it for me besides getting rid of exclusions.

NoClassDefFoundError while reading a pdf file

Iam trying to read a pdf file the code is
try {
File fileConn = new File(filePath);
InputStream inp = new FileInputStream(fileConn);
PdfReader reader = new PdfReader(inp);
int pages = reader.getNumberOfPages();
System.out.println("Pages" + pages);
} catch (Exception e) {
//Handle Exception
}
But the method is throwing NOClassDefFoundError. What coukd be the possible reason
Did you added pdfbox and itextpdf to your classpath?
Try this, if you're using maven:
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.0.6</version>
</dependency>

Categories

Resources