/* * Copyright (C) 2021 Christian Pierre MOMON * * This file is part of Logar, simple tool to manage http log files. * * Logar is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Logar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Logar. If not, see . */ package fr.devinsy.logar.app.anonymizer; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The Class AnonMapFile. */ public final class AnonMapFile { private static Logger logger = LoggerFactory.getLogger(AnonMapFile.class); public static final String DEFAULT_CHARSET_NAME = "UTF-8"; /** * Instantiates a new anon map file. */ private AnonMapFile() { } /** * Load. * * @param source * the source * @return the anon map */ public static AnonMap load(final File source) { AnonMap result; result = new AnonMap(); if ((source != null) && (source.exists())) { BufferedReader in = null; try { if (source.getName().endsWith(".gz")) { in = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(source)))); } else { in = new BufferedReader(new InputStreamReader(new FileInputStream(source), DEFAULT_CHARSET_NAME)); } boolean ended = false; while (!ended) { String key = in.readLine(); String value = in.readLine(); if (key == null) { ended = true; } else { result.put(key, value); } } } catch (IOException exception) { exception.printStackTrace(); } finally { IOUtils.closeQuietly(in); } } // return result; } /** * Save. * * @param source * the source * @param map * the map */ public static void save(final File target, final AnonMap map) { if (target == null) { throw new IllegalArgumentException("Null parameter source."); } else if (map == null) { throw new IllegalArgumentException("Null parameter map."); } else { PrintWriter out = null; try { if (target.getName().endsWith(".gz")) { out = new PrintWriter(new GZIPOutputStream(new FileOutputStream(target))); } else { out = new PrintWriter(new FileOutputStream(target)); } for (String key : map.getKeys()) { out.println(key); out.println(map.get(key)); } } catch (IOException exception) { System.err.println("Error with file [" + target.getAbsolutePath() + "]"); exception.printStackTrace(); } finally { IOUtils.closeQuietly(out); } } } }