All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.helger.xml.microdom.util.XMLMapHandler Maven / Gradle / Ivy

There is a newer version: 11.1.8
Show newest version
/*
 * Copyright (C) 2014-2024 Philip Helger (www.helger.com)
 * philip[at]helger[dot]com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.helger.xml.microdom.util;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.WillClose;
import javax.annotation.concurrent.Immutable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.helger.commons.ValueEnforcer;
import com.helger.commons.annotation.PresentForCodeCoverage;
import com.helger.commons.annotation.ReturnsMutableCopy;
import com.helger.commons.collection.impl.CommonsHashMap;
import com.helger.commons.collection.impl.ICommonsMap;
import com.helger.commons.io.EAppend;
import com.helger.commons.io.IHasInputStream;
import com.helger.commons.io.IHasOutputStream;
import com.helger.commons.io.stream.StreamHelper;
import com.helger.commons.state.ESuccess;
import com.helger.xml.microdom.IMicroDocument;
import com.helger.xml.microdom.IMicroElement;
import com.helger.xml.microdom.MicroDocument;
import com.helger.xml.microdom.serialize.MicroReader;
import com.helger.xml.microdom.serialize.MicroWriter;
import com.helger.xml.serialize.write.XMLWriterSettings;

/**
 * Simple class that reads a generic String-to-String mapping from a classpath
 * resource into a {@link Map}.
* The XML file needs to look as follows: * *
 * <mapping>
 *   <map key="..." value="..."/>
 *   <map key="..." value="..."/>
 *   ...
 * </mapping>
 * 
* * @author Philip */ @Immutable public final class XMLMapHandler { /** Root element name */ public static final String ELEMENT_MAPPING = "mapping"; /** Element name for a single mapping */ public static final String ELEMENT_MAP = "map"; /** Attribute name for key of a single mapping */ public static final String ATTR_KEY = "key"; /** Attribute name for value of a single mapping */ public static final String ATTR_VALUE = "value"; private static final Logger LOGGER = LoggerFactory.getLogger (XMLMapHandler.class); @PresentForCodeCoverage private static final XMLMapHandler INSTANCE = new XMLMapHandler (); private XMLMapHandler () {} @Nullable @ReturnsMutableCopy public static ICommonsMap readMap (@Nonnull final IHasInputStream aISP) { ValueEnforcer.notNull (aISP, "InputStreamProvider"); return readMap (aISP.getInputStream ()); } @Nonnull public static ESuccess readMap (@Nonnull final IHasInputStream aISP, @Nonnull final Map aTargetMap) { ValueEnforcer.notNull (aISP, "InputStreamProvider"); return readMap (aISP.getInputStream (), aTargetMap); } /** * Read a mapping from the passed input stream. * * @param aIS * The input stream to read from. May not be null. * @return null if reading the map failed */ @Nullable @ReturnsMutableCopy public static ICommonsMap readMap (@Nonnull @WillClose final InputStream aIS) { final ICommonsMap ret = new CommonsHashMap <> (); if (readMap (aIS, ret).isFailure ()) return null; return ret; } /** * Read a mapping from the passed input stream. * * @param aIS * The input stream to read from. May not be null. * @param aTargetMap * The target map to be filled. * @return {@link ESuccess#SUCCESS} if the stream could be opened, if it could * be read as XML and if the root element was correct. * {@link ESuccess#FAILURE} otherwise. */ @Nonnull public static ESuccess readMap (@Nonnull @WillClose final InputStream aIS, @Nonnull final Map aTargetMap) { ValueEnforcer.notNull (aIS, "InputStream"); ValueEnforcer.notNull (aTargetMap, "TargetMap"); try (final InputStream aCloseMe = aIS) { // open file final IMicroDocument aDoc = MicroReader.readMicroXML (aIS); if (aDoc != null) { readMap (aDoc.getDocumentElement (), aTargetMap); return ESuccess.SUCCESS; } } catch (final Exception ex) { LOGGER.warn ("Failed to read mapping resource '" + aIS + "'", ex); } return ESuccess.FAILURE; } @Nonnull public static ESuccess readMap (@Nonnull final IMicroElement aParentElement, @Nonnull final Map aTargetMap) { ValueEnforcer.notNull (aParentElement, "ParentElement"); ValueEnforcer.notNull (aTargetMap, "TargetMap"); try { // and insert all elements for (final IMicroElement eMap : aParentElement.getAllChildElements (ELEMENT_MAP)) { final String sName = eMap.getAttributeValue (ATTR_KEY); if (sName == null) LOGGER.warn ("Ignoring mapping element because key is null"); else { final String sValue = eMap.getAttributeValue (ATTR_VALUE); if (sValue == null) LOGGER.warn ("Ignoring mapping element because value is null"); else { if (aTargetMap.containsKey (sName)) LOGGER.warn ("Key '" + sName + "' is already contained - overwriting!"); aTargetMap.put (sName, sValue); } } } return ESuccess.SUCCESS; } catch (final Exception ex) { LOGGER.warn ("Failed to read mapping document", ex); } return ESuccess.FAILURE; } @Nonnull public static IMicroDocument createMapDocument (@Nonnull final Map aMap) { ValueEnforcer.notNull (aMap, "Map"); final IMicroDocument aDoc = new MicroDocument (); final IMicroElement eRoot = aDoc.appendElement (ELEMENT_MAPPING); for (final Map.Entry aEntry : aMap.entrySet ()) { final IMicroElement eMap = eRoot.appendElement (ELEMENT_MAP); eMap.setAttribute (ATTR_KEY, aEntry.getKey ()); eMap.setAttribute (ATTR_VALUE, aEntry.getValue ()); } return aDoc; } @Nonnull public static ESuccess writeMap (@Nonnull final Map aMap, @Nonnull final IHasOutputStream aOSP) { ValueEnforcer.notNull (aOSP, "OutputStreamProvider"); return writeMap (aMap, aOSP.getOutputStream (EAppend.DEFAULT)); } /** * Write the passed map to the passed output stream using the predefined XML * layout. * * @param aMap * The map to be written. May not be null. * @param aOS * The output stream to write to. The stream is closed independent of * success or failure. May not be null. * @return {@link ESuccess#SUCCESS} when everything went well, * {@link ESuccess#FAILURE} otherwise. */ @Nonnull public static ESuccess writeMap (@Nonnull final Map aMap, @Nonnull @WillClose final OutputStream aOS) { ValueEnforcer.notNull (aMap, "Map"); ValueEnforcer.notNull (aOS, "OutputStream"); try { final IMicroDocument aDoc = createMapDocument (aMap); return MicroWriter.writeToStream (aDoc, aOS, XMLWriterSettings.DEFAULT_XML_SETTINGS); } finally { StreamHelper.close (aOS); } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy