br.com.objectos.way.etc.MappingsGuice Maven / Gradle / Ivy
The newest version!
/*
* MappingsGuice.java criado em 27/12/2013
*
* Propriedade de Objectos Fábrica de Software LTDA.
* Reprodução parcial ou total proibida.
*/
package br.com.objectos.way.etc;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.Reader;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import org.yaml.snakeyaml.Yaml;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Files;
import com.google.inject.Inject;
import com.google.inject.Provider;
/**
* @author [email protected] (Marcio Endo)
*/
class MappingsGuice implements Mappings {
private final Provider yaml;
@Inject
public MappingsGuice(Provider yaml) {
this.yaml = yaml;
}
@Override
public Mapping read(File file) {
try {
Reader reader = readerOf(file);
Object load = yaml.get().load(reader);
return load0(load);
} catch (FileNotFoundException e) {
return MappingEmpty.INSTANCE;
}
}
@Override
public Mapping read(String text) {
Object load = yaml.get().load(text);
return load0(load);
}
@Override
public List readAll(File file) {
try {
Reader reader = readerOf(file);
Object load = yaml.get().load(reader);
return loadAll0(load);
} catch (FileNotFoundException e) {
return ImmutableList.of();
}
}
@Override
public List readAll(String text) {
Object load = yaml.get().load(text);
return loadAll0(load);
}
@SuppressWarnings("unchecked")
@Override
public Map readAsMap(File file) {
try {
Reader reader = readerOf(file);
Object load = yaml.get().load(reader);
return (Map) load;
} catch (FileNotFoundException e) {
return ImmutableMap.of();
}
}
@Override
public void write(Object model, File file) {
Writer writer = writerOf(file);
yaml.get().dump(model, writer);
}
@SuppressWarnings("unchecked")
@Override
public void writeProperty(EtcProperty property, File file) {
Map map;
try {
Reader reader = readerOf(file);
Object load = yaml.get().load(reader);
map = (Map) load;
} catch (FileNotFoundException e) {
map = ImmutableMap.of();
}
Map dump = property.write(map);
Writer writer = writerOf(file);
yaml.get().dump(dump, writer);
}
private Mapping load0(Object load) {
@SuppressWarnings("unchecked")
Map map = (Map) load;
return new MappingPojo(map);
}
private Reader readerOf(File file) throws FileNotFoundException {
return Files.newReader(file, Charsets.UTF_8);
}
private Writer writerOf(File file) {
try {
return Files.newWriter(file, Charsets.UTF_8);
} catch (FileNotFoundException e) {
String msg = String.format("Could not write file at %s: not found", file.getAbsolutePath());
throw new WayEtcException(msg);
}
}
private List loadAll0(Object load) {
return ToMapping.load(load);
}
}