org.openrewrite.json.tree.JsonRightPadded Maven / Gradle / Ivy
Show all versions of rewrite-json Show documentation
/*
* Copyright 2021 the original author or authors.
*
* 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
*
* https://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 org.openrewrite.json.tree;
import lombok.AccessLevel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.With;
import lombok.experimental.FieldDefaults;
import org.openrewrite.marker.Markers;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
/**
* A JSON element that could have trailing space.
*
* @param
*/
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
@EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true)
@Data
public class JsonRightPadded {
@With
T element;
@With
Space after;
@With
Markers markers;
public JsonRightPadded map(UnaryOperator map) {
return withElement(map.apply(element));
}
public static List getElements(List> ls) {
List list = new ArrayList<>();
for (JsonRightPadded l : ls) {
T elem = l.getElement();
list.add(elem);
}
return list;
}
public static List> withElements(List> before, List elements) {
// a cheaper check for the most common case when there are no changes
if (elements.size() == before.size()) {
boolean hasChanges = false;
for (int i = 0; i < before.size(); i++) {
if (before.get(i).getElement() != elements.get(i)) {
hasChanges = true;
break;
}
}
if (!hasChanges) {
return before;
}
}
List> after = new ArrayList<>(elements.size());
Map> beforeById = before.stream().collect(Collectors
.toMap(j -> j.getElement().getId(), Function.identity()));
for (J2 t : elements) {
if (beforeById.get(t.getId()) != null) {
JsonRightPadded found = beforeById.get(t.getId());
after.add(found.withElement(t));
} else {
after.add(new JsonRightPadded<>(t, Space.EMPTY, Markers.EMPTY));
}
}
return after;
}
public static JsonRightPadded build(T element) {
return new JsonRightPadded<>(element, Space.EMPTY, Markers.EMPTY);
}
@Override
public String toString() {
return "JsonRightPadded(element=" + element.getClass().getSimpleName() + ", after=" + after + ')';
}
}