br.com.objectos.io.flat.IntegerField Maven / Gradle / Ivy
The newest version!
/*
* Copyright 2015 Objectos, Fábrica de Software LTDA.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package br.com.objectos.io.flat;
import java.io.IOException;
import java.util.Set;
import br.com.objectos.io.flat.annotation.IntegerOption;
import com.google.common.collect.ImmutableSet;
/**
* @author [email protected] (Marcio Endo)
*/
class IntegerField extends Field {
final int value;
private final int length;
private final Set optionSet;
private IntegerField(int value, int length, Set optionSet) {
this.value = value;
this.length = length;
this.optionSet = optionSet;
}
public static IntegerField get(int value, int length, IntegerOption... options) {
Set optionSet = ImmutableSet.copyOf(options);
return new IntegerField(value, length, optionSet);
}
public static IntegerField get(
int value, int length, IntValueCondition condition, String text, IntegerOption... options) {
Set optionSet = ImmutableSet.copyOf(options);
return new Conditional(value, length, optionSet, condition, text);
}
@Override
void tryToWriteTo(FlatAppendable out) throws IOException {
StringBuilder format = new StringBuilder();
format.append('%');
for (IntegerOption option : optionSet) {
option.formatString(format);
}
format.append(length);
format.append('d');
out.append(length, format.toString(), value);
}
private static class Conditional extends IntegerField {
private final IntValueCondition condition;
private final String text;
public Conditional(int value,
int length,
Set optionSet,
IntValueCondition condition,
String text) {
super(value, length, optionSet);
this.condition = condition;
this.text = text;
}
@Override
void tryToWriteTo(FlatAppendable out) throws IOException {
if (condition.matches(value)) {
out.append(text);
} else {
super.tryToWriteTo(out);
}
}
}
}