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 + ">";
26 private static final String XML_FILE_DEFINITION_LINE = "<?xml";
28 static FileType getFileType(File file) {
29 String firstLine = readFirstLine(file);
30 if(isPlaintextStorage(firstLine)) {
32 } else if(isXmlStorage(firstLine))
35 throw new IllegalArgumentException("File " + file + " is not of permitted storage type: " + Arrays.toString(FileType.values()));
38 private static boolean isXmlStorage(String firstLine) {
39 boolean isXml = false;
40 isXml |= firstLine.startsWith(XML_STORAGE_FIRST_LINE);
41 isXml |= firstLine.startsWith(XML_FILE_DEFINITION_LINE);
45 private static boolean isPlaintextStorage(String firstLine) {
46 return firstLine.startsWith(DirectoryPersister.MODULES_START);
51 static String readFirstLine(File file) {
52 FirstLineReadingProcessor callback = new FirstLineReadingProcessor();
54 return Files.readLines(file, Charsets.UTF_8, callback);
55 } catch (IOException e) {
56 throw new IllegalArgumentException("Unable to detect file type of file " + file, e);
61 private static class FirstLineReadingProcessor implements com.google.common.io.LineProcessor<String> {
62 private String firstNonBlankLine;
65 public boolean processLine(String line) throws IOException {
66 if(isEmptyLine(line)) {
69 firstNonBlankLine = line.trim();
74 private boolean isEmptyLine(String line) {
75 return StringUtils.isBlank(line);
79 public String getResult() {
80 return firstNonBlankLine;