OpenCSV : throws error capturing csv header on parse method - java

My OpenCSV Version is : 5.5.2
I upload a CSV file and call the parseCSVFile method like this
List<CSVCouponData> csvData = CSVFileHelper.parseCSVFile(multipartFile.getInputStream());
Following is my code
public static List<CSVCouponData> parseCSVFile(InputStream inputStream) throws IOException {
CSVReader reader = null;
List<CSVCouponData> rec = null;
try {
reader = new CSVReader(new InputStreamReader(inputStream));
HeaderColumnNameMappingStrategy<CSVCouponData> beanStrategy = new HeaderColumnNameMappingStrategy<>();
beanStrategy.setType(CSVCouponData.class);
CsvToBean<CSVCouponData> csvToBean = new CsvToBean<>();
csvToBean.setCsvReader(reader);
csvToBean.setMappingStrategy(beanStrategy);
csvToBean.setIgnoreEmptyLines(true);
rec = csvToBean.parse();
} finally {
if(reader != null)
reader.close();
}
return rec;
}
The following is my CSVCouponData
public class CSVCouponData {
#CsvBindByName(column = "name", required = true)
private String name;
#CsvBindByName(column = "coupon-type", required = true)
private String couponType;
#CsvBindByName(column = "incentive-program-id", required = true)
private String programId;
#CsvBindByName(column = "coupons-amount")
private Long couponsAmount;
#CsvBindByName(column = "coupon-benefits.unit-of-measure")
private String unitOfMeasure;
#CsvBindByName(column = "coupon-benefits.benefit-target-party")
private String benefitTargetParty;
#CsvBindByName(column = "coupon-benefits.characteristics")
private String characteristics;
#CsvBindByName(column = "coupon-benefits.benefit-type")
private String benefitType;
#CsvBindByName(column = "coupon-benefits.benefit-confirmation-source")
private String benefitConfirmationSource;
#CsvBindByName(column = "coupon-benefits.benefit-currency")
private String benefitCurrency;
#CsvBindByName(column = "coupon-benefits.benefit-amount")
private String benefitAmount;
#CsvBindByName(column = "coupon-benefits.benefit-description", required = true)
private String benefitDescription;
#CsvBindByName(column = "benefit-catalog-info.product-offering-ids")
private String productOfferingIds;
#CsvBindByName(column = "benefit-catalog-info.discount-id")
private String discountId;
#CsvBindByName(column = "benefit-catalog-info.cardinality.min")
private Integer cardinalityMin;
#CsvBindByName(column = "benefit-catalog-info.cardinality.max")
private Integer cardinalityMax;
#CsvBindByName(column = "external-id", required = true)
private String externalId;
#CsvBindByName(column = "valid_from", required = true)
private String validFrom;
#CsvBindByName(column = "valid_to", required = true)
private String validTo;
#CsvBindByName(column = "sales_context.batch-id")
private String batchId;
#CsvBindByName(column = "sales_context.campaign-id")
private String campaignId;
#CsvBindByName(column = "sales_context.chain-id")
private String chainId;
#CsvBindByName(column = "sales_context.channel")
private String channel;
#CsvBindByName(column = "sales_context.dealer-id")
private String dealerId;
#CsvBindByName(column = "sales_context.sales-type")
private String salesType;
#CsvBindByName(column = "sales_context.salesperson-id")
private String salesPersonId;
#CsvBindByName(column = "incentive-coupon-batches.partner-name", required = true)
private String partnerName;
#CsvBindByName(column = "incentive-coupon-batches.redemption-specification-owner", required = true)
private String redemptionSpecificationOwner;
#CsvBindByName(column = "incentive-coupon-batches.distribution-specification.owner", required = true)
private String distributionSpecificationOwner;
#CsvBindByName(column = "incentive-coupon-batches.distribution-specification.method", required = true)
private String distributionSpecificationMethod;
#CsvBindByName(column = "incentive-coupons.code", required = true)
private String code;
#CsvBindByName(column = "brand")
private String brand;
When i debug my code it throws and error at this line rec = csvToBean.parse(); with this error
java.lang.RuntimeException: Error capturing CSV header!
Even though i have provided all the fields which are marked required =true in my CsvCouponData, i see this error
com.opencsv.exceptions.CsvRequiredFieldEmptyException: Header is missing required fields [INCENTIVE-PROGRAM-ID]. The list of headers encountered is [ incentive-program-id,coupon-type,name,coupon-benefits.benefit-description,external-id,valid_from,valid_to,incentive-coupon-batches.partner-name,incentive-coupon-batches.redemption-specification-owner,incentive-coupon-batches.distribution-specification.owner,incentive-coupon-batches.distribution-specification.method,incentive-coupons.code].
Initially i had opencsv version 4.4 and did not have this error.
But when i upgraded the version to 5.5.2 i started seeing this error. I have also upgraded to the latest version which is 5.6, but still no luck.
I have gone through this link which is almost similar to the error i get, but no solutions have helped
OpenCSV throws Error capturing CSV header on parse
Any suggestions please

I have figured out the issue. The problem is not with the code, but the problem was the file format. The csv file which we were uploading was saved with the following format .csv(utf-8). Then changing the format of the file to .csv solved the issue.

Related

unable to parse CSV with `CsvParser` abstract class mapping but works with JSON mapper

Unable to parse CSV files to Object type,
CsvMapper not working with polymorphism, while JSON mapper works with jsonString.
#Getter
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
property = "type", visible = true,
include = JsonTypeInfo.As.PROPERTY)
#JsonSubTypes({
#Type(value = FHR.class, name = "FHR"),
#Type(value = BHR.class, name = "BHR")})
public class PaymentBatchRecord {
protected String type;
}
#Getter
#Setter
#JsonPropertyOrder({
// "type",
"transmit_id",
"password",
"creation_date",
"creation_time",
"file_format_code",
"file_reference_code"
})
class FHR extends PaymentBatchRecord implements Serializable {
private final static long serialVersionUID = -584359005702082280L;
// #JsonProperty("type")
// private String type;
#JsonProperty("transmit_id")
private String transmitId;
#JsonProperty("password")
private String password;
#JsonProperty("creation_date")
private String creationDate;
#JsonProperty("creation_time")
private String creationTime;
#JsonProperty("file_format_code")
private String fileFormatCode;
#JsonProperty("file_reference_code")
private String fileReferenceCode;
}
#Setter
#Getter
#JsonPropertyOrder({
// "type",
"transaction_type",
"merchant_id",
"merchant_name",
"batch_entry_description",
"batch_reference_code",
"batch_number"
})
class BHR extends PaymentBatchRecord implements Serializable {
private final static long serialVersionUID = 1650905882208990490L;
// #JsonProperty("type")
// private String type;
#JsonProperty("transaction_type")
private String transactionType;
#JsonProperty("merchant_id")
private String merchantId;
#JsonProperty("merchant_name")
private String merchantName;
#JsonProperty("batch_entry_description")
private String batchEntryDescription;
#JsonProperty("batch_reference_code")
private String batchReferenceCode;
#JsonProperty("batch_number")
private Integer batchNumber;
}
and here is I'm trying to de-serialize
CsvMapper mapper = new CsvMapper();
// uncomment it to run but with all the null values
// mapper.enable(CsvParser.Feature.IGNORE_TRAILING_UNMAPPABLE)
;
CsvSchema sclema = mapper.schemaFor(PaymentBatchRecord.class)
.withoutHeader();
MappingIterator<PaymentBatchRecord> iterator = mapper
.readerFor(PaymentBatchRecord.class)
.with(sclema)
.readValues(in);
List<PaymentBatchRecord> ppojos = iterator.readAll();
and here is the sample csv input
FHR,BILLER_1,"biller1pwd","20200224","091503","CSV","202002240915031"
BHR,"PMT","BILLER_1","BILLER 1 NAME","UTILITY BILL",,1
Exception I got:
Exception in thread "main" com.fasterxml.jackson.dataformat.csv.CsvMappingException: Too many entries: expected at most 1 (value #1 (8 chars) "BILLER_1")
at [Source: (com.fasterxml.jackson.dataformat.csv.impl.UTF8Reader); line: 1, column: 5]
at com.fasterxml.jackson.dataformat.csv.CsvMappingException.from(CsvMappingException.java:28)
at com.fasterxml.jackson.dataformat.csv.CsvParser._reportCsvMappingError(CsvParser.java:1246)
at com.fasterxml.jackson.dataformat.csv.CsvParser._handleExtraColumn(CsvParser.java:1001)
at com.fasterxml.jackson.dataformat.csv.CsvParser._handleNextEntry(CsvParser.java:862)
at com.fasterxml.jackson.dataformat.csv.CsvParser.nextToken(CsvParser.java:609)
at com.fasterxml.jackson.core.util.JsonParserSequence.switchAndReturnNext(JsonParserSequence.java:234)
at com.fasterxml.jackson.core.util.JsonParserSequence.nextToken(JsonParserSequence.java:152)
at com.fasterxml.jackson.core.JsonParser.nextFieldName(JsonParser.java:861)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:295)
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:189)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:161)
at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer._deserializeTypedForId(AsPropertyTypeDeserializer.java:130)
at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromObject(AsPropertyTypeDeserializer.java:97)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeWithType(BeanDeserializerBase.java:1196)
at com.fasterxml.jackson.databind.deser.impl.TypeWrappedDeserializer.deserialize(TypeWrappedDeserializer.java:68)
at com.fasterxml.jackson.databind.MappingIterator.nextValue(MappingIterator.java:280)
at com.fasterxml.jackson.databind.MappingIterator.readAll(MappingIterator.java:320)
at com.fasterxml.jackson.databind.MappingIterator.readAll(MappingIterator.java:306)

