Log4j2 Custom RolloverStrategy - log4j2

Is there a way to write a custom RolloverStrategy in log4j2? I want to delete old files over 14 days and log4j2 currently doesn't support it (https://issues.apache.org/jira/browse/LOG4J2-524).
I wrote a custom Strategy and tried to implement RolloverStrategy interface but I don't see it being triggered on file rollover.

I got it working...I had to annotate my class with #Plugin as shown below:
#org.apache.logging.log4j.core.config.plugins.Plugin(name = "DeleteMaxAgeFilesStrategy", category = "Core", printObject = true)
public class DeleteMaxAgeFilesStrategy implements RolloverStrategy {
private static final Logger logger = LoggerFactory.getLogger(DeleteMaxAgeFilesStrategy.class);
private static final int DEFAULT_MAX_AGE = 14;
private final int maxAgeIndex;
public DeleteMaxAgeFilesStrategy(int maxAgeIndex) {
this.maxAgeIndex = maxAgeIndex;
}
#Override public RolloverDescription rollover(RollingFileManager manager) throws SecurityException {
purgeMaxAgeFiles(maxAgeIndex, manager);
return null;
}
#PluginFactory
public static DeleteMaxAgeFilesStrategy createStrategy(
#PluginAttribute("maxAge") final String maxAge) {
int maxAgeIndex = DEFAULT_MAX_AGE;
if (maxAge != null) {
maxAgeIndex = Integer.parseInt(maxAge);
}
return new DeleteMaxAgeFilesStrategy(maxAgeIndex);
}
/**
* Purge files older than defined maxAge. If file older than current date - maxAge delete them or else keep it.
*
* #param maxAgeIndex maxAge Index
* #param manager The RollingFileManager
*/
private void purgeMaxAgeFiles(final int maxAgeIndex, final RollingFileManager manager) {
String filename = manager.getFileName();
File file = new File(filename);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -maxAgeIndex);
Date cutoffDate = cal.getTime();
if (file.getParentFile().exists()) {
filename = file.getName().replaceAll("\\..*", "");
File[] files = file.getParentFile().listFiles(
new StartsWithFileFilter(filename, false));
for (int i = 0; i < files.length; i++) {
try {
BasicFileAttributes attr = Files.readAttributes(files[i].toPath(), BasicFileAttributes.class);
if (new Date(attr.creationTime().toMillis()).before(cutoffDate)) {
files[i].delete();
}
} catch (Exception e) {
logger.error("Unable to delete old log files at rollover", e);
}
}
}
}
class StartsWithFileFilter implements FileFilter {
private final String startsWith;
private final boolean inclDirs;
public StartsWithFileFilter(String startsWith, boolean includeDirectories) {
super();
this.startsWith = startsWith.toUpperCase();
inclDirs = includeDirectories;
}
/*
* (non-Javadoc)
*
* #see java.io.FileFilter#accept(java.io.File)
*/
public boolean accept(File pathname) {
if (!inclDirs && pathname.isDirectory()) {
return false;
} else
return pathname.getName().toUpperCase().startsWith(startsWith);
}
}
}
and here's my log4j2.xml config:
<RollingFile name="FileOut" fileName="${sys:application.log.path}/restly-api.log"
filePattern="${sys:application.log.path}/restly-api-%d{yyyy-MM-dd}.gz">
<PatternLayout pattern="%date{yyyy/MM/dd HH:mm:ss.SSS} %-5level [%t] [%logger{36}] %msg%n"/>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
</Policies>
<DeleteMaxAgeFilesStrategy maxAge="14"/>
</RollingFile>
Note: Log4j2 has implemented this feature in 2.6 release

Related

Programmatically changing the level of the Appender reference of a Logger in log4j2

