use of java.util.StringJoiner in project jabref by JabRef.
the class CanonicalBibtexEntry method getCanonicalRepresentation.
/**
* This returns a canonical BibTeX serialization. Special characters such as "{" or "&" are NOT escaped, but written
* as is
*
* Serializes all fields, even the JabRef internal ones. Does NOT serialize "KEY_FIELD" as field, but as key
*/
public static String getCanonicalRepresentation(BibEntry e) {
StringBuilder sb = new StringBuilder();
// generate first line: type and bibtex key
String citeKey = e.getCiteKeyOptional().orElse("");
sb.append(String.format("@%s{%s,", e.getType().toLowerCase(Locale.US), citeKey)).append('\n');
// we have to introduce a new Map as fields are stored case-sensitive in JabRef (see https://github.com/koppor/jabref/issues/45).
Map<String, String> mapFieldToValue = new HashMap<>();
// determine sorted fields -- all fields lower case
SortedSet<String> sortedFields = new TreeSet<>();
for (Entry<String, String> field : e.getFieldMap().entrySet()) {
String fieldName = field.getKey();
String fieldValue = field.getValue();
// JabRef stores the key in the field KEY_FIELD, which must not be serialized
if (!fieldName.equals(BibEntry.KEY_FIELD)) {
String lowerCaseFieldName = fieldName.toLowerCase(Locale.US);
sortedFields.add(lowerCaseFieldName);
mapFieldToValue.put(lowerCaseFieldName, fieldValue);
}
}
// generate field entries
StringJoiner sj = new StringJoiner(",\n", "", "\n");
for (String fieldName : sortedFields) {
String line = String.format(" %s = {%s}", fieldName, String.valueOf(mapFieldToValue.get(fieldName)).replaceAll("\\r\\n", "\n"));
sj.add(line);
}
sb.append(sj);
// append the closing entry bracket
sb.append('}');
return sb.toString();
}
use of java.util.StringJoiner in project ocvn by devgateway.
the class OCDSObjectExcelSheet method writeRowFlattenObject.
/**
* Function to flat export an array of objects. Example:
* [
* {
* x: aaa,
* y: bbb,
* },
* {
* x: ccc,
* y: ddd,
* }
* ]
*
* Will be printed as:
* | x | y |
* | aaa ; bbb | ccc ; ddd |
*
* @param objects
* @param row
*/
public void writeRowFlattenObject(final List<Object> objects, final Row row) {
final Iterator<Field> fields = OCDSObjectUtil.getFields(clazz);
while (fields.hasNext()) {
final Field field = fields.next();
final int fieldType = OCDSObjectUtil.getFieldType(field);
try {
switch(fieldType) {
case FieldType.BASIC_FIELD:
try {
// get the last 'free' cell
int coll = row.getLastCellNum() == -1 ? 0 : row.getLastCellNum();
StringJoiner flattenValue = new StringJoiner(" | ");
for (Object obj : objects) {
if (obj != null && PropertyUtils.getProperty(obj, field.getName()) != null) {
flattenValue.add(PropertyUtils.getProperty(obj, field.getName()).toString());
}
}
if (row.getRowNum() < 2) {
writeHeaderLabel(field, coll);
}
writeCell(flattenValue.toString(), row, coll);
} catch (NoSuchMethodException e) {
// do nothing
}
break;
case FieldType.OCDS_OBJECT_FIELD:
if (field.getType().equals(java.util.Set.class) || field.getType().equals(java.util.List.class)) {
LOGGER.error("Unsupported operation for field: '" + field.getName() + "'! You can not flatten an array of objects that contains other array of objects " + "that need to be printed in other sheet.");
} else {
final List<Object> newObjects = new ArrayList();
for (Object obj : objects) {
if (obj != null && PropertyUtils.getProperty(obj, field.getName()) != null && PropertyUtils.isReadable(obj, field.getName())) {
newObjects.add(PropertyUtils.getProperty(obj, field.getName()));
}
}
final OCDSObjectExcelSheet objectSheet = new OCDSObjectExcelSheet(this.workbook, OCDSObjectUtil.getFieldClass(field), excelSheetName, getHeaderPrefix() + field.getName());
objectSheet.writeRowFlattenObject(newObjects, row);
}
break;
case FieldType.OCDS_OBJECT_SEPARETE_SHEET_FIELD:
LOGGER.error("Unsupported operation for field: '" + field.getName() + "'! You can not flatten an array of objects that contains objects " + "that need to be printed in other sheet.");
break;
default:
LOGGER.error("Undefined field type");
break;
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
LOGGER.error(e);
}
}
}
use of java.util.StringJoiner in project jdk8u_jdk by JetBrains.
the class TabulatorsTest method testJoin.
@Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class)
public void testJoin(String name, TestData.OfRef<Integer> data) throws ReflectiveOperationException {
withData(data).terminal(s -> s.map(Object::toString).collect(Collectors.joining())).expectedResult(join(data, "")).exercise();
Collector<String, StringBuilder, String> likeJoining = Collector.of(StringBuilder::new, StringBuilder::append, (sb1, sb2) -> sb1.append(sb2.toString()), StringBuilder::toString);
withData(data).terminal(s -> s.map(Object::toString).collect(likeJoining)).expectedResult(join(data, "")).exercise();
withData(data).terminal(s -> s.map(Object::toString).collect(Collectors.joining(","))).expectedResult(join(data, ",")).exercise();
withData(data).terminal(s -> s.map(Object::toString).collect(Collectors.joining(",", "[", "]"))).expectedResult("[" + join(data, ",") + "]").exercise();
withData(data).terminal(s -> s.map(Object::toString).collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString()).expectedResult(join(data, "")).exercise();
withData(data).terminal(s -> s.map(Object::toString).collect(() -> new StringJoiner(","), (sj, cs) -> sj.add(cs), (j1, j2) -> j1.merge(j2)).toString()).expectedResult(join(data, ",")).exercise();
withData(data).terminal(s -> s.map(Object::toString).collect(() -> new StringJoiner(",", "[", "]"), (sj, cs) -> sj.add(cs), (j1, j2) -> j1.merge(j2)).toString()).expectedResult("[" + join(data, ",") + "]").exercise();
}
use of java.util.StringJoiner in project aic-expresso by aic-sri-international.
the class FunctionType method iterator.
@Override
public Iterator<Expression> iterator() {
if (!(getCodomain().isDiscrete() && getArgumentTypes().stream().allMatch(Type::isFinite))) {
throw new Error("Only function types with left-finite argument types and a discrete codomain can be enumerated.");
}
if (cachedIterateRegistry == null) {
// Pre-compute
cachedIterateRegistry = new DefaultRegistry();
int numCodomainValues = argumentTypes.stream().map(Type::cardinality).map(Expression::rationalValue).reduce(Rational.ONE, Rational::multiply).intValue();
cachedIterateRegistry = cachedIterateRegistry.makeNewContextWithAddedType(getCodomain());
Expression codomainTypeExpression = parse(getCodomain().getName());
codomainVariables = new ArrayList<>(numCodomainValues);
Map<Expression, Expression> symbolsAndTypes = new LinkedHashMap<>();
for (int i = 0; i < numCodomainValues; i++) {
Expression coDomainVariableI = makeSymbol("C" + (i + 1));
codomainVariables.add(coDomainVariableI);
symbolsAndTypes.put(coDomainVariableI, codomainTypeExpression);
}
List<Expression> argVariables = new ArrayList<>();
for (int i = 0; i < getArgumentTypes().size(); i++) {
cachedIterateRegistry = cachedIterateRegistry.makeNewContextWithAddedType(getArgumentTypes().get(i));
argVariables.add(makeSymbol("A" + (i + 1)));
symbolsAndTypes.put(argVariables.get(i), parse(getArgumentTypes().get(i).getName()));
}
cachedIterateRegistry = cachedIterateRegistry.setSymbolsAndTypes(symbolsAndTypes);
StringJoiner lambdaApplicationPrefix = new StringJoiner(", ", "(lambda ", " : ");
for (Expression argVar : argVariables) {
lambdaApplicationPrefix.add(argVar + " in " + symbolsAndTypes.get(argVar));
}
AssignmentMapsIterator assignmentsIterator = new AssignmentMapsIterator(argVariables, cachedIterateRegistry);
StringJoiner lambdaApplicationBody = new StringJoiner(" else ", "", ")");
AtomicInteger counter = new AtomicInteger(0);
assignmentsIterator.forEachRemaining(assignment -> {
if (counter.incrementAndGet() != numCodomainValues) {
StringJoiner condition = new StringJoiner(" and ", "if ", " then C" + counter);
for (int i = 0; i < argVariables.size(); i++) {
Expression argVariable = argVariables.get(i);
condition.add(argVariable + " = " + assignment.get(argVariable));
}
lambdaApplicationBody.add(condition.toString());
} else {
lambdaApplicationBody.add("C" + numCodomainValues);
}
});
genericLambda = parse(lambdaApplicationPrefix.toString() + lambdaApplicationBody.toString());
}
return FunctionIterator.functionIterator(new AssignmentMapsIterator(codomainVariables, cachedIterateRegistry), assignment -> {
Expression lambda = genericLambda;
for (int i = 0; i < codomainVariables.size(); i++) {
Expression codomainVariable = codomainVariables.get(i);
// NOTE: There will only be one occurrence of the codomain variable to replace,
// so can avoid doing an AllOccurrences replacement.
lambda = lambda.replaceFirstOccurrence(codomainVariable, assignment.get(codomainVariable), cachedIterateRegistry);
}
return lambda;
});
}
use of java.util.StringJoiner in project aic-expresso by aic-sri-international.
the class TupleType method iterator.
@Override
public Iterator<Expression> iterator() {
if (!getElementTypes().stream().allMatch(Type::isDiscrete)) {
throw new Error("Only tuple types with discrete element types can be enumerated.");
}
if (cachedIterateRegistry == null) {
// Pre-compute
elementVariables = new ArrayList<>();
cachedIterateRegistry = new DefaultRegistry();
Map<Expression, Expression> symbolsAndTypes = new LinkedHashMap<>();
for (int i = 0; i < getArity(); i++) {
Expression elementVariableI = makeSymbol("E" + (i + 1));
elementVariables.add(elementVariableI);
symbolsAndTypes.put(elementVariableI, parse(getElementTypes().get(i).getName()));
cachedIterateRegistry = cachedIterateRegistry.makeNewContextWithAddedType(elementTypes.get(i));
}
cachedIterateRegistry = cachedIterateRegistry.setSymbolsAndTypes(symbolsAndTypes);
StringJoiner tupleVariableRepresentation = new StringJoiner(", ", "tuple(", ")");
for (Expression eleVar : elementVariables) {
tupleVariableRepresentation.add(eleVar.toString());
}
genericTuple = parse(tupleVariableRepresentation.toString());
}
return FunctionIterator.functionIterator(new AssignmentMapsIterator(elementVariables, cachedIterateRegistry), assignment -> {
Expression tuple = genericTuple;
for (int i = 0; i < elementVariables.size(); i++) {
Expression elementVariable = elementVariables.get(i);
// NOTE: There will only be one occurrence of the element variable to replace,
// so can avoid doing an AllOccurrences replacement.
tuple = tuple.replaceFirstOccurrence(elementVariable, assignment.get(elementVariable), cachedIterateRegistry);
}
return tuple;
});
}
Aggregations