Error while mapping xml to java using jackson: com.fasterxml.jackson.databind.exc.MismatchedInputException

I have an xml file that I have to parse and map to a Java class:
<udm.DeployedApplication id="ID" token="TOKEN" created-by="AUTHOR" created-at="2018-12-10T10:02:36.264+0000" last-modified-by="AUTHOR" last-modified-at="2019-05-21T18:16:07.492+0000">
<version ref="REF"/>
<environment ref="REF2"/>
<deployeds>
<ci ref="ref3"/>
</deployeds>
<orchestrator>
<value>value1</value>
<value>value2</value>
<value>value3</value>
</orchestrator>
<optimizePlan>true</optimizePlan>
<boundConfigurationItems/>
<unresolvedPlaceholders/>
<undeployDependencies>false</undeployDependencies>
<bpcForceUndeployment>false</bpcForceUndeployment>
<enableAutomaticOrchestrators>true</enableAutomaticOrchestrators>
<hotDeploy>false</hotDeploy>
</udm.DeployedApplication>
XlDeployCi.java:
#JsonIgnoreProperties(ignoreUnknown = true)
public class XlDeployCi {
#JacksonXmlProperty(localName = "id")
private String id;
#JacksonXmlProperty(localName = "token")
private String token;
#JacksonXmlProperty(localName = "created-by")
private String createdBy;
#JacksonXmlProperty(localName = "created-at")
private Timestamp createdAt;
#JacksonXmlProperty(localName = "last-modified-by")
private String modifiedBy;
#JacksonXmlProperty(localName = "last-modified-at")
private Timestamp modifiedAt;
#JacksonXmlProperty(localName = "version")
private XlDeployRef version;
#JacksonXmlProperty(localName = "environment")
private XlDeployRef environment;
#JacksonXmlProperty(localName = "deployeds")
private List<XlDeployRef> deployeds;
#JacksonXmlProperty(localName = "orchestrator")
private XlDeployOrchestrator orchestrator;
#JacksonXmlProperty(localName = "boundConfigurationItems")
private String boundConfigurationItems;
#JacksonXmlProperty(localName = "unresolvedPlaceholders")
private String unresolvedPlaceholders;
#JacksonXmlProperty(localName = "optimizePlan")
private Boolean optimizePlan;
#JacksonXmlProperty(localName = "undeployDependencies")
private Boolean undeployDependencies;
#JacksonXmlProperty(localName = "bpcForceUndeployment")
private Boolean bpcForceUndeployment;
#JacksonXmlProperty(localName = "enableAutomaticOrchestrators")
private Boolean enableAutomaticOrchestrators;
#JacksonXmlProperty(localName = "hotDeploy")
private Boolean hotDeploy;
}
XlDeployRef.java:
#JsonIgnoreProperties(ignoreUnknown = true)
public class XlDeployRef {
#JacksonXmlProperty(localName = "ref")
private String ref;
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
}
XlDeployOrchestrator.java:
#JsonIgnoreProperties(ignoreUnknown = true)
public class XlDeployOrchestrator {
#JacksonXmlProperty(localName = "value")
private ArrayList <String> value;
}
TestXml.java:
public class TestXml {
private static final String FILE_PATH = "src/main/resources/xmlRest.txt";
#Test
public void testXml() throws JsonParseException, JsonMappingException, IOException {
String xmlFile = readFile(FILE_PATH, Charset.defaultCharset());
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.setDefaultUseWrapper(false);
xmlMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
List<XlDeployCi> list = xmlMapper.readValue(xmlFile, new TypeReference<List<XlDeployCi>>() {});
list.forEach(System.out::println);
}
private static String readFile(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
}
The error I get :
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of package.XlDeployCi
(although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('true')
EDIT
I tried few things, and found something strange, I changed my xml file to :
<udm.DeployedApplication id="Environments/UAT/Env/UAT-DCS_APL/dcs-application" token="b3dd242b-66ff-4548-81b1-062c8a1152be" created-by="ext.pcuciniello" created-at="2018-12-10T10:02:36.264+0000" last-modified-by="ext.pcuciniello" last-modified-at="2019-05-21T18:16:07.492+0000">
<version ref="Applications/Shipping/Java/DCS/dcs-application/dcs1.8.5-20190521"/>
<environment ref="Environments/UAT/Env/UAT-DCS_APL"/>
<deployeds>
<ci ref="Infrastructure/UAT/WEBLO/UAT_DCS_APL_DOMAIN/DCS_UAT_CLUSTER/dcs-application"/>
</deployeds>
<hotDeploy>true</hotDeploy>
</udm.DeployedApplication>
Then, I changed the XlDeployCi.java file:
#JsonIgnoreProperties(ignoreUnknown = true)
public class XlDeployCi {
#JacksonXmlProperty(localName = "id")
private String id;
#JacksonXmlProperty(localName = "token")
private String token;
#JacksonXmlProperty(localName = "created-by")
private String createdBy;
#JacksonXmlProperty(localName = "created-at")
private Timestamp createdAt;
#JacksonXmlProperty(localName = "last-modified-by")
private String modifiedBy;
#JacksonXmlProperty(localName = "last-modified-at")
private Timestamp modifiedAt;
#JacksonXmlProperty(localName = "version")
private XlDeployRef version;
#JacksonXmlProperty(localName = "environment")
private XlDeployRef environment;
#JacksonXmlProperty(localName = "deployeds")
private List<XlDeployRef> deployeds;
#JacksonXmlProperty(localName = "hotDeploy")
public String hotDeploy;
#Override
public String toString() {
return "XlDeployCi [id=" + id + ", token=" + token + ", createdBy=" + createdBy + ", createdAt=" + createdAt
+ ", modifiedBy=" + modifiedBy + ", modifiedAt=" + modifiedAt + ", version=" + version
+ ", environment=" + environment + ", deployeds=" + deployeds + ", hotDeploy=" + hotDeploy + "]";
}
}
The error I get :
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of package.XlDeployCi
(although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('false')
But, If I remove the line <hotDeploy>false</hotDeploy>, it works correctly.
It's seems, I can't do something like <X>Y</Y>, I can only do stuff like <X Y="Z"/>.
I found the solution:My mistake, (a terrible one), was, that I forgot to change the type of the mapping class for the method xmlMapper.readValue(String content, Class<T> valueType).
Indeed, I set the class of the mapping object as new TypeReference<List<XlDeployCi>>() {}. You should do that to get a list, but actually, I only needed 1 object.
I leave this answer, in case someone makes the same mistake as me.

How to make response class for a specific list (in xml )

Newbie to Android and developing an app where using XML parsing with the retrofit.
I have completed all the process and done the task except one.
I don't know how to create the POJO class for the "hours_of_operations" tag in below XML.
A sample code would be a great help.
<dealers>
<dealer>
<name>Minnesota Tile & Stone</name>
<address>
...... </address>
<phone>12345678</phone>
<url>www.xyz.com</url>
<showroom_display_level>ooopppss</showroom_display_level>
<distance>11.76</distance>
<open>false</open>
<hours_of_operations>
<hours_of_operation>
<days>M,W,F</days>
<hours>10:00 - 5:00</hours>
</hours_of_operation>
<hours_of_operation>
<days>T,Th</days>
<hours>10:00 - 8:00</hours>
</hours_of_operation>
<hours_of_operation>
<days>Sat</days>
<hours>10:00 - 4:00</hours>
</hours_of_operation>
</hours_of_operations>
<google_static_map_url>
....... </google_static_map_url>
<google_map_url>
.......</google_map_url>
</dealer>
I have done with all attributes, just not sure about "hours_of_operations" and data inside that. Here is my Dealer class
#Root(name = "dealer")
public class Dealer {
#Element(name = "name")
private String name;
#Element(name = "address")
private Address adress;
#Element(name = "phone")
private long phone;
#Element(name = "url")
private String url;
#Element(name = "showroom_display_level", required = false)
private String showroom_display_level;
#Element(name = "distance")
private String distance;
#Element(name = "open", required = false)
private String open;
#Element(name = "hours_of_operations")
private HoursOfOperation hours_of_operations;
#Element(name = "google_static_map_url")
private String google_static_map_url;
#Element(name = "google_map_url")
private String google_map_url;
--getters--n -setters--
hoursofoperation class
#Root(name = "hours_of_operation", strict = false)
public class HoursOfOperation {
#Element(name = "days", required = false)
private String days;
#Element(name = "hours", required = false)
private String hours;
getters--setters
Here is my response class
#Root(name = "dealers", strict = false)
public class ApiResponse {
#ElementList(inline = true, required = false)
public List<Dealer> dealerList;
}
I am done with this XML, just not sure about the "hours_of_operations"
Thanks in advance.

Issue mapping xml to java using simplexml 2.1.0

I am trying to map a xml response given by a web service to a java object using SimpleXML 2.1.0, but i am stuck.
This is the xml:
<QueryINVAP-WS-ASSETResponse baseLanguage="ES" creationDateTime="2016-11-08T17:10:09-03:00">
<INVAP-WS-ASSETSet>
<ASSET rowstamp="265381811">
<ASSETID>1529</ASSETID>
<ASSETNUM>2503</ASSETNUM>
<DESCRIPTION>POWER CHASSIS()</DESCRIPTION>
<ITEMNUM>A000232</ITEMNUM>
<LOCATION>LOCATIONTEST</LOCATION>
<SERIALNUM>123456789</SERIALNUM>
<SITEID>TVD</SITEID>
</ASSET>
</INVAP-WS-ASSETSet>
As you can imagine, the only data I want to convert to a java object are assetid, assetnum, description, itemnum, location, SerialNum and siteid.
Until now this is what I have:
#Root(name = "QueryINVAP-WS-ASSETResponse", strict = false)
public class Activos {
#ElementList(inline = true, entry = "ASSET", type = Activo.class)
private List<Activo> activos;
#Root
class Activo {
#Attribute(name = "rowstamp")
public String rowstamp;
#Element(name = "ASSETID")
public Integer assetid;
#Element(name = "ASSETNUM")
public String assetnum;
#Element(name = "DESCRIPTION")
public String description;
#Element(name = "LOCATION")
public String location;
#Element(name = "SERIALNUM")
public String serialnum;
#Element(name = "SITEID")
public String siteid;
}
}
The error I get is:
org.simpleframework.xml.core.ValueRequiredException: Unable to satisfy #org.simpleframework.xml.ElementList(data=false, empty=true, entry=ASSET, inline=true, name=, required=true, type=class invap.invapgestionmovil.modelos.Activos$Activo) on field 'activos' private java.util.List invap.invapgestionmovil.modelos.Activos.activos for class invap.invapgestionmovil.modelos.Activos at line 1
what am I doing wrong?
Well, finally I solved the issue. I created three classes:
#Root(name = "QueryINVAP-WS-ASSETResponse", strict=false)
public class QueryINVAPWSASSETResponse {
#Element(name = "INVAP-WS-ASSETSet")
private INVAPWSASSETSet set;
}
#Root(name = "INVAP-WS-ASSETSet", strict=false)
public class INVAPWSASSETSet {
#ElementList(inline=true, name = "ASSET")
private List<Activo> activos;
}
#Root(name = "ASSET", strict = false)
public class Activo {
#Attribute(name = "rowstamp")
public String rowstamp;
#Element(name = "ASSETID")
public Integer assetid;
#Element(name = "ASSETNUM")
public String assetnum;
#Element(name = "DESCRIPTION")
public String description;
#Element(name = "LOCATION")
public String location;
#Element(name = "SERIALNUM")
public String serialnum;
#Element(name = "SITEID")
public String siteid;
}
Now when I do the call I get the asset "wrapped" with the others two classes.
Hope this help others :)
Regards

Lucene Index on Document is not working by ClassBridge hook

Problem : When I am uploading a word document, I am able to search on title(Entered while uploading the document) and summary, but when I search using the some text in document I am getting the result.
I am using "hibernate-search-engine : 4.3.0.Final, lucene-core : 3.6.2"
POM.XML
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-orm</artifactId>
<version>${hibernate.search.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-engine</artifactId>
<version>${hibernate.search.version}</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>3.6.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queries</artifactId>
<version>3.6.2</version>
<scope>runtime</scope>
</dependency>
Classes
#Entity
#SequenceGenerator(name = "sitepagecontent_seq", sequenceName = "SITEPAGECONTENT_SEQ")
#Indexed(index = "SitePageContent")
#FullTextFilterDef(name = "condition1", impl = StatusFilterFactory.class) //Filter factory with parameters
#Analyzer (impl = StandardAnalyzer.class)
#ClassBridge(name = "splitcontentfileupload",
index = Index.YES,
store = Store.YES,
impl = WordDocHandlerBridge.class,
params = #org.hibernate.search.annotations.Parameter(name = "padding", value = " ")
)
#Table(name = "SITE_PAGE_CONTENT")
public class SitePageContent extends BaseObject implements Comparable<SitePageContent> {
// Fields
private static final long serialVersionUID = -7424477214552600300L;
private Long id;
#IndexedEmbedded
private Content content;
#IndexedEmbedded
private SitePage sitePage;
private Long sequence;
Content.java
#Entity
#SequenceGenerator(name = "content_seq", sequenceName = "CONTENT_SEQ")
#Table(name = "CONTENT")
#VersionSupportModel
public class Content extends BaseObject implements Comparable<Content> {
// ------------------------------ FIELDS ------------------------------
// Fields
private static final long serialVersionUID = 1441591301055742001L;
private Long id;
#IndexedEmbedded
private UploadedFile uploadedFile;
#IndexedEmbedded
private ContentType contentType;
#Field(index = Index.YES, store = Store.YES, analyzer = #Analyzer(impl = StandardAnalyzer.class))
private String title;
private String prevTitle;
#Field(index = Index.YES, store = Store.YES, analyzer = #Analyzer(impl = StandardAnalyzer.class))
private String teaser;
private String prevTeaser;
private String linkedContentType;
private String linkedUrl;
private Boolean linkedContentPopup;
#Field(index = Index.YES, store = Store.YES)
private String status;
private EcommUser createdBy;
private EcommUser modifiedBy;
#Temporal(TemporalType.DATE)
private Date createdDate;
#Temporal(TemporalType.DATE)
private Date modifiedDate;
private String shared;
private String statusTemp;
private Set<Request> requests = new HashSet<Request>(0);
#ContainedIn
private Set<SitePageContent> sitePageContents = new HashSet<SitePageContent>(0);
private Integer version;
private Integer articleId;
private String summary;
#Field(index = Index.YES, store = Store.YES, analyzer = #Analyzer(impl = StandardAnalyzer.class))
private String description;
#Field(index = Index.YES, store = Store.YES, analyzer = #Analyzer(impl = StandardAnalyzer.class))
private String contactName;
#Field(index = Index.YES, store = Store.YES, analyzer = #Analyzer(impl = StandardAnalyzer.class))
private String contactPhone;
#Field(index = Index.YES, store = Store.YES, analyzer = #Analyzer(impl = StandardAnalyzer.class))
private String contactEmail;
#Field(index = Index.YES, store = Store.YES, analyzer = #Analyzer(impl = StandardAnalyzer.class))
private String contactPostalAddress;
WordDocHandlerBridge.java
public class WordDocHandlerBridge implements FieldBridge, ParameterizedBridge {
protected final Log log = LogFactory.getLog(getClass());
public static String paddingProperty = "padding";
private String padding = "";
public void setParameterValues(Map arg0) {
Object padding = arg0.get( paddingProperty );
if (padding != null) {
this.padding = (String) padding;
}
}
public void set(String name, Object value, Document document, LuceneOptions luceneOptions) {
String fieldValue = "";
SitePageContent sitCont = (SitePageContent) value;
Content cont = sitCont.getContent();
UploadedFile upF = cont.getUploadedFile();
if (upF != null) {
String fieldValue1 = upF.getFileContentType();
if ( fieldValue1 == null ) {
fieldValue1 = "";
}
byte[] fieldValue2 = upF.getFileContent();
if ( fieldValue2 == null ) {
fieldValue2 = new byte[0];
}
fieldValue = convertFile2String(fieldValue1, fieldValue2);
} else {
fieldValue = "";
}
Field field = new Field( name, fieldValue, luceneOptions.getStore(), luceneOptions.getIndex(), luceneOptions.getTermVector() );
field.setBoost( luceneOptions.getBoost() );
document.add( field );
}
private String convertFile2String(String type, byte[] content) {
}
When I debugged "WordDocHandlerBridge.java", I am able to see my content is set in Field and added to document, but when I search I am not getting it.
Note : There is a standolne program which recreates the Index for me, If I recreated , I can see the result.
Can any one please help me resolve this.
I solved this, Method in WordDocHandlerBridge this class "convertFile2String", actually opens the file and reads the file and create a String to set the value in the Field, problem is Code is not closing the "File" and some how Luecene is not updating , but when I added close to the PDF and POI files it all started working.
Point here is it used to work with Luecene 2.4, this might be new feature in Lucene 3.6, which is good one.

Categories

Resources