I tested the solution to a similar question
How can I change the AppenderRef Level in log4j2 programmatically?
But the solution is not working for the latest version of log4j2.xml - 2.17.0 .
Usecase is slight different than the question referred to . I am configuring Log4J programmatically, through a configuration factory :
package test.config;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.config.*;
import org.apache.logging.log4j.core.config.builder.api.*;
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import simplica.util.CommonUtils;
import java.io.File;
import java.net.URI;
/**
* Configuration Factory to configure the Log4J2 Configuration programmatically
*
* #version 1.0
* #author Vishwanath Washimkar
*
*/
#Plugin(
name = "CustomConfigurationFactory",
category = ConfigurationFactory.CATEGORY)
#Order(50)
public class CustomConfigurationFactory extends ConfigurationFactory {
private LayoutComponentBuilder layoutBuilder;
private String logDirPath;
private EmailAppender emailAppender;
private String debugLoglevel;
private AppConfig appConfig;
private static ConfigurationBuilder<BuiltConfiguration> builder;
public static LoggerComponentBuilder labwareLogger;
/**
* Related to FileAppenders
*/
private final static String APPN_LAYOUT_PATTERN = "%d{MM-dd#HH:mm:ss}%-4r %-5p [%t] %37c %3x - %m%n";
public CustomConfigurationFactory(){
builder = newConfigurationBuilder();
appConfig = AppConfig.getInstance();
if(appConfig != null){
logDirPath = appConfig.getWeblimsLogPath();
emailAppender = appConfig.getEmailAppender();
}
}
#Override
protected String[] getSupportedTypes() {
return new String[] { "*" };
}
#Override
public Configuration getConfiguration(LoggerContext loggerContext, ConfigurationSource source) {
return null;
}
#Override
public Configuration getConfiguration(final LoggerContext loggerContext, final String name, final URI configLocation) {
return createConfiguration();
}
public Configuration createConfiguration() {
builder.setStatusLevel(Level.WARN);
builder.setConfigurationName("Test");
builder.setMonitorInterval("5");
layoutBuilder = builder.newLayout("PatternLayout").addAttribute("pattern", APPN_LAYOUT_PATTERN);
RootLoggerComponentBuilder rootLogger = builder.newRootLogger(Level.DEBUG);
if (CommonUtils.isValue(logDirPath)) {
File file = new File(logDirPath);
if (file.isDirectory() && file.canWrite()) {
configureWithFileAppender(builder, rootLogger);
} else {
configureWithConsoleAppender(builder, rootLogger);
}
} else {
//this is the last re course as every other configuration has failed
configureWithConsoleAppender(builder,rootLogger);
}
if(emailAppender != null){
if(!emailAppender.getEnabled()){
//add and enable email appender
configureEmailAppender(builder,rootLogger);
}
}
builder.add(rootLogger);
return builder.build();
}
private void configureEmailAppender(ConfigurationBuilder<BuiltConfiguration> builder, RootLoggerComponentBuilder rootLogger) {
String emailAppenderName = "emailAppender";
AppenderComponentBuilder smtpBuilder = builder.newAppender("emailAppender", "SMTP")//
.addAttribute("smtpUsername", emailAppender.getSMTPUsername())
.addAttribute("smtpPassword", emailAppender.getSMTPPassword())
.addAttribute("smtpProtocol", emailAppender.getSmtpProtocol())
.addAttribute("smtpHost", emailAppender.getSMTPHost())
.addAttribute("to", emailAppender.getTo())
.addAttribute("subject", emailAppender.getSubject())
.addAttribute("Cc", emailAppender.getCc())
.addAttribute("Bcc", emailAppender.getBcc())
.add(layoutBuilder);
builder.add(smtpBuilder);
if(emailAppender.getEnabled()){
rootLogger.add(builder.newAppenderRef(emailAppenderName));
}
}
private void configureWithConsoleAppender(ConfigurationBuilder<BuiltConfiguration> builder, RootLoggerComponentBuilder rootLogger) {
if(builder == null) throw new IllegalArgumentException("builder cannot be null");
// create a console appender
AppenderComponentBuilder appenderBuilder = builder.newAppender("console", "CONSOLE").addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
appenderBuilder.add(layoutBuilder);
builder.add(appenderBuilder);
rootLogger.add(builder.newAppenderRef("console"));
}
private void configureWithFileAppender(ConfigurationBuilder<BuiltConfiguration> builder, RootLoggerComponentBuilder rootLogger) {
if(builder == null) throw new IllegalArgumentException("builder cannot be null");
ComponentBuilder triggeringPolicy = builder.newComponent("Policies")
.addComponent(builder.newComponent("TimeBasedTriggeringPolicy").addAttribute("interval", "1"));
AppenderComponentBuilder debugLogBuilder = builder.newAppender("debugLog", "RollingFile")
.addAttribute("fileName", logDirPath + "\\" + "debug.log")
.addAttribute("filePattern", logDirPath + "\\" + "debug%d{MM-dd-yy}.log.gz")
.add(layoutBuilder)
.addComponent(triggeringPolicy);
AppenderComponentBuilder errorLogBuilder = builder.newAppender("errorLog", "RollingFile")
.addAttribute("fileName", logDirPath + "\\" + "error.log")
.addAttribute("filePattern", logDirPath + "\\" + "error-%d{MM-dd-yy}.log.gz")
.add(layoutBuilder)
.addComponent(triggeringPolicy);
builder.add(debugLogBuilder);
builder.add(errorLogBuilder);
labwareLogger = builder.newLogger("test", Level.DEBUG );
labwareLogger.add(builder.newAppenderRef("debugLog").addAttribute("level", getDebugLogLevel()));
labwareLogger.add(builder.newAppenderRef("errorLog").addAttribute("level", Level.ERROR));
builder.add(labwareLogger);
rootLogger.add(builder.newAppenderRef("debugLog").addAttribute("level", Level.WARN));
rootLogger.add(builder.newAppenderRef("errorLog").addAttribute("level", Level.ERROR));
}
private Level getDebugLogLevel() {
String logLevel = appConfig.getDebugLogLevel();
if("DEBUG".equalsIgnoreCase(logLevel)){
return Level.DEBUG;
}
if("INFO".equalsIgnoreCase(logLevel)){
return Level.INFO;
}
if("ERROR".equalsIgnoreCase(logLevel)){
return Level.ERROR;
}
if("WARN".equalsIgnoreCase(logLevel)){
return Level.WARN;
}
if("FATAL".equalsIgnoreCase(logLevel)){
return Level.FATAL;
}
if("TRACE".equalsIgnoreCase(logLevel)){
return Level.TRACE;
}
if("ALL".equalsIgnoreCase(logLevel)){
return Level.ALL;
}
//at the end lets just return the
return Level.WARN;
}
}
Then I am trying to change the logging level for appenderRef in a servlet.
package com.example.testwebapp;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
#WebServlet(name = "helloServlet", value = "/hello-servlet")
public class HelloServlet extends HttpServlet {
private String message;
public void init() {
message = "Hello World! from Vish";
}
int i =0;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
if(i > 2) {
LoggerContext context = (LoggerContext) LogManager.getContext(false);
Configuration config = context.getConfiguration();
LoggerConfig labware = config.getLoggerConfig("labware");
labware.removeAppender("debugLog");
labware.addAppender(config.getAppender("debugLog"), Level.DEBUG, null);
// This causes all Loggers to refetch information from their LoggerConfig.
context.updateLoggers();
}
i++;
response.setContentType("text/html");
getLog().debug("DEBUG log entryc 11111 ");
getLog().info("INFO log entry ");
getLog().error("ERROR log entry ");
getLog().warn("############# WAR log entry ");
// Hello
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>" + message + " World </h1>");
out.println("</body></html>");
}
public void destroy() {
}
/**
* #return The logger for the class.
*/
private static Log getLog() {
return LogFactory.getLog(HelloServlet.class);
}
}

