2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.config.persist.storage.directory.autodetect;
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Charsets;
12 import com.google.common.io.Files;
13 import org.apache.commons.lang3.StringUtils;
14 import org.opendaylight.controller.config.persist.storage.directory.DirectoryPersister;
15 import org.opendaylight.controller.config.persist.storage.file.xml.model.ConfigSnapshot;
18 import java.io.IOException;
19 import java.util.Arrays;
25 public static final String XML_STORAGE_FIRST_LINE = "<" + ConfigSnapshot.SNAPSHOT_ROOT_ELEMENT_NAME + ">";
27 static FileType getFileType(File file) {
28 String firstLine = readFirstLine(file);
29 if(isPlaintextStorage(firstLine)) {
31 } else if(isXmlStorage(firstLine))
34 throw new IllegalArgumentException("File " + file + " is not of permitted storage type: " + Arrays.toString(FileType.values()));
37 private static boolean isXmlStorage(String firstLine) {
38 return firstLine.startsWith(XML_STORAGE_FIRST_LINE);
41 private static boolean isPlaintextStorage(String firstLine) {
42 return firstLine.startsWith(DirectoryPersister.MODULES_START);
47 static String readFirstLine(File file) {
48 FirstLineReadingProcessor callback = new FirstLineReadingProcessor();
50 return Files.readLines(file, Charsets.UTF_8, callback);
51 } catch (IOException e) {
52 throw new IllegalArgumentException("Unable to detect file type of file " + file, e);
57 private static class FirstLineReadingProcessor implements com.google.common.io.LineProcessor<String> {
58 private String firstNonBlankLine;
61 public boolean processLine(String line) throws IOException {
62 if(isEmptyLine(line)) {
65 firstNonBlankLine = line.trim();
70 private boolean isEmptyLine(String line) {
71 return StringUtils.isBlank(line);
75 public String getResult() {
76 return firstNonBlankLine;