This is my java project strucutre
src/main/java
|_LoadXml.java
src/main/resources/
|_config.xml
src/test/java
src/test/resources
I want to load the following xml file using apache-common configuration library.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Here are some favorites</comment>
<entry key="favoriteSeason">summer</entry>
<entry key="favoriteFruit">pomegranate</entry>
<entry key="favoriteDay">today</entry>
</properties>
I have written the following code snippet for LoadXml.java
public static void configure() {
try {
XMLConfiguration config = new XMLConfiguration("config.xml");
node = config.getRootElementName();
} catch (ConfigurationException e) {
e.printStackTrace();
}
return;
}
I want to load xml keys and values into a map with hierarchy nodes seperated by a "."(dot). It would be greatly helpful if someone can help me in this regard.
Load xml keys and values into a Map:
public static Map<String, String> parseConfig() throws ConfigurationException {
XMLConfiguration config = new XMLConfiguration("config.xml");
NodeList list = config.getDocument().getElementsByTagName("entry");
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
String key = node.getAttributes().getNamedItem("key").getTextContent();
String val = node.getTextContent();
map.put(key, val);
}
System.out.println(map);
return map;
}
OUTPUT:
{favoriteSeason=summer, favoriteFruit=pomegranate, favoriteDay=today}
Just use the config.getRootNode() and then node.getChildren("entry")
XMLConfiguration config = new XMLConfiguration("_config.xml");
Map<String, String> configMap = new HashMap<String, String>();
ConfigurationNode node = config.getRootNode();
for (ConfigurationNode c : node.getChildren("entry"))
{
String key = (String)c.getAttribute(0).getValue();
String value = (String)c.getValue();
configMap.put(key, value);
}
Then you can just do:
System.out.println(configMap.get("favoriteSeason")); // prints: summer
Related
I am trying to implement Hazelcast caching with Camel blueprint. But I couldn't accomplish.I am able to create a hazelcast instance through java code (not through hazelcast XML config file). Instance has been craeted, but the cache loader class is not called during the instance creation (even though initialization method is EAGER). Attached some of the code snippets.
Let me know, if anyone come across this.
Code:
Hazelcast config
public class ConfigHack extends Config {
public ConfigHack(String instanceName ){
super(instanceName);
System.out.println("Going to create Hazelcast instance
................"+instanceName);
TcpIpConfig tcpIpConfig = new TcpIpConfig();
List membersList = new ArrayList<String>();
membersList.add("localhost");
tcpIpConfig.setMembers(membersList);
MulticastConfig multicastConfig = new MulticastConfig();
multicastConfig.setEnabled(true);
JoinConfig join = new JoinConfig();
join.setTcpIpConfig(tcpIpConfig);
join.setMulticastConfig(multicastConfig);
NetworkConfig networkConfig = new NetworkConfig();
networkConfig.setPort(5701);
networkConfig.setPortAutoIncrement(true);
networkConfig.setJoin(join);
GroupConfig groupConfig = new GroupConfig();
groupConfig.setName("devuser");
groupConfig.setPassword("devpassword");
MapStoreConfig mapStoreConfig = new MapStoreConfig();
//Absolute path in class name field below
mapStoreConfig.setClassName("VehicleCacheLoader");
mapStoreConfig.setImplementation(new VehicleCacheLoader());
mapStoreConfig.setEnabled(true);
mapStoreConfig.setInitialLoadMode(InitialLoadMode.EAGER);
mapStoreConfig.setWriteDelaySeconds(500);
MapConfig mapConfig = new MapConfig();
mapConfig.setName("vehicleMap");
mapConfig.setBackupCount(2);
mapConfig.setMaxIdleSeconds(1000000);
mapConfig.setEvictionPercentage(30);
mapConfig.setEvictionPolicy(EvictionPolicy.LFU);
mapConfig.setMapStoreConfig(mapStoreConfig);
Map<String,MapConfig> mapConfigs = new HashMap<String,MapConfig>();
mapConfigs.put("vehicleMap", mapConfig);
//config.setMapConfigs(mapConfigs);
addMapConfig(mapConfig);
setGroupConfig(groupConfig);
setNetworkConfig(networkConfig);
}
}
Cache loader class:
public class VehicleCacheLoader implements MapLoader<String, VehicleVO> {
#Override
public VehicleVO load(String paramK) {
System.out.println("Calling load method for Key " + paramK);
VehicleVO vehicleVO = new VehicleVO();
vehicleVO.setCustId("XXX");
vehicleVO.setVehicleHeader("XXX");
vehicleVO.setVehicleInitial("001");
vehicleVO.setVehicleNumber("1234");
vehicleVO.setVehicleObjId(paramK);
return vehicleVO;
}
#Override
public Map<String, VehicleVO> loadAll(Collection<String> paramCollection) {
System.out.println("Calling Load all values() " + "Got key = ");
VehicleVO vehicleVO = null;
Map<String, VehicleVO> vehicleDataMap = new HashMap<String, VehicleVO>();
for (String paramKey : paramCollection) {
System.out.println("Calling ...." + paramKey);
vehicleVO = new VehicleVO();
vehicleVO.setCustId("XXX");
vehicleVO.setVehicleHeader("XXX");
vehicleVO.setVehicleInitial("001");
vehicleVO.setVehicleNumber("1234");
vehicleVO.setVehicleObjId(paramKey);
vehicleDataMap.put(paramKey, vehicleVO);
}
return vehicleDataMap;
}
#Override
public Set<String> loadAllKeys() {
System.out.println("Calling Load all keys() ");
Set<String> vehicleKeys = new HashSet<String>();
vehicleKeys.add("XXX001");
vehicleKeys.add("XXX002");
vehicleKeys.add("XXX003");
vehicleKeys.add("XXX004");
return vehicleKeys;
}
}
Blueprint config:
-----------------
<bean id="hazelcastInstance" class="com.hazelcast.core.Hazelcast"
factory-method="newHazelcastInstance" destroy-method="shutdown">
<argument ref="hazelcastConfig"/>
</bean>
<bean id="hazelcastConfig" class="xx.yy.zz.ss.tt.cache.ConfigHack">
<argument value="TestInstance" />
</bean>
The line
mapConfigs.put("vehicleMap", mapConfig);
defines the configuration that will be used for maps with names matching "vehicaleMap".
In order to create such a map you need to run an operation against it, such as
hazelcastInstance.getMap("vehicleMap");
The distinction is clearer if the configuration was:
mapConfigs.put("vehicleMap*", mapConfig);
This would be used when you create a map named "vehicleMap1", or "vehicleMap123".
The configuration defines the configuration which will be used if needed. It's not needed til you first access the map, which is when the maps are created.
"EAGER" here refers to how the map loader is run, not to how the map is created.
I have a Map in managed bean
private Map<FaseProducao, Set<FichaTecnicaOperacao>> fichasTecnicasOperacaoResumo;
that reference to entity FichaTecnica:
public class FichaTecnica{
//...
private Set<FichaTecnicaOperacao> operacoes;
}
which I need to pass as a parameter on a beans.put () to generate an xls with jett:
public void createRelatorioFichaTecnica(FichaTecnica fichaTecnica) throws IOException {
//ommited...
Map<String, Object> beans = new HashMap<String, Object>();
beans.put("operacaoResumo", fichasTecnicasOperacaoResumo);
try (ByteArrayOutputStream saida = new ByteArrayOutputStream();
InputStream template = this.getClass().getResourceAsStream("/templates/jett/fichaTecnica.xls");
Workbook workbook = transformer.transform(template, beans);) {
//ommited...
}
}
when the xls is generated the exception happens:
WARNING [javax.enterprise.resource.webcontainer.jsf.lifecycle] (default task-28) #{ProdutoManagedBean.createRelatorioFichaTecnica(row)}: net.sf.jett.exception.AttributeExpressionException: Expected a "java.util.Collection" for "items", got a "java.util.HashMap": "${operacaoResumo}".
so I'm not understanding this error because a Map is a correct collection? So why does not jett recognize it in items = "$ {operacaoResumo}"? I created this forEach based on the link on the site:
http://jett.sourceforge.net/tags/forEach.html
As #rgettman said I did:
public void createRelatorioFichaTecnica(FichaTecnica fichaTecnica) throws IOException {
//ommited...
Map<String, Object> beans = new HashMap<String, Object>();
beans.put("operacaoResumo", fichasTechicasOperacaoResumo.keySet());
}
thank you all!
Sending the request to Server with the below xml for downloading
<?xml version="1.0" encoding="UTF-8"?>
<ResourceSet xmlns:v01"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<cycleTime>123</cycleTime>
<object>
<sourceUrl>http://10.34894.494/23.png</sourceUrl>
<accessUrl>http://10.126.45.72/cme/23.png</accessUrl>
<objectMetadata>
<headerName>Content-Length</headerName>
<headerName>E-Tag</headerName>
</objectMetadata>
</object>
<object>
<sourceUrl>http://10.84375.72/cme/23.png</sourceUrl>
<accessUrl>http://10.4575.572/cme/logo/23.png</accessUrl>
<objectMetadata>
<headerName>Content-Length</headerName>
<headerName>E-Tag</headerName>
</objectMetadata>
</object>
</ResourceSet>
There are 2 objects and which has same source URL and different Access URl .
My job is to download the image only once because source URL’s are duplicated .
Am iterating through the objects , but how I will know two objects has same source URL to download ?
There are 2 objects and which has same source URL and different Access URl .
My job is to download the image only once because source URL’s are duplicated .
Am iterating through the objects , but how I will know two objects has same source URL to download ?
public void download_resourceset_object_urls_images_to_local() throws Throwable {
List<String> sourceURis = GFDUtils.getSourceOrAccessURLs(xmlPath + xmlFileName, "sourceUrl");
dwInfoList = new HashMap<String, DownloadFileInfo>();
NSAUtils.removeFiles(ConfigLoader.DOWNLOAD_DIR);
boolean flag = HTTPClientFileDownload.downloadFile(sourceURis, ConfigLoader.DOWNLOAD_DIR, dwInfoList);
if (flag == true) {
logger.info("All URL files / images are downloaded successfully....");
} else
throw new GenericException("Files are not available / Failed download ");
}
here am iterating Xml and getting the Source URL to download
public static List<String> getSourceOrAccessURLs(String xmlPath, String urlname) throws IOException {
XStream xs = new XStream();
boolean flag = XMLValidation.validateXMLSchema(xmlPath);
File file = new File(xmlPath);
String xml = FileUtils.readFileToString(file);
if (flag == true) {
List<String> urls = new ArrayList<>();
try {
xs.processAnnotations(Resourceset.class);
Resourceset rs = (Resourceset) xs.fromXML(xml);
List<ResourcesetObject> rsoOject = rs.getResourcesetObject();
for (ResourcesetObject resourcesetObject : rsoOject) {
if (urlname.equals("sourceUrl")) {
urls.add(resourcesetObject.getSourceUrl());
} else {
urls.add(resourcesetObject.getAccessUrl());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return urls;
}
return null;
}
This URL Am passing for downloading.
Please help
Thanks,
If I have a set of properties, I understand that Springboot's relaxed data binder will read in a list of properties (or yaml) and populate the matching object. Like so:
Properties props = new Properties();
props.put("devices.imports[0]","imp1");
props.put("devices.imports[1]","imp2");
props.put("devices.definitions[0].id","first");
props.put("devices.definitions[1].id", "second");
DeviceConfig conf = new DeviceConfig();
PropertiesConfigurationFactory<DeviceConfig> pcf = new PropertiesConfigurationFactory<>(conf);
pcf.setProperties(props);
conf = pcf.getObject();
assertThat(conf.getDefinitions()).hasSize(2); //Definitions is coming in as 0 instead of the expected 2
DeviceConfig looks like this:
#ConfigurationProperties(prefix="devices")
public class DeviceConfig {
private List<String> imports = new ArrayList<>();
private List<DeviceDetailsProperties> definitions = new ArrayList<>();
public List<String> getImports() {
return this.imports;
}
public List<DeviceDetailsProperties> getDefinitions() {
return definitions;
}
public void setImports(List<String> imports) {
this.imports = imports;
}
public void setDefinitions(List<DeviceDetailsProperties> definitions) {
this.definitions = definitions;
}
}
DeviceDetailsProperties just has an id field with getters/setters.
Strangely neither the definitions (objects) or imports (Strings) are getting populated.
Using SpringBoot 1.2.0.RELEASE
When using the PropertiesConfigurationFactory in a manual way like this, it won't automatically use the prefix value in the annotation.
Add a targetName like so:
pcf.setTargetName("devices");
The corrected code would be:
Properties props = new Properties();
props.put("devices.imports[0]","imp1");
props.put("devices.imports[1]","imp2");
props.put("devices.definitions[0].id","first");
props.put("devices.definitions[1].id", "second");
DeviceConfig conf = new DeviceConfig();
PropertiesConfigurationFactory<DeviceConfig> pcf = new PropertiesConfigurationFactory<>(conf);
pcf.setProperties(props);
pcf.setTargetName("devices"); // <--- Add this line
conf = pcf.getObject();
assertThat(conf.getDefinitions()).hasSize(2);
I'm pretty new to java so bear with me. I'm trying to retrieve the properties of a child node. For instance I'm trying to retrieve all the properties associated with the image property:
/content
/foo
/jcr:content
/page
/page_child
/image <-----
Currently my script is retrieving all the properties from page_child but how do I get the properties of "image"
public void setPageContext(PageContext context) {
ValueMap properties = (ValueMap) context.getAttribute("properties");
closeText = properties.get("closeText", "");
imageURL = properties.get("fileReference", "");
}
public String getCloseText() { return closeText; }
public String getCloseText() { return imageURL; }
Take a look at /libs/foundation/components/adaptiveimage
In the JSP, they are creating a new Resource using the jcr:content of the image file.
Resource fileJcrContent = resource.getChild("file").getChild("jcr:content");
if (fileJcrContent != null) {
ValueMap fileProperties = fileJcrContent.adaptTo(ValueMap.class);
String mimeType = fileProperties.get("jcr:mimeType", "jpg");
extension = mimeType.substring(mimeType.lastIndexOf("/") + 1);
}
From there, all properties will be accessible through fileProperties.