View Javadoc
1   /*
2    * Copyright (c) 2020 bahlef.
3    * All rights reserved. This program and the accompanying materials
4    * are made available under the terms of the Eclipse Public License v2.0
5    * which accompanies this distribution, and is available at
6    * http://www.eclipse.org/legal/epl-v20.html
7    * Contributors:
8    * bahlef - initial API and implementation and/or initial documentation
9    */
10  package de.funfried.netbeans.plugins.external.formatter.java.spring;
11  
12  import java.util.ArrayList;
13  import java.util.List;
14  import java.util.Objects;
15  import java.util.SortedSet;
16  import java.util.logging.Level;
17  import java.util.logging.Logger;
18  
19  import org.apache.commons.collections4.CollectionUtils;
20  import org.apache.commons.lang3.tuple.Pair;
21  import org.eclipse.jdt.core.formatter.CodeFormatter;
22  import org.eclipse.jface.text.Document;
23  import org.eclipse.jface.text.IDocument;
24  import org.eclipse.jface.text.IRegion;
25  import org.eclipse.jface.text.Region;
26  import org.eclipse.text.edits.TextEdit;
27  import org.netbeans.api.annotations.common.CheckForNull;
28  import org.netbeans.api.annotations.common.NonNull;
29  
30  import de.funfried.netbeans.plugins.external.formatter.exceptions.FormattingFailedException;
31  import io.spring.javaformat.formatter.Formatter;
32  
33  /**
34   * Delegation class to the Spring formatter implementation.
35   *
36   * @author bahlef
37   */
38  public final class SpringJavaFormatterWrapper {
39  	/** Use to specify the kind of the code snippet to format. */
40  	private static final int FORMATTER_OPTS = CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS /* + CodeFormatter.K_CLASS_BODY_DECLARATIONS + CodeFormatter.K_STATEMENTS */;
41  
42  	/** The Spring {@link Formatter}. */
43  	private final Formatter formatter = new Formatter();
44  
45  	/**
46  	 * Package private Constructor for creating a new instance of {@link SpringJavaFormatterWrapper}.
47  	 */
48  	SpringJavaFormatterWrapper() {
49  	}
50  
51  	/**
52  	 * Formats the given {@code code} with the given configurations and returns
53  	 * the formatted code.
54  	 *
55  	 * @param code the unformatted code
56  	 * @param lineFeed the line feed to use for formatting
57  	 * @param changedElements a {@link SortedSet} containing ranges as {@link Pair}
58  	 *        objects defining the offsets which should be formatted
59  	 *
60  	 * @return the formatted code
61  	 *
62  	 * @throws FormattingFailedException if the external formatter failed to format the given code
63  	 */
64  	@CheckForNull
65  	public String format(String code, String lineFeed, SortedSet<Pair<Integer, Integer>> changedElements) throws FormattingFailedException {
66  		if (code == null) {
67  			return null;
68  		}
69  
70  		int codeLength = code.length();
71  
72  		List<IRegion> regions = new ArrayList<>();
73  		if (changedElements == null) {
74  			regions.add(new Region(0, codeLength));
75  		} else if (!CollectionUtils.isEmpty(changedElements)) {
76  			for (Pair<Integer, Integer> changedElement : changedElements) {
77  				int length = (changedElement.getRight() - changedElement.getLeft()) + 1;
78  				if (length > codeLength) {
79  					length = codeLength;
80  				}
81  
82  				regions.add(new Region(changedElement.getLeft(), length));
83  			}
84  		} else {
85  			// empty changed elements means nothing's left which can be formatted due to guarded sections
86  			return code;
87  		}
88  
89  		return format(code, regions.toArray(new IRegion[regions.size()]), lineFeed);
90  	}
91  
92  	/**
93  	 * Formats the given {@code code} with the given configurations and returns
94  	 * the formatted code.
95  	 *
96  	 * @param formatter the {@link CodeFormatter}
97  	 * @param code the unformatted code
98  	 * @param lineFeed the line feed to use for formatting
99  	 * @param regions an array containing {@link IRegion} objects defining the offsets which should be formatted
100 	 *
101 	 * @return the formatted code
102 	 *
103 	 * @throws FormattingFailedException if the external formatter failed to format the given code
104 	 */
105 	@CheckForNull
106 	private String format(@NonNull String code, @NonNull IRegion[] regions, String lineFeed) throws FormattingFailedException {
107 		String formattedCode = null;
108 
109 		try {
110 			TextEdit te = formatter.format(FORMATTER_OPTS, code, regions, 0, lineFeed);
111 			//TextEdit te = formatter.format(code, regions, lineFeed);
112 			if (te != null && te.getChildrenSize() > 0) {
113 				IDocument dc = new Document(code);
114 				te.apply(dc);
115 
116 				formattedCode = dc.get();
117 
118 				if (Objects.equals(code, formattedCode)) {
119 					return null;
120 				}
121 			}
122 		} catch (FormattingFailedException | IllegalArgumentException ex) {
123 			throw ex;
124 		} catch (Exception ex) {
125 			Logger.getLogger(SpringJavaFormatterWrapper.class.getName()).log(Level.SEVERE, "Formatting ran into", ex);
126 
127 			throw new FormattingFailedException(ex);
128 		}
129 
130 		return formattedCode;
131 	}
132 }