Java - Writing method for public int indexOf(T element) in a double linked list

Below I have the int indexOf(T element) method for a double linked list. I need help with the code to make sure it functions properly. The method should return the first occurence of the element in the list or -1 if element is not in the list. Below is the node class it uses. The IUDoubleLinkedList.java class implements IndexedUnsortedList.java which is where the indexOf method comes from. I tried using my indexOf method from my single linked list class but it's not the same so I hope to understand why it would be different and what code is used that is different between the the single and double linked list.
public class IUDoubleLinkedList<T> implements IndexedUnsortedList<T> {
private Node<T> head, tail;
private int size;
private int modCount;
public IUDoubleLinkedList() {
head = tail = null;
size = 0;
modCount = 0;
This is the indexOf(T element) method
#Override
public int indexOf(T element) {
// TODO Auto-generated method stub
return 0;
}
Below is the Node.java class it uses
public class Node<T> {
private Node<T> nextNode;
private T element;
private Node<T> prevNode;
/**
* Creates an empty node.
*/
public Node() {
nextNode = null;
element = null;
}
/**
* Creates a node storing the specified element.
*
* #param elem
* the element to be stored within the new node
*/
public Node(T element) {
nextNode = null;
this.element = element;
setPrevNode(null);
}
/**
* Returns the node that follows this one.
*
* #return the node that follows the current one
*/
public Node<T> getNextNode() {
return nextNode;
}
/**
* Sets the node that follows this one.
*
* #param node
* the node to be set to follow the current one
*/
public void setNextNode(Node<T> nextNode) {
this.nextNode = nextNode;
}
/**
* Returns the element stored in this node.
*
* #return the element stored in this node
*/
public T getElement() {
return element;
}
/**
* Sets the element stored in this node.
*
* #param elem
* the element to be stored in this node
*/
public void setElement(T element) {
this.element = element;
}
#Override
public String toString() {
return "Element: " + element.toString() + " Has next: " + (nextNode != null);
}
public Node<T> getPrevNode() {
return prevNode;
}
public void setPrevNode(Node<T> prevNode) {
this.prevNode = prevNode;
}
}
Check the following code, hope I helped you!
Insert item at head as well as tail end
public void insertItem(T elem) {
/* if head and tail both are null*/
if(head == null || tail == null) {
head = new Node<T>(elem);
tail = new Node<T>(elem);
}else {
Node<T> tempItem = new Node<T>();
tempItem.setElement(elem);
/* insert at head end /*
tempItem.setNextNode(head);
head.setPrevNode(tempItem);
head = tempItem;
Node<T> tempItem1 = new Node<T>();
tempItem1.setElement(elem);
/* append at tail end */
tail.setNextNode(tempItem1);
tempItem1.setPrevNode(tail);
tail = tempItem1;
}
size += 1;
}
Print item from head end
public void printItemsFromHead() {
while(head != null) {
System.out.print(head.getElement()+" --> ");
head = head.getNextNode();
}
}
Print item from tail end
public void printItemsFromTail() {
Node<T> temp = null;
while(tail != null) {
temp = tail;
System.out.print(tail.getElement()+" --> ");
tail = tail.getPrevNode();
}
/*System.out.println();
while(temp != null) {
System.out.print(temp.getElement()+" --> ");
temp = temp.getNextNode();
}*/
}
Implemention of indexOf function
#Override
public int indexOf(T element) {
int result = -1;
int headIndex = 0;
int tailIndex = size;
while(head != null && tail != null) {
if(head.getElement().equals(element)) {
result = headIndex;
break;
}
/*
if(tail.getElement().equals(element)) {
result = tailIndex;
break;
} */
head = head.getNextNode();
tail = tail.getPrevNode();
headIndex += 1;
tailIndex -= 1;
}
return result;
}
Driver class
public class Driver {
#SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> void main(String[] args) {
UDoubleLinkedList uDoubleLinkedList = new UDoubleLinkedList();
uDoubleLinkedList.insertItem(1);
uDoubleLinkedList.insertItem(2);
uDoubleLinkedList.insertItem(3);
uDoubleLinkedList.insertItem(4);
uDoubleLinkedList.insertItem(5);
System.out.println(uDoubleLinkedList.indexOf(1));
}
}

From java Object prepare the edi data

I am newbie in edi data. I am using smooks api to read the edi data and able to parse it into java object. I want to convert java object to edi data for that i am not getting much information. Here is the example i am trying to read from edi file and creating the java object -
customOrder.edi - COR*130*PINGPONG02*You got it to work*1230
---------------
POJO -
------
public class CustomOrder implements Serializable{
private int number;
private String sender;
private String message;
private int price;
// setter and getter
}
custom-order-mapping.xml -
-------------------------
<?xml version="1.0" encoding="UTF-8"?><medi:edimap xmlns:medi="http://www.milyn.org/schema/edi-message-mapping-1.3.xsd">
<medi:description name="DVD Order" version="1.0" />
<medi:delimiters segment="
" field="*" component="^" sub-component="~" />
<medi:segments xmltag="CustomOrder">
<medi:segment segcode="COR" xmltag="co">
<medi:field xmltag="number" />
<medi:field xmltag="sender" />
<medi:field xmltag="message" />
<medi:field xmltag="price" />
</medi:segment>
</medi:segments>
</medi:edimap>
smooks-config.xml -
------------------
<?xml version="1.0"?>
<smooks-resource-list
xmlns="http://www.milyn.org/xsd/smooks-1.1.xsd"
xmlns:edi="http://www.milyn.org/xsd/smooks/edi-1.1.xsd"
xmlns:jb="http://www.milyn.org/xsd/smooks/javabean-1.2.xsd"
xmlns:core="http://www.milyn.org/xsd/smooks/smooks-core-1.4.xsd">
<edi:reader mappingModel="/example/custom-order-mapping.xml" />
<jb:bean beanId="customer" class="example.model.CustomOrder" createOnElement="co">
<!-- Customer bindings... -->
<jb:value property="number" data="#/number" decoder="Integer"/>
<jb:value property="sender" data="#/sender" decoder="String"/>
<jb:value property="message" data="#/message" decoder="String"/>
<jb:value property="price" data="#/price" decoder="Integer"/>
</jb:bean>
</smooks-resource-list>
Main method -
--------------
Main smooksMain = new Main();
ExecutionContext executionContext = smooksMain.smooks.createExecutionContext();
org.milyn.payload.JavaResult result = smooksMain.runSmooksTransform(executionContext);
CustomOrder custOrder = (CustomOrder) result.getBean("customer");
// Need to get to edi data from java object custOrder
// Please help me - this part of code
I want to prepare edi data from java object. If any other api/framework apart from Smooks which will do the same, it will be fine for me.please let me know, Thanks.
I searched about it and get to know from smooks forum that to prepare edi data from java object, we have to use Edifact Java Compiler(EJC).
Above example is to prepare java object from edi data.
Pojo class have to implement EDIWritable and override the write method.Here is the changed Pojo class -
public class CustomOrder implements Serializable, EDIWritable{
private int number;
private IntegerDecoder numberDecoder;
private String sender;
private String message;
private int price;
private IntegerDecoder priceDecoder;
public CustomOrder() {
numberDecoder = new IntegerDecoder();
priceDecoder = new IntegerDecoder();
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public void setSender(String sender) {
this.sender = sender;
}
public String getSender() {
return sender;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public void write(Writer writer, Delimiters delimiters) throws IOException {
// TODO Auto-generated method stub
Writer nodeWriter = writer;
if(number != 0) {
nodeWriter.write(delimiters.escape(numberDecoder.encode(number)));
}
nodeWriter.write(delimiters.getField());
if(sender != null) {
nodeWriter.write(delimiters.escape(sender.toString()));
}
nodeWriter.write(delimiters.getField());
if(message != null) {
nodeWriter.write(delimiters.escape(message.toString()));
}
nodeWriter.write(delimiters.getField());
if(price != 0) {
nodeWriter.write(delimiters.escape(priceDecoder.encode(price)));
}
//nodeWriter.write(delimiters.getField());
writer.write(delimiters.getSegmentDelimiter());
writer.flush();
}
}
Next, we have to prepare the Factory of the pojo class -
CustomOrderFactory
public class CustomOrderFactory {
private Smooks smooks;
private Delimiters delimiters;
public static CustomOrderFactory getInstance() throws IOException, SAXException {
return new CustomOrderFactory();
}
public void addConfigurations(InputStream resourceConfigStream) throws SAXException, IOException {
smooks.addConfigurations(resourceConfigStream);
}
public void toEDI(CustomOrder instance, Writer writer) throws IOException {
instance.write(writer, delimiters);
}
private CustomOrderFactory() throws IOException, SAXException {
smooks = new Smooks(CustomOrderFactory.class.getResourceAsStream("smooks-config.xml"));
System.out.println("smooks is prepared");
try {
Edimap edimap = EDIConfigDigester.digestConfig(CustomOrderFactory.class.getResourceAsStream("custom-order-mapping.xml"));
System.out.println("ediMap is prepared");
delimiters = edimap.getDelimiters();
System.out.println("delimeter is prepared");
} catch(EDIConfigurationException e) {
IOException ioException = new IOException("Exception reading EDI Mapping model.");
ioException.initCause(e);
throw ioException;
}
}
}
Once CustomOrder object is ready, as shown above in Main class. We have to use this object to convert to edi data format. Here is the complete Main class -
Main class
----------
Main smooksMain = new Main();
ExecutionContext executionContext = smooksMain.smooks.createExecutionContext();
org.milyn.payload.JavaResult result = smooksMain.runSmooksTransform(executionContext);
CustomOrder custOrder = (CustomOrder) result.getBean("customer");
// Prepare edi data from java object custOrder
CustomOrderFactory customOrderFactory = CustomOrderFactory.getInstance();
OutputStream os = new FileOutputStream("createdEDIFile.edi");
customOrderFactory.toEDI(custOrder, new OutputStreamWriter(os));
System.out.println("Edi file is created from java object");
Thats it. Hope it would help. Thanks.

Partial Unmarshalling of an XML using JAXB to skip some xmlElement

I want to unmarshal an XML file to java object using JAXB. The XML file is very large and contains some nodes which I want to skip in some cases to improve performance as these elements are non editable by client java program.
A sample XML is as follows:
<Example id="10" date="1970-01-01" version="1.0">
<Properties>...</Properties>
<Summary>...</Summary>
<RawData>
<Document id="1">...</Document>
<Document id="2">...</Document>
<Document id="3">...</Document>
------
------
</RawData>
<Location></Location>
<Title></Title>
----- // more elements
</Example>
I have two use cases:
unmarshal into Example object which contains Properties, Summaries, RawData etc. without skipping any RawData. (already done this part)
unmarshal into Example object which exclude RawData. Elements nested in RawData is very large so do not want to read this in this use case.
Now I want to unmarshal the XML such that RawData can be skipped. I have tried the technique provided at this link.
Using technique provided in above link also skips all elements which come after RawData.
I have fixed the issue with XMLEventReader with following code:
public class PartialXmlEventReader implements XMLEventReader {
private final XMLEventReader reader;
private final QName qName;
private boolean skip = false;
public PartialXmlEventReader(final XMLEventReader reader, final QName element) {
this.reader = reader;
this.qName = element;
}
#Override
public String getElementText() throws XMLStreamException {
return reader.getElementText();
}
#Override
public Object getProperty(final String name) throws IllegalArgumentException {
return reader.getProperty(name);
}
#Override
public boolean hasNext() {
return reader.hasNext();
}
#Override
public XMLEvent nextEvent() throws XMLStreamException {
while (isEof(reader.peek())) {
reader.nextEvent();
}
return reader.nextEvent();
}
#Override
public XMLEvent nextTag() throws XMLStreamException {
return reader.nextTag();
}
#Override
public XMLEvent peek() throws XMLStreamException {
return reader.peek();
}
#Override
public Object next() {
return reader.next();
}
#Override
public void remove() {
reader.remove();
}
#Override
public void close() throws XMLStreamException {
reader.close();
}
private boolean isEof(final XMLEvent e) {
boolean returnValue = skip;
switch (e.getEventType()) {
case XMLStreamConstants.START_ELEMENT:
final StartElement se = (StartElement) e;
if (se.getName().equals(qName)) {
skip = true;
returnValue = true;
}
break;
case XMLStreamConstants.END_ELEMENT:
final EndElement ee = (EndElement) e;
if (ee.getName().equals(qName)) {
skip = false;
}
break;
}
return returnValue;
}
}
While Unmarshalling just pass this eventReader to the unmarshal method
final JAXBContext context = JAXBContext.newInstance(classes);
final Unmarshaller um = context.createUnmarshaller();
Reader reader = null;
try {
reader = new BufferedReader(new FileReader(xmlFile));
final QName qName = new QName("RawData");
final XMLInputFactory xif = XMLInputFactory.newInstance();
final XMLEventReader xmlEventReader = xif.createXMLEventReader(reader);
final Example example =
(Example) um.unmarshal(new PartialXmlEventReader(xmlEventReader, qName));
}
} finally {
IOUtils.closeQuietly(reader);
}
I hope this would help
try {
// First create a new XMLInputFactory
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
// Setup a new eventReader
InputStream in = new FileInputStream("myXml");
XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
// Read the XML document
Example example = null;
while (eventReader.hasNext()) {
XMLEvent event = eventReader.nextEvent();
if (event.isStartElement()) {
StartElement startElement = event.asStartElement();
// If we have a example element we create a new example
if (startElement.getName().getLocalPart().equals("Example")) {
example = new Example();
// We read the attributes from this tag and add the date
// and id attribute to our object
Iterator<Attribute> attributes = startElement
.getAttributes();
while (attributes.hasNext()) {
Attribute attribute = attributes.next();
if (attribute.getName().toString().equals("date")) {
example.setDate(attribute.getValue());
} else if (attribute.getName().toString().equals("id")) {
example.setId(attribute.getValue());
}
}
}
//get the Properties tag and add to object example
if (event.isStartElement()) {
if (event.asStartElement().getName().getLocalPart()
.equals("Properties")) {
event = eventReader.nextEvent();
example.setProperites(event.asCharacters().getData());
continue;
}
}
//get the Summary tag and add to object example
if (event.asStartElement().getName().getLocalPart()
.equals("Summary")) {
event = eventReader.nextEvent();
example.setSummary(event.asCharacters().getData());
continue;
}
// when you encounter the Rawdata tag just continue
//without adding it to the object created
if (event.asStartElement().getName().getLocalPart()
.equals("Rawdata")) {
event = eventReader.nextEvent();
// don't do anything
continue;
}
//get the location tag and add to object example
if (event.asStartElement().getName().getLocalPart()
.equals("Location")) {
event = eventReader.nextEvent();
example.setLocation(event.asCharacters().getData());
continue;
}
// read and add other elements that can be added
}
// If we reach the end of an example element/tag i.e closing tag
if (event.isEndElement()) {
EndElement endElement = event.asEndElement();
if (endElement.getName().getLocalPart().equals("Example")) {
//do something
}
}
}
} catch (FileNotFoundException | XMLStreamException e) {
}

How to sort the choices in a Wicket dropdown according to the current user locale?

I have the following issue:
a drop down with a list of elements
each of these elements has a fixed key, which is used by the IChoiceRenderer implementation to look up the localized version of the key (it's a standard, utility renderer implemented in a different package)
the list of localized keys is in a properties file, linked to the panel which instantiates the dropdown.
Is there an elegant/reusable solution to have the dropdown display its elements sorted alphabetically ?
In the end, I think using the render is probably the best approach. To make it reusable and efficient, I isolated this in a Behavior.
Here's the code:
import org.apache.wicket.Component;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.markup.html.form.AbstractChoice;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import static java.util.Arrays.sort;
/**
* This {#link Behavior} can only be used on {#link AbstractChoice} subclasses. It will sort the choices
* according to their "natural display order" (i.e. the natural order of the display values of the choices).
* This assumes that the display value implements {#link Comparable}. If this is not the case, you should
* provide a comparator for the display value. An instance of this class <em>cannot be shared</em> between components.
* Because the rendering can be costly, the sort-computation is done only once, by default,
* unless you set to <code>false</code> the <code>sortOnlyOnce</code> argument in the constructor.
*
* #author donckels (created on 2012-06-07)
*/
#SuppressWarnings({"unchecked"})
public class OrderedChoiceBehavior extends Behavior {
// ----- instance fields -----
private Comparator displayValueComparator;
private boolean sortOnlyOnce = true;
private boolean sorted;
// ----- constructors -----
public OrderedChoiceBehavior() {
}
public OrderedChoiceBehavior(boolean sortOnlyOnce) {
this.sortOnlyOnce = sortOnlyOnce;
}
public OrderedChoiceBehavior(boolean sortOnlyOnce, Comparator displayValueComparator) {
this.sortOnlyOnce = sortOnlyOnce;
this.displayValueComparator = displayValueComparator;
}
// ----- public methods -----
#Override
public void beforeRender(Component component) {
if (this.sorted && this.sortOnlyOnce) { return;}
AbstractChoice owner = (AbstractChoice) component;
IChoiceRenderer choiceRenderer = owner.getChoiceRenderer();
List choices = owner.getChoices();
// Temporary data structure: store the actual rendered value with its initial index
Object[][] displayValuesWithIndex = new Object[choices.size()][2];
for (int i = 0, valuesSize = choices.size(); i < valuesSize; i++) {
Object value = choices.get(i);
displayValuesWithIndex[i][0] = choiceRenderer.getDisplayValue(value);
displayValuesWithIndex[i][1] = i;
}
sort(displayValuesWithIndex, new DisplayValueWithIndexComparator());
List valuesCopy = new ArrayList(choices);
for (int i = 0, length = displayValuesWithIndex.length; i < length; i++) {
Object[] displayValueWithIndex = displayValuesWithIndex[i];
int originalIndex = (Integer) displayValueWithIndex[1];
choices.set(i, valuesCopy.get(originalIndex));
}
this.sorted = true;
}
public Comparator getDisplayValueComparator() {
return this.displayValueComparator;
}
// ----- inner classes -----
private class DisplayValueWithIndexComparator implements Comparator<Object[]> {
// ----- Comparator -----
public int compare(Object[] left, Object[] right) {
Object leftDisplayValue = left[0];
Object rightDisplayValue = right[0];
if (null == leftDisplayValue) { return -1;}
if (null == rightDisplayValue) { return 1;}
if (null == getDisplayValueComparator()) {
return ((Comparable) leftDisplayValue).compareTo(rightDisplayValue);
} else {
return getDisplayValueComparator().compare(leftDisplayValue, rightDisplayValue);
}
}
}
}
Use this extension of DropDownChoice using Java's Collator (basically locale sensitive sorting - take national characters and national sorting rules into account)
Code tested with Wicket 6 and Java 5+:
import java.text.Collator;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import org.apache.wicket.Session;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.model.IModel;
import com.google.common.collect.Ordering;
/**
* DropDownChoice which sort its choices (or in HTML's terminology select's options) according it's localized value
* and using current locale based Collator so it's sorted how it should be in particular language (ie. including national characters,
* using right order).
*
* #author Michal Bernhard michal#bernhard.cz 2013
*
* #param <T>
*/
public class OrderedDropDownChoice<T> extends DropDownChoice<T> {
public OrderedDropDownChoice(String id, IModel<? extends List<? extends T>> choices, IChoiceRenderer<? super T> renderer) {
super(id, choices, renderer);
}
public OrderedDropDownChoice(String id, IModel<? extends List<? extends T>> choices) {
super(id, choices);
}
public OrderedDropDownChoice(String id) {
super(id);
}
public OrderedDropDownChoice(
String id,
IModel<T> model,
IModel<? extends List<? extends T>> choices,
IChoiceRenderer<? super T> renderer) {
super(id, model, choices, renderer);
}
#Override
public List<? extends T> getChoices() {
List<? extends T> unsortedChoices = super.getChoices();
List<? extends T> sortedChoices = Ordering.from(displayValueAlphabeticComparator()).sortedCopy(unsortedChoices);
return sortedChoices;
}
private Collator localeBasedTertiaryCollator() {
Locale currentLocale = Session.get().getLocale();
Collator collator = Collator.getInstance(currentLocale);
collator.setStrength(Collator.TERTIARY);
return collator;
}
private Comparator<T> displayValueAlphabeticComparator() {
final IChoiceRenderer<? super T> renderer = getChoiceRenderer();
return new Comparator<T>() {
#Override
public int compare(T o1, T o2) {
Object o1DisplayValue = renderer.getDisplayValue(o1);
Object o2DisplayValue = renderer.getDisplayValue(o2);
return localeBasedTertiaryCollator().compare(o1DisplayValue, o2DisplayValue);
}
};
}
}
Copied from https://gist.github.com/michalbcz/7236242
If you want a Wicket-based solution you can try to sort the list with something like that:
public class ChoiceRendererComparator<T> implements Comparator<T> {
private final IChoiceRenderer<T> renderer;
public ChoiceRendererComparator(IChoiceRenderer<T> renderer) {
this.renderer = renderer;
}
#SuppressWarnings("unchecked")
public int compare(T o1, T o2) {
return ((Comparable<Object>) renderer.getDisplayValue(o1)).compareTo(renderer.getDisplayValue(o2));
}
}
Usage:
List<Entity> list = ...
IChoiceRenderer<Entity> renderer = ...
Collections.sort(list, new ChoiceRendererComparator<Entity>(renderer));
DropDownChoice<Entity> dropdown = new DropDownChoice<Entity>("dropdown", list, renderer);
The solution we use at my company is Javascript based, we set a special css class on the dropdowns we want to be sorted, and a little jQuery trick does the sort.
Facing the same problem, I moved part of the localisation data from my XMLs to the database, implemented a matching Resolver and was able to use the localized Strings for sorting.
The table design and hibernate configuration was kind of tricky and is described here: Hibernate #ElementCollection - Better solution needed.
The ResourceLoader is along these lines:
public class DataBaseStringResourceLoader extends ComponentStringResourceLoader {
private static final transient Logger logger = Logger
.getLogger(DataBaseStringResourceLoader.class);
#Inject
private ISomeDAO someDao;
#Inject
private IOtherDao otherDao;
#Inject
private IThisDAO thisDao;
#Inject
private IThatDAO thatDao;
#Override
public String loadStringResource(Class<?> clazz, String key, Locale locale,
String style, String variation) {
String resource = loadFromDB(key, new Locale(locale.getLanguage()));
if (resource == null) {
resource = super.loadStringResource(clazz, key, locale, style, variation);
}
return resource;
}
private String loadFromDB(String key, Locale locale) {
String resource = null;
if (locale.getLanguage() != Locale.GERMAN.getLanguage()
&& locale.getLanguage() != Locale.ENGLISH.getLanguage()) {
locale = Locale.ENGLISH;
}
if (key.startsWith("some") || key.startsWith("other")
|| key.startsWith("this") || key.startsWith("that")) {
Integer id = Integer.valueOf(key.substring(key.indexOf(".") + 1));
ILocalizedObject master;
if (key.startsWith("some")) {
master = someDao.findById(id);
} else if (key.startsWith("other")) {
master = otherDao.findById(id);
} else if (key.startsWith("this") ){
master = thisDao.findById(id);
} else {
master = thatDao.findById(id);
}
if (master != null && master.getNames().get(locale) != null) {
resource = master.getNames().get(locale).getName();
} else if (master == null) {
logger.debug("For key " + key + " there is no master.");
}
}
return resource;
}
[...]
}

Resources