001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 package org.apache.commons.monitoring.reporting.web.plugin.report.format; 018 019 import org.apache.commons.monitoring.configuration.Configuration; 020 import org.apache.commons.monitoring.counters.Unit; 021 import org.apache.commons.monitoring.reporting.web.handler.api.Template; 022 import org.apache.commons.monitoring.reporting.web.template.MapBuilder; 023 024 import java.util.Collection; 025 import java.util.Map; 026 027 public class CSVFormat extends MapFormat implements Format { 028 private static final String SEPARATOR = Configuration.getProperty(Configuration.COMMONS_MONITORING_PREFIX + "csv.separator", ";"); 029 public static final String HEADER = "Monitor" + SEPARATOR + "Role" + SEPARATOR + toCsv(ATTRIBUTES_ORDERED_LIST); 030 031 @Override 032 public Template render(final Map<String, ?> params) { 033 final Unit timeUnit = timeUnit(params); 034 return new Template("/templates/report/report-csv.vm", 035 new MapBuilder<String, Object>() 036 .set("headers", HEADER) 037 .set("separator", SEPARATOR) 038 .set("lines", snapshot(timeUnit)) 039 .build(), false); 040 } 041 042 @Override 043 public String type() { 044 return "text/plain"; 045 } 046 047 private static String toCsv(final Collection<String> line) { 048 final StringBuilder builder = new StringBuilder(); 049 for (final String s : line) { 050 builder.append(s).append(SEPARATOR); 051 } 052 053 final String str = builder.toString(); 054 return str.substring(0, str.length() - 1) + '\n'; 055 } 056 }